feat(platform): migrate Postgres accounts to minted credentials

Migration 64 converts the existing Postgres releases. It first applies
the CredentialTemplate CRD baked into its image, owned by the
cozystack-controller release so that release's upgrade adopts it: on a
live upgrade the tenant releases switched to the converted chart about
17 minutes before cozystack-controller upgraded, and every render in
between failed on the unknown kind. It then runs credentials-migrate
seed, which writes the account Secrets from <release>-credentials so
clients keep logging in at every point of the upgrade. A release that
grants createRole is left out and keeps its previous chart.

The finish half runs from a Job the migration creates, not from the
platform chart: a chart-rendered Job has a fixed name and an image that
changes every release, so the next platform upgrade cannot patch its
immutable pod template, and helm-controller would wait on a Job that
runs up to 30 minutes and exits non-zero while any release is left out.
The Job runs the image the hook runs as, read from its own pod, under a
least-privilege ClusterRole rather than cluster-admin, and its
ServiceAccount is owned by the Job so the garbage collector removes it.
The identity carries the migration number like the Job, so a later
conversion migration cannot delete the ServiceAccount a still-running
earlier Job uses.

The CredentialsMigrationIncomplete alert keys on the incomplete label of
the state ConfigMap through kube-state-metrics, which allowlists only
that one ConfigMap label, so a release whose plaintext was never retired
stays visible after the Job's TTL. The bats suite pins the CRD apply,
seed, image read, Job apply, ownership and stamp steps as fail-closed;
its fake kubectl counts the Job's name inside the Job document only.

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 c9653cbb79
commit d7144cda9e
8 files changed
+595 -4

No files matched your search

