#!/usr/bin/env bash # Shared sops/age helpers for scripts/secrets/backup-admin-key.sh, # scripts/secrets/rotate-admin-key.sh, and scripts/secrets/sync-host-keys.sh -- all three # derive an age public key from a private identity file the same way, two # of them resolve the same sops/age default key-file path, and two of them # run `sops updatekeys` the same way. Kept in one place so they can't drift # apart. Source alongside env.sh: # source "$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)/lib/sops-age.sh" # # Uses NIX_OPTS (an array of extra `nix-shell` options -- see env.sh's # nix_extra_opts) if the caller has already set it, same convention as # lib/ssh-host-keys.sh. Falls back to no extra options if the caller never # sourced env.sh. if ! declare -p NIX_OPTS >/dev/null 2>&1; then declare -a NIX_OPTS=() fi # sops/age's own default identity-file resolution order, minus $SOPS_AGE_KEY # itself (an inline identity, not a path -- callers that accept it check it # separately, before falling back to this). : "${DEFAULT_SOPS_AGE_KEY_FILE:=${SOPS_AGE_KEY_FILE:-${XDG_CONFIG_HOME:-$HOME/.config}/sops/age/keys.txt}}" # age_pubkey_from_identity_file # Prints the age public key for a private identity file (age-keygen -y). age_pubkey_from_identity_file() { local identity_file="$1" nix-shell "${NIX_OPTS[@]}" -p age --run "age-keygen -y '${identity_file}'" } # sops_yaml_admin_pubkey # Prints .sops.yaml's current &admin age public key, or empty (not an error # under set -e) if no such anchor line exists -- callers that need to treat # "missing" as fatal check for an empty result themselves. sops_yaml_admin_pubkey() { local sops_yaml="$1" grep -E '^ - &admin age1' "$sops_yaml" 2>/dev/null | awk '{print $NF}' || true } # sops_updatekeys [key-file] # Re-encrypts for .sops.yaml's current recipient set. If # is given, decrypts with that identity (SOPS_AGE_KEY_FILE) # instead of whatever's ambient -- needed when the ambient default key # doesn't match yet (e.g. mid-rotation, decrypting with the outgoing key). sops_updatekeys() { local secrets_file="$1" key_file="${2:-}" if [[ -n "$key_file" ]]; then SOPS_AGE_KEY_FILE="$key_file" nix-shell "${NIX_OPTS[@]}" -p sops --run \ "sops updatekeys --yes '${secrets_file}'" else nix-shell "${NIX_OPTS[@]}" -p sops --run "sops updatekeys --yes '${secrets_file}'" fi }