feat(postgres)!: issue user passwords through the credentials API

The chart generated every user's password at render time into
<release>-credentials, which tenants could read again at any time and
which Helm history kept for MaxHistory revisions, so a deployment whose
policy requires a credential shown once could not run PostgreSQL here.

The chart now renders a CredentialTemplate per user, and the users move
under CloudNativePG's managed roles, each pointing at its account
Secret, so the operator creates the role with the SCRAM verifier the
Secret holds, applies a changed Secret live, and reverts a password set
inside PostgreSQL. Every role is rendered as the init-script created it,
because the operator reverts an attribute that differs, revokes a parent
role missing from inRoles and clears a comment the spec leaves unset.
The init-script stops creating, passwording and altering accounts, where
it would be a second writer, and keeps the two things the operator has
no field for: the marker membership and the reset of the
createrole_self_grant an earlier chart set. Its marking pass waits a
bounded time for CloudNativePG to create the declared roles before it
marks them. users.app adopts the owner CloudNativePG bootstraps, whose
password the instance manager applies again from the bootstrap secret
on every pod start, so that secret is the app user's account Secret
and both writers apply the one stored verifier. A users.<name>.password
left in values draws an admission warning that points at a mint on the
user's Credential.

createRole is refused on every render path. A role a CREATEROLE user
creates makes that user a member of it, CloudNativePG revokes every
membership a managed role is not declared to hold, and the revoke fails
on the dependent self-grant, so the user would sit in cannotReconcile on
ordinary use; there is no per-role switch to leave memberships alone.
The account-name checks render with the managed roles too, so a restore
cannot bypass them: a user CloudNativePG or PostgreSQL reserves, a
database whose derived <name>_admin or <name>_readonly role starts with
pg_ or cnpg_ (which makes the CloudNativePG webhook reject the whole
Cluster), and a user whose account name is no valid object name are
refused. The chart's account naming is pinned to the API's on one table
of names.

A pre-upgrade hook refuses to let CloudNativePG adopt a role the chart
did not mark, because the operator adopts a managed role within seconds
of the spec reaching it, before any post-upgrade job could look. It
reads the live Cluster first and connects to the database only when the
upgrade adds a name CloudNativePG does not manage yet, so a database
that is down does not block the resize that might fix it. For each
absent declared database role it creates and marks the role as the
superuser before the Cluster applies, so no tenant can plant it in the
adoption window. The refusal and the create run in one psql session,
keyed on a snapshot of the role's existence taken at the top, so a role
planted in between collides with the CREATE and stops the hook; the
statements are built with format() and \gexec, since psql does not
substitute :'role' inside a DO $$ block. Verified on postgres:18: a
fresh role is created NOINHERIT, commented and marked, a role planted
after the snapshot fails the hook, and an existing unmarked role is
refused. The hook reads the Cluster at run time with a ServiceAccount
that may get only that Cluster, rather than through a template lookup,
which nothing re-renders when the object changes. The flag an earlier
chart set when a user held createRole is still read and never set, so
such a release keeps refusing to adopt a role it did not mark.

The EndpointAttachment e2e suite read testuser's password from that
Secret to probe the attached addresses. It now mints one per probe and
waits until the application's own Service accepts it, so the attached
address is still queried exactly once.

BREAKING CHANGE: PostgreSQL passwords are no longer readable from
<release>-credentials. A password is issued once, by a mint on the
account's Credential in core.cozystack.io, and replaced by the next
mint. users.<name>.createRole is refused; a release that sets it keeps
its previous chart version and passwords until it is false. Deleting a
Postgres application whose release is suspended is refused. The
conversion needs a platform variant with migrations enabled.

Co-authored-by: IvanHunters <xorokhotnikov@gmail.com>
Co-authored-by: Andrei Kvapil <kvapss@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:
authored and Andrei Kvapil committed 2026-11-30 18:21:27 +01:00
1 parent 780a358083
commit a67fa94fdb
32 files changed
+1430 -972

No files matched your search