+220
View File
@@ -0,0 +1,220 @@
#!/usr/bin/env bats
# -----------------------------------------------------------------------------
# Unit tests for platform migration 64 --> 65 (convert Postgres accounts to
# platform-minted credentials, first part).
#
# The migration seeds the account Secrets of every Postgres release, then
# creates the cozystack-credentials-migration-64 finish Job directly (rather
# than rendering it from the platform chart) so a changing migrations image
# never collides with an immutable pod template and helm-controller waits on no
# long-running Job. See packages/core/platform/images/migrations/migrations/64.
#
# FAIL CLOSED is pinned for each path: a failed seed, a pod whose image cannot
# be read, and a failed apply of the Job must stop the migration before it
# stamps the version, because migrations never re-run.
#
# The harness (docker, the migrations image base, fake kubectl and
# credentials-migrate on PATH) is the one hack/migration-58-http-cache-freeze.bats
# describes; see there for why each piece is load-bearing.
#
# Run with: hack/cozytest.sh hack/migration-64-postgres-credentials.bats
# -----------------------------------------------------------------------------
load test_helper
FAKEBIN="$PWD/hack/testdata/migration-64-postgres-credentials"
MIG_DIR="$PWD/packages/core/platform/images/migrations/migrations"
ALPINE=$(sed -n 's/^FROM \(alpine:[^ ]*\).*$/\1/p' \
"$PWD/packages/core/platform/images/migrations/Dockerfile" | head -1)
TESTIMG="cozystack-migration64-test:$(printf '%s' "$ALPINE" | sed 's/[^a-zA-Z0-9]/-/g')"
WORKROOT="${TMPDIR:-/tmp}/cozy-migration-64-$$"
IMAGE=registry.example.org/cozystack/cozystack:v1.7.0
cozy_cleanup() {
rm -rf "$WORKROOT"
return 0
}
cmdlog_line() {
grep -nE -- "$1" "$FAKE_CMDLOG" | head -1 | cut -d: -f1
}
run_migration() {
_run_migration_rc=0
docker run --rm --network none \
--user "$(id -u):$(id -g)" \
-v "$MIG_DIR:/migrations:ro" \
-v "$FAKEBIN:/fakebin:ro" \
-v "$WORK:/work" \
-e PATH=/fakebin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \
-e FAKE_CMDLOG=/work/cmdlog \
-e NAMESPACE="${NAMESPACE-}" \
-e FAKE_IMAGE="${FAKE_IMAGE-}" \
-e FAKE_IMAGE_EMPTY="${FAKE_IMAGE_EMPTY-}" \
-e FAKE_GETPOD_FAIL="${FAKE_GETPOD_FAIL-}" \
-e FAKE_CRD_FAIL="${FAKE_CRD_FAIL-}" \
-e CREDENTIAL_CRD_FILE=/work/credentialtemplates.yaml \
-e FAKE_APPLY_FAIL="${FAKE_APPLY_FAIL-}" \
-e FAKE_SEED_FAIL="${FAKE_SEED_FAIL-}" \
-e FAKE_GETJOB_FAIL="${FAKE_GETJOB_FAIL-}" \
-e FAKE_JOBUID_EMPTY="${FAKE_JOBUID_EMPTY-}" \
-e FAKE_PATCH_FAIL="${FAKE_PATCH_FAIL-}" \
"$TESTIMG" "/migrations/$1" || _run_migration_rc=$?
return "$_run_migration_rc"
}
prep() {
docker info >/dev/null 2>&1 || {
echo "docker is required: these tests run migration 64 inside a build of" >&2
echo "$ALPINE, the migrations image's base." >&2
return 1
}
docker build -q -t "$TESTIMG" - >/dev/null <<DOCKERFILE
FROM $ALPINE
DOCKERFILE
chmod +x "$FAKEBIN/kubectl" "$FAKEBIN/credentials-migrate"
mkdir -p "$WORKROOT"
WORK=$(mktemp -d "$WORKROOT/XXXXXX")
export FAKE_CMDLOG="$WORK/cmdlog"
: > "$FAKE_CMDLOG"
export NAMESPACE=cozy-system
export FAKE_IMAGE="$IMAGE"
unset FAKE_CRD_FAIL FAKE_IMAGE_EMPTY FAKE_GETPOD_FAIL FAKE_APPLY_FAIL FAKE_SEED_FAIL FAKE_GETJOB_FAIL FAKE_JOBUID_EMPTY FAKE_PATCH_FAIL || true
return 0
}
@test "it seeds, creates the finish Job on its own image, and stamps" {
prep
rc=0
run_migration 64 >"$WORK/out" 2>&1 || rc=$?
cat "$WORK/out"; cat "$FAKE_CMDLOG"
[ "$rc" -eq 0 ]
# The seed runs for migration 64.
grep -qE "^CREDMIGRATE seed --migration 64 " "$FAKE_CMDLOG"
# The CRD is applied, owned by the cozystack-controller release, and
# established before the seed, since the converted chart renders it.
_crd=$(cmdlog_line "^CRD established$")
_seed=$(cmdlog_line "^CREDMIGRATE seed")
[ -n "$_crd" ] && [ "$_crd" -lt "$_seed" ]
grep -qE "^CRD label$" "$FAKE_CMDLOG"
grep -qE "^CRD annotate$" "$FAKE_CMDLOG"
# The finish Job carries its least-privilege ClusterRole (never cluster-admin),
# ServiceAccount and binding, the migration number, and the image this hook
# runs as, read from its own pod rather than values.
grep -qE "^APPLY-FINISH role=1 sa=1 crb=1 admin=0 jobname=1 migration=1 image=1 serviceaccount=1$" "$FAKE_CMDLOG"
# The Job owns its ServiceAccount, so the cluster-admin identity is collected
# with the Job and does not stand indefinitely.
grep -qE "^PATCH-SA-OWNER owner=1$" "$FAKE_CMDLOG"
# A stale Job from an earlier run is deleted before the apply, so a rerun on a
# newer image does not fault on the immutable pod template; the ownership is
# set after the Job exists; and only then, after the Job is created and owned,
# the version is stamped. A stamp before the Job would mark the migration done
# with no finisher.
_del=$(cmdlog_line "^DELETE-JOB$")
_apply=$(cmdlog_line "^APPLY-FINISH ")
_own=$(cmdlog_line "^PATCH-SA-OWNER ")
_stamp=$(cmdlog_line "^STAMP 65$")
[ -n "$_del" ] && [ "$_del" -lt "$_apply" ]
[ -n "$_own" ] && [ "$_apply" -lt "$_own" ]
[ -n "$_stamp" ] && [ "$_own" -lt "$_stamp" ]
rm -rf "$WORK"
}
@test "a pod whose image cannot be read, as a failed get, stops before the Job and the stamp" {
prep
export FAKE_GETPOD_FAIL="the server could not find the requested resource"
rc=0
run_migration 64 >"$WORK/out" 2>&1 || rc=$?
cat "$WORK/out"; cat "$FAKE_CMDLOG"
[ "$rc" -ne 0 ]
grep -qE "^CREDMIGRATE seed --migration 64 " "$FAKE_CMDLOG"
if grep -qE "^APPLY-FINISH" "$FAKE_CMDLOG"; then echo "created the Job after a failed image read" >&2; return 1; fi
if grep -qF "STAMP" "$FAKE_CMDLOG"; then echo "stamped after a failed image read" >&2; return 1; fi
rm -rf "$WORK"
}
@test "a failed seed stops before the Job and before stamping" {
prep
export FAKE_SEED_FAIL="apiserver is unavailable"
rc=0
run_migration 64 >"$WORK/out" 2>&1 || rc=$?
cat "$WORK/out"; cat "$FAKE_CMDLOG"
[ "$rc" -ne 0 ]
if grep -qE "^APPLY-FINISH" "$FAKE_CMDLOG"; then echo "created the Job after a failed seed" >&2; return 1; fi
if grep -qF "STAMP" "$FAKE_CMDLOG"; then echo "stamped after a failed seed" >&2; return 1; fi
rm -rf "$WORK"
}
@test "a pod whose image cannot be read stops after the seed, before the Job and the stamp" {
prep
export FAKE_IMAGE_EMPTY=1
rc=0
run_migration 64 >"$WORK/out" 2>&1 || rc=$?
cat "$WORK/out"; cat "$FAKE_CMDLOG"
[ "$rc" -ne 0 ]
grep -qE "^CREDMIGRATE seed --migration 64 " "$FAKE_CMDLOG"
if grep -qE "^APPLY-FINISH" "$FAKE_CMDLOG"; then echo "created the Job with no image to run" >&2; return 1; fi
if grep -qF "STAMP" "$FAKE_CMDLOG"; then echo "stamped with no image to run" >&2; return 1; fi
rm -rf "$WORK"
}
@test "a failed apply of the Job stops before stamping" {
prep
export FAKE_APPLY_FAIL="admission webhook denied the request"
rc=0
run_migration 64 >"$WORK/out" 2>&1 || rc=$?
cat "$WORK/out"; cat "$FAKE_CMDLOG"
[ "$rc" -ne 0 ]
if grep -qF "STAMP" "$FAKE_CMDLOG"; then echo "stamped after the Job failed to apply" >&2; return 1; fi
rm -rf "$WORK"
}
@test "a Job whose uid cannot be read stops before owning the SA and before stamping" {
prep
export FAKE_GETJOB_FAIL="the server was unable to return a response"
rc=0
run_migration 64 >"$WORK/out" 2>&1 || rc=$?
cat "$WORK/out"; cat "$FAKE_CMDLOG"
[ "$rc" -ne 0 ]
if grep -qE "^PATCH-SA-OWNER" "$FAKE_CMDLOG"; then echo "patched ownership with no uid" >&2; return 1; fi
if grep -qF "STAMP" "$FAKE_CMDLOG"; then echo "stamped without owning the SA" >&2; return 1; fi
rm -rf "$WORK"
}
@test "an empty Job uid stops before owning the SA and before stamping" {
prep
export FAKE_JOBUID_EMPTY=1
rc=0
run_migration 64 >"$WORK/out" 2>&1 || rc=$?
cat "$WORK/out"; cat "$FAKE_CMDLOG"
[ "$rc" -ne 0 ]
if grep -qE "^PATCH-SA-OWNER" "$FAKE_CMDLOG"; then echo "patched ownership with an empty uid" >&2; return 1; fi
if grep -qF "STAMP" "$FAKE_CMDLOG"; then echo "stamped with an empty uid" >&2; return 1; fi
rm -rf "$WORK"
}
@test "a failed ownership patch stops before stamping" {
prep
export FAKE_PATCH_FAIL="serviceaccounts \"cozystack-credentials-migration-64\" not found"
rc=0
run_migration 64 >"$WORK/out" 2>&1 || rc=$?
cat "$WORK/out"; cat "$FAKE_CMDLOG"
[ "$rc" -ne 0 ]
if grep -qF "STAMP" "$FAKE_CMDLOG"; then echo "stamped after the ownership patch failed" >&2; return 1; fi
rm -rf "$WORK"
}
@test "a CRD that fails to apply stops before the seed and the stamp" {
prep
export FAKE_CRD_FAIL=1
rc=0
run_migration 64 >"$WORK/out" 2>&1 || rc=$?
cat "$WORK/out"; cat "$FAKE_CMDLOG"
[ "$rc" -ne 0 ]
if grep -qE "^CREDMIGRATE seed" "$FAKE_CMDLOG"; then echo "seeded without the CRD" >&2; return 1; fi
if grep -qF "STAMP" "$FAKE_CMDLOG"; then echo "stamped without the CRD" >&2; return 1; fi
}
+22
View File
@@ -0,0 +1,22 @@
#!/bin/sh
# Fake credentials-migrate for hack/migration-64-postgres-credentials.bats.
# Migration 64 runs `credentials-migrate seed` in the hook; the real binary is
# exercised by cmd/credentials-migrate's Go tests, so this fake only records the
# call and fails on demand to pin the hook's fail-closed behaviour.
#
# FAKE_CMDLOG file to append a one-line record of each call to
# FAKE_SEED_FAIL non-empty => `seed` exits 1 with this stderr
set -u
[ -n "${FAKE_CMDLOG:-}" ] && printf 'CREDMIGRATE %s\n' "$*" >> "$FAKE_CMDLOG"
case "${1:-}" in
seed)
if [ -n "${FAKE_SEED_FAIL:-}" ]; then
printf '%s\n' "$FAKE_SEED_FAIL" >&2
exit 1
fi
exit 0
;;
esac
exit 0
+127
View File
@@ -0,0 +1,127 @@
#!/bin/sh
# Fake kubectl for hack/migration-64-postgres-credentials.bats, modelled on
# hack/testdata/migration-58-http-cache/kubectl. It serves only the calls
# migration 64 and lib/cozystack-version.sh make, and logs each one to
# $FAKE_CMDLOG.
#
# Migration 64 reads its own pod's image, applies the finish Job (with its
# ServiceAccount and ClusterRoleBinding), and stamps the version. The Job
# manifest and the version stamp both arrive as `apply --filename -`, so this
# fake reads stdin and branches on the manifest's kind.
#
# FAKE_CMDLOG file to append a one-line record of each call to
# FAKE_IMAGE image the `get pod` call returns (default a test ref)
# FAKE_IMAGE_EMPTY non-empty => `get pod` returns an empty image
# FAKE_GETPOD_FAIL non-empty => `get pod` exits 1 with this stderr
# FAKE_APPLY_FAIL non-empty => applying the Job exits 1 with this stderr
set -u
log() { [ -n "${FAKE_CMDLOG:-}" ] && printf '%s\n' "$*" >> "$FAKE_CMDLOG"; }
log "KUBECTL $*"
args="$*"
IMAGE="${FAKE_IMAGE:-registry.example.org/cozystack/cozystack:v1.7.0}"
case "$args" in
*"apply --server-side --force-conflicts --filename "*credentialtemplates*)
log "CRD apply"
[ -n "${FAKE_CRD_FAIL-}" ] && exit 1
exit 0
;;
*"label crd credentialtemplates.cozystack.io app.kubernetes.io/managed-by=Helm"*)
log "CRD label"
exit 0
;;
*"annotate crd credentialtemplates.cozystack.io"*"meta.helm.sh/release-name=cozystack-controller"*)
log "CRD annotate"
exit 0
;;
*"wait --for=condition=established crd/credentialtemplates.cozystack.io"*)
log "CRD established"
exit 0
;;
*"get pod"*jsonpath*)
if [ -n "${FAKE_GETPOD_FAIL:-}" ]; then
printf '%s\n' "$FAKE_GETPOD_FAIL" >&2
exit 1
fi
[ -n "${FAKE_IMAGE_EMPTY:-}" ] || printf '%s' "$IMAGE"
exit 0
;;
*"delete job cozystack-credentials-migration-64"*)
# The hook deletes a Job left by an earlier run before recreating it.
log "DELETE-JOB"
exit 0
;;
*"delete serviceaccount cozystack-credentials-migration-64"*)
# The hook deletes a ServiceAccount left owned by the Job it just deleted,
# so the apply recreates a fresh, owner-less one.
log "DELETE-SA"
exit 0
;;
*"get job cozystack-credentials-migration-64"*jsonpath*)
# The hook reads the Job's uid to own its ServiceAccount.
if [ -n "${FAKE_GETJOB_FAIL:-}" ]; then
printf '%s\n' "$FAKE_GETJOB_FAIL" >&2
exit 1
fi
[ -n "${FAKE_JOBUID_EMPTY:-}" ] || printf '%s' "11111111-2222-3333-4444-555555555555"
exit 0
;;
*"patch serviceaccount cozystack-credentials-migration-64"*)
# The ownerReference tying the ServiceAccount to the Job.
if [ -n "${FAKE_PATCH_FAIL:-}" ]; then
printf '%s\n' "$FAKE_PATCH_FAIL" >&2
exit 1
fi
owner=$(printf '%s' "$args" | grep -c 'cozystack-credentials-migration-64')
log "PATCH-SA-OWNER owner=$owner"
exit 0
;;
*"apply --filename -"*)
manifest=$(cat)
case "$manifest" in
*"kind: ConfigMap"*)
v=$(printf '%s\n' "$manifest" | sed -n 's/^ version: "\{0,1\}\([0-9]\{1,\}\)"\{0,1\}$/\1/p' | head -1)
log "STAMP ${v:-unknown}"
exit 0
;;
*"kind: Job"*)
if [ -n "${FAKE_APPLY_FAIL:-}" ]; then
printf '%s\n' "$FAKE_APPLY_FAIL" >&2
exit 1
fi
# Record the fields the Job must carry, so a copy that drops the
# ServiceAccount, names the wrong migration, or renders the wrong image
# is caught.
role=$(printf '%s\n' "$manifest" | grep -c '^kind: ClusterRole$')
sa=$(printf '%s\n' "$manifest" | grep -c '^kind: ServiceAccount$')
crb=$(printf '%s\n' "$manifest" | grep -c '^kind: ClusterRoleBinding$')
# The binding must grant the least-privilege role, never cluster-admin.
admin=$(printf '%s\n' "$manifest" | grep -c 'cluster-admin')
# Count the name only inside the Job document: the ClusterRole, the
# ServiceAccount and the binding share it.
jobname=$(printf '%s\n' "$manifest" | sed -n '/^kind: Job$/,/^spec:$/p' | grep -c '^ name: cozystack-credentials-migration-64$')
mig=$(printf '%s\n' "$manifest" | grep -c -- '--migration=64')
img=$(printf '%s\n' "$manifest" | grep -c "^ image: ${IMAGE}$")
sacc=$(printf '%s\n' "$manifest" | grep -c '^ serviceAccountName: cozystack-credentials-migration-64$')
log "APPLY-FINISH role=$role sa=$sa crb=$crb admin=$admin jobname=$jobname migration=$mig image=$img serviceaccount=$sacc"
exit 0
;;
*)
log "APPLY-UNKNOWN"
printf 'fake kubectl: unmodelled apply\n' >&2
exit 1
;;
esac
;;
esac
log "UNHANDLED $args"
printf 'fake kubectl: unmodelled call: %s\n' "$args" >&2
exit 1
+190
View File
@@ -0,0 +1,190 @@
#!/bin/sh
# Migration 64 --> 65
# Convert PostgreSQL accounts to platform-minted credentials, first part.
#
# The converted postgres chart renders a CredentialTemplate per user, and
# each managed role reads its verifier from the template's account Secret,
# which cozystack-controller seeds with a random password only on a release
# marked for seeding. This hook runs before any component chart changes
# version and writes those Secrets, unowned, for every existing Postgres
# release from the passwords in <release>-credentials, so clients keep
# logging in at every point of the upgrade; the controller adopts them once
# the templates exist. A release whose every account got its Secret is
# marked for seeding, so users added later are seeded too.
#
# The second part is the cozystack-credentials-migration-64 Job, which waits
# per release for its chart to switch, then strips the plaintext and retires
# the source Secret. This hook creates that Job directly rather than rendering
# it from the platform chart: a chart-rendered Job has a fixed name and an
# image that changes every release, so the next platform upgrade cannot patch
# its immutable pod template, and helm-controller would wait on a Job that runs
# for up to 30 minutes and exits non-zero while any release is left out. A Job
# created here runs outside the platform HelmRelease, so it holds up no
# upgrade. It runs the image this hook runs as, read from its own pod. The Job
# is deleted and recreated rather than patched, so a hook that reruns on a
# newer image does not fault on the immutable pod template.
#
# The Job's ServiceAccount is bound to a least-privilege ClusterRole, not
# cluster-admin: finish needs only CRUD on Secrets, get/list/patch on
# HelmReleases, create on Events, and its state ConfigMap (pods/exec, which a
# later wave's MariaDB rotation needs, is not granted here). The ServiceAccount
# is owned by the Job, so the garbage collector removes it whenever the Job is
# (its TTL, a rerun, or by hand), on the success and the failure path alike, so
# no standing identity outlives the Job. A ClusterRoleBinding cannot be owned by
# a namespaced Job, so the binding is left; once the ServiceAccount is gone it
# grants to no subject that exists. On a conversion a stuck release leaves
# permanently failed, an operator clearing that release should delete the
# ClusterRoleBinding and ClusterRole by hand. While any release is left out,
# credentials-migrate labels its state ConfigMap credentials.cozystack.io/incomplete=true,
# which the CredentialsMigrationIncomplete alert fires on: the ConfigMap outlives
# the Job, so a release whose plaintext was never retired is seen until the
# conversion is finished, not only for the Job's TTL. To rerun it by hand, delete
# the Job and re-apply the manifest below.
#
# Fail-closed: migrations never re-run, so an error here stops the upgrade
# rather than stamping the version past a release that was not recorded.
set -euo pipefail
# shellcheck source=lib/cozystack-version.sh
. "$(dirname "$0")/lib/cozystack-version.sh"
NAMESPACE="${NAMESPACE:-cozy-system}"
# The converted postgres chart renders CredentialTemplates, whose CRD ships
# with cozystack-controller. That release can upgrade minutes after the tenant
# releases switch charts, and every render in between fails on the unknown
# kind, so apply the CRD baked into this image first, owned by the
# cozystack-controller release as its later upgrade expects to find it.
CRD_FILE="${CREDENTIAL_CRD_FILE:-/credential-crds/cozystack.io_credentialtemplates.yaml}"
kubectl apply --server-side --force-conflicts --filename "$CRD_FILE"
kubectl label crd credentialtemplates.cozystack.io app.kubernetes.io/managed-by=Helm --overwrite
kubectl annotate crd credentialtemplates.cozystack.io \
meta.helm.sh/release-name=cozystack-controller \
meta.helm.sh/release-namespace=cozy-system --overwrite
kubectl wait --for=condition=established crd/credentialtemplates.cozystack.io --timeout=60s
credentials-migrate seed \
--migration 64 \
--kind Postgres \
--format scram-sha-256 \
--accounts-path users \
--refuse-flag createRole \
--label 'cnpg.io/reload=true'
# The finish Job runs the same image as this hook, so a release and its
# conversion share the credentials-migrate build. Read it from this pod's own
# container by name rather than render it from values, which the hook does not
# carry, and rather than by position, which a webhook-injected container shifts.
image=$(kubectl get pod "$(hostname)" \
--namespace "$NAMESPACE" \
--output 'jsonpath={.spec.containers[?(@.name=="migration")].image}')
if [ -z "$image" ]; then
echo "cannot read this pod's image to run the finish Job" >&2
exit 1
fi
# Delete any Job left by an earlier run of this hook: its pod template is
# immutable, so a rerun on a newer image would fault on apply. finish recovers
# its progress from the state ConfigMap, so recreating the Job loses nothing.
# Delete the ServiceAccount with it: an earlier run may have left it owned by
# the Job just deleted, and the apply below does not touch ownerReferences, so
# without this the garbage collector could remove the re-applied ServiceAccount
# out from under the ownerReference patch. A fresh, owner-less ServiceAccount is
# never collected before the patch names the new Job.
kubectl delete job cozystack-credentials-migration-64 \
--namespace "$NAMESPACE" \
--ignore-not-found
kubectl delete serviceaccount cozystack-credentials-migration-64 \
--namespace "$NAMESPACE" \
--ignore-not-found
kubectl apply --filename - <<YAML
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
name: cozystack-credentials-migration-64
rules:
- apiGroups: [""]
resources: ["secrets"]
verbs: ["get", "create", "patch", "delete"]
- apiGroups: [""]
resources: ["configmaps"]
verbs: ["get", "create", "update"]
- apiGroups: [""]
resources: ["events"]
verbs: ["create"]
- apiGroups: ["helm.toolkit.fluxcd.io"]
resources: ["helmreleases"]
verbs: ["get", "list", "patch"]
---
apiVersion: v1
kind: ServiceAccount
metadata:
name: cozystack-credentials-migration-64
namespace: ${NAMESPACE}
---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
name: cozystack-credentials-migration-64
roleRef:
apiGroup: rbac.authorization.k8s.io
kind: ClusterRole
name: cozystack-credentials-migration-64
subjects:
- kind: ServiceAccount
name: cozystack-credentials-migration-64
namespace: ${NAMESPACE}
---
apiVersion: batch/v1
kind: Job
metadata:
name: cozystack-credentials-migration-64
namespace: ${NAMESPACE}
spec:
backoffLimit: 6
ttlSecondsAfterFinished: 604800
template:
metadata:
labels:
policy.cozystack.io/allow-to-apiserver: "true"
spec:
serviceAccountName: cozystack-credentials-migration-64
restartPolicy: OnFailure
containers:
- name: migration
image: ${image}
command:
- credentials-migrate
- finish
- --migration=64
- --kind=Postgres
- --format=scram-sha-256
- --accounts-path=users
- --refuse-flag=createRole
- --label=cnpg.io/reload=true
- --timeout=30m
env:
- name: CREDENTIALS_MIGRATE_ACTOR
value: system:serviceaccount:${NAMESPACE}:cozystack-credentials-migration-64
YAML
# Tie the ServiceAccount's lifetime to the Job: when the Job is deleted (its
# ttlSecondsAfterFinished, a rerun's delete above, or an operator by hand) the
# garbage collector removes the ServiceAccount, on the success and the failure
# path alike, so the least-privilege identity does not stand indefinitely after
# a release the conversion left out.
job_uid=$(kubectl get job cozystack-credentials-migration-64 \
--namespace "$NAMESPACE" \
--output 'jsonpath={.metadata.uid}')
if [ -z "$job_uid" ]; then
echo "cannot read the finish Job's uid to own its ServiceAccount" >&2
exit 1
fi
kubectl patch serviceaccount cozystack-credentials-migration-64 \
--namespace "$NAMESPACE" \
--type merge \
--patch "{\"metadata\":{\"ownerReferences\":[{\"apiVersion\":\"batch/v1\",\"kind\":\"Job\",\"name\":\"cozystack-credentials-migration-64\",\"uid\":\"${job_uid}\"}]}}"
stamp_cozystack_version 65
+1 -1
View File
@@ -89,7 +89,7 @@ migrations:
# refuses to advance past a migration file missing from the image (exit 1), so
# a stale pin fails loudly rather than silently skipping the etcd adoption.
image: ghcr.io/cozystack/cozystack/platform-migrations:v1.6.0@sha256:6777042e3e9c6bad76e7d96fb64baa115061975f39061cb3ede84e21d0e2213f
targetVersion: 64
targetVersion: 65
# Adopt legacy etcd clusters onto the v1alpha2 operator WITHOUT the mandatory
# pre-adoption safety snapshot (migration 50). Leave false unless migration 50
# has actually refused to proceed and you accept the risk: adoption rewires
@@ -0,0 +1,25 @@
apiVersion: operator.victoriametrics.com/v1beta1
kind: VMRule
metadata:
name: alerts-cozystack-credentials
spec:
groups:
- name: cozystack-credentials
params: {}
rules:
- alert: CredentialsMigrationIncomplete
annotations:
description: The credentials conversion recorded in ConfigMap {{ $labels.namespace
}}/{{ $labels.configmap }} left one or more releases unconverted, so their
tenant passwords may still be readable through the old <release>-credentials
Secret until the conversion is finished. Read the credentials-migration state
ConfigMap in cozy-system for the releases left out and the finish Job's log
for why, fix the cause, then delete the Job and re-apply its manifest from
the migration. This alert clears when the next finish run leaves none out.
summary: A credentials conversion left releases with tenant-readable passwords.
expr: kube_configmap_labels{job="kube-state-metrics", namespace="cozy-system", configmap=~"credentials-migration-.+", label_credentials_cozystack_io_incomplete="true"} > 0
for: 15m
labels:
severity: warning
exported_instance: '{{ $labels.namespace }}/{{ $labels.configmap }}'
service: cozystack-credentials
@@ -8,8 +8,8 @@ suite: kube-state-metrics exports the labels of pods, deployments and PVCs
templates:
- charts/kube-state-metrics/templates/deployment.yaml
tests:
- it: allowlists all labels of pods, deployments and persistentvolumeclaims
- it: allowlists all labels of pods, deployments and persistentvolumeclaims, and the credentials-migration incomplete key on configmaps
asserts:
- contains:
path: spec.template.spec.containers[0].args
content: --metric-labels-allowlist=pods=[*],deployments=[*],persistentvolumeclaims=[*]
content: --metric-labels-allowlist=pods=[*],deployments=[*],persistentvolumeclaims=[*],configmaps=[credentials.cozystack.io/incomplete]
@@ -33,7 +33,14 @@ kube-state-metrics:
# lineage labels. kube-state-metrics emits that metric only for resources on
# this list, one series per PVC; naming only the lineage keys would emit the
# same number of series.
- --metric-labels-allowlist=pods=[*],deployments=[*],persistentvolumeclaims=[*]
#
# configmaps names only the credentials.cozystack.io/incomplete key, which
# the credentials migration sets on its state ConfigMap: that ConfigMap
# outlives the finish Job, so the CredentialsMigrationIncomplete alert keys
# on kube_configmap_labels and fires until the conversion is finished, not
# only for the Job's TTL. Only the one key is named, so this adds a single
# series per credentials-migration ConfigMap, not one per ConfigMap label.
- --metric-labels-allowlist=pods=[*],deployments=[*],persistentvolumeclaims=[*],configmaps=[credentials.cozystack.io/incomplete]
rbac:
extraRules:
- apiGroups: