Files
notfiles/scripts/docker-creds.sh
T

187 lines
6.8 KiB
Bash
Executable File

#!/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
SCRIPT_DIR="$(cd -- "$(dirname -- "$(readlink -f -- "${BASH_SOURCE[0]}")")" && pwd -P)"
# shellcheck source=lib/common.sh
source "$SCRIPT_DIR/lib/common.sh"
usage() {
cat <<'EOF'
Usage: docker-creds.sh [STORE] [--no-passphrase]
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
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
path, store = sys.argv[1], sys.argv[2]
config = {}
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.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
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
}
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
local config_dir="${DOCKER_CONFIG:-${HOME:?HOME is not set}/.docker}"
local config_file="$config_dir/config.json"
# --- 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
# 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
# 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 "$@"