net-kingdom/sso-mfa/bootstrap/decrypt-secrets.sh

63 lines
1.9 KiB
Bash
Raw Normal View History

#!/usr/bin/env bash
# decrypt-secrets.sh — decrypt secrets.enc/ to secrets/ using age
#
# Usage:
# ./decrypt-secrets.sh [OUTPUT_DIR] [AGE_KEY_FILE]
#
# OUTPUT_DIR where to write plaintext secrets (default: ./secrets)
# AGE_KEY_FILE age private key file (default: ~/.config/net-kingdom/age.key)
#
# Decrypts all *.age files in secrets.enc/ to OUTPUT_DIR for use by
# create-secrets.sh scripts. Shred OUTPUT_DIR when done:
# find secrets/ -type f -exec shred -u {} \; && rm -rf secrets/
#
# The age key must be present on the machine. Keep it outside the repo:
# ~/.config/net-kingdom/age.key
set -euo pipefail
OUTPUT_DIR="${1:-./secrets}"
AGE_KEY="${2:-$HOME/.config/net-kingdom/age.key}"
ENC_DIR="$(dirname "$OUTPUT_DIR")/secrets.enc"
if [[ ! -d "$ENC_DIR" ]]; then
echo "ERROR: encrypted secrets directory not found: $ENC_DIR" >&2
echo "Expected secrets.enc/ next to the output directory." >&2
exit 1
fi
if [[ ! -f "$AGE_KEY" ]]; then
echo "ERROR: age key not found: $AGE_KEY" >&2
echo "Copy your age key to $AGE_KEY or pass the path as the second argument." >&2
exit 1
fi
if [[ -e "$OUTPUT_DIR" ]]; then
echo "ERROR: $OUTPUT_DIR already exists. Remove it first or choose a different path." >&2
exit 1
fi
echo "Decrypting $ENC_DIR$OUTPUT_DIR/"
echo ""
count=0
for component_dir in "$ENC_DIR"/*/; do
component=$(basename "$component_dir")
mkdir -p "$OUTPUT_DIR/$component"
for f in "$component_dir"*.age; do
[[ -f "$f" ]] || continue
fname=$(basename "${f%.age}")
out="$OUTPUT_DIR/$component/$fname"
age -d -i "$AGE_KEY" -o "$out" "$f"
echo " decrypted: secrets.enc/$component/$(basename "$f")$component/$fname"
count=$((count + 1))
done
done
echo ""
echo "$count file(s) decrypted to $OUTPUT_DIR/"
echo ""
echo "Use create-secrets.sh scripts, then shred:"
echo " find $OUTPUT_DIR -type f -exec shred -u {} \\; && rm -rf $OUTPUT_DIR"