Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
chore(gfs): deploy manifests, provisioning scripts, docs, and e2e fixtures
Alfredo Lopez8f86579a0fd1
diff --git a/deploy/base/control-plane/control-postgres.yaml b/deploy/base/control-plane/control-postgres.yamlindex 3a201b1f9..d344a28a2 100644--- a/deploy/base/control-plane/control-postgres.yaml+++ b/deploy/base/control-plane/control-postgres.yaml@@ -3,6 +3,8 @@ kind: PersistentVolumeClaimmetadata:name: control-postgres-datanamespace: control-plane+ labels:+ app: control-postgresspec:accessModes:- ReadWriteOnce@@ -89,6 +91,8 @@ kind: Servicemetadata:name: control-postgresnamespace: control-plane+ labels:+ app: control-postgresspec:type: ClusterIPselector:diff --git a/deploy/base/gfs/gfs-controller-db.yaml b/deploy/base/gfs/gfs-controller-db.yamlindex e4c3426b9..ea3799e30 100644--- a/deploy/base/gfs/gfs-controller-db.yaml+++ b/deploy/base/gfs/gfs-controller-db.yaml@@ -8,12 +8,15 @@ metadata:app.kubernetes.io/part-of: clerumtype: Opaque# The connection-string key is intentionally NOT declared in this manifest. It-# is OWNED by deploy/scripts/provision-gfs-db.sh, which grants LOGIN + password+# is OWNED by the explicit `rotate-writer` mode of+# deploy/scripts/provision-gfs-db.sh, which grants LOGIN + password# to the least-privilege gfs_controller role (created NOLOGIN by control-api-# migration 0048; SELECT on resource/grant/share, INSERT-only on gfs_audit —-# never write on grants) and patches the real DSN into this Secret. Because the+# migrations; resource/manifest writes required by GFSC, authorization reads,+# append-only audit, and never grant/share writes) and patches the real DSN+# into this Secret. Because the# key is absent here, `kubectl apply` of the overlay can never clobber a# provisioned DSN: the three-way merge only prunes keys present in# last-applied-configuration, and the provisioning patch never lands there# (issue #775). Fresh clusters fail loud instead: gfsc pods sit in-# CreateContainerConfigError (missing Secret key) until provisioning runs.+# CreateContainerConfigError (missing Secret key) until the explicit bootstrap+# rotation runs. Normal deploys never rotate this compatibility credential.diff --git a/deploy/base/gfs/gfs-controller-reader-db.yaml b/deploy/base/gfs/gfs-controller-reader-db.yamlnew file mode 100644index 000000000..b450c7cc5--- /dev/null+++ b/deploy/base/gfs/gfs-controller-reader-db.yaml@@ -0,0 +1,12 @@+apiVersion: v1+kind: Secret+metadata:+ name: gfs-controller-reader-db+ namespace: gfs+ labels:+ app.kubernetes.io/name: gfs-controller+ app.kubernetes.io/part-of: clerum+type: Opaque+# Provisioning-owned. `stage-reader` adds connection-string before HCC cutover;+# keeping the key out of last-applied configuration prevents overlay apply from+# erasing an already valid credential.diff --git a/deploy/base/gfs/kustomization.yaml b/deploy/base/gfs/kustomization.yamlindex ed8caf7e5..48123435d 100644--- a/deploy/base/gfs/kustomization.yaml+++ b/deploy/base/gfs/kustomization.yaml@@ -11,5 +11,6 @@ kind: Kustomizationresources:- gfs-config.yaml- gfs-controller-db.yaml+ - gfs-controller-reader-db.yaml- networkpolicies.yaml- rbac.yamldiff --git a/deploy/scripts/apply-gfs-writer-secret.sh b/deploy/scripts/apply-gfs-writer-secret.shnew file mode 100755index 000000000..27dfe39e1--- /dev/null+++ b/deploy/scripts/apply-gfs-writer-secret.sh@@ -0,0 +1,30 @@+#!/usr/bin/env bash+# Preserve a provisioning-owned writer DSN while migrating legacy apply ownership.+set -euo pipefail++CONTEXT="${CONTEXT:?set CONTEXT to the target kube-context}"+ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"+MANIFEST="${ROOT}/deploy/base/gfs/gfs-controller-db.yaml"+NAMESPACE=gfs+SECRET=gfs-controller-db++kc() { kubectl --context="$CONTEXT" "$@"; }+fail() { printf '[apply-gfs-writer-secret] ERROR: %s\n' "$*" >&2; exit 1; }++if existing="$(kc -n "$NAMESPACE" get secret "$SECRET" -o name 2>&1)"; then+ # The historical manifest declared data.connection-string. Replace only its+ # last-applied ownership record before apply so the live provisioned key is+ # preserved; this command does not mutate Secret data.+ kc apply set-last-applied --create-annotation=true -f "$MANIFEST" >/dev/null \+ || fail "cannot migrate legacy apply ownership for ${NAMESPACE}/${SECRET}"+elif grep -qF "namespaces \"${NAMESPACE}\" not found" <<<"$existing"; then+ fail "namespace ${NAMESPACE} is not declared; apply deploy/base/namespaces.yaml before GFS Secrets"+elif grep -qF "secrets \"${SECRET}\" not found" <<<"$existing"; then+ : # Fresh bootstrap: the normal apply below creates the empty fail-closed Secret.+else+ fail "cannot determine whether ${NAMESPACE}/${SECRET} exists"+fi++kc apply -f "$MANIFEST" >/dev/null \+ || fail "cannot apply ${NAMESPACE}/${SECRET}"+printf '[apply-gfs-writer-secret] %s/%s declared without changing its provisioned DSN\n' "$NAMESPACE" "$SECRET" >&2diff --git a/deploy/scripts/control-api-runtime-access-profiles.tsv b/deploy/scripts/control-api-runtime-access-profiles.tsvindex c6e1ccf9c..827f74e50 100644--- a/deploy/scripts/control-api-runtime-access-profiles.tsv+++ b/deploy/scripts/control-api-runtime-access-profiles.tsv@@ -9,6 +9,7 @@ control_admin_password_reset_requests legacy_dmlcontrol_admin_revoked_tokens legacy_dmlcontrol_admin_users legacy_dmlgfs_audit legacy_dml+gfs_blob_manifests nonegfs_grants legacy_dmlgfs_resources legacy_dmlgfs_shares legacy_dmldiff --git a/deploy/scripts/converge-control-db-after-reset.sh b/deploy/scripts/converge-control-db-after-reset.shnew file mode 100755index 000000000..2362f6765--- /dev/null+++ b/deploy/scripts/converge-control-db-after-reset.sh@@ -0,0 +1,246 @@+#!/usr/bin/env bash+# Rebuild the control-api database contract and restore persisted GFS roles+# after an intentional PostgreSQL data-volume recreation.+set -euo pipefail++CONTEXT="${CONTEXT:?set CONTEXT to the target kube-context}"+ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"+OVERLAY=""+JOB_NAME="control-api-db-migrate-reset"+NAMESPACE=control-plane+PVC=control-postgres-data+RESET_STATE=control-db-reset-state++while [ "$#" -gt 0 ]; do+ case "$1" in+ --overlay)+ OVERLAY="${2:?--overlay requires a path}"+ shift 2+ ;;+ --job-name)+ JOB_NAME="${2:?--job-name requires a value}"+ shift 2+ ;;+ *)+ printf '[converge-control-db-after-reset] ERROR: unknown argument: %s\n' "$1" >&2+ exit 2+ ;;+ esac+done++[ -n "$OVERLAY" ] \+ || { printf '[converge-control-db-after-reset] ERROR: --overlay is required\n' >&2; exit 2; }++kc() { kubectl --context="$CONTEXT" "$@"; }+fail() { printf '[converge-control-db-after-reset] ERROR: %s\n' "$*" >&2; exit 1; }++read_reset_state() {+ local raw+ raw="$(kc -n "$NAMESPACE" get configmap "$RESET_STATE" -o \+ 'jsonpath={.metadata.uid}{"|"}{.metadata.resourceVersion}{"|"}{.data.stateVersion}{"|"}{.data.phase}{"|"}{.data.originalPvcUid}{"|"}{.data.replacementPvcUid}{"|"}{.data.hccReplicas}{"|"}{.data.workflowReplicas}{"|"}{.data.traceReplicas}{"|"}{.data.writerReplicas}{"|"}{.data.readerReplicas}{"|"}{.data.controlApiReplicas}')" \+ || return 1+ IFS='|' read -r STATE_UID STATE_RV STATE_VERSION STATE_PHASE ORIGINAL_PVC_UID \+ REPLACEMENT_PVC_UID HCC_REPLICAS WORKFLOW_REPLICAS TRACE_REPLICAS \+ WRITER_REPLICAS READER_REPLICAS CONTROL_API_REPLICAS <<<"$raw"+ case "$STATE_PHASE" in+ authorized|deleting-original)+ fail "reset is still in storage phase '${STATE_PHASE}'; run reset-control-db-storage.sh --resume to finish it before convergence" ;;+ esac+ [ -n "$STATE_UID" ] && [ -n "$STATE_RV" ] && [ "$STATE_VERSION" = 1 ] \+ && [[ "$STATE_PHASE" =~ ^(original-deleted|replacement-bound|converged)$ ]] \+ && [ -n "$ORIGINAL_PVC_UID" ] && [ -n "$REPLACEMENT_PVC_UID" ] \+ && [[ "$HCC_REPLICAS" =~ ^[0-9]+$ ]] \+ && [[ "$WORKFLOW_REPLICAS" =~ ^[0-9]+$ ]] \+ && [[ "$TRACE_REPLICAS" =~ ^[0-9]+$ ]] \+ && [[ "$WRITER_REPLICAS" =~ ^[1-9][0-9]*$ ]] \+ && [[ "$READER_REPLICAS" =~ ^[1-9][0-9]*$ ]] \+ && [[ "$CONTROL_API_REPLICAS" =~ ^[1-9][0-9]*$ ]] \+ || fail "reset recovery state is incomplete or invalid"+}++cas_phase() {+ local expected_phase="$1" next_phase="$2" expected_replacement="$3" next_replacement="$4" patch+ patch="$(python3 - "$STATE_RV" "$expected_phase" "$next_phase" \+ "$ORIGINAL_PVC_UID" "$expected_replacement" "$next_replacement" <<'PY'+import json+import sys++rv, old_phase, new_phase, original_uid, old_replacement, new_replacement = sys.argv[1:]+print(json.dumps([+ {"op": "test", "path": "/metadata/resourceVersion", "value": rv},+ {"op": "test", "path": "/data/stateVersion", "value": "1"},+ {"op": "test", "path": "/data/phase", "value": old_phase},+ {"op": "test", "path": "/data/originalPvcUid", "value": original_uid},+ {"op": "test", "path": "/data/replacementPvcUid", "value": old_replacement},+ {"op": "replace", "path": "/data/phase", "value": new_phase},+ {"op": "replace", "path": "/data/replacementPvcUid", "value": new_replacement},+]))+PY+)" || fail "cannot build reset-state compare-and-swap patch"+ kc -n "$NAMESPACE" patch configmap "$RESET_STATE" --type=json -p "$patch" >/dev/null \+ || fail "reset state changed concurrently while advancing ${expected_phase} to ${next_phase}"+ read_reset_state || fail "cannot reload reset state after advancing to ${next_phase}"+ [ "$STATE_PHASE" = "$next_phase" ] && [ "$REPLACEMENT_PVC_UID" = "$next_replacement" ] \+ || fail "reset-state compare-and-swap did not persist ${next_phase}"+}++current_pvc_uid() {+ kc -n "$NAMESPACE" get pvc "$PVC" -o 'jsonpath={.metadata.uid}' --ignore-not-found+}++assert_replacement_uid() {+ local observed+ observed="$(current_pvc_uid)" || fail "cannot inspect replacement PVC"+ [ -n "$observed" ] || fail "replacement PVC is missing"+ [ "$observed" = "$REPLACEMENT_PVC_UID" ] \+ || fail "replacement PVC UID changed after it was bound"+}++delete_reset_state() {+ local remaining_uid+ if printf '{"apiVersion":"v1","kind":"DeleteOptions","preconditions":{"uid":"%s"}}\n' \+ "$STATE_UID" | kc -n "$NAMESPACE" delete --raw \+ "/api/v1/namespaces/${NAMESPACE}/configmaps/${RESET_STATE}" -f - --wait=true >/dev/null; then+ CONVERGED=true+ return 0+ fi+ remaining_uid="$(kc -n "$NAMESPACE" get configmap "$RESET_STATE" \+ -o 'jsonpath={.metadata.uid}' --ignore-not-found)" \+ || fail "cannot resolve reset-state cleanup result"+ if [ -z "$remaining_uid" ]; then+ CONVERGED=true+ return 0+ fi+ [ "$remaining_uid" = "$STATE_UID" ] \+ || fail "a different reset state replaced the completed recovery record"+ CONVERGED=true+ fail "verified convergence is complete but reset-state cleanup failed; retry convergence"+}++CONVERGED=false+fail_closed() {+ local rc=$? scale_rc+ if [ "$CONVERGED" != true ]; then+ set +e+ scale_rc=0+ kc -n control-plane scale deployment/host-context-controller --replicas=0 >/dev/null || scale_rc=1+ kc -n control-plane scale deployment/workflow-recipes deployment/trace-maintenance-worker --replicas=0 >/dev/null || scale_rc=1+ kc -n gfs scale deployment/gfsc-writer deployment/gfsc-reader --replicas=0 >/dev/null || scale_rc=1+ printf '[converge-control-db-after-reset] ERROR: convergence failed; DB-dependent controllers remain scaled to zero' >&2+ [ "$scale_rc" -eq 0 ] || printf ' (failed to confirm fail-closed scale)' >&2+ printf '\n' >&2+ fi+ trap - EXIT+ exit "$rc"+}+trap fail_closed EXIT++read_reset_state || fail "reset recovery state is missing"+observed_uid="$(current_pvc_uid)" || fail "cannot inspect replacement PVC"+[ -n "$observed_uid" ] || fail "replacement PVC is missing"+case "$STATE_PHASE" in+ original-deleted)+ [ "$ORIGINAL_PVC_UID" = none ] || [ "$observed_uid" != "$ORIGINAL_PVC_UID" ] \+ || fail "authorized original PVC still occupies the claim name"+ cas_phase original-deleted replacement-bound unbound "$observed_uid"+ ;;+ replacement-bound|converged)+ [ "$REPLACEMENT_PVC_UID" != unbound ] || fail "reset state has no replacement UID"+ [ "$observed_uid" = "$REPLACEMENT_PVC_UID" ] || fail "replacement PVC UID changed"+ ;;+esac++# A completed run can leave only its recovery record behind if cleanup failed.+# Revalidate the bound replacement and exact runtime, then retry cleanup without+# rerunning migrations or rotating credentials.+if [ "$STATE_PHASE" = converged ]; then+ kc -n gfs scale deployment/gfsc-writer --replicas="$WRITER_REPLICAS" >/dev/null+ kc -n gfs scale deployment/gfsc-reader --replicas="$READER_REPLICAS" >/dev/null+ kc -n gfs rollout status deployment/gfsc-writer --timeout=180s >/dev/null+ kc -n gfs rollout status deployment/gfsc-reader --timeout=180s >/dev/null+ CONTEXT="$CONTEXT" bash "$ROOT/scripts/minikube/verify-gfs.sh"+ kc -n control-plane scale deployment/workflow-recipes --replicas="$WORKFLOW_REPLICAS" >/dev/null+ kc -n control-plane scale deployment/trace-maintenance-worker --replicas="$TRACE_REPLICAS" >/dev/null+ if [ "$WORKFLOW_REPLICAS" -gt 0 ]; then+ kc -n control-plane rollout status deployment/workflow-recipes --timeout=180s >/dev/null+ fi+ if [ "$TRACE_REPLICAS" -gt 0 ]; then+ kc -n control-plane rollout status deployment/trace-maintenance-worker --timeout=180s >/dev/null+ fi+ kc -n control-plane scale deployment/host-context-controller --replicas="$HCC_REPLICAS" >/dev/null+ if [ "$HCC_REPLICAS" -gt 0 ]; then+ kc -n control-plane rollout status deployment/host-context-controller --timeout=180s >/dev/null+ fi+ assert_replacement_uid+ delete_reset_state+ printf '[converge-control-db-after-reset] verified convergence already complete; recovery state removed\n' >&2+ trap - EXIT+ exit 0+fi++kc -n control-plane scale deployment/host-context-controller --replicas=0 >/dev/null+HCC_PODS="$(kc -n control-plane get pods -l app=host-context-controller -o name)"+if [ -n "$HCC_PODS" ]; then+ kc -n control-plane wait --for=delete pod \+ -l app=host-context-controller --timeout=180s >/dev/null+fi+kc -n control-plane scale deployment/workflow-recipes deployment/trace-maintenance-worker --replicas=0 >/dev/null+WORKFLOW_PODS="$(kc -n control-plane get pods -l app=workflow-recipes -o name)"+if [ -n "$WORKFLOW_PODS" ]; then+ kc -n control-plane wait --for=delete pod -l app=workflow-recipes --timeout=180s >/dev/null+fi+TRACE_PODS="$(kc -n control-plane get pods -l app=trace-maintenance-worker -o name)"+if [ -n "$TRACE_PODS" ]; then+ kc -n control-plane wait --for=delete pod -l app=trace-maintenance-worker --timeout=180s >/dev/null+fi+kc -n gfs scale \+ deployment/gfsc-writer deployment/gfsc-reader --replicas=0 >/dev/null+GFSC_PODS="$(kc -n gfs get pods -l app=gfs-controller -o name)"+if [ -n "$GFSC_PODS" ]; then+ kc -n gfs wait --for=delete pod \+ -l app=gfs-controller --timeout=180s >/dev/null+fi++env CONTEXT="$CONTEXT" ALLOWED_CONTEXTS="$CONTEXT" \+ bash "$ROOT/deploy/scripts/run-control-api-db-migration.sh" \+ --overlay "$OVERLAY" --job-name "$JOB_NAME"+env CONTEXT="$CONTEXT" ALLOWED_CONTEXTS="$CONTEXT" \+ bash "$ROOT/deploy/scripts/provision-control-api-runtime-roles.sh"++kc -n control-plane scale deployment/control-api --replicas="$CONTROL_API_REPLICAS" >/dev/null+kc -n control-plane rollout status deployment/control-api --timeout=180s >/dev/null++GFS_RESTORE_ACTIVE_NOLOGIN=true CONTEXT="$CONTEXT" \+ bash "$ROOT/deploy/scripts/reconcile-gfs-deploy-credentials.sh"++kc -n gfs scale deployment/gfsc-writer \+ --replicas="$WRITER_REPLICAS" >/dev/null+kc -n gfs scale deployment/gfsc-reader \+ --replicas="$READER_REPLICAS" >/dev/null+kc -n gfs rollout status deployment/gfsc-writer --timeout=180s >/dev/null+kc -n gfs rollout status deployment/gfsc-reader --timeout=180s >/dev/null+CONTEXT="$CONTEXT" bash "$ROOT/scripts/minikube/verify-gfs.sh"++kc -n control-plane scale deployment/workflow-recipes --replicas="$WORKFLOW_REPLICAS" >/dev/null+kc -n control-plane scale deployment/trace-maintenance-worker --replicas="$TRACE_REPLICAS" >/dev/null+if [ "$WORKFLOW_REPLICAS" -gt 0 ]; then+ kc -n control-plane rollout status deployment/workflow-recipes --timeout=180s >/dev/null+fi+if [ "$TRACE_REPLICAS" -gt 0 ]; then+ kc -n control-plane rollout status deployment/trace-maintenance-worker --timeout=180s >/dev/null+fi++kc -n control-plane scale deployment/host-context-controller \+ --replicas="$HCC_REPLICAS" >/dev/null+if [ "$HCC_REPLICAS" -gt 0 ]; then+ kc -n control-plane rollout status \+ deployment/host-context-controller --timeout=180s >/dev/null+fi+assert_replacement_uid+read_reset_state || fail "cannot reload reset state before completion"+[ "$STATE_PHASE" = replacement-bound ] \+ || fail "reset state changed before convergence completion"+cas_phase replacement-bound converged "$REPLACEMENT_PVC_UID" "$REPLACEMENT_PVC_UID"+delete_reset_state+printf '[converge-control-db-after-reset] migrations, runtime roles, GFS restore, and verification complete\n' >&2+trap - EXITdiff --git a/deploy/scripts/lib/gfs-credential-recovery.sh b/deploy/scripts/lib/gfs-credential-recovery.shnew file mode 100644index 000000000..8ec51b0b5--- /dev/null+++ b/deploy/scripts/lib/gfs-credential-recovery.sh@@ -0,0 +1,101 @@+#!/usr/bin/env bash+# Explicit recovery decision for an abandoned credential in `applying`.++dsn_authentication_state() {+ local rc+ if dsn_authenticates_as "$1" "$2"; then+ printf authenticated+ return 0+ else+ rc=$?+ fi+ if [ "$rc" -eq 1 ]; then+ printf rejected+ else+ printf unavailable+ fi+}++require_authenticated_dsn() {+ local state+ state="$(dsn_authentication_state "$1" "$2")"+ [ "$state" = authenticated ] && return 0+ [ "$state" = rejected ] && die "$3 authentication rejected"+ die "$3 authentication probe unavailable"+}++authenticate_or_restore_nologin() {+ local role="$1" kind="$2" active="$3" lifecycle="$4" context="$5" state+ state="$(dsn_authentication_state "$active" "$role")"+ [ "$state" = authenticated ] && return 0+ [ "$state" = unavailable ] && die "${context} authentication probe unavailable; refusing credential mutation"+ restore_nologin_role_from_active "$role" "$kind" "$active" "$lifecycle" \+ || die "${context} authentication rejected and the role is not safely restorable from NOLOGIN"+}++recover_abandoned_applying() {+ local role="$1" secret="$2" active="$3" pending="$4" login_state pending_auth active_auth+ [ -n "$pending" ] || die "${GFS_NS}/${secret} is applying without a pending candidate"+ dsn_has_role "$pending" "$role" || die "${GFS_NS}/${secret} contains an invalid applying candidate"+ [ "${GFS_RECOVER_ABANDONED_STATE:-false}" = true ] \+ || die "${GFS_NS}/${secret} is applying; confirm the prior process ended, then retry with GFS_RECOVER_ABANDONED_STATE=true"++ pending_auth="$(dsn_authentication_state "$pending" "$role")"+ case "$pending_auth" in+ authenticated)+ log "Recovering an explicitly confirmed applying candidate"+ printf applied+ return 0+ ;;+ unavailable)+ die "candidate authentication probe is unavailable; refusing credential recovery"+ ;;+ esac+ if [ -n "$active" ]; then+ active_auth="$(dsn_authentication_state "$active" "$role")"+ case "$active_auth" in+ authenticated)+ log "Releasing an explicitly confirmed applying candidate whose database change did not commit"+ printf '%s' "$pending" | release_abandoned_candidate "$secret" \+ || die "abandoned applying candidate changed during recovery"+ printf pending+ return 0+ ;;+ unavailable)+ die "active authentication probe is unavailable; refusing credential recovery"+ ;;+ esac+ fi+ if [ -z "$active" ]; then+ login_state="$(role_can_login "$role")" \+ || die "cannot determine role state while recovering fresh credential bootstrap"+ if [ "$login_state" = f ]; then+ log "Releasing a fresh applying candidate because the database role remains NOLOGIN"+ printf '%s' "$pending" | release_abandoned_candidate "$secret" \+ || die "fresh applying candidate changed during recovery"+ printf pending+ return 0+ fi+ fi+ die "abandoned applying state matches neither committed nor pending credential; manual database recovery required"+}++restore_nologin_role_from_active() {+ local role="$1" kind="$2" active="$3" state="$4" login_state password auth_state+ [ "${GFS_RESTORE_ACTIVE_NOLOGIN:-false}" = true ] || return 1+ [ "$state" = ready ] || return 1+ login_state="$(role_can_login "$role")" || return 1+ [ "$login_state" = f ] || return 1+ verify_role_contract "$role" "$kind" false || return 1+ password="$(printf '%s' "$active" | gfs_dsn_password)" || return 1+ set_role_password "$role" "$password" || return 1+ unset password+ auth_state="$(dsn_authentication_state "$active" "$role")"+ if [ "$auth_state" != authenticated ] || ! verify_role_contract "$role" "$kind"; then+ if ! disable_role_login "$role"; then+ log "ERROR: failed to compensate ${role} back to NOLOGIN after restore verification failed"+ fi+ return 1+ fi+ log "Restored ${kind} LOGIN from its unchanged committed DSN after database bootstrap"+}diff --git a/deploy/scripts/lib/gfs-credential-rollout.sh b/deploy/scripts/lib/gfs-credential-rollout.shnew file mode 100644index 000000000..9b13065c7--- /dev/null+++ b/deploy/scripts/lib/gfs-credential-rollout.sh@@ -0,0 +1,120 @@+#!/usr/bin/env bash+# Targeted GFSC rollout transitions after a credential is committed.++deployment_uses_secret() {+ local deployment="$1" secret="$2" refs error+ if ! refs="$(kc -n "$GFS_NS" get deployment "$deployment" -o \+ 'jsonpath={range .spec.template.spec.containers[*].env[*]}{.valueFrom.secretKeyRef.name}{"\n"}{end}' 2>&1)"; then+ error="$refs"+ grep -qiE 'not ?found' <<<"$error" && return 1+ die "cannot inspect ${GFS_NS}/${deployment} Secret references"+ fi+ grep -Fxq "$secret" <<<"$refs"+}++deployment_exists() {+ local deployment="$1" error+ if error="$(kc -n "$GFS_NS" get deployment "$deployment" -o name 2>&1)"; then+ return 0+ fi+ grep -qiE 'not ?found' <<<"$error" && return 1+ die "cannot determine whether ${GFS_NS}/${deployment} exists"+}++credential_rollout_pending() {+ local deployment="$1" secret="$2" rotated rows+ # A failed annotation read must not masquerade as "never rotated": that+ # would silently skip a stale-pod rollout the rotation still requires.+ # stderr is captured separately so a success-path kubectl warning can never+ # pollute the timestamp the awk gate below compares against.+ local rotated_err_file rotated_err+ rotated_err_file="$(mktemp)"+ if ! rotated="$(gfs_secret_rotated_at "$secret" 2>"$rotated_err_file")"; then+ rotated_err="$(cat "$rotated_err_file")"+ rm -f "$rotated_err_file"+ die "cannot read ${GFS_NS}/${secret} rotation annotation: ${rotated_err}"+ fi+ rm -f "$rotated_err_file"+ [ -n "$rotated" ] || return 1+ if ! rows="$(kc -n "$GFS_NS" get pods -l 'app=gfs-controller' -o \+ 'jsonpath={range .items[*]}{.metadata.ownerReferences[0].name}{"|"}{.metadata.creationTimestamp}{"|"}{.status.conditions[?(@.type=="Ready")].status}{"|"}{.metadata.deletionTimestamp}{"\n"}{end}' 2>&1)"; then+ die "cannot list ${GFS_NS} GFS controller pods"+ fi+ printf '%s\n' "$rows" | awk -F'|' -v prefix="${deployment}-" -v rotated="$rotated" \+ '$1 ~ "^" prefix && $4 == "" { seen=1; if ($2 < rotated || $3 != "True") found=1 } END { exit !(found || !seen) }'+}++credential_rollout_required() {+ local deployment="$1" secret="$2" state="$3"+ case "$state" in+ rollout-pending|rollout-running)+ # A pre-overlay retry must not restart an old template and mark the+ # lifecycle ready before HCC has wired the dedicated Secret.+ deployment_uses_secret "$deployment" "$secret"+ ;;+ *)+ credential_rollout_pending "$deployment" "$secret"+ ;;+ esac+}++credential_adoption_timestamp() {+ local deployment="$1" selector="$2" expected_dsn="$3" rows live oldest="" pod created ready+ if ! deployment_exists "$deployment"; then+ date -u '+%Y-%m-%dT%H:%M:%SZ'+ return 0+ fi+ rows="$(kc -n "$GFS_NS" get pods -l "$selector" -o \+ 'jsonpath={range .items[*]}{.metadata.name}{"|"}{.metadata.creationTimestamp}{"|"}{.status.conditions[?(@.type=="Ready")].status}{"|"}{.metadata.deletionTimestamp}{"\n"}{end}')" \+ || die "cannot inspect ${deployment} pods for legacy credential adoption"+ live="$(printf '%s\n' "$rows" | awk -F'|' 'NF >= 3 && $4 == "" {print}')"+ [ -n "$live" ] || die "cannot adopt legacy credential without a live ${deployment} pod"+ while IFS='|' read -r pod created ready _deleting; do+ [ "$ready" = True ] || die "cannot adopt legacy credential while ${pod} is not Ready"+ printf '%s' "$expected_dsn" | kc -n "$GFS_NS" exec -i "$pod" -- node -e '+let input=""; process.stdin.setEncoding("utf8");+process.stdin.on("data", chunk => input += chunk);+process.stdin.on("end", () => process.exit(input === process.env.GFS_PG_CONNECTION_STRING ? 0 : 1));' \+ >/dev/null 2>&1 || die "${pod} does not consume the legacy writer credential being adopted"+ [ -z "$oldest" ] || [ "$created" ">" "$oldest" ] || oldest="$created"+ [ -n "$oldest" ] || oldest="$created"+ done <<<"$live"+ printf '%s' "$oldest"+}++rollout_exact() {+ local deployment="$1"+ kc -n "$GFS_NS" rollout restart "deployment/${deployment}" >/dev/null+ kc -n "$GFS_NS" rollout status "deployment/${deployment}" --timeout="$ROLLOUT_TIMEOUT"+}++complete_rollout() {+ local secret="$1" deployment="$2" rotated state rc+ rotated="$(gfs_secret_rotated_at "$secret")"+ state="$(gfs_secret_state "$secret")"+ case "$state" in+ rollout-pending|ready)+ claim_secret_rollout "$secret" "$rotated" "$state" \+ || die "credential rollout state was superseded before ${deployment} could claim it"+ ;;+ rollout-running)+ [ "${GFS_RECOVER_ABANDONED_STATE:-false}" = true ] \+ || die "${deployment} rollout is already claimed; confirm the prior process ended, then retry with GFS_RECOVER_ABANDONED_STATE=true"+ log "Recovering an explicitly confirmed interrupted ${deployment} rollout"+ ;;+ *) die "cannot rollout ${deployment} from credential state ${state}" ;;+ esac+ if ! deployment_exists "$deployment"; then+ log "${GFS_NS}/${deployment} is not present; credential is staged for its future pod"+ mark_secret_rollout_ready "$secret" "$rotated" rollout-running \+ || die "staged credential state was superseded; refusing a stale completion"+ return 0+ fi+ if rollout_exact "$deployment"; then+ mark_secret_rollout_ready "$secret" "$rotated" rollout-running \+ || die "${deployment} rolled out but credential state was superseded; refusing a stale completion"+ return 0+ else rc=$?+ fi+ return "$rc"+}diff --git a/deploy/scripts/lib/gfs-credential-secret.sh b/deploy/scripts/lib/gfs-credential-secret.shnew file mode 100644index 000000000..d6cb34291--- /dev/null+++ b/deploy/scripts/lib/gfs-credential-secret.sh@@ -0,0 +1,200 @@+#!/usr/bin/env bash+# Atomic Kubernetes Secret transitions for resumable GFSC credential rotation.+# Candidate connection material is accepted only on stdin.+# Snapshot globals are consumed by the provisioning script that sources this file.+# shellcheck disable=SC2034++gfs_secret_state() {+ kc -n "$GFS_NS" get secret "$1" -o 'jsonpath={.metadata.annotations.clerum\.io/gfs-dsn-state}'+}++gfs_secret_rotated_at() {+ kc -n "$GFS_NS" get secret "$1" -o 'jsonpath={.metadata.annotations.clerum\.io/gfs-dsn-rotated-at}'+}++ensure_secret_state() {+ local secret="$1" state rv+ state="$(gfs_secret_state "$secret")"+ [ -n "$state" ] && return 0+ rv="$(secret_resource_version "$secret")"+ python3 -c 'import json, sys+print(json.dumps({"metadata": {"resourceVersion": sys.argv[1], "annotations": {"clerum.io/gfs-dsn-state": "ready"}}}))' "$rv" \+ | kc -n "$GFS_NS" patch secret "$secret" --type=merge --patch-file=/dev/stdin >/dev/null \+ || [ -n "$(gfs_secret_state "$secret")" ]+}++load_secret_snapshot() {+ local secret="$1" encoded rv annotations state rotated active pending+ encoded="$(kc -n "$GFS_NS" get secret "$secret" -o json | python3 -c 'import base64, json, sys+obj = json.load(sys.stdin)+metadata = obj.get("metadata") or {}+annotations = metadata.get("annotations") or {}+data = obj.get("data") or {}+def decode_data(key):+ value = data.get(key, "")+ return base64.b64decode(value, validate=True) if value else b""+values = [+ str(metadata.get("resourceVersion", "")).encode(),+ (b"yes" if annotations else b"no"),+ str(annotations.get("clerum.io/gfs-dsn-state", "")).encode(),+ str(annotations.get("clerum.io/gfs-dsn-rotated-at", "")).encode(),+ decode_data("connection-string"),+ decode_data("pending-connection-string"),+]+print("|".join(base64.b64encode(value).decode() for value in values))')" || return 1+ IFS='|' read -r rv annotations state rotated active pending <<<"$encoded"+ GFS_SNAPSHOT_RV="$(printf '%s' "$rv" | base64 -d)" || return 1+ GFS_SNAPSHOT_ANNOTATIONS="$(printf '%s' "$annotations" | base64 -d)" || return 1+ GFS_SNAPSHOT_STATE="$(printf '%s' "$state" | base64 -d)" || return 1+ GFS_SNAPSHOT_ROTATED_AT="$(printf '%s' "$rotated" | base64 -d)" || return 1+ GFS_SNAPSHOT_ACTIVE="$(printf '%s' "$active" | base64 -d)" || return 1+ GFS_SNAPSHOT_PENDING="$(printf '%s' "$pending" | base64 -d)" || return 1+ [ -n "$GFS_SNAPSHOT_RV" ]+}++adopt_legacy_secret_state() {+ local secret="$1" expected_rv="$2" annotations_exist="$3" existing_stamp="$4" adopted_at="$5"+ python3 -c 'import json, sys+rv, annotations_exist, existing_stamp, adopted_at = sys.argv[1:]+state = {"clerum.io/gfs-dsn-state": "ready"}+if not existing_stamp:+ state["clerum.io/gfs-dsn-rotated-at"] = adopted_at+op = {"op": "add", "path": "/metadata/annotations", "value": state}+if annotations_exist == "yes":+ op = {"op": "add", "path": "/metadata/annotations/clerum.io~1gfs-dsn-state", "value": "ready"}+ops = [{"op": "test", "path": "/metadata/resourceVersion", "value": rv}, op]+if annotations_exist == "yes" and not existing_stamp:+ ops.append({"op": "add", "path": "/metadata/annotations/clerum.io~1gfs-dsn-rotated-at", "value": adopted_at})+print(json.dumps(ops))' "$expected_rv" "$annotations_exist" "$existing_stamp" "$adopted_at" \+ | kc -n "$GFS_NS" patch secret "$secret" --type=json --patch-file=/dev/stdin >/dev/null 2>&1+}++gfs_candidate_patch() {+ local transition="$1"+ python3 -c 'import base64, datetime, json, sys+transition = sys.argv[1]+candidate = base64.b64encode(sys.stdin.buffer.read()).decode()+state_path = "/metadata/annotations/clerum.io~1gfs-dsn-state"+pending_path = "/data/pending-connection-string"+ops = []+if transition == "claim":+ ops = [+ {"op": "test", "path": state_path, "value": "pending"},+ {"op": "test", "path": pending_path, "value": candidate},+ {"op": "replace", "path": state_path, "value": "applying"},+ ]+elif transition == "promote":+ stamp = datetime.datetime.now(datetime.timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")+ ops = [+ {"op": "test", "path": state_path, "value": "applying"},+ {"op": "test", "path": pending_path, "value": candidate},+ {"op": "add", "path": "/data/connection-string", "value": candidate},+ {"op": "remove", "path": pending_path},+ {"op": "replace", "path": state_path, "value": "rollout-pending"},+ {"op": "add", "path": "/metadata/annotations/clerum.io~1gfs-dsn-rotated-at", "value": stamp},+ ]+elif transition == "rollback":+ ops = [+ {"op": "test", "path": state_path, "value": "applying"},+ {"op": "test", "path": pending_path, "value": candidate},+ {"op": "remove", "path": pending_path},+ {"op": "replace", "path": state_path, "value": "ready"},+ ]+elif transition == "release":+ ops = [+ {"op": "test", "path": state_path, "value": "applying"},+ {"op": "test", "path": pending_path, "value": candidate},+ {"op": "replace", "path": state_path, "value": "pending"},+ ]+else:+ raise SystemExit(2)+print(json.dumps(ops))' "$transition"+}++stage_secret_candidate() {+ local secret="$1" candidate rv data_exists staging_err+ staging_err="$(mktemp)"+ candidate="$(cat)"+ rv="$(secret_resource_version "$secret")" || { rm -f "$staging_err"; return 1; }+ data_exists="$(kc -n "$GFS_NS" get secret "$secret" \+ -o 'go-template={{if .data}}yes{{else}}no{{end}}')" || { rm -f "$staging_err"; return 1; }+ if printf '%s' "$candidate" | python3 -c 'import base64, json, sys+rv, data_exists = sys.argv[1:]+candidate = base64.b64encode(sys.stdin.buffer.read()).decode()+state_path = "/metadata/annotations/clerum.io~1gfs-dsn-state"+data_op = {"op": "add", "path": "/data/pending-connection-string", "value": candidate}+if data_exists == "no":+ data_op = {"op": "add", "path": "/data", "value": {"pending-connection-string": candidate}}+print(json.dumps([+ {"op": "test", "path": "/metadata/resourceVersion", "value": rv},+ {"op": "test", "path": state_path, "value": "ready"},+ data_op,+ {"op": "replace", "path": state_path, "value": "pending"},+]))' "$rv" "$data_exists" \+ | kc -n "$GFS_NS" patch secret "$secret" --type=json --patch-file=/dev/stdin 2>"$staging_err" >/dev/null; then+ rm -f "$staging_err"+ unset candidate+ return 0+ fi+ if [ -s "$staging_err" ]; then+ printf '[gfs-credential-secret] staging candidate on %s/%s failed: %s\n' \+ "$GFS_NS" "$secret" "$(cat "$staging_err")" >&2+ fi+ rm -f "$staging_err"+ unset candidate+ return 1+}++# The CAS patches lose races by design, but a non-CAS failure (RBAC, API+# server) must not read as contention: surface the captured error text so+# callers' "another operation won" diagnostics stay truthful.+candidate_patch_apply() {+ local op="$1" secret="$2" out+ if out="$(gfs_candidate_patch "$op" \+ | kc -n "$GFS_NS" patch secret "$secret" --type=json --patch-file=/dev/stdin 2>&1 >/dev/null)"; then+ return 0+ fi+ printf '[gfs-credential-secret] %s candidate patch on %s/%s failed: %s\n' \+ "$op" "$GFS_NS" "$secret" "$out" >&2+ return 1+}++claim_secret_candidate() {+ candidate_patch_apply claim "$1"+}++promote_secret_candidate() {+ candidate_patch_apply promote "$1"+}++clear_secret_candidate() {+ candidate_patch_apply rollback "$1"+}++release_abandoned_candidate() {+ candidate_patch_apply release "$1"+}++claim_secret_rollout() {+ local secret="$1" expected_rotated_at="$2" expected_state="$3"+ python3 -c 'import json, sys+state, stamp = sys.argv[1:]+print(json.dumps([+ {"op": "test", "path": "/metadata/annotations/clerum.io~1gfs-dsn-state", "value": state},+ {"op": "test", "path": "/metadata/annotations/clerum.io~1gfs-dsn-rotated-at", "value": stamp},+ {"op": "replace", "path": "/metadata/annotations/clerum.io~1gfs-dsn-state", "value": "rollout-running"},+]))' "$expected_state" "$expected_rotated_at" \+ | kc -n "$GFS_NS" patch secret "$secret" --type=json --patch-file=/dev/stdin >/dev/null+}++mark_secret_rollout_ready() {+ local secret="$1" expected_rotated_at="$2" expected_state="$3"+ python3 -c 'import json, sys+state, stamp = sys.argv[1:]+print(json.dumps([+ {"op": "test", "path": "/metadata/annotations/clerum.io~1gfs-dsn-state", "value": state},+ {"op": "test", "path": "/metadata/annotations/clerum.io~1gfs-dsn-rotated-at", "value": stamp},+ {"op": "replace", "path": "/metadata/annotations/clerum.io~1gfs-dsn-state", "value": "ready"},+]))' "$expected_state" "$expected_rotated_at" \+ | kc -n "$GFS_NS" patch secret "$secret" --type=json --patch-file=/dev/stdin >/dev/null+}diff --git a/deploy/scripts/lib/gfs-dsn-probe.sh b/deploy/scripts/lib/gfs-dsn-probe.shnew file mode 100644index 000000000..fb0f950b0--- /dev/null+++ b/deploy/scripts/lib/gfs-dsn-probe.sh@@ -0,0 +1,91 @@+#!/usr/bin/env bash+# Validate a persisted GFSC connection URI from stdin. Connection material+# never enters argv or the environment.++gfs_dsn_validate() {+ local expected_role="$1" expected_host="$2" expected_port="$3" expected_db="$4"+ python3 -c '+import sys+import unicodedata+import re+from urllib.parse import unquote, urlsplit++expected_role, expected_host, expected_port, expected_db = sys.argv[1:]+try:+ raw = sys.stdin.read()+ if not raw or "\\" in raw or any(ch.isspace() or unicodedata.category(ch).startswith("C") for ch in raw):+ raise ValueError+ parsed = urlsplit(raw)+ _userinfo, separator, _host = parsed.netloc.rpartition("@")+ password = unquote(parsed.password or "")+ valid = (+ parsed.scheme in ("postgres", "postgresql")+ and bool(separator)+ and unquote(parsed.username or "") == expected_role+ and bool(re.fullmatch(r"[0-9a-f]{48}", password))+ and parsed.hostname == expected_host+ and parsed.port == int(expected_port)+ and unquote(parsed.path.removeprefix("/")) == expected_db+ and not parsed.query+ and not parsed.fragment+ )+except (ValueError, UnicodeError):+ valid = False+if not valid:+ raise SystemExit(1)+' "$expected_role" "$expected_host" "$expected_port" "$expected_db"+}++gfs_dsn_password() {+ python3 -c '+import sys+import re+from urllib.parse import unquote, urlsplit+value = unquote(urlsplit(sys.stdin.read()).password or "")+if not re.fullmatch(r"[0-9a-f]{48}", value):+ raise SystemExit(1)+print(value, end="")+'+}++gfs_dsn_authenticates_as() {+ local dsn="$1" expected_role="$2" actual rc+ printf '%s' "$dsn" | gfs_dsn_validate \+ "$expected_role" "$PG_HOST" "$PG_PORT" "$PG_DB" || return 1++ # Authenticate through the same Service DNS and SCRAM path used by GFSC.+ # The connection string stays on stdin; the fixed program emits only the+ # authenticated role and intentionally suppresses connection error details.+ actual="$(printf '%s' "$dsn" | kc -n "$PG_NS" exec -i "$PG_PROBE_DEPLOY" -- node -e '+const { Client } = require("pg");+let raw = "";+process.stdin.on("data", chunk => { raw += chunk });+process.stdin.on("end", async () => {+ const client = new Client({ connectionString: raw, connectionTimeoutMillis: 5000 });+ try {+ await client.connect();+ const result = await client.query("SELECT current_user");+ process.stdout.write(result.rows[0].current_user);+ } catch (error) {+ if (error && (error.code === "28P01" || error.code === "28000")) {+ process.stdout.write("GFS_DSN_AUTH_REJECTED");+ process.exitCode = 41;+ } else {+ process.exitCode = 42;+ }+ } finally {+ await client.end().catch(() => undefined);+ }+});' 2>/dev/null)" && rc=0 || rc=$?+ if [ "$rc" -ne 0 ]; then+ # A fixed marker plus the remote process exit code identifies a completed+ # authentication rejection. Kubernetes API, exec-stream, pod readiness,+ # and transport failures are unavailable, never bad credentials.+ if [ "$rc" -eq 41 ] && [ "$actual" = GFS_DSN_AUTH_REJECTED ]; then+ return 1+ fi+ return 2+ fi+ actual="${actual//[[:space:]]/}"+ [ "$actual" = "$expected_role" ]+}diff --git a/deploy/scripts/preflight-gfs-db-reset.sh b/deploy/scripts/preflight-gfs-db-reset.shnew file mode 100755index 000000000..ab0f7bb6b--- /dev/null+++ b/deploy/scripts/preflight-gfs-db-reset.sh@@ -0,0 +1,45 @@+#!/usr/bin/env bash+# Prove that active GFS credentials can be restored after PostgreSQL recreation.+# This preflight intentionally inspects Kubernetes metadata only: it must remain+# usable when PostgreSQL is unavailable or corrupt.+set -euo pipefail++CONTEXT="${CONTEXT:?set CONTEXT to the target kube-context}"+ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"+GFS_NS="${GFS_NS:-gfs}"+PG_HOST="${PG_HOST:-control-postgres.control-plane.svc.cluster.local}"+PG_PORT="${PG_PORT:-5432}"+PG_DB="${PG_DB:-profiles}"++# shellcheck source=/dev/null+source "$ROOT/deploy/scripts/lib/gfs-dsn-probe.sh"+# shellcheck source=/dev/null+source "$ROOT/deploy/scripts/lib/gfs-credential-secret.sh"++kc() { kubectl --context="$CONTEXT" "$@"; }+fail() { printf '[preflight-gfs-db-reset] ERROR: %s\n' "$*" >&2; exit 1; }++validate_restorable_secret() {+ local secret="$1" expected_role="$2"++ load_secret_snapshot "$secret" \+ || fail "cannot read a valid snapshot for ${GFS_NS}/${secret}"+ [ "$GFS_SNAPSHOT_STATE" = "ready" ] \+ || fail "${GFS_NS}/${secret} is not in ready state"+ [ -z "$GFS_SNAPSHOT_PENDING" ] \+ || fail "${GFS_NS}/${secret} has a pending credential"+ [ -n "$GFS_SNAPSHOT_ACTIVE" ] \+ || fail "${GFS_NS}/${secret} has no active credential to restore"+ printf '%s' "$GFS_SNAPSHOT_ACTIVE" \+ | gfs_dsn_validate "$expected_role" "$PG_HOST" "$PG_PORT" "$PG_DB" \+ || fail "${GFS_NS}/${secret} active credential violates the expected DSN contract"+}++# Migrate only the legacy kubectl apply ownership record. This never reads or+# changes Secret data and makes the active writer credential safe from a later+# overlay apply.+CONTEXT="$CONTEXT" bash "$ROOT/deploy/scripts/apply-gfs-writer-secret.sh"+validate_restorable_secret gfs-controller-db gfs_controller+validate_restorable_secret gfs-controller-reader-db gfs_controller_reader++printf '[preflight-gfs-db-reset] active writer and reader credentials are restorable\n' >&2diff --git a/deploy/scripts/provision-control-api-runtime-roles.sh b/deploy/scripts/provision-control-api-runtime-roles.shindex bbacfd14f..1c4c16ffc 100755--- a/deploy/scripts/provision-control-api-runtime-roles.sh+++ b/deploy/scripts/provision-control-api-runtime-roles.sh@@ -45,30 +45,39 @@ context_is_allowed() {}read_existing_dsn() {- local secret_name="$1"- if ! kctl -n "$PG_NAMESPACE" get secret "$secret_name" >/dev/null 2>&1; then+ local secret_name="$1" snapshot+ if ! snapshot="$(kctl -n "$PG_NAMESPACE" get secret "$secret_name" -o json --ignore-not-found)"; then+ die "cannot inspect $PG_NAMESPACE/$secret_name"+ fi+ if [ -z "$snapshot" ]; thenreturn 0fi- kctl -n "$PG_NAMESPACE" get secret "$secret_name" \- -o 'go-template={{with .data}}{{with index . "connection-string"}}{{. | base64decode}}{{end}}{{end}}'+ printf '%s' "$snapshot" | python3 -c '+import base64+import json+import sys++obj = json.load(sys.stdin)+value = ((obj.get("data") or {}).get("connection-string") or "")+if value:+ sys.stdout.buffer.write(base64.b64decode(value, validate=True))+'}password_from_valid_dsn() {local expected_role="$1"- local dsn="$2"- EXPECTED_ROLE="$expected_role" EXPECTED_HOST="$PG_HOST" EXPECTED_PORT="$PG_PORT" \- EXPECTED_DATABASE="$PG_DATABASE" DSN="$dsn" python3 - <<'PY'-import os+ python3 -c 'import reimport sysfrom urllib.parse import unquote, urlparse-parsed = urlparse(os.environ["DSN"])+expected_role, expected_host, expected_port, expected_database = sys.argv[1:]+parsed = urlparse(sys.stdin.read())expected = {- "role": os.environ["EXPECTED_ROLE"],- "host": os.environ["EXPECTED_HOST"],- "port": int(os.environ["EXPECTED_PORT"]),- "database": os.environ["EXPECTED_DATABASE"],+ "role": expected_role,+ "host": expected_host,+ "port": int(expected_port),+ "database": expected_database,}password = unquote(parsed.password or "")valid = (@@ -76,13 +85,13 @@ valid = (and unquote(parsed.username or "") == expected["role"]and parsed.hostname == expected["host"]and parsed.port == expected["port"]- and parsed.path == f"/{expected['database']}"+ and parsed.path == "/" + expected_databaseand re.fullmatch(r"[0-9a-f]{64}", password) is not None)if not valid:sys.exit(1)sys.stdout.write(password)-PY+' "$expected_role" "$PG_HOST" "$PG_PORT" "$PG_DATABASE"}resolve_password() {@@ -91,7 +100,7 @@ resolve_password() {local existing_dsn passwordexisting_dsn="$(read_existing_dsn "$secret_name")"if [ -n "$existing_dsn" ]; then- if ! password="$(password_from_valid_dsn "$role_name" "$existing_dsn")"; then+ if ! password="$(printf '%s' "$existing_dsn" | password_from_valid_dsn "$role_name")"; thendie "$PG_NAMESPACE/$secret_name contains an invalid runtime DSN; refusing to rotate implicitly"fiprintf '%s' "$password"@@ -101,8 +110,11 @@ resolve_password() {}ensure_secret_exists() {- local secret_name="$1"- if kctl -n "$PG_NAMESPACE" get secret "$secret_name" >/dev/null 2>&1; then+ local secret_name="$1" existing+ if ! existing="$(kctl -n "$PG_NAMESPACE" get secret "$secret_name" -o name --ignore-not-found)"; then+ die "cannot determine whether $PG_NAMESPACE/$secret_name exists"+ fi+ if [ -n "$existing" ]; thenreturn 0fikctl -n "$PG_NAMESPACE" create secret generic "$secret_name" \@@ -148,9 +160,9 @@ reconcile_role() {local role_name="$1"local secret_name="$2"local password dsn+ ensure_secret_exists "$secret_name"password="$(resolve_password "$role_name" "$secret_name")"apply_role_password "$role_name" "$password"- ensure_secret_exists "$secret_name"dsn="postgresql://${role_name}:${password}@${PG_HOST}:${PG_PORT}/${PG_DATABASE}"patch_connection_string "$secret_name" "$dsn"password=''diff --git a/deploy/scripts/provision-gfs-db.sh b/deploy/scripts/provision-gfs-db.shindex 84f1c43a8..7e3d0ca2a 100755--- a/deploy/scripts/provision-gfs-db.sh+++ b/deploy/scripts/provision-gfs-db.sh@@ -1,70 +1,404 @@#!/usr/bin/env bash-# Provision the least-privilege gfs_controller Postgres login for gfsc.-#-# Migration 0048 (gfs permission store) creates the `gfs_controller` role NOLOGIN (SELECT on-# resource/grant/share, INSERT-only on gfs_audit). This script completes the-# deliberate two-step security model: it grants LOGIN + a password and writes-# the real DSN into the `gfs-controller-db` Secret (shipped empty), then rolls-# gfsc so it picks the credential up. gfsc /readyz fails closed until this runs.-#-# CONTEXT-aware (never relies on the current kube-context). Idempotent: re-running-# rotates the password and re-patches the Secret.-#-# Usage:-# CONTEXT=<kube-context> [PG_DEPLOY=deploy/control-postgres] [PG_NS=control-plane] \-# [PG_DB=profiles] [PG_SUPERUSER=postgres] [GFS_NS=gfs] \-# deploy/scripts/provision-gfs-db.sh+# Reconcile or explicitly rotate the two least-privilege GFSC database logins.+# `stage-writer` adopts or validates without rotating; `stage-reader` is+# additive and rolls only a reader recovering a newly committed credential.set -euo pipefail+SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"+# shellcheck source=lib/gfs-dsn-probe.sh+source "${SCRIPT_DIR}/lib/gfs-dsn-probe.sh"+# shellcheck source=lib/gfs-credential-secret.sh+source "${SCRIPT_DIR}/lib/gfs-credential-secret.sh"+# shellcheck source=lib/gfs-credential-rollout.sh+source "${SCRIPT_DIR}/lib/gfs-credential-rollout.sh"+# shellcheck source=lib/gfs-credential-recovery.sh+source "${SCRIPT_DIR}/lib/gfs-credential-recovery.sh"++usage() {+ cat <<'EOF'+Usage: CONTEXT=<kube-context> deploy/scripts/provision-gfs-db.sh <mode>++Modes (required; there is no default):+ stage-writer Validate and atomically adopt/reconcile the existing writer without rotation+ stage-reader Reconcile reader; rollout only to recover a stale deployed reader+ rotate-reader Rotate only the reader credential and restart only gfsc-reader+ rotate-writer Rotate only the writer credential and restart only gfsc-writer+EOF+}+CONTEXT="${CONTEXT:?set CONTEXT to the target kube-context}"+MODE="${1:-}"+[ $# -eq 1 ] || { usage >&2; exit 2; }+case "$MODE" in+ stage-writer|stage-reader|rotate-reader|rotate-writer) ;;+ *) usage >&2; exit 2 ;;+esac+PG_NS="${PG_NS:-control-plane}"PG_DEPLOY="${PG_DEPLOY:-deploy/control-postgres}"+PG_PROBE_DEPLOY="${PG_PROBE_DEPLOY:-deploy/control-api}"PG_DB="${PG_DB:-profiles}"PG_SUPERUSER="${PG_SUPERUSER:-postgres}"PG_HOST="${PG_HOST:-control-postgres.control-plane.svc.cluster.local}"PG_PORT="${PG_PORT:-5432}"GFS_NS="${GFS_NS:-gfs}"-GFS_DB_SECRET="${GFS_DB_SECRET:-gfs-controller-db}"-GFS_DEPLOY_SELECTOR="${GFS_DEPLOY_SELECTOR:-clerum.io/managed-by=host-context-controller}"+WRITER_SECRET="${GFS_WRITER_DB_SECRET:-gfs-controller-db}"+READER_SECRET="${GFS_READER_DB_SECRET:-gfs-controller-reader-db}"+# Consumed by the sourced, domain-specific rollout helper.+# shellcheck disable=SC2034+ROLLOUT_TIMEOUT="${GFS_ROLLOUT_TIMEOUT:-240s}"kc() { kubectl --context="$CONTEXT" "$@"; }-log() { printf '[provision-gfs-db] %s\n' "$*"; }-# One ATOMIC merge-patch carrying the DSN and the human-readable rotation-# annotation together — no partial state where the credential rotated but the-# breadcrumb (or vice versa) did not. verify-gfs.sh proves pod freshness from-# the Secret's server-side managedFields timestamps, not from this annotation.-write_secret_patch() {- python3 -c 'import json, sys, datetime-stamp = datetime.datetime.now(datetime.timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")-print(json.dumps({- "stringData": {"connection-string": sys.stdin.read()},- "metadata": {"annotations": {"clerum.io/gfs-dsn-rotated-at": stamp}},-}))'+log() { printf '[provision-gfs-db] %s\n' "$*" >&2; }+die() { log "ERROR: $*"; exit 1; }++secret_value() {+ local secret="$1" key="$2" encoded decoded+ if ! encoded="$(kc -n "$GFS_NS" get secret "$secret" -o "jsonpath={.data.${key}}")"; then+ die "cannot read ${GFS_NS}/$secret; refusing to treat an API or RBAC failure as an absent credential"+ fi+ [ -n "$encoded" ] || return 0+ if ! decoded="$(printf '%s' "$encoded" | base64 -d)"; then+ die "${GFS_NS}/$secret contains an invalid $key encoding"+ fi+ printf '%s' "$decoded"+}++secret_dsn() { secret_value "$1" connection-string; }+pending_dsn() { secret_value "$1" pending-connection-string; }+secret_resource_version() {+ kc -n "$GFS_NS" get secret "$1" -o 'jsonpath={.metadata.resourceVersion}'+}++dsn_has_role() {+ local dsn="$1" role="$2"+ printf '%s' "$dsn" | gfs_dsn_validate "$role" "$PG_HOST" "$PG_PORT" "$PG_DB"}-# A URL-safe password (hex — no characters that need DSN escaping).-ROLE_SECRET="$(openssl rand -hex 24)"+dsn_authenticates_as() {+ gfs_dsn_authenticates_as "$1" "$2"+}-log "Granting LOGIN to gfs_controller (rotating password) in ${PG_NS}/${PG_DEPLOY} db=${PG_DB}"-# ALTER ROLE is idempotent; the role must already exist (migration 0048). If it-# does not, fail loud — gfsc cannot work without the permission store role.-kc -n "$PG_NS" exec -i "$PG_DEPLOY" -- psql -v ON_ERROR_STOP=1 -U "$PG_SUPERUSER" -d "$PG_DB" -f - <<SQL-DO \$\$ BEGIN IF NOT EXISTS (SELECT 1 FROM pg_roles WHERE rolname='gfs_controller') THEN RAISE EXCEPTION 'gfs_controller role missing — run control-api migrations (0048) first'; END IF; END \$\$;-\set gfs_role_secret $ROLE_SECRET-SELECT format('ALTER ROLE gfs_controller LOGIN %s %L', 'PASS' || 'WORD', :'gfs_role_secret') \gexec+verify_role_contract() {+ local role="$1" kind="$2" login_required="${3:-true}"+ log "Verifying ${kind} role attributes and privilege boundary"+ kc -n "$PG_NS" exec -i "$PG_DEPLOY" -- psql -v ON_ERROR_STOP=1 -U "$PG_SUPERUSER" -d "$PG_DB" -v role_name="$role" -v role_kind="$kind" -v login_required="$login_required" -f - <<'SQL'+SELECT EXISTS (+ SELECT 1 FROM pg_roles+ WHERE rolname = :'role_name'+ AND ((:'login_required' = 'true' AND rolcanlogin)+ OR (:'login_required' = 'false' AND NOT rolcanlogin))+ AND NOT rolsuper AND NOT rolcreatedb AND NOT rolcreaterole+ AND NOT rolreplication AND NOT rolbypassrls+ AND NOT rolinherit+ AND NOT EXISTS (+ SELECT 1 FROM pg_auth_members WHERE member = pg_roles.oid+ )+) AS role_ok \gset+\if :role_ok+\else+SELECT 1/0;+\endif+SELECT (:'role_kind' <> 'reader' OR (+ has_table_privilege(:'role_name', 'gfs_resources', 'SELECT')+ AND has_table_privilege(:'role_name', 'gfs_grants', 'SELECT')+ AND has_table_privilege(:'role_name', 'gfs_shares', 'SELECT')+ AND has_table_privilege(:'role_name', 'gfs_audit', 'INSERT')+ AND has_sequence_privilege(:'role_name', 'gfs_audit_sequence_no_seq', 'USAGE')+ AND has_sequence_privilege(:'role_name', 'gfs_audit_sequence_no_seq', 'SELECT')+ AND NOT has_sequence_privilege(:'role_name', 'gfs_audit_sequence_no_seq', 'UPDATE')+ AND NOT has_any_column_privilege(:'role_name', 'gfs_resources', 'INSERT,UPDATE,REFERENCES')+ AND NOT has_table_privilege(:'role_name', 'gfs_resources', 'DELETE,TRUNCATE,TRIGGER')+ AND NOT has_any_column_privilege(:'role_name', 'gfs_grants', 'INSERT,UPDATE,REFERENCES')+ AND NOT has_table_privilege(:'role_name', 'gfs_grants', 'DELETE,TRUNCATE,TRIGGER')+ AND NOT has_any_column_privilege(:'role_name', 'gfs_shares', 'INSERT,UPDATE,REFERENCES')+ AND NOT has_table_privilege(:'role_name', 'gfs_shares', 'DELETE,TRUNCATE,TRIGGER')+ AND NOT has_any_column_privilege(:'role_name', 'gfs_blob_manifests', 'SELECT,INSERT,UPDATE,REFERENCES')+ AND NOT has_table_privilege(:'role_name', 'gfs_blob_manifests', 'DELETE,TRUNCATE,TRIGGER')+ AND NOT has_any_column_privilege(:'role_name', 'gfs_audit', 'SELECT,UPDATE,REFERENCES')+ AND NOT has_table_privilege(:'role_name', 'gfs_audit', 'DELETE,TRUNCATE,TRIGGER')+)) AS privilege_ok \gset+\if :privilege_ok+\else+SELECT 1/0;+\endif+SELECT (:'role_kind' <> 'writer' OR (+ has_table_privilege(:'role_name', 'gfs_resources', 'SELECT')+ AND has_table_privilege(:'role_name', 'gfs_resources', 'INSERT')+ AND has_table_privilege(:'role_name', 'gfs_resources', 'UPDATE')+ AND NOT has_any_column_privilege(:'role_name', 'gfs_resources', 'REFERENCES')+ AND NOT has_table_privilege(:'role_name', 'gfs_resources', 'DELETE,TRUNCATE,TRIGGER')+ AND has_table_privilege(:'role_name', 'gfs_blob_manifests', 'SELECT')+ AND has_table_privilege(:'role_name', 'gfs_blob_manifests', 'INSERT')+ AND has_table_privilege(:'role_name', 'gfs_blob_manifests', 'UPDATE')+ AND has_table_privilege(:'role_name', 'gfs_blob_manifests', 'DELETE')+ AND NOT has_any_column_privilege(:'role_name', 'gfs_blob_manifests', 'REFERENCES')+ AND NOT has_table_privilege(:'role_name', 'gfs_blob_manifests', 'TRUNCATE,TRIGGER')+ AND has_table_privilege(:'role_name', 'gfs_grants', 'SELECT')+ AND NOT has_any_column_privilege(:'role_name', 'gfs_grants', 'INSERT,UPDATE,REFERENCES')+ AND NOT has_table_privilege(:'role_name', 'gfs_grants', 'DELETE,TRUNCATE,TRIGGER')+ AND has_table_privilege(:'role_name', 'gfs_shares', 'SELECT')+ AND NOT has_any_column_privilege(:'role_name', 'gfs_shares', 'INSERT,UPDATE,REFERENCES')+ AND NOT has_table_privilege(:'role_name', 'gfs_shares', 'DELETE,TRUNCATE,TRIGGER')+ AND has_table_privilege(:'role_name', 'gfs_audit', 'INSERT')+ AND has_sequence_privilege(:'role_name', 'gfs_audit_sequence_no_seq', 'USAGE')+ AND has_sequence_privilege(:'role_name', 'gfs_audit_sequence_no_seq', 'SELECT')+ AND NOT has_sequence_privilege(:'role_name', 'gfs_audit_sequence_no_seq', 'UPDATE')+ AND NOT has_any_column_privilege(:'role_name', 'gfs_audit', 'SELECT,UPDATE,REFERENCES')+ AND NOT has_table_privilege(:'role_name', 'gfs_audit', 'DELETE,TRUNCATE,TRIGGER')+)) AS writer_privilege_ok \gset+\if :writer_privilege_ok+\else+SELECT 1/0;+\endif+SELECT (+ NOT has_table_privilege(:'role_name', 'control_admin_users', 'SELECT')+ AND has_column_privilege(:'role_name', 'control_admin_users', 'id', 'SELECT')+ AND has_column_privilege(:'role_name', 'control_admin_users', 'status', 'SELECT')+ AND NOT EXISTS (+ SELECT 1+ FROM information_schema.columns+ WHERE table_schema = 'public'+ AND table_name = 'control_admin_users'+ AND column_name NOT IN ('id', 'status')+ AND has_column_privilege(:'role_name', 'control_admin_users', column_name, 'SELECT')+ )+ AND NOT has_any_column_privilege(:'role_name', 'control_admin_users',+ 'INSERT,UPDATE,REFERENCES')+ AND NOT has_table_privilege(:'role_name', 'control_admin_users',+ 'DELETE,TRUNCATE,TRIGGER')+ AND NOT has_table_privilege(:'role_name', 'team_members', 'SELECT')+ AND has_column_privilege(:'role_name', 'team_members', 'team_id', 'SELECT')+ AND has_column_privilege(:'role_name', 'team_members', 'user_id', 'SELECT')+ AND has_column_privilege(:'role_name', 'team_members', 'status', 'SELECT')+ AND NOT EXISTS (+ SELECT 1+ FROM information_schema.columns+ WHERE table_schema = 'public'+ AND table_name = 'team_members'+ AND column_name NOT IN ('team_id', 'user_id', 'status')+ AND has_column_privilege(:'role_name', 'team_members', column_name, 'SELECT')+ )+ AND NOT has_any_column_privilege(:'role_name', 'team_members',+ 'INSERT,UPDATE,REFERENCES')+ AND NOT has_table_privilege(:'role_name', 'team_members',+ 'DELETE,TRUNCATE,TRIGGER')+) AS subject_privilege_ok \gset+\if :subject_privilege_ok+\else+SELECT 1/0;+\endifSQL+}++verify_role() {+ local role="$1" kind="$2" ref_name=WRITER_SECRET persisted+ [ "$kind" = reader ] && ref_name=READER_SECRET+ persisted="$(secret_dsn "${!ref_name}")"+ dsn_has_role "$persisted" "$role" || die "persisted ${kind} candidate rejected"+ require_authenticated_dsn "$persisted" "$role" "persisted ${kind}"+ verify_role_contract "$role" "$kind"+}++set_role_password() {+ local role="$1" value="$2"+ {+ printf '\\set role_name %s\n' "$role"+ printf '\\set role_secret %s\n' "$value"+ cat <<'SQL'+SELECT CASE+ WHEN EXISTS (SELECT 1 FROM pg_roles WHERE rolname = :'role_name')+ THEN format('ALTER ROLE %I LOGIN PASSWORD %L', :'role_name', :'role_secret')+ ELSE 'SELECT 1/0'+END \gexec+SQL+ } | kc -n "$PG_NS" exec -i "$PG_DEPLOY" -- \+ psql -Xq -v ON_ERROR_STOP=1 -U "$PG_SUPERUSER" -d "$PG_DB" -f - 2>/dev/null+}++disable_role_login() {+ local role="$1"+ printf 'ALTER ROLE %s NOLOGIN;\n' "$role" \+ | kc -n "$PG_NS" exec -i "$PG_DEPLOY" -- psql -Xq -v ON_ERROR_STOP=1 -U "$PG_SUPERUSER" -d "$PG_DB" >/dev/null+}++role_can_login() {+ printf "SELECT rolcanlogin FROM pg_roles WHERE rolname = :'role_name';\n" \+ | kc -n "$PG_NS" exec -i "$PG_DEPLOY" -- psql -XAtq -v ON_ERROR_STOP=1 \+ -U "$PG_SUPERUSER" -d "$PG_DB" -v role_name="$1" -f -+}++ensure_pending_candidate() {+ local role="$1" secret="$2" candidate password state+ candidate="$(pending_dsn "$secret")"+ if [ -n "$candidate" ]; then+ state="$(gfs_secret_state "$secret")"+ [ "$state" = pending ] || die "${GFS_NS}/${secret} candidate is owned by state ${state}; refusing concurrent adoption"+ dsn_has_role "$candidate" "$role" || die "${GFS_NS}/${secret} contains an invalid pending candidate"+ log "Resuming persisted pending candidate for ${secret}"+ printf '%s' "$candidate"+ return 0+ fi+ password="$(openssl rand -hex 24)"+ candidate="postgresql://${role}:${password}@${PG_HOST}:${PG_PORT}/${PG_DB}"+ printf '%s' "$candidate" | stage_secret_candidate "$secret" \+ || die "failed to stage credential candidate; another operation or API update won the state transition"+ printf '%s' "$candidate"+}++promote_candidate() {+ printf '%s' "$2" | promote_secret_candidate "$1"+}++rollback_uncommitted_candidate() {+ local role="$1" secret="$2" active="$3" candidate="$4" previous auth_state+ [ "$(gfs_secret_state "$secret")" = applying ] || return 1+ [ "$(pending_dsn "$secret")" = "$candidate" ] || return 1+ if [ -n "$active" ]; then+ previous="$(printf '%s' "$active" | gfs_dsn_password)" || return 1+ set_role_password "$role" "$previous" || return 1+ auth_state="$(dsn_authentication_state "$active" "$role")"+ [ "$auth_state" = authenticated ] || return 1+ else+ disable_role_login "$role" || return 1+ fi+ printf '%s' "$candidate" | clear_secret_candidate "$secret"+}-DSN="postgresql://gfs_controller:${ROLE_SECRET}@${PG_HOST}:${PG_PORT}/${PG_DB}"+reconcile_credential() {+ local role="$1" kind="$2" secret="$3" deployment="$4" rotate="$5"+ local active pending candidate value login_state state rotated recovery candidate_applied=false auth_state+ ensure_secret_state "$secret" || die "cannot initialize credential state for ${GFS_NS}/${secret}"+ active="$(secret_dsn "$secret")"+ pending="$(pending_dsn "$secret")"+ state="$(gfs_secret_state "$secret")"-log "Writing DSN into ${GFS_NS}/${GFS_DB_SECRET}.connection-string (with rotation annotation, atomically)"-printf '%s' "$DSN" | write_secret_patch | kc -n "$GFS_NS" patch secret "$GFS_DB_SECRET" --type=merge --patch-file=/dev/stdin >/dev/null+ if [ "$state" = applying ]; then+ recovery="$(recover_abandoned_applying "$role" "$secret" "$active" "$pending")"+ if [ "$recovery" = applied ]; then+ candidate="$pending"+ candidate_applied=true+ elif [ "$recovery" = pending ]; then+ state=pending+ else+ die "unexpected abandoned credential recovery result"+ fi+ fi++ if [ -z "$pending" ] && [ -n "$active" ]; then+ dsn_has_role "$active" "$role" || die "${GFS_NS}/${secret} contains an invalid committed DSN"+ authenticate_or_restore_nologin "$role" "$kind" "$active" "$state" "${GFS_NS}/${secret}"+ if [ "$state" = rollout-pending ] || [ "$state" = rollout-running ]; then+ if credential_rollout_required "$deployment" "$secret" "$state"; then+ log "Resuming incomplete ${deployment} rollout without rotating again"+ complete_rollout "$secret" "$deployment"+ verify_role "$role" "$kind"+ return 0+ fi+ log "${deployment} does not consume ${secret} yet; preserving ${state} until post-overlay reconciliation"+ verify_role "$role" "$kind"+ return 0+ fi+ if credential_rollout_required "$deployment" "$secret" "$state"; then+ log "Recovering stale ${deployment} pods without rotating again"+ complete_rollout "$secret" "$deployment"+ verify_role "$role" "$kind"+ return 0+ fi+ if [ "$rotate" = false ]; then+ log "Preserving existing valid ${kind} credential"+ verify_role "$role" "$kind"+ return 0+ fi+ fi++ if [ -z "$pending" ] && [ -z "$active" ]; then+ login_state="$(role_can_login "$role")"+ [ "$login_state" = f ] || die "${role} is LOGIN while ${GFS_NS}/${secret} is empty; refusing an unrecoverable overwrite"+ fi++ if [ "$candidate_applied" = false ]; then+ candidate="$(ensure_pending_candidate "$role" "$secret")"+ printf '%s' "$candidate" | claim_secret_candidate "$secret" \+ || die "credential candidate was claimed by another operation; no database change was attempted"+ fi+ value="$(printf '%s' "$candidate" | gfs_dsn_password)" || die "pending candidate secret is invalid"+ if [ "$candidate_applied" = false ]; then+ if ! set_role_password "$role" "$value"; then+ die "database role update failed; applying candidate retained for explicit recovery"+ fi+ fi+ auth_state="$(dsn_authentication_state "$candidate" "$role")"+ if [ "$auth_state" != authenticated ] || ! verify_role_contract "$role" "$kind"; then+ if rollback_uncommitted_candidate "$role" "$secret" "$active" "$candidate"; then+ die "candidate verification failed; previous credential restored"+ fi+ die "candidate verification failed and compensation could not complete; pending candidate retained for recovery"+ fi+ if ! promote_candidate "$secret" "$candidate"; then+ die "candidate authenticated but promotion did not converge; confirm the prior process ended, then retry with GFS_RECOVER_ABANDONED_STATE=true"+ fi+ unset candidate value+ verify_role "$role" "$kind"+ if [ "$rotate" = true ] || deployment_uses_secret "$deployment" "$secret"; then+ complete_rollout "$secret" "$deployment"+ else+ log "${deployment} does not consume ${secret} yet; credential staged without rollout"+ rotated="$(gfs_secret_rotated_at "$secret")"+ mark_secret_rollout_ready "$secret" "$rotated" rollout-pending \+ || die "staged credential state was superseded; refusing a stale completion"+ fi+}++stage_writer() {+ local adopted_at+ load_secret_snapshot "$WRITER_SECRET" \+ || die "cannot read a consistent ${GFS_NS}/${WRITER_SECRET} snapshot"+ if [ -n "$GFS_SNAPSHOT_STATE" ]; then+ reconcile_credential gfs_controller writer "$WRITER_SECRET" gfsc-writer false+ return 0+ fi++ [ -n "$GFS_SNAPSHOT_ACTIVE" ] || die "${GFS_NS}/${WRITER_SECRET} has no writer credential to adopt"+ [ -z "$GFS_SNAPSHOT_PENDING" ] || die "${GFS_NS}/${WRITER_SECRET} has a legacy pending candidate without lifecycle ownership"+ dsn_has_role "$GFS_SNAPSHOT_ACTIVE" gfs_controller \+ || die "${GFS_NS}/${WRITER_SECRET} contains an invalid legacy writer DSN"+ authenticate_or_restore_nologin gfs_controller writer "$GFS_SNAPSHOT_ACTIVE" \+ "$GFS_SNAPSHOT_STATE" "${GFS_NS}/${WRITER_SECRET} legacy writer"+ verify_role_contract gfs_controller writer++ adopted_at="$GFS_SNAPSHOT_ROTATED_AT"+ [ -n "$adopted_at" ] || adopted_at="$(credential_adoption_timestamp gfsc-writer \+ 'app=gfs-controller,clerum.io/gfsc-role=writer' "$GFS_SNAPSHOT_ACTIVE")"+ adopt_legacy_secret_state "$WRITER_SECRET" "$GFS_SNAPSHOT_RV" "$GFS_SNAPSHOT_ANNOTATIONS" \+ "$GFS_SNAPSHOT_ROTATED_AT" "$adopted_at" \+ || die "legacy writer Secret changed during adoption; retry after confirming the competing operation"++ [ "$(gfs_secret_state "$WRITER_SECRET")" = ready ] \+ || die "legacy writer adoption did not persist ready state"+ [ -z "$(pending_dsn "$WRITER_SECRET")" ] \+ || die "legacy writer adoption observed an unexpected pending candidate"+ [ "$(secret_dsn "$WRITER_SECRET")" = "$GFS_SNAPSHOT_ACTIVE" ] \+ || die "legacy writer adoption changed the committed DSN"+ verify_role gfs_controller writer+ log "Adopted legacy writer credential without rotation or rollout"+}-if kc -n "$GFS_NS" get deployment -l "$GFS_DEPLOY_SELECTOR" -o name 2>/dev/null | grep -q .; then- log "Rolling gfsc so it picks up the new credential"- kc -n "$GFS_NS" rollout restart deployment -l "$GFS_DEPLOY_SELECTOR" >/dev/null- kc -n "$GFS_NS" rollout status deployment -l "$GFS_DEPLOY_SELECTOR" --timeout=120s-else- log "No gfsc deployments yet; DSN is staged for future pods"-fi+case "$MODE" in+ stage-writer)+ stage_writer+ ;;+ stage-reader)+ reconcile_credential gfs_controller_reader reader "$READER_SECRET" gfsc-reader false+ ;;+ rotate-reader)+ log "Explicitly rotating reader credential"+ reconcile_credential gfs_controller_reader reader "$READER_SECRET" gfsc-reader true+ ;;+ rotate-writer)+ log "Explicitly rotating writer credential"+ reconcile_credential gfs_controller writer "$WRITER_SECRET" gfsc-writer true+ ;;+esac-log "Done."+log "Mode ${MODE} completed"diff --git a/deploy/scripts/provision-gfs-runtime.sh b/deploy/scripts/provision-gfs-runtime.shindex 4bdbe99a4..06582c4d7 100755--- a/deploy/scripts/provision-gfs-runtime.sh+++ b/deploy/scripts/provision-gfs-runtime.sh@@ -1,6 +1,8 @@#!/usr/bin/env bashset -euo pipefail+ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"+usage() {cat <<'EOF'Usage:@@ -116,6 +118,71 @@ kctl() {kubectl --context "$CONTEXT" "$@"}+deployment_references_secret() {+ local deployment="$1" secret="$2" refs+ if ! refs="$(kctl -n gfs get deployment "$deployment" -o \+ 'jsonpath={range .spec.template.spec.containers[*].env[*]}{.valueFrom.secretKeyRef.name}{"\n"}{end}' 2>&1)"; then+ grep -qiE 'not ?found' <<<"$refs" && return 1+ die "cannot inspect gfs/${deployment} Secret references: $refs"+ fi+ grep -Fxq "$secret" <<<"$refs"+}++wait_for_gfsc_secret_references() {+ local deadline=$((SECONDS + 240))+ while [ "$SECONDS" -lt "$deadline" ]; do+ if deployment_references_secret gfsc-writer gfs-controller-db && \+ deployment_references_secret gfsc-reader gfs-controller-reader-db; then+ return 0+ fi+ log "Waiting for HCC to publish writer/reader deployments with their dedicated Secrets"+ sleep 5+ done+ kctl -n gfs get globalfilesystem gfs -o yaml || true+ kctl -n gfs get deployments,pods -o wide || true+ die "GFSC deployments did not adopt their dedicated Secrets before timeout"+}++wait_for_globalfilesystem_ready() {+ local deadline=$((SECONDS + 240)) phase=""+ while [ "$SECONDS" -lt "$deadline" ]; do+ phase="$(kctl -n gfs get globalfilesystem gfs -o 'jsonpath={.status.phase}' 2>/dev/null || true)"+ if [ "$phase" = "Ready" ]; then+ log "GlobalFileSystem/gfs is Ready"+ return 0+ fi+ log "GlobalFileSystem/gfs phase=${phase:-<empty>}; waiting"+ sleep 5+ done+ kctl -n gfs get globalfilesystem gfs -o yaml || true+ kctl -n gfs get deploy,pods,pvc,svc,networkpolicy -o wide || true+ die "GlobalFileSystem/gfs did not become Ready before timeout"+}++finalize_credentials_after_overlay() {+ local out+ if out="$(kctl -n gfs get globalfilesystem gfs -o name 2>&1)"; then+ :+ elif grep -qiE 'not ?found' <<<"$out"; then+ log "GlobalFileSystem/gfs is not installed; leaving credentials staged for the future runtime"+ return 0+ else+ die "cannot determine GlobalFileSystem/gfs presence: $out"+ fi++ log "Waiting for the post-overlay HCC rollout"+ kctl -n control-plane rollout status deployment/host-context-controller --timeout=240s+ wait_for_gfsc_secret_references++ log "Finalizing staged GFS credentials after the overlay"+ CONTEXT="$CONTEXT" bash "$ROOT/deploy/scripts/reconcile-gfs-deploy-credentials.sh"++ log "Waiting for the exact GFSC writer and reader rollouts"+ kctl -n gfs rollout status deployment/gfsc-writer --timeout=240s+ kctl -n gfs rollout status deployment/gfsc-reader --timeout=240s+ wait_for_globalfilesystem_ready+}+INSTANCES_DIR="$OVERLAY/instances"log "Checking required GFS platform resources"@@ -131,46 +198,15 @@ elsebash scripts/minikube/sync-auth-key.sh --context "$CONTEXT"fi-log "Provisioning gfsc database access"-CONTEXT="$CONTEXT" bash deploy/scripts/provision-gfs-db.sh-if [ "$SKIP_INSTANCES" = "1" ]; then- # DB-credential heal ONLY: skip the instances apply AND the- # GlobalFileSystem-Ready wait below. provision-gfs-db.sh already rolled the- # gfsc deployments and waited for their rollout, which is exactly the- # surface this mode changes — entering the CR readiness gate here would- # couple every prod promotion to overall GFS health once the CR exists.+ # Prod promotion does not manage CR instances here. Credential staging was+ # already completed before overlay apply and never triggers a rollout.log "Skipping CRD instances apply and GlobalFileSystem readiness wait (--skip-instances)"- exit 0-fi-if [ -d "$INSTANCES_DIR" ]; then+elif [ -d "$INSTANCES_DIR" ]; thenlog "Applying CRD instances from $INSTANCES_DIR"kctl apply -f "$INSTANCES_DIR"elselog "No instances directory found at $INSTANCES_DIR"- exit 0-fi--if ! kctl -n gfs get globalfilesystem gfs >/dev/null 2>&1; then- log "GlobalFileSystem/gfs not present after instance apply; nothing to wait for"- exit 0fi-log "Waiting for GlobalFileSystem/gfs status.phase=Ready"-deadline=$((SECONDS + 240))-while [ "$SECONDS" -lt "$deadline" ]; do- phase="$(kctl -n gfs get globalfilesystem gfs -o 'jsonpath={.status.phase}' 2>/dev/null || true)"- if [ "$phase" = "Ready" ]; then- log "GlobalFileSystem/gfs is Ready"- log "Waiting for gfsc writer and reader rollouts"- kctl -n gfs rollout status deployment/gfsc-writer --timeout=240s- kctl -n gfs rollout status deployment/gfsc-reader --timeout=240s- exit 0- fi- log "GlobalFileSystem/gfs phase=${phase:-<empty>}; waiting"- sleep 5-done--kctl -n gfs get globalfilesystem gfs -o yaml || true-kctl -n gfs get deploy,pods,pvc,svc,networkpolicy -o wide || true-die "GlobalFileSystem/gfs did not become Ready before timeout"+finalize_credentials_after_overlaydiff --git a/deploy/scripts/reconcile-gfs-deploy-credentials.sh b/deploy/scripts/reconcile-gfs-deploy-credentials.shnew file mode 100755index 000000000..6d821c606--- /dev/null+++ b/deploy/scripts/reconcile-gfs-deploy-credentials.sh@@ -0,0 +1,20 @@+#!/usr/bin/env bash+# One deploy-time entrypoint for writer ownership, bootstrap, and reader staging.+set -euo pipefail++CONTEXT="${CONTEXT:?set CONTEXT to the target kube-context}"+ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"+GFS_NS="${GFS_NS:-gfs}"++CONTEXT="$CONTEXT" bash "$ROOT/deploy/scripts/apply-gfs-writer-secret.sh"+writer_dsn_b64="$(kubectl --context="$CONTEXT" -n "$GFS_NS" get secret gfs-controller-db \+ -o 'jsonpath={.data.connection-string}')" \+ || { printf '[reconcile-gfs-deploy] ERROR: cannot inspect writer Secret\n' >&2; exit 1; }+if [ -z "$writer_dsn_b64" ]; then+ CONTEXT="$CONTEXT" bash "$ROOT/deploy/scripts/provision-gfs-db.sh" rotate-writer+fi+CONTEXT="$CONTEXT" bash "$ROOT/deploy/scripts/provision-gfs-db.sh" stage-writer++kubectl --context="$CONTEXT" apply -f "$ROOT/deploy/base/gfs/gfs-controller-reader-db.yaml" >/dev/null+CONTEXT="$CONTEXT" bash "$ROOT/deploy/scripts/provision-gfs-db.sh" stage-reader+printf '[reconcile-gfs-deploy] writer and reader credentials reconciled\n' >&2diff --git a/deploy/scripts/reset-control-db-storage.sh b/deploy/scripts/reset-control-db-storage.shnew file mode 100755index 000000000..c9865fc82--- /dev/null+++ b/deploy/scripts/reset-control-db-storage.sh@@ -0,0 +1,537 @@+#!/usr/bin/env bash+# Fail-closed destructive boundary for an intentional control-postgres reset.+set -euo pipefail++CONTEXT="${CONTEXT:?set CONTEXT to the target kube-context}"+ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"+NAMESPACE=control-plane+PVC=control-postgres-data+SCRUB_POD=control-postgres-storage-reset+RESET_STATE=control-db-reset-state+EXPECTED_PVC_UID=""+EXPECT_NO_PVC=false+RESUME=false++while [ "$#" -gt 0 ]; do+ case "$1" in+ --expected-pvc-uid)+ EXPECTED_PVC_UID="${2:?--expected-pvc-uid requires a value}"+ shift 2+ ;;+ --expect-no-pvc)+ EXPECT_NO_PVC=true+ shift+ ;;+ --resume)+ RESUME=true+ shift+ ;;+ *)+ printf '[reset-control-db-storage] ERROR: unknown argument: %s\n' "$1" >&2+ exit 2+ ;;+ esac+done++if [ "$EXPECT_NO_PVC" = true ] && [ -n "$EXPECTED_PVC_UID" ]; then+ printf '[reset-control-db-storage] ERROR: choose exactly one PVC expectation\n' >&2+ exit 2+fi+[ "$EXPECT_NO_PVC" = true ] || [ -n "$EXPECTED_PVC_UID" ] \+ || { printf '[reset-control-db-storage] ERROR: --expected-pvc-uid or --expect-no-pvc is required\n' >&2; exit 2; }++kc() { kubectl --context="$CONTEXT" "$@"; }+fail() { printf '[reset-control-db-storage] ERROR: %s\n' "$*" >&2; exit 1; }++deployment_replicas() {+ local namespace="$1" deployment="$2" value+ if ! value="$(kc -n "$namespace" get "deployment/$deployment" -o 'jsonpath={.spec.replicas}' 2>&1)"; then+ case "$namespace $value" in+ 'gfs '*NotFound*)+ fail "gfs deployment ${deployment} not found — this cluster has not adopted the GFS stack, and the control-DB reset requires running gfsc-writer/gfsc-reader for verified restoration (see docs/deploy/minikube.md)"+ ;;+ esac+ fail "cannot capture ${namespace}/${deployment} replicas: ${value}"+ fi+ [[ "$value" =~ ^[0-9]+$ ]] \+ || fail "invalid ${namespace}/${deployment} replica count"+ printf '%s' "$value"+}++wait_for_deployment_pods_gone() {+ local namespace="$1" selector="$2" pods+ pods="$(kc -n "$namespace" get pods -l "$selector" -o name)" \+ || fail "cannot inspect ${namespace} pods selected by ${selector}"+ if [ -n "$pods" ]; then+ kc -n "$namespace" wait --for=delete pod -l "$selector" --timeout=180s >/dev/null \+ || fail "timed out quiescing ${namespace} pods selected by ${selector}"+ fi+}++read_reset_state() {+ local raw+ raw="$(kc -n "$NAMESPACE" get configmap "$RESET_STATE" -o \+ 'jsonpath={.metadata.resourceVersion}{"|"}{.data.stateVersion}{"|"}{.data.phase}{"|"}{.data.originalPvcUid}{"|"}{.data.replacementPvcUid}{"|"}{.data.hccReplicas}{"|"}{.data.workflowReplicas}{"|"}{.data.traceReplicas}{"|"}{.data.writerReplicas}{"|"}{.data.readerReplicas}{"|"}{.data.controlApiReplicas}')" \+ || return 1+ IFS='|' read -r STATE_RV STATE_VERSION STATE_PHASE STATE_ORIGINAL_PVC_UID \+ STATE_REPLACEMENT_PVC_UID STATE_HCC_REPLICAS STATE_WORKFLOW_REPLICAS \+ STATE_TRACE_REPLICAS STATE_WRITER_REPLICAS STATE_READER_REPLICAS \+ STATE_CONTROL_API_REPLICAS <<<"$raw"+ [ -n "$STATE_RV" ] \+ && [ "$STATE_VERSION" = 1 ] \+ && [[ "$STATE_PHASE" =~ ^(authorized|deleting-original|original-deleted|replacement-bound|converged)$ ]] \+ && [ -n "$STATE_ORIGINAL_PVC_UID" ] \+ && [ -n "$STATE_REPLACEMENT_PVC_UID" ] \+ && [[ "$STATE_HCC_REPLICAS" =~ ^[0-9]+$ ]] \+ && [[ "$STATE_WORKFLOW_REPLICAS" =~ ^[0-9]+$ ]] \+ && [[ "$STATE_TRACE_REPLICAS" =~ ^[0-9]+$ ]] \+ && [[ "$STATE_WRITER_REPLICAS" =~ ^[0-9]+$ ]] \+ && [[ "$STATE_READER_REPLICAS" =~ ^[0-9]+$ ]] \+ && [[ "$STATE_CONTROL_API_REPLICAS" =~ ^[1-9][0-9]*$ ]] \+ || fail "${NAMESPACE}/${RESET_STATE} is incomplete or invalid"+}++cas_reset_phase() {+ local expected_phase="$1" next_phase="$2" expected_replacement="$3" next_replacement="$4"+ local patch+ patch="$(python3 - "$STATE_RV" "$expected_phase" "$next_phase" \+ "$STATE_ORIGINAL_PVC_UID" "$expected_replacement" "$next_replacement" <<'PY'+import json+import sys++rv, expected_phase, next_phase, original_uid, expected_replacement, next_replacement = sys.argv[1:]+print(json.dumps([+ {"op": "test", "path": "/metadata/resourceVersion", "value": rv},+ {"op": "test", "path": "/data/stateVersion", "value": "1"},+ {"op": "test", "path": "/data/phase", "value": expected_phase},+ {"op": "test", "path": "/data/originalPvcUid", "value": original_uid},+ {"op": "test", "path": "/data/replacementPvcUid", "value": expected_replacement},+ {"op": "replace", "path": "/data/phase", "value": next_phase},+ {"op": "replace", "path": "/data/replacementPvcUid", "value": next_replacement},+]))+PY+)" || fail "cannot build reset-state compare-and-swap patch"+ kc -n "$NAMESPACE" patch configmap "$RESET_STATE" --type=json -p "$patch" >/dev/null \+ || fail "reset state changed concurrently while advancing ${expected_phase} to ${next_phase}"+ read_reset_state || fail "cannot reload reset state after advancing to ${next_phase}"+ [ "$STATE_PHASE" = "$next_phase" ] \+ && [ "$STATE_REPLACEMENT_PVC_UID" = "$next_replacement" ] \+ || fail "reset-state compare-and-swap did not persist ${next_phase}"+}++# The scrub pod can only mount the claim by name, so the authorized original+# object is frozen first: a finalizer added under a UID+resourceVersion+# compare-and-swap guarantees the name cannot be reused by a replacement+# between the UID check and the scrub mount. The API server refuses new+# finalizers on terminating objects and refuses a same-name create while the+# pinned object exists, so a pinned claim is provably the authorized original.+RESET_SCRUB_FINALIZER=clerum.io/control-db-reset-scrub++original_finalizer_step() {+ local mode="$1" expected_uid="$2" claim_json+ claim_json="$(kc -n "$NAMESPACE" get pvc "$PVC" -o json --ignore-not-found)" \+ || return 1+ RESET_CLAIM_JSON="$claim_json" python3 - "$mode" "$expected_uid" "$RESET_SCRUB_FINALIZER" <<'PY'+import json+import os+import sys++mode, expected_uid, finalizer = sys.argv[1:]+raw = os.environ.get("RESET_CLAIM_JSON", "").strip()+if not raw:+ print("absent")+ sys.exit(0)+meta = json.loads(raw).get("metadata") or {}+if meta.get("uid", "") != expected_uid:+ print("replaced")+ sys.exit(0)+finalizers = list(meta.get("finalizers") or [])+present = finalizer in finalizers+if mode == "ensure" and meta.get("deletionTimestamp"):+ print("terminating")+ sys.exit(0)+if present == (mode == "ensure"):+ print("done")+ sys.exit(0)+if mode == "ensure":+ value = finalizers + [finalizer]+else:+ value = [item for item in finalizers if item != finalizer]+patch = [+ {"op": "test", "path": "/metadata/uid", "value": expected_uid},+ {"op": "test", "path": "/metadata/resourceVersion", "value": meta.get("resourceVersion", "")},+ {"op": "replace" if finalizers else "add", "path": "/metadata/finalizers", "value": value},+]+print("patch " + json.dumps(patch))+PY+}++sync_original_finalizer() {+ # ensure -> pinned (scrub may mount by name) or skip (original gone/replaced).+ # remove -> done. Terminating or persistently contended claims fail closed.+ local mode="$1" expected_uid="$2" attempt step+ for attempt in 1 2 3 4 5; do+ step="$(original_finalizer_step "$mode" "$expected_uid")" \+ || fail "cannot inspect ${NAMESPACE}/${PVC} while settling its scrub finalizer"+ case "$step" in+ done)+ if [ "$mode" = ensure ]; then printf pinned; else printf done; fi+ return 0+ ;;+ absent|replaced)+ if [ "$mode" = ensure ]; then printf skip; else printf done; fi+ return 0+ ;;+ terminating)+ fail "authorized original ${NAMESPACE}/${PVC} is terminating; if this reset just issued its delete, retry --resume after termination completes — otherwise an external delete is in flight and scrubbing an unpinnable claim is refused"+ ;;+ "patch "*)+ # A lost compare-and-swap means the claim changed concurrently; the+ # next iteration re-reads and re-adjudicates the live object.+ kc -n "$NAMESPACE" patch pvc "$PVC" --type=json -p "${step#patch }" >/dev/null || true+ ;;+ *)+ fail "unexpected scrub-finalizer state for ${NAMESPACE}/${PVC}: ${step}"+ ;;+ esac+ done+ fail "cannot settle the ${RESET_SCRUB_FINALIZER} finalizer on ${NAMESPACE}/${PVC} after repeated concurrent changes"+}++quiesce_gfs() {+ # HCC owns GFSC and must stop first so its reconciler cannot undo the+ # zero-replica boundary while PostgreSQL storage is being removed.+ kc -n control-plane scale deployment/host-context-controller --replicas=0 >/dev/null \+ || fail "cannot quiesce control-plane/host-context-controller"+ wait_for_deployment_pods_gone control-plane app=host-context-controller+ kc -n control-plane scale deployment/workflow-recipes deployment/trace-maintenance-worker --replicas=0 >/dev/null \+ || fail "cannot quiesce PostgreSQL-dependent control-plane workers"+ wait_for_deployment_pods_gone control-plane app=workflow-recipes+ wait_for_deployment_pods_gone control-plane app=trace-maintenance-worker+ kc -n gfs scale deployment/gfsc-writer deployment/gfsc-reader --replicas=0 >/dev/null \+ || fail "cannot quiesce GFS controllers"+ wait_for_deployment_pods_gone gfs app=gfs-controller+}++RESET_ACTIVE=false+fail_closed() {+ local rc=$?+ if [ "$RESET_ACTIVE" = true ]; then+ set +e+ kc -n control-plane scale deployment/host-context-controller --replicas=0 >/dev/null+ kc -n control-plane scale deployment/workflow-recipes deployment/trace-maintenance-worker --replicas=0 >/dev/null+ kc -n gfs scale deployment/gfsc-writer deployment/gfsc-reader --replicas=0 >/dev/null+ printf '[reset-control-db-storage] ERROR: reset interrupted; DB-dependent controllers remain scaled to zero and %s/%s preserves recovery state; a pinned original PVC keeps the %s finalizer until --resume completes the scrub\n' \+ "$NAMESPACE" "$RESET_STATE" "$RESET_SCRUB_FINALIZER" >&2+ fi+ trap - EXIT+ exit "$rc"+}+trap fail_closed EXIT++wait_for_pods_gone() {+ local selector="$1" deadline=$((SECONDS + 120)) pods+ while true; do+ pods="$(kc -n "$NAMESPACE" get pods -l "$selector" -o json | python3 -c '+import json+import sys++for item in json.load(sys.stdin).get("items", []):+ owners = (item.get("metadata") or {}).get("ownerReferences") or []+ if any(owner.get("kind") == "ReplicaSet" for owner in owners):+ print((item.get("metadata") or {}).get("name", ""))+')" \+ || fail "cannot inspect pods matching ${selector}"+ [ -z "$pods" ] && return 0+ (( SECONDS < deadline )) \+ || fail "timed out waiting for pods matching ${selector} to terminate"+ sleep 1+ done+}++remove_scrub_pod() {+ kc -n "$NAMESPACE" delete pod "$SCRUB_POD" \+ --ignore-not-found=true --wait=true >/dev/null \+ || fail "cannot remove cleanup pod ${NAMESPACE}/${SCRUB_POD}"+}++report_scrub_failure() {+ local reason="$1"+ printf '[reset-control-db-storage] cleanup pod failed: %s\n' "$reason" >&2+ if ! kc -n "$NAMESPACE" logs "pod/$SCRUB_POD" >&2; then+ printf '[reset-control-db-storage] cleanup pod logs unavailable\n' >&2+ fi+ remove_scrub_pod+ fail "refusing to delete ${NAMESPACE}/${PVC}: storage cleanup did not succeed"+}++wait_for_scrub() {+ local deadline=$((SECONDS + 120)) phase+ while true; do+ phase="$(kc -n "$NAMESPACE" get pod "$SCRUB_POD" \+ -o 'jsonpath={.status.phase}')" \+ || report_scrub_failure "cannot inspect pod status"+ case "$phase" in+ Succeeded) return 0 ;;+ Failed) report_scrub_failure "pod entered Failed phase" ;;+ esac+ (( SECONDS < deadline )) \+ || report_scrub_failure "timed out waiting for Succeeded phase"+ sleep 1+ done+}++scrub_claim_contents() {+ local postgres_image+ postgres_image="$(kc -n "$NAMESPACE" get deployment control-postgres \+ -o 'jsonpath={.spec.template.spec.containers[?(@.name=="postgres")].image}')" \+ || fail "cannot resolve the current control-postgres image"+ [ -n "$postgres_image" ] \+ || fail "control-postgres deployment has no postgres container image"++ # A crash between pod creation and removal leaves the fixed-name pod behind;+ # remove any leftover first so --resume can recreate it instead of failing+ # AlreadyExists forever.+ remove_scrub_pod++ # Use the database image already selected by the deployment. The pod receives+ # only the exact database PVC: no hostPath, service-account token, or+ # privileged container is needed to remove storage-provider-retained bytes.+ if ! kc -n "$NAMESPACE" create -f - >/dev/null <<EOF+apiVersion: v1+kind: Pod+metadata:+ name: ${SCRUB_POD}+ namespace: ${NAMESPACE}+ labels:+ app: control-postgres-storage-reset+spec:+ automountServiceAccountToken: false+ restartPolicy: Never+ activeDeadlineSeconds: 120+ terminationGracePeriodSeconds: 5+ securityContext:+ seccompProfile:+ type: RuntimeDefault+ containers:+ - name: scrub+ image: ${postgres_image}+ imagePullPolicy: IfNotPresent+ command: ["/bin/sh", "-ceu"]+ args:+ - |+ find /reset-target -mindepth 1 -xdev -delete+ test -z "\$(find /reset-target -mindepth 1 -xdev -print -quit)"+ securityContext:+ allowPrivilegeEscalation: false+ privileged: false+ readOnlyRootFilesystem: true+ # Root is required to remove storage-provider-retained bytes across+ # arbitrary UIDs. Allowed by control-plane's PSA enforce=baseline;+ # restricted enforcement would reject this pod.+ runAsUser: 0+ volumeMounts:+ - name: reset-target+ mountPath: /reset-target+ volumes:+ - name: reset-target+ persistentVolumeClaim:+ claimName: ${PVC}+EOF+ then+ fail "cannot create cleanup pod ${NAMESPACE}/${SCRUB_POD}"+ fi++ wait_for_scrub+ remove_scrub_pod+}++CONTEXT="$CONTEXT" bash "$ROOT/deploy/scripts/preflight-gfs-db-reset.sh"++claim_uid="$(kc -n "$NAMESPACE" get pvc "$PVC" \+ -o 'jsonpath={.metadata.uid}' --ignore-not-found)" \+ || fail "cannot inspect ${NAMESPACE}/${PVC}"+expected_state_uid="$EXPECTED_PVC_UID"+[ "$EXPECT_NO_PVC" = true ] && expected_state_uid=none+if read_reset_state; then+ [ "$RESUME" = true ] \+ || fail "${NAMESPACE}/${RESET_STATE} already exists; refusing concurrent reset (use --resume only for the same interrupted reset)"+ [ "$STATE_ORIGINAL_PVC_UID" = "$expected_state_uid" ] \+ || fail "existing reset state belongs to a different PVC expectation"+ RESET_ACTIVE=true+ case "$STATE_PHASE" in+ authorized)+ if [ "$expected_state_uid" = none ]; then+ [ -z "$claim_uid" ] || fail "a PVC appeared before the no-PVC reset entered its destructive phase"+ else+ [ -z "$claim_uid" ] || [ "$claim_uid" = "$expected_state_uid" ] \+ || fail "${NAMESPACE}/${PVC} changed before the destructive phase was recorded"+ fi+ ;;+ deleting-original)+ # Once this phase is durable, only the authorized original UID can ever+ # be scrubbed or deleted. A different UID is a replacement and is left+ # untouched for converge-control-db-after-reset.sh to bind by CAS.+ ;;+ original-deleted)+ [ -z "$claim_uid" ] || [ "$claim_uid" != "$expected_state_uid" ] \+ || fail "the authorized original PVC reappeared after deletion"+ ;;+ replacement-bound|converged)+ [ "$STATE_REPLACEMENT_PVC_UID" != unbound ] \+ || fail "${STATE_PHASE} reset state has no replacement UID"+ [ "$claim_uid" = "$STATE_REPLACEMENT_PVC_UID" ] \+ || fail "replacement PVC UID changed after it was bound"+ ;;+ esac+else+ [ "$RESUME" = false ] \+ || fail "--resume requested but ${NAMESPACE}/${RESET_STATE} does not exist"+ if [ -n "$claim_uid" ]; then+ [ "$EXPECT_NO_PVC" = false ] \+ || fail "${NAMESPACE}/${PVC} exists; --expect-no-pvc cannot authorize its deletion"+ [ "$claim_uid" = "$EXPECTED_PVC_UID" ] \+ || fail "${NAMESPACE}/${PVC} UID changed before reset authorization was consumed"+ else+ [ "$EXPECT_NO_PVC" = true ] \+ || fail "approved ${NAMESPACE}/${PVC} UID is no longer present"+ fi+ hcc_replicas="$(deployment_replicas control-plane host-context-controller)"+ workflow_replicas="$(deployment_replicas control-plane workflow-recipes)"+ trace_replicas="$(deployment_replicas control-plane trace-maintenance-worker)"+ writer_replicas="$(deployment_replicas gfs gfsc-writer)"+ reader_replicas="$(deployment_replicas gfs gfsc-reader)"+ control_api_replicas="$(deployment_replicas "$NAMESPACE" control-api)"+ [ "$writer_replicas" -gt 0 ] && [ "$reader_replicas" -gt 0 ] \+ || fail "active GFSC writer and reader replicas are required for verified restoration"+ # Zero here means a previous reset quiesced control-api and its state record+ # was cleared: storing 0 would pass this script's checks and only fail in+ # converge AFTER the PVC is destroyed. Fail before anything is deleted.+ [ "$control_api_replicas" -gt 0 ] \+ || fail "control-api has 0 replicas at capture time; scale it up (or --resume the interrupted reset that quiesced it) before authorizing a new reset"+ kc -n "$NAMESPACE" create configmap "$RESET_STATE" \+ --from-literal="stateVersion=1" \+ --from-literal="phase=authorized" \+ --from-literal="originalPvcUid=$expected_state_uid" \+ --from-literal="replacementPvcUid=unbound" \+ --from-literal="hccReplicas=$hcc_replicas" \+ --from-literal="workflowReplicas=$workflow_replicas" \+ --from-literal="traceReplicas=$trace_replicas" \+ --from-literal="writerReplicas=$writer_replicas" \+ --from-literal="readerReplicas=$reader_replicas" \+ --from-literal="controlApiReplicas=$control_api_replicas" >/dev/null \+ || fail "cannot acquire reset state lock ${NAMESPACE}/${RESET_STATE}"+ read_reset_state || fail "cannot read newly acquired reset state"+fi+RESET_ACTIVE=true++# A converged reset already restored storage AND controllers; only its+# recovery-record cleanup can still be pending. Quiescing here would tear a+# healthy stack down to zero, so convergence owns that retry entirely.+if [ "$STATE_PHASE" = converged ]; then+ RESET_ACTIVE=false+ printf '[reset-control-db-storage] reset already converged; re-run converge-control-db-after-reset.sh to retry recovery-state cleanup\n' >&2+ trap - EXIT+ exit 0+fi++quiesce_gfs++# A resumed reset that has already deleted the original PVC must never turn a+# replacement PVC into a new destructive target. Convergence owns replacement+# binding and all later phases.+if [ "$STATE_PHASE" = original-deleted ] \+ || [ "$STATE_PHASE" = replacement-bound ]; then+ printf '[reset-control-db-storage] reset already passed original deletion (%s); replacement storage left untouched\n' \+ "$STATE_PHASE" >&2+ trap - EXIT+ exit 0+fi++kc -n "$NAMESPACE" scale deployment/control-api --replicas=0 >/dev/null+kc -n "$NAMESPACE" scale deployment/control-postgres --replicas=0 >/dev/null+wait_for_pods_gone app=control-api+wait_for_pods_gone app=control-postgres++if [ "$STATE_PHASE" = authorized ]; then+ read_reset_state || fail "cannot reload reset state before destructive phase"+ [ "$STATE_PHASE" = authorized ] \+ || fail "reset state changed before destructive phase"+ cas_reset_phase authorized deleting-original unbound unbound+fi++claim_uid="$(kc -n "$NAMESPACE" get pvc "$PVC" \+ -o 'jsonpath={.metadata.uid}' --ignore-not-found)" \+ || fail "cannot inspect ${NAMESPACE}/${PVC}"+[ "$STATE_PHASE" = deleting-original ] \+ || fail "destructive reset requires the durable deleting-original phase"+if [ -n "$claim_uid" ] \+ && { [ "$expected_state_uid" = none ] || [ "$claim_uid" != "$expected_state_uid" ]; }; then+ # The authorized original is already gone and a replacement now occupies+ # the name. It is never scrubbed or deleted by this reset invocation.+ claim_uid=""+fi+if [ -n "$claim_uid" ]; then+ # Freeze the authorized original before the scrub pod mounts by name: while+ # the finalizer is held the claim name cannot be handed to a replacement, so+ # the volume the scrub pod receives is provably the authorized original.+ pin_state="$(sync_original_finalizer ensure "$claim_uid")"+ if [ "$pin_state" = skip ]; then+ # The authorized original disappeared before it could be pinned; whatever+ # occupies the name now is a replacement and is never scrubbed.+ claim_uid=""+ fi+fi+[ -z "$claim_uid" ] || scrub_claim_contents+delete_uid="$(kc -n "$NAMESPACE" get pvc "$PVC" \+ -o 'jsonpath={.metadata.uid}' --ignore-not-found)" \+ || fail "cannot recheck ${NAMESPACE}/${PVC} before deletion"+if [ -n "$claim_uid" ]; then+ [ "$delete_uid" = "$claim_uid" ] \+ || fail "${NAMESPACE}/${PVC} changed between storage scrub and deletion"+ unpin_state="$(sync_original_finalizer remove "$claim_uid")"+ [ "$unpin_state" = done ] \+ || fail "cannot release the ${RESET_SCRUB_FINALIZER} finalizer before deletion"+ # The API-server UID precondition closes the name-reuse race between the+ # final check and deletion. It cannot delete a replacement PVC.+ printf '{"apiVersion":"v1","kind":"DeleteOptions","preconditions":{"uid":"%s"}}\n' \+ "$claim_uid" | kc -n "$NAMESPACE" delete --raw \+ "/api/v1/namespaces/${NAMESPACE}/persistentvolumeclaims/${PVC}" \+ -f - --wait=true >/dev/null \+ || fail "cannot delete the UID-bound original PVC"+elif [ -n "$delete_uid" ] && [ "$delete_uid" = "$expected_state_uid" ]; then+ fail "authorized original PVC appeared before deletion without being scrubbed"+fi++# Most StorageClasses reclaim the PV automatically. If a Released PV remains,+# delete only the volume bound to the exact claim UID observed above.+if [ -n "$claim_uid" ]; then+ released_pvs="$(kc get pv -o json | python3 -c '+import json+import sys++expected_uid = sys.argv[1]+for item in json.load(sys.stdin).get("items", []):+ phase = (item.get("status") or {}).get("phase", "")+ claim = (item.get("spec") or {}).get("claimRef") or {}+ if (+ phase == "Released"+ and claim.get("namespace") == "control-plane"+ and claim.get("name") == "control-postgres-data"+ and claim.get("uid") == expected_uid+ ):+ print((item.get("metadata") or {}).get("name", ""))+' "$claim_uid")" || fail "cannot inspect released persistent volumes"+ while IFS= read -r pv; do+ [ -z "$pv" ] && continue+ kc delete pv "$pv" --ignore-not-found=true --wait=true >/dev/null+ done <<<"$released_pvs"+fi++read_reset_state || fail "cannot reload reset state after original deletion"+[ "$STATE_PHASE" = deleting-original ] \+ || fail "reset state changed before recording original deletion"+cas_reset_phase deleting-original original-deleted unbound unbound++printf '[reset-control-db-storage] control-postgres storage deleted after safe scale-down\n' >&2+trap - EXITdiff --git a/deploy/scripts/run-control-api-db-migration.sh b/deploy/scripts/run-control-api-db-migration.shindex 7dd5fe442..6b6760f11 100755--- a/deploy/scripts/run-control-api-db-migration.sh+++ b/deploy/scripts/run-control-api-db-migration.sh@@ -434,7 +434,7 @@ runtime_access_contract_values() {/^[[:space:]]*#/ || /^[[:space:]]*$/ { next }NF != 2 { exit 2 }$1 !~ /^[a-z][a-z0-9_]*$/ { exit 3 }- $2 !~ /^(legacy_dml|upsert|append|read)$/ { exit 4 }+ $2 !~ /^(legacy_dml|upsert|append|read|none)$/ { exit 4 }seen[$1]++ { exit 5 }{count++@@ -575,7 +575,7 @@ verify_runtime_access_contract() {JOIN actual_relations actual USING (relation_name)CROSS JOIN LATERAL (VALUES- ('SELECT', true),+ ('SELECT', expected.access_profile != 'none'),('INSERT', expected.access_profile IN ('legacy_dml', 'upsert', 'append')),('UPDATE', expected.access_profile IN ('legacy_dml', 'upsert')),('DELETE', expected.access_profile = 'legacy_dml'),diff --git a/deploy/scripts/verify-gfs-hcc-phase.sh b/deploy/scripts/verify-gfs-hcc-phase.shnew file mode 100755index 000000000..438c2340d--- /dev/null+++ b/deploy/scripts/verify-gfs-hcc-phase.sh@@ -0,0 +1,107 @@+#!/usr/bin/env bash+# Verify the two intentional HCC/GFSC rollback states without exposing DSNs.+set -euo pipefail++ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"+# shellcheck source=lib/gfs-dsn-probe.sh+source "$ROOT/deploy/scripts/lib/gfs-dsn-probe.sh"++usage() {+ cat <<'EOF'+Usage:+ verify-gfs-hcc-phase.sh --context <kube-context> --phase writer-compat|candidate++writer-compat verifies the temporary rollback state: both GFSC deployments use+the retained writer identity. It is not reader/writer isolation.++candidate verifies the restored split: writer and reader use their dedicated+credential references and authenticate as distinct database roles.+EOF+}++fail() { printf '[verify-gfs-hcc-phase] FAIL: %s\n' "$*" >&2; exit 1; }+log() { printf '[verify-gfs-hcc-phase] %s\n' "$*"; }++CONTEXT=""+PHASE=""+while [ "$#" -gt 0 ]; do+ case "$1" in+ --context) CONTEXT="${2:-}"; shift 2 ;;+ --context=*) CONTEXT="${1#--context=}"; shift ;;+ --phase) PHASE="${2:-}"; shift 2 ;;+ --phase=*) PHASE="${1#--phase=}"; shift ;;+ -h|--help) usage; exit 0 ;;+ *) fail "unknown argument: $1" ;;+ esac+done++[ -n "$CONTEXT" ] || { usage >&2; exit 2; }+case "$PHASE" in writer-compat|candidate) ;; *) usage >&2; exit 2 ;; esac++GFS_NS="${GFS_NS:-gfs}"+PG_NS="${PG_NS:-control-plane}"+PG_PROBE_DEPLOY="${PG_PROBE_DEPLOY:-deploy/control-api}"+PG_DB="${PG_DB:-profiles}"+PG_HOST="${PG_HOST:-control-postgres.control-plane.svc.cluster.local}"+PG_PORT="${PG_PORT:-5432}"+VERIFY_ROLLOUT_TIMEOUT="${VERIFY_ROLLOUT_TIMEOUT:-240s}"++kc() { kubectl --context="$CONTEXT" "$@"; }++read_field() {+ local out+ out="$(kc "$@" 2>&1)" || fail "kubectl $* failed: $out"+ printf '%s' "$out"+}++deployment_env_value() {+ local deployment="$1" env_name="$2" value+ value="$(read_field -n "$GFS_NS" get deployment "$deployment" -o \+ "go-template={{range .spec.template.spec.containers}}{{range .env}}{{if eq .name \"$env_name\"}}{{if .value}}{{.value}}{{else}}{{.valueFrom.secretKeyRef.name}}{{end}}{{\"\\n\"}}{{end}}{{end}}{{end}}")"+ value="${value//$'\r'/}"+ value="${value//$'\n'/}"+ [ -n "$value" ] || fail "deployment/$deployment has no explicit $env_name"+ printf '%s' "$value"+}++verify_deployment_contract() {+ local deployment="$1" expected_ref="$2" expected_role="$3" actual+ actual="$(deployment_env_value "$deployment" PG_CONNECTION_STRING)"+ [ "$actual" = "$expected_ref" ] \+ || fail "deployment/$deployment credential reference is $actual, expected $expected_ref for $PHASE"+ actual="$(deployment_env_value "$deployment" GFS_STORAGE_ROLE)"+ [ "$actual" = "$expected_role" ] \+ || fail "deployment/$deployment storage role is $actual, expected $expected_role"+ kc -n "$GFS_NS" rollout status "deployment/$deployment" --timeout="$VERIFY_ROLLOUT_TIMEOUT" >/dev/null \+ || fail "deployment/$deployment did not roll out"+}++verify_credential_role() {+ local object="$1" expected_role="$2" encoded dsn rc+ encoded="$(read_field -n "$GFS_NS" get secret "$object" -o 'jsonpath={.data.connection-string}')"+ [ -n "$encoded" ] || fail "$GFS_NS/$object has no database URI"+ dsn="$(printf '%s' "$encoded" | base64 -d)" || fail "$GFS_NS/$object database URI is not valid base64"+ set +e+ gfs_dsn_authenticates_as "$dsn" "$expected_role"+ rc=$?+ set -e+ unset dsn+ case "$rc" in+ 0) log "$object authenticates as $expected_role" ;;+ 1) fail "$object was rejected or did not authenticate as $expected_role" ;;+ *) fail "$object role probe was unavailable; phase cannot be verified" ;;+ esac+}++verify_deployment_contract gfsc-writer gfs-controller-db writer+verify_credential_role gfs-controller-db gfs_controller++if [ "$PHASE" = writer-compat ]; then+ verify_deployment_contract gfsc-reader gfs-controller-db reader+ log 'writer-compat verified: both deployments use the retained writer identity'+ log 'reader/writer database isolation is intentionally NOT active in this temporary phase'+else+ verify_deployment_contract gfsc-reader gfs-controller-reader-db reader+ verify_credential_role gfs-controller-reader-db gfs_controller_reader+ log 'candidate verified: reader/writer references and authenticated database users are distinct'+fidiff --git a/deploy/scripts/wait-gfsc-secret-references.sh b/deploy/scripts/wait-gfsc-secret-references.shnew file mode 100755index 000000000..e91a0df78--- /dev/null+++ b/deploy/scripts/wait-gfsc-secret-references.sh@@ -0,0 +1,53 @@+#!/usr/bin/env bash+# Wait until HCC has published the split GFSC deployments referencing their+# dedicated Secrets (writer -> gfs-controller-db, reader ->+# gfs-controller-reader-db). Running a credential reconcile before that point+# races the HCC cutover: the staged reader credential stays rollout-pending and+# the terminal verify-gfs check fails even though serving is healthy.+#+# Fresh bootstrap (HCC has not created the GFSC deployments yet) is not the+# racing case: it is logged and skipped so the callers' documented ordering —+# reconcile now, finalize after HCC creates the stack — stays intact.+set -euo pipefail++[ -n "${CONTEXT:-}" ] || { echo "[wait-gfsc-secret-references] CONTEXT is required" >&2; exit 1; }++kctl() {+ kubectl --context "$CONTEXT" "$@"+}++die() {+ echo "[wait-gfsc-secret-references] ERROR: $*" >&2+ exit 1+}++deployment_references_secret() {+ local deployment="$1" secret="$2" refs+ if ! refs="$(kctl -n gfs get deployment "$deployment" -o \+ 'jsonpath={range .spec.template.spec.containers[*].env[*]}{.valueFrom.secretKeyRef.name}{"\n"}{end}' 2>&1)"; then+ grep -qiE 'not ?found' <<<"$refs" && return 1+ die "cannot inspect gfs/${deployment} Secret references: $refs"+ fi+ grep -Fxq "$secret" <<<"$refs"+}++if ! writer_probe="$(kctl -n gfs get deployment gfsc-writer -o name 2>&1)"; then+ if grep -qiE 'not ?found' <<<"$writer_probe"; then+ echo "[wait-gfsc-secret-references] GFSC deployments not created yet (fresh bootstrap) — skipping secret-reference wait"+ exit 0+ fi+ die "cannot inspect gfs/gfsc-writer: $writer_probe"+fi++deadline=$((SECONDS + 240))+while [ "$SECONDS" -lt "$deadline" ]; do+ if deployment_references_secret gfsc-writer gfs-controller-db && \+ deployment_references_secret gfsc-reader gfs-controller-reader-db; then+ exit 0+ fi+ echo "[wait-gfsc-secret-references] waiting for HCC to publish writer/reader deployments with their dedicated Secrets"+ sleep 5+done+kctl -n gfs get globalfilesystem gfs -o yaml || true+kctl -n gfs get deployments,pods -o wide || true+die "GFSC deployments did not adopt their dedicated Secrets before timeout"diff --git a/desktop-app/test/e2e-playwright/gfs-agent-copy.test.ts b/desktop-app/test/e2e-playwright/gfs-agent-copy.test.tsnew file mode 100644index 000000000..d00cfa1b7--- /dev/null+++ b/desktop-app/test/e2e-playwright/gfs-agent-copy.test.ts@@ -0,0 +1,462 @@+/**+ * Issue #797 T2: real Desktop login -> exact Agent A -> native Copy/Rename ->+ * exact Agent B denial -> audited revoke -> same-runtime Agent A denial.+ * SQL/PVC and grant operations are named preconditions/assertions only; no+ * fixture helper performs the agent mutations under test.+ */+import { type Locator, type Page, expect, test } from '@playwright/test'+import {+ type AgentGfsCopyFixtures,+ assertGfsInfraHealthy,+ countGfsLiveChildrenByName,+ getGfsChildResourceSummary,+ getGfsTreeAclShareCounts,+ getGfsTreeAclShareRows,+ getGfsTreeSnapshot,+ gfsGrantRevokeAuditCount,+ revokeGfsGrantViaControlApi,+ seedAgentGfsCopyFixtures,+} from './helpers/gfsFixtures'+import { exactNameFilter } from './helpers/agentLocators'+import { getManagedAgentPodIdentity } from './helpers/gfsAgentDiscovery'+import { openAgentsPage, openResourcesNavItem } from './navigationHelpers'+import { launchAndLogin } from './workflowUi'++const OWNER_EMAIL = '[email protected]'+// Multi-tool turns (rename + recursive list + read-every-file) on the local+// glm profile routinely exceed the 180s single-turn calibration.+const RESPONSE_TIMEOUT_MS = 300_000+const SENSITIVE_OUTPUT =+ /\/data\/gfs|\/mnt\/|\.generations|blob_key|blobKey|\bSQL\b|internal (?:path|error)|stack trace/i++async function openExactAgent(+ page: Page,+ agentName: string,+ opts: { reuseThread?: boolean } = {}+): Promise<void> {+ await openAgentsPage(page)+ await expect(page.getByRole('heading', { name: 'Agents', exact: true })).toBeVisible()+ const row = page.getByLabel(`Open details for ${agentName}`, { exact: true })+ await expect(row).toBeVisible({ timeout: 30_000 })+ await row.click()+ await expect(page.getByText(agentName, { exact: true }).first()).toBeVisible({ timeout: 15_000 })+ await page.getByTestId('nav-chat').click()+ await expect(page.getByTestId('chat-input')).toBeVisible({ timeout: 30_000 })+ // Starting a new chat can reset the composer to the DEFAULT agent, so it+ // must happen BEFORE the agent switch — never after, or the turn silently+ // goes to the wrong agent.+ if (!opts.reuseThread) {+ const fresh = page.getByRole('button', { name: /new (?:chat|thread)/i }).first()+ if (await fresh.isVisible().catch(() => false)) await fresh.click()+ }+ // The product binds the composer to an agent ONLY through the chat view's+ // "Switch chat agent" selector — opening another agent's details page+ // deliberately does not switch the chat. Drive exactly that user flow.+ const switcher = page.getByRole('button', { name: 'Switch chat agent' })+ const boundSwitcher = switcher.filter(exactNameFilter(agentName))+ const breadcrumb = page+ .getByRole('navigation', { name: 'Chat breadcrumb' })+ .getByText(agentName, { exact: true })+ if (!(await boundSwitcher.or(breadcrumb).first().isVisible().catch(() => false))) {+ await switcher.first().click()+ await page.getByRole('menuitem', { name: agentName, exact: true }).click()+ }+ // A stateless agent suspended at idle wakes through the rpc-proxy+ // wake-and-hold path (up to ~90s of scale-up) before its chat shell binds;+ // the binding element itself remains mandatory and is the LAST gate before+ // any turn is sent.+ await expect(boundSwitcher.or(breadcrumb).first()).toBeVisible({ timeout: 120_000 })+ if (opts.reuseThread) {+ // reuseThread continues the agent's MOST-RECENT session. Callers must drive+ // purely by visible NAMES here (never resource identifiers), because which+ // of the agent's threads is most-recent is not guaranteed: any earlier step+ // that opens a fresh thread for this agent becomes the newest one, so the+ // reused prompt must not presume a specific prior conversation history.+ await page.locator('.agent-dedicated-session-title-btn').first().click()+ await expect(page.getByTestId('agent-response').first()).toBeVisible({ timeout: 15_000 })+ } else {+ await expect(page.getByTestId('agent-response')).toHaveCount(0, { timeout: 10_000 })+ }+}++async function sendAgentTurn(page: Page, prompt: string): Promise<Locator> {+ const responseIndex = await page.getByTestId('agent-response').count()+ const approvalIndex = await page.getByTestId('approval-approve-btn').count()+ const progressIndex = await page.getByTestId('progress-expand-btn').count()+ await expect(page.getByTestId('chat-input')).toBeEnabled()+ await page.getByTestId('chat-input').fill(prompt)+ await page.getByTestId('send-button').click()++ const response = page.getByTestId('agent-response').nth(responseIndex)+ const retrySend = page.getByRole('button', { name: 'Retry last send' })+ let approvals = 0+ let sendRetries = 0+ const deadline = Date.now() + RESPONSE_TIMEOUT_MS+ for (;;) {+ const remaining = deadline - Date.now()+ if (remaining <= 0) throw new Error('timed out waiting for the issue #797 agent turn')+ // A just-restarted runtime can drop the send with a visible "Temporary+ // connection issue" banner; a real user presses the product's own+ // "Retry last send". Bounded — a persistent failure still fails the turn.+ if (await retrySend.isVisible().catch(() => false)) {+ if (sendRetries >= 3) throw new Error('agent send kept failing after 3 product retries')+ sendRetries += 1+ // An absorbed retry must be LOUD in a green run: warn on the console+ // and annotate the test report, without changing pass/fail semantics.+ const turnLabel = prompt.slice(0, 80)+ console.warn(+ `[gfs-agent-copy] "Retry last send" pressed (attempt ${sendRetries}/3) for turn: ${turnLabel}`+ )+ test+ .info()+ .annotations.push({+ type: 'retry-last-send',+ description: `attempt ${sendRetries}/3 for turn: ${turnLabel}`,+ })+ await retrySend.click()+ continue+ }+ const approval = page.getByTestId('approval-approve-btn').nth(approvalIndex + approvals)+ const approvalWait = approval+ .waitFor({ state: 'visible', timeout: Math.min(remaining, 10_000) })+ .then(() => 'approval' as const)+ const responseWait = response+ .waitFor({ state: 'visible', timeout: Math.min(remaining, 10_000) })+ .then(() => 'response' as const)+ // The losing waitFor keeps its timer; silence its eventual rejection so a+ // settled turn cannot surface a late "Target closed" unhandled rejection.+ // .catch() returns a NEW promise, so the originals still race unchanged.+ void approvalWait.catch(() => undefined)+ void responseWait.catch(() => undefined)+ let visible: 'approval' | 'response'+ try {+ visible = await Promise.race([approvalWait, responseWait])+ } catch {+ // Neither appeared within this slice; loop to re-check the retry banner+ // and the overall deadline.+ continue+ }+ if (visible === 'response') break+ await approval.click()+ approvals += 1+ }+ await expect(response).toBeVisible({ timeout: RESPONSE_TIMEOUT_MS })+ const expand = page.getByTestId('progress-expand-btn').nth(progressIndex)+ await expect(expand).toBeVisible({ timeout: 30_000 })+ await expand.click()+ return expand.locator('..')+}++function toolRow(stepper: Locator, name: string): Locator {+ return stepper.locator('.stepper-step').filter({ hasText: name }).last()+}++async function expectToolSuccess(stepper: Locator, name: string): Promise<void> {+ const row = toolRow(stepper, name)+ await expect(row).toBeVisible({ timeout: 15_000 })+ await expect(row.locator('.stepper-step-fn')).toContainText(name)+ await expect(row.locator('.stepper-step-duration.state-error')).toHaveCount(0)+}++async function expectToolForbidden(stepper: Locator, name: string): Promise<void> {+ const row = toolRow(stepper, name)+ await expect(row).toBeVisible({ timeout: 15_000 })+ await expect(row.locator('.stepper-step-fn')).toContainText(name)+ await expect(row.locator('.stepper-step-duration.state-error')).toContainText(/gfsc 403.*forbidden/i)+ await expect(row).not.toContainText(/gfsc 503|not_mounted/i)+ await expect(stepper).not.toContainText(SENSITIVE_OUTPUT)+}++async function expectToolConflict(stepper: Locator, name: string): Promise<void> {+ // A copy onto an existing name is a non-destructive conflict: gfsc maps+ // already_exists to 409, which mcp-host redacts to `gfsc 409: conflict`.+ // It must never read as a 503/not_mounted infra failure and must never leak+ // server internals.+ const row = toolRow(stepper, name)+ await expect(row).toBeVisible({ timeout: 15_000 })+ await expect(row.locator('.stepper-step-fn')).toContainText(name)+ await expect(row.locator('.stepper-step-duration.state-error')).toContainText(/gfsc 409.*conflict/i)+ await expect(row).not.toContainText(/gfsc 503|not_mounted/i)+ await expect(stepper).not.toContainText(SENSITIVE_OUTPUT)+}++async function expectCopyPublicOutput(stepper: Locator): Promise<void> {+ // The step-output panel renders the mcp-host preview, which truncates each+ // line at 200 chars (toolUseLoopPreviews MAX_LINE_LENGTH) — a single-line+ // copy JSON is cut after ok/requestId/resourceId/gfsUri. Those visible+ // fields are asserted here; name and object/file/folder counts are business+ // signals proven from the database right after each copy (child-by-name+ // lookup plus full tree-snapshot equality), where truncation cannot hide a+ // wrong result.+ const row = toolRow(stepper, 'gfs_copy')+ await row.click()+ const output = row+ .locator('xpath=following-sibling::*[@data-testid="step-output-panel"][1]')+ .locator('.stepper-step-output-code')+ await expect(output).toBeVisible({ timeout: 10_000 })+ await expect(output).toContainText('"ok":true')+ await expect(output).toContainText('"requestId":')+ await expect(output).toContainText('"resourceId":')+ await expect(output).toContainText('"gfsUri":"gfs://main/')+ await expect(output).not.toContainText(SENSITIVE_OUTPUT)+}++function comparableTree(root: ReturnType<typeof getGfsTreeSnapshot>) {+ return root.map(({ relativePath, kind, bytes, content }) => ({ relativePath, kind, bytes, content }))+}++async function openFilesBrowser(page: Page): Promise<Locator> {+ await openResourcesNavItem(page, 'nav-files')+ const browser = page.getByRole('region', { name: 'Global File System browser' })+ await expect(browser).toBeVisible({ timeout: 20_000 })+ return browser+}++async function browseSourceTree(page: Page, fixtures: AgentGfsCopyFixtures): Promise<void> {+ const browser = await openFilesBrowser(page)+ await browser.getByRole('button', { name: fixtures.tree.sourceName, exact: true }).click()+ await expect(+ browser.getByRole('button', { name: fixtures.tree.standaloneFileName, exact: true })+ ).toBeVisible()+ await browser.getByRole('button', { name: 'nested', exact: true }).click()+ await expect(browser.getByRole('button', { name: 'alpha.txt', exact: true })).toBeVisible()+ await browser.getByRole('button', { name: 'empty', exact: true }).click()+ await expect(browser.getByText('This folder is empty', { exact: true })).toBeVisible()+}++async function browseDestinationTree(page: Page, fixtures: AgentGfsCopyFixtures): Promise<void> {+ const browser = await openFilesBrowser(page)+ await browser.getByRole('button', { name: fixtures.tree.destinationName, exact: true }).click()+ await expect(browser.getByRole('button', { name: fixtures.fileCopyName, exact: true })).toBeVisible()+ await browser.getByRole('button', { name: fixtures.renamedFolderName, exact: true }).click()+ await expect(browser.getByRole('button', { name: 'nested', exact: true })).toBeVisible()+ await browser.getByRole('button', { name: 'nested', exact: true }).click()+ await expect(browser.getByRole('button', { name: 'alpha.txt', exact: true })).toBeVisible()+ await expect(browser.getByRole('button', { name: 'deeper', exact: true })).toBeVisible()+ await browser.getByRole('button', { name: 'empty', exact: true }).click()+ await expect(browser.getByText('This folder is empty', { exact: true })).toBeVisible()+}++test.describe('GFS per-agent native Copy and immediate grant enforcement (issue #797)', () => {+ test.describe.configure({ mode: 'serial' })+ let fixtures: AgentGfsCopyFixtures++ test.beforeAll(() => {+ assertGfsInfraHealthy()+ fixtures = seedAgentGfsCopyFixtures(OWNER_EMAIL)+ })++ test.afterAll(() => fixtures?.cleanup())++ test('copies complete trees and revokes destination access in one runtime', async ({}, testInfo) => {+ // Four real LLM turns (each allowed RESPONSE_TIMEOUT_MS) plus Electron+ // login and two Files-tree walks cannot fit the 240s config default.+ testInfo.setTimeout(1_200_000)+ const sourceBefore = getGfsTreeSnapshot(fixtures.tree.sourceResourceId)+ const sourceAclShareBefore = getGfsTreeAclShareRows(fixtures.tree.sourceResourceId)+ const sourceAclShareRecords = sourceAclShareBefore.map(+ row => JSON.parse(row) as { kind: 'grant' | 'share'; row: Record<string, unknown> }+ )+ expect(+ sourceAclShareRecords.filter(+ record =>+ record.kind === 'share' &&+ record.row.id === fixtures.sourceShareId &&+ record.row.subject_id === fixtures.sourceShareSubjectId+ )+ ).toHaveLength(1)+ expect(+ sourceAclShareRecords.filter(+ record =>+ record.kind === 'grant' && record.row.subject_id === fixtures.sourceShareSubjectId+ )+ ).toHaveLength(0)+ expect(getGfsTreeAclShareCounts(fixtures.tree.sourceResourceId).shares).toBeGreaterThanOrEqual(1)+ const { app, page } = await launchAndLogin(OWNER_EMAIL)+ try {+ await test.step('Agent A copies one file through the native tool', async () => {+ await browseSourceTree(page, fixtures)+ await openExactAgent(page, fixtures.agentA.name)+ const steps = await sendAgentTurn(+ page,+ `In drive main, open the folder named "${fixtures.tree.sourceName}" and read the file ` ++ `"${fixtures.tree.standaloneFileName}" inside it. Then copy that file into the folder ` ++ `named "${fixtures.tree.destinationName}", naming the copy "${fixtures.fileCopyName}". ` ++ `Use only your native Clerum GFS tools; never download and re-upload content yourself.`+ )+ await expectToolSuccess(steps, 'gfs_read')+ await expectToolSuccess(steps, 'gfs_copy')+ await expectCopyPublicOutput(steps)+ const copied = getGfsChildResourceSummary({+ parentResourceId: fixtures.tree.destinationResourceId,+ name: fixtures.fileCopyName,+ })+ expect(copied).not.toBeNull()+ expect(copied?.resourceId).not.toBe(fixtures.tree.standaloneFileResourceId)+ const copiedTree = getGfsTreeSnapshot(copied!.resourceId)+ const sourceFile = sourceBefore.find(node => node.resourceId === fixtures.tree.standaloneFileResourceId)+ expect(comparableTree(copiedTree)).toEqual([+ { relativePath: '.', kind: 'file', bytes: sourceFile!.bytes, content: sourceFile!.content },+ ])+ expect(getGfsTreeAclShareRows(fixtures.tree.sourceResourceId)).toEqual(sourceAclShareBefore)+ expect(getGfsTreeAclShareCounts(copied!.resourceId)).toEqual({ grants: 0, shares: 0 })+ })++ await test.step('Agent A recursively copies the complete folder', async () => {+ const steps = await sendAgentTurn(+ page,+ `Now copy the complete folder named "${fixtures.tree.sourceName}" from drive main into ` ++ `the folder named "${fixtures.tree.destinationName}", naming the copy ` ++ `"${fixtures.folderCopyName}". Make exactly one copy; do not move or delete anything.`+ )+ await expectToolSuccess(steps, 'gfs_copy')+ await expectCopyPublicOutput(steps)+ })++ await test.step('Agent A renames the copied root and reads it back', async () => {+ // A separate short turn keeps the user intent unambiguous: renaming+ // must never be "helpfully" followed by a fresh copy of the old name.+ const steps = await sendAgentTurn(+ page,+ `Rename the copy named "${fixtures.folderCopyName}" (inside ` ++ `"${fixtures.tree.destinationName}") to "${fixtures.renamedFolderName}". Then list ` ++ `that renamed folder recursively and read every file inside it. Do not copy, move, ` ++ `or delete anything.`+ )+ await expectToolSuccess(steps, 'gfs_rename')+ await expectToolSuccess(steps, 'gfs_list')+ await expectToolSuccess(steps, 'gfs_read')+ })++ await test.step('visible browse and persisted tree prove Copy did real work', async () => {+ const copied = getGfsChildResourceSummary({+ parentResourceId: fixtures.tree.destinationResourceId,+ name: fixtures.renamedFolderName,+ })+ expect(copied).not.toBeNull()+ expect(+ getGfsChildResourceSummary({+ parentResourceId: fixtures.tree.destinationResourceId,+ name: fixtures.folderCopyName,+ })+ ).toBeNull()+ const copiedTree = getGfsTreeSnapshot(copied!.resourceId)+ expect(comparableTree(copiedTree)).toEqual(comparableTree(sourceBefore))+ for (const source of sourceBefore) {+ expect(copiedTree.map(node => node.resourceId)).not.toContain(source.resourceId)+ }+ expect(getGfsTreeSnapshot(fixtures.tree.sourceResourceId)).toEqual(sourceBefore)+ expect(getGfsTreeAclShareRows(fixtures.tree.sourceResourceId)).toEqual(sourceAclShareBefore)+ expect(getGfsTreeAclShareCounts(copied!.resourceId)).toEqual({ grants: 0, shares: 0 })+ await browseDestinationTree(page, fixtures)+ })++ await test.step('copying onto an existing name is a non-destructive conflict (no duplicate)', async () => {+ // The file copy from the first step already put `fileCopyName` under the+ // destination. Copying the same source file there under the same name+ // must be refused (already_exists → gfsc 409), and — the load-bearing+ // business signal — must leave exactly one live child with that name.+ const beforeSummary = getGfsChildResourceSummary({+ parentResourceId: fixtures.tree.destinationResourceId,+ name: fixtures.fileCopyName,+ })+ expect(beforeSummary).not.toBeNull()+ expect(+ countGfsLiveChildrenByName({+ parentResourceId: fixtures.tree.destinationResourceId,+ name: fixtures.fileCopyName,+ })+ ).toBe(1)+ // Fresh thread on purpose: A has no memory of the earlier copy, so it+ // must actually re-attempt the copy by name and surface the tool's real+ // result rather than answering "already done" from context.+ await openExactAgent(page, fixtures.agentA.name)+ const steps = await sendAgentTurn(+ page,+ `In drive main, copy the file "${fixtures.tree.standaloneFileName}" from the folder ` ++ `"${fixtures.tree.sourceName}" into the folder "${fixtures.tree.destinationName}", ` ++ `naming the copy "${fixtures.fileCopyName}". Use your native Clerum GFS copy tool and ` ++ `report exactly what it returns. Attempt the copy even if a listing suggests the name ` ++ `already exists — do not decline based on a prior listing — and do not rename, delete, ` ++ `or overwrite anything.`+ )+ await expectToolConflict(steps, 'gfs_copy')+ // The existing copy is untouched and NO duplicate row was created.+ const afterSummary = getGfsChildResourceSummary({+ parentResourceId: fixtures.tree.destinationResourceId,+ name: fixtures.fileCopyName,+ })+ expect(afterSummary?.resourceId).toBe(beforeSummary?.resourceId)+ expect(+ countGfsLiveChildrenByName({+ parentResourceId: fixtures.tree.destinationResourceId,+ name: fixtures.fileCopyName,+ })+ ).toBe(1)+ })++ await test.step('Agent B passes root/destination grants but unreadable child denies the tree', async () => {+ await openExactAgent(page, fixtures.agentB.name)+ const steps = await sendAgentTurn(+ page,+ `Copy the folder named "${fixtures.tree.sourceName}" from drive main into the folder ` ++ `named "${fixtures.tree.destinationName}", naming the copy "${fixtures.deniedCopyName}". ` ++ `Attempt the copy with your native Clerum GFS copy tool and report exactly what it ` ++ `returns — do not decline based on a prior listing, even if it looks like you lack access.`+ )+ await expectToolForbidden(steps, 'gfs_copy')+ expect(+ getGfsChildResourceSummary({+ parentResourceId: fixtures.tree.destinationResourceId,+ name: fixtures.deniedCopyName,+ })+ ).toBeNull()+ })++ await test.step('audited revoke denies Agent A immediately in the same runtime', async () => {+ await openExactAgent(page, fixtures.agentA.name, { reuseThread: true })+ const runtimeBefore = getManagedAgentPodIdentity(fixtures.agentA)+ const auditBefore = gfsGrantRevokeAuditCount(fixtures.agentA)+ await revokeGfsGrantViaControlApi(fixtures.destinationGrantId)+ expect(gfsGrantRevokeAuditCount(fixtures.agentA)).toBe(auditBefore + 1)+ const steps = await sendAgentTurn(+ page,+ `Copy the folder "${fixtures.tree.sourceName}" into the folder ` ++ `"${fixtures.tree.destinationName}", naming the copy ` ++ `"${fixtures.revokedCopyName}". Attempt the copy with your native Clerum GFS copy ` ++ `tool and report exactly what it returns — do not decline based on a prior listing, ` ++ `even if it looks like you lack access.`+ )+ // Under name driving, revoking the destination removes even its+ // resolvability (no-disclosure): the visible denial surfaces on the+ // agent's own discovery tool (gfsc 403/404) BEFORE any gfs_copy can be+ // issued. Require a gfsc-denied tool row, forbid any successful+ // gfs_copy, and keep the infra-shape negatives.+ const deniedGfsRow = steps+ .locator('.stepper-step-duration.state-error')+ .filter({ hasText: /gfsc 40[34]/ })+ await expect(deniedGfsRow.first()).toBeVisible({ timeout: 15_000 })+ const successfulCopy = steps+ .locator('.stepper-step')+ .filter({ has: page.locator('.stepper-step-fn', { hasText: 'gfs_copy' }) })+ .filter({ hasNot: page.locator('.stepper-step-duration.state-error') })+ await expect(successfulCopy).toHaveCount(0)+ await expect(steps).not.toContainText(/gfsc 503|not_mounted/i)+ await expect(steps).not.toContainText(SENSITIVE_OUTPUT)+ // Same-runtime proof: the denial must come from live cache+ // invalidation, not from a pod restart re-reading grants.+ expect(getManagedAgentPodIdentity(fixtures.agentA)).toBe(runtimeBefore)+ expect(+ getGfsChildResourceSummary({+ parentResourceId: fixtures.tree.destinationResourceId,+ name: fixtures.revokedCopyName,+ })+ ).toBeNull()+ })++ expect(getGfsTreeSnapshot(fixtures.tree.sourceResourceId)).toEqual(sourceBefore)+ } finally {+ await app.close()+ }+ })+})diff --git a/desktop-app/test/e2e-playwright/gfs-agent-file-read.test.ts b/desktop-app/test/e2e-playwright/gfs-agent-file-read.test.tsindex 12c107cb4..d010e37b9 100644--- a/desktop-app/test/e2e-playwright/gfs-agent-file-read.test.ts+++ b/desktop-app/test/e2e-playwright/gfs-agent-file-read.test.ts@@ -19,12 +19,13 @@* - Infra guard: gfsc unhealthy ⇒ the suite THROWS (never skips, never mocks).*/import { expect, test } from '@playwright/test'+import { exactNameFilter } from './helpers/agentLocators'import {type AgentGfsFixtures,assertGfsInfraHealthy,seedAgentGfsFixtures,} from './helpers/gfsFixtures'-import { openResourcesNavItem } from './navigationHelpers'+import { openAgentsPage, openResourcesNavItem } from './navigationHelpers'import { launchAndLogin } from './workflowUi'const OWNER_EMAIL = '[email protected]'@@ -35,17 +36,46 @@ const PROGRESS_TIMEOUT_MS = 30_000type Page = import('@playwright/test').Page-async function enterAgentChat(page: Page): Promise<void> {- // The agents TABLE row opens the workspace in 'details' view (FleetBoard- // wires onOpenAgentWorkspace(agent, 'details')) — the chat lives under the- // primary nav-chat item. With the single seeded agent the chat home renders- // "New chat with <agent>" and the ComposerPanel textarea directly; a cold- // Electron renderer can take a while, so the wait mirrors the 45s entry- // budget of workflowUi's login poll.+async function enterAgentChat(page: Page, agentName: string): Promise<void> {+ // The agents TABLE row opens the workspace in 'details' view — navigating+ // to details does not rebind the composer (only the "Switch chat agent"+ // dropdown does), and the chat lives under the primary nav-chat item. With+ // the single seeded agent the chat home renders "New chat with <agent>" and+ // the ComposerPanel textarea directly; a cold Electron renderer can take a+ // while, so the wait mirrors the 45s entry budget of workflowUi's login+ // poll.+ await openAgentsPage(page)+ const exactAgent = page.getByLabel(`Open details for ${agentName}`, { exact: true })+ await expect(exactAgent).toBeVisible({ timeout: 30_000 })+ await exactAgent.click()+ await expect(page.getByText(agentName, { exact: true }).first()).toBeVisible()const chatInput = page.locator('[data-testid="chat-input"]')- if (await chatInput.isVisible().catch(() => false)) returnawait page.getByTestId('nav-chat').click()await chatInput.waitFor({ state: 'visible', timeout: 45_000 })+ // In the two-agent #797 topology a denial from the WRONG agent must not be+ // able to satisfy this suite: assert the composer is bound to the exact+ // agent before any turn is sent (same contract as the copy suite).+ const selectedAgentInNewChat = page+ .getByRole('button', { name: 'Switch chat agent' })+ .filter(exactNameFilter(agentName))+ const selectedAgentInThread = page+ .getByRole('navigation', { name: 'Chat breadcrumb' })+ .getByText(agentName, { exact: true })+ // The chat view can restore whichever agent was last used; the product's+ // way to rebind is the "Switch chat agent" selector.+ if (+ !(await selectedAgentInNewChat+ .or(selectedAgentInThread)+ .first()+ .isVisible()+ .catch(() => false))+ ) {+ await page.getByRole('button', { name: 'Switch chat agent' }).first().click()+ await page.getByRole('menuitem', { name: agentName, exact: true }).click()+ }+ await expect(selectedAgentInNewChat.or(selectedAgentInThread).first()).toBeVisible({+ timeout: 15_000,+ })}async function startFreshThread(page: Page): Promise<void> {@@ -89,14 +119,19 @@ async function sendGfsTask(if (remaining <= 0) {throw new Error('Timed out waiting for approval prompt or agent response')}- const firstVisible = await Promise.race([- nextApproval- .waitFor({ state: 'visible', timeout: remaining })- .then(() => 'approval' as const),- newResponse.waitFor({ state: 'visible', timeout: remaining }).then(() => 'response' as const),- ]).catch(() => {+ const approvalWait = nextApproval+ .waitFor({ state: 'visible', timeout: remaining })+ .then(() => 'approval' as const)+ const responseWait = newResponse+ .waitFor({ state: 'visible', timeout: remaining })+ .then(() => 'response' as const)+ const firstVisible = await Promise.race([approvalWait, responseWait]).catch(() => {throw new Error('Timed out waiting for approval prompt or agent response')})+ // Silence the losing waitFor so its later rejection cannot surface as an+ // unhandled "Target closed" failure after the turn already settled.+ void approvalWait.catch(() => undefined)+ void responseWait.catch(() => undefined)if (firstVisible === 'response') breakawait nextApproval.click()approvalsSeen += 1@@ -154,12 +189,16 @@ test.describe('GFS agent file read (issue #775)', () => {let expandBtn: import('@playwright/test').Locatorlet response = ''await test.step('agent resolves and reads the gfs:// URI', async () => {- await enterAgentChat(page)+ await enterAgentChat(page, fixtures.agent.name)await startFreshThread(page)+ // The user drives with the path they just saw in the Files browser —+ // never with resource UUIDs or gfs:// URIs, which are internal+ // storage identifiers a real user does not know.const result = await sendGfsTask(page,- `Resolve and read this GFS file and quote its contents verbatim: ${fixtures.granted.fileUri}. ` +- 'Use the clerum gfs tools (gfs_resolve first, then gfs_read). Do not answer from memory.'+ `Read the file at path "/${fixtures.granted.name}/${fixtures.granted.fileName}" in GFS ` ++ 'drive main and quote its contents verbatim. Use your Clerum GFS tools; do not answer ' ++ 'from memory.')expandBtn = result.expandBtnresponse = result.response@@ -173,10 +212,9 @@ test.describe('GFS agent file read (issue #775)', () => {await test.step('tool details prove the real read (business signal)', async () => {await expandBtn.click()- const resolveRow = toolStepRow(page, 'gfs_resolve')- await expect(resolveRow).toBeVisible({ timeout: 10_000 })- await expect(resolveRow.locator('.stepper-step-duration.state-error')).toHaveCount(0)-+ // Which discovery tool the agent picks for a path (resolve vs list) is+ // its own business; the required proof is the successful read whose+ // output carries the run-unique sentinel served from the real PVC.const readRow = toolStepRow(page, 'gfs_read')await expect(readRow).toBeVisible({ timeout: 10_000 })await expect(readRow.locator('.stepper-step-duration.state-error')).toHaveCount(0)@@ -202,12 +240,13 @@ test.describe('GFS agent file read (issue #775)', () => {const { app, page } = await launchAndLogin(OWNER_EMAIL)try {await test.step('agent attempts to read the ungranted gfs:// URI', async () => {- await enterAgentChat(page)+ await enterAgentChat(page, fixtures.agent.name)await startFreshThread(page)const { response, expandBtn } = await sendGfsTask(page,- `Resolve and read this GFS file and quote its contents verbatim: ${fixtures.ungranted.fileUri}. ` +- 'Use the clerum gfs tools (gfs_resolve first, then gfs_read). Do not answer from memory.'+ `Read the file at path "/${fixtures.ungranted.name}/${fixtures.ungranted.fileName}" in ` ++ 'GFS drive main and quote its contents verbatim. Do not answer from memory — attempt ' ++ 'the read with your Clerum GFS tools even if the file is not in your listing.')// Credential repair must be distinguishable from resource// authorization: the store is healthy, so the ONLY acceptable failure@@ -224,14 +263,19 @@ test.describe('GFS agent file read (issue #775)', () => {.filter({ has: page.locator('.stepper-step-fn', { hasText: /gfs_/ }) })await expect(gfsSteps.first()).toBeVisible({ timeout: 10_000 })- // At least one gfs step must surface the clean authorization denial.- // Short error summaries (<=60 chars, like `gfsc 403: not authorized…`)- // render inline in the error badge; only long ones (like the 503- // not_mounted envelope) get a separate .stepper-step-error-detail.+ // Under human name/path driving a denied file is deliberately+ // indistinguishable from an absent one (no-disclosure): the agent+ // cannot reach a direct 403 without legitimately holding the resource+ // id, so the contract here is that NO gfs_read ever succeeds, nothing+ // leaks the sentinel content, and no infra 503/not_mounted shape+ // appears. The deterministic gfsc-403 badge contract is proven by the+ // issue #797 copy journey, where the agent owns its discovered ids.+ const successfulRead = page+ .locator('.stepper-step')+ .filter({ has: page.locator('.stepper-step-fn', { hasText: 'gfs_read' }) })+ .filter({ hasNot: page.locator('.stepper-step-duration.state-error') })+ await expect(successfulRead).toHaveCount(0)const errorBadges = page.locator('.stepper-step-duration.state-error')- await expect(errorBadges.filter({ hasText: /gfsc 403/ }).first()).toBeVisible({- timeout: 10_000,- })await expect(errorBadges.filter({ hasText: /not_mounted|gfsc 503/ })).toHaveCount(0)await expect(page.locator('.stepper-step-error-detail').filter({ hasText: /not_mounted|gfsc 503/ })diff --git a/desktop-app/test/e2e-playwright/helpers/agentLocators.ts b/desktop-app/test/e2e-playwright/helpers/agentLocators.tsnew file mode 100644index 000000000..59270326d--- /dev/null+++ b/desktop-app/test/e2e-playwright/helpers/agentLocators.ts@@ -0,0 +1,17 @@+/**+ * Shared locator filters for asserting the chat composer is bound to the+ * EXACT agent under test.+ */++/**+ * Anchored exact-name filter for `Locator.filter()`.+ *+ * `filter({ hasText: string })` is SUBSTRING matching: 'chatllm' would accept+ * a composer bound to 'chatllm-stateless'. Anchor it so binding can only be+ * satisfied by the exact agent.+ */+export function exactNameFilter(name: string): { hasText: RegExp } {+ return {+ hasText: new RegExp(`^\\s*${name.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}\\s*$`),+ }+}diff --git a/desktop-app/test/e2e-playwright/helpers/gfsAclShareFixtures.ts b/desktop-app/test/e2e-playwright/helpers/gfsAclShareFixtures.tsnew file mode 100644index 000000000..8027f6596--- /dev/null+++ b/desktop-app/test/e2e-playwright/helpers/gfsAclShareFixtures.ts@@ -0,0 +1,66 @@+import {+ UUID_RE,+ runControlPostgresSql,+ sqlLiteral,+} from '../../../../tests/e2e/gfsUiFixtures'++/**+ * Named setup precondition: shares may target users/teams, never managed Host+ * subjects. Keeping one real source share makes the E2E prove both halves of+ * the Copy ACL contract: the source row is unchanged and no destination row is+ * cloned.+ */+export function seedIssue797SourceShare(resourceId: string, shareUserId: string): string {+ if (!UUID_RE.test(resourceId) || !UUID_RE.test(shareUserId)) {+ throw new Error('issue #797 source share requires UUID resource and user subjects')+ }+ const shareId = runControlPostgresSql(`+ INSERT INTO gfs_shares (+ drive, resource_id, subject_type, subject_id, permissions,+ include_descendants, created_by+ )+ VALUES (+ 'main', ${sqlLiteral(resourceId)}::uuid, 'user', ${sqlLiteral(shareUserId)},+ ARRAY['read']::text[], true, 'e2e:issue-797-source-share'+ )+ ON CONFLICT (drive, resource_id, subject_type, subject_id)+ DO UPDATE SET+ permissions = EXCLUDED.permissions,+ include_descendants = EXCLUDED.include_descendants,+ created_by = EXCLUDED.created_by+ RETURNING id::text;+ `)+ .split('\n')+ .map(line => line.trim())+ .find(line => UUID_RE.test(line))+ if (!shareId) throw new Error('failed to seed issue #797 source user share')+ return shareId+}++/** Canonical JSONB rows for every direct grant/share under a resource tree. */+export function getGfsTreeAclShareRows(rootId: string): string[] {+ if (!UUID_RE.test(rootId)) throw new Error(`invalid GFS root id: ${rootId}`)+ return runControlPostgresSql(`+ WITH RECURSIVE tree AS (+ SELECT resource_id FROM gfs_resources+ WHERE drive = 'main' AND resource_id = ${sqlLiteral(rootId)}::uuid+ AND deleted_at IS NULL+ UNION ALL+ SELECT child.resource_id FROM gfs_resources child+ JOIN tree ON child.parent_resource_id = tree.resource_id+ WHERE child.drive = 'main' AND child.deleted_at IS NULL+ ), acl_rows AS (+ SELECT 'grant'::text AS row_kind, id::text AS row_id,+ jsonb_build_object('kind', 'grant', 'row', to_jsonb(g))::text AS row_json+ FROM gfs_grants g WHERE resource_id IN (SELECT resource_id FROM tree)+ UNION ALL+ SELECT 'share'::text AS row_kind, id::text AS row_id,+ jsonb_build_object('kind', 'share', 'row', to_jsonb(s))::text AS row_json+ FROM gfs_shares s WHERE resource_id IN (SELECT resource_id FROM tree)+ )+ SELECT row_json FROM acl_rows ORDER BY row_kind, row_id;+ `)+ .split('\n')+ .map(line => line.trim())+ .filter(line => line.startsWith('{') && line.endsWith('}'))+}diff --git a/desktop-app/test/e2e-playwright/helpers/gfsAgentDiscovery.ts b/desktop-app/test/e2e-playwright/helpers/gfsAgentDiscovery.tsnew file mode 100644index 000000000..9394beecb--- /dev/null+++ b/desktop-app/test/e2e-playwright/helpers/gfsAgentDiscovery.ts@@ -0,0 +1,169 @@+/**+ * TEST-HARNESS discovery, not agent behavior: this module finds eligible+ * HCC-managed Host CRDs via kubectl so the suites can pick the two journey+ * agents (Agent A / Agent B). It has nothing to do with the agents' own+ * tool-based GFS file discovery (gfs_resolve/gfs_list), which the journeys+ * exercise through the real chat UI.+ */+import { kubectlOut } from '../../../../tests/e2e/gfsUiFixtures'++/** Historical fleet-wide identity, retained only as an explicit rejection guard. */+const LEGACY_FLEET_WIDE_SUBJECT_ID = '1st:mcp-host/standalone'++export interface ManagedGfsAgent {+ name: string+ namespace: string+ subjectId: string+}++interface CandidateError {+ namespace: string+ name: string+ message: string+}++function formatCandidateError(item: CandidateError): string {+ return `${item.namespace}/${item.name}: ${item.message}`+}++/**+ * Reads HCC safe metadata only: the Secret ANNOTATIONS below (expected subject,+ * host UID/generation) are non-sensitive drift metadata. No credential data is+ * requested, decoded, or printed — the go-template projects annotations only.+ */+function discoverManagedGfsAgentCandidates(): {+ candidates: ManagedGfsAgent[]+ candidateErrors: CandidateError[]+} {+ const expected = 'clerum.io/gfs-token-expected-subject'+ const uid = 'clerum.io/gfs-token-host-uid'+ const generation = 'clerum.io/gfs-token-host-generation'+ const template =+ `{{range .items}}{{with .metadata.annotations}}{{if index . "${expected}"}}` ++ `{{index . "${expected}"}}{{"\\t"}}` ++ `{{index . "${uid}"}}{{"\\t"}}` ++ `{{index . "${generation}"}}{{"\\n"}}{{end}}{{end}}{{end}}`+ const output = kubectlOut(['get', 'secrets', '-A', '-o', `go-template=${template}`])+ const bySubject = new Map<string, ManagedGfsAgent>()+ const candidateErrors: CandidateError[] = []+ for (const line of output.split('\n').map(value => value.trim()).filter(Boolean)) {+ const [annotatedSubject, hostUid, hostGeneration] = line.split('\t')+ const match = /^host:1st:([a-z0-9](?:[-a-z0-9]*[a-z0-9])?)\/([a-z0-9](?:[-a-z0-9]*[a-z0-9])?)$/.exec(+ annotatedSubject ?? ''+ )+ if (!match || !hostUid || !/^\d+$/.test(hostGeneration ?? '')) continue+ const namespace = match[1]!+ const name = match[2]!+ const subjectId = `1st:${namespace}/${name}`+ if (name === 'standalone' || subjectId === LEGACY_FLEET_WIDE_SUBJECT_ID) continue+ let hostState = ''+ try {+ hostState = kubectlOut([+ '-n',+ namespace,+ 'get',+ 'hosts',+ name,+ '-o',+ 'go-template={{.metadata.uid}}{{"\\t"}}{{.metadata.generation}}{{"\\t"}}{{if .metadata.deletionTimestamp}}deleting{{end}}{{"\\t"}}{{if eq .spec.enabled false}}disabled{{end}}',+ ]).trim()+ } catch (error) {+ // An infra error while validating a candidate must not be silently+ // reported as "agent does not exist"; it is surfaced with the final+ // topology failure so a broken kubectl path fails for the real reason.+ candidateErrors.push({+ namespace,+ name,+ message: error instanceof Error ? error.message : String(error),+ })+ continue+ }+ const [activeUid, activeGeneration, deleting, disabled] = hostState.split('\t')+ if (activeUid !== hostUid || activeGeneration !== hostGeneration || deleting || disabled) continue+ bySubject.set(subjectId, { name, namespace, subjectId })+ }+ if (bySubject.size === 0 && candidateErrors.length > 0) {+ throw new Error(+ `GFS agent discovery could not validate any candidate host: ${candidateErrors+ .map(formatCandidateError)+ .join('; ')}`+ )+ }+ return {+ candidates: [...bySubject.values()].sort((a, b) => a.subjectId.localeCompare(b.subjectId)),+ candidateErrors,+ }+}++function chooseManagedGfsAgent(+ candidates: ManagedGfsAgent[],+ candidateErrors: CandidateError[],+ requested: string | undefined,+ excluded?: string+): ManagedGfsAgent | undefined {+ const eligible = candidates.filter(item => item.subjectId !== excluded)+ if (requested) {+ const matches = eligible.filter(item => item.name === requested)+ if (matches.length !== 1) {+ // If the requested agent was among the candidates whose kubectl+ // validation errored, "missing" would misreport an infra failure as a+ // topology failure — include the recorded error for that candidate.+ const requestedErrors = candidateErrors+ .filter(item => item.name === requested)+ .map(formatCandidateError)+ throw new Error(+ `HCC agent "${requested}" is missing or ambiguous` ++ (requestedErrors.length > 0+ ? ` (candidate validation errors: ${requestedErrors.join('; ')})`+ : '')+ )+ }+ return matches[0]+ }+ return eligible.find(item => eligible.filter(other => other.name === item.name).length === 1)+}++/**+ * Live pod identity (UID + startTime) for an HCC-managed agent. Used to prove+ * "same runtime" claims: revocation enforcement must not depend on a pod+ * restart, so the identity captured before a revoke must equal the identity+ * observed after the denied retry.+ */+export function getManagedAgentPodIdentity(agent: ManagedGfsAgent): string {+ const identity = kubectlOut([+ '-n',+ agent.namespace,+ 'get',+ 'pods',+ '-l',+ `app=${agent.name}`,+ '-o',+ 'go-template={{range .items}}{{if not .metadata.deletionTimestamp}}{{.metadata.uid}}{{"\\t"}}{{.status.startTime}}{{"\\n"}}{{end}}{{end}}',+ ]).trim()+ if (!identity) {+ throw new Error(`no live pod found for HCC-managed agent ${agent.namespace}/${agent.name}`)+ }+ return identity+}++export function discoverManagedGfsAgent(): ManagedGfsAgent {+ const { candidates, candidateErrors } = discoverManagedGfsAgentCandidates()+ const agent = chooseManagedGfsAgent(candidates, candidateErrors, process.env.E2E_GFS_AGENT_A)+ if (!agent) throw new Error('GFS agent E2E requires one unambiguous HCC-managed agent name')+ return agent+}++export function discoverManagedGfsAgents(): [ManagedGfsAgent, ManagedGfsAgent] {+ const { candidates, candidateErrors } = discoverManagedGfsAgentCandidates()+ const agentA = chooseManagedGfsAgent(candidates, candidateErrors, process.env.E2E_GFS_AGENT_A)+ const agentB = chooseManagedGfsAgent(+ candidates,+ candidateErrors,+ process.env.E2E_GFS_AGENT_B,+ agentA?.subjectId+ )+ if (!agentA || !agentB || agentA.name === agentB.name) {+ throw new Error('Issue #797 requires two distinct, unambiguous HCC-managed agent names')+ }+ return [agentA, agentB]+}diff --git a/desktop-app/test/e2e-playwright/helpers/gfsFixtures.ts b/desktop-app/test/e2e-playwright/helpers/gfsFixtures.tsindex 1b404edc4..642d2faec 100644--- a/desktop-app/test/e2e-playwright/helpers/gfsFixtures.ts+++ b/desktop-app/test/e2e-playwright/helpers/gfsFixtures.ts@@ -1,39 +1,43 @@-/**- * GFS fixtures for the agent-file-read E2E journey (issue #775).- *- * Seeds two isolated GFS files through the shared SQL fixtures:- * - `granted`: visible to the Desktop user AND granted read to the agent- * host `chatllm` — the happy path.- * - `ungranted`: visible to the Desktop user but NOT granted to the host —- * the agent must receive a clean authorization denial (403),- * never a permission-store outage (503 not_mounted).- *- * Also provides the fail-loud infra guard: when gfsc is unhealthy the suite- * THROWS with the concrete pod/Secret state. It never skips and never mocks —- * a broken permission store is an infrastructure blocker, not a reason to- * fake a pass (repo rule: tests fail loud, especially minikube E2E).- */+/** Exact-subject GFS fixtures for the #775 regression and #797 Copy journey. */import {type GfsFileFixture,cleanupGfsFixture,+ countGfsLiveChildrenByName,+ getGfsChildResourceSummary,getE2EUserId,kubectlOut,+ runControlPostgresSql,seedGfsFileFixture,seedGfsGrant,+ sqlLiteral,uniqueGfsFixtureName,} from '../../../../tests/e2e/gfsUiFixtures'+import {+ type GfsCopyTreeFixture,+ cleanupGfsCopyTreeFixture,+ getGfsHostGrantsUnderTree,+ getGfsTreeAclShareCounts,+ getGfsTreeSnapshot,+ seedGfsCopyTreeFixture,+} from '../../../../tests/e2e/gfsCopyFixtures'+import { request } from '@playwright/test'+import {+ discoverManagedGfsAgent,+ discoverManagedGfsAgents,+ type ManagedGfsAgent,+} from './gfsAgentDiscovery'+import { seedIssue797SourceShare } from './gfsAclShareFixtures'-/**- * The Desktop agent journey runs through the concrete `chatllm` Host. GFS- * grants are host-specific, so `chatllm-stateless` and every other first-party- * Host remain independently denied unless they receive their own grant.- */-export const FIRST_PARTY_HOST_SUBJECT_ID = '1st:mcp-host/chatllm'+export {+ discoverManagedGfsAgent,+ discoverManagedGfsAgents,+ type ManagedGfsAgent,+} from './gfsAgentDiscovery'+export { getGfsTreeAclShareRows } from './gfsAclShareFixtures'const GFS_NS = 'gfs'-// Pod-template labels — pods do NOT inherit the deployment-level managed-by-// label (see gfsFactory commonLabels vs spec.selector).const GFSC_POD_SELECTOR = 'app=gfs-controller'+const ISSUE_797_SHARE_RECIPIENT_EMAIL = '[email protected]'/*** FAIL LOUD, NEVER SKIP: proves gfsc can actually authorize before any test@@ -88,6 +92,8 @@ export function assertGfsInfraHealthy(): void {}export interface AgentGfsFixtures {+ /** Exact HCC-managed host granted by this fixture. */+ agent: ManagedGfsAgent/** Visible to the user AND readable by the agent host (happy path). */granted: GfsFileFixture/** Visible to the user but NOT granted to the host (expects a 403 denial). */@@ -96,12 +102,170 @@ export interface AgentGfsFixtures {cleanup(): void}+export interface AgentGfsCopyFixtures {+ agentA: ManagedGfsAgent+ agentB: ManagedGfsAgent+ tree: GfsCopyTreeFixture+ fileCopyName: string+ folderCopyName: string+ renamedFolderName: string+ deniedCopyName: string+ revokedCopyName: string+ destinationGrantId: string+ /** Source user-share whose exact row must survive Copy unchanged. */+ sourceShareId: string+ sourceShareSubjectId: string+ cleanup(): void+}++export function seedAgentGfsCopyFixtures(ownerEmail: string): AgentGfsCopyFixtures {+ const [agentA, agentB] = discoverManagedGfsAgents()+ const tree = seedGfsCopyTreeFixture(uniqueGfsFixtureName('e2e-gfs-copy-797'))+ try {+ const ownerUserId = getE2EUserId(ownerEmail)+ const sourceShareSubjectId = getE2EUserId(ISSUE_797_SHARE_RECIPIENT_EMAIL)+ for (const resourceId of [tree.sourceResourceId, tree.destinationResourceId]) {+ seedGfsGrant({+ resourceId,+ subjectType: 'user',+ subjectId: ownerUserId,+ permissions: ['read'],+ inherit: true,+ grantedBy: 'e2e:issue-797-owner',+ })+ }+ seedGfsGrant({+ resourceId: tree.sourceResourceId,+ subjectType: 'host',+ subjectId: agentA.subjectId,+ permissions: ['read'],+ inherit: true,+ grantedBy: 'e2e:issue-797-agent-a',+ })+ seedGfsGrant({+ resourceId: tree.sourceResourceId, subjectType: 'host', subjectId: agentB.subjectId,+ permissions: ['read'], inherit: false, grantedBy: 'e2e:issue-797-agent-b-root-only',+ })+ seedGfsGrant({+ resourceId: tree.destinationResourceId, subjectType: 'host', subjectId: agentB.subjectId,+ permissions: ['read', 'write'], inherit: true, grantedBy: 'e2e:issue-797-agent-b-destination',+ })+ const agentBSource = getGfsHostGrantsUnderTree(tree.sourceResourceId, agentB.subjectId)+ if (agentBSource.length !== 1 || agentBSource[0]?.resourceId !== tree.sourceResourceId ||+ agentBSource[0].inherit || agentBSource[0].permissions.join(',') !== 'read') {+ throw new Error('Agent B fixture must have root-only source read and no descendant grant')+ }+ const agentBDest = getGfsHostGrantsUnderTree(tree.destinationResourceId, agentB.subjectId)+ if (agentBDest.length !== 1 || !agentBDest[0]?.inherit ||+ agentBDest[0].permissions.join(',') !== 'read,write') {+ throw new Error('Agent B fixture must have destination read/write')+ }+ const destinationGrantId = seedGfsGrant({+ resourceId: tree.destinationResourceId,+ subjectType: 'host',+ subjectId: agentA.subjectId,+ permissions: ['read', 'write'],+ inherit: true,+ grantedBy: 'e2e:issue-797-agent-a',+ })+ const sourceShareId = seedIssue797SourceShare(tree.sourceResourceId, sourceShareSubjectId)+ return {+ agentA,+ agentB,+ tree,+ fileCopyName: `${tree.sourceName}-file-copy.txt`,+ folderCopyName: `${tree.sourceName}-copy`,+ renamedFolderName: `${tree.sourceName}-renamed`,+ deniedCopyName: `${tree.sourceName}-agent-b-denied`,+ revokedCopyName: `${tree.sourceName}-revoked-denied`,+ destinationGrantId,+ sourceShareId,+ sourceShareSubjectId,+ cleanup: () => cleanupGfsCopyTreeFixture(tree),+ }+ } catch (error) {+ try {+ cleanupGfsCopyTreeFixture(tree)+ } catch (cleanupError) {+ throw new Error(+ `GFS Copy setup failed (${String(error)}) and cleanup failed (${String(cleanupError)})`+ )+ }+ throw error+ }+}++export async function revokeGfsGrantViaControlApi(grantId: string): Promise<void> {+ const rawBase = process.env.E2E_CONTROL_API_URL || process.env.CONTROL_API_BASE_URL+ if (!rawBase) throw new Error('audited GFS revoke requires an explicit Control API URL')+ const base = new URL(rawBase)+ if (!['127.0.0.1', 'localhost'].includes(base.hostname)) {+ throw new Error(`refusing issue #797 fixture revoke against ${base.origin}`)+ }+ // The desktop suite has no storageState producer, so the admin session is+ // created here through the real cookie login the Control UI uses. The+ // local-only default password is safe behind the localhost guard above and+ // matches the repo-wide E2E admin credential priority.+ const api = await request.newContext({ baseURL: base.origin })+ try {+ const username = process.env.TEST_ADMIN_USERNAME || 'admin'+ const password =+ process.env.E2E_ADMIN_PASSWORD ||+ process.env.ADMIN_PASSWORD ||+ process.env.ADMIN_PASS ||+ process.env.TEST_ADMIN_PASSWORD ||+ 'admin123!'+ const login = await api.post('/api/v1/admin/auth/login', {+ data: { username, password },+ })+ if (!login.ok()) {+ throw new Error(+ `audited GFS revoke admin login failed with HTTP ${login.status()}: ${await login.text()}`+ )+ }+ // The admin session cookie is issued Secure; Playwright's cookie jar+ // rightly refuses to send Secure cookies over the http:// port-forward, so+ // API-only consumers send the captured value as an explicit Cookie header+ // (same pattern as the root suite's adminSessionCookieHeader helper).+ const sessionCookie = (await api.storageState()).cookies.find(+ cookie => cookie.name === 'control_ui_admin_session'+ )+ if (!sessionCookie?.value) {+ throw new Error('audited GFS revoke admin login did not set control_ui_admin_session')+ }+ const response = await api.delete(`/api/v1/gfs/grants/${encodeURIComponent(grantId)}`, {+ headers: {+ 'X-Request-Id': `e2e-797-revoke-${Date.now()}`,+ cookie: `${sessionCookie.name}=${sessionCookie.value}`,+ },+ })+ if (!response.ok()) {+ throw new Error(`audited GFS revoke failed with HTTP ${response.status()}: ${await response.text()}`)+ }+ } finally {+ await api.dispose()+ }+}++export function gfsGrantRevokeAuditCount(agent: ManagedGfsAgent): number {+ const rows = runControlPostgresSql(`+ SELECT count(*)::text FROM gfs_audit+ WHERE subject = ${sqlLiteral(`host:${agent.subjectId}`)}+ AND op = 'grant.delete' AND outcome = 'allowed';+ `)+ return Number(rows.trim())+}++export {+ countGfsLiveChildrenByName,+ getGfsChildResourceSummary,+ getGfsTreeAclShareCounts,+ getGfsTreeSnapshot,+}+export function seedAgentGfsFixtures(ownerEmail: string): AgentGfsFixtures {+ const agent = discoverManagedGfsAgent()const ownerUserId = getE2EUserId(ownerEmail)- // Exception-safe seeding: if any later step throws, tear down whatever was- // already created (rows + PVC blobs) before rethrowing — a partial seed must- // not leak into the shared profile, and afterAll never runs on a failed- // beforeAll.const seeded: GfsFileFixture[] = []let granted: GfsFileFixturelet ungranted: GfsFileFixture@@ -127,7 +291,7 @@ export function seedAgentGfsFixtures(ownerEmail: string): AgentGfsFixtures {seedGfsGrant({resourceId: granted.fileResourceId,subjectType: 'host',- subjectId: FIRST_PARTY_HOST_SUBJECT_ID,+ subjectId: agent.subjectId,permissions: ['read'],inherit: true,grantedBy: 'e2e:gfs-agent-file-read',@@ -152,6 +316,7 @@ export function seedAgentGfsFixtures(ownerEmail: string): AgentGfsFixtures {}return {+ agent,granted,ungranted,cleanup: () => {diff --git a/desktop-app/test/e2e-playwright/workflowUi.ts b/desktop-app/test/e2e-playwright/workflowUi.tsindex b2f66b09a..405565c31 100644--- a/desktop-app/test/e2e-playwright/workflowUi.ts+++ b/desktop-app/test/e2e-playwright/workflowUi.ts@@ -594,14 +594,19 @@ export async function launchAndLogin(await emailInput.fill(email)await passwordInput.fill(E2E_DESKTOP_PASSWORD)const signInButton = page.getByRole('button', { name: /^Sign in$/ })- await expect(signInButton).toBeEnabled({ timeout: 10_000 })- await humanUiClick(signInButton)+ // A restored session can race the form: the shell may replace the form+ // between fill and click, making the button legitimately disappear.+ // Accept either outcome — click when clickable, and only ever settle on+ // the authenticated shell.await expect.poll(async () => {if (await authenticatedShell.isVisible().catch(() => false)) return 'authenticated'const errorToast = page.getByRole('alert').filter({ hasText: /login|password|failed/i })if (await errorToast.isVisible().catch(() => false)) return 'error'+ if (await signInButton.isEnabled().catch(() => false)) {+ await humanUiClick(signInButton).catch(() => undefined)+ }return 'pending'},{@@ -615,11 +620,31 @@ export async function launchAndLogin(await expect(authenticatedShell).toBeVisible({ timeout: 60_000 })await expect(settingsMenuButton).toBeVisible({ timeout: 20_000 })- await humanUiClick(settingsMenuButton)+ // Session-list hydration storms can dismiss the account popover at any+ // point of the check, so the whole open->verify sequence retries a bounded+ // number of times. The final attempt performs the same hard assertions, so+ // a genuinely missing identity still fails loudly.const signedInAccount = page.getByLabel('Signed in account')- await expect(signedInAccount).toBeVisible({ timeout: 20_000 })- await expect(userDisplayName).toBeVisible({ timeout: 20_000 })- await expect(signedInAccount).toContainText(email, { timeout: 20_000 })+ const verifyIdentity = async (timeout: number) => {+ await humanUiClick(settingsMenuButton)+ await expect(signedInAccount).toBeVisible({ timeout })+ await expect(userDisplayName).toBeVisible({ timeout })+ await expect(signedInAccount).toContainText(email, { timeout })+ }+ let identityVerified = false+ for (let attempt = 0; attempt < 4 && !identityVerified; attempt += 1) {+ try {+ await verifyIdentity(7_000)+ identityVerified = true+ } catch {+ await page.keyboard.press('Escape')+ await page.waitForTimeout(1_000)+ }+ }+ // The account section inside the popover resolves from its own fetch,+ // which can starve behind large session-list hydration; the final attempt+ // gets the full budget and still hard-fails on a missing identity.+ if (!identityVerified) await verifyIdentity(60_000)await page.keyboard.press('Escape')} catch (error) {const bodyText = await pagediff --git a/desktop-app/test/gfsAclShareFixtures.test.ts b/desktop-app/test/gfsAclShareFixtures.test.tsnew file mode 100644index 000000000..3db3831d2--- /dev/null+++ b/desktop-app/test/gfsAclShareFixtures.test.ts@@ -0,0 +1,53 @@+import { beforeEach, describe, expect, it, vi } from 'vitest'++const runControlPostgresSqlMock = vi.hoisted(() => vi.fn())++vi.mock('../../tests/e2e/gfsUiFixtures', () => ({+ UUID_RE: /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,+ runControlPostgresSql: runControlPostgresSqlMock,+ sqlLiteral: (value: string) => `'${value.replace(/'/g, "''")}'`,+}))++import {+ getGfsTreeAclShareRows,+ seedIssue797SourceShare,+} from './e2e-playwright/helpers/gfsAclShareFixtures'++describe('issue #797 GFS ACL/share fixture evidence', () => {+ beforeEach(() => runControlPostgresSqlMock.mockReset())++ it('seeds the named source share for a user, never a Host subject', () => {+ runControlPostgresSqlMock.mockReturnValue('d4d2c593-6932-488e-844c-c5852b910783\n')++ expect(+ seedIssue797SourceShare(+ '5a50453e-04d1-4403-8473-23013eaa56c7',+ 'ef72208d-783a-4574-9181-440a6764fa27'+ )+ ).toBe('d4d2c593-6932-488e-844c-c5852b910783')++ const sql = String(runControlPostgresSqlMock.mock.calls[0]?.[0])+ expect(sql).toContain("'user', 'ef72208d-783a-4574-9181-440a6764fa27'")+ expect(sql).toContain("ARRAY['read']::text[], true")+ expect(sql).not.toContain("'host'")+ })++ it('returns stable full-row JSON evidence for both grants and shares', () => {+ const rows = [+ '{"kind":"grant","row":{"id":"grant-1"}}',+ '{"kind":"share","row":{"id":"share-1"}}',+ ]+ runControlPostgresSqlMock.mockReturnValue(`\n${rows.join('\n')}\n`)++ expect(getGfsTreeAclShareRows('5a50453e-04d1-4403-8473-23013eaa56c7')).toEqual(rows)+ const sql = String(runControlPostgresSqlMock.mock.calls[0]?.[0])+ expect(sql).toContain("jsonb_build_object('kind', 'grant', 'row', to_jsonb(g))")+ expect(sql).toContain("jsonb_build_object('kind', 'share', 'row', to_jsonb(s))")+ expect(sql).toContain('ORDER BY row_kind, row_id')+ })++ it('rejects an invalid root before querying PostgreSQL', () => {+ expect(() => getGfsTreeAclShareRows('not-a-resource-id')).toThrow('invalid GFS root id')+ expect(runControlPostgresSqlMock).not.toHaveBeenCalled()+ })+})diff --git a/desktop-app/test/gfsFixtureDiscovery.test.ts b/desktop-app/test/gfsFixtureDiscovery.test.tsnew file mode 100644index 000000000..e9f517c22--- /dev/null+++ b/desktop-app/test/gfsFixtureDiscovery.test.ts@@ -0,0 +1,74 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'++const execFileSyncMock = vi.hoisted(() => vi.fn())++vi.mock('node:child_process', () => ({+ execFileSync: execFileSyncMock,+}))++import {+ discoverManagedGfsAgent,+ discoverManagedGfsAgents,+} from './e2e-playwright/helpers/gfsFixtures'++describe('discoverManagedGfsAgents', () => {+ const context = 'clerum-codex-gfs-fixture-test'+ let secretRows: string++ beforeEach(() => {+ process.env.E2E_K8S_CONTEXT = context+ secretRows =+ 'host:1st:mcp-host/agent-a\tuid-a\t1\n' ++ 'host:1st:mcp-host/agent-b\tuid-b\t2\n' ++ 'host:1st:mcp-host/incomplete\t\t\n'+ execFileSyncMock.mockImplementation((_command: string, args: string[]) => {+ const resourceIndex = args.indexOf('get') + 1+ const resource = args[resourceIndex]+ if (resource === 'secrets') {+ return secretRows+ }+ if (resource === 'hosts' && args[resourceIndex + 1] === 'agent-a') {+ return 'uid-a\t1\t\t'+ }+ if (resource === 'hosts' && args[resourceIndex + 1] === 'agent-b') {+ return 'uid-b\t2\t\t'+ }+ throw new Error(`unexpected kubectl call: ${args.join(' ')}`)+ })+ })++ afterEach(() => {+ delete process.env.E2E_K8S_CONTEXT+ execFileSyncMock.mockReset()+ })++ it('reads only annotated Secret metadata and returns two active exact-subject hosts', () => {+ expect(discoverManagedGfsAgents()).toEqual([+ { name: 'agent-a', namespace: 'mcp-host', subjectId: '1st:mcp-host/agent-a' },+ { name: 'agent-b', namespace: 'mcp-host', subjectId: '1st:mcp-host/agent-b' },+ ])++ const calls = execFileSyncMock.mock.calls+ expect(calls).toHaveLength(3)+ for (const [command, args] of calls) {+ expect(command).toBe('kubectl')+ expect(args.slice(0, 2)).toEqual(['--context', context])+ }++ const secretArgs = calls[0]![1] as string[]+ const outputArg = secretArgs.find(value => value.startsWith('go-template='))+ expect(outputArg).toContain('{{with .metadata.annotations}}')+ expect(outputArg).toContain('clerum.io/gfs-token-expected-subject')+ expect(secretArgs).not.toContain('json')+ })++ it('keeps the single-agent read regression independent from the two-agent Copy gate', () => {+ secretRows = 'host:1st:mcp-host/agent-a\tuid-a\t1\n'++ expect(discoverManagedGfsAgent()).toEqual({+ name: 'agent-a',+ namespace: 'mcp-host',+ subjectId: '1st:mcp-host/agent-a',+ })+ })+})diff --git a/docs/deploy/gfs-permission-store.md b/docs/deploy/gfs-permission-store.mdindex 7d4812deb..ab070fb4c 100644--- a/docs/deploy/gfs-permission-store.md+++ b/docs/deploy/gfs-permission-store.md@@ -9,19 +9,23 @@ not_mounted` on every GFS operation.No GFS database credential ever lives in code or in a committed manifest:-1. **Migration `0048_gfs_permission_store`** (control-api,- `applyGfsPermissionStoreSchema` in `control-api/src/db.ts`) creates the- `gfs_controller` role **NOLOGIN**, purely as a GRANT target: SELECT on- `gfs_resources` / `gfs_grants` / `gfs_shares`, INSERT-only on `gfs_audit`,- column-scoped SELECT on `control_admin_users` / `team_members`, and explicit- REVOKEs for everything else.-2. **`deploy/scripts/provision-gfs-db.sh`** (CONTEXT-aware, idempotent) grants- `LOGIN`, rotates the password (`openssl rand -hex 24`), builds the DSN,- patches it into the `gfs/gfs-controller-db` Secret key `connection-string`,- stamps the rotation timestamp as the `clerum.io/gfs-dsn-rotated-at`- annotation, and rolls both gfsc deployments (selector- `clerum.io/managed-by=host-context-controller`).-3. **host-context-controller** injects the Secret into gfsc pods as the+1. Existing migrations create the writer `gfs_controller` role; the additive+ reader-role migration creates `gfs_controller_reader`. Both begin as+ `NOLOGIN` GRANT targets. Writer retains mutation authority required by GFSC;+ reader receives authorization reads, append-only audit access, `NOINHERIT`,+ and no memberships or manifest authority.+2. **`deploy/scripts/provision-gfs-db.sh`** requires one explicit mode:+ `stage-writer`, `stage-reader`, `rotate-reader`, or `rotate-writer`. Normal+ deployment runs `stage-writer` and then `stage-reader`; both preserve valid+ credentials. `stage-writer` atomically adopts a legacy writer Secret that+ predates lifecycle annotations only after strict DSN, real SCRAM authentication,+ privilege-contract, empty-pending, and resourceVersion checks. It never rotates+ the password or restarts the writer. `stage-reader` performs a directed reader+ restart only when an existing reader already consumes a newly committed+ reader credential and is stale for that credential.+ Reader rotation targets only `gfsc-reader`, and writer rotation targets only+ `gfsc-writer`. No mode uses a broad selector.+3. **host-context-controller** injects the independent reader/writer Secrets into gfsc pods as the`GFS_PG_CONNECTION_STRING` env var via `secretKeyRef`(`host-context-controller/src/k8s/gfsFactory.ts`). Env vars resolve at**pod creation time** — a Secret rotation only takes effect after the pods@@ -31,6 +35,75 @@ No GFS database credential ever lives in code or in a committed manifest:`GfsError("not_mounted")` HTTP 503 — gfsc never authorizes what it cannotverify).+## Deployment and rotation order++Normal dev/prod order is: migrations, runtime-role reconciliation, apply the+central `reconcile-gfs-deploy-credentials.sh` entrypoint, then apply+the environment overlay. This sequence does not rotate an already-valid role.+The reconciler migrates legacy writer apply ownership, bootstraps the writer+with explicit `rotate-writer` only when its connection key is empty, validates+non-rotating `stage-writer`, and declares/stages the reader.+On fresh cutover the overlay creates the reader with the staged identity; on+recovery, `stage-reader` may restart only a stale `gfsc-reader` that already+references the committed reader Secret.++Credential changes use the Secret lifecycle `ready → pending → applying →+rollout-pending → rollout-running → ready`. A second process cannot adopt+`applying`. After confirming that the previous process has ended, recover an+abandoned apply or rollout with the same explicit mode plus+`GFS_RECOVER_ABANDONED_STATE=true`; the persisted candidate is resumed instead+of generating another credential.++Legacy adoption reads resourceVersion, lifecycle, active DSN, pending candidate,+and rotation timestamp from one Kubernetes GET. Its JSON Patch tests that exact+resourceVersion, so a concurrent rotation wins and adoption writes nothing. If+an old Secret lacks the timestamp, adoption does not invent pod freshness: each+live writer pod must be Ready and prove, through a no-output stdin comparison,+that its loaded environment contains the exact authenticated DSN. The oldest+matching pod creation time becomes the conservative freshness boundary. No pod+is restarted. If no writer deployment exists yet, the adoption time is safe+because every future pod will necessarily be newer.++Every database-recreation path runs `preflight-gfs-db-reset.sh` before scaling+down or deleting the PVC. The preflight intentionally does not authenticate to+PostgreSQL, because reset and WAL recovery must remain usable when the database+is unavailable or corrupt. It reads one Kubernetes snapshot per Secret and+fails closed unless writer and reader are both `ready`, have no pending+candidate, and contain a structurally valid active DSN for the exact expected+role, Service endpoint, port, and database.++After PostgreSQL is recreated and Ready, all reset paths call the single+`converge-control-db-after-reset.sh` entrypoint. It applies migrations,+reconciles runtime roles, waits for Control API, opts into+`GFS_RESTORE_ACTIVE_NOLOGIN=true`, and runs the real Service/SCRAM verifier.+That reset-only restoration requires lifecycle `ready`, no candidate, the+exact disabled-role privilege contract, and the unchanged committed DSN;+normal deploys cannot reactivate a disabled role. The shared sequence is used+by local, dev, prod, and full-setup `--reset-db` paths so no caller can report+success after only a partial database rebuild. Automatic destructive WAL+recovery is intentionally disabled: replacing control-DB storage always+requires the exact observed PVC UID. Resume stays bound to that original+authorization and may converge the replacement, but it may never scrub a+different PVC.++For an existing minikube profile with Ready control-api, full setup, pre-gate+sync, and `minikube-deploy-all` complete the same reader staging before the full+overlay. A fresh profile first declares the Secrets and remains fail-closed;+after migrations it runs `rotate-writer` only if the writer key is empty, then+runs `stage-writer` and `stage-reader`. A non-empty writer key is validated and+preserved; a legacy Secret receives the CAS-protected lifecycle annotation and,+only when absent, a conservative pod-backed rotation timestamp.++`rotate-reader` performs an availability-preserving directed reader rollout with+`maxUnavailable: 0` and `maxSurge: 1`. Successful local probes do not guarantee+zero interruption in dev or prod. `rotate-writer` performs a directed singleton-writer rollout+and therefore has a bounded write interruption; it is not zero-downtime. HCC,+not either rotation mode, owns full GFSC image/template rollout ordering.++Both roles require `USAGE` and `SELECT`, but not `UPDATE`, on+`gfs_audit_sequence_no_seq`. Reader also requires `NOINHERIT` and zero role+memberships.+## The manifest is provisioning-owned (the historical reapply hazard)`deploy/base/gfs/gfs-controller-db.yaml` declares the Secret **without** the@@ -42,11 +115,13 @@ provisioned DSN.Historically the manifest shipped `connection-string: ""`, so every overlayapply silently wiped the provisioned credential — the root enabler of issue-#775. If you operate a cluster whose Secret predates this change, the FIRST-apply after upgrading removes the legacy empty key from last-applied (and with-it the provisioned value): re-run the provisioning script immediately after-that first apply. `make minikube-deploy-all` now does this automatically when-the GFS stack is deployed and control-api is Ready.+#775. `deploy/scripts/apply-gfs-writer-secret.sh` makes that historical first+upgrade safe: for an existing Secret it first replaces only the legacy+`last-applied-configuration` record with the keyless manifest, then performs+the normal apply. The live DSN is never removed. Fresh bootstrap skips that+migration and creates the empty fail-closed Secret normally. Dev/prod CI, GCP+Make targets, full setup, pre-gate sync, and `minikube-deploy-all` all use this+single helper before an overlay can prune legacy ownership.On a fresh cluster the failure mode is loud by construction: gfsc pods sit in`CreateContainerConfigError` (missing Secret key) until provisioning runs.@@ -116,16 +191,23 @@ and user-facing 503s later).## Recovery```bash-CONTEXT=<kube-context> deploy/scripts/provision-gfs-db.sh # idempotent+CONTEXT=<kube-context> deploy/scripts/provision-gfs-db.sh rotate-reader+# Use rotate-writer only when writer repair is explicitly required.MINIKUBE_PROFILE=<profile> make minikube-verify-gfs```-The script verifies the role exists (fails loud pointing at migration 0048),+The script verifies the role exists (writer migration 0048; reader migration 0071),rotates the password, patches the Secret, stamps the rotation annotation, and-rolls + waits for both gfsc deployments.+rolls and waits only for the selected gfsc Deployment.## Credential repair is not resource authorization+HCC rollback retains both database roles and their Kubernetes objects. Capture+the exact pre-cutover revision and immutable images, use `rollout undo` with+that revision, prove old HCC reconciles through the writer compatibility+identity, and reapply the candidate through the normal branch-owned helper.+Do not use an ad hoc rollback manifest or remove the additive reader state.+After the store is healthy again, an agent host can still receive a legitimate**403 denial** for a specific file: a host principal resolves only to its ownsubject (`gfs-controller/src/authz/subjectResolver.ts`, deny-by-default), and@@ -134,3 +216,37 @@ user-selected resource is an explicit governance operation through thedelegation engine (`control-api/src/gfs/delegation.ts`). When validating acredential repair, use a fixture that IS granted to the host — a 403 on anungranted file is the authorization model working, not a regression.++## Legacy `standalone` grant cutover++`host:1st:mcp-host/standalone` is a retired fleet-wide principal. Managed Hosts+authenticate only as their exact `host:1st:<namespace>/<name>` subject, future+Hosts inherit nothing, and the legacy subject is never an authorization+fallback. Legacy rows remain visible for inventory until their individual+replacements have been reviewed; their presence does not make them effective.++Migration is deliberately separate from deployment. Dev and production+workflows must not infer recipients, fan a grant out to every Host, or mutate+grants automatically. Before the identity cutover in an environment that may+contain legacy rows:++1. Build Control API and run `scripts/gfs-legacy-standalone-grants.mjs report`+ against HTTPS or a loopback port-forward, using the CLI's private local+ authentication-file option.+2. Save the emitted `mappingTemplate` as a reviewed JSON document. For each+ legacy grant, name only the exact active Host subjects approved to receive+ it. An empty target list is valid and means no replacement grant.+3. Run the CLI's `apply` mode with that mapping and `--confirm-reviewed`, then+ rerun `report`.+4. Resolve every failed or unexpected mapping explicitly. Do not broaden a+ mapping merely to make the report empty, and securely remove temporary+ local authentication and mapping artifacts afterward.++The CLI enforces private-file permissions and bounded mappings; its header+documents the complete invocation. Apply creates only approved individual+grants, rejects managed-agent permissions beyond `read` and `write`, and does+not delete or rewrite the source legacy row. If a mapping is incomplete at+cutover, the affected agent loses that legacy access by design (fail closed):+no data is deleted and no permission is silently inherited. Treat the reviewed+report as an environment rollout precondition while keeping apply an explicit+operator action rather than a deployment side effect.diff --git a/scripts/gfs-legacy-standalone-grants.mjs b/scripts/gfs-legacy-standalone-grants.mjsnew file mode 100755index 000000000..3458e0815--- /dev/null+++ b/scripts/gfs-legacy-standalone-grants.mjs@@ -0,0 +1,131 @@+#!/usr/bin/env node++/**+ * Build Control API, then run `report --base-url URL --session-file FILE`.+ * Copy the emitted mappingTemplate to a reviewed JSON file, fill each exact+ * target list, then run `apply` with the same options plus+ * `--mapping FILE --confirm-reviewed`. The session file must be mode 0600; its+ * value is used only for the request cookie and is never emitted.+ */++import { readFile, stat } from 'node:fs/promises'+import { pathToFileURL } from 'node:url'+import {+ applyReviewedLegacyGrantMigration,+ buildLegacyGrantMigrationReport,+} from '../control-api/dist/gfs/legacyStandaloneGrantMigration.js'++const MAX_MAPPING_FILE_BYTES = 1024 * 1024++function option(args, name) {+ const index = args.indexOf(name)+ return index >= 0 ? args[index + 1] : undefined+}++async function readPrivateValue(path) {+ const metadata = await stat(path)+ if ((metadata.mode & 0o077) !== 0) throw new Error('session_file_permissions_too_open')+ const value = (await readFile(path, 'utf8')).trim()+ if (!value || value.length > 4096) throw new Error('session_file_invalid')+ return value+}++export async function readBoundedMapping(path) {+ const metadata = await stat(path)+ if (!metadata.isFile() || metadata.size > MAX_MAPPING_FILE_BYTES) {+ throw new Error('mapping_file_invalid_or_too_large')+ }+ const contents = await readFile(path)+ if (contents.byteLength > MAX_MAPPING_FILE_BYTES) {+ throw new Error('mapping_file_invalid_or_too_large')+ }+ return JSON.parse(contents.toString('utf8'))+}++export class LegacyGrantControlApiClient {+ constructor(baseUrl, sessionValue, fetchImpl = fetch) {+ const parsed = new URL(baseUrl)+ const loopbackHost = ['localhost', '127.0.0.1', '[::1]'].includes(parsed.hostname)+ const safeTransport = parsed.protocol === 'https:' || (parsed.protocol === 'http:' && loopbackHost)+ if (!safeTransport || parsed.username || parsed.password) {+ throw new Error('base_url_invalid')+ }+ this.baseUrl = parsed.toString().replace(/\/$/, '')+ this.sessionValue = sessionValue+ this.fetchImpl = fetchImpl+ }++ async request(path, options = {}) {+ const response = await this.fetchImpl(`${this.baseUrl}${path}`, {+ ...options,+ redirect: 'error',+ headers: {+ Cookie: `control_ui_admin_session=${this.sessionValue}`,+ 'Content-Type': 'application/json',+ ...options.headers,+ },+ })+ const body = await response.json().catch(() => ({}))+ return { response, body }+ }++ async getLegacyGrants() {+ const result = await this.request('/api/v1/gfs/grants/legacy-standalone')+ if (!result.response.ok) throw new Error(`legacy_grant_report_failed:${result.response.status}`)+ return result.body+ }++ async getTrustedHostDirectory() {+ const result = await this.request('/api/v1/admin/hosts-overview')+ if (!result.response.ok) throw new Error(`trusted_host_directory_failed:${result.response.status}`)+ return result.body+ }++ async putGrant(body) {+ try {+ const result = await this.request('/api/v1/gfs/grants', {+ method: 'PUT',+ body: JSON.stringify(body),+ })+ return {+ ok: result.response.ok,+ status: result.response.status,+ error:+ typeof result.body?.error === 'string' && /^[a-z][a-z0-9_]{0,63}$/.test(result.body.error)+ ? result.body.error+ : result.response.ok+ ? undefined+ : 'request_rejected',+ }+ } catch {+ return { ok: false, error: 'request_failed' }+ }+ }+}++export async function main(args = process.argv.slice(2)) {+ const mode = args[0]+ const baseUrl = option(args, '--base-url')+ const sessionFile = option(args, '--session-file')+ if (!['report', 'apply'].includes(mode) || !baseUrl || !sessionFile) {+ throw new Error('usage: report|apply --base-url URL --session-file MODE_0600_FILE')+ }+ const api = new LegacyGrantControlApiClient(baseUrl, await readPrivateValue(sessionFile))+ if (mode === 'report') return buildLegacyGrantMigrationReport(api)+ if (!args.includes('--confirm-reviewed')) throw new Error('apply_requires_confirm_reviewed')+ const mappingPath = option(args, '--mapping')+ if (!mappingPath) throw new Error('apply_requires_mapping')+ return applyReviewedLegacyGrantMigration(api, await readBoundedMapping(mappingPath))+}++if (import.meta.url === pathToFileURL(process.argv[1] ?? '').href) {+ main()+ .then(result => {+ process.stdout.write(`${JSON.stringify(result, null, 2)}\n`)+ if (result.mode === 'apply' && !result.allApprovedIndividualGrantsSucceeded) process.exitCode = 1+ })+ .catch(error => {+ process.stderr.write(`${error instanceof Error ? error.message : 'migration_failed'}\n`)+ process.exitCode = 1+ })+}diff --git a/scripts/minikube/ensure-pvcs.sh b/scripts/minikube/ensure-pvcs.shindex 187c6edfc..f2d66bb4c 100755--- a/scripts/minikube/ensure-pvcs.sh+++ b/scripts/minikube/ensure-pvcs.sh@@ -3,7 +3,7 @@# ensure-pvcs.sh — Idempotent PVC size reconciliation# ======================================================================#-# Checks each known PVC against the desired size in manifests.+# Checks non-database workspace PVCs against the desired size in manifests.# If a PVC exists with the wrong size (Kubernetes forbids shrinking),# this script:# 1. Scales the owning Deployment to 0 replicas@@ -13,8 +13,9 @@## Called automatically by:# - make minikube-deploy-mcp (mcp-host-workspace)-# - make minikube-deploy-profiles (control-postgres-data)-# - make minikube-deploy-all (both, via the above)+#+# control-postgres-data is deliberately excluded. Database storage recreation+# requires the explicit, credential-safe `make minikube-db-reset` workflow.## Usage:# ./scripts/minikube/ensure-pvcs.sh@@ -68,4 +69,3 @@ ensure_pvc() {# ── Known PVCs ────────────────────────────────────────────────────────# Size values must match the PVC specs in deploy/minikube/services/*/ensure_pvc "mcp-host-workspace" "mcp-host" "1Gi" "mcp-host" "mcp-host"-ensure_pvc "control-postgres-data" "control-plane" "1Gi" "control-postgres" "control-plane"diff --git a/scripts/minikube/pre-gate-sync.sh b/scripts/minikube/pre-gate-sync.shindex 68ce1b499..01f7d631c 100755--- a/scripts/minikube/pre-gate-sync.sh+++ b/scripts/minikube/pre-gate-sync.sh@@ -229,7 +229,7 @@ provision_gfs_serving() {# FAIL LOUD: with the GFS stack deployed, a broken gfs_controller credential# means every GFS operation 503s (issue #775). Continuing would burn the# whole gate run on a cluster that cannot pass.- if ! CONTEXT="${PROFILE}" bash "${PROJECT_DIR}/deploy/scripts/provision-gfs-db.sh"; then+ if ! CONTEXT="${PROFILE}" bash "${PROJECT_DIR}/deploy/scripts/reconcile-gfs-deploy-credentials.sh"; thenlog "ERROR: gfs DB provisioning FAILED — gfsc cannot authorize any operation. Aborting ${GATE_NAME} pre-gate sync."exit 1fi@@ -327,13 +327,27 @@ run_if_changed desktop-app "npm test"if [[ "${cluster_changed}" == "true" ]]; thenlog "Cluster-relevant changes detected — rebuilding and redeploying before ${GATE_NAME}"+ # Apply the canonical cluster bootstrap before any namespaced Secret work.+ (+ cd "${PROJECT_DIR}"+ make minikube-deploy-crds+ )+ CONTEXT="${PROFILE}" bash "${PROJECT_DIR}/deploy/scripts/apply-gfs-writer-secret.sh"+ writer_dsn="$(${KC} -n gfs get secret gfs-controller-db -o 'jsonpath={.data.connection-string}')"+ if [[ -n "${writer_dsn}" ]]; then+ if ! ${KC} -n control-plane rollout status deployment/control-api --timeout=5s >/dev/null 2>&1; then+ err "Existing GFS writer detected but control-api is not Ready; refusing full overlay sync"+ exit 1+ fi+ log "Upgrade path — reconciling GFS credentials before full overlay sync"+ CONTEXT="${PROFILE}" bash "${PROJECT_DIR}/deploy/scripts/reconcile-gfs-deploy-credentials.sh"+ else+ log "Fresh bootstrap — reader staging deferred until post-migration convergence; GFSC remains fail-closed"+ fi(cd "${PROJECT_DIR}"make minikube-build-imagesmake minikube-verify-images- # CRD changes live outside the Kustomize overlay. Apply them before the- # service rollout so cluster-backed E2E sees the same schema as the branch.- make minikube-deploy-crdsmake minikube-apply-secretsmake minikube-deploy-allif [[ "${infra_changed}" == "true" ]]; thendiff --git a/scripts/minikube/verify-gfs.sh b/scripts/minikube/verify-gfs.shindex 270ae1b15..06d95b105 100755--- a/scripts/minikube/verify-gfs.sh+++ b/scripts/minikube/verify-gfs.sh@@ -1,121 +1,78 @@#!/usr/bin/env bash-# Verify the gfs permission-store credential wiring (issue #775).-#-# Proves, WITHOUT decoding or printing any credential value, that:-# 1. The gfs-controller-db Secret has a non-empty connection-string key.-# 2. The gfsc deployments (reader + writer) exist and are rolled out.-# 3. Every gfsc pod was created AFTER the Secret's last server-side update-# (its newest managedFields timestamp — stamped by the API server, the-# SAME clock that stamps pod creationTimestamps, so operator clock skew-# cannot fake or break this check). Env vars from secretKeyRef resolve at-# pod creation, so an older pod may hold a stale credential even when the-# Secret looks correct. The human-readable clerum.io/gfs-dsn-rotated-at-# annotation is informational only.-# 4. Every gfsc pod is Ready — the readiness probe IS /readyz, which pings-# the store and (with the fresh-connection probe) re-authenticates, so-# Ready implies the credential actually works.-#-# FAIL LOUD: every check exits non-zero with a concrete, actionable message —-# including when kubectl itself cannot answer (API/RBAC errors are reported,-# never conflated with "check passed" or silently aborted by set -e). The only-# exit-0 skip is a cluster without the GFS stack (no gfs-config).-#-# Usage:-# CONTEXT=<kube-context> [GFS_NS=gfs] [GFS_DB_SECRET=gfs-controller-db] \-# scripts/minikube/verify-gfs.sh+# Verify reader/writer GFSC credentials independently without printing DSNs.set -euo pipefail+PROJECT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"+# shellcheck source=../../deploy/scripts/lib/gfs-dsn-probe.sh+source "${PROJECT_DIR}/deploy/scripts/lib/gfs-dsn-probe.sh"+CONTEXT="${CONTEXT:?set CONTEXT to the target kube-context}"GFS_NS="${GFS_NS:-gfs}"-GFS_DB_SECRET="${GFS_DB_SECRET:-gfs-controller-db}"-GFS_DEPLOY_SELECTOR="${GFS_DEPLOY_SELECTOR:-clerum.io/managed-by=host-context-controller}"-# Pods do NOT inherit the deployment's managed-by label — the pod template-# carries the deployment's spec.selector labels (see gfsFactory commonLabels vs-# selector), so pod queries need their own selector.-GFS_POD_SELECTOR="${GFS_POD_SELECTOR:-app=gfs-controller}"-# Bounded convergence window: pre-gate flows may verify right after a rollout.+PG_NS="${PG_NS:-control-plane}"+PG_PROBE_DEPLOY="${PG_PROBE_DEPLOY:-deploy/control-api}"+PG_DB="${PG_DB:-profiles}"+PG_HOST="${PG_HOST:-control-postgres.control-plane.svc.cluster.local}"+PG_PORT="${PG_PORT:-5432}"VERIFY_ROLLOUT_TIMEOUT="${VERIFY_ROLLOUT_TIMEOUT:-60s}"kc() { kubectl --context="$CONTEXT" "$@"; }log() { printf '[verify-gfs] %s\n' "$*"; }-fail() {- printf '[verify-gfs] FAIL: %s\n' "$*" >&2- exit 1-}-# kc wrapper for reads whose OUTPUT we consume: a kubectl failure must produce-# an actionable FAIL, never a silent set -e abort inside a $() substitution.-kc_read() {- local out- if ! out="$(kc "$@" 2>&1)"; then- fail "kubectl ${*} failed: ${out}"- fi- printf '%s' "$out"-}+fail() { printf '[verify-gfs] FAIL: %s\n' "$*" >&2; exit 1; }+kc_read() { local out; out="$(kc "$@" 2>&1)" || fail "kubectl $* failed: $out"; printf '%s' "$out"; }-if ! kc get configmap gfs-config -n "$GFS_NS" >/dev/null 2>&1; then- log "gfs-config not found in namespace ${GFS_NS} — GFS stack not deployed, nothing to verify"+if crd_out="$(kc get crd globalfilesystems.clerum.io -o name 2>&1)"; then+ log "${crd_out} is installed"+elif grep -qiE 'not ?found' <<<"$crd_out"; then+ log "GlobalFileSystem CRD is not installed; GFS is not adopted"exit 0+else+ fail "cannot determine whether the GlobalFileSystem CRD is installed: ${crd_out}"fi-# ── 1. Secret populated (length only — never decode the value) ──────────────-DSN_B64="$(kc_read -n "$GFS_NS" get secret "$GFS_DB_SECRET" -o jsonpath='{.data.connection-string}')"-DSN_B64_LEN="$(printf '%s' "$DSN_B64" | wc -c | tr -d ' ')"-if [[ "${DSN_B64_LEN}" -eq 0 ]]; then- fail "Secret ${GFS_NS}/${GFS_DB_SECRET} has an empty or missing connection-string key — run: CONTEXT=${CONTEXT} deploy/scripts/provision-gfs-db.sh"+if instance_out="$(kc -n "$GFS_NS" get globalfilesystem gfs -o name 2>&1)"; then+ log "${instance_out} is present; verifying its database identities"+elif grep -qiE 'not ?found' <<<"$instance_out"; then+ log "GlobalFileSystem/gfs is not adopted; no GFS instance to verify"+ exit 0+else+ fail "cannot determine whether GlobalFileSystem/gfs is adopted: ${instance_out}"fi-log "Secret ${GFS_NS}/${GFS_DB_SECRET}.connection-string is populated (${DSN_B64_LEN} base64 chars)"+kc_read -n "$GFS_NS" get configmap gfs-config -o name >/dev/null-# ── 2. gfsc deployments exist and are rolled out ─────────────────────────────-DEPLOYS="$(kc_read -n "$GFS_NS" get deployment -l "$GFS_DEPLOY_SELECTOR" -o name)"-if [[ -z "$DEPLOYS" ]]; then- fail "no gfsc deployments matching '${GFS_DEPLOY_SELECTOR}' in ${GFS_NS} — the GFS stack is deployed (gfs-config exists) but host-context-controller has not reconciled gfsc"-fi-while IFS= read -r deploy; do- if ! kc -n "$GFS_NS" rollout status "$deploy" --timeout="$VERIFY_ROLLOUT_TIMEOUT" >/dev/null 2>&1; then- fail "${deploy} is not rolled out — check: kubectl --context=${CONTEXT} -n ${GFS_NS} describe ${deploy}"- fi- log "${deploy} rolled out"-done <<< "$DEPLOYS"+verify_role() {+ local role="$1" secret="$2" deployment="$3" selector="$4"+ local encoded dsn lifecycle pending rotated_at rows live-# ── 3. Pods postdate the Secret's last server-side update ────────────────────-# managedFields[].time is stamped by the kube-apiserver — the same clock as pod-# creationTimestamps — so this comparison is immune to operator-machine skew.-# Any Secret update (the provisioning patch included) advances it; comparing-# against the NEWEST entry errs in the fail-loud direction.-ROTATED_AT="$(kc_read -n "$GFS_NS" get secret "$GFS_DB_SECRET" \- -o jsonpath='{range .metadata.managedFields[*]}{.time}{"\n"}{end}' | sort | tail -1)"-if [[ -z "$ROTATED_AT" ]]; then- fail "Secret ${GFS_NS}/${GFS_DB_SECRET} exposes no managedFields timestamps — cannot prove pods postdate the credential; re-run: CONTEXT=${CONTEXT} deploy/scripts/provision-gfs-db.sh"-fi-# '|' separator keeps EMPTY fields (a pod with no Ready condition or no-# deletionTimestamp must not collapse the column count).-POD_ROWS="$(kc_read -n "$GFS_NS" get pods -l "$GFS_POD_SELECTOR" \- -o jsonpath='{range .items[*]}{.metadata.name}{"|"}{.metadata.creationTimestamp}{"|"}{.status.conditions[?(@.type=="Ready")].status}{"|"}{.metadata.deletionTimestamp}{"\n"}{end}')"-LIVE_PODS="$(printf '%s\n' "$POD_ROWS" | awk -F'|' 'NF >= 3 && $4 == "" { print }')"-if [[ -z "$LIVE_PODS" ]]; then- fail "no (non-terminating) gfsc pods matching '${GFS_POD_SELECTOR}' in ${GFS_NS}"-fi-while IFS='|' read -r pod created _ready _deleting; do- [[ -z "$pod" ]] && continue- # RFC3339 UTC timestamps in the same format compare lexicographically.- if [[ "$created" < "$ROTATED_AT" ]]; then- fail "pod ${pod} (created ${created}) predates the Secret's last update (${ROTATED_AT}) — it may hold a stale credential. Roll it: kubectl --context=${CONTEXT} -n ${GFS_NS} rollout restart deployment -l '${GFS_DEPLOY_SELECTOR}'"- fi-done <<< "$LIVE_PODS"-log "all gfsc pods postdate the Secret's last update (${ROTATED_AT})"+ lifecycle="$(kc_read -n "$GFS_NS" get secret "$secret" -o \+ 'jsonpath={.metadata.annotations.clerum\.io/gfs-dsn-state}')"+ [ "$lifecycle" = ready ] || fail "${secret} credential lifecycle is ${lifecycle:-unset}, not ready"+ pending="$(kc_read -n "$GFS_NS" get secret "$secret" \+ -o 'go-template={{if index .data "pending-connection-string"}}yes{{else}}no{{end}}')"+ [ "$pending" = no ] || fail "${secret} retains an unfinished credential candidate"-# ── 4. Pods Ready (readiness probe IS /readyz — store reachable + coherent) ──-# A pod with NO Ready condition yet (Pending/unscheduled) counts as NOT ready.-NOT_READY="$(printf '%s\n' "$LIVE_PODS" | awk -F'|' '$3 != "True" { print $1 }')"-if [[ -n "$NOT_READY" ]]; then- while IFS= read -r pod; do- [[ -z "$pod" ]] && continue- printf '[verify-gfs] pod %s NOT Ready — recent events:\n' "$pod" >&2- kc -n "$GFS_NS" get events --field-selector "involvedObject.name=${pod}" \- --sort-by=.lastTimestamp -o custom-columns='TIME:.lastTimestamp,REASON:.reason,MESSAGE:.message' 2>/dev/null | tail -5 >&2 || true- done <<< "$NOT_READY"- fail "gfsc pods not Ready: $(echo "$NOT_READY" | tr '\n' ' ')— /readyz is failing (permission store unreachable, credential invalid, or storage unmounted)"-fi-log "all gfsc pods Ready (/readyz green — permission store reachable and credential valid)"+ encoded="$(kc_read -n "$GFS_NS" get secret "$secret" -o 'jsonpath={.data.connection-string}')"+ [ -n "$encoded" ] || fail "${GFS_NS}/${secret}.connection-string is empty"+ dsn="$(printf '%s' "$encoded" | base64 -d)" || fail "${GFS_NS}/${secret} has invalid encoding"+ gfs_dsn_authenticates_as "$dsn" "$role" \+ || fail "${secret} cannot authenticate through the expected PostgreSQL Service and role"+ unset dsn+ log "${secret} authenticates as ${role}"++ kc -n "$GFS_NS" rollout status "deployment/${deployment}" --timeout="$VERIFY_ROLLOUT_TIMEOUT" >/dev/null 2>&1 \+ || fail "deployment/${deployment} is not rolled out"+ rotated_at="$(kc_read -n "$GFS_NS" get secret "$secret" -o jsonpath='{.metadata.annotations.clerum\.io/gfs-dsn-rotated-at}')"+ [ -n "$rotated_at" ] || fail "${secret} has no credential rotation timestamp"+ rows="$(kc_read -n "$GFS_NS" get pods -l "$selector" -o jsonpath='{range .items[*]}{.metadata.name}{"|"}{.metadata.creationTimestamp}{"|"}{.status.conditions[?(@.type=="Ready")].status}{"|"}{.metadata.deletionTimestamp}{"\n"}{end}')"+ live="$(printf '%s\n' "$rows" | awk -F'|' 'NF >= 3 && $4 == "" {print}')"+ [ -n "$live" ] || fail "no live pods for ${deployment}"+ while IFS='|' read -r pod created ready _deleting; do+ [ "$created" ">" "$rotated_at" ] || [ "$created" = "$rotated_at" ] \+ || fail "${pod} predates ${secret}; run the directed ${deployment} rotation"+ [ "$ready" = True ] || fail "${pod} is not Ready"+ done <<<"$live"+ log "${deployment} is fresh for ${secret} and Ready"+}-log "OK — gfs permission-store wiring verified"+verify_role gfs_controller gfs-controller-db gfsc-writer 'app=gfs-controller,clerum.io/gfsc-role=writer'+verify_role gfs_controller_reader gfs-controller-reader-db gfsc-reader 'app=gfs-controller,clerum.io/gfsc-role=reader'+log 'OK — distinct reader/writer database identities and deployments verified'diff --git a/scripts/tests/gfs-legacy-standalone-grants.test.mjs b/scripts/tests/gfs-legacy-standalone-grants.test.mjsnew file mode 100644index 000000000..2dfb04004--- /dev/null+++ b/scripts/tests/gfs-legacy-standalone-grants.test.mjs@@ -0,0 +1,70 @@+import assert from 'node:assert/strict'+import { chmod, mkdtemp, rm, writeFile } from 'node:fs/promises'+import { tmpdir } from 'node:os'+import { join } from 'node:path'+import { describe, it } from 'node:test'+import {+ LegacyGrantControlApiClient,+ readBoundedMapping,+} from '../gfs-legacy-standalone-grants.mjs'++describe('legacy standalone grant client transport boundary', () => {+ it('rejects plaintext HTTP for a non-loopback host', () => {+ assert.throws(+ () => new LegacyGrantControlApiClient('http://control-api.example.test', 'unit-test-session'),+ /base_url_invalid/+ )+ })++ it('allows exact loopback HTTP hosts and HTTPS', () => {+ for (const url of [+ 'http://localhost:8090',+ 'http://127.0.0.1:8090',+ 'http://[::1]:8090',+ 'https://control-api.example.test',+ ]) {+ assert.doesNotThrow(() => new LegacyGrantControlApiClient(url, 'unit-test-session'))+ }+ })++ it('forces redirect errors so a caller cannot forward the session to a redirect target', async () => {+ const calls = []+ const fetchImpl = async (url, options) => {+ calls.push({ url, options })+ if (options.redirect === 'error') throw new TypeError('redirect blocked')+ throw new Error('unsafe redirect policy')+ }+ const client = new LegacyGrantControlApiClient(+ 'https://control-api.example.test',+ 'unit-test-session',+ fetchImpl+ )++ await assert.rejects(+ client.request('/api/v1/gfs/grants/legacy-standalone', { redirect: 'follow' }),+ /redirect blocked/+ )+ assert.equal(calls.length, 1)+ assert.equal(calls[0].options.redirect, 'error')+ assert.match(calls[0].options.headers.Cookie, /^control_ui_admin_session=/)+ })+})++describe('reviewed mapping file bound', () => {+ it('accepts a small JSON mapping and rejects an oversized file before parsing', async () => {+ const directory = await mkdtemp(join(tmpdir(), 'gfs-grant-mapping-test-'))+ const small = join(directory, 'small.json')+ const large = join(directory, 'large.json')+ try {+ await writeFile(small, '{"version":1}')+ await chmod(small, 0o600)+ await writeFile(large, Buffer.alloc(1024 * 1024 + 1, 0x20))+ await chmod(large, 0o600)++ await assert.doesNotReject(readBoundedMapping(small))+ await assert.rejects(readBoundedMapping(large), /mapping_file_invalid_or_too_large/)+ } finally {+ await rm(directory, { recursive: true, force: true })+ }+ })+})diff --git a/scripts/tests/test-converge-control-db-after-reset.sh b/scripts/tests/test-converge-control-db-after-reset.shnew file mode 100755index 000000000..7066e65e3--- /dev/null+++ b/scripts/tests/test-converge-control-db-after-reset.sh@@ -0,0 +1,167 @@+#!/usr/bin/env bash+set -euo pipefail++ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"+TMP="$(mktemp -d)"+trap 'rm -rf "$TMP"' EXIT+mkdir -p "$TMP/bin"+LOG="$TMP/calls.log"++cat >"$TMP/bin/kubectl" <<'EOF'+#!/bin/bash+set -euo pipefail+printf 'kubectl %s\n' "$*" >>"$FAKE_LOG"+case "$*" in+ *'get configmap control-db-reset-state -o jsonpath={.metadata.uid} --ignore-not-found'*)+ [ -s "$FAKE_STATE" ] && cut -d'|' -f1 "$FAKE_STATE"+ ;;+ *'get configmap control-db-reset-state'*) [ -s "$FAKE_STATE" ] && cat "$FAKE_STATE" ;;+ *'get pvc control-postgres-data'*) printf '%s' "${FAKE_PVC_UID:-replacement-uid}" ;;+ *'patch configmap control-db-reset-state'*)+ [ "${FAIL_CAS:-false}" != true ] || exit 1+ IFS='|' read -r state_uid rv version phase original replacement hcc workflow trace writer reader <"$FAKE_STATE"+ payload=""+ while [ "$#" -gt 0 ]; do+ if [ "$1" = -p ]; then shift; payload="$1"; break; fi+ shift+ done+ next_phase="$(python3 -c 'import json,sys; p=json.loads(sys.argv[1]); print(next(x["value"] for x in p if x["op"]=="replace" and x["path"]=="/data/phase"))' "$payload")"+ next_replacement="$(python3 -c 'import json,sys; p=json.loads(sys.argv[1]); print(next(x["value"] for x in p if x["op"]=="replace" and x["path"]=="/data/replacementPvcUid"))' "$payload")"+ printf '%s|%s|%s|%s|%s|%s|%s|%s|%s|%s|%s\n' "$state_uid" "$((rv + 1))" "$version" "$next_phase" "$original" "$next_replacement" "$hcc" "$workflow" "$trace" "$writer" "$reader" >"$FAKE_STATE"+ ;;+ *'scale deployment/host-context-controller --replicas=0') exit 0 ;;+ *'get pods -l app=host-context-controller -o name') printf 'pod/hcc-old\n' ;;+ *'wait --for=delete pod -l app=host-context-controller --timeout=180s') exit 0 ;;+ *'get pods -l app=gfs-controller -o name') printf 'pod/gfsc-writer-old\n' ;;+ *'scale deployment/gfsc-writer deployment/gfsc-reader --replicas=0') exit 0 ;;+ *'scale deployment/gfsc-writer --replicas=3') exit 0 ;;+ *'scale deployment/gfsc-reader --replicas=2') exit 0 ;;+ *'scale deployment/workflow-recipes deployment/trace-maintenance-worker --replicas=0') exit 0 ;;+ *'scale deployment/workflow-recipes --replicas=5') exit 0 ;;+ *'scale deployment/trace-maintenance-worker --replicas=6') exit 0 ;;+ *'wait --for=delete pod -l app=gfs-controller --timeout=180s') exit 0 ;;+ *'rollout status deployment/control-api --timeout=180s') exit 0 ;;+ *'rollout status deployment/gfsc-writer --timeout=180s') exit 0 ;;+ *'rollout status deployment/gfsc-reader --timeout=180s') exit 0 ;;+ *'rollout status deployment/workflow-recipes --timeout=180s') exit 0 ;;+ *'rollout status deployment/trace-maintenance-worker --timeout=180s') exit 0 ;;+ *'scale deployment/host-context-controller --replicas=4') exit 0 ;;+ *'rollout status deployment/host-context-controller --timeout=180s') exit 0 ;;+ *'get pods -l app=workflow-recipes -o name') printf 'pod/workflow-old\n' ;;+ *'get pods -l app=trace-maintenance-worker -o name') printf 'pod/trace-old\n' ;;+ *'wait --for=delete pod -l app=workflow-recipes --timeout=180s') exit 0 ;;+ *'wait --for=delete pod -l app=trace-maintenance-worker --timeout=180s') exit 0 ;;+ *'delete --raw /api/v1/namespaces/control-plane/configmaps/control-db-reset-state'*)+ cat >/dev/null+ [ "${FAIL_STATE_DELETE:-false}" != true ] || exit 1+ rm -f "$FAKE_STATE"+ ;;+ *'scale deployment/control-api --replicas=2') exit 0 ;;+ *) printf 'unexpected kubectl call: %s\n' "$*" >&2; exit 1 ;;+esac+EOF++cat >"$TMP/bin/bash" <<'EOF'+#!/bin/sh+printf 'bash %s\n' "$*" >>"$FAKE_LOG"+case "$*" in+ *reconcile-gfs-deploy-credentials.sh*) [ "${FAIL_RECONCILE:-false}" != true ] ;;+ *scripts/minikube/verify-gfs.sh*) [ "${FAIL_VERIFY:-false}" != true ] ;;+ *) exit 0 ;;+esac+EOF+chmod +x "$TMP/bin/kubectl" "$TMP/bin/bash"++run_converge() {+ PATH="$TMP/bin:$PATH" FAKE_LOG="$LOG" FAKE_STATE="$TMP/state" CONTEXT=test-context "$@" \+ /bin/bash "$ROOT/deploy/scripts/converge-control-db-after-reset.sh" --overlay fake-overlay+}++init_state() {+ local phase="${1:-original-deleted}" replacement="${2:-unbound}"+ printf 'state-uid|1|1|%s|claim-uid-1|%s|4|5|6|3|2|2\n' \+ "$phase" "$replacement" >"$TMP/state"+}++: >"$LOG"+init_state+if ! run_converge >"$TMP/success.out" 2>&1; then+ cat "$TMP/success.out" >&2+ cat "$LOG" >&2+ printf 'FAIL: successful convergence fixture failed\n' >&2+ exit 1+fi+writer_zero="$(grep -n 'scale deployment/gfsc-writer deployment/gfsc-reader --replicas=0' "$LOG" | head -1 | cut -d: -f1)"+hcc_zero="$(grep -n 'scale deployment/host-context-controller --replicas=0' "$LOG" | head -1 | cut -d: -f1)"+hcc_wait="$(grep -n 'wait --for=delete pod -l app=host-context-controller' "$LOG" | cut -d: -f1)"+migration="$(grep -n 'run-control-api-db-migration.sh' "$LOG" | head -1 | cut -d: -f1)"+restore_writer="$(grep -n 'scale deployment/gfsc-writer --replicas=3' "$LOG" | cut -d: -f1)"+restore_reader="$(grep -n 'scale deployment/gfsc-reader --replicas=2' "$LOG" | cut -d: -f1)"+reconcile="$(grep -n 'reconcile-gfs-deploy-credentials.sh' "$LOG" | cut -d: -f1)"+hcc_restore="$(grep -n 'scale deployment/host-context-controller --replicas=4' "$LOG" | cut -d: -f1)"+gfs_verify="$(grep -n 'scripts/minikube/verify-gfs.sh' "$LOG" | cut -d: -f1)"+workflow_restore="$(grep -n 'scale deployment/workflow-recipes --replicas=5' "$LOG" | cut -d: -f1)"+trace_restore="$(grep -n 'scale deployment/trace-maintenance-worker --replicas=6' "$LOG" | cut -d: -f1)"+state_delete="$(grep -n 'delete --raw /api/v1/namespaces/control-plane/configmaps/control-db-reset-state' "$LOG" | cut -d: -f1)"+[[ "$hcc_zero" -lt "$hcc_wait" && "$hcc_wait" -lt "$writer_zero" && "$writer_zero" -lt "$migration" && \+ "$reconcile" -lt "$restore_writer" && "$reconcile" -lt "$restore_reader" && \+ "$gfs_verify" -lt "$workflow_restore" && "$gfs_verify" -lt "$trace_restore" && \+ "$workflow_restore" -lt "$hcc_restore" && "$hcc_restore" -lt "$state_delete" ]] \+ || { printf 'FAIL: GFSC isolation/restore order is wrong\n' >&2; exit 1; }+grep -q 'wait --for=delete pod -l app=gfs-controller' "$LOG" \+ || { printf 'FAIL: GFSC pod termination was not awaited\n' >&2; exit 1; }++: >"$LOG"+init_state+if run_converge env FAIL_RECONCILE=true >/dev/null 2>&1; then+ printf 'FAIL: failed reconciliation was reported as success\n' >&2+ exit 1+fi+[[ "$(grep -c 'scale deployment/gfsc-writer deployment/gfsc-reader --replicas=0' "$LOG")" -eq 2 ]] \+ || { printf 'FAIL: failure did not reassert the zero-replica state\n' >&2; exit 1; }+! grep -q 'scale deployment/gfsc-writer --replicas=3' "$LOG" \+ || { printf 'FAIL: writer replicas were restored after failure\n' >&2; exit 1; }+! grep -q 'scale deployment/gfsc-reader --replicas=2' "$LOG" \+ || { printf 'FAIL: reader replicas were restored after failure\n' >&2; exit 1; }+! grep -q 'scale deployment/host-context-controller --replicas=4' "$LOG" \+ || { printf 'FAIL: HCC was restored after failure\n' >&2; exit 1; }++: >"$LOG"+init_state+if run_converge env FAIL_VERIFY=true >/dev/null 2>&1; then+ printf 'FAIL: failed GFS verification was reported as success\n' >&2+ exit 1+fi+! grep -q 'scale deployment/host-context-controller --replicas=4' "$LOG" \+ || { printf 'FAIL: HCC was restored before successful GFS verification\n' >&2; exit 1; }++: >"$LOG"+init_state+if run_converge env FAIL_STATE_DELETE=true >/dev/null 2>&1; then+ printf 'FAIL: reset-state deletion failure was reported as success\n' >&2+ exit 1+fi+grep -q '|converged|' "$TMP/state" \+ || { printf 'FAIL: cleanup failure did not preserve completed phase\n' >&2; exit 1; }+[[ "$(grep -c 'scale deployment/host-context-controller --replicas=0' "$LOG")" -eq 1 ]] \+ || { printf 'FAIL: cleanup-only failure incorrectly requiesced verified workloads\n' >&2; exit 1; }++: >"$LOG"+if ! run_converge >/dev/null 2>&1; then+ printf 'FAIL: converged-state cleanup resume failed\n' >&2; exit 1+fi+! grep -q 'run-control-api-db-migration.sh' "$LOG" \+ || { printf 'FAIL: cleanup resume reran migrations\n' >&2; exit 1; }+! grep -q 'reconcile-gfs-deploy-credentials.sh' "$LOG" \+ || { printf 'FAIL: cleanup resume reconciled credentials\n' >&2; exit 1; }+[ ! -e "$TMP/state" ] || { printf 'FAIL: cleanup resume left recovery state\n' >&2; exit 1; }++: >"$LOG"+init_state replacement-bound replacement-uid+if run_converge env FAKE_PVC_UID=substituted-uid >/dev/null 2>&1; then+ printf 'FAIL: replacement UID substitution was accepted\n' >&2; exit 1+fi+grep -q 'scale deployment/workflow-recipes deployment/trace-maintenance-worker --replicas=0' "$LOG" \+ || { printf 'FAIL: UID ambiguity did not keep DB workers fail-closed\n' >&2; exit 1; }++printf 'PASS: post-reset convergence isolates DB-dependent controllers and preserves replica counts\n'diff --git a/scripts/tests/test-gfs-credential-lifecycle.sh b/scripts/tests/test-gfs-credential-lifecycle.shnew file mode 100755index 000000000..b8e3facf2--- /dev/null+++ b/scripts/tests/test-gfs-credential-lifecycle.sh@@ -0,0 +1,367 @@+#!/usr/bin/env bash+# shellcheck disable=SC2016,SC2030,SC2031+set -euo pipefail++ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"+fail() { printf 'FAIL: %s\n' "$*" >&2; exit 1; }++test_empty_secret_stage() (+ set -euo pipefail+ GFS_NS=gfs+ secret_resource_version() { printf '17'; }+ kc() {+ case " $* " in+ *' get secret '*' go-template='*) printf 'no' ;;+ *' patch secret '*)+ python3 -c 'import base64, json, sys+ops = json.load(sys.stdin)+assert ops[0] == {"op": "test", "path": "/metadata/resourceVersion", "value": "17"}+assert ops[1]["value"] == "ready"+assert ops[2]["path"] == "/data"+assert ops[2]["value"]["pending-connection-string"] == base64.b64encode(b"candidate").decode()+assert ops[3]["value"] == "pending"'+ ;;+ *) return 1 ;;+ esac+ }+ source "$ROOT/deploy/scripts/lib/gfs-credential-secret.sh"+ printf candidate | stage_secret_candidate empty-secret+) || fail 'empty Secret stage patch is invalid'++test_stage_conflict() (+ set -euo pipefail+ GFS_NS=gfs+ secret_resource_version() { printf '18'; }+ kc() {+ case " $* " in+ *' get secret '*' go-template='*) printf 'yes' ;;+ *' patch secret '*) cat >/dev/null; return 1 ;;+ *) return 1 ;;+ esac+ }+ source "$ROOT/deploy/scripts/lib/gfs-credential-secret.sh"+ ! printf candidate | stage_secret_candidate conflicted-secret+) || fail 'stage conflict was reported as success'++test_legacy_state_adoption() (+ set -euo pipefail+ GFS_NS=gfs+ kc() {+ case " $* " in+ *' get secret '*' go-template='*) printf yes ;;+ *' patch secret '*)+ python3 -c 'import json, sys+ops = json.load(sys.stdin)+assert ops == [+ {"op": "test", "path": "/metadata/resourceVersion", "value": "23"},+ {"op": "add", "path": "/metadata/annotations/clerum.io~1gfs-dsn-state", "value": "ready"},+]'+ ;;+ *) return 1 ;;+ esac+ }+ source "$ROOT/deploy/scripts/lib/gfs-credential-secret.sh"+ adopt_legacy_secret_state writer-secret 23 yes existing-stamp existing-stamp+) || fail 'legacy state adoption is not CAS guarded'++test_legacy_state_adoption_conflict() (+ set -euo pipefail+ GFS_NS=gfs+ live_state=applying+ kc() {+ case " $* " in+ *' patch secret '*) cat >/dev/null; return 1 ;;+ *) return 1 ;;+ esac+ }+ source "$ROOT/deploy/scripts/lib/gfs-credential-secret.sh"+ ! adopt_legacy_secret_state writer-secret stale-rv yes existing-stamp existing-stamp+ [ "$live_state" = applying ]+) || fail 'legacy adoption overwrote a concurrent applying state'++test_deployment_error_boundary() {+ local mode="$1" expected="$2" rc+ set +e+ (+ GFS_NS=gfs+ die() { exit 70; }+ kc() {+ if [ "$mode" = notfound ]; then+ printf 'Error from server (NotFound): deployment not found\n' >&2+ else+ printf 'Error from server (Forbidden): denied\n' >&2+ fi+ return 1+ }+ source "$ROOT/deploy/scripts/lib/gfs-credential-rollout.sh"+ deployment_exists gfsc-reader+ )+ rc=$?+ set -e+ [ "$rc" -eq "$expected" ] || fail "deployment $mode returned $rc, expected $expected"+}+test_deployment_error_boundary notfound 1+test_deployment_error_boundary forbidden 70++test_secret_reference_error() {+ local rc+ set +e+ (+ GFS_NS=gfs+ die() { exit 70; }+ kc() { printf 'connection refused\n' >&2; return 1; }+ source "$ROOT/deploy/scripts/lib/gfs-credential-rollout.sh"+ deployment_uses_secret gfsc-reader reader-secret+ )+ rc=$?+ set -e+ [ "$rc" -eq 70 ] || fail "Secret-reference API failure returned $rc"+}+test_secret_reference_error++test_pod_list_error() {+ local rc+ set +e+ (+ GFS_NS=gfs+ die() { exit 70; }+ gfs_secret_rotated_at() { printf '2026-01-01T00:00:00Z'; }+ kc() { printf 'RBAC denied\n' >&2; return 1; }+ source "$ROOT/deploy/scripts/lib/gfs-credential-rollout.sh"+ credential_rollout_pending gfsc-reader reader-secret+ )+ rc=$?+ set -e+ [ "$rc" -eq 70 ] || fail "pod-list API failure returned $rc"+}+test_pod_list_error++test_terminating_pod_filter() (+ set -euo pipefail+ GFS_NS=gfs+ gfs_secret_rotated_at() { printf '2026-01-02T00:00:00Z'; }+ kc() {+ printf '%s\n' \+ 'gfsc-reader-old|2026-01-01T00:00:00Z|False|2026-01-02T00:01:00Z' \+ 'gfsc-reader-new|2026-01-02T00:00:01Z|True|'+ }+ source "$ROOT/deploy/scripts/lib/gfs-credential-rollout.sh"+ ! credential_rollout_pending gfsc-reader reader-secret+) || fail 'terminating pod triggered a redundant rollout'++test_consecutive_pre_overlay_stage_preserves_pending() (+ set -euo pipefail+ GFS_NS=gfs+ deployment_uses_secret() { return 1; }+ credential_rollout_pending() { fail 'pending lifecycle must be gated by the deployment Secret reference'; }+ source "$ROOT/deploy/scripts/lib/gfs-credential-rollout.sh"+ ! credential_rollout_required gfsc-reader reader-secret rollout-pending+) || fail 'a consecutive pre-overlay reader stage could complete rollout-pending prematurely'++test_post_overlay_stage_completes_pending() (+ set -euo pipefail+ GFS_NS=gfs+ deployment_uses_secret() { [ "$1" = gfsc-reader ] && [ "$2" = reader-secret ]; }+ credential_rollout_pending() { fail 'pending lifecycle must use the explicit Secret-reference gate'; }+ source "$ROOT/deploy/scripts/lib/gfs-credential-rollout.sh"+ credential_rollout_required gfsc-reader reader-secret rollout-pending+) || fail 'post-overlay reader stage did not release rollout-pending'++test_idempotent_ready_stage_needs_no_rollout() (+ set -euo pipefail+ GFS_NS=gfs+ deployment_uses_secret() { fail 'ready lifecycle must not use the cutover gate'; }+ credential_rollout_pending() { return 1; }+ source "$ROOT/deploy/scripts/lib/gfs-credential-rollout.sh"+ ! credential_rollout_required gfsc-reader reader-secret ready+) || fail 'an idempotent reader stage requested a redundant rollout'++test_rollout_status_rc2() {+ local marker rc+ marker="$(mktemp)"+ set +e+ (+ GFS_NS=gfs+ ROLLOUT_TIMEOUT=1s+ GFS_RECOVER_ABANDONED_STATE=false+ die() { exit 70; }+ log() { :; }+ gfs_secret_rotated_at() { printf '2026-01-01T00:00:00Z'; }+ gfs_secret_state() { printf 'rollout-pending'; }+ claim_secret_rollout() { return 0; }+ mark_secret_rollout_ready() { printf marked >"$marker"; }+ kc() {+ case " $* " in+ *' get deployment '*) printf 'deployment.apps/gfsc-reader'; return 0 ;;+ *' rollout restart '*) return 0 ;;+ *' rollout status '*) return 2 ;;+ esac+ return 1+ }+ source "$ROOT/deploy/scripts/lib/gfs-credential-rollout.sh"+ complete_rollout reader-secret gfsc-reader+ )+ rc=$?+ set -e+ [ "$rc" -eq 2 ] || fail "rollout status rc=2 became $rc"+ [ ! -s "$marker" ] || fail 'failed rollout was marked ready'+ rm -f "$marker"+}+test_rollout_status_rc2++test_claimed_rollout_requires_confirmation() {+ local rc+ set +e+ (+ GFS_NS=gfs+ GFS_RECOVER_ABANDONED_STATE=false+ die() { exit 70; }+ gfs_secret_rotated_at() { printf '2026-01-01T00:00:00Z'; }+ gfs_secret_state() { printf 'rollout-running'; }+ source "$ROOT/deploy/scripts/lib/gfs-credential-rollout.sh"+ complete_rollout reader-secret gfsc-reader+ )+ rc=$?+ set -e+ [ "$rc" -eq 70 ] || fail "claimed rollout was adopted with rc=$rc"+}+test_claimed_rollout_requires_confirmation++test_fresh_applying_nologin_recovery() (+ set -euo pipefail+ GFS_NS=gfs+ GFS_RECOVER_ABANDONED_STATE=true+ released="$(mktemp)"+ trap 'rm -f "$released"' EXIT+ die() { exit 70; }+ log() { :; }+ dsn_has_role() { [ "$1" = candidate ] && [ "$2" = gfs_controller_reader ]; }+ dsn_authenticates_as() { return 1; }+ role_can_login() { printf f; }+ release_abandoned_candidate() { cat >"$released"; }+ source "$ROOT/deploy/scripts/lib/gfs-credential-recovery.sh"+ result="$(recover_abandoned_applying gfs_controller_reader reader-secret '' candidate)"+ [ "$result" = pending ] || fail "fresh NOLOGIN recovery returned $result"+ [ "$(cat "$released")" = candidate ] || fail 'fresh NOLOGIN recovery released the wrong candidate'+) || fail 'fresh NOLOGIN applying state was not safely resumable'++test_fresh_applying_login_fails_closed() {+ local rc+ set +e+ (+ set -euo pipefail+ GFS_NS=gfs+ GFS_RECOVER_ABANDONED_STATE=true+ die() { exit 70; }+ log() { :; }+ dsn_has_role() { return 0; }+ dsn_authenticates_as() { return 1; }+ role_can_login() { printf t; }+ release_abandoned_candidate() { fail 'LOGIN role candidate must not be released automatically'; }+ source "$ROOT/deploy/scripts/lib/gfs-credential-recovery.sh"+ recover_abandoned_applying gfs_controller_reader reader-secret '' candidate+ ) >/dev/null 2>&1+ rc=$?+ set -e+ [ "$rc" -eq 70 ] || fail "fresh LOGIN recovery returned $rc instead of failing closed"+}+test_fresh_applying_login_fails_closed++test_applied_candidate_recovery() (+ set -euo pipefail+ GFS_NS=gfs+ GFS_RECOVER_ABANDONED_STATE=true+ die() { exit 70; }+ log() { :; }+ dsn_has_role() { return 0; }+ dsn_authenticates_as() { [ "$1" = candidate ]; }+ role_can_login() { fail 'role state must not be queried after candidate authentication'; }+ release_abandoned_candidate() { fail 'applied candidate must not be released'; }+ source "$ROOT/deploy/scripts/lib/gfs-credential-recovery.sh"+ [ "$(recover_abandoned_applying gfs_controller_reader reader-secret active candidate)" = applied ]+) || fail 'applied candidate was not resumed without mutation'++test_active_candidate_release() (+ set -euo pipefail+ GFS_NS=gfs+ GFS_RECOVER_ABANDONED_STATE=true+ released="$(mktemp)"+ trap 'rm -f "$released"' EXIT+ die() { exit 70; }+ log() { :; }+ dsn_has_role() { return 0; }+ dsn_authenticates_as() { [ "$1" = active ]; }+ role_can_login() { fail 'role state must not be queried with a valid active credential'; }+ release_abandoned_candidate() { cat >"$released"; }+ source "$ROOT/deploy/scripts/lib/gfs-credential-recovery.sh"+ [ "$(recover_abandoned_applying gfs_controller_reader reader-secret active candidate)" = pending ]+ [ "$(cat "$released")" = candidate ]+) || fail 'valid active credential did not release the abandoned candidate'++test_release_cas_loss_fails_closed() {+ local rc+ set +e+ (+ set -euo pipefail+ GFS_NS=gfs+ GFS_RECOVER_ABANDONED_STATE=true+ die() { exit 70; }+ log() { :; }+ dsn_has_role() { return 0; }+ dsn_authenticates_as() { [ "$1" = active ]; }+ role_can_login() { return 1; }+ release_abandoned_candidate() { cat >/dev/null; return 1; }+ source "$ROOT/deploy/scripts/lib/gfs-credential-recovery.sh"+ recover_abandoned_applying gfs_controller_reader reader-secret active candidate+ ) >/dev/null 2>&1+ rc=$?+ set -e+ [ "$rc" -eq 70 ] || fail "lost recovery CAS returned $rc instead of failing closed"+}+test_release_cas_loss_fails_closed++test_verifier_lifecycle_gate() {+ local state="$1" pending="$2" fake_dir rc+ fake_dir="$(mktemp -d)"+ printf '%s\n' \+ '#!/usr/bin/env bash' \+ 'case " $* " in' \+ ' *" get crd globalfilesystems.clerum.io "*) echo globalfilesystems.clerum.io ;;' \+ ' *" get globalfilesystem gfs "*) echo globalfilesystem.clerum.io/gfs ;;' \+ ' *" get configmap gfs-config "*) echo configmap/gfs-config ;;' \+ ' *" get secret "*"jsonpath={.metadata.annotations.clerum\\.io/gfs-dsn-state}"*) printf "%s" "$FAKE_STATE" ;;' \+ ' *" get secret "*"go-template="*) printf "%s" "$FAKE_PENDING" ;;' \+ ' *) exit 1 ;;' \+ 'esac' >"$fake_dir/kubectl"+ chmod +x "$fake_dir/kubectl"+ set +e+ PATH="$fake_dir:$PATH" FAKE_STATE="$state" FAKE_PENDING="$pending" CONTEXT=fake \+ bash "$ROOT/scripts/minikube/verify-gfs.sh" >/dev/null 2>&1+ rc=$?+ set -e+ rm -rf "$fake_dir"+ [ "$rc" -ne 0 ] || fail "verifier accepted state=$state pending=$pending"+}+test_verifier_lifecycle_gate applying no+test_verifier_lifecycle_gate ready yes++test_verifier_crd_gate() {+ local mode="$1" expected="$2" fake_dir rc+ fake_dir="$(mktemp -d)"+ printf '%s\n' \+ '#!/usr/bin/env bash' \+ 'if [ "$FAKE_CRD_MODE" = notfound ]; then echo "Error from server (NotFound): CRD not found" >&2; else echo "Error from server (Forbidden): denied" >&2; fi' \+ 'exit 1' >"$fake_dir/kubectl"+ chmod +x "$fake_dir/kubectl"+ set +e+ PATH="$fake_dir:$PATH" FAKE_CRD_MODE="$mode" CONTEXT=fake \+ bash "$ROOT/scripts/minikube/verify-gfs.sh" >/dev/null 2>&1+ rc=$?+ set -e+ rm -rf "$fake_dir"+ [ "$rc" -eq "$expected" ] || fail "verifier CRD $mode returned $rc, expected $expected"+}+test_verifier_crd_gate notfound 0+test_verifier_crd_gate forbidden 1++printf 'PASS: GFS credential lifecycle fail-closed contract\n'diff --git a/scripts/tests/test-gfs-db-reset-preflight.sh b/scripts/tests/test-gfs-db-reset-preflight.shnew file mode 100755index 000000000..6400ed858--- /dev/null+++ b/scripts/tests/test-gfs-db-reset-preflight.sh@@ -0,0 +1,133 @@+#!/usr/bin/env bash+set -euo pipefail++ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"+TMP="$(mktemp -d)"+trap 'rm -rf "$TMP"' EXIT+FAKE_BIN="$TMP/bin"+LOG="$TMP/kubectl.log"+mkdir -p "$FAKE_BIN"++cat >"$FAKE_BIN/kubectl" <<'EOF'+#!/usr/bin/env bash+set -euo pipefail+printf '%s\n' "$*" >>"$FAKE_KUBECTL_LOG"++if [[ "$*" == *"apply set-last-applied"* ]] && [ "${FAKE_APPLY_FAILURE:-false}" = true ]; then+ exit 1+fi+if [[ "$*" == *"apply set-last-applied"* ]] || [[ "$*" == *" apply -f "* ]]; then+ exit 0+fi++if [[ "$*" == *"get secret gfs-controller-db -o name"* ]]; then+ printf 'secret/gfs-controller-db\n'+ exit 0+fi++if [[ "$*" == *"get secret"*"-o json"* ]]; then+ if [ "${FAKE_API_FAILURE:-false}" = true ]; then+ exit 1+ fi++ if [[ "$*" == *"gfs-controller-reader-db"* ]]; then+ role=gfs_controller_reader+ state="${FAKE_READER_STATE-ready}"+ pending="${FAKE_READER_PENDING:-}"+ active="${FAKE_READER_DSN-postgresql://gfs_controller_reader:bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb@control-postgres.control-plane.svc.cluster.local:5432/profiles}"+ else+ role=gfs_controller+ state="${FAKE_WRITER_STATE-ready}"+ pending="${FAKE_WRITER_PENDING:-}"+ active="${FAKE_WRITER_DSN-postgresql://gfs_controller:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa@control-postgres.control-plane.svc.cluster.local:5432/profiles}"+ fi++ if [ "${FAKE_MALFORMED_B64:-false}" = true ]; then+ printf '{"metadata":{"resourceVersion":"42","annotations":{"clerum.io/gfs-dsn-state":"ready"}},"data":{"connection-string":"%%%"}}\n'+ exit 0+ fi++ ROLE="$role" STATE="$state" PENDING="$pending" ACTIVE="$active" python3 - <<'PY'+import base64+import json+import os++def encoded(value: str) -> str:+ return base64.b64encode(value.encode()).decode()++data = {}+if os.environ["ACTIVE"]:+ data["connection-string"] = encoded(os.environ["ACTIVE"])+if os.environ["PENDING"]:+ data["pending-connection-string"] = encoded(os.environ["PENDING"])+print(json.dumps({+ "metadata": {+ "resourceVersion": "42",+ "annotations": {+ "clerum.io/gfs-dsn-state": os.environ["STATE"],+ "clerum.io/gfs-dsn-rotated-at": "2026-07-18T00:00:00Z",+ },+ },+ "data": data,+}))+PY+ exit 0+fi++printf 'unexpected kubectl invocation: %s\n' "$*" >&2+exit 1+EOF+chmod +x "$FAKE_BIN/kubectl"++run_preflight() {+ env PATH="$FAKE_BIN:$PATH" FAKE_KUBECTL_LOG="$LOG" CONTEXT=test-context "$@" \+ bash "$ROOT/deploy/scripts/preflight-gfs-db-reset.sh"+}++: >"$LOG"+output="$(run_preflight 2>&1)"+[[ "$output" != *"postgresql://"* ]] || { echo 'FAIL: preflight leaked a DSN' >&2; exit 1; }+[[ "$output" != *"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"* ]] || { echo 'FAIL: preflight leaked writer password' >&2; exit 1; }+[[ "$output" != *"bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"* ]] || { echo 'FAIL: preflight leaked reader password' >&2; exit 1; }+! grep -Eq 'exec|psql' "$LOG" || { echo 'FAIL: metadata preflight contacted PostgreSQL' >&2; exit 1; }+[[ "$(grep -c 'get secret gfs-controller-db -o json' "$LOG")" -eq 1 ]] || { echo 'FAIL: writer was not read as one snapshot' >&2; exit 1; }+[[ "$(grep -c 'get secret gfs-controller-reader-db -o json' "$LOG")" -eq 1 ]] || { echo 'FAIL: reader was not read as one snapshot' >&2; exit 1; }++if run_preflight FAKE_WRITER_STATE=pending >/dev/null 2>&1; then+ echo 'FAIL: non-ready writer was accepted' >&2+ exit 1+fi+if run_preflight FAKE_WRITER_STATE= >/dev/null 2>&1; then+ echo 'FAIL: writer without lifecycle state was accepted' >&2+ exit 1+fi+if run_preflight FAKE_READER_PENDING=candidate >/dev/null 2>&1; then+ echo 'FAIL: pending reader credential was accepted' >&2+ exit 1+fi+if run_preflight FAKE_WRITER_DSN='postgresql://gfs_controller_reader:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa@control-postgres.control-plane.svc.cluster.local:5432/profiles' >/dev/null 2>&1; then+ echo 'FAIL: wrong writer role was accepted' >&2+ exit 1+fi+if run_preflight FAKE_MALFORMED_B64=true >/dev/null 2>&1; then+ echo 'FAIL: malformed Secret base64 was accepted' >&2+ exit 1+fi+if run_preflight FAKE_WRITER_DSN='postgresql://gfs_controller:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa@wrong-host:5432/profiles' >/dev/null 2>&1; then+ echo 'FAIL: invalid writer endpoint was accepted' >&2+ exit 1+fi+if run_preflight FAKE_READER_DSN= >/dev/null 2>&1; then+ echo 'FAIL: missing reader credential was accepted' >&2+ exit 1+fi+if run_preflight FAKE_API_FAILURE=true >/dev/null 2>&1; then+ echo 'FAIL: Kubernetes API failure was accepted' >&2+ exit 1+fi+if run_preflight FAKE_APPLY_FAILURE=true >/dev/null 2>&1; then+ echo 'FAIL: writer ownership migration failure was accepted' >&2+ exit 1+fi++echo 'PASS: GFS DB reset preflight'diff --git a/scripts/tests/test-gfs-deploy-contract.sh b/scripts/tests/test-gfs-deploy-contract.shnew file mode 100755index 000000000..3362d00e7--- /dev/null+++ b/scripts/tests/test-gfs-deploy-contract.sh@@ -0,0 +1,158 @@+#!/usr/bin/env bash+set -euo pipefail+ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"; cd "$ROOT"+fail() { echo "FAIL: $*" >&2; exit 1; }+for mode in stage-writer stage-reader rotate-reader rotate-writer; do+ grep -q "$mode" deploy/scripts/provision-gfs-db.sh || fail "missing $mode"+done+grep -q 'PG_DB="${PG_DB:-profiles}"' deploy/scripts/provision-gfs-db.sh || fail 'provisioner canonical GFS database default drifted'+grep -q 'PG_DB="${PG_DB:-profiles}"' deploy/scripts/preflight-gfs-db-reset.sh || fail 'reset preflight diverges from provisioner GFS database default'+grep -q 'recover_abandoned_applying' deploy/scripts/provision-gfs-db.sh || fail 'explicit applying-state recovery is not wired'+grep -q 'role_can_login' deploy/scripts/lib/gfs-credential-recovery.sh || fail 'fresh bootstrap recovery does not verify NOLOGIN'+! grep -q 'rollout restart deployment -l' deploy/scripts/provision-gfs-db.sh || fail 'broad rollout'+role_migration="$(sed -n "/version: '0074_gfs_runtime_role_exact_contract'/,/^ },$/p" control-api/src/db.ts)"+[[ "$role_migration" == *'ALTER ROLE gfs_controller'* && "$role_migration" == *'ALTER ROLE gfs_controller_reader'* && "$role_migration" == *'NOINHERIT NOSUPERUSER NOCREATEDB NOCREATEROLE NOREPLICATION NOBYPASSRLS'* ]] || fail 'exact GFS runtime role attributes are not reconciled'+[[ "$role_migration" != *'NOLOGIN'* && "$role_migration" != *'LOGIN'* && "$role_migration" != *'PASSWORD'* && "$role_migration" != *'DROP ROLE'* ]] || fail 'role-contract migration changes credentials or replaces a role'+[[ "$role_migration" == *"ARRAY['gfs_controller', 'gfs_controller_reader']"* && "$role_migration" == *"EXECUTE format('REVOKE %I FROM %I'"* ]] || fail 'role-contract migration leaves inherited memberships'+provision_contract="$(sed -n '/verify_role_contract()/,/^}/p' deploy/scripts/provision-gfs-db.sh)"+[[ "$provision_contract" == *"has_column_privilege(:'role_name', 'control_admin_users', 'id', 'SELECT')"* && "$provision_contract" == *"has_column_privilege(:'role_name', 'team_members', 'status', 'SELECT')"* && "$provision_contract" == *"column_name NOT IN ('id', 'status')"* && "$provision_contract" == *"column_name NOT IN ('team_id', 'user_id', 'status')"* ]] || fail 'provisioner does not verify the exact subject-column contract'+writer_case="$(sed -n '/rotate-writer)/,/;;/p' deploy/scripts/provision-gfs-db.sh)"+[[ "$writer_case" == *'reconcile_credential gfs_controller writer "$WRITER_SECRET" gfsc-writer true'* && "$writer_case" != *'gfsc-reader'* ]] || fail 'writer rollout scope'+for workflow in .github/workflows/deploy-dev.yaml .github/workflows/deploy-prod.yaml; do+ heading="$(grep -n 'Reconcile GFS database credentials' "$workflow" | head -1 | cut -d: -f1)"+ reconcile="$(grep -n 'reconcile-gfs-deploy-credentials.sh' "$workflow" | head -1 | cut -d: -f1)"+ overlay="$(grep -n 'Apply kustomize overlay' "$workflow" | head -1 | cut -d: -f1)"+ [[ "$heading" -lt "$reconcile" && "$reconcile" -lt "$overlay" ]] || fail "$workflow order"+ runtime="$(grep -n 'provision-gfs-runtime.sh' "$workflow" | head -1 | cut -d: -f1)"+ verify="$(grep -n 'scripts/minikube/verify-gfs.sh' "$workflow" | head -1 | cut -d: -f1)"+ [[ -n "$runtime" && -n "$verify" && "$overlay" -lt "$runtime" && "$runtime" -lt "$verify" ]] \+ || fail "$workflow missing post-overlay GFS reconciliation before verification"+done+runtime_script="$(cat deploy/scripts/provision-gfs-runtime.sh)"+[[ "$runtime_script" == *'reconcile-gfs-deploy-credentials.sh'* ]] \+ || fail 'post-overlay runtime path does not reconcile staged credentials'+[[ "$runtime_script" == *'rollout status deployment/gfsc-writer'* && \+ "$runtime_script" == *'rollout status deployment/gfsc-reader'* ]] \+ || fail 'post-overlay runtime path does not wait for exact GFSC rollouts'+[[ "$runtime_script" != *'rollout restart'* && "$runtime_script" != *'rotate-writer'* ]] \+ || fail 'post-overlay runtime path rotates or unconditionally restarts GFS'+grep -q 'NAMESPACES="channels control-plane gfs ' .github/workflows/deploy-prod.yaml || fail 'prod GFS rollout gate absent'+for target in gcp-dev-deploy-all gcp-prod-deploy-all; do+ recipe="$(make -n "$target" CONFIRM=yes 2>/dev/null || true)"+ reconcile="$(printf '%s\n' "$recipe" | grep -n 'reconcile-gfs-deploy-credentials.sh' | head -1 | cut -d: -f1)"+ overlay="$(printf '%s\n' "$recipe" | grep -n 'kustomize deploy/overlays/' | head -1 | cut -d: -f1)"+ [[ -n "$reconcile" && -n "$overlay" && "$reconcile" -lt "$overlay" ]] || fail "$target order"+ [[ "$recipe" == *'scripts/minikube/verify-gfs.sh'* ]] || fail "$target missing GFS verification"+done+make_block() {+ awk -v target="$1" '$0 ~ "^" target ":" {active=1} active && /^\.PHONY:/ {exit} active {print}' Makefile+}+for target in gcp-prod-deploy-service gcp-prod-deploy-release gcp-dev-deploy-service; do+ block="$(make_block "$target")"+ reconcile="$(grep -n 'reconcile-gfs-deploy-credentials.sh' <<<"$block" | head -1 | cut -d: -f1)"+ overlay="$(grep -n 'kustomize deploy/overlays/gcp-' <<<"$block" | head -1 | cut -d: -f1)"+ verify="$(grep -n 'verify-gfs.sh' <<<"$block" | head -1 | cut -d: -f1)"+ [[ -n "$reconcile" && -n "$overlay" && -n "$verify" && "$reconcile" -lt "$overlay" && "$overlay" -lt "$verify" ]] \+ || fail "$target bypasses GFS deploy reconciliation"+done+for target in minikube-db-reset gcp-prod-db-reset gcp-dev-db-reset; do+ block="$(make_block "$target")"+ reset="$(grep -n 'reset-control-db-storage.sh' <<<"$block" | head -1 | cut -d: -f1)"+ recreate="$(grep -n 'apply -k .* -l app=control-postgres' <<<"$block" | head -1 | cut -d: -f1)"+ postgres_ready="$(grep -nE 'wait .*control-postgres|wait .*deploy/control-postgres' <<<"$block" | head -1 | cut -d: -f1)"+ converge="$(grep -n 'converge-control-db-after-reset.sh' <<<"$block" | head -1 | cut -d: -f1)"+ success="$(grep -n 'DB reset complete' <<<"$block" | tail -1 | cut -d: -f1)"+ [[ -n "$reset" && -n "$recreate" && -n "$postgres_ready" && -n "$converge" && -n "$success" ]] && \+ [[ "$reset" -lt "$recreate" && "$recreate" -lt "$postgres_ready" && "$postgres_ready" -lt "$converge" && "$converge" -lt "$success" ]] \+ || fail "$target bypasses safe GFS reset recovery"+done+reset_storage="$(cat deploy/scripts/reset-control-db-storage.sh)"+for required in preflight-gfs-db-reset.sh 'scale deployment/control-api --replicas=0' 'scale deployment/control-postgres --replicas=0' 'wait_for_pods_gone app=control-api' 'wait_for_pods_gone app=control-postgres' 'preconditions":{"uid":"%s"}' 'persistentvolumeclaims/${PVC}'; do+ [[ "$reset_storage" == *"$required"* ]] || fail "reset storage boundary omits $required"+done+preflight="$(grep -n 'preflight-gfs-db-reset.sh' deploy/scripts/reset-control-db-storage.sh | cut -d: -f1)"+scale="$(grep -n 'scale deployment/control-api' deploy/scripts/reset-control-db-storage.sh | cut -d: -f1)"+delete="$(grep -n 'delete --raw' deploy/scripts/reset-control-db-storage.sh | head -1 | cut -d: -f1)"+[[ "$preflight" -lt "$scale" && "$scale" -lt "$delete" ]] || fail 'reset storage mutates before metadata preflight'+grep -q 'claim.get("namespace") == "control-plane"' deploy/scripts/reset-control-db-storage.sh || fail 'released PV cleanup is not namespace-scoped'+grep -q 'claim.get("uid") == expected_uid' deploy/scripts/reset-control-db-storage.sh || fail 'released PV cleanup is not claim-UID-scoped'+! grep -q 'ensure_pvc "control-postgres-data"' scripts/minikube/ensure-pvcs.sh || fail 'generic PVC reconciler can still delete the control database'+reset_convergence="$(cat deploy/scripts/converge-control-db-after-reset.sh)"+for required in run-control-api-db-migration.sh provision-control-api-runtime-roles.sh 'rollout status deployment/control-api' 'GFS_RESTORE_ACTIVE_NOLOGIN=true' reconcile-gfs-deploy-credentials.sh verify-gfs.sh; do+ [[ "$reset_convergence" == *"$required"* ]] || fail "reset convergence omits $required"+done+migration="$(grep -n 'run-control-api-db-migration.sh' deploy/scripts/converge-control-db-after-reset.sh | cut -d: -f1)"+roles="$(grep -n 'provision-control-api-runtime-roles.sh' deploy/scripts/converge-control-db-after-reset.sh | cut -d: -f1)"+scale="$(grep -n 'scale deployment/control-api' deploy/scripts/converge-control-db-after-reset.sh | cut -d: -f1)"+ready="$(grep -n 'rollout status deployment/control-api' deploy/scripts/converge-control-db-after-reset.sh | cut -d: -f1)"+restore="$(grep -n 'GFS_RESTORE_ACTIVE_NOLOGIN=true' deploy/scripts/converge-control-db-after-reset.sh | cut -d: -f1)"+verify="$(grep -n 'verify-gfs.sh' deploy/scripts/converge-control-db-after-reset.sh | tail -1 | cut -d: -f1)"+success="$(grep -n 'migrations, runtime roles, GFS restore, and verification complete' deploy/scripts/converge-control-db-after-reset.sh | cut -d: -f1)"+[[ "$migration" -lt "$roles" && "$roles" -lt "$scale" && "$scale" -lt "$ready" && "$ready" -lt "$restore" && "$restore" -lt "$verify" && "$verify" -lt "$success" ]] \+ || fail 'reset convergence ordering is incomplete'+! grep -q '|| true' deploy/scripts/converge-control-db-after-reset.sh || fail 'reset convergence suppresses a critical failure'+for upgrade_path in Makefile scripts/minikube/pre-gate-sync.sh scripts/minikube/full-setup.sh; do+ grep -q 'get secret gfs-controller-db' "$upgrade_path" || fail "$upgrade_path does not distinguish partial bootstrap"+done+assert_minikube_upgrade_classifier() {+ local path="$1" start="$2" end="$3" block dsn classify ready abort reconcile fallback fresh+ block="$(awk -v start="$start" -v end="$end" '+ index($0, start) { active=1 }+ active { print }+ active && index($0, end) { exit }+ ' "$path")"+ dsn="$(grep -n 'writer_dsn=.*get secret gfs-controller-db' <<<"$block" | head -1 | cut -d: -f1)"+ classify="$(grep -nE 'if \[\[? -n .*writer_dsn' <<<"$block" | head -1 | cut -d: -f1)"+ ready="$(grep -n 'rollout status deployment/control-api' <<<"$block" | head -1 | cut -d: -f1)"+ abort="$(grep -n 'exit 1' <<<"$block" | tail -1 | cut -d: -f1)"+ reconcile="$(grep -n 'reconcile-gfs-deploy-credentials.sh' <<<"$block" | head -1 | cut -d: -f1)"+ fallback="$(grep -nE '^[[:space:]]*else' <<<"$block" | tail -1 | cut -d: -f1)"+ fresh="$(grep -ni 'fresh bootstrap' <<<"$block" | tail -1 | cut -d: -f1)"+ [[ -n "$dsn" && -n "$classify" && -n "$ready" && -n "$abort" && -n "$reconcile" && -n "$fallback" && -n "$fresh" ]] \+ || fail "$path upgrade classifier is incomplete"+ [[ "$dsn" -lt "$classify" && "$classify" -lt "$ready" && "$ready" -lt "$abort" && \+ "$abort" -lt "$reconcile" && "$reconcile" -lt "$fallback" && "$fallback" -lt "$fresh" ]] \+ || fail "$path does not reconcile ready upgrades, abort unready upgrades, and defer only empty bootstraps"+}+assert_minikube_upgrade_classifier Makefile '# Upgrade path: adopt/validate writer' 'kustomize deploy/overlays/minikube'+assert_minikube_upgrade_classifier scripts/minikube/full-setup.sh '# Upgrade path: stage the additive reader' 'Applying kustomize overlay'+assert_minikube_upgrade_classifier scripts/minikube/pre-gate-sync.sh 'apply-gfs-writer-secret.sh' 'make minikube-build-images'+full_setup_classifier="$(sed -n '/# Upgrade path: stage the additive reader/,/Applying kustomize overlay/p' scripts/minikube/full-setup.sh)"+reset_classifier="$(grep -n 'if \[ "$RESET_DB" = true \]; then' <<<"$full_setup_classifier" | head -1 | cut -d: -f1)"+reset_classifier_defer="$(grep -n 'HCC cutover deferred until post-convergence verification' <<<"$full_setup_classifier" | head -1 | cut -d: -f1)"+reset_classifier_else="$(grep -n '^else$' <<<"$full_setup_classifier" | head -1 | cut -d: -f1)"+reset_classifier_dsn="$(grep -n 'writer_dsn=.*get secret gfs-controller-db' <<<"$full_setup_classifier" | head -1 | cut -d: -f1)"+[[ -n "$reset_classifier" && -n "$reset_classifier_defer" && -n "$reset_classifier_else" && -n "$reset_classifier_dsn" ]] && \+ [[ "$reset_classifier" -lt "$reset_classifier_defer" && "$reset_classifier_defer" -lt "$reset_classifier_else" && \+ "$reset_classifier_else" -lt "$reset_classifier_dsn" ]] \+ || fail 'full-setup reset still reaches the control-api readiness upgrade classifier'+full_setup_reset="$(sed -n '/# 6a. Optional DB reset/,/# 6c. Re-apply generated service tokens/p' scripts/minikube/full-setup.sh)"+reset_defer="$(grep -n 'HCC cutover deferred until post-convergence verification' <<<"$full_setup_reset" | head -1 | cut -d: -f1)"+reset_postgres_only="$(grep -n 'apply -k .* -l app=control-postgres' <<<"$full_setup_reset" | head -1 | cut -d: -f1)"+reset_converge="$(grep -n 'converge-control-db-after-reset.sh' <<<"$full_setup_reset" | head -1 | cut -d: -f1)"+reset_full_overlay="$(grep -n 'kubectl kustomize .* | .* apply -f -' <<<"$full_setup_reset" | tail -1 | cut -d: -f1)"+[[ -n "$reset_defer" && -n "$reset_postgres_only" && -n "$reset_converge" && -n "$reset_full_overlay" ]] && \+ [[ "$reset_defer" -lt "$reset_postgres_only" && "$reset_postgres_only" -lt "$reset_converge" && "$reset_converge" -lt "$reset_full_overlay" ]] \+ || fail 'full-setup reset can require ready control-api or cut over HCC before convergence'+pre_gate_crds="$(grep -n 'make minikube-deploy-crds' scripts/minikube/pre-gate-sync.sh | cut -d: -f1)"+pre_gate_writer="$(grep -n 'apply-gfs-writer-secret.sh' scripts/minikube/pre-gate-sync.sh | head -1 | cut -d: -f1)"+pre_gate_overlay="$(grep -n 'make minikube-deploy-all' scripts/minikube/pre-gate-sync.sh | head -1 | cut -d: -f1)"+[[ "$(wc -l <<<"$pre_gate_crds" | tr -d ' ')" -eq 1 ]] || fail 'pre-gate must apply CRDs exactly once'+[[ "$pre_gate_crds" -lt "$pre_gate_writer" && "$pre_gate_writer" -lt "$pre_gate_overlay" ]] \+ || fail 'pre-gate must apply namespaces/CRDs before GFS Secrets and overlay'+make -n minikube-deploy-all MINIKUBE_PROFILE=test-context \+ | awk '/deploy\/base\/namespaces.yaml/{namespaces=NR} /apply-gfs-writer-secret.sh/{writer=NR} END{exit !(namespaces && writer && namespaces < writer)}' \+ || fail 'minikube-deploy-all must declare namespaces before the GFS writer Secret'+render="$(mktemp)"; trap 'rm -f "$render"' EXIT+kubectl kustomize deploy/overlays/gcp-prod >"$render"+grep -q 'name: gfs-controller-reader-db' "$render" || fail 'reader resource absent'+grep -A1 'name: CONTEXT_MAPPER_GFSC_IMAGE' "$render" | grep -q 'gfs-controller:sha-' || fail 'prod pin absent'+! grep -A1 'name: CONTEXT_MAPPER_GFSC_IMAGE' "$render" | grep -q 'gfs-controller:test' || fail 'test tag in prod'+bash scripts/tests/test-gfs-credential-lifecycle.sh+bash scripts/tests/test-provision-gfs-runtime.sh+bash scripts/tests/test-gfs-writer-secret-apply.sh+bash scripts/tests/test-gfs-nologin-restore.sh+bash scripts/tests/test-gfs-db-reset-preflight.sh+bash scripts/tests/test-reset-control-db-storage.sh+bash scripts/tests/test-gfs-hcc-rollback-static.sh+echo 'PASS: GFS deploy contract'diff --git a/scripts/tests/test-gfs-dsn-probe.sh b/scripts/tests/test-gfs-dsn-probe.shnew file mode 100755index 000000000..67c5c989f--- /dev/null+++ b/scripts/tests/test-gfs-dsn-probe.sh@@ -0,0 +1,63 @@+#!/usr/bin/env bash+set -euo pipefail++ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"+PG_HOST=control-postgres.control-plane.svc.cluster.local+PG_PORT=5432+PG_DB=profiles+PG_NS=control-plane+PG_PROBE_DEPLOY=deploy/control-api+DSN="postgresql://gfs_controller:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa@${PG_HOST}:${PG_PORT}/${PG_DB}"+PROBE_MODE=authenticated++kc() {+ cat >/dev/null+ case "$PROBE_MODE" in+ authenticated) printf gfs_controller ;;+ rejected) printf GFS_DSN_AUTH_REJECTED; return 41 ;;+ unavailable) return 1 ;;+ ambiguous) return 41 ;;+ esac+}++source "$ROOT/deploy/scripts/lib/gfs-dsn-probe.sh"+grep -q 'error.code === "28P01".*error.code === "28000"' \+ "$ROOT/deploy/scripts/lib/gfs-dsn-probe.sh" \+ || { printf 'FAIL: probe does not limit rejection to PostgreSQL authentication SQLSTATEs\n' >&2; exit 1; }++gfs_dsn_authenticates_as "$DSN" gfs_controller \+ || { printf 'FAIL: authenticated DSN was rejected\n' >&2; exit 1; }++for mode_and_rc in rejected:1 unavailable:2 ambiguous:2; do+ PROBE_MODE="${mode_and_rc%%:*}"+ expected="${mode_and_rc##*:}"+ set +e+ gfs_dsn_authenticates_as "$DSN" gfs_controller+ rc=$?+ set -e+ [ "$rc" -eq "$expected" ] \+ || { printf 'FAIL: %s probe returned %s, expected %s\n' "$PROBE_MODE" "$rc" "$expected" >&2; exit 1; }+done++calls="$(mktemp)"+set +e+(+ GFS_NS=gfs+ GFS_RECOVER_ABANDONED_STATE=true+ die() { exit 70; }+ log() { :; }+ dsn_has_role() { return 0; }+ dsn_authenticates_as() { printf 'probe:%s\n' "$1" >>"$calls"; return 2; }+ role_can_login() { printf role-state >>"$calls"; return 1; }+ release_abandoned_candidate() { printf mutation >>"$calls"; return 1; }+ source "$ROOT/deploy/scripts/lib/gfs-credential-recovery.sh"+ recover_abandoned_applying gfs_controller_reader reader-secret active candidate+) >/dev/null 2>&1+rc=$?+set -e+[ "$rc" -eq 70 ] || { rm -f "$calls"; printf 'FAIL: unavailable recovery probe returned %s\n' "$rc" >&2; exit 1; }+[ "$(cat "$calls")" = 'probe:candidate' ] \+ || { rm -f "$calls"; printf 'FAIL: unavailable recovery probe performed a mutation\n' >&2; exit 1; }+rm -f "$calls"++printf 'PASS: GFS DSN probe distinguishes rejection from unavailability\n'diff --git a/scripts/tests/test-gfs-hcc-rollback-static.sh b/scripts/tests/test-gfs-hcc-rollback-static.shnew file mode 100755index 000000000..5a47724b9--- /dev/null+++ b/scripts/tests/test-gfs-hcc-rollback-static.sh@@ -0,0 +1,22 @@+#!/usr/bin/env bash+set -euo pipefail++ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"+rollback="$(sed -n '/^gcp-prod-rollback:/,/^\.PHONY: gcp-prod-gfs-candidate-reapply/p' "$ROOT/Makefile")"+reapply="$(sed -n '/^gcp-prod-gfs-candidate-reapply:/,/^\.PHONY:/p' "$ROOT/Makefile")"+verify="$(cat "$ROOT/deploy/scripts/verify-gfs-hcc-phase.sh")"++bash -n "$ROOT/deploy/scripts/verify-gfs-hcc-phase.sh"+[[ "$rollback" == *'GFS_HCC_PRE_CUTOVER_REVISION'* ]] || { echo 'FAIL: exact HCC revision is not required' >&2; exit 1; }+[[ "$rollback" == *'--to-revision="$$revision"'* ]] || { echo 'FAIL: exact HCC revision is not targeted' >&2; exit 1; }+[[ "$rollback" == *'--phase writer-compat'* ]] || { echo 'FAIL: compatibility phase is not verified' >&2; exit 1; }+[[ "$rollback" != *'|| true'* ]] || { echo 'FAIL: rollback swallows errors' >&2; exit 1; }+[[ "$rollback" != *'rollout undo deploy --all'* ]] || { echo 'FAIL: HCC remains in bulk undo' >&2; exit 1; }+[[ "$rollback" == *'DB isolation is NOT active'* ]] || { echo 'FAIL: compatibility is mislabeled as isolation' >&2; exit 1; }+[[ "$reapply" == *'gcp-prod-deploy-all CONFIRM=yes'* ]] || { echo 'FAIL: reapply bypasses canonical deploy' >&2; exit 1; }+[[ "$reapply" == *'--phase candidate'* ]] || { echo 'FAIL: restored candidate is not verified' >&2; exit 1; }+[[ "$verify" == *'writer-compat|candidate'* ]] || { echo 'FAIL: verifier does not constrain phases' >&2; exit 1; }+[[ "$verify" == *'gfs_dsn_authenticates_as'* ]] || { echo 'FAIL: verifier does not prove database users' >&2; exit 1; }+[[ "$verify" == *'phase cannot be verified'* ]] || { echo 'FAIL: unavailable probes do not fail closed' >&2; exit 1; }++echo 'PASS: GFS HCC rollback contract is exact, fail-fast, and phase-aware'diff --git a/scripts/tests/test-gfs-nologin-restore.sh b/scripts/tests/test-gfs-nologin-restore.shnew file mode 100755index 000000000..306b15356--- /dev/null+++ b/scripts/tests/test-gfs-nologin-restore.sh@@ -0,0 +1,98 @@+#!/usr/bin/env bash+set -euo pipefail++ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"+fail() { printf 'FAIL: %s\n' "$*" >&2; exit 1; }++run_restore() (+ set -euo pipefail+ calls="$1"; export GFS_RESTORE_ACTIVE_NOLOGIN="$2"+ state="$3"; login="$4"; pre_ok="$5"; set_ok="$6"; auth_rc="$7"; post_ok="$8"+ log() { :; }+ role_can_login() { printf '%s' "$login"; }+ verify_role_contract() {+ if [ "${3:-true}" = false ]; then+ printf 'pre-contract\n' >>"$calls"; [ "$pre_ok" = yes ]+ else+ printf 'post-contract\n' >>"$calls"; [ "$post_ok" = yes ]+ fi+ }+ gfs_dsn_password() { cat >/dev/null; printf exact-password; }+ set_role_password() {+ printf 'set:%s:%s\n' "$1" "$2" >>"$calls"+ [ "$set_ok" = yes ]+ }+ dsn_authenticates_as() { printf 'auth\n' >>"$calls"; return "$auth_rc"; }+ disable_role_login() { printf 'disable:%s\n' "$1" >>"$calls"; }+ source "$ROOT/deploy/scripts/lib/gfs-credential-recovery.sh"+ restore_nologin_role_from_active gfs_controller writer active-dsn "$state"+)++assert_failure_without_set() {+ local name="$1" flag="$2" state="$3" login="$4" pre="$5" set_ok="$6" auth="$7" post="$8" calls+ calls="$(mktemp)"+ if run_restore "$calls" "$flag" "$state" "$login" "$pre" "$set_ok" "$auth" "$post"; then+ rm -f "$calls"; fail "$name unexpectedly succeeded"+ fi+ ! grep -q '^set:' "$calls" || { rm -f "$calls"; fail "$name mutated the role"; }+ rm -f "$calls"+}++assert_failure_without_set no-flag false ready f yes yes 0 yes+assert_failure_without_set wrong-state true applying f yes yes 0 yes+assert_failure_without_set already-login true ready t yes yes 0 yes+assert_failure_without_set pre-contract true ready f no yes 0 yes++calls="$(mktemp)"+set +e+(+ set -euo pipefail+ GFS_RESTORE_ACTIVE_NOLOGIN=true+ die() { exit 70; }+ dsn_authenticates_as() { printf auth >>"$calls"; return 2; }+ role_can_login() { printf role-state >>"$calls"; return 1; }+ set_role_password() { printf set >>"$calls"; }+ source "$ROOT/deploy/scripts/lib/gfs-credential-recovery.sh"+ authenticate_or_restore_nologin gfs_controller writer active-dsn ready writer+)+rc=$?+set -e+[ "$rc" -eq 70 ] || { rm -f "$calls"; fail "pre-restore unavailable probe returned $rc"; }+[ "$(cat "$calls")" = auth ] || { rm -f "$calls"; fail 'pre-restore unavailable probe mutated the role'; }+rm -f "$calls"++calls="$(mktemp)"+run_restore "$calls" true ready f yes yes 0 yes || fail 'valid explicit restore failed'+[ "$(grep -c '^set:gfs_controller:exact-password$' "$calls")" -eq 1 ] || fail 'password was not restored exactly once'+[ "$(cat "$calls")" = $'pre-contract\nset:gfs_controller:exact-password\nauth\npost-contract' ] \+ || fail 'restore verification order changed'+rm -f "$calls"++for failure in set auth post; do+ calls="$(mktemp)"+ set_ok=yes; auth=0; post=yes+ [ "$failure" != set ] || set_ok=no+ [ "$failure" != auth ] || auth=1+ [ "$failure" != post ] || post=no+ ! run_restore "$calls" true ready f yes "$set_ok" "$auth" "$post" \+ || { rm -f "$calls"; fail "$failure failure was reported as success"; }+ rm -f "$calls"+done++for auth_failure in 1 2; do+ calls="$(mktemp)"+ ! run_restore "$calls" true ready f yes yes "$auth_failure" yes \+ || { rm -f "$calls"; fail "auth rc=$auth_failure was reported as success"; }+ [ "$(grep -c '^disable:gfs_controller$' "$calls")" -eq 1 ] \+ || { rm -f "$calls"; fail "auth rc=$auth_failure did not compensate to NOLOGIN"; }+ rm -f "$calls"+done++calls="$(mktemp)"+! run_restore "$calls" true ready f yes yes 0 no \+ || { rm -f "$calls"; fail 'post-contract failure was reported as success'; }+[ "$(grep -c '^disable:gfs_controller$' "$calls")" -eq 1 ] \+ || { rm -f "$calls"; fail 'post-contract failure did not compensate to NOLOGIN'; }+rm -f "$calls"++printf 'PASS: explicit NOLOGIN restoration is gated and fail-closed\n'diff --git a/scripts/tests/test-gfs-writer-secret-apply.sh b/scripts/tests/test-gfs-writer-secret-apply.shnew file mode 100755index 000000000..f69058910--- /dev/null+++ b/scripts/tests/test-gfs-writer-secret-apply.sh@@ -0,0 +1,54 @@+#!/usr/bin/env bash+set -euo pipefail++ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"+fail() { printf 'FAIL: %s\n' "$*" >&2; exit 1; }++run_case() {+ local mode="$1" expected="$2" fake log rc+ fake="$(mktemp -d)"+ log="$fake/calls"+ cat >"$fake/kubectl" <<'SH'+#!/usr/bin/env bash+printf '%s\n' "$*" >>"$FAKE_LOG"+ case " $* " in+ *' get secret gfs-controller-db '*)+ case "$FAKE_MODE" in+ existing) printf 'secret/gfs-controller-db\n'; exit 0 ;;+ absent) printf 'Error from server (NotFound): secrets "gfs-controller-db" not found\n' >&2; exit 1 ;;+ forbidden) printf 'Error from server (Forbidden): denied\n' >&2; exit 1 ;;+ namespace-absent) printf 'Error from server (NotFound): namespaces "gfs" not found\n' >&2; exit 1 ;;+ namespace-forbidden) printf 'Error from server (Forbidden): namespaces "gfs" is forbidden\n' >&2; exit 1 ;;+ esac ;;+ *) exit 0 ;;+esac+SH+ chmod +x "$fake/kubectl"+ set +e+ PATH="$fake:$PATH" FAKE_LOG="$log" FAKE_MODE="$mode" CONTEXT=fake \+ bash "$ROOT/deploy/scripts/apply-gfs-writer-secret.sh" >/dev/null 2>&1+ rc=$?+ set -e+ [ "$rc" -eq "$expected" ] || fail "$mode returned $rc, expected $expected"+ if [ "$mode" = namespace-absent ]; then+ ! grep -q 'apply -f' "$log" || fail 'fresh namespace bootstrap applied a namespaced Secret too early'+ elif [ "$mode" = namespace-forbidden ]; then+ ! grep -q 'apply -f' "$log" || fail 'namespace API denial reached apply'+ elif [ "$mode" = existing ]; then+ [ "$(grep -n 'apply set-last-applied' "$log" | cut -d: -f1)" -lt \+ "$(grep -n 'apply -f' "$log" | cut -d: -f1)" ] || fail 'legacy ownership was not migrated before apply'+ elif [ "$mode" = absent ]; then+ ! grep -q 'apply set-last-applied' "$log" || fail 'fresh bootstrap attempted legacy migration'+ grep -q 'apply -f' "$log" || fail 'fresh bootstrap did not create Secret'+ else+ ! grep -q 'apply -f' "$log" || fail 'API denial was treated as absence'+ fi+ rm -rf "$fake"+}++run_case existing 0+run_case absent 0+run_case forbidden 1+run_case namespace-absent 1+run_case namespace-forbidden 1+printf 'PASS: GFS writer Secret apply preserves legacy data ownership\n'diff --git a/scripts/tests/test-minikube-full-setup.sh b/scripts/tests/test-minikube-full-setup.shindex 3e1decc24..2c5d55aef 100755--- a/scripts/tests/test-minikube-full-setup.sh+++ b/scripts/tests/test-minikube-full-setup.sh@@ -241,18 +241,46 @@ assert_branch_scoped_minikube_context_is_supported() {}assert_gfs_provisioning_follows_migrations_and_core_readiness() {- local migration_line provision_line readiness_line core_block+ local overlay_line ensure_line migration_line reconcile_after_migration control_ready_line core_block reset_block wal_block+ local reset_boundary reset_overlay reset_pg_ready reset_converge+ local wal_detect wal_error+ overlay_line="$(grep -n 'Kustomize overlay applied' scripts/minikube/full-setup.sh | head -1 | cut -d: -f1)"+ ensure_line="$(grep -n 'ensure_control_postgres_ready' scripts/minikube/full-setup.sh | tail -1 | cut -d: -f1)"migration_line="$(grep -n 'deploy/scripts/run-control-api-db-migration.sh' scripts/minikube/full-setup.sh | head -1 | cut -d: -f1)"- provision_line="$(grep -n 'deploy/scripts/provision-gfs-db.sh' scripts/minikube/full-setup.sh | head -1 | cut -d: -f1)"- readiness_line="$(grep -n '^CORE_DEPLOYS=(' scripts/minikube/full-setup.sh | head -1 | cut -d: -f1)"+ reconcile_after_migration="$(grep -n 'reconcile-gfs-deploy-credentials.sh' scripts/minikube/full-setup.sh | tail -1 | cut -d: -f1)"+ control_ready_line="$(grep -n 'rollout status deployment/control-api.*timeout=180s' scripts/minikube/full-setup.sh | head -1 | cut -d: -f1)"core_block="$(sed -n '/^CORE_DEPLOYS=(/,/^)/p' scripts/minikube/full-setup.sh)"-- if [[ -n "$migration_line" && -n "$provision_line" && -n "$readiness_line" ]] && \- [[ "$migration_line" -lt "$readiness_line" && "$readiness_line" -lt "$provision_line" ]] && \+ reset_block="$(sed -n '/# 6a. Optional DB reset/,/# 6c. Re-apply generated service tokens/p' scripts/minikube/full-setup.sh)"+ wal_block="$(sed -n '/A stale or late corruption signature/,/err "${ns}\/\${name} NOT ready"/p' scripts/minikube/full-setup.sh)"++ reset_boundary="$(grep -n 'reset-control-db-storage.sh' <<<"$reset_block" | head -1 | cut -d: -f1)"+ reset_overlay="$(grep -n 'Kustomize overlay applied' <<<"$reset_block" | head -1 | cut -d: -f1)"+ reset_pg_ready="$(grep -n 'rollout status deployment/control-postgres' <<<"$reset_block" | head -1 | cut -d: -f1)"+ reset_converge="$(grep -n 'converge-control-db-after-reset.sh' <<<"$reset_block" | head -1 | cut -d: -f1)"++ wal_detect="$(grep -n 'postgres_has_invalid_checkpoint' <<<"$wal_block" | head -1 | cut -d: -f1)"+ wal_error="$(grep -n 'automatic destructive recovery is disabled' <<<"$wal_block" | head -1 | cut -d: -f1)"++ if [[ -n "$overlay_line" && -n "$ensure_line" && -n "$migration_line" && -n "$reconcile_after_migration" && -n "$control_ready_line" ]] && \+ [[ "$overlay_line" -lt "$ensure_line" && "$ensure_line" -lt "$migration_line" && "$migration_line" -lt "$control_ready_line" && "$control_ready_line" -lt "$reconcile_after_migration" ]] && \+ ! grep -q 'provision-gfs-db.sh.*\(rotate\|stage\)-' scripts/minikube/full-setup.sh && \+ grep -q 'Fresh bootstrap detected.*GFSC remains fail-closed' scripts/minikube/full-setup.sh && \+ [[ "$reset_boundary" -lt "$reset_overlay" && "$reset_overlay" -lt "$reset_pg_ready" && "$reset_pg_ready" -lt "$reset_converge" ]] && \+ [[ "$wal_detect" -lt "$wal_error" ]] && \+ ! grep -q 'reset-control-db-storage.sh' <<<"$wal_block" && \+ ! grep -q '^recover_control_postgres_wal()' scripts/minikube/full-setup.sh && \+ grep -q 'CONTROL_DB_RESET_PVC_UID is required with --reset-db' scripts/minikube/full-setup.sh && \+ grep -q 'RESET_STORAGE_ARGS.*--expected-pvc-uid' scripts/minikube/full-setup.sh && \+ grep -q 'get configmap control-db-reset-state' <<<"$reset_block" && \+ grep -q 'scale deployment/gfsc-writer --replicas="\$RESET_WRITER_REPLICAS"' <<<"$reset_block" && \+ grep -q 'scale deployment/gfsc-reader --replicas="\$RESET_READER_REPLICAS"' <<<"$reset_block" && \+ grep -q 'scale deployment/host-context-controller --replicas="\$RESET_HCC_REPLICAS"' <<<"$reset_block" && \+ ! grep -q 'delete pvc control-postgres-data' scripts/minikube/full-setup.sh && \+ ! grep -q 'GFS_RESTORE_ACTIVE_NOLOGIN=true' scripts/minikube/full-setup.sh && \[[ "$core_block" != *"gfs-controller"* ]]; then- pass "full-setup provisions GFS after migrations and the non-GFS core readiness gate"+ pass "full-setup centralizes explicit UID-bound reset and never auto-deletes on WAL logs"else- fail "full-setup GFS provisioning order can run before migrations or deadlock on GFS readiness"+ fail "full-setup GFS/reset ordering can leave partial roles or deadlock on GFS readiness"fi}@@ -260,7 +288,7 @@ assert_full_setup_defaults_to_db_rebuild() {if grep -Eq '^RESET_DB=true$' scripts/minikube/full-setup.sh && \grep -Fq 'case "${REUSE_DB:-false}" in' scripts/minikube/full-setup.sh && \grep -Eq -- '--keep-db\)[[:space:]]+RESET_DB=false' scripts/minikube/full-setup.sh && \- grep -Fq 'delete pvc control-postgres-data' scripts/minikube/full-setup.sh; then+ grep -Fq 'reset-control-db-storage.sh' scripts/minikube/full-setup.sh; thenpass "full-setup rebuilds the DB by default with a REUSE_DB/--keep-db opt-out"elsefail "full-setup does not default to a clean DB rebuild with a REUSE_DB/--keep-db opt-out"diff --git a/scripts/tests/test-provision-control-api-runtime-roles.sh b/scripts/tests/test-provision-control-api-runtime-roles.shindex 35ec5f395..9ab2218a4 100755--- a/scripts/tests/test-provision-control-api-runtime-roles.sh+++ b/scripts/tests/test-provision-control-api-runtime-roles.sh@@ -4,6 +4,7 @@ set -euo pipefailROOT_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")/../.." && pwd)"SCRIPT="$ROOT_DIR/deploy/scripts/provision-control-api-runtime-roles.sh"TEST_CONTEXT="clerum-runtime-role-test"+CASE_CONTEXT="$TEST_CONTEXT"PASSWORD_A="aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"PASSWORD_B="bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"@@ -34,22 +35,31 @@ fiif [[ "${1:-}" == "-n" && "${3:-}" == "get" && "${4:-}" == "secret" ]]; thensecret_name="${5:-}"- if [[ "$TEST_MODE" == "generate" ]]; then+ if [[ "$TEST_MODE" == "api-failure" ]]; thenexit 1fi- if [[ "$*" == *" -o go-template="* ]]; then- if [[ "$TEST_MODE" == "empty" ]]; then- exit 0- fi+ if [[ "$TEST_MODE" == "generate" ]]; then+ exit 0+ fi+ if [[ "$*" == *" -o name --ignore-not-found"* ]]; then+ printf 'secret/%s\n' "$secret_name"+ exit 0+ fi+ if [[ "$*" == *" -o json --ignore-not-found"* ]]; then+ dsn=''if [[ "$TEST_MODE" == "invalid" ]]; then- printf 'postgresql://wrong-role:not-valid@wrong-host:5432/wrong-db'+ dsn='postgresql://wrong-role:not-valid@wrong-host:5432/wrong-db'+ elif [[ "$TEST_MODE" == "empty" ]]; then+ dsn=''elif [[ "$secret_name" == "control-api-postgres-runtime" ]]; then- printf 'postgresql://control_api_runtime:%[email protected]:5432/profiles' "$PASSWORD_A"+ dsn="postgresql://control_api_runtime:${PASSWORD_A}@control-postgres.control-plane.svc.cluster.local:5432/profiles"else- printf 'postgresql://trace_maintenance_runtime:%[email protected]:5432/profiles' "$PASSWORD_B"+ dsn="postgresql://trace_maintenance_runtime:${PASSWORD_B}@control-postgres.control-plane.svc.cluster.local:5432/profiles"fi+ encoded="$(printf '%s' "$dsn" | base64 | tr -d '\n')"+ printf '{"metadata":{"name":"%s"},"data":{"connection-string":"%s"}}\n' "$secret_name" "$encoded"+ exit 0fi- exit 0fiif [[ "${1:-}" == "-n" && "${3:-}" == "create" && "${4:-}" == "secret" ]]; then@@ -103,8 +113,8 @@ run_case() {: >"$TMP_DIR/sql-$mode.log": >"$TMP_DIR/patches-$mode.jsonl"rm -f "$TMP_DIR/openssl-$mode.count"- TEST_MODE="$mode" \- TEST_CONTEXT="$TEST_CONTEXT" \+ if ! TEST_MODE="$mode" \+ TEST_CONTEXT="$CASE_CONTEXT" \TEST_LOG="$TMP_DIR/kubectl-$mode.log" \TEST_SQL="$TMP_DIR/sql-$mode.log" \TEST_PATCHES="$TMP_DIR/patches-$mode.jsonl" \@@ -112,10 +122,13 @@ run_case() {PASSWORD_A="$PASSWORD_A" \PASSWORD_B="$PASSWORD_B" \PATH="$TMP_DIR:$PATH" \- CONTEXT="$TEST_CONTEXT" \- ALLOWED_CONTEXTS="$TEST_CONTEXT" \+ CONTEXT="$CASE_CONTEXT" \+ ALLOWED_CONTEXTS="$CASE_CONTEXT" \PROVISION_WORKFLOW_RECIPES_RUNTIME=false \- bash "$SCRIPT" >"$output_file" 2>&1+ bash "$SCRIPT" >"$output_file" 2>&1; then+ cat "$output_file" >&2+ fail "runtime role provisioning case failed: $mode"+ fi}if CONTEXT=blocked ALLOWED_CONTEXTS="$TEST_CONTEXT" PATH="$TMP_DIR:$PATH" \@@ -157,7 +170,7 @@ fipass "valid runtime DSNs are reused without rotation"if TEST_MODE=invalid \- TEST_CONTEXT="$TEST_CONTEXT" \+ TEST_CONTEXT="$CASE_CONTEXT" \TEST_LOG="$TMP_DIR/kubectl-invalid.log" \TEST_SQL="$TMP_DIR/sql-invalid.log" \TEST_PATCHES="$TMP_DIR/patches-invalid.jsonl" \@@ -165,8 +178,8 @@ if TEST_MODE=invalid \PASSWORD_A="$PASSWORD_A" \PASSWORD_B="$PASSWORD_B" \PATH="$TMP_DIR:$PATH" \- CONTEXT="$TEST_CONTEXT" \- ALLOWED_CONTEXTS="$TEST_CONTEXT" \+ CONTEXT="$CASE_CONTEXT" \+ ALLOWED_CONTEXTS="$CASE_CONTEXT" \PROVISION_WORKFLOW_RECIPES_RUNTIME=false \bash "$SCRIPT" >"$TMP_DIR/output-invalid" 2>&1; thenfail "invalid existing runtime DSN was accepted"@@ -177,6 +190,33 @@ grep -q 'contains an invalid runtime DSN' "$TMP_DIR/output-invalid" || \[[ ! -s "$TMP_DIR/patches-invalid.jsonl" ]] || fail "invalid DSN patched a Secret"pass "invalid existing runtime DSN fails closed before mutation"+: >"$TMP_DIR/kubectl-api-failure.log"+: >"$TMP_DIR/sql-api-failure.log"+: >"$TMP_DIR/patches-api-failure.jsonl"+if TEST_MODE=api-failure \+ TEST_CONTEXT="$CASE_CONTEXT" \+ TEST_LOG="$TMP_DIR/kubectl-api-failure.log" \+ TEST_SQL="$TMP_DIR/sql-api-failure.log" \+ TEST_PATCHES="$TMP_DIR/patches-api-failure.jsonl" \+ TEST_OPENSSL_COUNT="$TMP_DIR/openssl-api-failure.count" \+ PASSWORD_A="$PASSWORD_A" \+ PASSWORD_B="$PASSWORD_B" \+ PATH="$TMP_DIR:$PATH" \+ CONTEXT="$CASE_CONTEXT" \+ ALLOWED_CONTEXTS="$CASE_CONTEXT" \+ PROVISION_WORKFLOW_RECIPES_RUNTIME=false \+ bash "$SCRIPT" >"$TMP_DIR/output-api-failure" 2>&1; then+ fail "Kubernetes Secret read failure was treated as absence"+fi+[[ ! -e "$TMP_DIR/openssl-api-failure.count" ]] || fail "API failure generated a credential"+[[ ! -s "$TMP_DIR/sql-api-failure.log" ]] || fail "API failure reached Postgres"+[[ ! -s "$TMP_DIR/patches-api-failure.jsonl" ]] || fail "API failure patched a Secret"+pass "Kubernetes API and RBAC failures abort before credential mutation"++! grep -q 'DSN=' "$SCRIPT" || fail "runtime DSN is exposed through a child environment"+grep -q 'sys.stdin.read()' "$SCRIPT" || fail "runtime DSN parser does not consume stdin"+pass "runtime DSNs are parsed through stdin, not child environments"+if grep -v -- "--context=$TEST_CONTEXT" "$TMP_DIR/kubectl-generate.log" | grep -q .; thenfail "a kubectl invocation omitted the explicit context"fidiff --git a/scripts/tests/test-provision-gfs-runtime.sh b/scripts/tests/test-provision-gfs-runtime.shnew file mode 100755index 000000000..bf69dcce4--- /dev/null+++ b/scripts/tests/test-provision-gfs-runtime.sh@@ -0,0 +1,70 @@+#!/usr/bin/env bash+set -euo pipefail++ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"+TMP="$(mktemp -d)"+trap 'rm -rf "$TMP"' EXIT+mkdir -p "$TMP/bin" "$TMP/overlay/instances"++cat >"$TMP/bin/bash" <<'MOCK'+#!/bin/bash+printf 'bash %s\n' "$*" >>"$CALL_LOG"+MOCK++cat >"$TMP/bin/kubectl" <<'MOCK'+#!/bin/bash+set -euo pipefail+printf 'kubectl %s\n' "$*" >>"$CALL_LOG"+case " $* " in+ *' get globalfilesystem gfs -o name '*) printf 'globalfilesystem.clerum.io/gfs\n' ;;+ *' get globalfilesystem gfs -o jsonpath={.status.phase} '*) printf 'Ready' ;;+ *' get deployment gfsc-writer '*) printf 'gfs-controller-db\n' ;;+ *' get deployment gfsc-reader '*) printf 'gfs-controller-reader-db\n' ;;+ *) : ;;+esac+MOCK+chmod +x "$TMP/bin/bash" "$TMP/bin/kubectl"++export CALL_LOG="$TMP/calls.log"+for run in first-upgrade idempotent-rerun; do+ PATH="$TMP/bin:$PATH" /bin/bash "$ROOT/deploy/scripts/provision-gfs-runtime.sh" \+ --context clerum-dev-test \+ --overlay "$TMP/overlay" \+ --skip-auth-sync >/dev/null+done+PATH="$TMP/bin:$PATH" /bin/bash "$ROOT/deploy/scripts/provision-gfs-runtime.sh" \+ --context gke-prod-test \+ --overlay "$TMP/overlay" \+ --allow-prod \+ --skip-auth-sync \+ --skip-instances >/dev/null++reconcile="$ROOT/deploy/scripts/reconcile-gfs-deploy-credentials.sh"+[ "$(grep -Fc "bash $reconcile" "$CALL_LOG")" -eq 3 ] || {+ echo 'FAIL: post-overlay credential reconciliation did not run once per deploy' >&2+ exit 1+}+[ "$(grep -Fc 'rollout status deployment/host-context-controller --timeout=240s' "$CALL_LOG")" -eq 3 ] || {+ echo 'FAIL: HCC was not awaited before every post-overlay reconciliation' >&2+ exit 1+}+for deployment in gfsc-writer gfsc-reader; do+ [ "$(grep -Fc "rollout status deployment/$deployment --timeout=240s" "$CALL_LOG")" -eq 3 ] || {+ echo "FAIL: $deployment was not awaited after every reconciliation" >&2+ exit 1+ }+done+[ "$(grep -Fc 'apply -f' "$CALL_LOG")" -eq 2 ] || {+ echo 'FAIL: prod --skip-instances mutated CRD instances' >&2+ exit 1+}+! grep -Fq 'rollout restart' "$CALL_LOG" || {+ echo 'FAIL: runtime finalization introduced an unconditional rollout restart' >&2+ exit 1+}+! grep -Eq 'rotate-(writer|reader)' "$CALL_LOG" || {+ echo 'FAIL: runtime finalization introduced credential rotation' >&2+ exit 1+}++echo 'PASS: post-overlay GFS runtime reconciliation is ordered and rerunnable'diff --git a/scripts/tests/test-reset-control-db-storage.sh b/scripts/tests/test-reset-control-db-storage.shnew file mode 100755index 000000000..9382e6101--- /dev/null+++ b/scripts/tests/test-reset-control-db-storage.sh@@ -0,0 +1,255 @@+#!/usr/bin/env bash+set -euo pipefail++ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"+TMP="$(mktemp -d)"+trap 'rm -rf "$TMP"' EXIT+mkdir -p "$TMP/bin"++cat >"$TMP/bin/kubectl" <<'EOF'+#!/usr/bin/env bash+set -euo pipefail+printf '%s\n' "$*" >>"$FAKE_LOG"++case "$*" in+ *'get secret gfs-controller-db -o name') printf 'secret/gfs-controller-db\n' ;;+ *'get secret'*'-o json')+ if [[ "$*" == *gfs-controller-reader-db* ]]; then role=gfs_controller_reader; else role=gfs_controller; fi+ DSN="postgresql://${role}:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa@control-postgres.control-plane.svc.cluster.local:5432/profiles" \+ python3 -c 'import base64,json,os; print(json.dumps({"metadata":{"resourceVersion":"1","annotations":{"clerum.io/gfs-dsn-state":"ready"}},"data":{"connection-string":base64.b64encode(os.environ["DSN"].encode()).decode()}}))'+ ;;+ *'apply set-last-applied'*|*' apply -f '*) exit 0 ;;+ *'get pvc control-postgres-data -o json --ignore-not-found'*)+ # JSON view consumed by the scrub-finalizer compare-and-swap. Finalizer+ # presence is tracked in a file toggled by the pvc patch mock below.+ if [ "$FAKE_MODE" = no-pvc ]; then exit 0; fi+ uid=claim-uid-1+ [ "$FAKE_MODE" != pin-replaced ] || uid=replacement-uid+ deletion=''+ [ "$FAKE_MODE" != pin-terminating ] || deletion=',"deletionTimestamp":"2026-07-21T00:00:00Z"'+ fin='"kubernetes.io/pvc-protection"'+ [ ! -f "$FAKE_FINALIZER" ] || fin="$fin,\"clerum.io/control-db-reset-scrub\""+ printf '{"metadata":{"uid":"%s","resourceVersion":"10","finalizers":[%s]%s}}\n' "$uid" "$fin" "$deletion"+ ;;+ *'patch pvc control-postgres-data --type=json'*)+ [ "$FAKE_MODE" != pin-patch-fail ] || exit 1+ payload=""+ while [ "$#" -gt 0 ]; do+ if [ "$1" = -p ]; then shift; payload="$1"; break; fi+ shift+ done+ [ -n "$payload" ] || { printf 'missing pvc patch payload\n' >&2; exit 1; }+ case "$payload" in+ *control-db-reset-scrub*) touch "$FAKE_FINALIZER" ;;+ *)+ if [ "$FAKE_MODE" = unpin-contention ] && [ ! -f "$FAKE_UNPIN" ]; then+ touch "$FAKE_UNPIN"+ exit 1+ fi+ rm -f "$FAKE_FINALIZER"+ ;;+ esac+ ;;+ *'get pvc control-postgres-data'*)+ count=0; [ ! -f "$FAKE_COUNTER" ] || count="$(cat "$FAKE_COUNTER")"+ count=$((count + 1)); printf '%s' "$count" >"$FAKE_COUNTER"+ if [ "$FAKE_MODE" = no-pvc ]; then exit 0; fi+ if [[ "$FAKE_MODE" =~ ^resume-(after-delete|replacement-bound|converged|deleting-replacement)$ ]]; then printf replacement-uid; exit 0; fi+ if [ "$FAKE_MODE" = uid-mismatch ] && [ "$count" -eq 1 ]; then printf other-uid; exit 0; fi+ if [ "$FAKE_MODE" = uid-replaced-before-scrub ] && [ "$count" -ge 2 ]; then printf replacement-uid; exit 0; fi+ if [ "$FAKE_MODE" = uid-replaced-before-delete ] && [ "$count" -eq 3 ]; then printf replacement-uid; exit 0; fi+ if [ "$FAKE_MODE" = pin-replaced ] && [ "$count" -ge 3 ]; then printf replacement-uid; exit 0; fi+ printf claim-uid-1+ ;;+ *'get configmap control-db-reset-state'*)+ [ -s "$FAKE_STATE" ] || exit 1+ cat "$FAKE_STATE"+ ;;+ *'get deployment/host-context-controller'*) printf 4 ;;+ *'get deployment/workflow-recipes'*) printf 5 ;;+ *'get deployment/trace-maintenance-worker'*) printf 6 ;;+ *'get deployment/gfsc-writer'*) printf 3 ;;+ *'get deployment/gfsc-reader'*) printf 2 ;;+ *'get deployment/control-api'*) printf 2 ;;+ *'create configmap control-db-reset-state'*)+ [ "$FAKE_MODE" != state-create-fail ] || exit 1+ printf '1|1|authorized|%s|unbound|4|5|6|3|2|2\n' "${FAKE_ORIGINAL_UID:-claim-uid-1}" >"$FAKE_STATE"+ ;;+ *'patch configmap control-db-reset-state'*)+ [ "$FAKE_MODE" != state-cas-fail ] || exit 1+ IFS='|' read -r rv version phase original replacement hcc workflow trace writer reader controlapi <"$FAKE_STATE"+ payload=""+ while [ "$#" -gt 0 ]; do+ if [ "$1" = -p ]; then shift; payload="$1"; break; fi+ shift+ done+ [ -n "$payload" ] || { printf 'missing patch payload\n' >&2; exit 1; }+ next_phase="$(python3 -c 'import json,sys; p=json.loads(sys.argv[1]); print(next(x["value"] for x in p if x["op"]=="replace" and x["path"]=="/data/phase"))' "$payload")" || { printf 'cannot parse phase\n' >&2; exit 1; }+ next_replacement="$(python3 -c 'import json,sys; p=json.loads(sys.argv[1]); print(next(x["value"] for x in p if x["op"]=="replace" and x["path"]=="/data/replacementPvcUid"))' "$payload")" || { printf 'cannot parse replacement\n' >&2; exit 1; }+ printf '%s|%s|%s|%s|%s|%s|%s|%s|%s|%s|%s\n' "$((rv + 1))" "$version" "$next_phase" "$original" "$next_replacement" "$hcc" "$workflow" "$trace" "$writer" "$reader" "$controlapi" >"$FAKE_STATE"+ ;;+ *'scale deployment/host-context-controller --replicas=0'*) exit 0 ;;+ *'scale deployment/workflow-recipes deployment/trace-maintenance-worker --replicas=0'*) exit 0 ;;+ *'scale deployment/gfsc-writer deployment/gfsc-reader --replicas=0'*) exit 0 ;;+ *'get pods -l app=host-context-controller -o name') printf 'pod/hcc-old\n' ;;+ *'get pods -l app=gfs-controller -o name') printf 'pod/gfsc-old\n' ;;+ *'get pods -l app=workflow-recipes -o name') printf 'pod/workflow-old\n' ;;+ *'get pods -l app=trace-maintenance-worker -o name') printf 'pod/trace-old\n' ;;+ *'wait --for=delete pod -l app=host-context-controller'*) exit 0 ;;+ *'wait --for=delete pod -l app=gfs-controller'*) exit 0 ;;+ *'wait --for=delete pod -l app=workflow-recipes'*) exit 0 ;;+ *'wait --for=delete pod -l app=trace-maintenance-worker'*) exit 0 ;;+ *'scale deployment/control-api --replicas=0'*) exit 0 ;;+ *'scale deployment/control-postgres --replicas=0'*) exit 0 ;;+ *'get pods -l'*'-o json') printf '{"items":[]}\n' ;;+ *'get deployment control-postgres'*) printf 'postgres:16-alpine' ;;+ *'create -f -'*) cat >"$FAKE_MANIFEST"; [ "$FAKE_MODE" != scrub-create-fail ] ;;+ *'get pod control-postgres-storage-reset'*) printf Succeeded ;;+ *'delete pod control-postgres-storage-reset'*) exit 0 ;;+ *'delete --raw /api/v1/namespaces/control-plane/persistentvolumeclaims/control-postgres-data'*) cat >/dev/null; exit 0 ;;+ *'get pv -o json'*) printf '{"items":[]}\n' ;;+ *) printf 'unexpected kubectl invocation: %s\n' "$*" >&2; exit 91 ;;+esac+EOF+chmod +x "$TMP/bin/kubectl"++run_case() {+ local mode="$1"; shift+ : >"$TMP/$mode.log"; : >"$TMP/$mode.manifest"+ rm -f "$TMP/$mode.counter" "$TMP/$mode.state" "$TMP/$mode.finalizer" "$TMP/$mode.unpin"+ case "$mode" in+ concurrent|resume) printf '1|1|deleting-original|claim-uid-1|unbound|4|5|6|3|2|2\n' >"$TMP/$mode.state" ;;+ resume-pinned)+ printf '1|1|deleting-original|claim-uid-1|unbound|4|5|6|3|2|2\n' >"$TMP/$mode.state"+ touch "$TMP/$mode.finalizer" ;;+ resume-after-delete) printf '1|1|original-deleted|claim-uid-1|unbound|4|5|6|3|2|2\n' >"$TMP/$mode.state" ;;+ resume-replacement-bound) printf '1|1|replacement-bound|claim-uid-1|replacement-uid|4|5|6|3|2|2\n' >"$TMP/$mode.state" ;;+ resume-converged) printf '1|1|converged|claim-uid-1|replacement-uid|4|5|6|3|2|2\n' >"$TMP/$mode.state" ;;+ resume-deleting-replacement) printf '1|1|deleting-original|claim-uid-1|unbound|4|5|6|3|2|2\n' >"$TMP/$mode.state" ;;+ state-substitution) printf '1|1|replacement-bound|claim-uid-1|other-replacement|4|5|6|3|2|2\n' >"$TMP/$mode.state" ;;+ esac+ env PATH="$TMP/bin:$PATH" FAKE_MODE="$mode" FAKE_LOG="$TMP/$mode.log" \+ FAKE_MANIFEST="$TMP/$mode.manifest" FAKE_COUNTER="$TMP/$mode.counter" \+ FAKE_STATE="$TMP/$mode.state" FAKE_FINALIZER="$TMP/$mode.finalizer" \+ FAKE_UNPIN="$TMP/$mode.unpin" \+ FAKE_ORIGINAL_UID="$([ "$mode" = no-pvc ] && printf none || printf claim-uid-1)" CONTEXT=test \+ bash "$ROOT/deploy/scripts/reset-control-db-storage.sh" "$@" >"$TMP/$mode.out" 2>&1+}++if ! run_case success --expected-pvc-uid claim-uid-1; then+ cat "$TMP/success.out" >&2+ cat "$TMP/success.log" >&2+ exit 1+fi+log="$TMP/success.log"+hcc_zero="$(grep -n 'scale deployment/host-context-controller --replicas=0' "$log" | head -1 | cut -d: -f1)"+hcc_wait="$(grep -n 'wait --for=delete pod -l app=host-context-controller' "$log" | cut -d: -f1)"+gfsc_zero="$(grep -n 'scale deployment/gfsc-writer deployment/gfsc-reader --replicas=0' "$log" | head -1 | cut -d: -f1)"+scrub="$(grep -n 'create -f -' "$log" | cut -d: -f1)"+pvc_delete="$(grep -n 'delete --raw /api/v1/namespaces/control-plane/persistentvolumeclaims/control-postgres-data' "$log" | cut -d: -f1)"+[[ "$hcc_zero" -lt "$hcc_wait" && "$hcc_wait" -lt "$gfsc_zero" && "$gfsc_zero" -lt "$scrub" && "$scrub" -lt "$pvc_delete" ]]+grep -q -- '--from-literal=hccReplicas=4' "$log"+grep -q -- '--from-literal=workflowReplicas=5' "$log"+grep -q -- '--from-literal=traceReplicas=6' "$log"+grep -q -- '--from-literal=writerReplicas=3' "$log"+grep -q -- '--from-literal=readerReplicas=2' "$log"+grep -q -- '--from-literal=controlApiReplicas=2' "$log"+grep -q 'find /reset-target -mindepth 1 -xdev -delete' "$TMP/success.manifest"+# The scrub-finalizer pin closes the mount-by-name reuse window: the original+# is pinned before the scrub pod exists and released only after the post-scrub+# UID recheck, immediately before the UID-preconditioned delete.+pin="$(grep -n 'patch pvc control-postgres-data' "$log" | head -1 | cut -d: -f1)"+unpin="$(grep -n 'patch pvc control-postgres-data' "$log" | tail -1 | cut -d: -f1)"+[[ -n "$pin" && -n "$unpin" && "$pin" != "$unpin" ]]+[[ "$pin" -lt "$scrub" && "$scrub" -lt "$unpin" && "$unpin" -lt "$pvc_delete" ]]++run_case resume --expected-pvc-uid claim-uid-1 --resume+! grep -q 'create configmap control-db-reset-state' "$TMP/resume.log"+grep -q 'delete --raw /api/v1/namespaces/control-plane/persistentvolumeclaims/control-postgres-data' "$TMP/resume.log"+# A crash can leave the fixed-name scrub pod behind; resume must remove any+# leftover BEFORE creating its own, or it would fail AlreadyExists forever.+leftover_cleanup="$(grep -n 'delete pod control-postgres-storage-reset' "$TMP/resume.log" | head -1 | cut -d: -f1)"+resume_scrub="$(grep -n 'create -f -' "$TMP/resume.log" | head -1 | cut -d: -f1)"+[[ -n "$leftover_cleanup" && -n "$resume_scrub" && "$leftover_cleanup" -lt "$resume_scrub" ]]++# A crash BETWEEN pin and unpin leaves the original still pinned. Resume must+# treat the present finalizer as an idempotent "already pinned" (no second pin+# patch), run the scrub, and issue exactly one pvc patch — the unpin — before+# the UID-preconditioned delete.+run_case resume-pinned --expected-pvc-uid claim-uid-1 --resume+[ "$(grep -c 'patch pvc control-postgres-data' "$TMP/resume-pinned.log")" -eq 1 ]+rp_scrub="$(grep -n 'create -f -' "$TMP/resume-pinned.log" | head -1 | cut -d: -f1)"+rp_unpin="$(grep -n 'patch pvc control-postgres-data' "$TMP/resume-pinned.log" | head -1 | cut -d: -f1)"+rp_delete="$(grep -n 'delete --raw /api/v1/namespaces/control-plane/persistentvolumeclaims/control-postgres-data' "$TMP/resume-pinned.log" | head -1 | cut -d: -f1)"+[[ -n "$rp_scrub" && -n "$rp_unpin" && -n "$rp_delete" ]]+[[ "$rp_scrub" -lt "$rp_unpin" && "$rp_unpin" -lt "$rp_delete" ]]+# The single patch really released the finalizer in the mock's tracked state.+[ ! -f "$TMP/resume-pinned.finalizer" ]++run_case resume-after-delete --expected-pvc-uid claim-uid-1 --resume+! grep -q 'create -f -' "$TMP/resume-after-delete.log"+grep -q 'scale deployment/host-context-controller --replicas=0' "$TMP/resume-after-delete.log"+! grep -q 'persistentvolumeclaims/control-postgres-data' "$TMP/resume-after-delete.log"++for mode in resume-deleting-replacement resume-replacement-bound resume-converged; do+ run_case "$mode" --expected-pvc-uid claim-uid-1 --resume+ ! grep -q 'create -f -' "$TMP/$mode.log"+ ! grep -q 'persistentvolumeclaims/control-postgres-data' "$TMP/$mode.log"+done+grep -q 'original-deleted' "$TMP/resume-deleting-replacement.state"+# A converged reset already restored the controllers; a stray resume must not+# quiesce the healthy stack, only point the operator back at convergence.+! grep -q 'scale deployment' "$TMP/resume-converged.log"+grep -q 'converge-control-db-after-reset.sh' "$TMP/resume-converged.out"++run_case uid-replaced-before-scrub --expected-pvc-uid claim-uid-1+! grep -q 'create -f -' "$TMP/uid-replaced-before-scrub.log"+! grep -q 'persistentvolumeclaims/control-postgres-data' "$TMP/uid-replaced-before-scrub.log"+grep -q 'original-deleted' "$TMP/uid-replaced-before-scrub.state"++# A replacement that takes the name between the UID check and the finalizer+# pin is detected by the pin CAS itself: no scrub pod is created, nothing is+# deleted, and the reset still converges to original-deleted.+run_case pin-replaced --expected-pvc-uid claim-uid-1+! grep -q 'create -f -' "$TMP/pin-replaced.log"+! grep -q 'persistentvolumeclaims/control-postgres-data' "$TMP/pin-replaced.log"+grep -q 'original-deleted' "$TMP/pin-replaced.state"++# A contended finalizer release retries against the live object and still+# completes the UID-preconditioned delete (1 pin + 2 unpin attempts).+run_case unpin-contention --expected-pvc-uid claim-uid-1+[ "$(grep -c 'patch pvc control-postgres-data' "$TMP/unpin-contention.log")" -eq 3 ]+grep -q 'create -f -' "$TMP/unpin-contention.log"+grep -q 'delete --raw /api/v1/namespaces/control-plane/persistentvolumeclaims/control-postgres-data' "$TMP/unpin-contention.log"++# A terminating original or a persistently failing pin must fail closed+# before any scrub pod exists and before anything is deleted.+for mode in pin-terminating pin-patch-fail; do+ if run_case "$mode" --expected-pvc-uid claim-uid-1; then+ echo "FAIL: $mode was accepted" >&2; exit 1+ fi+ ! grep -q 'create -f -' "$TMP/$mode.log"+ ! grep -q 'persistentvolumeclaims/control-postgres-data' "$TMP/$mode.log"+done++for mode in missing-expectation uid-mismatch concurrent uid-replaced-before-delete state-create-fail state-cas-fail state-substitution; do+ args=(--expected-pvc-uid claim-uid-1)+ [ "$mode" != missing-expectation ] || args=()+ [ "$mode" != state-substitution ] || args+=(--resume)+ if run_case "$mode" "${args[@]}"; then+ echo "FAIL: $mode was accepted" >&2; exit 1+ fi+done+! grep -q 'scale deployment/host-context-controller' "$TMP/uid-mismatch.log"+! grep -q 'scale deployment/host-context-controller' "$TMP/concurrent.log"+! grep -q 'persistentvolumeclaims/control-postgres-data' "$TMP/uid-replaced-before-delete.log"+grep -q 'scale deployment/host-context-controller --replicas=0' "$TMP/uid-replaced-before-delete.log"+grep -q 'scale deployment/gfsc-writer deployment/gfsc-reader --replicas=0' "$TMP/uid-replaced-before-delete.log"+grep -q 'scale deployment/workflow-recipes deployment/trace-maintenance-worker --replicas=0' "$TMP/uid-replaced-before-delete.log"+grep -q 'scale deployment/host-context-controller --replicas=0' "$TMP/state-substitution.log"++run_case no-pvc --expect-no-pvc+! grep -q 'create -f -' "$TMP/no-pvc.log"+grep -q -- '--from-literal=originalPvcUid=none' "$TMP/no-pvc.log"++printf 'PASS: control DB reset is UID-bound, scrub-pinned, crash-resumable, and quiesces DB-dependent controllers\n'diff --git a/tests/contracts/gfs-host-subject-vectors.json b/tests/contracts/gfs-host-subject-vectors.jsonnew file mode 100644index 000000000..0cb467a3b--- /dev/null+++ b/tests/contracts/gfs-host-subject-vectors.json@@ -0,0 +1,74 @@+[+ {+ "label": "canonical host",+ "namespace": "mcp-host",+ "name": "quarterly-analyst",+ "displayText": "Quarterly Analyst",+ "expectedSubjectId": "1st:mcp-host/quarterly-analyst",+ "expectedSubject": "host:1st:mcp-host/quarterly-analyst"+ },+ {+ "label": "same durable identity after recreation",+ "namespace": "agent-workloads",+ "name": "researcher-7",+ "displayText": "Researcher recreated runtime",+ "expectedSubjectId": "1st:agent-workloads/researcher-7",+ "expectedSubject": "host:1st:agent-workloads/researcher-7"+ },+ {+ "label": "uppercase namespace",+ "namespace": "Mcp-Host",+ "name": "analyst",+ "displayText": "Analyst",+ "expectedSubjectId": null,+ "expectedSubject": null+ },+ {+ "label": "display text used as name",+ "namespace": "mcp-host",+ "name": "Quarterly Analyst",+ "displayText": "Quarterly Analyst",+ "expectedSubjectId": null,+ "expectedSubject": null+ },+ {+ "label": "leading namespace whitespace",+ "namespace": " mcp-host",+ "name": "analyst",+ "displayText": "Analyst",+ "expectedSubjectId": null,+ "expectedSubject": null+ },+ {+ "label": "trailing name whitespace",+ "namespace": "mcp-host",+ "name": "analyst ",+ "displayText": "Analyst",+ "expectedSubjectId": null,+ "expectedSubject": null+ },+ {+ "label": "path traversal name",+ "namespace": "mcp-host",+ "name": "../analyst",+ "displayText": "Analyst",+ "expectedSubjectId": null,+ "expectedSubject": null+ },+ {+ "label": "empty namespace",+ "namespace": "",+ "name": "analyst",+ "displayText": "Analyst",+ "expectedSubjectId": null,+ "expectedSubject": null+ },+ {+ "label": "overlong name",+ "namespace": "mcp-host",+ "name": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",+ "displayText": "Analyst",+ "expectedSubjectId": null,+ "expectedSubject": null+ }+]diff --git a/tests/e2e/gfsCopyFixtures.ts b/tests/e2e/gfsCopyFixtures.tsnew file mode 100644index 000000000..5b50b1c8d--- /dev/null+++ b/tests/e2e/gfsCopyFixtures.ts@@ -0,0 +1,310 @@+import { seedGfsBlobWithKubectlCp } from './gfsBlobFixtureWriter'+import {+ GFS_E2E_DRIVE,+ UUID_RE,+ assertFixtureName,+ firstDataLine,+ gfsWriterPod,+ kubectlContext,+ kubectlOut,+ ridOf,+ runControlPostgresSql,+ splitSqlRow,+ sqlLiteral,+} from './gfsFixtureCore'+import { cleanupGfsFixture } from './gfsResourceFixtures'++export interface GfsCopyTreeFixture {+ sourceName: string+ destinationName: string+ sourceResourceId: string+ destinationResourceId: string+ standaloneFileName: string+ standaloneFileResourceId: string+ sourceUri: string+ destinationUri: string+}++export interface GfsTreeSnapshotNode {+ relativePath: string+ resourceId: string+ parentResourceId: string | null+ name: string+ kind: 'file' | 'directory'+ bytes: number+ version: number+ content: string | null+}++export interface GfsHostGrantRow {+ resourceId: string+ permissions: string[]+ inherit: boolean+}++export function cleanupGfsCopyTreeFixture(fixture: GfsCopyTreeFixture): void {+ const failures: string[] = []+ for (const name of [fixture.sourceName, fixture.destinationName]) {+ try {+ cleanupGfsFixture(name)+ } catch (error) {+ failures.push(`${name}: ${error instanceof Error ? error.message : String(error)}`)+ }+ }+ if (failures.length > 0) throw new Error(`GFS Copy fixture cleanup failed: ${failures.join('; ')}`)+}++function driveRoot(): string {+ const row = firstDataLine(+ runControlPostgresSql(`+ INSERT INTO gfs_resources (drive, parent_resource_id, name, kind, path_cache)+ VALUES (${sqlLiteral(GFS_E2E_DRIVE)}, NULL, '', 'directory', '/')+ ON CONFLICT (drive) WHERE parent_resource_id IS NULL AND deleted_at IS NULL+ DO UPDATE SET updated_at = gfs_resources.updated_at+ RETURNING resource_id::text;+ `)+ )+ if (!UUID_RE.test(row)) throw new Error(`failed to resolve GFS drive root: ${row}`)+ return row+}++function insertResource(input: {+ parentId: string+ name: string+ kind: 'file' | 'directory'+ path: string+ content?: Buffer+}): string {+ const content = input.content ?? Buffer.alloc(0)+ const row = firstDataLine(+ runControlPostgresSql(`+ INSERT INTO gfs_resources (drive, parent_resource_id, name, kind, path_cache, bytes)+ VALUES (+ ${sqlLiteral(GFS_E2E_DRIVE)}, ${sqlLiteral(input.parentId)}::uuid,+ ${sqlLiteral(input.name)}, ${sqlLiteral(input.kind)}, ${sqlLiteral(input.path)},+ ${input.kind === 'file' ? content.byteLength : 0}+ ) RETURNING resource_id::text;+ `)+ )+ if (!UUID_RE.test(row)) throw new Error(`failed to seed GFS resource ${input.path}: ${row}`)+ if (input.kind === 'file') {+ seedGfsBlobWithKubectlCp({+ context: kubectlContext(),+ writerPod: gfsWriterPod(),+ blobKey: ridOf(row),+ content,+ timeoutMs: 20_000,+ })+ }+ return row+}++/** Named precondition only: Copy and Rename are always performed by the agent. */+export function seedGfsCopyTreeFixture(name: string): GfsCopyTreeFixture {+ assertFixtureName(name)+ const sourceName = `${name}-source`+ const destinationName = `${name}-destination`+ const standaloneFileName = 'standalone.txt'+ const seeded: string[] = []+ try {+ const rootId = driveRoot()+ const sourceResourceId = insertResource({+ parentId: rootId,+ name: sourceName,+ kind: 'directory',+ path: `/${sourceName}`,+ })+ seeded.push(sourceName)+ const destinationResourceId = insertResource({+ parentId: rootId,+ name: destinationName,+ kind: 'directory',+ path: `/${destinationName}`,+ })+ seeded.push(destinationName)+ const standaloneFileResourceId = insertResource({+ parentId: sourceResourceId,+ name: standaloneFileName,+ kind: 'file',+ path: `/${sourceName}/${standaloneFileName}`,+ content: Buffer.from(`issue-797 standalone ${name}\n`, 'utf8'),+ })+ const nestedId = insertResource({+ parentId: sourceResourceId,+ name: 'nested',+ kind: 'directory',+ path: `/${sourceName}/nested`,+ })+ insertResource({+ parentId: nestedId,+ name: 'empty',+ kind: 'directory',+ path: `/${sourceName}/nested/empty`,+ })+ insertResource({+ parentId: nestedId,+ name: 'alpha.txt',+ kind: 'file',+ path: `/${sourceName}/nested/alpha.txt`,+ content: Buffer.from(`issue-797 alpha ${name}\n`, 'utf8'),+ })+ const deeperId = insertResource({+ parentId: nestedId,+ name: 'deeper',+ kind: 'directory',+ path: `/${sourceName}/nested/deeper`,+ })+ insertResource({+ parentId: deeperId,+ name: 'beta.txt',+ kind: 'file',+ path: `/${sourceName}/nested/deeper/beta.txt`,+ content: Buffer.from(`issue-797 beta ${name}\n`, 'utf8'),+ })+ return {+ sourceName,+ destinationName,+ sourceResourceId,+ destinationResourceId,+ standaloneFileName,+ standaloneFileResourceId,+ sourceUri: `gfs://${GFS_E2E_DRIVE}/${ridOf(sourceResourceId)}`,+ destinationUri: `gfs://${GFS_E2E_DRIVE}/${ridOf(destinationResourceId)}`,+ }+ } catch (error) {+ const teardownFailures: string[] = []+ for (const fixtureName of seeded.reverse()) {+ try {+ cleanupGfsFixture(fixtureName)+ } catch (cleanupError) {+ teardownFailures.push(+ `${fixtureName}: ${cleanupError instanceof Error ? cleanupError.message : String(cleanupError)}`+ )+ }+ }+ if (teardownFailures.length > 0) {+ throw new Error(+ `GFS copy-tree seeding failed (${error instanceof Error ? error.message : String(error)}) ` ++ `AND teardown of partial state failed: ${teardownFailures.join('; ')}`+ )+ }+ throw error+ }+}++function readContent(resourceId: string, blobKey: string | null): string {+ const path = blobKey+ ? (() => {+ if (!/^[0-9a-f]{32}\/[0-9a-f-]{36}$/i.test(blobKey)) {+ throw new Error(`invalid GFS generation key in snapshot: ${blobKey}`)+ }+ return `/data/gfs/.generations/${blobKey}`+ })()+ : `/data/gfs/${ridOf(resourceId)}`+ return kubectlOut(['-n', 'gfs', 'exec', gfsWriterPod(), '--', 'cat', path], 20_000)+}++export function getGfsTreeSnapshot(rootId: string): GfsTreeSnapshotNode[] {+ if (!UUID_RE.test(rootId)) throw new Error(`invalid GFS root id: ${rootId}`)+ const rows = runControlPostgresSql(`+ WITH RECURSIVE tree AS (+ SELECT resource_id, parent_resource_id, name, kind, bytes, version, blob_key,+ '.'::text AS relative_path+ FROM gfs_resources+ WHERE drive = ${sqlLiteral(GFS_E2E_DRIVE)}+ AND resource_id = ${sqlLiteral(rootId)}::uuid AND deleted_at IS NULL+ UNION ALL+ SELECT child.resource_id, child.parent_resource_id, child.name, child.kind,+ child.bytes, child.version, child.blob_key, tree.relative_path || '/' || child.name+ FROM gfs_resources child JOIN tree ON child.parent_resource_id = tree.resource_id+ WHERE child.drive = ${sqlLiteral(GFS_E2E_DRIVE)} AND child.deleted_at IS NULL+ )+ SELECT relative_path || '|' || resource_id::text || '|' ||+ coalesce(parent_resource_id::text, '') || '|' || name || '|' || kind || '|' ||+ bytes::text || '|' || version::text || '|' || coalesce(blob_key, '')+ FROM tree ORDER BY relative_path;+ `)+ .split('\n')+ .map(line => line.trim())+ .filter(Boolean)++ return rows.map(row => {+ const parts = splitSqlRow(row)+ if (parts.length !== 8) throw new Error(`invalid GFS snapshot row shape: ${row}`)+ const [relativePath, resourceId, parentId, name, kind, bytes, version, blobKey] = parts as [+ string,+ string,+ string,+ string,+ string,+ string,+ string,+ string,+ ]+ if (!UUID_RE.test(resourceId) || (parentId && !UUID_RE.test(parentId))) {+ throw new Error(`invalid GFS snapshot row: ${row}`)+ }+ const normalizedKind = kind === 'directory' ? 'directory' : 'file'+ return {+ relativePath,+ resourceId,+ parentResourceId: parentId || null,+ name,+ kind: normalizedKind,+ bytes: Number(bytes),+ version: Number(version),+ content: normalizedKind === 'file' ? readContent(resourceId, blobKey || null) : null,+ }+ })+}++export function getGfsTreeAclShareCounts(rootId: string): { grants: number; shares: number } {+ if (!UUID_RE.test(rootId)) throw new Error(`invalid GFS root id: ${rootId}`)+ const row = firstDataLine(+ runControlPostgresSql(`+ WITH RECURSIVE tree AS (+ SELECT resource_id FROM gfs_resources+ WHERE drive = ${sqlLiteral(GFS_E2E_DRIVE)}+ AND resource_id = ${sqlLiteral(rootId)}::uuid AND deleted_at IS NULL+ UNION ALL+ SELECT child.resource_id FROM gfs_resources child+ JOIN tree ON child.parent_resource_id = tree.resource_id+ WHERE child.drive = ${sqlLiteral(GFS_E2E_DRIVE)} AND child.deleted_at IS NULL+ )+ SELECT (SELECT count(*) FROM gfs_grants WHERE resource_id IN (SELECT resource_id FROM tree))::text || '|' ||+ (SELECT count(*) FROM gfs_shares WHERE resource_id IN (SELECT resource_id FROM tree))::text;+ `)+ )+ const parts = splitSqlRow(row)+ if (parts.length !== 2) throw new Error(`invalid GFS ACL/share count row: ${row}`)+ const [grants, shares] = parts as [string, string]+ return { grants: Number(grants), shares: Number(shares) }+}++export function getGfsHostGrantsUnderTree(rootId: string, subjectId: string): GfsHostGrantRow[] {+ if (!UUID_RE.test(rootId) || !/^1st:[a-z0-9-]+\/[a-z0-9-]+$/.test(subjectId)) {+ throw new Error('invalid GFS host-grant tree query')+ }+ return runControlPostgresSql(`+ WITH RECURSIVE tree AS (+ SELECT resource_id FROM gfs_resources+ WHERE drive = ${sqlLiteral(GFS_E2E_DRIVE)}+ AND resource_id = ${sqlLiteral(rootId)}::uuid AND deleted_at IS NULL+ UNION ALL+ SELECT child.resource_id FROM gfs_resources child+ JOIN tree ON child.parent_resource_id = tree.resource_id+ WHERE child.drive = ${sqlLiteral(GFS_E2E_DRIVE)} AND child.deleted_at IS NULL+ )+ SELECT resource_id::text || '|' || array_to_string(permissions, ',') || '|' || inherit::text+ FROM gfs_grants WHERE resource_id IN (SELECT resource_id FROM tree)+ AND subject_type = 'host' AND subject_id = ${sqlLiteral(subjectId)} ORDER BY resource_id;+ `).split('\n').map(line => line.trim()).filter(Boolean).map(row => {+ const parts = splitSqlRow(row)+ if (parts.length !== 3 || !UUID_RE.test(parts[0] ?? '')) throw new Error(`invalid host grant row: ${row}`)+ return {+ resourceId: parts[0]!,+ permissions: parts[1] ? parts[1].split(',') : [],+ inherit: parts[2] === 't' || parts[2] === 'true',+ }+ })+}diff --git a/tests/e2e/gfsResourceFixtures.ts b/tests/e2e/gfsResourceFixtures.tsindex 933644345..05d6d71de 100644--- a/tests/e2e/gfsResourceFixtures.ts+++ b/tests/e2e/gfsResourceFixtures.ts@@ -41,10 +41,17 @@ function seedGfsBlob(resourceId: string, content: Buffer): void {}}-function cleanupGfsBlob(resourceId: string): void {- const blobKey = ridOf(resourceId)+function cleanupGfsBlob(resourceId: string, blobKey?: string | null): void {+ const physicalPath = blobKey+ ? (() => {+ if (!/^[0-9a-f]{32}\/[0-9a-f-]{36}$/i.test(blobKey)) {+ throw new Error(`refusing to clean invalid GFS generation key: ${blobKey}`)+ }+ return `/data/gfs/.generations/${blobKey}`+ })()+ : `/data/gfs/${ridOf(resourceId)}`kubectlOut(- ['-n', 'gfs', 'exec', gfsWriterPod(), '--', 'rm', '-f', `/data/gfs/${blobKey}`],+ ['-n', 'gfs', 'exec', gfsWriterPod(), '--', 'rm', '-f', physicalPath],20_000)}@@ -182,13 +189,13 @@ export function seedGfsGrant(input: {permissions: GfsPermission[]inherit?: booleangrantedBy?: string-}): void {+}): string {const subjectId = input.subjectType === 'operator' ? '' : (input.subjectId ?? '')if (input.subjectType !== 'operator' && subjectId.length === 0) {throw new Error(`subjectId is required for ${input.subjectType} GFS grants`)}const permissions = `ARRAY[${input.permissions.map(sqlLiteral).join(', ')}]::text[]`- runControlPostgresSql(`+ const grantId = firstDataLine(runControlPostgresSql(`INSERT INTO gfs_grants (drive, resource_id, subject_type, subject_id, permissions, inherit, granted_by)@@ -206,8 +213,11 @@ export function seedGfsGrant(input: {permissions = EXCLUDED.permissions,inherit = EXCLUDED.inherit,granted_by = EXCLUDED.granted_by,- updated_at = now();- `)+ updated_at = now()+ RETURNING id::text;+ `))+ if (!UUID_RE.test(grantId)) throw new Error(`failed to seed GFS grant: ${grantId}`)+ return grantId}export function getGfsGrantSummary(input: {@@ -292,10 +302,42 @@ export function getGfsChildResourceSummary(input: {}}+/**+ * Count LIVE (non-tombstoned) direct children of a parent that carry an exact+ * name. Used to prove a rejected copy left the existing child intact. The+ * partial unique index gfs_resources_sibling_uniq (control-api/src/db.ts) makes+ * two LIVE same-name siblings physically impossible, so this returns 0 or 1;+ * its value over getGfsChildResourceSummary is the deleted_at filter — that+ * helper does not exclude tombstones and would still return non-null after a+ * destructive delete, whereas `count === 1` proves a live row still exists.+ */+export function countGfsLiveChildrenByName(input: {+ parentResourceId: string+ name: string+}): number {+ if (!UUID_RE.test(input.parentResourceId)) {+ throw new Error(`invalid parent resource id: ${input.parentResourceId}`)+ }+ const row = firstDataLine(+ runControlPostgresSql(`+ SELECT count(*)::text+ FROM gfs_resources+ WHERE drive = ${sqlLiteral(GFS_E2E_DRIVE)}+ AND parent_resource_id = ${sqlLiteral(input.parentResourceId)}::uuid+ AND name = ${sqlLiteral(input.name)}+ AND deleted_at IS NULL;+ `)+ )+ if (!row) throw new Error('count query returned no row')+ const count = Number(row.trim())+ if (!Number.isInteger(count)) throw new Error(`unexpected count result: ${row}`)+ return count+}+export function cleanupGfsFixture(name: string): void {assertFixtureName(name)- const resourceIds = runControlPostgresSql(`- SELECT resource_id::text+ const resources = runControlPostgresSql(`+ SELECT resource_id::text || '|' || coalesce(blob_key, '')FROM gfs_resourcesWHERE drive = ${sqlLiteral(GFS_E2E_DRIVE)}AND kind = 'file'@@ -303,11 +345,15 @@ export function cleanupGfsFixture(name: string): void {`).split('\n').map(line => line.trim())- .filter(line => UUID_RE.test(line))+ .filter(Boolean)+ .map(splitSqlRow)+ .filter((parts): parts is [string, string] =>+ parts.length === 2 && UUID_RE.test(parts[0] ?? '')+ )const cleanupErrors: unknown[] = []- for (const resourceId of resourceIds) {+ for (const [resourceId, blobKey] of resources) {try {- cleanupGfsBlob(resourceId)+ cleanupGfsBlob(resourceId, blobKey || null)} catch (error) {cleanupErrors.push(error)}