fix(examples): mint the Postgres password in the backup examples

The examples read the application password from <release>-credentials,
which the chart no longer renders. They now mint it and pass it to psql
on stdin rather than as a kubectl exec argument, which travels in the
request URI the audit log records at any level. The minted password is
cached in a per-run mktemp -d directory, private and fresh each run, so
a later run never reads a password a mint has since replaced and no
other host user can read it. The helper's tests stub the mint.

Co-authored-by: IvanHunters <xorokhotnikov@gmail.com>
Assisted-by: LLM
Signed-off-by: Timofei Larkin <lllamnyp@gmail.com>
Signed-off-by: Andrei Kvapil <kvapss@gmail.com>
This commit is contained in:
Timofei LarkinandIvanHunters authored and Andrei Kvapil committed 2026-11-30 18:21:27 +01:00
1 parent a67fa94fdb
commit f982ea2cb9
3 files changed
+98 -60

No files matched your search

+40 -23
View File
@@ -84,40 +84,57 @@ psql_exec() {
psql -U postgres -d "$db" -tAc "$sql"
}
# Password of an application user, minted once through the credentials API and
# cached for the rest of the run: a mint replaces the account's password, so
# minting on every login would invalidate the previous attempt. The Credential
# is named <release>.<account>, where <account> is the user name lowercased
# with every character outside [a-z0-9-] replaced by "-", and the chart names
# the CNPG Cluster after the release, so the cluster IS the release here.
# Args: <cluster> <user>
# Minted passwords are cached for this run only, in a private run-scoped
# directory (mktemp -d is 0700), so a later run does not read a password a mint
# has since replaced, and no other user on the host can read the cache.
export COZY_PW_CACHE_DIR="${COZY_PW_CACHE_DIR:-$(mktemp -d "${TMPDIR:-/tmp}/cozy-pw.XXXXXXXX")}"
app_password() {
local cluster="$1" user="$2"
local acct cache
acct=$(printf '%s' "$user" | tr '[:upper:]' '[:lower:]' | sed 's/[^a-z0-9-]/-/g')
cache="${COZY_PW_CACHE_DIR}/${cluster}-${acct}"
if [[ ! -s "$cache" ]]; then
kubectl create --raw "/apis/core.cozystack.io/v1alpha1/namespaces/${NAMESPACE}/credentials/${cluster}.${acct}/mint" \
-f <(printf '{"apiVersion":"core.cozystack.io/v1alpha1","kind":"CredentialRequest"}') \
| jq -r '.status.password // empty' > "$cache"
fi
[[ -s "$cache" ]] || { log_error "no password minted for user '${user}' of ${cluster}"; return 1; }
cat "$cache"
}
# Run a psql statement AS the application user over TCP (via the cluster's -rw
# Service), forcing password authentication. psql_exec above connects as the
# in-pod postgres superuser through the local socket (peer auth) and so never
# exercises a user's password; only this path proves the password the
# <release>-credentials Secret advertises actually authenticates. The password is
# read from that chart-managed Secret with jq, not a jsonpath: a username may
# contain a '.', and jsonpath's `{.data['a.b']}` treats the dot as a path step
# and returns nothing, so a dotted user would read an empty password and time out
# on a credential that is fine. jq indexes the key as a literal string. The chart
# names the CNPG Cluster, the -rw Service and the credentials Secret all after the
# release, so the cluster IS the release here - derive the Secret from it rather
# than taking a separate name that a caller can get wrong (a release/app-name
# mix-up read a Secret that never exists and made every login time out).
# exercises a user's password.
# Args: <cluster> <user> <db> <sql>
psql_app_exec() {
local cluster="$1" user="$2" db="$3" sql="$4"
local pod pw
pod=$(cnpg_primary_pod "$cluster")
[[ -n "$pod" ]] || { log_error "no primary pod for cnpg cluster '$cluster'"; return 1; }
pw=$(kubectl -n "$NAMESPACE" get secret "${cluster}-credentials" -o json \
| jq -r --arg u "$user" '.data[$u] // empty' | base64 -d)
[[ -n "$pw" ]] || { log_error "no password for user '${user}' in ${cluster}-credentials"; return 1; }
kubectl -n "$NAMESPACE" exec "$pod" -c postgres -- \
env PGPASSWORD="$pw" psql -h "${cluster}-rw" -U "$user" -d "$db" -tAc "$sql"
pw=$(app_password "$cluster" "$user") || return 1
# The password goes to psql on stdin: exec arguments travel in the request
# URI, which the audit log records at any level.
printf '%s\n' "$pw" | kubectl -n "$NAMESPACE" exec -i "$pod" -c postgres -- \
sh -c 'IFS= read -r PGPASSWORD; export PGPASSWORD; exec psql "$@"' sh \
-h "${cluster}-rw" -U "$user" -d "$db" -tAc "$sql"
}
# Block until the application user can authenticate against a cluster, or fail
# after <timeout>s. Needed after a to-copy restore: the driver clears
# bootstrap.enabled once recovery converges so the chart's init-job re-runs
# ALTER ROLE ... WITH PASSWORD, converging the recovered roles (which carry the
# source's password hashes) onto the freshly generated <release>-credentials
# Secret. That convergence is asynchronous - a HelmRelease upgrade plus its
# post-upgrade init-job hook - so this is a readiness wait on an eventually
# consistent property, not a retry over a deterministic step.
# after <timeout>s. Needed after a to-copy restore: the recovered roles carry
# the source's password hashes until CloudNativePG applies the verifier from
# the account Secret, which it does once the restored primary is up and the
# release has left bootstrap. That convergence is asynchronous, so this is a
# readiness wait on an eventually consistent property, not a retry over a
# deterministic step.
# Args: <cluster> <user> <db> <timeout>
wait_for_app_login() {
local cluster="$1" user="$2" db="$3" timeout="${4:-300}"
@@ -137,7 +154,7 @@ wait_for_app_login() {
return 0
fi
if [[ $elapsed -ge $timeout ]]; then
log_error "Timeout waiting for user '${user}' to authenticate against ${cluster}: the credentials Secret advertises a password the roles never received (bootstrap not cleared, or the init-job did not reconcile). Last attempt: $(cat "$errfile")"
log_error "Timeout waiting for user '${user}' to authenticate against ${cluster}: the minted password never reached the role (bootstrap not cleared, or CloudNativePG did not apply the account Secret). Last attempt: $(cat "$errfile")"
rm -f "$errfile"
return 1
fi
+4 -5
View File
@@ -264,11 +264,10 @@ if [[ "$GOT" != "$SENTINEL_TOKEN" ]]; then
fi
log_success "Round-trip verified: '${PG_TARGET_NAME}' restored sentinel '${GOT}' from S3."
# The passwords in <target>-credentials are chart-generated and do not match the
# password hashes recovery brought back with the roles; the driver clears
# bootstrap.enabled so the init-job reconciles them. Prove the app user can
# actually log in against the restored copy - psql_exec above only ever used the
# in-pod postgres superuser, so a broken credential would otherwise pass silently.
# The roles recovery brought back carry the source's password hashes until
# CloudNativePG applies the target's account Secret. Prove the app user can
# log in against the restored copy - psql_exec above only ever used the in-pod
# postgres superuser, so a broken credential would otherwise pass silently.
print_header "Step 40 verify: the app user authenticates against the restored copy"
wait_for_app_login "$PG_TARGET_CLUSTER" app demo 360
APP_GOT=$(psql_app_exec "$PG_TARGET_CLUSTER" app demo \
+54 -32
View File
@@ -1,92 +1,114 @@
#!/usr/bin/env bats
# Unit tests for the app-login helpers the postgres backup example uses to prove
# the restored copy authenticates. The bug they pin: the credentials Secret is
# named after the release (== the CNPG cluster, `postgres-<name>`), not the short
# app name, so resolving it from anything but the cluster reads a Secret that
# does not exist and the login can never pass. Others: a genuine failure names
# the Secret on timeout; a login printing '1' is a success even with stderr
# noise; and a username with a dot reads its password (jq, not jsonpath).
# the restored copy authenticates. The password comes from a mint on the
# account's Credential, named <release>.<account> after the release (== the CNPG
# cluster, `postgres-<name>`), not the short app name: resolving it from anything
# but the cluster mints on a credential that does not exist, and the login can
# never pass. Others: a genuine failure names the credential on timeout; a login
# printing '1' is a success even with stderr noise; a username with a dot maps to
# its account name; and a run mints once, since a second mint replaces the
# password the first one returned.
#
# The helper reads the Secret with `get secret ... -o json | jq`, so the kubectl
# stub returns JSON. 00-helpers.sh is `#!/bin/bash` (it uses arrays), so it is
# exercised in a bash subshell rather than sourced into this runner, which is
# 00-helpers.sh is `#!/bin/bash` (it uses arrays and process substitution), so it
# is exercised in a bash subshell rather than sourced into this runner, which is
# /bin/sh (dash in CI). It is sourced first, then the stubs override its
# cluster-touching functions.
# cluster-touching functions. Each test gets its own TMPDIR, where the helper
# caches the minted password.
load test_helper
@test "psql_app_exec reads the credentials Secret named after the cluster, not the app name" {
MINT=/apis/core.cozystack.io/v1alpha1/namespaces/tenant-test/credentials
@test "psql_app_exec mints on the credential named after the cluster, not the app name" {
calls=$(mktemp)
CALLS="$calls" bash -uc '
CALLS="$calls" MINT="$MINT" TMPDIR=$(mktemp -d) bash -uc '
NAMESPACE=tenant-test
. examples/backups/postgres/00-helpers.sh
cnpg_primary_pod() { echo "${1}-1"; }
kubectl() {
printf "kubectl %s\n" "$*" >> "$CALLS"
case "$*" in
*"get secret postgres-pg-target-credentials -o json"*) printf "%s" "{\"data\":{\"app\":\"cGFzcw==\"}}" ;;
*"get secret "*) echo "WRONG secret queried: $*" >&2; return 1 ;;
*"create --raw $MINT/postgres-pg-target.app/mint"*) printf "%s" "{\"status\":{\"password\":\"pass\"}}" ;;
*"create --raw "*) echo "WRONG credential minted: $*" >&2; return 1 ;;
*" exec "*) echo 1 ;;
*) return 0 ;;
esac
}
psql_app_exec postgres-pg-target app demo "SELECT 1;" >/dev/null
'
grep -q 'get secret postgres-pg-target-credentials -o json' "$calls"
if grep -q 'get secret pg-target-credentials ' "$calls"; then
echo "resolved the Secret from the app name, not the cluster" >&2
grep -q "create --raw $MINT/postgres-pg-target.app/mint" "$calls"
if grep -q "credentials/pg-target.app/" "$calls"; then
echo "resolved the credential from the app name, not the cluster" >&2
exit 1
fi
}
@test "wait_for_app_login names the failing Secret on timeout instead of swallowing it" {
@test "wait_for_app_login names the failing credential on timeout instead of swallowing it" {
out=$(mktemp)
bash -uc '
TMPDIR=$(mktemp -d) bash -uc '
NAMESPACE=tenant-test
. examples/backups/postgres/00-helpers.sh
cnpg_primary_pod() { echo "${1}-1"; }
kubectl() {
case "$*" in
# Secret exists but has no password for app; the helper log_errors
# naming it, and the wait loop must surface that on timeout.
*"get secret postgres-pg-target-credentials -o json"*) printf "%s" "{\"data\":{}}" ;;
# The mint answers without a password; the helper log_errors
# naming the user, and the wait loop must surface that on timeout.
*"create --raw "*) printf "%s" "{\"status\":{}}" ;;
*) return 0 ;;
esac
}
wait_for_app_login postgres-pg-target app demo 0
' >"$out" 2>&1 && { echo "wait_for_app_login unexpectedly passed with no password" >&2; exit 1; }
grep -q "no password for user 'app' in postgres-pg-target-credentials" "$out"
grep -q "no password minted for user 'app' of postgres-pg-target" "$out"
}
@test "psql_app_exec reads the password for a username containing a dot" {
@test "psql_app_exec maps a username containing a dot to its account name" {
calls=$(mktemp)
CALLS="$calls" bash -uc '
CALLS="$calls" MINT="$MINT" TMPDIR=$(mktemp -d) bash -uc '
NAMESPACE=tenant-test
. examples/backups/postgres/00-helpers.sh
cnpg_primary_pod() { echo "${1}-1"; }
kubectl() {
printf "kubectl %s\n" "$*" >> "$CALLS"
case "$*" in
# A dotted key is why jsonpath fails and jq is used; return the
# Secret as JSON so jq can index the literal "app.user" key.
*"get secret postgres-pg-target-credentials -o json"*) printf "%s" "{\"data\":{\"app.user\":\"cGFzcw==\"}}" ;;
*"create --raw $MINT/postgres-pg-target.app-user/mint"*) printf "%s" "{\"status\":{\"password\":\"pass\"}}" ;;
*" exec "*) echo 1 ;;
*) return 0 ;;
esac
}
psql_app_exec postgres-pg-target app.user demo "SELECT 1;" >/dev/null
psql_app_exec postgres-pg-target app.User demo "SELECT 1;" >/dev/null
'
grep -q 'get secret postgres-pg-target-credentials -o json' "$calls"
grep -q "create --raw $MINT/postgres-pg-target.app-user/mint" "$calls"
}
@test "psql_app_exec mints once per run" {
calls=$(mktemp)
CALLS="$calls" TMPDIR=$(mktemp -d) bash -uc '
NAMESPACE=tenant-test
. examples/backups/postgres/00-helpers.sh
cnpg_primary_pod() { echo "${1}-1"; }
kubectl() {
printf "kubectl %s\n" "$*" >> "$CALLS"
case "$*" in
*"create --raw "*) printf "%s" "{\"status\":{\"password\":\"pass\"}}" ;;
*" exec "*) echo 1 ;;
*) return 0 ;;
esac
}
psql_app_exec postgres-pg-target app demo "SELECT 1;" >/dev/null
psql_app_exec postgres-pg-target app demo "SELECT 1;" >/dev/null
'
[ "$(grep -c 'create --raw ' "$calls")" -eq 1 ]
}
@test "wait_for_app_login treats a login that prints '1' as success even with stderr noise" {
bash -uc '
TMPDIR=$(mktemp -d) bash -uc '
NAMESPACE=tenant-test
. examples/backups/postgres/00-helpers.sh
cnpg_primary_pod() { echo "${1}-1"; }
kubectl() {
case "$*" in
*"get secret postgres-pg-target-credentials -o json"*) printf "%s" "{\"data\":{\"app\":\"cGFzcw==\"}}" ;;
*"create --raw "*) printf "%s" "{\"status\":{\"password\":\"pass\"}}" ;;
# A successful SELECT 1 prints 1 on stdout; a NOTICE on stderr
# must not be read as a failure (success is stdout-only).
*" exec "*) echo 1; echo "NOTICE: something" >&2 ;;