diff --git a/api/apps/v1alpha1/postgresql/types.go b/api/apps/v1alpha1/postgresql/types.go index 76e62b179..95b0a57c1 100644 --- a/api/apps/v1alpha1/postgresql/types.go +++ b/api/apps/v1alpha1/postgresql/types.go @@ -65,7 +65,7 @@ type ConfigSpec struct { // Read-replica autoscaling configuration. // +kubebuilder:default:={} Autoscaling Autoscaling `json:"autoscaling"` - // Users configuration map. Passwords are always auto-generated and stored in the `-credentials` Secret; they cannot be set from values — read a user's password from that Secret. A `password` left over in values from before the field was removed is ignored by the render and draws an admission warning, but it is not inert on an upgraded release: the chart preserves whatever password is already in the Secret, which on the first upgrade is the value that was set before removal, so that value stays the live credential until it is rotated (dedicated rotation is tracked in cozystack/community#72). The live password lives only in the Secret. + // Users configuration map. Each user is a PostgreSQL role the operator manages from an account Secret the platform keeps. Passwords are issued through the Cozystack credentials API: a mint on the account's `Credential` (`core.cozystack.io`) returns a new password once and stores only its SCRAM verifier, and a revoke retires the password without issuing one. A `password` key here is ignored and draws an admission warning. A password set inside PostgreSQL is reverted by the operator. // +kubebuilder:default:={} Users map[string]User `json:"users,omitempty"` // Databases configuration map. The PostgreSQL system databases `postgres`, `template0` and `template1` are refused. @@ -243,9 +243,9 @@ type TLS struct { } type User struct { - // Whether the user can bypass row-level security policies (BYPASSRLS). A role can only create other roles carrying BYPASSRLS if it holds the attribute itself, so this is required alongside `createRole` to provision a privileged service role. + // Whether the user can bypass row-level security policies (BYPASSRLS). A role can only create other roles carrying BYPASSRLS if it holds the attribute itself. BypassRls bool `json:"bypassRls,omitempty"` - // Whether the user can create and manage roles (CREATEROLE). Requires PostgreSQL 16 or newer. Setting it back to `false` withdraws the attribute only: the roles the user created, and its ADMIN and SET memberships in them, stay. Once any user has held it, the chart no longer adopts an existing role it did not create, so a user or database declared later under the name of such a role fails the init job until a platform administrator drops that role. + // Not supported while users are CloudNativePG managed roles: the chart refuses to render when it is true, and a release that sets it keeps its previous chart version until it is false. CloudNativePG revokes every membership a managed role is not declared to hold, including the one PostgreSQL gives a CREATEROLE user in each role it creates. Setting it to false withdraws CREATEROLE from a role that held it. CreateRole bool `json:"createRole,omitempty"` // Whether the user has replication privileges. Replication bool `json:"replication,omitempty"` diff --git a/hack/check-postgres-app-owner-password.bats b/hack/check-postgres-app-owner-password.bats deleted file mode 100644 index 724bb714c..000000000 --- a/hack/check-postgres-app-owner-password.bats +++ /dev/null @@ -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 -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; } -} diff --git a/hack/e2e-chainsaw/endpointattachment/chainsaw-test.yaml b/hack/e2e-chainsaw/endpointattachment/chainsaw-test.yaml index 772ef6e65..ee7b939f3 100644 --- a/hack/e2e-chainsaw/endpointattachment/chainsaw-test.yaml +++ b/hack/e2e-chainsaw/endpointattachment/chainsaw-test.yaml @@ -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" diff --git a/hack/e2e-chainsaw/endpointattachment/query-as-testuser.sh b/hack/e2e-chainsaw/endpointattachment/query-as-testuser.sh new file mode 100755 index 000000000..75545c9ed --- /dev/null +++ b/hack/e2e-chainsaw/endpointattachment/query-as-testuser.sh @@ -0,0 +1,40 @@ +#!/usr/bin/env bash +# Usage: query-as-testuser.sh +# +# Mints a password for testuser of , waits until accepts +# it, then runs once against from 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" diff --git a/packages/apps/postgres/README.md b/packages/apps/postgres/README.md index 915f26298..ce47c9761 100644 --- a/packages/apps/postgres/README.md +++ b/packages/apps/postgres/README.md @@ -277,12 +277,12 @@ For `sslmode=verify-full` to work, the CA bundle retrieved above must be saved t ### Users configuration -| Name | Description | Type | Value | -| ------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------- | ------- | -| `users` | Users configuration map. Passwords are always auto-generated and stored in the `-credentials` Secret; they cannot be set from values — read a user's password from that Secret. A `password` left over in values from before the field was removed is ignored by the render and draws an admission warning, but it is not inert on an upgraded release: the chart preserves whatever password is already in the Secret, which on the first upgrade is the value that was set before removal, so that value stays the live credential until it is rotated (dedicated rotation is tracked in cozystack/community#72). The live password lives only in the Secret. | `map[string]object` | `{}` | -| `users[name].replication` | Whether the user has replication privileges. | `bool` | `false` | -| `users[name].createRole` | Whether the user can create and manage roles (CREATEROLE). Requires PostgreSQL 16 or newer. Setting it back to `false` withdraws the attribute only: the roles the user created, and its ADMIN and SET memberships in them, stay. Once any user has held it, the chart no longer adopts an existing role it did not create, so a user or database declared later under the name of such a role fails the init job until a platform administrator drops that role. | `bool` | `false` | -| `users[name].bypassRls` | Whether the user can bypass row-level security policies (BYPASSRLS). A role can only create other roles carrying BYPASSRLS if it holds the attribute itself, so this is required alongside `createRole` to provision a privileged service role. | `bool` | `false` | +| Name | Description | Type | Value | +| ------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------- | ------- | +| `users` | Users configuration map. Each user is a PostgreSQL role the operator manages from an account Secret the platform keeps. Passwords are issued through the Cozystack credentials API: a mint on the account's `Credential` (`core.cozystack.io`) returns a new password once and stores only its SCRAM verifier, and a revoke retires the password without issuing one. A `password` key here is ignored and draws an admission warning. A password set inside PostgreSQL is reverted by the operator. | `map[string]object` | `{}` | +| `users[name].replication` | Whether the user has replication privileges. | `bool` | `false` | +| `users[name].createRole` | Not supported while users are CloudNativePG managed roles: the chart refuses to render when it is true, and a release that sets it keeps its previous chart version until it is false. CloudNativePG revokes every membership a managed role is not declared to hold, including the one PostgreSQL gives a CREATEROLE user in each role it creates. Setting it to false withdraws CREATEROLE from a role that held it. | `bool` | `false` | +| `users[name].bypassRls` | Whether the user can bypass row-level security policies (BYPASSRLS). A role can only create other roles carrying BYPASSRLS if it holds the attribute itself. | `bool` | `false` | ### Databases configuration @@ -363,7 +363,16 @@ users: replication: true ``` -Passwords cannot be set here — they are auto-generated and stored in the `-credentials` Secret. Read a user's password with `kubectl get tenantsecret -credentials -o json | jq -r '.data["user1"]' | base64 -d` (a username may contain a `.`, which `jsonpath` would treat as a path step and return nothing). +Passwords cannot be set here. Each user is an account of the Cozystack credentials API: a `Credential` named `.` in `core.cozystack.io/v1alpha1`, where `` is the user name lowercased with every character outside `[a-z0-9-]` replaced by `-`. A mint returns a new password once and replaces the previous one; only its SCRAM verifier is stored, so the password cannot be read back: + +```bash +kubectl create --raw "/apis/core.cozystack.io/v1alpha1/namespaces//credentials/postgres-.user1/mint" \ + -f <(echo '{"apiVersion":"core.cozystack.io/v1alpha1","kind":"CredentialRequest"}') | jq -r .status.password +``` + +A user added to an existing application has no password until the first mint. Names PostgreSQL or CloudNativePG reserve (`postgres`, `streaming_replica`, `pg_*`, `cnpg_*`), the name of a database role (`_admin`, `_readonly`), and two users mapping to one account name are refused. + +Downgrading the platform past the conversion to minted passwords is not supported: the previous chart generates a new password for every account. A manual `helm rollback` of a release to a revision from before the conversion is undone at its next reconcile, and meanwhile the old revision's `-credentials` shows a password that no longer works; mint again once the release is back. ### databases diff --git a/packages/apps/postgres/templates/NOTES.txt b/packages/apps/postgres/templates/NOTES.txt index 214cd79f8..685296e11 100644 --- a/packages/apps/postgres/templates/NOTES.txt +++ b/packages/apps/postgres/templates/NOTES.txt @@ -1,20 +1,11 @@ {{- if and .Values.bootstrap.enabled .Values.users }} WARNING: this PostgreSQL was provisioned as a restore (bootstrap.enabled=true). -The roles recovered from the backup keep their original password hashes, but the -{{ .Release.Name }}-credentials Secret now holds freshly generated passwords that -are NOT yet applied to the database — the init-job that runs ALTER ROLE is skipped -while bootstrap is on. While bootstrap is on the credentials Secret carries the -annotation postgres.cozystack.io/credentials-pending: "true". That flag tracks only -the bootstrap phase, not the whole convergence: the restore driver REMOVES it when -it clears bootstrap.enabled, and that same reconcile is what triggers the init-job -— so the flag is already gone for the short window before the init-job has finished -applying the passwords. Do not read a missing flag as "converged". - -The restore driver clears bootstrap.enabled automatically once recovery is healthy, -and the next reconcile runs the init-job to apply the Secret's passwords onto the -recovered roles — no action is required. Confirm convergence by logging in as an -application user rather than by the flag; until a login with the Secret's password -succeeds, do not treat the advertised application passwords as usable — the database -is reachable as the CloudNativePG superuser in the meantime. +The roles recovered from the backup keep the password hashes of the source. Each +declared user is a managed role of the Cluster pointing at its account Secret, +and CloudNativePG applies the stored value from that Secret once the recovered +primary is up, so a password minted on this application's credentials +(core.cozystack.io) takes effect without any action here. A restored account +whose Secret was seeded with this application has no issued password yet: mint +one, and poll a login with it until it succeeds. {{- end }} diff --git a/packages/apps/postgres/templates/_accounts.tpl b/packages/apps/postgres/templates/_accounts.tpl new file mode 100644 index 000000000..7810840e2 --- /dev/null +++ b/packages/apps/postgres/templates/_accounts.tpl @@ -0,0 +1,62 @@ +{{/* + Account Secret naming, which must match pkg/credentials/account.MapName: + each user's CredentialTemplate is named ., where + is the user name lowercased with every character outside + [a-z0-9-] replaced by "-", and the controller writes its account Secret as +