feat: improve scripts and write tests
This commit is contained in:
32 files changed
+3817
-723
No files matched your search
+169
-68
@@ -1,85 +1,186 @@
|
||||
#!/usr/bin/env bash
|
||||
# Point Docker at a credential store and, for `pass`, set up GPG + pass.
|
||||
#
|
||||
# 1. Sets "credsStore" in ~/.docker/config.json (all other keys preserved).
|
||||
# 2. For the `pass` store only: creates a dedicated GPG key (if there isn't
|
||||
# one already) and initializes ~/.password-store with it.
|
||||
#
|
||||
# Safe to re-run: every step is skipped when already done.
|
||||
|
||||
set -euo pipefail
|
||||
|
||||
store="${1:-pass}"
|
||||
no_passphrase=0
|
||||
[ "${2:-}" = "--no-passphrase" ] && no_passphrase=1
|
||||
SCRIPT_DIR="$(cd -- "$(dirname -- "$(readlink -f -- "${BASH_SOURCE[0]}")")" && pwd -P)"
|
||||
# shellcheck source=lib/common.sh
|
||||
source "$SCRIPT_DIR/lib/common.sh"
|
||||
|
||||
config_dir="$HOME/.docker"
|
||||
config_file="$config_dir/config.json"
|
||||
usage() {
|
||||
cat <<'EOF'
|
||||
Usage: docker-creds.sh [STORE] [--no-passphrase]
|
||||
|
||||
# Identity used for the dedicated docker-creds GPG key. Stable so re-runs
|
||||
# are idempotent (we look the key up by this uid rather than guessing).
|
||||
gpg_name="Docker Credential Store"
|
||||
gpg_email="${USER}@$(hostname)"
|
||||
gpg_uid="$gpg_name <$gpg_email>"
|
||||
STORE credential helper suffix: pass (default), secretservice,
|
||||
osxkeychain, desktop, ... (uses docker-credential-STORE)
|
||||
--no-passphrase pass only: create the GPG key WITHOUT a passphrase.
|
||||
Anyone who can read ~/.gnupg can then decrypt your
|
||||
registry credentials.
|
||||
-h, --help show this help
|
||||
|
||||
# --- credsStore in config.json (merge, never clobber auths) -------------
|
||||
if ! command -v "docker-credential-$store" >/dev/null 2>&1; then
|
||||
echo "warning: docker-credential-$store not found in PATH" >&2
|
||||
echo " is docker-credential-helpers installed and the rebuild applied?" >&2
|
||||
fi
|
||||
Environment: DOCKER_CONFIG (default ~/.docker), PASSWORD_STORE_DIR (default ~/.password-store)
|
||||
|
||||
Exit codes: 0 ok, 1 failure, 2 usage error.
|
||||
EOF
|
||||
}
|
||||
|
||||
STORE="pass"
|
||||
NO_PASSPHRASE=0
|
||||
|
||||
parse_args() {
|
||||
local store_set=0 a
|
||||
for a in "$@"; do
|
||||
case "$a" in
|
||||
"") ;; # `just` passes an empty string when a recipe argument is unset
|
||||
-h|--help) usage; exit 0 ;;
|
||||
--no-passphrase) NO_PASSPHRASE=1 ;;
|
||||
-*) die "unknown option: $a (see --help)" 2 ;;
|
||||
*)
|
||||
((store_set == 0)) || die "unexpected extra argument: $a" 2
|
||||
STORE="$a"; store_set=1 ;;
|
||||
esac
|
||||
done
|
||||
[[ "$STORE" =~ ^[a-z0-9][a-z0-9._-]*$ ]] || die "invalid credential store name: '$STORE'" 2
|
||||
}
|
||||
|
||||
# Merge credsStore into config.json without losing anything else.
|
||||
# * refuses to touch a file that isn't a JSON object
|
||||
# * writes atomically (temp file + rename), mode 0600
|
||||
# * if the path is a symlink (e.g. managed by home-manager) it is replaced
|
||||
# by a regular file rather than writing through to a read-only target
|
||||
set_creds_store() {
|
||||
local config_file="$1" store="$2"
|
||||
python3 - "$config_file" "$store" <<'PY'
|
||||
import json, os, sys, tempfile
|
||||
|
||||
mkdir -p "$config_dir"
|
||||
python3 - "$config_file" "$store" <<'PY'
|
||||
import json, os, sys
|
||||
path, store = sys.argv[1], sys.argv[2]
|
||||
config = {}
|
||||
if os.path.exists(path):
|
||||
with open(path) as f:
|
||||
if os.path.lexists(path):
|
||||
try:
|
||||
with open(path, encoding="utf-8") as f:
|
||||
text = f.read()
|
||||
except OSError as e:
|
||||
sys.exit(f"cannot read {path}: {e}")
|
||||
if text.strip():
|
||||
try:
|
||||
config = json.load(f)
|
||||
except json.JSONDecodeError:
|
||||
config = {}
|
||||
config = json.loads(text)
|
||||
except json.JSONDecodeError as e:
|
||||
sys.exit(f"{path} is not valid JSON ({e}); refusing to overwrite it. "
|
||||
"Fix or move it, then re-run.")
|
||||
if not isinstance(config, dict):
|
||||
sys.exit(f"{path} does not contain a JSON object; refusing to overwrite it.")
|
||||
|
||||
if config.get("credsStore") == store and os.path.exists(path):
|
||||
print(f'credsStore is already "{store}" in {path}')
|
||||
sys.exit(0)
|
||||
|
||||
if os.path.islink(path):
|
||||
print(f"note: {path} was a symlink to {os.readlink(path)}; replacing it with a regular file",
|
||||
file=sys.stderr)
|
||||
|
||||
config["credsStore"] = store
|
||||
with open(path, "w") as f:
|
||||
json.dump(config, f, indent=2)
|
||||
f.write("\n")
|
||||
directory = os.path.dirname(path) or "."
|
||||
fd, tmp = tempfile.mkstemp(dir=directory, prefix=".config.json.", suffix=".tmp")
|
||||
try:
|
||||
with os.fdopen(fd, "w", encoding="utf-8") as f: # mkstemp creates it 0600
|
||||
json.dump(config, f, indent=2)
|
||||
f.write("\n")
|
||||
f.flush()
|
||||
os.fsync(f.fileno())
|
||||
os.replace(tmp, path)
|
||||
except BaseException:
|
||||
try:
|
||||
os.unlink(tmp)
|
||||
except FileNotFoundError:
|
||||
pass
|
||||
raise
|
||||
print(f'Set credsStore = "{store}" in {path}')
|
||||
PY
|
||||
chmod u+w "$config_file"
|
||||
echo "Set credsStore = \"$store\" in $config_file"
|
||||
}
|
||||
|
||||
# The remaining steps only apply to the pass-backed store.
|
||||
[ "$store" = "pass" ] || { echo "store is '$store'; skipping GPG/pass setup."; exit 0; }
|
||||
main() {
|
||||
parse_args "$@"
|
||||
need_cmd python3
|
||||
# Check every tool up front so a missing one can't leave us half-configured.
|
||||
[[ "$STORE" != "pass" ]] || need_cmd gpg pass
|
||||
|
||||
# --- GPG key (generate only if our uid doesn't already have one) --------
|
||||
if gpg --list-secret-keys "$gpg_uid" >/dev/null 2>&1; then
|
||||
echo "GPG key for '$gpg_uid' already exists; skipping generation."
|
||||
else
|
||||
echo "Generating GPG key for '$gpg_uid'..."
|
||||
protection="# (passphrase-protected; pinentry will prompt)"
|
||||
if [ "$no_passphrase" -eq 1 ]; then
|
||||
echo "warning: creating an UNPROTECTED key (--no-passphrase)." >&2
|
||||
echo " anyone who can read ~/.gnupg can decrypt your registry creds." >&2
|
||||
protection="%no-protection"
|
||||
fi
|
||||
gpg --batch --full-generate-key <<EOF
|
||||
%echo Generating docker-credential key
|
||||
Key-Type: eddsa
|
||||
Key-Curve: ed25519
|
||||
Subkey-Type: ecdh
|
||||
Subkey-Curve: cv25519
|
||||
Name-Real: $gpg_name
|
||||
Name-Email: $gpg_email
|
||||
Expire-Date: 0
|
||||
$protection
|
||||
%commit
|
||||
%echo done
|
||||
EOF
|
||||
fi
|
||||
local config_dir="${DOCKER_CONFIG:-${HOME:?HOME is not set}/.docker}"
|
||||
local config_file="$config_dir/config.json"
|
||||
|
||||
# Pull the fingerprint back out for pass.
|
||||
fpr="$(gpg --list-secret-keys --with-colons "$gpg_uid" \
|
||||
| awk -F: '/^fpr:/ {print $10; exit}')"
|
||||
[ -n "$fpr" ] || { echo "error: could not determine GPG fingerprint" >&2; exit 1; }
|
||||
# --- credsStore in config.json ------------------------------------------
|
||||
if ! command -v "docker-credential-$STORE" >/dev/null 2>&1; then
|
||||
warn "docker-credential-$STORE not found in PATH"
|
||||
warn " is docker-credential-helpers installed and the rebuild applied?"
|
||||
fi
|
||||
(umask 077 && mkdir -p -- "$config_dir")
|
||||
set_creds_store "$config_file" "$STORE" || die "could not update $config_file" 1
|
||||
|
||||
# --- pass init (only if the store isn't already initialized) ------------
|
||||
store_dir="${PASSWORD_STORE_DIR:-$HOME/.password-store}"
|
||||
if [ -f "$store_dir/.gpg-id" ]; then
|
||||
echo "pass already initialized at $store_dir; skipping init."
|
||||
else
|
||||
pass init "$fpr"
|
||||
fi
|
||||
# The remaining steps only apply to the pass-backed store.
|
||||
if [[ "$STORE" != "pass" ]]; then
|
||||
log "store is '$STORE'; skipping GPG/pass setup."
|
||||
return 0
|
||||
fi
|
||||
|
||||
echo
|
||||
echo "Done. Remaining manual step: docker login"
|
||||
# Let pinentry-curses find the terminal.
|
||||
if tty -s 2>/dev/null; then GPG_TTY="$(tty)"; export GPG_TTY; fi
|
||||
|
||||
# --- GPG key (generate only if our uid doesn't already have one) --------
|
||||
# Stable identity so re-runs find the key instead of creating another.
|
||||
local gpg_name="Docker Credential Store" user host gpg_email gpg_uid
|
||||
user="$(id -un)"
|
||||
host="$(hostname 2>/dev/null || uname -n)"
|
||||
gpg_email="${user//[^A-Za-z0-9._-]/_}@${host//[^A-Za-z0-9._-]/_}"
|
||||
gpg_uid="$gpg_name <$gpg_email>"
|
||||
|
||||
if gpg --list-secret-keys "$gpg_uid" >/dev/null 2>&1; then
|
||||
log "GPG key for '$gpg_uid' already exists; skipping generation."
|
||||
else
|
||||
log "Generating GPG key for '$gpg_uid'..."
|
||||
local -a params=(
|
||||
"%echo Generating docker-credential key"
|
||||
"Key-Type: eddsa"
|
||||
"Key-Curve: ed25519"
|
||||
"Subkey-Type: ecdh"
|
||||
"Subkey-Curve: cv25519"
|
||||
"Name-Real: $gpg_name"
|
||||
"Name-Email: $gpg_email"
|
||||
"Expire-Date: 0"
|
||||
)
|
||||
if ((NO_PASSPHRASE)); then
|
||||
warn "creating an UNPROTECTED key (--no-passphrase)."
|
||||
warn " anyone who can read ~/.gnupg can decrypt your registry creds."
|
||||
params+=("%no-protection")
|
||||
else
|
||||
info "gpg will ask for a passphrase (via pinentry)."
|
||||
fi
|
||||
params+=("%commit" "%echo done")
|
||||
printf '%s\n' "${params[@]}" | gpg --batch --full-generate-key \
|
||||
|| die "GPG key generation failed" 1
|
||||
fi
|
||||
|
||||
# Pull the fingerprint back out for pass. Don't `exit` early in awk: with
|
||||
# pipefail that can SIGPIPE gpg and fail the whole pipeline at random.
|
||||
local fpr
|
||||
fpr="$(gpg --list-secret-keys --with-colons "$gpg_uid" \
|
||||
| awk -F: '/^fpr:/ && !seen { print $10; seen = 1 }')"
|
||||
[[ "$fpr" =~ ^[0-9A-Fa-f]{40,}$ ]] || die "could not determine the GPG key fingerprint (got '${fpr:0:80}')" 1
|
||||
|
||||
# --- pass init (only if the store isn't already initialized) ------------
|
||||
local store_dir="${PASSWORD_STORE_DIR:-$HOME/.password-store}"
|
||||
if [[ -f "$store_dir/.gpg-id" ]]; then
|
||||
log "pass already initialized at $store_dir; skipping init."
|
||||
else
|
||||
pass init "$fpr" || die "pass init failed" 1
|
||||
fi
|
||||
|
||||
echo >&2
|
||||
log "Done. Remaining manual step: docker login"
|
||||
}
|
||||
|
||||
main "$@"
|
||||
Reference in new issue
Block a user