@@ -1,25 +0,0 @@
#!/usr/bin/env bats
# Unit test: on a fresh install, packages/apps/postgres hands CNPG the same
# users.app password it stores in <release>-credentials.
#
# The password is generated at render time, so the two Secrets can only be
# compared within one render. helm-unittest asserts each document against a
# fixed value and has no way to compare one document with another, so a chart
# generating two independent passwords would still pass the chart's own suite.
load test_helper
REPO_ROOT="$(cd "$(dirname "${BATS_TEST_FILENAME:-$0}")/.." && pwd)"
CHART="$REPO_ROOT/packages/apps/postgres"
@test "a fresh users.app gets one generated password in both Secrets" {
rendered="$BATS_TEST_TMPDIR/init-script.yaml"
helm template pg "$CHART" --namespace tenant-test \
--set-json '_cluster={"scheduling":{}}' --set-json 'users={"app":{}}' \
--show-only templates/init-script.yaml > "$rendered"
app=$(yq -e 'select(.kind == "Secret" and .metadata.name == "pg-credentials").stringData.app' "$rendered")
owner=$(yq -e 'select(.kind == "Secret" and .metadata.name == "pg-app-owner").stringData.password' "$rendered")
[ -n "$app" ] || { echo "no generated password for app in pg-credentials" >&2; return 1; }
[ "$app" = "$owner" ] || { printf 'pg-credentials app: %s\npg-app-owner password: %s\n' "$app" "$owner" >&2; return 1; }
}
@@ -68,6 +68,26 @@ spec:
metadata:
name: postgres-ea-b-rw
(subsets[0].addresses[0].ip != null): true
# The probes below mint testuser's password, which needs the Credential
# cozystack-controller keeps for each application user.
- assert:
timeout: 2m
resource:
apiVersion: core.cozystack.io/v1alpha1
kind: Credential
metadata:
name: postgres-ea-a.testuser
spec:
user: testuser
- assert:
timeout: 2m
resource:
apiVersion: core.cozystack.io/v1alpha1
kind: Credential
metadata:
name: postgres-ea-b.testuser
spec:
user: testuser
# Lineage: ea-b's primary is tenant-facing, but not ea-a's, so an attachment
# naming ea-a is refused and renders nothing.
@@ -121,18 +141,17 @@ spec:
(addresses[0] != null): true
(claimName != null): true
- script:
timeout: 2m
timeout: 4m
content: |
set -eu
ip=$(kubectl -n "$NAMESPACE" get endpointattachments.local.sdn.cozystack.io ea-a-ro -o jsonpath='{.status.addresses[0]}')
pod=$(kubectl -n "$NAMESPACE" get pod -l cnpg.io/cluster=postgres-ea-a,cnpg.io/instanceRole=primary -o name | head -n1)
# The chart generates each user's password into its credentials Secret.
pw=$(kubectl get secret postgres-ea-a-credentials --namespace "$NAMESPACE" --output jsonpath='{.data.testuser}' | base64 -d)
# The attached address must answer as a replica, not as the primary
# the pod itself is: "t" from pg_is_in_recovery() proves the
# -ro selector was mirrored, not the -rw one.
kubectl -n "$NAMESPACE" exec "$pod" -c postgres -- \
env PGPASSWORD="$pw" psql -h "$ip" -U testuser -d testdb -tAc 'SELECT pg_is_in_recovery()'
# -ro selector was mirrored, not the -rw one. The wait is on the
# application's own -ro Service, so the replica already has the
# minted password when the address is asked.
./query-as-testuser.sh postgres-ea-a "$pod" postgres-ea-a-ro "$ip" 'SELECT pg_is_in_recovery()'
check:
($error == null): true
(trim_space($stdout)): "t"
@@ -207,7 +226,7 @@ spec:
phase: Attached
claimName: ea-held
- script:
timeout: 2m
timeout: 4m
content: |
set -eu
ip=$(kubectl get ipaddressclaims.local.sdn.cozystack.io ea-held --namespace "$NAMESPACE" --output jsonpath='{.metadata.annotations.e2e\.cozystack\.io/reserved-address}')
@@ -217,9 +236,7 @@ spec:
pod=$(kubectl -n "$NAMESPACE" get pod -l cnpg.io/cluster=postgres-ea-b -o name | head -n1)
# Probe from ea-b's pod so the answer cannot come from the local
# instance: the reserved address must reach ea-a's primary.
pw=$(kubectl get secret postgres-ea-a-credentials --namespace "$NAMESPACE" --output jsonpath='{.data.testuser}' | base64 -d)
kubectl -n "$NAMESPACE" exec "$pod" -c postgres -- \
env PGPASSWORD="$pw" psql -h "$ip" -U testuser -d testdb -tAc "SELECT current_setting('cluster_name') || ' ' || pg_is_in_recovery()"
./query-as-testuser.sh postgres-ea-a "$pod" postgres-ea-a-rw "$ip" "SELECT current_setting('cluster_name') || ' ' || pg_is_in_recovery()"
check:
($error == null): true
(trim_space($stdout)): "postgres-ea-a false"
@@ -277,7 +294,7 @@ spec:
phase: Attached
claimName: ea-held
- script:
timeout: 2m
timeout: 4m
content: |
set -eu
ip=$(kubectl get ipaddressclaims.local.sdn.cozystack.io ea-held --namespace "$NAMESPACE" --output jsonpath='{.metadata.annotations.e2e\.cozystack\.io/reserved-address}')
@@ -285,9 +302,7 @@ spec:
got=$(kubectl -n "$NAMESPACE" get endpointattachments.local.sdn.cozystack.io ea-b-rw-held -o jsonpath='{.status.addresses[0]}')
[ "$got" = "$ip" ]
pod=$(kubectl -n "$NAMESPACE" get pod -l cnpg.io/cluster=postgres-ea-a,cnpg.io/instanceRole=primary -o name | head -n1)
pw=$(kubectl get secret postgres-ea-b-credentials --namespace "$NAMESPACE" --output jsonpath='{.data.testuser}' | base64 -d)
kubectl -n "$NAMESPACE" exec "$pod" -c postgres -- \
env PGPASSWORD="$pw" psql -h "$ip" -U testuser -d testdb -tAc "SELECT current_setting('cluster_name') || ' ' || pg_is_in_recovery()"
./query-as-testuser.sh postgres-ea-b "$pod" postgres-ea-b-rw "$ip" "SELECT current_setting('cluster_name') || ' ' || pg_is_in_recovery()"
check:
($error == null): true
(trim_space($stdout)): "postgres-ea-b false"
+40
View File
@@ -0,0 +1,40 @@
#!/usr/bin/env bash
# Usage: query-as-testuser.sh <release> <pod> <ready-host> <host> <query>
#
# Mints a password for testuser of <release>, waits until <ready-host> accepts
# it, then runs <query> once against <host> from <pod> and prints the answer.
#
# The chart keeps no password a tenant can read back, so each probe mints its
# own. A mint replaces the previous password, and CloudNativePG applies it
# live, on a replica once replay reaches it; the wait is on the application's
# own Service, so the address under test is queried exactly once and a wrong
# answer from it is never retried away. The wait carries its own deadline: the
# step's ceiling kills only the calling shell, which would leave this loop
# running and holding the step's output open.
set -euo pipefail
release=$1 pod=$2 ready=$3 host=$4 query=$5
pw=$(kubectl create --raw "/apis/core.cozystack.io/v1alpha1/namespaces/$NAMESPACE/credentials/$release.testuser/mint" \
--filename <(printf '{"apiVersion":"core.cozystack.io/v1alpha1","kind":"CredentialRequest"}') \
| jq --raw-output '.status.password')
[ "${#pw}" -eq 32 ] || { echo "minted password has ${#pw} characters, want 32" >&2; exit 1; }
# The password goes to psql on stdin: exec arguments travel in the request
# URI, which the audit log records at any level.
psql_on() {
printf '%s\n' "$pw" | kubectl --namespace "$NAMESPACE" exec --stdin "$pod" --container postgres -- \
sh -c 'IFS= read -r PGPASSWORD; export PGPASSWORD; exec psql "$@"' sh \
-h "$1" -U testuser -d testdb -tAc "$2"
}
deadline=$((SECONDS + 180))
until [ "$(psql_on "$ready" 'SELECT 1' 2>/dev/null | tr -d '[:space:]')" = 1 ]; do
if [ "$SECONDS" -ge "$deadline" ]; then
echo "$ready did not accept the password minted for $release.testuser within 180s" >&2
exit 1
fi
sleep 5
done
psql_on "$host" "$query"