diff --git a/hack/migration-68-rabbitmq-credentials.bats b/hack/migration-68-rabbitmq-credentials.bats new file mode 100644 index 000000000..d68cafa7a --- /dev/null +++ b/hack/migration-68-rabbitmq-credentials.bats @@ -0,0 +1,202 @@ +#!/usr/bin/env bats +# ----------------------------------------------------------------------------- +# Unit tests for platform migration 68 --> 69 (convert RabbitMQ users to +# platform-minted credentials, first part). +# +# The migration seeds the account Secrets of every RabbitMQ release, then +# creates the cozystack-credentials-migration-68 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/68. +# +# 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-68-rabbitmq-credentials.bats +# ----------------------------------------------------------------------------- + +load test_helper + +FAKEBIN="$PWD/hack/testdata/migration-68-rabbitmq-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-migration68-test:$(printf '%s' "$ALPINE" | sed 's/[^a-zA-Z0-9]/-/g')" +WORKROOT="${TMPDIR:-/tmp}/cozy-migration-68-$$" +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_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 68 inside a build of" >&2 + echo "$ALPINE, the migrations image's base." >&2 + return 1 + } + docker build -q -t "$TESTIMG" - >/dev/null < "$FAKE_CMDLOG" + export NAMESPACE=cozy-system + export FAKE_IMAGE="$IMAGE" + unset 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 68 >"$WORK/out" 2>&1 || rc=$? + cat "$WORK/out"; cat "$FAKE_CMDLOG" + [ "$rc" -eq 0 ] + + # The seed runs for migration 68, reading the per-user Secrets by label and + # labelling the account Secrets for the topology operator. + grep -qE "^CREDMIGRATE seed --migration 68 --kind RabbitMQ --format plaintext .*--source-selector apps.cozystack.io/user-secret=true --source-key password --label rabbitmq.com/topology-operator=true$" "$FAKE_CMDLOG" + grep -qE "^APPLY-RABBITMQ selector=1 key=1 hide=1 list=1$" "$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 appdefs=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 69$") + [ -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 68 >"$WORK/out" 2>&1 || rc=$? + cat "$WORK/out"; cat "$FAKE_CMDLOG" + [ "$rc" -ne 0 ] + grep -qE "^CREDMIGRATE seed --migration 68 " "$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 68 >"$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 68 >"$WORK/out" 2>&1 || rc=$? + cat "$WORK/out"; cat "$FAKE_CMDLOG" + [ "$rc" -ne 0 ] + grep -qE "^CREDMIGRATE seed --migration 68 " "$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 68 >"$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 68 >"$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 68 >"$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\" not found" + rc=0 + run_migration 68 >"$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" +} diff --git a/hack/testdata/migration-68-rabbitmq-credentials/credentials-migrate b/hack/testdata/migration-68-rabbitmq-credentials/credentials-migrate new file mode 100755 index 000000000..978ef8d45 --- /dev/null +++ b/hack/testdata/migration-68-rabbitmq-credentials/credentials-migrate @@ -0,0 +1,22 @@ +#!/bin/sh +# Fake credentials-migrate for hack/migration-68-rabbitmq-credentials.bats. +# Migration 68 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 diff --git a/hack/testdata/migration-68-rabbitmq-credentials/kubectl b/hack/testdata/migration-68-rabbitmq-credentials/kubectl new file mode 100755 index 000000000..3c1937b03 --- /dev/null +++ b/hack/testdata/migration-68-rabbitmq-credentials/kubectl @@ -0,0 +1,119 @@ +#!/bin/sh +# Fake kubectl for hack/migration-68-rabbitmq-credentials.bats, modelled on +# hack/testdata/migration-58-http-cache/kubectl. It serves only the calls +# migration 68 and lib/cozystack-version.sh make, and logs each one to +# $FAKE_CMDLOG. +# +# Migration 68 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 + *"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-68"*) + # The hook deletes a Job left by an earlier run before recreating it. + log "DELETE-JOB" + exit 0 + ;; + + *"delete serviceaccount cozystack-credentials-migration-68"*) + # 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-68"*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-68"*) + # 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-68') + 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') + # The ServiceAccount, ClusterRole and binding share the Job's name, so + # count the name inside the Job document only. + jobname=$(printf '%s\n' "$manifest" | awk '/^kind: Job$/ { j = 1 } j && /^ name: cozystack-credentials-migration-68$/ { c++ } END { print c + 0 }') + mig=$(printf '%s\n' "$manifest" | grep -c -- '--migration=68') + img=$(printf '%s\n' "$manifest" | grep -c "^ image: ${IMAGE}$") + sacc=$(printf '%s\n' "$manifest" | grep -c '^ serviceAccountName: cozystack-credentials-migration-68$') + # RabbitMQ finish reads the per-user sources by label, hides the + # operator's administrator Secret, and needs list on Secrets for it. + selector=$(printf '%s\n' "$manifest" | grep -c -- '--source-selector=apps.cozystack.io/user-secret=true') + key=$(printf '%s\n' "$manifest" | grep -c -- '--source-key=password') + hide=$(printf '%s\n' "$manifest" | grep -c -- '--hide-secret-suffix=-default-user') + list=$(printf '%s\n' "$manifest" | grep -c 'verbs: \["get", "list", "create", "patch", "delete"\]') + log "APPLY-RABBITMQ selector=$selector key=$key hide=$hide list=$list" + # It reads the definitions to hide -default-user only once they do. + appdefs=$(printf '%s\n' "$manifest" | grep -c '^ resources: \["applicationdefinitions"\]$') + log "APPLY-FINISH role=$role sa=$sa crb=$crb admin=$admin jobname=$jobname migration=$mig image=$img serviceaccount=$sacc appdefs=$appdefs" + 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 diff --git a/packages/core/platform/images/migrations/migrations/68 b/packages/core/platform/images/migrations/migrations/68 new file mode 100755 index 000000000..f4b545370 --- /dev/null +++ b/packages/core/platform/images/migrations/migrations/68 @@ -0,0 +1,179 @@ +#!/bin/sh +# Migration 68 --> 69 +# Convert RabbitMQ users to platform-minted credentials, first part. +# +# The converted rabbitmq chart renders a CredentialTemplate per user and +# points each User's importCredentialsSecret at 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 +# RabbitMQ release from the per-user --credentials Secrets the +# old chart generated, so clients keep logging in at every point of the +# upgrade; the controller adopts them once the templates exist. The old +# chart kept one Secret per user, holding username and password, so they are +# found by label and by the Helm release that rendered them. A release whose +# every user got its Secret is marked for seeding, so users added later are +# seeded too. The account Secret carries the label messaging-topology-operator +# caches Secrets by; without it the operator's admission webhook refuses the +# User. +# +# The second part is the cozystack-credentials-migration-68 Job, which waits +# per release for its chart to switch, then strips any users..password +# left in the values, deletes a per-user Secret Helm did not prune, and labels +# the operator's -default-user Secret not tenant-visible. That Secret +# holds the administrator messaging-topology-operator logs in with. The +# converted ApplicationDefinition excludes it, which keeps it hidden on every +# rewrite by the cluster operator: that rewrite replaces the Secret's labels, +# and the lineage webhook stamps it again from the definition. The label is +# still needed for the Secret as it stands, which the webhook stamped visible +# under the old definition and leaves alone until such a rewrite. It goes on +# only once the definition in the API excludes the Secret: the rabbitmq-rd +# chart upgrades after the new cluster operator is Ready, whose first pass +# rewrites the Secret, and a label written before would be undone by it. Its +# password is not rotated here: the broker takes the default user's password +# only at first boot, so a rotation is a broker operation this Job does not +# have. +# +# The Job is created directly rather than rendered from the platform chart, +# for the reasons migration 64 gives, and runs the image this hook runs as. +# Its ServiceAccount, ClusterRole and binding carry this migration's number, +# so a conversion running in the same upgrade never deletes or re-owns +# another's identity. The ClusterRole is least-privilege: finish needs CRUD +# and list on Secrets (list, for the per-user sources), get/list/patch on +# HelmReleases, create on Events, and its state ConfigMap. The ServiceAccount +# is owned by the Job, so the garbage collector removes it with the Job; the +# ClusterRoleBinding cannot be owned by a namespaced Job and is left, granting +# to no subject once the ServiceAccount is gone. To rerun the Job by hand, +# delete it 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}" +NAME=cozystack-credentials-migration-68 + +credentials-migrate seed \ + --migration 68 \ + --kind RabbitMQ \ + --format plaintext \ + --accounts-path users \ + --source-selector 'apps.cozystack.io/user-secret=true' \ + --source-key password \ + --label 'rabbitmq.com/topology-operator=true' + +# The finish Job runs the same image as this hook. Read it from this pod's +# own container by name, as migration 64 does. +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 and ServiceAccount left by an earlier run of this hook: the +# pod template is immutable, and a ServiceAccount still owned by the deleted +# Job could be collected after the apply below. finish recovers its progress +# from the state ConfigMap, so recreating the Job loses nothing. +kubectl delete job "$NAME" \ + --namespace "$NAMESPACE" \ + --ignore-not-found +kubectl delete serviceaccount "$NAME" \ + --namespace "$NAMESPACE" \ + --ignore-not-found + +kubectl apply --filename - <&2 + exit 1 +fi +kubectl patch serviceaccount "$NAME" \ + --namespace "$NAMESPACE" \ + --type merge \ + --patch "{\"metadata\":{\"ownerReferences\":[{\"apiVersion\":\"batch/v1\",\"kind\":\"Job\",\"name\":\"${NAME}\",\"uid\":\"${job_uid}\"}]}}" + +stamp_cozystack_version 69 diff --git a/packages/core/platform/values.yaml b/packages/core/platform/values.yaml index eb764c949..5937dd32f 100644 --- a/packages/core/platform/values.yaml +++ b/packages/core/platform/values.yaml @@ -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: 68 + targetVersion: 69 # 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