mirror of
https://github.com/cozystack/cozystack.git
synced 2026-12-05 22:53:43 +09:00
The e2e test mints a password, logs in with it, and checks every place it could be read again: the account Secret must hold a SCRAM verifier, decoded rather than matched in the raw base64; neither the application, any Helm revision nor what the tenant's super-admins read through tenantsecrets may carry it; and they cannot read the account Secret. Each read is captured in an assignment, which stops the script on failure, so a failed kubectl, base64 or gunzip cannot leave a check with nothing to assert on, and at least one Helm release Secret is required. The step runs under bash and passes the password to psql on stdin, never as an exec argument. 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>
831 lines
38 KiB
YAML
831 lines
38 KiB
YAML
# Chainsaw port of hack/e2e-apps/postgres.bats ("Create DB PostgreSQL").
|
|
#
|
|
# Every `timeout N sh -ec "until kubectl get ..."` + `kubectl wait` pair from
|
|
# the BATS test collapses into a single assert: chainsaw polls until the
|
|
# resource exists AND matches, or the timeout expires. Failure output is a
|
|
# structured diff of the assertion tree against the live object.
|
|
apiVersion: chainsaw.kyverno.io/v1alpha1
|
|
kind: Test
|
|
metadata:
|
|
name: postgres
|
|
spec:
|
|
# Diagnostics collected automatically when any step fails. The BATS suite
|
|
# only does this in harbor.bats, by hand.
|
|
catch:
|
|
- events: {}
|
|
- describe:
|
|
apiVersion: helm.toolkit.fluxcd.io/v2
|
|
kind: HelmRelease
|
|
name: postgres-test
|
|
- podLogs:
|
|
selector: cnpg.io/cluster=postgres-test
|
|
tail: 50
|
|
steps:
|
|
- name: create-postgres
|
|
try:
|
|
- apply:
|
|
file: postgres.yaml
|
|
|
|
- name: wait-helmrelease-ready
|
|
try:
|
|
# 11m: above the 600s install timeout cozystack-api gives this release;
|
|
# see "Sizing an HR-Ready budget" in docs/agents/e2e-testing.md.
|
|
- assert:
|
|
timeout: 11m
|
|
resource:
|
|
apiVersion: helm.toolkit.fluxcd.io/v2
|
|
kind: HelmRelease
|
|
metadata:
|
|
name: postgres-test
|
|
status:
|
|
# JMESPath filter: condition order in the array does not matter
|
|
(conditions[?type == 'Ready']):
|
|
- status: "True"
|
|
|
|
- name: wait-init-job-complete
|
|
try:
|
|
- assert:
|
|
timeout: 2m
|
|
resource:
|
|
apiVersion: batch/v1
|
|
kind: Job
|
|
metadata:
|
|
name: postgres-test-init-job
|
|
status:
|
|
(conditions[?type == 'Complete']):
|
|
- status: "True"
|
|
|
|
- name: verify-services-and-endpoints
|
|
try:
|
|
# Replaces three `until kubectl get svc ... | grep -q 5432` loops
|
|
# TODO(chainsaw>0.2.15): the (ports[0].port) / (ports[*].port) projection form in
|
|
# these Service asserts is a v0.2.15 workaround for mis-evaluated number-literal
|
|
# filters (ports[?port==`5432`]); (ports[0]) also checks only the first port.
|
|
# Restore the filter form on a chainsaw bump. Same workaround lives in
|
|
# kafka/mariadb/harbor — see "Chainsaw v0.2.15 gotchas" in docs/agents/e2e-testing.md.
|
|
- assert:
|
|
resource:
|
|
apiVersion: v1
|
|
kind: Service
|
|
metadata:
|
|
name: postgres-test-r
|
|
spec:
|
|
(ports[0].port): 5432
|
|
- assert:
|
|
resource:
|
|
apiVersion: v1
|
|
kind: Service
|
|
metadata:
|
|
name: postgres-test-ro
|
|
spec:
|
|
(ports[0].port): 5432
|
|
- assert:
|
|
resource:
|
|
apiVersion: v1
|
|
kind: Service
|
|
metadata:
|
|
name: postgres-test-rw
|
|
spec:
|
|
(ports[0].port): 5432
|
|
# Replaces `until kubectl get endpoints ... | grep -q '[0-9]'` loops.
|
|
# The read-only endpoint is skipped, same as in the BATS test.
|
|
- assert:
|
|
timeout: 3m
|
|
resource:
|
|
apiVersion: v1
|
|
kind: Endpoints
|
|
metadata:
|
|
name: postgres-test-r
|
|
(subsets[0].addresses[0].ip != null): true
|
|
- assert:
|
|
timeout: 3m
|
|
resource:
|
|
apiVersion: v1
|
|
kind: Endpoints
|
|
metadata:
|
|
name: postgres-test-rw
|
|
(subsets[0].addresses[0].ip != null): true
|
|
# Functional probe — the BATS test never actually talks to the database.
|
|
- script:
|
|
timeout: 2m
|
|
content: |
|
|
set -eu
|
|
pod=$(kubectl -n "$NAMESPACE" get pod \
|
|
-l cnpg.io/cluster=postgres-test,cnpg.io/instanceRole=primary \
|
|
-o name | head -n1)
|
|
kubectl -n "$NAMESPACE" exec "$pod" -c postgres -- \
|
|
psql -U postgres -tAc 'SELECT 1'
|
|
check:
|
|
($error == null): true
|
|
(contains($stdout, '1')): true
|
|
# The init-job is operator-created (not applied by chainsaw), so it is
|
|
# not part of automatic cleanup — delete it explicitly, as BATS does.
|
|
finally:
|
|
- delete:
|
|
ref:
|
|
apiVersion: batch/v1
|
|
kind: Job
|
|
name: postgres-test-init-job
|
|
|
|
# No second disclosure: the minted password logs in over TCP as the user,
|
|
# the Credential records the mint, no read path the design names carries
|
|
# the password (the audit log aside, which the sandbox does not collect),
|
|
# and a second mint replaces the first once CloudNativePG applies it.
|
|
- name: verify-minted-credential
|
|
try:
|
|
- assert:
|
|
timeout: 2m
|
|
resource:
|
|
apiVersion: core.cozystack.io/v1alpha1
|
|
kind: Credential
|
|
metadata:
|
|
name: postgres-test.testuser
|
|
spec:
|
|
application:
|
|
kind: Postgres
|
|
name: test
|
|
user: testuser
|
|
status:
|
|
password:
|
|
origin: NotIssued
|
|
# bash for pipefail and process substitution; the sandbox's /bin/sh is dash.
|
|
- script:
|
|
timeout: 5m
|
|
shell: bash
|
|
content: |
|
|
set -euo pipefail
|
|
cred=postgres-test.testuser
|
|
as="--as=e2e-postgres-probe --as-group=system:authenticated --as-group=${NAMESPACE}-super-admin"
|
|
mint() {
|
|
kubectl create --raw "/apis/core.cozystack.io/v1alpha1/namespaces/$NAMESPACE/credentials/$cred/mint" \
|
|
-f <(printf '{"apiVersion":"core.cozystack.io/v1alpha1","kind":"CredentialRequest"}') \
|
|
| jq -r '.status.password'
|
|
}
|
|
# The password goes to psql on stdin: exec arguments travel in the
|
|
# request URI, which the audit log records at any level.
|
|
login() {
|
|
printf '%s\n' "$1" | kubectl -n "$NAMESPACE" exec -i "$pod" -c postgres -- \
|
|
sh -c 'IFS= read -r PGPASSWORD; export PGPASSWORD; exec psql "$@"' sh \
|
|
-h postgres-test-rw -U testuser -d testdb -tAc 'SELECT 1' 2>/dev/null | tr -d '[:space:]' || true
|
|
}
|
|
# Fails when any of the named texts carries the password.
|
|
refuse() {
|
|
local what=$1 text=$2
|
|
if printf '%s' "$text" | grep -qF -- "$first"; then
|
|
echo "$what carries the minted password" >&2
|
|
exit 1
|
|
fi
|
|
}
|
|
pod=$(kubectl -n "$NAMESPACE" get pod \
|
|
-l cnpg.io/cluster=postgres-test,cnpg.io/instanceRole=primary -o name | head -n1)
|
|
|
|
first=$(mint)
|
|
[ "${#first}" -eq 32 ] || { echo "minted password has ${#first} characters, want 32" >&2; exit 1; }
|
|
# CloudNativePG applies the changed account Secret live; a readiness
|
|
# wait on that eventually consistent property, not a retry.
|
|
until [ "$(login "$first")" = "1" ]; do sleep 5; done
|
|
|
|
view=$(kubectl -n "$NAMESPACE" get credentials.core.cozystack.io "$cred" -o json)
|
|
[ "$(printf '%s' "$view" | jq -r .status.password.origin)" = "Minted" ] || { echo "origin is not Minted: $view" >&2; exit 1; }
|
|
[ "$(printf '%s' "$view" | jq -r '.status.history[0].operation')" = "Mint" ] || { echo "history lacks the mint: $view" >&2; exit 1; }
|
|
refuse "the Credential" "$view"
|
|
|
|
# The account Secret holds the verifier, decoded, never the password.
|
|
stored=$(kubectl -n "$NAMESPACE" get secret "$cred.account" -o json | jq -r '.data.password' | base64 -d)
|
|
case "$stored" in
|
|
'SCRAM-SHA-256$4096:'*) ;;
|
|
*) echo "the account Secret does not hold a SCRAM verifier" >&2; exit 1 ;;
|
|
esac
|
|
refuse "the account Secret" "$stored"
|
|
|
|
# Capture each read in an assignment first: under set -e a failing
|
|
# command substitution in an argument does not stop the script (the
|
|
# argument just comes out empty and the check passes without reading).
|
|
events=$(kubectl -n "$NAMESPACE" get events -o json)
|
|
refuse "an Event" "$events"
|
|
application=$(kubectl -n "$NAMESPACE" get postgreses.apps.cozystack.io test -o json)
|
|
refuse "the application" "$application"
|
|
# Every revision of the release, decoded: Helm stores each as base64
|
|
# of gzipped JSON inside the Secret's base64. Require at least one, so
|
|
# an empty match cannot pass the check without reading anything.
|
|
rels=$(kubectl -n "$NAMESPACE" get secret -l owner=helm,name=postgres-test -o name)
|
|
[ -n "$rels" ] || { echo "no Helm release Secret for postgres-test to inspect" >&2; exit 1; }
|
|
for rel in $rels; do
|
|
decoded=$(kubectl -n "$NAMESPACE" get "$rel" -o jsonpath='{.data.release}' | base64 -d | base64 -d | gunzip)
|
|
refuse "Helm release $rel" "$decoded"
|
|
done
|
|
# Everything the tenant's own super-admins can read through
|
|
# tenantsecrets, decoded; the account Secret is not among it.
|
|
visible=$(kubectl -n "$NAMESPACE" get tenantsecrets.core.cozystack.io $as -o json)
|
|
if printf '%s' "$visible" | jq -r '.items[].metadata.name' | grep -Fqx "$cred.account"; then
|
|
echo "the account Secret is listed through tenantsecrets" >&2; exit 1
|
|
fi
|
|
decoded_visible=$(printf '%s' "$visible" | jq -r '.items[].data // {} | .[] | @base64d')
|
|
refuse "tenantsecrets" "$decoded_visible"
|
|
# can-i exits 1 when it answers no, so the answer is read from its
|
|
# output; anything but a plain "no" fails, an error included.
|
|
answer=$(kubectl -n "$NAMESPACE" auth can-i get "secret/$cred.account" $as 2>&1) || true
|
|
if [ "$answer" != no ]; then
|
|
echo "the tenant super-admin group can read the account Secret, or can-i did not answer: $answer" >&2
|
|
exit 1
|
|
fi
|
|
|
|
second=$(mint)
|
|
[ "$second" != "$first" ] || { echo "a second mint returned the same password" >&2; exit 1; }
|
|
until [ "$(login "$second")" = "1" ]; do sleep 5; done
|
|
if [ "$(login "$first")" = "1" ]; then echo "the replaced password still logs in" >&2; exit 1; fi
|
|
check:
|
|
($error == null): true
|
|
|
|
# The trust anchor a client verifies against, checked against the live
|
|
# operator rather than against our own beliefs about it.
|
|
#
|
|
# This is the only independent witness the CA-extraction feature has. Its unit
|
|
# tests build CNPG's CA Secret from a fixture that encodes the same assumption
|
|
# the shipped ApplicationDefinition encodes ("{{ .release }}-ca", key ca.crt),
|
|
# so the two agree by construction and cannot catch each other being wrong.
|
|
# Only a real CNPG can say whether that name and key are right, and only a real
|
|
# apiserver can say whether the lineage webhook actually promotes the
|
|
# projection to a tenant-readable object.
|
|
- name: verify-tenant-ca-projection
|
|
try:
|
|
# Postgres never opts out of TLS: CNPG mints its CA regardless of the
|
|
# chart's tls flag, so the projection is expected on this plain fixture.
|
|
#
|
|
# The labels are the assertion that matters. tenant-ca is stamped by the
|
|
# controller; tenantresource is stamped by the LINEAGE WEBHOOK, computed
|
|
# from the ApplicationDefinition's spec.secrets — the new matchLabels
|
|
# include. It is "true" only if the whole chain held: definition selects the
|
|
# label, webhook admitted the object, verdict came out positive. Nothing
|
|
# short of a live cluster proves that link.
|
|
- assert:
|
|
timeout: 2m
|
|
resource:
|
|
apiVersion: v1
|
|
kind: Secret
|
|
metadata:
|
|
name: postgres-test.tenant-ca
|
|
labels:
|
|
internal.cozystack.io/tenant-ca: "true"
|
|
internal.cozystack.io/tenantresource: "true"
|
|
type: Opaque
|
|
# The projection must be the CA and ONLY the CA. Everything below is
|
|
# deterministic once the assert above has passed, so it runs without retry.
|
|
- script:
|
|
content: |
|
|
set -eu
|
|
|
|
# Exactly one key, and it is ca.crt. Any second key is a leak in the
|
|
# making: the source this was lifted from carries a private key.
|
|
keys=$(kubectl -n "$NAMESPACE" get secret postgres-test.tenant-ca \
|
|
-o go-template='{{range $k, $v := .data}}{{$k}}{{"\n"}}{{end}}' | sort | tr '\n' ' ')
|
|
if [ "$keys" != "ca.crt " ]; then
|
|
echo "projection must hold exactly ca.crt, holds: $keys" >&2
|
|
exit 1
|
|
fi
|
|
|
|
# It lifted the right certificate: the projection's ca.crt is CNPG's
|
|
# ca.crt. This is what pins "{{ .release }}-ca" to reality — if CNPG ever
|
|
# renames its CA Secret, the controller finds nothing and this fails.
|
|
#
|
|
# Compare the parsed certificates, not the raw PEM. The controller
|
|
# re-encodes ca.crt from the DER it parsed (certificateChainPEM), so a PEM
|
|
# header line or a column-width change at the source would redden a
|
|
# byte-for-byte comparison of a correct projection. The certificate
|
|
# fingerprint is identity-stable across any re-encoding.
|
|
src=$(kubectl -n "$NAMESPACE" get secret postgres-test-ca -o jsonpath='{.data.ca\.crt}' | base64 -d)
|
|
proj=$(kubectl -n "$NAMESPACE" get secret postgres-test.tenant-ca -o jsonpath='{.data.ca\.crt}' | base64 -d)
|
|
if [ -z "$src" ]; then
|
|
echo "CNPG's postgres-test-ca has no ca.crt — the declared source name or key is wrong" >&2
|
|
exit 1
|
|
fi
|
|
src_fp=$(echo "$src" | openssl x509 -noout -fingerprint -sha256)
|
|
proj_fp=$(echo "$proj" | openssl x509 -noout -fingerprint -sha256)
|
|
if [ "$src_fp" != "$proj_fp" ]; then
|
|
echo "projection does not carry CNPG's CA certificate" >&2
|
|
exit 1
|
|
fi
|
|
|
|
# And the point of the whole exercise: the source carries the CA
|
|
# PRIVATE KEY, the projection must not. Asserting the source really
|
|
# does hold ca.key keeps this honest — if CNPG ever stopped storing it
|
|
# there, this check would otherwise pass while proving nothing.
|
|
if ! kubectl -n "$NAMESPACE" get secret postgres-test-ca \
|
|
-o go-template='{{if .data}}{{range $k, $v := .data}}{{$k}}{{"\n"}}{{end}}{{end}}' | grep -qx 'ca.key'; then
|
|
echo "CNPG's CA Secret no longer carries ca.key — this check has stopped proving anything" >&2
|
|
exit 1
|
|
fi
|
|
if kubectl -n "$NAMESPACE" get secret postgres-test.tenant-ca \
|
|
-o go-template='{{if .data}}{{range $k, $v := .data}}{{$k}}{{"\n"}}{{end}}{{end}}' | grep -qx 'ca.key'; then
|
|
echo "projection leaked the CA private key" >&2
|
|
exit 1
|
|
fi
|
|
|
|
# Belt and braces on the bytes themselves: no PEM key header of any
|
|
# flavour survived into the tenant-readable object.
|
|
if kubectl -n "$NAMESPACE" get secret postgres-test.tenant-ca \
|
|
-o jsonpath='{.data.ca\.crt}' | base64 -d | grep -qi 'BEGIN .*PRIVATE KEY'; then
|
|
echo "projection carries PEM private key material" >&2
|
|
exit 1
|
|
fi
|
|
|
|
# The delivery path the README actually tells a tenant to use, run as
|
|
# the command the README prints. Everything above reads the raw Secret,
|
|
# which only an admin can do — it proves the projection's SHAPE and
|
|
# nothing about whether a tenant can reach it.
|
|
#
|
|
# core.cozystack.io/tenantsecrets serves only objects labelled
|
|
# tenantresource=true, and that label is the lineage webhook's verdict,
|
|
# computed from this app's ApplicationDefinition selectors. So this
|
|
# query 404s unless the whole chain held: the definition selects
|
|
# tenant-ca, the webhook admitted the projection, and the verdict came
|
|
# out positive. It is the one assertion that exercises the registry
|
|
# rather than inspecting its input.
|
|
anchor=$(kubectl -n "$NAMESPACE" get tenantsecret postgres-test.tenant-ca \
|
|
-o jsonpath='{.data.ca\.crt}' | base64 -d)
|
|
if ! echo "$anchor" | grep -q 'BEGIN CERTIFICATE'; then
|
|
echo "the trust anchor is not served through core.cozystack.io/tenantsecrets" >&2
|
|
exit 1
|
|
fi
|
|
|
|
# And the negative that gives the positive its meaning: the registry
|
|
# must NOT serve CNPG's key-bearing CA. It carries no tenant-ca label,
|
|
# so the definition does not select it and the webhook marks it
|
|
# tenantresource=false. If this ever starts resolving, the label path
|
|
# has stopped gating on the platform's verdict.
|
|
if kubectl -n "$NAMESPACE" get tenantsecret postgres-test-ca >/dev/null 2>&1; then
|
|
echo "CNPG's key-bearing CA is being served as a tenant secret" >&2
|
|
exit 1
|
|
fi
|
|
check:
|
|
($error == null): true
|
|
|
|
# The collation repair Job rebuilds an index whose collation changed library
|
|
# version. The pass is SQL run by a Job a Helm hook starts, so only a real
|
|
# server can say whether it works. A collation created with an explicit version reads as stale
|
|
# without swapping the operand image, and so does a C.<codeset> collation
|
|
# once the database records another Debian release as the one it was
|
|
# repaired for, which makes one more upgrade of the release enough to run
|
|
# the pass over both. A database created after the last run records no
|
|
# release, the state every existing cluster starts from; there a stale libc
|
|
# collation is what tells the pass that glibc moved.
|
|
- name: rebuild-index-after-collation-version-change
|
|
try:
|
|
- script:
|
|
timeout: 2m
|
|
content: |
|
|
set -eu
|
|
pod=$(kubectl -n "$NAMESPACE" get pod \
|
|
-l cnpg.io/cluster=postgres-test,cnpg.io/instanceRole=primary \
|
|
-o name | head -n1)
|
|
kubectl -n "$NAMESPACE" exec -i "$pod" -c postgres -- \
|
|
psql -U postgres -d testdb -v ON_ERROR_STOP=1 <<'EOF'
|
|
CREATE COLLATION stale_icu (provider = icu, locale = 'en', version = '0');
|
|
CREATE TABLE collation_probe (s text COLLATE stale_icu);
|
|
INSERT INTO collation_probe SELECT 'v' || g FROM generate_series(1, 1000) g;
|
|
CREATE UNIQUE INDEX collation_probe_s ON collation_probe (s);
|
|
CREATE EXTENSION IF NOT EXISTS btree_gist;
|
|
CREATE TABLE collation_probe_excl (s text COLLATE stale_icu, EXCLUDE USING gist (s WITH =));
|
|
INSERT INTO collation_probe_excl SELECT 'k' || g FROM generate_series(1, 200) g;
|
|
CREATE TABLE collation_probe_c (s text COLLATE "C.utf8" UNIQUE);
|
|
INSERT INTO collation_probe_c SELECT 'c' || g FROM generate_series(1, 1000) g;
|
|
ALTER DATABASE testdb SET cozystack.collation_release = 'pgdg11';
|
|
CREATE TABLE collation_probe_before AS
|
|
SELECT 'collation_probe_s'::regclass::oid AS index,
|
|
(SELECT relfilenode FROM pg_class WHERE oid = 'collation_probe_excl_s_excl'::regclass) AS in_place_file,
|
|
'collation_probe_c_s_key'::regclass::oid AS c_index;
|
|
CREATE DATABASE collation_probe_unrecorded;
|
|
\c collation_probe_unrecorded
|
|
CREATE COLLATION stale_libc (provider = libc, locale = 'en_US.utf8', version = '0');
|
|
CREATE TABLE collation_probe_c (s text COLLATE "C.utf8" UNIQUE);
|
|
INSERT INTO collation_probe_c SELECT 'c' || g FROM generate_series(1, 1000) g;
|
|
CREATE TABLE collation_probe_before AS SELECT 'collation_probe_c_s_key'::regclass::oid AS c_index;
|
|
EOF
|
|
check:
|
|
($error == null): true
|
|
# A repair Job left by the install has completed already; it goes
|
|
# first, so that the Job awaited below is the one this upgrade starts.
|
|
- script:
|
|
timeout: 2m
|
|
content: |
|
|
set -eu
|
|
kubectl -n "$NAMESPACE" delete job postgres-test-collation-repair --ignore-not-found --wait=true
|
|
check:
|
|
($error == null): true
|
|
# A declared user is the smallest change that makes Helm upgrade the
|
|
# release, and so run the hook, without restarting PostgreSQL.
|
|
- patch:
|
|
resource:
|
|
apiVersion: apps.cozystack.io/v1alpha1
|
|
kind: Postgres
|
|
metadata:
|
|
name: test
|
|
spec:
|
|
users:
|
|
collationprobe: {}
|
|
# 11m: above the 600s upgrade timeout cozystack-api gives this release.
|
|
# The step above that waited for this Job deleted it, so the Job found
|
|
# here is the one the upgrade created.
|
|
- assert:
|
|
timeout: 11m
|
|
resource:
|
|
apiVersion: batch/v1
|
|
kind: Job
|
|
metadata:
|
|
name: postgres-test-init-job
|
|
status:
|
|
(conditions[?type == 'Complete']):
|
|
- status: "True"
|
|
# The repair runs in a Job a post-upgrade hook starts outside the
|
|
# release, after the init Job. The label is what makes the
|
|
# WorkloadMonitor report a failed repair on the Application.
|
|
- assert:
|
|
timeout: 15m
|
|
resource:
|
|
apiVersion: batch/v1
|
|
kind: Job
|
|
metadata:
|
|
name: postgres-test-collation-repair
|
|
labels:
|
|
app.kubernetes.io/name: postgres.apps.cozystack.io
|
|
app.kubernetes.io/instance: postgres-test
|
|
workloads.cozystack.io/report-failure: "true"
|
|
status:
|
|
(conditions[?type == 'Complete']):
|
|
- status: "True"
|
|
# The next upgrade finds that Job complete on the same image and replaces
|
|
# it with a new run under the same name.
|
|
- script:
|
|
timeout: 1m
|
|
content: |
|
|
set -eu
|
|
# A failed repair must stay visible until the next upgrade replaces it.
|
|
ttl=$(kubectl -n "$NAMESPACE" get job postgres-test-collation-repair -o jsonpath='{.spec.ttlSecondsAfterFinished}')
|
|
if [ -n "$ttl" ]; then
|
|
echo "the collation repair Job has ttlSecondsAfterFinished=$ttl, so a failed repair would disappear" >&2
|
|
exit 1
|
|
fi
|
|
kubectl -n "$NAMESPACE" annotate job postgres-test-collation-repair e2e.cozystack.io/previous-run=true
|
|
check:
|
|
($error == null): true
|
|
- patch:
|
|
resource:
|
|
apiVersion: apps.cozystack.io/v1alpha1
|
|
kind: Postgres
|
|
metadata:
|
|
name: test
|
|
spec:
|
|
users:
|
|
collationprobe: {}
|
|
collationprobe2: {}
|
|
- script:
|
|
timeout: 15m
|
|
content: |
|
|
set -eu
|
|
until [ "$(kubectl -n "$NAMESPACE" get job postgres-test-collation-repair --ignore-not-found \
|
|
-o jsonpath='{.metadata.annotations.e2e\.cozystack\.io/previous-run}|{.status.conditions[?(@.type=="Complete")].status}')" = "|True" ]; do
|
|
sleep 5
|
|
done
|
|
check:
|
|
($error == null): true
|
|
- script:
|
|
timeout: 2m
|
|
content: |
|
|
set -eu
|
|
pod=$(kubectl -n "$NAMESPACE" get pod \
|
|
-l cnpg.io/cluster=postgres-test,cnpg.io/instanceRole=primary \
|
|
-o name | head -n1)
|
|
q() {
|
|
kubectl -n "$NAMESPACE" exec "$pod" -c postgres -- \
|
|
psql -U postgres -d testdb -v ON_ERROR_STOP=1 -tAc "$1"
|
|
}
|
|
refreshed=$(q "SELECT collversion = pg_collation_actual_version(oid) FROM pg_collation WHERE collname = 'stale_icu'")
|
|
if [ "$refreshed" != t ]; then
|
|
echo "the collation repair Job left the collation version stale" >&2
|
|
exit 1
|
|
fi
|
|
# REINDEX CONCURRENTLY gives the index a new OID, so an unchanged
|
|
# one means the version was refreshed over an index nobody rebuilt.
|
|
rebuilt=$(q "SELECT 'collation_probe_s'::regclass::oid <> index FROM collation_probe_before")
|
|
if [ "$rebuilt" != t ]; then
|
|
echo "the collation repair Job refreshed the collation version without rebuilding the index" >&2
|
|
exit 1
|
|
fi
|
|
q "CREATE EXTENSION IF NOT EXISTS amcheck"
|
|
q "SELECT bt_index_check('collation_probe_s', true)"
|
|
# An exclusion constraint's index is rebuilt in place: it keeps its
|
|
# OID and gets a new storage file.
|
|
rebuilt_in_place=$(q "SELECT c.relfilenode <> b.in_place_file FROM pg_class c, collation_probe_before b WHERE c.oid = 'collation_probe_excl_s_excl'::regclass")
|
|
if [ "$rebuilt_in_place" != t ]; then
|
|
echo "the collation repair Job did not rebuild the exclusion constraint's index" >&2
|
|
exit 1
|
|
fi
|
|
rebuilt_c=$(q "SELECT 'collation_probe_c_s_key'::regclass::oid <> c_index FROM collation_probe_before")
|
|
if [ "$rebuilt_c" != t ]; then
|
|
echo "the collation repair Job did not rebuild the index on a C.<codeset> collation after the Debian release changed" >&2
|
|
exit 1
|
|
fi
|
|
q "SELECT bt_index_check('collation_probe_c_s_key', true)"
|
|
release=$(q "SELECT current_setting('cozystack.collation_release', true) = substring(current_setting('server_version') from 'pgdg[0-9]+')")
|
|
if [ "$release" != t ]; then
|
|
echo "the collation repair Job did not record the Debian release it repaired the database for" >&2
|
|
exit 1
|
|
fi
|
|
qu() {
|
|
kubectl -n "$NAMESPACE" exec "$pod" -c postgres -- \
|
|
psql -U postgres -d collation_probe_unrecorded -v ON_ERROR_STOP=1 -tAc "$1"
|
|
}
|
|
rebuilt_unrecorded=$(qu "SELECT 'collation_probe_c_s_key'::regclass::oid <> c_index FROM collation_probe_before")
|
|
if [ "$rebuilt_unrecorded" != t ]; then
|
|
echo "the collation repair Job did not rebuild the index on a C.<codeset> collation in a database that recorded no release and holds a stale libc collation" >&2
|
|
exit 1
|
|
fi
|
|
qu "CREATE EXTENSION IF NOT EXISTS amcheck"
|
|
qu "SELECT bt_index_check('collation_probe_c_s_key', true)"
|
|
release=$(qu "SELECT current_setting('cozystack.collation_release', true) = substring(current_setting('server_version') from 'pgdg[0-9]+')")
|
|
if [ "$release" != t ]; then
|
|
echo "the collation repair Job did not record the Debian release it repaired the unrecorded database for" >&2
|
|
exit 1
|
|
fi
|
|
# The pass keeps its progress in a setting of the database and
|
|
# removes it once nothing is left to repair.
|
|
progress=$(q "SELECT count(*) FROM pg_db_role_setting s JOIN pg_database d ON d.oid = s.setdatabase, unnest(s.setconfig) AS c WHERE d.datname = current_database() AND c LIKE 'cozystack.collation_repair=%'")
|
|
if [ "$progress" != 0 ]; then
|
|
echo "the collation repair Job left its repair setting on a database it finished repairing" >&2
|
|
exit 1
|
|
fi
|
|
leftovers=$(q "SELECT count(*) FROM pg_index WHERE NOT indisvalid")
|
|
if [ "$leftovers" != 0 ]; then
|
|
echo "the rebuild left $leftovers invalid index(es) behind" >&2
|
|
exit 1
|
|
fi
|
|
# The Job above also completes on a retry, so a hook that failed
|
|
# first would pass unseen without this.
|
|
cd ../../..
|
|
. hack/e2e-chainsaw/_lib/remediation-guard.sh
|
|
statuses=$(kubectl -n "$NAMESPACE" get helmrelease postgres-test \
|
|
-o jsonpath="$HELMRELEASE_HISTORY_JSONPATH")
|
|
printf 'HelmRelease postgres-test history statuses:\n%s\n' "${statuses:-<empty>}"
|
|
if helmrelease_has_remediation_cycle "$statuses"; then
|
|
echo "HelmRelease postgres-test failed an action while the index was rebuilt" >&2
|
|
exit 1
|
|
fi
|
|
check:
|
|
($error == null): true
|
|
finally:
|
|
- delete:
|
|
ref:
|
|
apiVersion: batch/v1
|
|
kind: Job
|
|
name: postgres-test-init-job
|
|
- delete:
|
|
ref:
|
|
apiVersion: batch/v1
|
|
kind: Job
|
|
name: postgres-test-collation-repair
|
|
# The Postgres CR itself was applied by chainsaw and is deleted (and waited
|
|
# on) automatically during cleanup — no explicit teardown step needed.
|
|
---
|
|
# Full barman-cloud backup -> restore round-trips, driving the validated
|
|
# example scripts (examples/backups/postgres) as the harness so the test and
|
|
# the documented flow can never drift. run-all.sh runs Bucket -> source
|
|
# Postgres + sentinel row -> CNPG strategy + BackupClass -> ad-hoc BackupJob
|
|
# (waits Succeeded) -> empty target Postgres + to-copy RestoreJob (waits
|
|
# Succeeded, asserts the sentinel round-tripped through S3) -> a point-in-time
|
|
# restore between two marker writes (step 45, asserts the pre-marker survived
|
|
# and the post-marker did not) -> a negative unreachable-target restore
|
|
# (step 46, asserts it terminates Failed with a message attributing it to the PITR
|
|
# target rather than hanging or falsely succeeding; the reason-classification
|
|
# itself is unit-tested, being best-effort against a still-archiving source). The
|
|
# in-cluster witness that a barman-cloud
|
|
# plugin backup is taken, restorable, point-in-time-recoverable, and that a
|
|
# bad target is rejected quickly.
|
|
#
|
|
# Runs in tenant-root, not the default tenant-test: the S3 client here is the
|
|
# barman-cloud sidecar INSIDE the Postgres Pod, and the e2e tenant is created
|
|
# isolated (hack/e2e-install-cozystack.bats) — its Cilium egress allowlist
|
|
# blocks a tenant-test Pod from reaching tenant-root's seaweedfs, while a
|
|
# tenant-root Pod reaches it over same-tenant egress. The harness targets the
|
|
# in-cluster endpoint (S3_ENDPOINT below) instead of the BucketInfo external
|
|
# ingress URL, which in CI is an unroutable placeholder, and trusts its
|
|
# self-signed cert by copying the seaweedfs CA secret (seaweedfs-ca-cert,
|
|
# auto-discovered from the cert-manager Certificate) into the per-app
|
|
# endpointCA Secret. (The bucket suite's mc checks lean on the same
|
|
# tenant-root seaweedfs, just from the test runner via port-forward.)
|
|
apiVersion: chainsaw.kyverno.io/v1alpha1
|
|
kind: Test
|
|
metadata:
|
|
name: postgres-2-backup-roundtrip
|
|
spec:
|
|
namespace: tenant-root
|
|
skipDelete: true
|
|
catch:
|
|
- events: {}
|
|
- describe:
|
|
apiVersion: helm.toolkit.fluxcd.io/v2
|
|
kind: HelmRelease
|
|
name: postgres-pg-src
|
|
- describe:
|
|
apiVersion: postgresql.cnpg.io/v1
|
|
kind: Cluster
|
|
name: postgres-pg-src
|
|
- describe:
|
|
apiVersion: barmancloud.cnpg.io/v1
|
|
kind: ObjectStore
|
|
- describe:
|
|
apiVersion: backups.cozystack.io/v1alpha1
|
|
kind: BackupJob
|
|
- describe:
|
|
apiVersion: backups.cozystack.io/v1alpha1
|
|
kind: RestoreJob
|
|
# The barman-cloud backup/WAL work runs in the cnpg Cluster Pods' sidecar; a
|
|
# failed upload or TLS handshake leaves its error only in that Pod's log.
|
|
- podLogs:
|
|
selector: cnpg.io/cluster=postgres-pg-src
|
|
tail: 200
|
|
steps:
|
|
- name: run
|
|
try:
|
|
# The 76m budget is the whole documented flow: bucket provisioning, a
|
|
# 2-replica source Postgres, the plugin base backup to S3, a second backup
|
|
# held pending on the fenced Cluster until the fence is lifted (step 26,
|
|
# which waits for the Cluster to come back healthy), an empty target
|
|
# app, and THREE sequential purge + re-bootstrap restores against it - the
|
|
# latest-point to-copy restore, the point-in-time restore (step 45), and
|
|
# the negative unreachable-target restore (step 46, which sets a short
|
|
# restoreTimeoutSeconds and must terminate Failed at that deadline, attributed
|
|
# to the PITR target), and the in-place restore (step 50, the
|
|
# regression guard for the archive-vs-recovery serverName collision)
|
|
# (convention 6: justified in-line). The old 25m budget predated the PITR
|
|
# phases; four restores plus the negative phase need the larger window,
|
|
# and the 660s bucket and Postgres HR waits in run-all.sh add 16m to it.
|
|
# run-all.sh fails fast on terminal BackupJob/RestoreJob phases and stalled
|
|
# HelmReleases rather than polling out the budget.
|
|
- script:
|
|
timeout: 76m
|
|
content: |
|
|
set -eu
|
|
cd ../../..
|
|
[ -x examples/backups/postgres/run-all.sh ] || { echo "postgres backup example scripts not found at examples/backups/postgres" >&2; exit 1; }
|
|
COZY_E2E_BACKUP_PREFLIGHT=1 NAMESPACE="$NAMESPACE" S3_ENDPOINT="https://seaweedfs-s3.tenant-root:8333" \
|
|
examples/backups/postgres/run-all.sh
|
|
check:
|
|
($error == null): true
|
|
finally:
|
|
# Resumes the driver-suspended HelmReleases before deleting the RestoreJob
|
|
# so the apps are not stranded, then removes every resource the harness
|
|
# created (chainsaw did not apply them, so they are not part of automatic
|
|
# cleanup).
|
|
- description: backup-flow cleanup
|
|
script:
|
|
timeout: 8m
|
|
content: |
|
|
set -eu
|
|
cd ../../..
|
|
NAMESPACE="$NAMESPACE" examples/backups/postgres/cleanup.sh
|
|
---
|
|
# A system database that a version before the refusal took over is handed back
|
|
# by the next init-job run, and only what this chart marked changes hands.
|
|
#
|
|
# The helm-unittest and bats suites check the rendered SQL against a fake psql;
|
|
# only a real PostgreSQL can say that the predicates select what they claim. The
|
|
# state an older version left is rebuilt by hand as the superuser, since the
|
|
# chart now refuses to produce it:
|
|
# * postgres is commented as managed and owned by a postgres_admin role that
|
|
# carries the cozystack:managed mark, as the chart left it: it must come back
|
|
# to the superuser, and the role must be dropped;
|
|
# * template1 is commented as managed, but its template1_admin carries only the
|
|
# role comment, which a CREATEROLE holder can forge, and not the mark: the
|
|
# comment must be cleared and everything that role owns or was granted must
|
|
# stay as it is, in template1 and in a database cloned from it.
|
|
apiVersion: chainsaw.kyverno.io/v1alpha1
|
|
kind: Test
|
|
metadata:
|
|
name: postgres-3-system-databases
|
|
spec:
|
|
catch:
|
|
- events: {}
|
|
- describe:
|
|
apiVersion: helm.toolkit.fluxcd.io/v2
|
|
kind: HelmRelease
|
|
name: postgres-sysdb
|
|
- podLogs:
|
|
selector: job-name=postgres-sysdb-init-job
|
|
tail: 200
|
|
steps:
|
|
- name: create-postgres
|
|
try:
|
|
- apply:
|
|
file: postgres-sysdb.yaml
|
|
# 11m: above the 600s install timeout cozystack-api gives this release;
|
|
# see "Sizing an HR-Ready budget" in docs/agents/e2e-testing.md.
|
|
- assert:
|
|
timeout: 11m
|
|
resource:
|
|
apiVersion: helm.toolkit.fluxcd.io/v2
|
|
kind: HelmRelease
|
|
metadata:
|
|
name: postgres-sysdb
|
|
status:
|
|
(conditions[?type == 'Ready']):
|
|
- status: "True"
|
|
- assert:
|
|
timeout: 2m
|
|
resource:
|
|
apiVersion: batch/v1
|
|
kind: Job
|
|
metadata:
|
|
name: postgres-sysdb-init-job
|
|
status:
|
|
(conditions[?type == 'Complete']):
|
|
- status: "True"
|
|
|
|
- name: rebuild-taken-over-system-databases
|
|
try:
|
|
- script:
|
|
timeout: 3m
|
|
content: |
|
|
set -eu
|
|
pod=$(kubectl -n "$NAMESPACE" get pod \
|
|
-l cnpg.io/cluster=postgres-sysdb,cnpg.io/instanceRole=primary -o name | head -n1)
|
|
[ -n "$pod" ] || { echo "no primary pod for postgres-sysdb" >&2; exit 1; }
|
|
sql() { kubectl -n "$NAMESPACE" exec -i "$pod" -c postgres -- psql -v ON_ERROR_STOP=1 -U postgres -d "$1"; }
|
|
sql postgres <<'SQL'
|
|
CREATE ROLE postgres_admin NOLOGIN;
|
|
COMMENT ON ROLE postgres_admin IS 'role managed by helm';
|
|
GRANT "cozystack:managed" TO postgres_admin WITH INHERIT FALSE, SET FALSE;
|
|
COMMENT ON DATABASE postgres IS 'database managed by helm';
|
|
ALTER DATABASE postgres OWNER TO postgres_admin;
|
|
CREATE ROLE template1_admin NOLOGIN;
|
|
COMMENT ON ROLE template1_admin IS 'role managed by helm';
|
|
CREATE ROLE template1_readonly NOLOGIN;
|
|
COMMENT ON DATABASE template1 IS 'database managed by helm';
|
|
ALTER DATABASE template1 OWNER TO template1_admin;
|
|
SQL
|
|
sql template1 <<'SQL'
|
|
ALTER SCHEMA public OWNER TO template1_admin;
|
|
CREATE TABLE public.kept (id int);
|
|
ALTER TABLE public.kept OWNER TO template1_admin;
|
|
GRANT SELECT ON public.kept TO template1_readonly;
|
|
SQL
|
|
sql postgres <<'SQL'
|
|
CREATE DATABASE sysdb_clone TEMPLATE template1;
|
|
SQL
|
|
# The next run must be a new Job: remove the completed one so the
|
|
# assert below cannot match it.
|
|
kubectl -n "$NAMESPACE" delete job postgres-sysdb-init-job --wait=true
|
|
# Declaring a user is enough for an upgrade, and runs the init-job.
|
|
kubectl -n "$NAMESPACE" patch postgres.apps.cozystack.io sysdb --type merge \
|
|
-p '{"spec":{"users":{"sysdbuser":{},"sysdbprobe":{}}}}'
|
|
check:
|
|
($error == null): true
|
|
- assert:
|
|
timeout: 11m
|
|
resource:
|
|
apiVersion: batch/v1
|
|
kind: Job
|
|
metadata:
|
|
name: postgres-sysdb-init-job
|
|
status:
|
|
(conditions[?type == 'Complete']):
|
|
- status: "True"
|
|
|
|
- name: verify-release
|
|
try:
|
|
- script:
|
|
timeout: 2m
|
|
content: |
|
|
set -eu
|
|
pod=$(kubectl -n "$NAMESPACE" get pod \
|
|
-l cnpg.io/cluster=postgres-sysdb,cnpg.io/instanceRole=primary -o name | head -n1)
|
|
q() { kubectl -n "$NAMESPACE" exec "$pod" -c postgres -- psql -v ON_ERROR_STOP=1 -U postgres -tA -d "$1" -c "$2"; }
|
|
fail=0
|
|
expect() {
|
|
got=$(q "$1" "$3")
|
|
if [ "$got" != "$4" ]; then
|
|
echo "FAIL: $2: got '$got', want '$4'" >&2
|
|
fail=1
|
|
fi
|
|
}
|
|
comment="SELECT coalesce(shobj_description(oid, 'pg_database'), '<none>') FROM pg_database WHERE datname = "
|
|
owner="SELECT pg_get_userbyid(datdba) FROM pg_database WHERE datname = "
|
|
expect postgres "postgres comment cleared" "$comment'postgres'" '<none>'
|
|
expect postgres "postgres back to the superuser" "$owner'postgres'" postgres
|
|
expect postgres "marked postgres_admin dropped" "SELECT count(*) FROM pg_roles WHERE rolname = 'postgres_admin'" 0
|
|
expect postgres "template1 comment cleared" "$comment'template1'" '<none>'
|
|
expect postgres "unmarked template1_admin still exists" "SELECT count(*) FROM pg_roles WHERE rolname = 'template1_admin'" 1
|
|
expect postgres "template1 still owned by the unmarked role" "$owner'template1'" template1_admin
|
|
for db in template1 sysdb_clone; do
|
|
expect "$db" "$db public still owned by the unmarked role" \
|
|
"SELECT pg_get_userbyid(nspowner) FROM pg_namespace WHERE nspname = 'public'" template1_admin
|
|
expect "$db" "$db kept table still owned by the unmarked role" \
|
|
"SELECT tableowner FROM pg_tables WHERE schemaname = 'public' AND tablename = 'kept'" template1_admin
|
|
expect "$db" "$db grant to the unmarked readonly role kept" \
|
|
"SELECT has_table_privilege('template1_readonly', 'public.kept', 'SELECT')" t
|
|
done
|
|
exit "$fail"
|
|
check:
|
|
($error == null): true
|
|
# The Postgres CR was applied by chainsaw; deleting it removes the whole
|
|
# cluster, the databases and roles built above included.
|