From 4940559e2e0e3d8c880b221761cacba61e88849f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rapha=C3=ABl=20Titsworth-Morin?= Date: Thu, 19 Nov 2026 21:56:51 +0000 Subject: [PATCH 01/17] feat(selfhost): add encrypted backups and guarded operations --- deploy/selfhost/.env.example | 13 +- deploy/selfhost/README.md | 151 ++++- deploy/selfhost/created-resources.d.mts | 32 + deploy/selfhost/created-resources.mjs | 156 +++++ deploy/selfhost/docker-compose.yml | 2 +- deploy/selfhost/gcp-bootstrap.sh | 89 ++- package.json | 3 + scripts/selfhost/backup-cli.ts | 63 ++ scripts/selfhost/backup-encryption.test.ts | 146 +++++ scripts/selfhost/backup-encryption.ts | 274 ++++++++ scripts/selfhost/backup-entrypoint.test.ts | 188 ++++++ scripts/selfhost/backup-lib.ts | 492 ++++++++++++++ scripts/selfhost/backup-paths.ts | 51 ++ scripts/selfhost/backup-recovery.ts | 155 +++++ scripts/selfhost/backup.test.ts | 607 ++++++++++++++++++ scripts/selfhost/backup.ts | 30 + scripts/selfhost/bucket-objects.ts | 91 +++ scripts/selfhost/created-resources.test.ts | 88 +++ scripts/selfhost/deploy.ts | 7 + scripts/selfhost/gcp-bootstrap.test.ts | 74 +++ scripts/selfhost/install-record.ts | 111 ++++ .../selfhost/live/backup-restore.live.test.ts | 176 +++++ scripts/selfhost/operator-ci-guard.test.ts | 79 +++ scripts/selfhost/operator-only.ts | 10 + scripts/selfhost/restore.ts | 35 + scripts/selfhost/teardown-box.ts | 304 +++++++++ scripts/selfhost/teardown-compose.ts | 69 ++ scripts/selfhost/teardown-gcp-bootstrap.ts | 255 ++++++++ .../selfhost/teardown-gcp-firewall.test.ts | 82 +++ scripts/selfhost/teardown-gcp.ts | 499 ++++++++++++++ scripts/selfhost/teardown-model.ts | 273 ++++++++ scripts/selfhost/teardown-outside.ts | 84 +++ scripts/selfhost/teardown-state-dir.ts | 232 +++++++ scripts/selfhost/teardown-state.test.ts | 190 ++++++ scripts/selfhost/teardown.test.ts | 261 ++++++++ scripts/selfhost/teardown.ts | 264 ++++++++ scripts/selfhost/testdata/fake-docker.mjs | 30 + scripts/selfhost/testdata/fake-gcloud-iam.mjs | 31 +- scripts/selfhost/testdata/fake-gcloud.mjs | 83 +++ scripts/selfhost/upgrade-compose.ts | 58 ++ scripts/selfhost/upgrade-lib.ts | 310 ++++----- scripts/selfhost/upgrade-migrations.test.ts | 161 +++++ scripts/selfhost/upgrade-migrations.ts | 162 +++++ scripts/selfhost/upgrade-preflight.test.ts | 117 ++++ scripts/selfhost/upgrade-preflight.ts | 35 + scripts/selfhost/upgrade-safeguards.test.ts | 244 +++++++ scripts/selfhost/upgrade.test.ts | 204 +++--- scripts/selfhost/upgrade.ts | 32 +- .../2026-11-19-l24-selfhost-operations.md | 49 ++ 49 files changed, 6876 insertions(+), 276 deletions(-) create mode 100644 deploy/selfhost/created-resources.d.mts create mode 100644 deploy/selfhost/created-resources.mjs create mode 100644 scripts/selfhost/backup-cli.ts create mode 100644 scripts/selfhost/backup-encryption.test.ts create mode 100644 scripts/selfhost/backup-encryption.ts create mode 100644 scripts/selfhost/backup-entrypoint.test.ts create mode 100644 scripts/selfhost/backup-lib.ts create mode 100644 scripts/selfhost/backup-paths.ts create mode 100644 scripts/selfhost/backup-recovery.ts create mode 100644 scripts/selfhost/backup.test.ts create mode 100644 scripts/selfhost/backup.ts create mode 100644 scripts/selfhost/bucket-objects.ts create mode 100644 scripts/selfhost/created-resources.test.ts create mode 100644 scripts/selfhost/install-record.ts create mode 100644 scripts/selfhost/live/backup-restore.live.test.ts create mode 100644 scripts/selfhost/operator-ci-guard.test.ts create mode 100644 scripts/selfhost/operator-only.ts create mode 100644 scripts/selfhost/restore.ts create mode 100644 scripts/selfhost/teardown-box.ts create mode 100644 scripts/selfhost/teardown-compose.ts create mode 100644 scripts/selfhost/teardown-gcp-bootstrap.ts create mode 100644 scripts/selfhost/teardown-gcp-firewall.test.ts create mode 100644 scripts/selfhost/teardown-gcp.ts create mode 100644 scripts/selfhost/teardown-model.ts create mode 100644 scripts/selfhost/teardown-outside.ts create mode 100644 scripts/selfhost/teardown-state-dir.ts create mode 100644 scripts/selfhost/teardown-state.test.ts create mode 100644 scripts/selfhost/teardown.test.ts create mode 100644 scripts/selfhost/teardown.ts create mode 100755 scripts/selfhost/testdata/fake-docker.mjs create mode 100755 scripts/selfhost/testdata/fake-gcloud.mjs create mode 100644 scripts/selfhost/upgrade-compose.ts create mode 100644 scripts/selfhost/upgrade-migrations.test.ts create mode 100644 scripts/selfhost/upgrade-migrations.ts create mode 100644 scripts/selfhost/upgrade-preflight.test.ts create mode 100644 scripts/selfhost/upgrade-preflight.ts create mode 100644 scripts/selfhost/upgrade-safeguards.test.ts create mode 100644 tasks/active/2026-11-19-l24-selfhost-operations.md diff --git a/deploy/selfhost/.env.example b/deploy/selfhost/.env.example index ef0f6396e0..a2aa29ae03 100644 --- a/deploy/selfhost/.env.example +++ b/deploy/selfhost/.env.example @@ -23,6 +23,9 @@ GCP_PROJECT= # Optional services: `tunnel` runs frps for nodes; `local-store` runs the bundled object store # (trials only); `mail-collector` and `mail-in` are described below. COMPOSE_PROFILES=tunnel +# Required before running Compose: run `pnpm selfhost:deploy --init`, then copy the +# installation-specific project name it prints here. Never share it with another installation. +# COMPOSE_PROJECT_NAME=sam-selfhost- # Fleet bucket. Google Cloud Storage via Application Default Credentials (on GCE, the VM's # service account needs roles/storage.objectAdmin on the bucket): @@ -32,6 +35,7 @@ CELLD_BUCKET=gs://my-sam-bucket/celld # CELLD_BUCKET=s3://celld-fleet # S3_ENDPOINT=http://127.0.0.1:9000 # AWS_ACCESS_KEY_ID=sam-objectstore +# R2_S3_REGION=us-east-1 # REQUIRED for every s3:// operator store # AWS_SECRET_ACCESS_KEY= # at least 24 characters (the store refuses less): openssl rand -hex 24 # Loopback ports (host network). Change only on conflict, and only here: a variable set in the @@ -52,8 +56,7 @@ CELLD_BUCKET=gs://my-sam-bucket/celld # as R2_ACCESS_KEY_ID / R2_SECRET_ACCESS_KEY in .state/secrets.env (never the fleet credential). # The deploy derives the bucket and key prefix. Unset: presigned uploads stay off. # R2_S3_REGION is the store's SigV4 signing region: "auto" by default for a gs:// bucket, -# REQUIRED for an s3:// bucket (MinIO usually us-east-1): the deploy refuses R2_S3_ENDPOINT -# without it. +# REQUIRED for every s3:// operator store (MinIO usually us-east-1), including backup/restore. # R2_S3_ENDPOINT=https://storage.googleapis.com # R2_S3_REGION=auto @@ -98,6 +101,12 @@ CELLD_BUCKET=gs://my-sam-bucket/celld # Where `pnpm selfhost:deploy` keeps platform keys, gateway.env and the celld project. # SAM_SELFHOST_STATE_DIR=./.state +# Encrypted backups and automatic upgrade recovery require a separate operator-owned raw +# 32-byte key, mode 0600. Keep it outside state and backup directories, with an offline copy. +# Generate it directly into a private file; never print it (README, Backup and restore). +# Use an absolute path: this file does not expand $HOME. +# SAM_BACKUP_KEY_FILE=/absolute/private/path/to/backup.key + # frp connections Caddy accepts per client address per window at wss://api.SAM_DOMAIN/~!frp # (each one is a Login the Worker checks). Nodes keep one connection each; raise it if many nodes # share one public address (a NAT gateway). Window: 1s-99s, 1m-99m or 1h. diff --git a/deploy/selfhost/README.md b/deploy/selfhost/README.md index a9ca4aa9bc..e94296a33b 100644 --- a/deploy/selfhost/README.md +++ b/deploy/selfhost/README.md @@ -52,7 +52,10 @@ From the repository root on the VM: only that address can claim the new install by signing in with an emailed code. 4. `pnpm selfhost:deploy --init`: generates the platform keys (`.state/platform-keys.json`; back it up), `.state/gateway.env` (the reverse-tunnel gateway secret and lease port range) and the - mail-collector files. Run it again after changing the port range or turning a profile on. + mail-collector files. Set `COMPOSE_PROJECT_NAME` in `.env` to the installation-specific name + this command prints, before running Compose. Keep that name with this install; another install + needs its own state directory and project name. Run init again after changing the port range + or turning a profile on (`scripts/selfhost/install-record.ts:expectedComposeProjectFor`). 5. `(cd deploy/selfhost && docker compose build)`: builds the two local images (`caddy`, and `sam-mx` when `mail-in` is on). See [Image builds](#image-builds). 6. `(cd deploy/selfhost && docker compose up -d)`. Run compose from `deploy/selfhost/`, as every @@ -64,7 +67,10 @@ From the repository root on the VM: `celld deploy`, then waits until the new version answers. 8. Sign in at `https://app.SAM_DOMAIN`. To add someone, or a first administrator without `BOOTSTRAP_OWNER_EMAIL`: `pnpm selfhost:create-account --email someone@example.com [--superadmin]`. -9. GCP nodes: `pnpm selfhost:gcp-bootstrap -- --project --api-url https://api.SAM_DOMAIN`. +9. GCP nodes: `pnpm selfhost:gcp-bootstrap -- --project --api-url https://api.SAM_DOMAIN +--state-dir /absolute/path/to/install/.state --installation-id `. + Use the generated installation's 32-character hexadecimal id; it is a public identifier. + Keep the state directory with this install: the bootstrap writes creation receipts there. It runs after step 7 because it checks the token issuer the running install advertises. It creates a workload identity pool and provider trusting only this install, and a node service account, then prints the credential JSON to paste in **Admin -> Credentials** (Cloud Provider, @@ -89,31 +95,129 @@ From the repository root on the VM: `pnpm selfhost:deploy --dry-run` prints the Worker configuration it would deploy, secrets redacted. +## Backup and restore + +The fleet bucket contains Worker secrets as well as application data. The backup command encrypts +**the entire backup**, including the bucket, `.state/`, `.env` and its manifest, with AES-256-GCM. +It briefly stops celld for a consistent second bucket copy and restarts it even if that copy +fails (`scripts/selfhost/backup-lib.ts:runBackup`, `runPlainBackup`). Temporary plaintext lives +under the private `.tmp/selfhost-backups/` directory and is removed on success or failure. +Backup, restore and upgrade are operator-box commands; they refuse GitHub Actions. + +Create a separate raw 32-byte key once. These commands write the key directly to a private file; +they do not print it, and refuse to overwrite an existing key: + +```sh +install -d -m 700 "$HOME/.config/sam" +(umask 077; set -C; openssl rand 32 > "$HOME/.config/sam/backup.key") +pnpm selfhost:backup --encryption-key-file "$HOME/.config/sam/backup.key" +``` + +Use `--to /absolute/path/to/new-backup` for a specific destination; the default is +`deploy/selfhost/backups/`. Keep the key outside installation state and all backup +folders. Alternatively set `SAM_BACKUP_KEY_FILE` in the private `.env` to the key's **absolute** +path. The file must be owned by the operator, mode 0600, exactly 32 raw bytes, and have no symlinks +or hard links (`scripts/selfhost/backup-encryption.ts:readBackupKey`). Store a separate offline +copy of this key with your recovery records. Losing it makes the backups unrecoverable; keeping +it alongside a backup defeats that backup's encryption. Never print keys, Worker secrets or raw +bucket deployment manifests when diagnosing a failure. + +Restore into a fresh disposable or replacement installation using the same SAM checkout/ref as +the original backup. Prepare an existing mode-0600 target `.env` with its own domain, object-store +settings, absolute state path and installation-specific Compose project. Its state directory +must be empty or absent, and its bucket/prefix must contain no objects. For an `s3://` store, +set `R2_S3_REGION` as well as `S3_ENDPOINT` and its credentials. + +```sh +pnpm selfhost:restore --from /absolute/path/to/backup \ + --box-env /absolute/path/to/target.env --state-dir /absolute/path/to/fresh-state \ + --encryption-key-file "$HOME/.config/sam/backup.key" +``` + +Restore authenticates the complete encrypted inventory and every file before touching the target. +It copies state and bucket data, keeps the target `.env`, strips the source installation's +creation receipts, and leaves celld stopped. Follow the printed checkout and Compose commands +to start the recovered install, then verify its data (`scripts/selfhost/backup-lib.ts:runRestore`). +This command refuses an occupied target; it does not overwrite an existing fleet. + ## Upgrade ```sh -pnpm selfhost:upgrade --to +pnpm selfhost:upgrade --to --encryption-key-file "$HOME/.config/sam/backup.key" +``` + +Every upgrade requires a fresh encrypted pre-upgrade backup; `--skip-backup` is unsupported. +Use `--backup-to /absolute/path/to/new-backup` to choose its location, or let the command create +`backups/pre-upgrade-` next to the state directory. Keep that snapshot and its key +until you have verified the upgraded installation. + +Before deploying, the upgrade checks the active deployment's Durable Object classes against the +installed migration history and the target checkout. Unknown, removed, duplicated or reordered +migration tags, and changes to existing class declarations, are refused. Self-host-only tags, +including `selfhost-hosted-git-v1` when present in that checkout, participate in the same check +(`scripts/selfhost/upgrade-migrations.ts:installedMigrations`, `assertMigrationProgression`). + +The command requires a clean tracked checkout and an installation-specific Compose project with +creation receipts. It checks out the target, runs `deploy --init`, rebuilds changed local images, +restarts Compose when its inputs changed, deploys and checks health. Failure automatically restores +the encrypted snapshot and previous code/dependencies before starting the previous version. +The recovery checks the original installation, bucket, state and Compose ownership before removing +its disposable celld cache (`scripts/selfhost/upgrade-lib.ts:runUpgrade`, `recoverUpgrade`; +`scripts/selfhost/backup-recovery.ts:runRollback`). Redeploying an old Worker alone cannot undo a +migration. + +An unfinished operation retains `.state/upgrade-pending.json` with the previous ref and encrypted +snapshot path. Keep celld stopped if automatic recovery fails; retain the snapshot and key, and +retry the same upgrade command to recover the original install before attempting a new upgrade. +Do not delete the pending record to bypass a failed recovery. + +For a nondefault install, use `--box-env`, `--state-dir` and, if needed, `--secrets`. Every deploy +and Compose operation uses that installation's environment and overlays. Set +`SAM_SELFHOST_STATE_DIR` to an absolute path when running Compose manually. + +Older installs using the shared `sam-selfhost` project may set `COMPOSE_PROJECT_NAME=sam-selfhost` +explicitly for backup. Upgrades and destructive teardown refuse that shared identity. Move to a +separate, installation-specific Compose project through an operator-controlled migration first; +these commands do not adopt or automatically migrate the old project. + +## Teardown + +Inventory is read-only by default. Review a dry run before confirming either removal mode: + +```sh +pnpm selfhost:teardown +pnpm selfhost:teardown --keep-data --dry-run +pnpm selfhost:teardown --keep-data --confirm +pnpm selfhost:teardown --remove-everything --dry-run +pnpm selfhost:teardown --remove-everything --confirm ``` -It refuses a checkout with uncommitted changes, checks the ref out, runs `deploy --init`, rebuilds -only the images whose build inputs changed (explicitly, with `docker compose build `), -restarts the stack (`up -d`, never `--build`) only when compose inputs changed, deploys, checks -health and prints how to roll back. For a box other than the default, pass `--box-env`, -`--state-dir` and `--secrets`; every deploy and compose command it runs or prints uses that box's -`.env` and every compose file its `COMPOSE_FILE` selects. Docker compose reads -`SAM_SELFHOST_STATE_DIR` relative to `deploy/selfhost/`, so when `--state-dir` (or a `.env` outside -`deploy/selfhost/`) puts the state elsewhere, the upgrade passes the absolute path to every compose -command it runs or prints. Set it in the box `.env` as an absolute path to run `docker compose` -by hand. - -If an upgrade fails, `.state/upgrade-pending.json` records the ref it started from and the printed -output gives both ways out: run the same `selfhost:upgrade --to ` again to retry (it reruns -every step, from the recorded ref, and its rollback still names that ref), or run the printed -rollback commands. The file is removed once an upgrade passes its health check. - -**It takes no backup.** Copy the fleet bucket and `deploy/selfhost/.state` yourself first. An -upgrade that carries a D1 migration cannot be rolled back by redeploying the old ref; only your -own pre-upgrade copy restores it. +`--keep-data` stops/removes this installation's Compose containers and owned node VMs, while +keeping its volumes, bucket, configuration, backups, keys, workload identity pool/provider, service +account and IAM grants. The retained data keeps the identity needed to use it again. + +`--remove-everything` also removes proven-owned local volumes/state and cloud resources recorded +as created for this installation. It preserves backups unless `--delete-backups` is explicit, +and preserves local platform key material unless `--destroy-key` is explicit. It does not adopt +resources because their names look familiar. Foreign, ambiguous, replaced and unrecorded resources +are preserved; a refusal/failure returns a nonzero exit status. The summary lists retained data +and manual cleanup steps (`scripts/selfhost/teardown.ts`, `teardown-model.ts:execute`). + +Operator-managed `gs://` and external `s3://` stores and their contents are retained for manual +cleanup: a configured bucket URL or prefix is not creation proof. Verify exclusive ownership +before deleting anything there. The bundled trial store is removed only with its proven-owned +installation-specific Compose volume. DNS records, the box VM, its network and other manually +created resources remain operator cleanup steps. Never run destructive verification against a +shared install; use disposable resources you created for the test. + +For new GCP node firewall rules, the bootstrap optionally accepts `--create-firewalls +--agent-source-ranges ` together with `--installation-id` and `--state-dir`. +It creates only missing rules and records their immutable ids and installation/environment scope. +Choose agent source ranges appropriate for your ingress path. Existing shared rules are not +adopted. Teardown deletes a recorded rule only after rechecking its id, owner and absence of +other VM users; it preserves shared or legacy rules (`deploy/selfhost/gcp-bootstrap.sh`, +`scripts/selfhost/teardown-gcp.ts:firewallItems`). Keep `.state/created-resources.json` after a +partial teardown: it is the receipt used to resume cleanup. ## Image builds @@ -213,13 +317,12 @@ bucket's deploy manifests, so the bucket credential is the install's master key. and run agents only once a GitHub App (the `GITHUB_*` Worker secrets in `.state/secrets.env`) or a GitLab integration is configured. Without one, sign-in, administration and nodes work, but no agent session can start. -- **Backup, restore and teardown** commands. Back up the fleet bucket and `.state/` yourself. Do not put data on this box that you could not afford to lose or leak. ## Tests -- `pnpm selfhost:test`: deploy, upgrade, account and configuration logic, compose wiring, pinned +- `pnpm selfhost:test`: deploy, encrypted backup/restore, upgrade recovery, teardown ownership, account and configuration logic, compose wiring, pinned versions, `caddy/start.sh` (no Docker needed). - `pnpm selfhost:live-test`: the box's real Caddy image (built from `caddy/Dockerfile`), frp and celld in Docker with host networking: gateway 404s and path tricks, the frp rate limit, header diff --git a/deploy/selfhost/created-resources.d.mts b/deploy/selfhost/created-resources.d.mts new file mode 100644 index 0000000000..aefeb54221 --- /dev/null +++ b/deploy/selfhost/created-resources.d.mts @@ -0,0 +1,32 @@ +// Types for created-resources.mjs (the record of what an install created; no secrets). +export const FORMAT: 'sam-created-resources/1'; + +export interface CreatedResource { + cloud: string; + kind: string; + name: string; + attributes?: Record; + createdBy: string; + action: 'created' | 'reused'; + createdAt?: string; + removedAt?: string; +} + +export interface CreatedResourcesRecord { + format: typeof FORMAT; + resources: CreatedResource[]; +} + +export function readRecord(file: string): CreatedResourcesRecord; +export function addResource( + file: string, + entry: Omit, + now?: Date +): void; +export function markRemoved( + file: string, + cloud: string, + kind: string, + name: string, + now?: Date +): void; diff --git a/deploy/selfhost/created-resources.mjs b/deploy/selfhost/created-resources.mjs new file mode 100644 index 0000000000..0d9091971e --- /dev/null +++ b/deploy/selfhost/created-resources.mjs @@ -0,0 +1,156 @@ +#!/usr/bin/env node +// The record of cloud resources SAM's setup scripts created for one install, kept in the box +// state (`.state/created-resources.json`, mode 0600) so a teardown removes exactly those and +// nothing else. Provider-neutral: one entry per resource, whatever the cloud. +// +// { +// "format": "sam-created-resources/1", +// "resources": [{ +// "cloud": "gcp" | "aws" | "azure" | ..., +// "kind": "kms-key" | "iam-binding" | "service-account" | ..., // the cloud's own terms +// "name": "", // unique per cloud+kind +// "attributes": { "project": "...", "role": "...", ... }, // strings, never secrets +// "createdBy": "gcp-bootstrap", +// "action": "created" | "reused", // reused: existed before; a teardown leaves it +// "createdAt": "", +// "removedAt": "" // set once a teardown removed it +// }] +// } +// +// Used by deploy/selfhost/gcp-bootstrap.sh: +// created-resources.mjs add [k=v ...] +// created-resources.mjs list -> kindnameactionremovedAt +// created-resources.mjs removed +import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs'; +import { dirname } from 'node:path'; + +export const FORMAT = 'sam-created-resources/1'; +const SECRETISH = /(secret|token|password|private|credential|key-material)/i; + +export function readRecord(file) { + if (!existsSync(file)) return { format: FORMAT, resources: [] }; + const parsed = JSON.parse(readFileSync(file, 'utf8')); + if (parsed?.format !== FORMAT || !Array.isArray(parsed.resources)) { + throw new Error(`${file} is not a ${FORMAT} record`); + } + const names = new Set(); + for (const r of parsed.resources) { + if ( + !r || + typeof r.cloud !== 'string' || + !r.cloud || + typeof r.kind !== 'string' || + !r.kind || + typeof r.name !== 'string' || + !r.name || + typeof r.createdBy !== 'string' || + !['created', 'reused'].includes(r.action) || + (r.attributes !== undefined && + (!r.attributes || + typeof r.attributes !== 'object' || + Array.isArray(r.attributes) || + Object.values(r.attributes).some((v) => typeof v !== 'string'))) + ) { + throw new Error('invalid resource receipt; refusing ambiguous ownership'); + } + const key = JSON.stringify([r.cloud, r.kind, r.name]); + if (names.has(key)) throw new Error('duplicate resource receipt; refusing ambiguous ownership'); + names.add(key); + } + return parsed; +} + +function writeRecord(file, record) { + mkdirSync(dirname(file), { recursive: true, mode: 0o700 }); + const tmp = `${file}.tmp-${process.pid}`; + writeFileSync(tmp, `${JSON.stringify(record, null, 2)}\n`, { mode: 0o600 }); + renameSync(tmp, file); +} + +/** + * Adds or refreshes one entry. A live resource once recorded as created never becomes "reused". + * An entry a teardown removed that is recorded again exists again: it takes the new action and + * loses its removedAt, so a later teardown neither skips it as already removed nor deletes a + * resource this run only found (reused). + */ +export function addResource(file, entry, now = new Date()) { + for (const key of Object.keys(entry.attributes ?? {})) { + if (SECRETISH.test(key)) + throw new Error(`refusing to record attribute ${key}: no secrets here`); + } + const record = readRecord(file); + const existing = record.resources.find( + (r) => r.cloud === entry.cloud && r.kind === entry.kind && r.name === entry.name + ); + if (existing) { + const replaced = + existing.attributes?.identity && + entry.attributes?.identity && + existing.attributes.identity !== entry.attributes.identity; + if ( + !existing.removedAt && + !replaced && + ['install', 'installation', 'environment'].some( + (key) => + existing.attributes?.[key] && + entry.attributes?.[key] && + existing.attributes[key] !== entry.attributes[key] + ) + ) { + throw new Error('resource ownership scope changed; refusing to adopt an existing receipt'); + } + if (existing.removedAt || replaced) { + Object.assign(existing, { action: entry.action, createdAt: now.toISOString() }); + delete existing.removedAt; + } else if (existing.action !== 'created') { + existing.action = entry.action; + } + existing.attributes = { ...existing.attributes, ...entry.attributes }; + } else { + record.resources.push({ ...entry, createdAt: now.toISOString() }); + } + writeRecord(file, record); +} + +export function markRemoved(file, cloud, kind, name, now = new Date()) { + const record = readRecord(file); + const entry = record.resources.find( + (r) => r.cloud === cloud && r.kind === kind && r.name === name + ); + if (!entry) throw new Error(`${cloud} ${kind} ${name} is not in ${file}`); + entry.removedAt = now.toISOString(); + writeRecord(file, record); +} + +if (import.meta.url === `file://${process.argv[1]}`) { + const [command, file, ...rest] = process.argv.slice(2); + try { + if (command === 'add') { + const [cloud, kind, name, action, createdBy, ...pairs] = rest; + if (!cloud || !kind || !name || !['created', 'reused'].includes(action) || !createdBy) { + throw new Error( + 'usage: add [k=v ...]' + ); + } + const attributes = Object.fromEntries( + pairs.map((pair) => [pair.slice(0, pair.indexOf('=')), pair.slice(pair.indexOf('=') + 1)]) + ); + addResource(file, { cloud, kind, name, attributes, createdBy, action }); + } else if (command === 'list') { + const [cloud, createdBy] = rest; + for (const r of readRecord(file).resources) { + if (r.cloud === cloud && r.createdBy === createdBy) { + process.stdout.write(`${r.kind}\t${r.name}\t${r.action}\t${r.removedAt ?? ''}\n`); + } + } + } else if (command === 'removed') { + const [cloud, kind, name] = rest; + markRemoved(file, cloud, kind, name); + } else { + throw new Error('usage: created-resources.mjs add|list|removed ...'); + } + } catch (error) { + process.stderr.write(`created-resources: ${error.message}\n`); + process.exit(1); + } +} diff --git a/deploy/selfhost/docker-compose.yml b/deploy/selfhost/docker-compose.yml index aafab1f178..cfe8e3157e 100644 --- a/deploy/selfhost/docker-compose.yml +++ b/deploy/selfhost/docker-compose.yml @@ -23,7 +23,7 @@ # `docker compose build` (or when the image does not exist yet); `pnpm selfhost:upgrade` rebuilds # a service only when its build inputs changed. The pinned celld version must match CELLD_VERSION # in scripts/selfhost/versions.ts, which the deploy script uses for `celld deploy`. -name: sam-selfhost +name: ${COMPOSE_PROJECT_NAME:?Set the installation-specific project printed by selfhost:deploy --init} services: celld: diff --git a/deploy/selfhost/gcp-bootstrap.sh b/deploy/selfhost/gcp-bootstrap.sh index b5add84162..13ead3e14a 100755 --- a/deploy/selfhost/gcp-bootstrap.sh +++ b/deploy/selfhost/gcp-bootstrap.sh @@ -31,6 +31,10 @@ # --provider-id default: sam-api # --service-account default: sam-nodes (account id, before @) # --skip-issuer-check do not fetch /.well-known/openid-configuration first +# --state-dir creation receipts (default deploy/selfhost/.state) +# --installation-id normalized SAM_INSTALLATION_ID; enables ownership receipts for teardown +# --create-firewalls create absent shared SAM node rules with installation ownership metadata +# --agent-source-ranges required with --create-firewalls (comma-separated; agent ingress) # --dry-run print every gcloud command that would change something; change nothing set -euo pipefail @@ -41,6 +45,11 @@ PROVIDER_ID="sam-api" SA_ID="sam-nodes" DRY_RUN=0 CHECK_ISSUER=1 +INSTALLATION_ID="" +CREATE_FIREWALLS=0 +AGENT_RANGES="" +STATE_DIR="$(cd "$(dirname "$0")" && pwd)/.state" +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" # The APIs node provisioning calls: compute (VMs, firewalls; packages/providers/src/gcp*.ts), # cloudbilling (list prices, gcp-pricing.ts), and iam, sts and iamcredentials (the pool and the @@ -70,6 +79,10 @@ while [[ $# -gt 0 ]]; do --provider-id) need_value "$1" $#; PROVIDER_ID="$2"; shift 2 ;; --service-account) need_value "$1" $#; SA_ID="$2"; shift 2 ;; --skip-issuer-check) CHECK_ISSUER=0; shift ;; + --installation-id) need_value "$1" $#; INSTALLATION_ID="$2"; shift 2 ;; + --create-firewalls) CREATE_FIREWALLS=1; shift ;; + --agent-source-ranges) need_value "$1" $#; AGENT_RANGES="$2"; shift 2 ;; + --state-dir) need_value "$1" $#; STATE_DIR="$2"; shift 2 ;; --dry-run) DRY_RUN=1; shift ;; # The header comment, up to the first line that is not a comment. -h|--help) awk 'NR > 1 && /^#/ { sub(/^# ?/, ""); print; next } NR > 1 { exit }' "$0"; exit 0 ;; @@ -78,7 +91,7 @@ while [[ $# -gt 0 ]]; do done # grep checks below are line by line: refuse any value with a newline before they run. -for value in "$PROJECT" "$API_URL" "$POOL_ID" "$PROVIDER_ID" "$SA_ID"; do +for value in "$PROJECT" "$API_URL" "$POOL_ID" "$PROVIDER_ID" "$SA_ID" "$INSTALLATION_ID" "$AGENT_RANGES"; do case "$value" in *$'\n'*|*$'\r'*) die "arguments must not contain line breaks" ;; *) ;; @@ -103,6 +116,13 @@ printf '%s' "$POOL_ID" | grep -Eq '^[a-z][a-z0-9-]{3,31}$' || die "invalid --poo printf '%s' "$PROVIDER_ID" | grep -Eq '^[a-z][a-z0-9-]{3,31}$' || die "invalid --provider-id: $PROVIDER_ID" printf '%s' "$SA_ID" | grep -Eq '^[a-z][a-z0-9-]{5,29}$' || die "invalid --service-account: $SA_ID" SA_EMAIL="${SA_ID}@${PROJECT}.iam.gserviceaccount.com" +if [[ -n "$INSTALLATION_ID" ]]; then + printf '%s' "$INSTALLATION_ID" | grep -Eq '^[a-f0-9]{32}$' || die "--installation-id must be the normalized 32 hex installation id" +fi +if [[ "$CREATE_FIREWALLS" -eq 1 ]]; then + [[ -n "$INSTALLATION_ID" && -n "$AGENT_RANGES" ]] || die "--create-firewalls requires --installation-id and --agent-source-ranges" + printf '%s' "$AGENT_RANGES" | grep -Eq '^[0-9a-fA-F:.,/]+$' || die "invalid --agent-source-ranges" +fi # Only tokens SAM signs for the installation's own (platform) credential: SAM sets # user_id = platform: for those and the bare owner id for a user's credential # (gcpIdentityTokenUserId in apps/api/src/services/gcp-sts.ts). So a user's GCP credential that @@ -133,6 +153,14 @@ change_retry() { command -v gcloud >/dev/null 2>&1 || die "gcloud is not installed or not on PATH" +# Receipts contain public resource identifiers only, never credentials. Reuse never becomes +# creation proof; teardown will preserve resources that existed before this install. +record_resource() { + [[ "$DRY_RUN" -eq 0 && -n "$INSTALLATION_ID" ]] || return 0 + node "$SCRIPT_DIR/created-resources.mjs" add "$STATE_DIR/created-resources.json" gcp "$1" "$2" "$3" gcp-bootstrap \ + "project=$PROJECT" "install=$ISSUER" "identity=$4" "pool=$POOL_ID" "environment=selfhost" "installation=$INSTALLATION_ID" "account=$SA_EMAIL" "member=${5:-}" "role=${6:-}" +} + # The OIDC provider trusts the issuer the install advertises: check it before trusting it. if [[ "$CHECK_ISSUER" -eq 1 ]]; then discovery="$(curl -fsS --max-time 10 "${ISSUER}/.well-known/openid-configuration" 2>/dev/null)" \ @@ -155,6 +183,7 @@ change services enable "${NODE_APIS[@]}" --project="$PROJECT" # A deleted pool still describes (state DELETED) and keeps its id for 30 days: reusing it as # "exists" would then try to create a provider in a deleted pool (R13 D5). +pool_action=reused if pool_state="$(gcloud iam workload-identity-pools describe "$POOL_ID" --project="$PROJECT" \ --location=global --format='value(state)' 2>/dev/null)"; then [[ "$pool_state" != "DELETED" ]] \ @@ -182,13 +211,20 @@ if pool_state="$(gcloud iam workload-identity-pools describe "$POOL_ID" --projec done <<<"$pool_providers" echo "pool ${POOL_ID}: exists" else + pool_action=created change iam workload-identity-pools create "$POOL_ID" --project="$PROJECT" --location=global \ --display-name="SAM ${ISSUER#https://api.}" \ --description="Dedicated to the SAM install whose token issuer is ${ISSUER}" fi +if [[ "$DRY_RUN" -eq 0 && -n "$INSTALLATION_ID" ]]; then + pool_identity="$(gcloud iam workload-identity-pools describe "$POOL_ID" --project="$PROJECT" --location=global --format='value(name)')" + record_resource workload-identity-pool "$POOL_ID" "$pool_action" "$pool_identity" +fi + # SAM signs aud=https://iam.googleapis.com/ (gcp-sts.ts). AUDIENCE="https://iam.googleapis.com/projects/${PROJECT_NUMBER}/locations/global/workloadIdentityPools/${POOL_ID}/providers/${PROVIDER_ID}" +provider_action=reused if provider_state="$(gcloud iam workload-identity-pools providers describe "$PROVIDER_ID" \ --project="$PROJECT" --location=global --workload-identity-pool="$POOL_ID" \ --format='value(state)' 2>/dev/null)"; then @@ -226,6 +262,7 @@ else # Only this install's platform tokens are admitted (attributeCondition), and only tokens # addressed to this provider: SAM signs aud=https://iam.googleapis.com/ (gcp-sts.ts). Mapping # matches the guided setup (gcp-setup.ts). + provider_action=created change iam workload-identity-pools providers create-oidc "$PROVIDER_ID" --project="$PROJECT" \ --location=global --workload-identity-pool="$POOL_ID" --display-name="SAM API" \ --issuer-uri="$ISSUER" \ @@ -234,6 +271,11 @@ else --attribute-condition="$CONDITION" fi +if [[ "$DRY_RUN" -eq 0 && -n "$INSTALLATION_ID" ]]; then + provider_identity="$(gcloud iam workload-identity-pools providers describe "$PROVIDER_ID" --project="$PROJECT" --location=global --workload-identity-pool="$POOL_ID" --format='value(name)')" + record_resource workload-identity-provider "$PROVIDER_ID" "$provider_action" "$provider_identity" +fi + sa_existed=0 if exists iam service-accounts describe "$SA_EMAIL" --project="$PROJECT"; then sa_existed=1 @@ -319,9 +361,34 @@ if [[ "$sa_existed" -eq 1 ]]; then || die "service account ${SA_EMAIL} has ${key_count} user-managed key(s); anyone holding one acts as the node account. Delete them (gcloud iam service-accounts keys list --iam-account=${SA_EMAIL} --managed-by=user, then gcloud iam service-accounts keys delete --iam-account=${SA_EMAIL}), then run this again; or pass --service-account ." fi +if [[ "$DRY_RUN" -eq 0 && -n "$INSTALLATION_ID" ]]; then + sa_identity="$(gcloud iam service-accounts describe "$SA_EMAIL" --project="$PROJECT" --format='value(uniqueId)')" + sa_action=created + [[ "$sa_existed" -eq 0 ]] || sa_action=reused + record_resource service-account "$SA_EMAIL" "$sa_action" "$sa_identity" +fi + for role in "${NODE_ROLES[@]}"; do + grant_action=reused + if [[ "$DRY_RUN" -eq 0 && -n "$INSTALLATION_ID" ]]; then + policy="$(gcloud projects get-iam-policy "$PROJECT" --format=json)" || die "cannot read project IAM policy" + grant_status=0 + printf '%s' "$policy" | ROLE="$role" MEMBER="serviceAccount:$SA_EMAIL" node -e ' + let text=""; process.stdin.on("data", x=>text+=x); process.stdin.on("end", ()=>{ + let p; try {p=JSON.parse(text)} catch {process.exit(2)}; if (!p || !Array.isArray(p.bindings ?? [])) process.exit(2); + process.exit((p.bindings ?? []).some(b=>b.role===process.env.ROLE && b.members?.includes(process.env.MEMBER)) ? 0 : 10); + });' || grant_status=$? + case "$grant_status" in + 0) ;; + 10) grant_action=created ;; + *) die "cannot parse project IAM policy" ;; + esac + fi change_retry projects add-iam-policy-binding "$PROJECT" --member="serviceAccount:${SA_EMAIL}" \ --role="$role" --condition=None --quiet --format=none + if [[ "$DRY_RUN" -eq 0 && -n "$INSTALLATION_ID" ]]; then + record_resource iam-binding "projects/$PROJECT#$role#serviceAccount:$SA_EMAIL" "$grant_action" "$sa_identity" "serviceAccount:$SA_EMAIL" "$role" + fi done # Scope: the whole pool. Its only provider (checked above on every run) admits only tokens whose @@ -334,6 +401,26 @@ change_retry iam service-accounts add-iam-policy-binding "$SA_EMAIL" --project=" --role=roles/iam.workloadIdentityUser --member="$POOL_PRINCIPAL" \ --condition=None --quiet --format=none +# Optional: make only rules absent at creation time, preserving an ownership receipt. +# Existing same-name rules belong to whoever created them and are never adopted. +if [[ "$CREATE_FIREWALLS" -eq 1 ]]; then + for rule in sam-allow-agent sam-allow-app-routes; do + if gcloud compute firewall-rules describe "$rule" --project="$PROJECT" --format=json >/dev/null 2>&1; then + echo "firewall $rule: exists; not adopted" + continue + fi + ranges="$AGENT_RANGES"; ports=tcp:8080,tcp:8443; tag=sam-agent + if [[ "$rule" == sam-allow-app-routes ]]; then ranges=0.0.0.0/0; ports=tcp:80,tcp:443; tag=sam-deployment-app-routes; fi + description="SAM installation=$INSTALLATION_ID environment=selfhost issuer=$ISSUER" + change compute firewall-rules create "$rule" --project="$PROJECT" --network=default --direction=INGRESS \ + --priority=1000 --target-tags="$tag" --allow="$ports" --source-ranges="$ranges" --description="$description" + if [[ "$DRY_RUN" -eq 0 && -n "$INSTALLATION_ID" ]]; then + identity="$(gcloud compute firewall-rules describe "$rule" --project="$PROJECT" --format='value(id)')" + record_resource firewall-rule "$rule" created "$identity" + fi + done +fi + [[ "$DRY_RUN" -eq 1 ]] && echo "Dry run: nothing was changed." # The shape parseGcpCredential (apps/api/src/services/provider-credential-codecs.ts) reads. cat < Date.now(), + log, + user: uid !== undefined && gid !== undefined ? `${uid}:${gid}` : undefined, + }; +} diff --git a/scripts/selfhost/backup-encryption.test.ts b/scripts/selfhost/backup-encryption.test.ts new file mode 100644 index 0000000000..af3d6c6024 --- /dev/null +++ b/scripts/selfhost/backup-encryption.test.ts @@ -0,0 +1,146 @@ +import { randomBytes } from 'node:crypto'; +import { + chmodSync, + existsSync, + mkdirSync, + mkdtempSync, + readFileSync, + rmSync, + statSync, + symlinkSync, + writeFileSync, +} from 'node:fs'; +import { join, resolve } from 'node:path'; + +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; + +import { decryptBackupTree, encryptBackupTree, readBackupKey } from './backup-encryption.js'; + +const cleanup: string[] = []; +beforeEach(() => { + for (const name of Object.keys(process.env)) { + if (name === 'CI' || name === 'GITHUB_ACTIONS' || name.startsWith('RUNNER_')) + vi.stubEnv(name, undefined); + } +}); +function fixture() { + mkdirSync(resolve('.tmp'), { recursive: true }); + const root = mkdtempSync(resolve('.tmp/backup-encryption-')); + cleanup.push(root); + const source = join(root, 'source'); + const encrypted = join(root, 'encrypted'); + const restored = join(root, 'restored'); + const key = join(root, 'key'); + mkdirSync(source); + writeFileSync(key, randomBytes(32), { mode: 0o600 }); + writeFileSync(join(source, 'secrets.env'), 'PRIVATE_KEY=operator-test-fixture'); + return { root, source, encrypted, restored, key }; +} +afterEach(() => { + vi.unstubAllEnvs(); + for (const root of cleanup.splice(0)) rmSync(root, { recursive: true, force: true }); +}); + +describe('operator encrypted backup trees', () => { + it('round trips binary archives larger than the chunk size, empty files and directories without storing plaintext', () => { + const f = fixture(); + const archive = randomBytes(8 * 1024 * 1024 + 7); + mkdirSync(join(f.source, 'objects')); + mkdirSync(join(f.source, 'empty-directory')); + writeFileSync(join(f.source, 'objects', 'archive.bin'), archive); + writeFileSync(join(f.source, 'empty'), ''); + encryptBackupTree(f.source, f.encrypted, f.key); + expect( + readFileSync(join(f.encrypted, 'secrets.env')).includes(Buffer.from('operator-test-fixture')) + ).toBe(false); + expect(readFileSync(join(f.encrypted, 'objects', 'archive.bin')).equals(archive)).toBe(false); + decryptBackupTree(f.encrypted, f.restored, f.key); + expect(readFileSync(join(f.restored, 'objects', 'archive.bin')).equals(archive)).toBe(true); + expect(readFileSync(join(f.restored, 'secrets.env'), 'utf8')).toBe( + 'PRIVATE_KEY=operator-test-fixture' + ); + expect(readFileSync(join(f.restored, 'empty'))).toHaveLength(0); + expect(statSync(join(f.restored, 'empty-directory')).isDirectory()).toBe(true); + expect(statSync(f.restored).mode & 0o777).toBe(0o700); + expect(statSync(join(f.restored, 'secrets.env')).mode & 0o777).toBe(0o600); + }); + + it.each([ + 'header', + 'ciphertext', + 'tag', + 'truncated', + 'missing', + 'extra', + 'renamed', + 'wrong-key', + 'manifest', + ])('refuses %s and removes all incomplete plaintext', (corruption) => { + const f = fixture(); + encryptBackupTree(f.source, f.encrypted, f.key); + const path = join(f.encrypted, 'secrets.env'); + const bytes = readFileSync(path); + if (corruption === 'missing') rmSync(path); + else if (corruption === 'extra') writeFileSync(join(f.encrypted, 'extra'), bytes); + else if (corruption === 'renamed') { + rmSync(path); + writeFileSync(join(f.encrypted, 'renamed'), bytes); + } else if (corruption === 'wrong-key') writeFileSync(f.key, randomBytes(32)); + else if (corruption === 'truncated') writeFileSync(path, bytes.subarray(0, bytes.length - 1)); + else if (corruption === 'manifest') + writeFileSync(join(f.encrypted, '.sam-backup-manifest'), bytes); + else { + const offset = + corruption === 'header' ? 9 : corruption === 'ciphertext' ? 20 : bytes.length - 1; + bytes[offset] = (bytes[offset] ?? 0) ^ 1; + writeFileSync(path, bytes); + } + expect(() => decryptBackupTree(f.encrypted, f.restored, f.key)).toThrow( + 'authentication failed' + ); + expect(existsSync(f.restored)).toBe(false); + }); + + it('rejects valid ciphertext substituted from another snapshot under the same key', () => { + const f = fixture(); + const second = join(f.root, 'second'); + encryptBackupTree(f.source, f.encrypted, f.key); + encryptBackupTree(f.source, second, f.key); + writeFileSync(join(f.encrypted, 'secrets.env'), readFileSync(join(second, 'secrets.env'))); + expect(() => decryptBackupTree(f.encrypted, f.restored, f.key)).toThrow( + 'authentication failed' + ); + expect(existsSync(f.restored)).toBe(false); + }); + + it('refuses symlink inputs and keys, insecure keys, invalid lengths and keys inside the tree', () => { + const f = fixture(); + chmodSync(f.key, 0o644); + expect(() => readBackupKey(f.key)).toThrow(); + chmodSync(f.key, 0o600); + writeFileSync(f.key, randomBytes(31)); + expect(() => readBackupKey(f.key)).toThrow('exactly 32'); + writeFileSync(f.key, randomBytes(32)); + symlinkSync(f.key, join(f.root, 'linked-key')); + expect(() => readBackupKey(join(f.root, 'linked-key'))).toThrow('symlinks'); + symlinkSync(f.key, join(f.source, 'link')); + expect(() => encryptBackupTree(f.source, f.encrypted, f.key)).toThrow(); + expect(existsSync(f.encrypted)).toBe(false); + rmSync(join(f.source, 'link')); + writeFileSync(join(f.source, 'inside-key'), randomBytes(32), { mode: 0o600 }); + expect(() => encryptBackupTree(f.source, f.encrypted, join(f.source, 'inside-key'))).toThrow( + 'separately' + ); + }); + + it('refuses existing destinations, overlapping trees and CI before reading any key', () => { + const f = fixture(); + mkdirSync(f.encrypted); + expect(() => encryptBackupTree(f.source, f.encrypted, f.key)).toThrow('already exist'); + expect(() => encryptBackupTree(f.source, join(f.source, 'nested'), f.key)).toThrow('overlap'); + vi.stubEnv('GITHUB_ACTIONS', 'true'); + expect(() => readBackupKey('/does-not-exist')).toThrow('forbidden in CI'); + expect(() => encryptBackupTree(f.source, f.encrypted, f.key)).toThrow('forbidden in CI'); + expect(() => decryptBackupTree(f.source, f.restored, f.key)).toThrow('forbidden in CI'); + }); +}); diff --git a/scripts/selfhost/backup-encryption.ts b/scripts/selfhost/backup-encryption.ts new file mode 100644 index 0000000000..c5f08d1182 --- /dev/null +++ b/scripts/selfhost/backup-encryption.ts @@ -0,0 +1,274 @@ +import { assertOperatorExecution } from './operator-only'; +/** Operator-only backup encryption. The 32-byte key must be stored separately from backups. */ +import { + type CipherGCM, + createCipheriv, + createDecipheriv, + type DecipherGCM, + randomBytes, +} from 'node:crypto'; +import { + closeSync, + constants, + existsSync, + fstatSync, + lstatSync, + mkdirSync, + openSync, + readdirSync, + readFileSync, + readSync, + realpathSync, + rmSync, + writeFileSync, + writeSync, +} from 'node:fs'; +import { dirname, isAbsolute, join, relative, resolve, sep } from 'node:path'; + +import { assertPrivateFile } from './secret-files.js'; + +// Versioned wire format: magic | 12-byte nonce | ciphertext | 16-byte GCM tag. +const MAGIC = Buffer.from('SAMBAK01'); +const NONCE_BYTES = 12; +const TAG_BYTES = 16; +const KEY_BYTES = 32; +const CHUNK_BYTES = 64 * 1024; +const MANIFEST = '.sam-backup-manifest'; + +/** Raw random bytes, not a password or hex string. Never print the returned buffer. */ +export function readBackupKey(keyFile: string): Buffer { + assertOperatorExecution(); + if (realpathSync(keyFile) !== resolve(keyFile)) + throw new Error('Backup key must not use symlinks'); + assertPrivateFile(keyFile); + const fd = openSync(keyFile, constants.O_RDONLY | constants.O_NOFOLLOW); + try { + const stat = fstatSync(fd); + if ( + !stat.isFile() || + stat.nlink !== 1 || + (stat.mode & 0o777) !== 0o600 || + stat.size !== KEY_BYTES || + (process.getuid !== undefined && stat.uid !== process.getuid()) + ) { + throw new Error( + 'Backup key must be a mode-0600 regular file containing exactly 32 random bytes' + ); + } + return readExact(fd, KEY_BYTES, 0); + } finally { + closeSync(fd); + } +} + +function within(root: string, path: string): boolean { + const rel = relative(root, path); + return rel === '' || (!rel.startsWith(`..${sep}`) && rel !== '..' && !isAbsolute(rel)); +} + +function prepare(source: string, destination: string, keyFile: string): Buffer { + assertOperatorExecution(); + if (realpathSync(source) !== resolve(source) || !lstatSync(source).isDirectory()) { + throw new Error('Backup source must be a directory without symlinks'); + } + if (existsSync(destination)) throw new Error('Backup destination must not already exist'); + if (realpathSync(dirname(resolve(destination))) !== dirname(resolve(destination))) { + throw new Error('Backup destination parent must not use symlinks'); + } + if ( + within(resolve(source), resolve(destination)) || + within(resolve(destination), resolve(source)) + ) { + throw new Error('Backup source and destination must not overlap'); + } + const keyPath = realpathSync(keyFile); + if (within(resolve(source), keyPath) || within(resolve(destination), keyPath)) { + throw new Error('Store the backup key separately from the backup trees'); + } + return readBackupKey(keyFile); +} + +interface Tree { + files: string[]; + directories: string[]; +} +function scan(root: string): Tree { + const tree: Tree = { files: [], directories: [] }; + const visit = (dir: string): void => { + for (const name of readdirSync(join(root, dir)).sort()) { + const path = dir ? `${dir}/${name}` : name; + const stat = lstatSync(join(root, path)); + if (stat.isDirectory()) { + tree.directories.push(path); + visit(path); + } else if (stat.isFile() && stat.nlink === 1) tree.files.push(path); + else throw new Error('Backup tree contains a symlink, hard link or special file'); + } + }; + visit(''); + return tree; +} + +function aad(header: Buffer, path: string): Buffer { + return Buffer.concat([header, Buffer.from(`\0${path}`, 'utf8')]); +} +function header(): Buffer { + return Buffer.concat([MAGIC, randomBytes(NONCE_BYTES)]); +} +function writeAll(fd: number, data: Buffer): void { + let offset = 0; + while (offset < data.length) offset += writeSync(fd, data, offset, data.length - offset); +} +function readExact(fd: number, size: number, position: number): Buffer { + const data = Buffer.alloc(size); + let offset = 0; + while (offset < size) { + const n = readSync(fd, data, offset, size - offset, position + offset); + if (n === 0) throw new Error('Truncated encrypted backup'); + offset += n; + } + return data; +} + +/** Bounded memory even for database/object archives larger than the operator's RAM. */ +function transformFile( + source: string, + destination: string, + path: string, + key: Buffer, + decrypt: boolean, + snapshot = '' +): void { + assertOperatorExecution(); + const input = openSync(source, constants.O_RDONLY | constants.O_NOFOLLOW); + let output: number | undefined; + try { + const stat = fstatSync(input); + if (!stat.isFile() || stat.nlink !== 1) throw new Error('Backup input must be a regular file'); + const prefix = decrypt ? readExact(input, MAGIC.length + NONCE_BYTES, 0) : header(); + if (!prefix.subarray(0, MAGIC.length).equals(MAGIC)) + throw new Error('Unknown backup encryption format'); + const nonce = prefix.subarray(MAGIC.length); + const cipher = decrypt + ? createDecipheriv('aes-256-gcm', key, nonce) + : createCipheriv('aes-256-gcm', key, nonce); + cipher.setAAD(aad(prefix, `${snapshot}\0${path}`)); + let position = decrypt ? prefix.length : 0; + const end = decrypt ? stat.size - TAG_BYTES : stat.size; + if (end < position) throw new Error('Truncated encrypted backup'); + if (decrypt) (cipher as DecipherGCM).setAuthTag(readExact(input, TAG_BYTES, end)); + output = openSync(destination, 'wx', 0o600); + if (!decrypt) writeAll(output, prefix); + const chunk = Buffer.alloc(CHUNK_BYTES); + while (position < end) { + const count = readSync(input, chunk, 0, Math.min(chunk.length, end - position), position); + if (count === 0) throw new Error('Backup input changed during encryption'); + writeAll(output, cipher.update(chunk.subarray(0, count))); + position += count; + } + writeAll(output, cipher.final()); + if (!decrypt) writeAll(output, (cipher as CipherGCM).getAuthTag()); + } finally { + closeSync(input); + if (output !== undefined) closeSync(output); + } +} + +function sealManifest(tree: Tree, snapshot: string, key: Buffer): Buffer { + const prefix = header(); + const cipher = createCipheriv('aes-256-gcm', key, prefix.subarray(MAGIC.length)); + cipher.setAAD(aad(prefix, `\0${MANIFEST}`)); + return Buffer.concat([ + prefix, + cipher.update(JSON.stringify({ snapshot, tree })), + cipher.final(), + cipher.getAuthTag(), + ]); +} + +/** Destination is new, private, and contains ciphertext only, including an authenticated inventory. */ +export function encryptBackupTree(source: string, destination: string, keyFile: string): void { + assertOperatorExecution(); + const key = prepare(source, destination, keyFile); + let created = false; + try { + const tree = scan(source); + const snapshot = randomBytes(16).toString('hex'); + if (tree.files.includes(MANIFEST) || tree.directories.includes(MANIFEST)) + throw new Error('Reserved backup manifest name'); + mkdirSync(destination, { mode: 0o700 }); + created = true; + for (const dir of tree.directories) mkdirSync(join(destination, dir), { mode: 0o700 }); + for (const file of tree.files) + transformFile(join(source, file), join(destination, file), file, key, false, snapshot); + writeFileSync(join(destination, MANIFEST), sealManifest(tree, snapshot, key), { + mode: 0o600, + flag: 'wx', + }); + } catch { + if (created) rmSync(destination, { recursive: true, force: true }); + throw new Error('Backup encryption failed; incomplete output removed'); + } finally { + key.fill(0); + } +} + +/** + * Decrypt into a NEW private scratch directory. Nothing may restore from it until this returns: + * GCM authenticates at end-of-file, and every file and the full inventory must pass first. + * The caller must remove the plaintext scratch directory after restore, including on failure. + */ +export function decryptBackupTree(source: string, destination: string, keyFile: string): void { + assertOperatorExecution(); + const key = prepare(source, destination, keyFile); + let created = false; + try { + const tree = scan(source); + if (!tree.files.includes(MANIFEST)) throw new Error('Missing encrypted inventory'); + // Bound manifest plaintext to the actual inventory size, even for untrusted input. + const inventory = { + files: tree.files.filter((f) => f !== MANIFEST), + directories: tree.directories, + }; + const expected = JSON.stringify(inventory); + const manifestSize = + Buffer.byteLength(JSON.stringify({ snapshot: '0'.repeat(32), tree: inventory })) + + MAGIC.length + + NONCE_BYTES + + TAG_BYTES; + if (lstatSync(join(source, MANIFEST)).size !== manifestSize) + throw new Error('Backup inventory size mismatch'); + mkdirSync(destination, { mode: 0o700 }); + created = true; + transformFile(join(source, MANIFEST), join(destination, MANIFEST), MANIFEST, key, true); + // Compare canonical JSON, never trust manifest paths for filesystem operations. + const manifest: unknown = JSON.parse(readFileSync(join(destination, MANIFEST), 'utf8')); + if ( + typeof manifest !== 'object' || + manifest === null || + !('snapshot' in manifest) || + typeof manifest.snapshot !== 'string' || + !/^[a-f0-9]{32}$/.test(manifest.snapshot) || + !('tree' in manifest) || + JSON.stringify(manifest.tree) !== expected + ) { + throw new Error('Backup inventory mismatch'); + } + rmSync(join(destination, MANIFEST)); + for (const dir of tree.directories) mkdirSync(join(destination, dir), { mode: 0o700 }); + for (const file of tree.files.filter((f) => f !== MANIFEST)) + transformFile( + join(source, file), + join(destination, file), + file, + key, + true, + manifest.snapshot + ); + } catch { + if (created) rmSync(destination, { recursive: true, force: true }); + throw new Error('Backup authentication failed; incomplete plaintext removed'); + } finally { + key.fill(0); + } +} diff --git a/scripts/selfhost/backup-entrypoint.test.ts b/scripts/selfhost/backup-entrypoint.test.ts new file mode 100644 index 0000000000..cfa7789121 --- /dev/null +++ b/scripts/selfhost/backup-entrypoint.test.ts @@ -0,0 +1,188 @@ +/** + * `pnpm selfhost:backup` then `pnpm selfhost:restore`, run as the real commands (tsx backup.ts, + * tsx restore.ts) with fake `gcloud` and `docker` binaries first on PATH (testdata/). The fake + * gcloud reproduces the box failure from PR #2675: objects celld rewrites while running vanish + * mid-copy in the live pass, and the aborted pass leaves state that broke the delta pass with + * `[Errno 2] No such file or directory: /bucket/nodes/node_.json`. + */ +import { spawnSync } from 'node:child_process'; +import { randomBytes } from 'node:crypto'; +import { + chmodSync, + copyFileSync, + existsSync, + mkdirSync, + mkdtempSync, + readdirSync, + readFileSync, + rmSync, + writeFileSync, +} from 'node:fs'; +import { join, resolve } from 'node:path'; + +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; + +import { decryptBackupTree } from './backup-encryption'; + +const REPO = resolve(import.meta.dirname, '../..'); +const TSX = join(REPO, 'node_modules/.bin/tsx'); +let root: string; +let env: NodeJS.ProcessEnv; + +function tree(dir: string, base = dir): Record { + const out: Record = {}; + if (!existsSync(dir)) return out; + for (const entry of readdirSync(dir, { withFileTypes: true })) { + const path = join(dir, entry.name); + if (entry.isDirectory()) Object.assign(out, tree(path, base)); + else out[path.slice(base.length + 1)] = readFileSync(path, 'utf8'); + } + return out; +} + +function put(dir: string, files: Record): void { + for (const [name, body] of Object.entries(files)) { + mkdirSync(join(dir, name, '..'), { recursive: true }); + writeFileSync(join(dir, name), body); + } +} + +function run(script: string, args: string[]) { + return spawnSync(TSX, [join(REPO, 'scripts/selfhost', script), ...args], { + cwd: REPO, + env, + encoding: 'utf8', + }); +} + +const FLEET = 'gs://fleet/celld'; + +beforeEach(() => { + for (const name of Object.keys(process.env)) { + if (name === 'CI' || name === 'GITHUB_ACTIONS' || name.startsWith('RUNNER_')) + vi.stubEnv(name, undefined); + } + mkdirSync(resolve('.tmp'), { recursive: true }); + root = mkdtempSync(resolve('.tmp/sam-backup-cli-')); + writeFileSync(join(root, 'backup-key'), randomBytes(32), { mode: 0o600 }); + const bin = join(root, 'bin'); + mkdirSync(bin); + for (const name of ['gcloud', 'docker']) { + copyFileSync(join(import.meta.dirname, `testdata/fake-${name}.mjs`), join(bin, name)); + chmodSync(join(bin, name), 0o755); + } + const state = join(root, 'fake'); + mkdirSync(state); + writeFileSync(join(state, 'celld'), 'running'); + env = { + ...process.env, + PATH: `${bin}:${process.env.PATH ?? ''}`, + FAKE_GCS_ROOT: join(root, 'gcs'), + FAKE_STATE: state, + }; + + // The running fleet as the live pass sees it. + put(join(root, 'gcs/fleet/celld'), { + 'd1/main.ltx': 'rows-v1', + 'current.json': '{"v":3}', + 'nodes/node_live.json': '{"lease":1}', + 'nodes/node_retired.json': '{"lease":7}', + 'fleet/capacity-v1.json': '{"free":2}', + }); + // celld rewrites these every few seconds: the live pass meets vanished generations (404). + writeFileSync( + join(state, 'churn.json'), + JSON.stringify(['nodes/node_live.json', 'fleet/capacity-v1.json']) + ); + // What celld wrote between the live pass and its shutdown: a node row retired (present in the + // live pass, absent in the delta pass), a new one, and fresh contents for churned objects. + writeFileSync( + join(state, 'on-stop.json'), + JSON.stringify({ + bucketDir: join(root, 'gcs/fleet/celld'), + remove: ['nodes/node_retired.json'], + write: { + 'nodes/node_live.json': '{"lease":2}', + 'nodes/node_new.json': '{"lease":1}', + 'fleet/capacity-v1.json': '{"free":1}', + 'd1/main.ltx': 'rows-v2', + }, + }) + ); + + mkdirSync(join(root, 'state')); + writeFileSync(join(root, 'state/platform-keys.json'), '{"k":"v"}'); + writeFileSync(join(root, 'box.env'), `CELLD_BUCKET=${FLEET}\n`, { mode: 0o600 }); +}); + +afterEach(() => { + vi.unstubAllEnvs(); + rmSync(root, { recursive: true, force: true }); +}); + +describe('selfhost:backup and selfhost:restore (real entry points, fake gcloud)', () => { + // Runs the real backup and restore entry points as child processes: give them room under load. + it( + 'backs up exactly the post-stop bucket when objects vanish between the passes, and restores it into an empty install', + { timeout: 60_000 }, + () => { + const dest = join(root, 'backups/b1'); + const backup = run('backup.ts', [ + '--to', + dest, + '--encryption-key-file', + join(root, 'backup-key'), + '--box-env', + join(root, 'box.env'), + '--state-dir', + join(root, 'state'), + ]); + expect(backup.stderr).toBe(''); + expect(backup.status).toBe(0); + expect(backup.stdout).toContain('live pre-copy incomplete'); + + // What celld left when it stopped is the consistent state; the backup is exactly that. + const afterStop = tree(join(root, 'gcs/fleet/celld')); + expect(afterStop['nodes/node_retired.json']).toBeUndefined(); + const inspection = join(root, 'inspection'); + decryptBackupTree(dest, inspection, join(root, 'backup-key')); + expect(tree(join(inspection, 'bucket'))).toEqual(afterStop); + expect(readdirSync(dest).sort()).toEqual( + ['.sam-backup-manifest', 'backup-manifest.json', 'bucket', 'env', 'state'].sort() + ); + + const manifest = JSON.parse(readFileSync(join(inspection, 'backup-manifest.json'), 'utf8')); + expect(manifest).toMatchObject({ version: 1, bucket: FLEET, objectCount: 5 }); + expect(typeof manifest.downtimeMs).toBe('number'); + expect(manifest.downtimeMs).toBeGreaterThanOrEqual(manifest.deltaCopyMs); + + rmSync(inspection, { recursive: true, force: true }); + const calls = readFileSync(join(root, 'fake/calls.log'), 'utf8').trim().split('\n'); + expect(calls.map((c) => c.split(' ').slice(0, 3).join(' '))).toEqual([ + 'gcloud storage rsync', // live + 'docker compose --project-name', + 'gcloud storage rsync', // delta, celld stopped + 'docker compose --project-name', + ]); + expect(calls[1]).toMatch(/stop celld$/); + expect(calls[3]).toMatch(/start celld$/); + + // Restore into an empty install: new bucket, no platform keys yet. + writeFileSync(join(root, 'new.env'), 'CELLD_BUCKET=gs://fresh/celld\n', { mode: 0o600 }); + const restore = run('restore.ts', [ + '--from', + dest, + '--encryption-key-file', + join(root, 'backup-key'), + '--box-env', + join(root, 'new.env'), + '--state-dir', + join(root, 'new-state'), + ]); + expect(restore.stderr).toBe(''); + expect(restore.status).toBe(0); + expect(tree(join(root, 'gcs/fresh/celld'))).toEqual(afterStop); + expect(tree(join(root, 'new-state'))).toEqual({ 'platform-keys.json': '{"k":"v"}' }); + } + ); +}); diff --git a/scripts/selfhost/backup-lib.ts b/scripts/selfhost/backup-lib.ts new file mode 100644 index 0000000000..9cd04fa0b9 --- /dev/null +++ b/scripts/selfhost/backup-lib.ts @@ -0,0 +1,492 @@ +import { assertOperatorExecution } from './operator-only'; +/** Encrypted operator backups with a stopped-writer consistency boundary. */ +import { + cpSync, + lstatSync, + mkdtempSync, + realpathSync, + existsSync, + mkdirSync, + readdirSync, + readFileSync, + renameSync, + rmSync, + writeFileSync, +} from 'node:fs'; +import { join, relative, resolve, dirname } from 'node:path'; + +import { recordBackup, composeProjectFor } from './install-record'; +import { assertOperationPaths, assertBackupOutside } from './backup-paths'; +import { decryptBackupTree, encryptBackupTree, readBackupKey } from './backup-encryption'; +import { ensurePrivateDir } from './secret-files'; + +/** + * Rebuildable caches under the state dir, left out of every backup. `go-cache` is the vm-agent + * build cache (`pnpm selfhost:deploy` refills it); on the test box it was 1.6 GB of a 3.6 GB backup, + * and the state copy runs while celld is stopped, so it also lengthened every backup's downtime. + */ +export const STATE_CACHE_EXCLUDES = ['go-cache']; + +export function isRebuildableCachePath(stateDir: string, src: string): boolean { + const rel = relative(stateDir, src); + return STATE_CACHE_EXCLUDES.some((path) => rel === path || rel.startsWith(`${path}/`)); +} + +export const OBJECTSTORE_IMAGE = + 'pgsty/minio@sha256:b6bfe7239bfc83fb90d31612d9704d86039dd714f7904b3f1ad68f211e602372'; +export const MANIFEST_NAME = 'backup-manifest.json'; +export const BUCKET_DIR = 'bucket'; +/** Where the live pre-copy lands. It is renamed to BUCKET_DIR before the delta copy (runBackup). */ +export const LIVE_DIR = '.bucket-live'; +/** A from-scratch copy, used only when the delta copy fails (runBackup). */ +export const FULL_DIR = '.bucket-full'; +/** Suffix of gcloud's in-flight download files; one left by an aborted pass is not an object. */ +const GCLOUD_TEMP_SUFFIX = '_.gstmp'; +export const STATE_DIR = 'state'; +export const ENV_FILE = 'env'; + +export interface RunResult { + status: number; + stdout: string; + stderr: string; +} + +/** Runs a command. `env` is the child's environment (secrets go here, never in `args`). */ +export type Runner = (command: string, args: string[], env?: NodeJS.ProcessEnv) => RunResult; + +export interface BoxContext { + /** Parsed deploy/selfhost/.env. */ + box: Readonly>; + envFile: string; + stateDir: string; + /** Every compose file the box runs with, in order (composeFilesFor). */ + composeFiles: string[]; + run: Runner; + now: () => number; + log: (message: string) => void; + /** uid:gid for files `mc` writes into a local directory. */ + user?: string; + /** Separate operator-owned raw 32-byte encryption key, never backed up. */ + encryptionKeyFile?: string; +} + +export interface BucketUrl { + scheme: 'gs' | 's3'; + bucket: string; + prefix: string; +} + +export function parseBucketUrl(url: string): BucketUrl { + const match = /^(gs|s3):\/\/([^/]+)\/?(.*)$/.exec(url.trim()); + if (!match) throw new Error(`CELLD_BUCKET must be gs://bucket[/prefix] or s3://bucket[/prefix]`); + return { + scheme: match[1] as 'gs' | 's3', + bucket: match[2] as string, + prefix: (match[3] ?? '').replace(/\/+$/, ''), + }; +} + +export function check(result: RunResult, what: string): RunResult { + if (result.status !== 0) { + // Tool diagnostics may embed signed URLs or credentials. Never relay them. + throw new Error( + `${what} failed (exit ${result.status}); inspect the tool locally without sharing secret-bearing output` + ); + } + return result; +} + +export function mcEnv(ctx: BoxContext): NodeJS.ProcessEnv { + const endpoint = ctx.box.S3_ENDPOINT?.trim(); + const key = ctx.box.AWS_ACCESS_KEY_ID ?? ''; + const secret = ctx.box.AWS_SECRET_ACCESS_KEY ?? ''; + if (!endpoint) throw new Error('s3:// buckets need S3_ENDPOINT in .env'); + const url = new URL(endpoint); + url.username = encodeURIComponent(key); + url.password = encodeURIComponent(secret); + return { ...process.env, MC_HOST_src: url.toString().replace(/\/$/, '') }; +} + +export function mcArgs(ctx: BoxContext, mounts: string[], mcCommand: string[]): string[] { + return [ + 'run', + '--rm', + '--network', + 'host', + ...(ctx.user ? ['--user', ctx.user] : []), + '-e', + 'MC_HOST_src', + '-e', + 'MC_CONFIG_DIR=/tmp/mc', + ...mounts.flatMap((m) => ['-v', m]), + '--entrypoint', + 'mc', + OBJECTSTORE_IMAGE, + ...mcCommand, + ]; +} + +export function bucketPath(url: BucketUrl): string { + return url.prefix ? `${url.bucket}/${url.prefix}` : url.bucket; +} + +/** Copy the fleet bucket into `dir`, deleting files no longer in the bucket (a mirror). */ +export function pullBucket(ctx: BoxContext, dir: string): void { + const url = parseBucketUrl(ctx.box.CELLD_BUCKET ?? ''); + mkdirSync(dir, { recursive: true, mode: 0o700 }); + if (url.scheme === 'gs') { + check( + ctx.run('gcloud', [ + 'storage', + 'rsync', + '--recursive', + '--delete-unmatched-destination-objects', + `gs://${bucketPath(url)}`, + dir, + ]), + 'gcloud storage rsync (bucket -> backup)' + ); + return; + } + check( + ctx.run( + 'docker', + mcArgs( + ctx, + [`${resolve(dir)}:/backup`], + ['mirror', '--overwrite', '--remove', '--quiet', `src/${bucketPath(url)}`, '/backup'] + ), + mcEnv(ctx) + ), + 'mc mirror (bucket -> backup)' + ); +} + +/** Copy `dir` into the (empty) fleet bucket. */ +export function pushBucket(ctx: BoxContext, dir: string): void { + const url = parseBucketUrl(ctx.box.CELLD_BUCKET ?? ''); + if (url.scheme === 'gs') { + check( + ctx.run('gcloud', ['storage', 'rsync', '--recursive', dir, `gs://${bucketPath(url)}`]), + 'gcloud storage rsync (backup -> bucket)' + ); + return; + } + check( + ctx.run( + 'docker', + mcArgs( + ctx, + [`${resolve(dir)}:/backup:ro`], + ['mirror', '--quiet', '/backup', `src/${bucketPath(url)}`] + ), + mcEnv(ctx) + ), + 'mc mirror (backup -> bucket)' + ); +} + +/** Whether the fleet bucket (under its prefix) holds no objects. */ +export function bucketIsEmpty(ctx: BoxContext): boolean { + const url = parseBucketUrl(ctx.box.CELLD_BUCKET ?? ''); + if (url.scheme === 'gs') { + const result = ctx.run('gcloud', ['storage', 'ls', `gs://${bucketPath(url)}/**`]); + if (result.status !== 0 && /matched no objects/i.test(result.stderr)) return true; + return check(result, 'gcloud storage ls').stdout.trim() === ''; + } + const result = check( + ctx.run('docker', mcArgs(ctx, [], ['ls', '--recursive', `src/${bucketPath(url)}`]), mcEnv(ctx)), + 'mc ls' + ); + return result.stdout.trim() === ''; +} + +export { composeFilesFor } from './compose-env'; + +/** `docker compose` arguments for this box: every compose file, then its .env, then `args`. */ +export function composeArgs( + ctx: Pick & Partial>, + args: string[] +): string[] { + return [ + 'compose', + '--project-name', + composeProjectFor(ctx.box ?? {}, ctx.stateDir ?? resolve(dirname(ctx.envFile), '.state')), + ...ctx.composeFiles.flatMap((file) => ['-f', file]), + '--env-file', + ctx.envFile, + ...args, + ]; +} + +function compose(ctx: BoxContext, args: string[]): void { + check(ctx.run('docker', composeArgs(ctx, args)), `docker compose ${args.join(' ')}`); +} + +export interface BackupManifest { + version: 1; + createdAt: string; + /** The bucket URL only; credentials are never written here. */ + bucket: string; + samCommit: string | null; + precopyMs: number; + /** celld stopped -> celld started again. */ + downtimeMs: number; + deltaCopyMs: number; + objectCount: number; +} + +function countFiles(dir: string): number { + if (!existsSync(dir)) return 0; + let count = 0; + for (const entry of readdirSync(dir, { withFileTypes: true })) { + count += entry.isDirectory() ? countFiles(join(dir, entry.name)) : 1; + } + return count; +} + +function firstLine(err: unknown): string { + return err instanceof Error ? (err.message.split('\n')[0] ?? '').slice(0, 200) : String(err); +} + +/** Deletes gcloud download temporaries an aborted pass left behind (they are not bucket objects). */ +function removeGcloudTemporaries(dir: string): void { + for (const entry of readdirSync(dir, { withFileTypes: true })) { + const path = join(dir, entry.name); + if (entry.isDirectory()) removeGcloudTemporaries(path); + else if (entry.name.endsWith(GCLOUD_TEMP_SUFFIX)) rmSync(path, { force: true }); + } +} + +/** Live pre-copy, short stop, delta, restart. Returns the manifest written into `dest`. */ +function runPlainBackup( + ctx: BoxContext, + dest: string, + samCommit: string | null = null +): BackupManifest { + if (existsSync(dest) && readdirSync(dest).length > 0) { + throw new Error(`${dest} is not empty; choose a new backup directory`); + } + ensurePrivateDir(dest); + const bucketDir = join(dest, BUCKET_DIR); + + const liveDir = join(dest, LIVE_DIR); + const fullDir = join(dest, FULL_DIR); + + const precopyStart = ctx.now(); + ctx.log(`live pre-copy of ${ctx.box.CELLD_BUCKET} (celld keeps running)`); + // Best effort: a running node rewrites its lease, waker and capacity objects every few seconds, + // so `gcloud storage rsync` meets generations that vanished mid-copy (404) and exits non-zero. + // The pre-copy only shortens the downtime; the delta copy below, with celld stopped, is the one + // that must succeed, and it fails loudly if the store itself is unreachable. + // + // The pre-copy goes to its own directory. An aborted gcloud pass leaves state keyed by the + // destination path it was writing (resumable-download tracker files, `_.gstmp` temporaries), and + // a second rsync into the SAME paths tripped over it on the box: `[Errno 2] No such file or + // directory: /bucket/nodes/node_.json` for objects celld removed between the passes. + // Renaming the tree before the delta copy means gcloud has no state for any destination path it + // is about to write; only the bytes carry over. + try { + pullBucket(ctx, liveDir); + } catch (err) { + // Box round R17: the 404 on a node lease read like a defect. It is the expected case. + ctx.log( + 'live pre-copy incomplete (expected: celld rewrites its node lease, waker and capacity ' + + 'objects every few seconds, so a copy of the running bucket misses some, often with a ' + + `404); the delta copy with celld stopped copies them: ${firstLine(err)}` + ); + } + const precopyMs = ctx.now() - precopyStart; + if (existsSync(liveDir)) { + removeGcloudTemporaries(liveDir); + renameSync(liveDir, bucketDir); + } + + ctx.log('stopping celld for the delta copy'); + compose(ctx, ['stop', 'celld']); + const stoppedAt = ctx.now(); + let deltaCopyMs = 0; + let startedAt = stoppedAt; + try { + // With celld stopped the bucket is the consistent state. The mirror (with deletion) converges + // the local tree on exactly that: objects celld removed after the pre-copy are deleted here. + try { + pullBucket(ctx, bucketDir); + } catch (err) { + // Whatever the local tree holds, a copy into a directory no pass has touched cannot meet it. + // Costs a full copy of downtime, once, instead of leaving the operator without a backup. + ctx.log( + `delta copy failed, copying the whole bucket again with celld stopped: ${firstLine(err)}` + ); + rmSync(fullDir, { recursive: true, force: true }); + pullBucket(ctx, fullDir); + rmSync(bucketDir, { recursive: true, force: true }); + renameSync(fullDir, bucketDir); + } + deltaCopyMs = ctx.now() - stoppedAt; + cpSync(ctx.stateDir, join(dest, STATE_DIR), { + recursive: true, + preserveTimestamps: true, + filter: (src) => { + if (isRebuildableCachePath(ctx.stateDir, src)) return false; + if (!lstatSync(src).isSymbolicLink()) return true; + // prepareCelldProject regenerates source/migration links from the recorded SAM ref. + if (relative(ctx.stateDir, src).startsWith('project/')) return false; + throw new Error('Installation state contains an unsupported symlink'); + }, + }); + cpSync(ctx.envFile, join(dest, ENV_FILE), { preserveTimestamps: true }); + } finally { + ctx.log('starting celld'); + compose(ctx, ['start', 'celld']); + startedAt = ctx.now(); + } + + const manifest: BackupManifest = { + version: 1, + createdAt: new Date(stoppedAt).toISOString(), + bucket: ctx.box.CELLD_BUCKET ?? '', + samCommit, + precopyMs, + downtimeMs: startedAt - stoppedAt, + deltaCopyMs, + objectCount: countFiles(bucketDir), + }; + writeFileSync(join(dest, MANIFEST_NAME), `${JSON.stringify(manifest, null, 2)}\n`, { + mode: 0o600, + }); + // Listed for `pnpm selfhost:teardown`, which deletes a backup only with --delete-backups. + ctx.log( + `backup complete: ${manifest.objectCount} objects, celld down ${(manifest.downtimeMs / 1000).toFixed(1)} s -> ${dest}` + ); + return manifest; +} + +export function readManifest(dir: string): BackupManifest { + const path = join(dir, MANIFEST_NAME); + if (!existsSync(path)) throw new Error(`${dir} has no ${MANIFEST_NAME}; not a backup`); + let parsed: unknown; + try { + parsed = JSON.parse(readFileSync(path, 'utf8')); + } catch { + throw new Error('Invalid backup manifest'); + } + if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) + throw new Error('Invalid backup manifest'); + const item = parsed as Record; + if ( + item.version !== 1 || + typeof item.createdAt !== 'string' || + !/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/.test(item.createdAt) || + !Number.isFinite(Date.parse(item.createdAt)) || + !( + item.samCommit === null || + (typeof item.samCommit === 'string' && /^[0-9a-f]{40}$/.test(item.samCommit)) + ) || + typeof item.bucket !== 'string' || + ['precopyMs', 'downtimeMs', 'deltaCopyMs', 'objectCount'].some( + (name) => + typeof item[name] !== 'number' || !Number.isFinite(item[name]) || (item[name] as number) < 0 + ) + ) { + throw new Error('Invalid backup manifest'); + } + parseBucketUrl(item.bucket); + return parsed as BackupManifest; +} + +/** + * Restore `from` into an empty install: the target bucket (the CELLD_BUCKET in ctx.box) must be + * empty and the target `.state/` must have no platform keys. celld stays stopped; the caller + * prints how to start the stack. + */ +function runPlainRestore(ctx: BoxContext, from: string): BackupManifest { + const manifest = readManifest(from); + if (existsSync(ctx.stateDir) && readdirSync(ctx.stateDir).length > 0) { + throw new Error(`${ctx.stateDir} is not empty: restore only into an empty install`); + } + if (!bucketIsEmpty(ctx)) { + throw new Error(`${ctx.box.CELLD_BUCKET} is not empty: restore only into an empty bucket`); + } + // Harmless when the stack is not up; required so no celld writes while the bucket fills. + compose(ctx, ['stop', 'celld']); + ctx.log(`copying ${manifest.objectCount} objects into ${ctx.box.CELLD_BUCKET}`); + pushBucket(ctx, join(from, BUCKET_DIR)); + ensurePrivateDir(ctx.stateDir); + cpSync(join(from, STATE_DIR), ctx.stateDir, { recursive: true, preserveTimestamps: true }); + return manifest; +} + +/** Backups are operator-only: no secret-bearing reads or decryptions in CI. */ +export function backupKey(ctx: BoxContext): string { + assertOperatorExecution(); + if (!ctx.encryptionKeyFile) + throw new Error( + '--encryption-key-file (or SAM_BACKUP_KEY_FILE) is required; keep this 32-byte key apart from backups' + ); + readBackupKey(ctx.encryptionKeyFile).fill(0); + assertOperationPaths(ctx); + return ctx.encryptionKeyFile; +} + +export function backupScratch(): string { + const root = resolve(import.meta.dirname, '../../.tmp/selfhost-backups'); + let existing = root; + while (!existsSync(existing)) existing = dirname(existing); + if (realpathSync(existing) !== existing) throw new Error('Backup scratch must not use symlinks'); + ensurePrivateDir(root); + if (realpathSync(root) !== root) throw new Error('Backup scratch must not use symlinks'); + return mkdtempSync(join(root, 'operation-')); +} + +/** Persist only authenticated ciphertext. Temporary plaintext is private and always removed. */ +export function runBackup( + ctx: BoxContext, + dest: string, + samCommit: string | null = null +): BackupManifest { + assertOperatorExecution(); + const key = backupKey(ctx); + assertBackupOutside(ctx, dest); + if (existsSync(dest)) throw new Error('Backup destination already exists; choose a fresh path'); + const keyPath = resolve(key); + for (const dir of [ctx.stateDir, dest]) { + const rel = relative(resolve(dir), keyPath); + if (!rel.startsWith('..') && !rel.startsWith('/')) + throw new Error('Keep the backup key outside installation state and backups'); + } + ensurePrivateDir(dirname(resolve(dest))); + const temp = backupScratch(); + try { + const plain = join(temp, 'plain'); + const manifest = runPlainBackup(ctx, plain, samCommit); + encryptBackupTree(plain, dest, key); + recordBackup(ctx.stateDir, dest); + ctx.log(`encrypted backup complete -> ${dest}`); + return manifest; + } finally { + rmSync(temp, { recursive: true, force: true }); + } +} + +/** Authenticate every byte before any target bucket or compose operation. */ +export function runRestore(ctx: BoxContext, from: string): BackupManifest { + assertOperatorExecution(); + const key = backupKey(ctx); + assertBackupOutside(ctx, from); + const temp = backupScratch(); + try { + const plain = join(temp, 'plain'); + decryptBackupTree(from, plain, key); + const manifest = runPlainRestore(ctx, plain); + // Creation receipts belong to the source install, never to a fresh restore target. + rmSync(join(ctx.stateDir, 'created-resources.json'), { force: true }); + return manifest; + } finally { + rmSync(temp, { recursive: true, force: true }); + } +} + +export { runRollback } from './backup-recovery'; + +export { assertBackupOutside } from './backup-paths'; diff --git a/scripts/selfhost/backup-paths.ts b/scripts/selfhost/backup-paths.ts new file mode 100644 index 0000000000..080986ff68 --- /dev/null +++ b/scripts/selfhost/backup-paths.ts @@ -0,0 +1,51 @@ +/** Validate backup/restore filesystem boundaries before any mutation. */ +import { existsSync, lstatSync, realpathSync } from 'node:fs'; +import { dirname, resolve } from 'node:path'; +import { homedir } from 'node:os'; +import type { BoxContext } from './backup-lib'; +/** Refuse ambiguous paths before reading a bucket or changing any local/cloud state. */ +export function assertOperationPaths(ctx: BoxContext): void { + const paths = [ctx.stateDir, ctx.envFile, ctx.encryptionKeyFile] + .filter((p): p is string => Boolean(p)) + .map((p) => resolve(p)); + const canonical = (path: string): void => { + let current = path; + while (!existsSync(current)) { + const parent = dirname(current); + if (parent === current) throw new Error('Invalid operation path'); + current = parent; + } + if (realpathSync(current) !== current || lstatSync(current).isSymbolicLink()) + throw new Error('Operation paths must not use symlinks'); + }; + paths.forEach(canonical); + const state = resolve(ctx.stateDir); + const repo = resolve(import.meta.dirname, '../..'); + const scratch = resolve(repo, '.tmp/selfhost-backups'); + if ( + [repo, homedir(), scratch].some( + (protectedPath) => state === protectedPath || protectedPath.startsWith(`${state}/`) + ) || + state === '/' + ) { + throw new Error('Unsafe installation state path'); + } + for (let i = 0; i < paths.length; i++) + for (let j = i + 1; j < paths.length; j++) { + const left = paths[i] as string, + right = paths[j] as string; + if (left === right || left.startsWith(`${right}/`) || right.startsWith(`${left}/`)) + throw new Error('State, environment and backup key paths must not overlap'); + } +} + +/** Backup payload paths may never contain or live inside installation state/key paths. */ +export function assertBackupOutside(ctx: BoxContext, path: string): void { + const root = resolve(path); + for (const value of [ctx.stateDir, ctx.envFile, ctx.encryptionKeyFile]) { + if (!value) continue; + const other = resolve(value); + if (root === other || root.startsWith(`${other}/`) || other.startsWith(`${root}/`)) + throw new Error('Backup and installation paths must not overlap'); + } +} diff --git a/scripts/selfhost/backup-recovery.ts b/scripts/selfhost/backup-recovery.ts new file mode 100644 index 0000000000..efec38b3d0 --- /dev/null +++ b/scripts/selfhost/backup-recovery.ts @@ -0,0 +1,155 @@ +import { assertOperatorExecution } from './operator-only'; +/** Restore an upgrade's authenticated snapshot to the same owned installation. */ +import { cpSync, readFileSync, rmSync } from 'node:fs'; +import { join, resolve } from 'node:path'; +import { decryptBackupTree } from './backup-encryption'; +import { + type BoxContext, + assertBackupOutside, + backupKey, + backupScratch, + BUCKET_DIR, + STATE_DIR, + ENV_FILE, + readManifest, + check, + composeArgs, + parseBucketUrl, + bucketPath, + mcArgs, + mcEnv, +} from './backup-lib'; +import { readRecord } from '../../deploy/selfhost/created-resources.mjs'; +import { assertRollbackReady } from './upgrade-preflight'; +import { composeProjectFor } from './install-record'; +function compose(ctx: BoxContext, args: string[]): void { + check(ctx.run('docker', composeArgs(ctx, args)), 'rollback compose operation'); +} +function readIdentity(path: string): Record { + try { + const value: unknown = JSON.parse(readFileSync(path, 'utf8')); + if (typeof value !== 'object' || value === null || Array.isArray(value)) throw new Error(); + return value as Record; + } catch { + throw new Error('Cannot verify rollback installation identity'); + } +} +function assertStateReceipt(path: string, expected: string, id: unknown): void { + let record; + try { + record = readRecord(join(path, 'created-resources.json')); + } catch { + throw new Error('Cannot verify rollback state ownership'); + } + const states = record.resources.filter( + (r) => r.cloud === 'box' && r.kind === 'state-dir' && r.action === 'created' && !r.removedAt + ); + const installs = record.resources.filter( + (r) => r.cloud === 'box' && r.kind === 'installation' && r.action === 'created' && !r.removedAt + ); + if ( + states.length !== 1 || + states[0]?.name !== expected || + installs.length !== 1 || + installs[0]?.name !== id + ) { + throw new Error('Rollback state directory has no exact installation ownership receipt'); + } +} + +/** Drop only this compose project's disposable celld cache, never its fleet store. */ +function discardCelldCache(ctx: BoxContext): void { + const project = composeProjectFor(ctx.box, ctx.stateDir); + assertRollbackReady(ctx); + const name = `${project}_celld-data`; + const inspect = () => { + const result = check( + ctx.run('docker', ['volume', 'inspect', name]), + 'inspect celld cache ownership' + ); + let value: unknown; + try { + value = JSON.parse(result.stdout); + } catch { + throw new Error('Cannot verify celld cache ownership'); + } + if (!Array.isArray(value) || value.length !== 1) + throw new Error('Ambiguous celld cache ownership'); + const volume = value[0] as { Name?: unknown; Labels?: Record }; + if ( + volume?.Name !== name || + volume.Labels?.['com.docker.compose.project'] !== project || + volume.Labels?.['com.docker.compose.volume'] !== 'celld-data' + ) { + throw new Error('Foreign celld cache; refusing rollback cache removal'); + } + }; + inspect(); + compose(ctx, ['rm', '--stop', '--force', 'celld']); + inspect(); + check(ctx.run('docker', ['volume', 'rm', name]), 'remove owned celld cache'); +} + +/** + * Compensate only an upgrade of this exact install using its own pre-upgrade snapshot. + * The target is the original scoped bucket, never an arbitrary restore destination. + */ +export function runRollback(ctx: BoxContext, from: string): void { + assertOperatorExecution(); + const key = backupKey(ctx); + assertBackupOutside(ctx, from); + const temp = backupScratch(); + try { + const plain = join(temp, 'plain'); + decryptBackupTree(from, plain, key); + const manifest = readManifest(plain); + if (manifest.bucket !== ctx.box.CELLD_BUCKET) + throw new Error('Rollback snapshot belongs to a different bucket'); + const oldKeys = readIdentity(join(plain, STATE_DIR, 'platform-keys.json')); + const currentKeys = readIdentity(join(ctx.stateDir, 'platform-keys.json')); + if ( + typeof oldKeys.SAM_INSTALLATION_ID !== 'string' || + oldKeys.SAM_INSTALLATION_ID !== currentKeys.SAM_INSTALLATION_ID + ) { + throw new Error('Rollback snapshot belongs to a different installation'); + } + assertStateReceipt(join(plain, STATE_DIR), ctx.stateDir, oldKeys.SAM_INSTALLATION_ID); + assertStateReceipt(ctx.stateDir, ctx.stateDir, currentKeys.SAM_INSTALLATION_ID); + compose(ctx, ['stop', 'celld']); + discardCelldCache(ctx); + const url = parseBucketUrl(ctx.box.CELLD_BUCKET ?? ''); + const source = join(plain, BUCKET_DIR); + if (url.scheme === 'gs') { + check( + ctx.run('gcloud', [ + 'storage', + 'rsync', + '--recursive', + '--delete-unmatched-destination-objects', + source, + `gs://${bucketPath(url)}`, + ]), + 'restore pre-upgrade bucket' + ); + } else { + check( + ctx.run( + 'docker', + mcArgs( + ctx, + [`${resolve(source)}:/backup:ro`], + ['mirror', '--overwrite', '--remove', '--quiet', '/backup', `src/${bucketPath(url)}`] + ), + mcEnv(ctx) + ), + 'restore pre-upgrade bucket' + ); + } + // State may hold new generated files: replace it, retaining the source ownership receipts. + rmSync(ctx.stateDir, { recursive: true, force: true }); + cpSync(join(plain, STATE_DIR), ctx.stateDir, { recursive: true }); + cpSync(join(plain, ENV_FILE), ctx.envFile); + } finally { + rmSync(temp, { recursive: true, force: true }); + } +} diff --git a/scripts/selfhost/backup.test.ts b/scripts/selfhost/backup.test.ts new file mode 100644 index 0000000000..a9a4b1c989 --- /dev/null +++ b/scripts/selfhost/backup.test.ts @@ -0,0 +1,607 @@ +/** + * selfhost:backup / selfhost:restore orchestration (backup-lib.ts) against a fake object store + * that really copies files: an `mc mirror` or `gcloud storage rsync` invocation is interpreted + * and executed against a directory standing in for the bucket. The real-store version of the + * round trip is live/backup-restore.live.test.ts (pinned MinIO image, Docker). + */ +import { randomBytes } from 'node:crypto'; +import { + cpSync, + existsSync, + mkdirSync, + mkdtempSync, + readdirSync, + readFileSync, + rmSync, + statSync, + symlinkSync, + writeFileSync, +} from 'node:fs'; +import { basename, join, resolve } from 'node:path'; + +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; + +import { decryptBackupTree, encryptBackupTree } from './backup-encryption'; +import { + type BoxContext, + MANIFEST_NAME, + OBJECTSTORE_IMAGE, + runBackup, + runRestore, + type RunResult, + runRollback, +} from './backup-lib'; +import { recordInstall } from './install-record'; + +const PLATFORM_KEYS = JSON.stringify({ SAM_INSTALLATION_ID: 'test-installation' }); +const SECRET = 'store-secret-value-123'; +let root: string; +let calls: Array<{ command: string; args: string[]; env?: NodeJS.ProcessEnv }>; +let clock: number; +/** How many pulls after the live one fail (1: the delta copy; 2: the delta and the full copy). */ +let failDeltaCopy: number; +let failLiveCopy: boolean; +let cacheProof: 'owned' | 'foreign' | 'ambiguous' | 'changed'; +let cacheInspections: number; + +function tree(dir: string, base = dir): Record { + const out: Record = {}; + if (!existsSync(dir)) return out; + for (const entry of readdirSync(dir, { withFileTypes: true })) { + const path = join(dir, entry.name); + if (entry.isDirectory()) Object.assign(out, tree(path, base)); + else out[path.slice(base.length + 1)] = readFileSync(path, 'utf8'); + } + return out; +} + +/** Bucket "s3://fleet/celld" lives at /store/fleet/celld. */ +function storePath(spec: string): string { + return join(root, 'store', spec.replace(/^src\//, '')); +} + +function fakeRun(command: string, args: string[], env?: NodeJS.ProcessEnv): RunResult { + calls.push({ command, args, env }); + clock += 1000; // every command takes one second of fake time + const ok = { status: 0, stdout: '', stderr: '' }; + if (command === 'docker' && args[0] === 'compose') return ok; + if (command === 'docker' && args[0] === 'volume') { + if (args[1] === 'rm') return ok; + if (args[1] === 'inspect') { + cacheInspections += 1; + const name = args[2] ?? ''; + const project = name.replace(/_celld-data$/, ''); + const foreign = + cacheProof === 'foreign' || (cacheProof === 'changed' && cacheInspections > 1); + const volume = { + Name: name, + Labels: { + 'com.docker.compose.project': foreign ? 'another-installation' : project, + 'com.docker.compose.volume': 'celld-data', + }, + }; + return { + ...ok, + stdout: JSON.stringify(cacheProof === 'ambiguous' ? [volume, volume] : [volume]), + }; + } + } + + if (command === 'gcloud' && args[0] === 'storage' && args[1] === 'rsync') { + const [src, dst] = args.slice(-2) as [string, string]; + const from = src.startsWith('gs://') ? storePath(src.slice(5)) : src; + const to = dst.startsWith('gs://') ? storePath(dst.slice(5)) : dst; + if (args.includes('--delete-unmatched-destination-objects')) + rmSync(to, { recursive: true, force: true }); + mkdirSync(to, { recursive: true }); + cpSync(from, to, { recursive: true }); + return ok; + } + + if (command === 'docker' && args[0] === 'run') { + const mount = args[args.indexOf('-v') + 1] ?? ''; + const hostDir = mount.split(':')[0] as string; + const mc = args.slice(args.indexOf(OBJECTSTORE_IMAGE) + 1); + if (mc[0] === 'ls') { + const listed = Object.keys(tree(storePath(mc[2] as string))); + return { ...ok, stdout: listed.map((k) => `[date] 1B ${k}`).join('\n') }; + } + if (mc[0] === 'mirror') { + const [src, dst] = mc.slice(-2) as [string, string]; + if (src.startsWith('src/')) { + // bucket -> backup; the second (delta) pull can be made to fail + const pulls = calls.filter((c) => c.args.includes('/backup') && c.args[0] === 'run'); + if (pulls.length >= 2 && pulls.length <= 1 + failDeltaCopy) + return { status: 1, stdout: '', stderr: 'boom' }; + if (failLiveCopy && pulls.length === 1) { + // a running node rewrote an object mid-copy: part of the bucket arrives, then 404 + mkdirSync(join(hostDir, 'd1'), { recursive: true }); + writeFileSync(join(hostDir, 'd1/main.ltx'), 'stale'); + return { + status: 1, + stdout: '', + stderr: 'ERROR: gs://b/celld%2Fwake%2Fwaker.json#1 not found: 404.', + }; + } + rmSync(hostDir, { recursive: true, force: true }); + cpSync(storePath(src), hostDir, { recursive: true }); + } else { + if (mc.includes('--remove')) rmSync(storePath(dst), { recursive: true, force: true }); + mkdirSync(storePath(dst), { recursive: true }); + cpSync(hostDir, storePath(dst), { recursive: true }); + } + return ok; + } + } + throw new Error(`unexpected command ${command} ${args.join(' ')}`); +} + +function ctx(bucket: string, stateDir: string): BoxContext { + return { + box: { + CELLD_BUCKET: bucket, + R2_S3_REGION: 'us-east-1', + S3_ENDPOINT: 'http://127.0.0.1:9000', + AWS_ACCESS_KEY_ID: 'sam-objectstore', + AWS_SECRET_ACCESS_KEY: SECRET, + }, + envFile: join(root, 'box.env'), + stateDir, + encryptionKeyFile: join(root, 'backup-key'), + composeFiles: ['/x/docker-compose.yml'], + run: fakeRun, + now: () => clock, + log: () => undefined, + }; +} + +beforeEach(() => { + for (const name of Object.keys(process.env)) { + if (name === 'CI' || name === 'GITHUB_ACTIONS' || name.startsWith('RUNNER_')) + vi.stubEnv(name, undefined); + } + mkdirSync(resolve('.tmp'), { recursive: true }); + root = mkdtempSync(resolve('.tmp/sam-backup-')); + writeFileSync(join(root, 'backup-key'), randomBytes(32), { mode: 0o600 }); + calls = []; + clock = 1_000_000; + failDeltaCopy = 0; + failLiveCopy = false; + cacheProof = 'owned'; + cacheInspections = 0; + const fleet = join(root, 'store/fleet/celld'); + mkdirSync(join(fleet, 'd1'), { recursive: true }); + writeFileSync(join(fleet, 'd1/main.ltx'), 'rows'); + writeFileSync(join(fleet, 'current.json'), '{"v":3}'); + mkdirSync(join(root, 'state')); + writeFileSync(join(root, 'state/platform-keys.json'), PLATFORM_KEYS); + writeFileSync(join(root, 'box.env'), `AWS_SECRET_ACCESS_KEY=${SECRET}\n`, { mode: 0o600 }); +}); + +afterEach(() => { + vi.unstubAllEnvs(); + rmSync(root, { recursive: true, force: true }); +}); + +function inspectBackup(dest: string, part: string): Record { + const plain = join(root, 'inspection'); + decryptBackupTree(dest, plain, join(root, 'backup-key')); + try { + return tree(join(plain, part)); + } finally { + rmSync(plain, { recursive: true, force: true }); + } +} + +describe('runBackup', () => { + it('pre-copies live, stops celld only for the delta, restarts it, and records the downtime', () => { + const dest = join(root, 'backups/b1'); + const manifest = runBackup(ctx('s3://fleet/celld', join(root, 'state')), dest, 'a'.repeat(40)); + + const sequence = calls.map((c) => + c.args[0] === 'compose' + ? `compose ${c.args.slice(-2).join(' ')}` + : `${c.command} ${c.args[0]}` + ); + expect(sequence).toEqual([ + 'docker run', // live pre-copy + 'compose stop celld', + 'docker run', // delta + 'compose start celld', + ]); + // stop at t+2s, delta done t+3s, start at t+4s: 2 s of downtime on the fake clock. + expect(manifest).toMatchObject({ downtimeMs: 2000, deltaCopyMs: 1000, objectCount: 2 }); + expect(inspectBackup(dest, 'bucket')).toEqual({ + 'd1/main.ltx': 'rows', + 'current.json': '{"v":3}', + }); + expect(inspectBackup(dest, 'state')).toEqual({ 'platform-keys.json': PLATFORM_KEYS }); + expect(statSync(dest).mode & 0o777).toBe(0o700); + + // The store credential travels in the environment only, and never into the manifest. + for (const call of calls) expect(call.args.join(' ')).not.toContain(SECRET); + expect(calls[0]!.env?.MC_HOST_src).toContain(SECRET); + expect(readFileSync(join(dest, MANIFEST_NAME), 'utf8')).not.toContain(SECRET); + }); + + it('leaves the rebuildable vm-agent build cache out of the state copy', () => { + mkdirSync(join(root, 'state/go-cache/ab'), { recursive: true }); + writeFileSync(join(root, 'state/go-cache/ab/obj-d'), 'compiled'); + mkdirSync(join(root, 'state/project'), { recursive: true }); + writeFileSync(join(root, 'state/project/wrangler.json'), '{}'); + // A file whose name only starts like the cache is not the cache. + writeFileSync(join(root, 'state/go-cache-notes'), 'kept'); + const dest = join(root, 'backups/b-cache'); + runBackup(ctx('s3://fleet/celld', join(root, 'state')), dest, 'a'.repeat(40)); + expect(inspectBackup(dest, 'state')).toEqual({ + 'platform-keys.json': PLATFORM_KEYS, + 'project/wrangler.json': '{}', + 'go-cache-notes': 'kept', + }); + }); + + it('finishes the backup when the live pre-copy fails because objects changed mid-copy', () => { + failLiveCopy = true; + const logs: string[] = []; + const dest = join(root, 'backups/b3'); + const manifest = runBackup( + { ...ctx('s3://fleet/celld', join(root, 'state')), log: (m) => logs.push(m) }, + dest + ); + expect(manifest.objectCount).toBe(2); + // the delta copy with celld stopped replaced the stale partial copy + expect(inspectBackup(dest, 'bucket')).toEqual({ + 'd1/main.ltx': 'rows', + 'current.json': '{"v":3}', + }); + expect(logs.some((l) => l.startsWith('live pre-copy incomplete'))).toBe(true); + expect(calls.at(-1)!.args.slice(-2)).toEqual(['start', 'celld']); + }); + + it('falls back to a whole copy into an untouched directory when the delta copy fails', () => { + failDeltaCopy = 1; + const logs: string[] = []; + const dest = join(root, 'backups/b4'); + const manifest = runBackup( + { ...ctx('s3://fleet/celld', join(root, 'state')), log: (m) => logs.push(m) }, + dest + ); + const pulls = calls + .filter((c) => c.args[0] === 'run') + .map((c) => c.args[c.args.indexOf('-v') + 1]); + expect(pulls.map((mount) => basename((mount ?? '').split(':')[0] ?? ''))).toEqual([ + '.bucket-live', + 'bucket', + '.bucket-full', + ]); + expect(logs.some((l) => l.startsWith('delta copy failed'))).toBe(true); + expect(manifest.objectCount).toBe(2); + expect(readdirSync(dest).sort()).toEqual([ + '.sam-backup-manifest', + 'backup-manifest.json', + 'bucket', + 'env', + 'state', + ]); + expect(inspectBackup(dest, 'bucket')).toEqual({ + 'd1/main.ltx': 'rows', + 'current.json': '{"v":3}', + }); + // celld stays stopped through both copies, and the downtime records both. + expect(calls.map((c) => c.args.at(-1)).filter((a) => a === 'celld')).toHaveLength(2); + expect(manifest.downtimeMs).toBe(3000); // stop t+2s, failed delta t+3s, whole copy t+4s, start t+5s + }); + + it('restarts celld when the delta copy and the whole copy both fail', () => { + failDeltaCopy = 2; + expect(() => + runBackup(ctx('s3://fleet/celld', join(root, 'state')), join(root, 'backups/b2')) + ).toThrow(/mc mirror/); + expect(calls.at(-1)!.args.slice(-2)).toEqual(['start', 'celld']); + }); + + it('refuses a non-empty destination', () => { + mkdirSync(join(root, 'used')); + writeFileSync(join(root, 'used/x'), '1'); + expect(() => + runBackup(ctx('s3://fleet/celld', join(root, 'state')), join(root, 'used')) + ).toThrow(/already exists/); + expect(calls).toHaveLength(0); + }); + + it('uses gcloud storage rsync for a gs:// bucket', () => { + const run = (command: string, args: string[]) => { + calls.push({ command, args }); + return { status: 0, stdout: '', stderr: '' }; + }; + runBackup({ ...ctx('gs://my-bucket/celld', join(root, 'state')), run }, join(root, 'b3')); + // live pass into its own directory; the delta pass into `bucket`, a path gcloud never wrote + expect(basename(calls[2]?.args.at(-1) ?? '')).toBe('bucket'); + expect(calls[0]).toMatchObject({ + command: 'gcloud', + args: [ + 'storage', + 'rsync', + '--recursive', + '--delete-unmatched-destination-objects', + 'gs://my-bucket/celld', + expect.stringMatching(/\/\.bucket-live$/), + ], + }); + }); +}); + +describe('runRestore', () => { + it.each(['createdAt', 'samCommit', 'objectCount', 'downtimeMs'] as const)( + 'refuses authenticated invalid %s manifest metadata before cloud operations', + (field) => { + const context = ctx('s3://fleet/celld', join(root, 'state')); + const source = join(root, 'metadata-source'); + runBackup(context, source); + const plain = join(root, 'metadata-plain'); + const altered = join(root, 'metadata-altered'); + decryptBackupTree(source, plain, context.encryptionKeyFile!); + try { + const manifest = JSON.parse(readFileSync(join(plain, MANIFEST_NAME), 'utf8')) as Record< + string, + unknown + >; + manifest[field] = + field === 'createdAt' || field === 'samCommit' + ? 'fixture-sensitive-metadata\nunsafe-output' + : -1; + writeFileSync(join(plain, MANIFEST_NAME), JSON.stringify(manifest)); + encryptBackupTree(plain, altered, context.encryptionKeyFile!); + } finally { + rmSync(plain, { recursive: true, force: true }); + } + calls = []; + let error: unknown; + try { + runRestore(ctx('s3://fresh/celld', join(root, 'new-state')), altered); + } catch (caught) { + error = caught; + } + expect(error).toBeInstanceOf(Error); + expect(String(error)).not.toContain('fixture-sensitive-metadata'); + expect(calls).toHaveLength(0); + expect(existsSync(join(root, 'new-state'))).toBe(false); + } + ); + + it('refuses existing state without platform keys instead of overwriting its files', () => { + const dest = join(root, 'backup-existing-state'); + runBackup(ctx('s3://fleet/celld', join(root, 'state')), dest); + const state = join(root, 'existing-state'); + mkdirSync(state); + writeFileSync(join(state, 'operator-file'), 'keep-this-file'); + calls = []; + expect(() => runRestore(ctx('s3://fresh/celld', state), dest)).toThrow(/not empty/); + expect(calls).toHaveLength(0); + expect(tree(state)).toEqual({ 'operator-file': 'keep-this-file' }); + }); + + it('authenticates all backup ciphertext before any store query or compose operation', () => { + const dest = join(root, 'backup-auth'); + runBackup(ctx('s3://fleet/celld', join(root, 'state')), dest); + writeFileSync(join(dest, 'env'), 'damaged ciphertext'); + calls = []; + expect(() => runRestore(ctx('s3://fresh/celld', join(root, 'new-state')), dest)).toThrow( + 'authentication failed' + ); + expect(calls).toHaveLength(0); + expect(existsSync(join(root, 'new-state'))).toBe(false); + }); + + it('restores bucket and state into an empty install (round trip)', () => { + const dest = join(root, 'backups/b1'); + runBackup(ctx('s3://fleet/celld', join(root, 'state')), dest); + + const newState = join(root, 'new-state'); + runRestore(ctx('s3://fresh/celld', newState), dest); + + expect(tree(join(root, 'store/fresh/celld'))).toEqual(tree(join(root, 'store/fleet/celld'))); + expect(tree(newState)).toEqual({ 'platform-keys.json': PLATFORM_KEYS }); + }); + + it('refuses a bucket that already holds objects', () => { + const dest = join(root, 'backups/b1'); + runBackup(ctx('s3://fleet/celld', join(root, 'state')), dest); + calls = []; + expect(() => runRestore(ctx('s3://fleet/celld', join(root, 'new-state')), dest)).toThrow( + /not empty/ + ); + expect(calls.some((c) => c.args.includes('stop'))).toBe(false); + }); + + it('refuses a state directory that already has platform keys', () => { + const dest = join(root, 'backups/b1'); + runBackup(ctx('s3://fleet/celld', join(root, 'state')), dest); + expect(() => runRestore(ctx('s3://fresh/celld', join(root, 'state')), dest)).toThrow( + /not empty/ + ); + }); +}); + +describe('runRollback', () => { + beforeEach(() => { + const context = ctx('gs://fleet/celld', join(root, 'state')); + recordInstall(context.stateDir, context.envFile, context.box, 'test-installation'); + }); + + it.each([ + ['current', 'missing'], + ['current', 'foreign'], + ['current', 'ambiguous'], + ['snapshot', 'missing'], + ['snapshot', 'foreign'], + ['snapshot', 'ambiguous'], + ] as const)('refuses %s %s state ownership receipts before mutations', (location, defect) => { + const context = ctx('gs://fleet/celld', join(root, 'state')); + const original = join(root, 'receipt-snapshot'); + runBackup(context, original); + let snapshot = original; + let state = context.stateDir; + const plain = join(root, 'receipt-plain'); + if (location === 'snapshot') { + decryptBackupTree(original, plain, context.encryptionKeyFile!); + state = join(plain, 'state'); + } + try { + const file = join(state, 'created-resources.json'); + const receipt = JSON.parse(readFileSync(file, 'utf8')) as { + resources: Array<{ kind: string; name: string }>; + }; + const index = receipt.resources.findIndex((r) => r.kind === 'state-dir'); + const entry = receipt.resources[index]!; + if (defect === 'missing') receipt.resources.splice(index, 1); + else if (defect === 'foreign') entry.name = join(root, 'foreign-state'); + else receipt.resources.push({ ...entry, name: join(root, 'another-state') }); + writeFileSync(file, JSON.stringify(receipt)); + if (location === 'snapshot') { + snapshot = join(root, 'altered-receipt-snapshot'); + encryptBackupTree(plain, snapshot, context.encryptionKeyFile!); + } + } finally { + if (location === 'snapshot') rmSync(plain, { recursive: true, force: true }); + } + calls = []; + expect(() => runRollback(context, snapshot)).toThrow(/ownership/); + expect(calls).toHaveLength(0); + }); + + it.each(['current', 'snapshot'])( + 'sanitizes malformed %s platform key JSON before any runner call', + (location) => { + const context = ctx('gs://fleet/celld', join(root, 'state')); + const snapshot = join(root, 'malformed-identity-snapshot'); + const fragment = 'fixture-token-that-must-never-appear'; + if (location === 'snapshot') + writeFileSync( + join(context.stateDir, 'platform-keys.json'), + `{"ENCRYPTION_KEY":"${fragment}` + ); + runBackup(context, snapshot); + writeFileSync( + join(context.stateDir, 'platform-keys.json'), + location === 'current' ? `{"ENCRYPTION_KEY":"${fragment}` : PLATFORM_KEYS + ); + calls = []; + let error: unknown; + try { + runRollback(context, snapshot); + } catch (caught) { + error = caught; + } + expect(error).toBeInstanceOf(Error); + expect((error as Error).message).toContain('Cannot verify rollback installation identity'); + expect(String(error)).not.toContain(fragment); + expect(calls).toHaveLength(0); + } + ); + + it.each(['foreign', 'ambiguous', 'changed'] as const)( + 'refuses %s cache ownership before deleting volumes or copying the rollback bucket', + (proof) => { + const dest = join(root, 'cache-snapshot'); + const context = ctx('gs://fleet/celld', join(root, 'state')); + runBackup(context, dest); + calls = []; + cacheProof = proof; + expect(() => runRollback(context, dest)).toThrow(/cache ownership|Foreign celld cache/); + expect(cacheInspections).toBe(proof === 'changed' ? 2 : 1); + expect( + calls.some((c) => c.command === 'docker' && c.args[0] === 'volume' && c.args[1] === 'rm') + ).toBe(false); + expect(calls.some((c) => c.command === 'gcloud')).toBe(false); + expect(readFileSync(join(root, 'state/platform-keys.json'), 'utf8')).toBe(PLATFORM_KEYS); + } + ); + + it.each(['bucket', 'installation'])( + 'refuses rollback to a different %s before mutating resources', + (kind) => { + const dest = join(root, 'snapshot'); + runBackup(ctx('gs://fleet/celld', join(root, 'state')), dest); + if (kind === 'installation') + writeFileSync( + join(root, 'state/platform-keys.json'), + JSON.stringify({ SAM_INSTALLATION_ID: 'different-installation' }) + ); + calls = []; + const target = ctx( + kind === 'bucket' ? 'gs://other/celld' : 'gs://fleet/celld', + join(root, 'state') + ); + expect(() => runRollback(target, dest)).toThrow(`different ${kind}`); + expect(calls).toHaveLength(0); + } + ); + + it('restores the exact pre-upgrade GCS tree, removing newly written objects and state', () => { + const dest = join(root, 'rollback-snapshot'); + const context = ctx('gs://fleet/celld', join(root, 'state')); + runBackup(context, dest); + const expectedState = inspectBackup(dest, 'state'); + writeFileSync(join(root, 'store/fleet/celld/current.json'), 'upgraded'); + writeFileSync(join(root, 'store/fleet/celld/new-object'), 'introduced during failed upgrade'); + writeFileSync(join(root, 'state/new-state'), 'new state'); + writeFileSync(join(root, 'box.env'), 'changed after backup'); + calls = []; + runRollback(context, dest); + expect(tree(join(root, 'store/fleet/celld'))).toEqual({ + 'current.json': '{"v":3}', + 'd1/main.ltx': 'rows', + }); + expect(tree(join(root, 'state'))).toEqual(expectedState); + expect(readFileSync(join(root, 'box.env'), 'utf8')).toBe(`AWS_SECRET_ACCESS_KEY=${SECRET}\n`); + expect(calls.find((c) => c.command === 'gcloud')?.args).toContain( + '--delete-unmatched-destination-objects' + ); + expect(calls.some((c) => c.args.includes('stop'))).toBe(true); + expect(cacheInspections).toBe(2); + const volumeDelete = calls.find( + (c) => c.command === 'docker' && c.args[0] === 'volume' && c.args[1] === 'rm' + ); + expect(volumeDelete?.args[2]).toMatch(/^sam-selfhost-[a-f0-9]{12}_celld-data$/); + expect( + calls.find((c) => c.command === 'docker' && c.args.includes('--force'))?.args.slice(-4) + ).toEqual(['rm', '--stop', '--force', 'celld']); + }); +}); + +describe('operation path boundaries', () => { + it.each(['backup', 'restore', 'rollback'] as const)( + 'rejects symlink state/env, keys under state and backup/state overlap for %s before any runner call', + (operation) => { + const context = ctx('gs://fleet/celld', join(root, 'state')); + const snapshot = join(root, 'path-snapshot'); + runBackup(context, snapshot); + const invoke = (candidate: BoxContext, path = snapshot): void => { + if (operation === 'backup') + runBackup(candidate, path === snapshot ? join(root, 'new-backup') : path); + else if (operation === 'restore') runRestore(candidate, path); + else runRollback(candidate, path); + }; + symlinkSync(context.stateDir, join(root, 'linked-state')); + symlinkSync(context.envFile, join(root, 'linked-env')); + const nestedKey = join(context.stateDir, 'backup-key'); + writeFileSync(nestedKey, readFileSync(join(root, 'backup-key')), { mode: 0o600 }); + for (const candidate of [ + { ...context, stateDir: join(root, 'linked-state') }, + { ...context, envFile: join(root, 'linked-env') }, + { ...context, encryptionKeyFile: nestedKey }, + ]) { + calls = []; + expect(() => invoke(candidate)).toThrow(/symlinks|overlap/); + expect(calls).toHaveLength(0); + } + calls = []; + expect(() => invoke(context, join(context.stateDir, 'snapshot'))).toThrow(/overlap/); + expect(calls).toHaveLength(0); + expect(readFileSync(join(context.stateDir, 'platform-keys.json'), 'utf8')).toBe( + PLATFORM_KEYS + ); + } + ); +}); diff --git a/scripts/selfhost/backup.ts b/scripts/selfhost/backup.ts new file mode 100644 index 0000000000..02b1e8943d --- /dev/null +++ b/scripts/selfhost/backup.ts @@ -0,0 +1,30 @@ +/** + * `pnpm selfhost:backup [--to ] [--box-env ] [--state-dir ]` + * + * Consistent copy of the fleet bucket plus `.state/` and `.env` (backup-lib.ts). celld is + * stopped only for the delta copy; the downtime is printed and kept in the backup's manifest. + * Default destination: deploy/selfhost/backups/ (gitignored, mode 0700). + */ +import { join, resolve } from 'node:path'; +import { parseArgs } from 'node:util'; + +import { gitCommit, loadBox, SELFHOST_DIR } from './backup-cli'; +import { runBackup } from './backup-lib'; + +const { values } = parseArgs({ + options: { + to: { type: 'string' }, + 'encryption-key-file': { type: 'string' }, + 'box-env': { type: 'string' }, + 'state-dir': { type: 'string' }, + }, +}); +const ctx = loadBox( + resolve(values['box-env'] ?? join(SELFHOST_DIR, '.env')), + values['state-dir'], + values['encryption-key-file'] +); +const stamp = new Date().toISOString().replace(/[:.]/g, '-'); +const dest = resolve(values.to ?? join(SELFHOST_DIR, 'backups', stamp)); +runBackup(ctx, dest, gitCommit()); +process.stdout.write(`${dest}\n`); diff --git a/scripts/selfhost/bucket-objects.ts b/scripts/selfhost/bucket-objects.ts new file mode 100644 index 0000000000..b8888835a9 --- /dev/null +++ b/scripts/selfhost/bucket-objects.ts @@ -0,0 +1,91 @@ +/** + * Object-level access to the fleet bucket for the plaintext listing and purge (plaintext-scan.ts): + * list, read and delete objects under celld's key prefix, with the tool the box already uses for + * each store (backup-lib.ts): `gcloud storage` for gs://, `mc` from the pinned objectstore image + * for s3://. Credentials travel in the environment, never on a command line. + */ +import { type BoxContext, bucketPath, check, mcArgs, mcEnv, parseBucketUrl } from './backup-lib'; + +export interface BucketObject { + /** Key relative to the bucket prefix (`deploy/workspaces-api//manifest.json`). */ + key: string; + size: number; + lastModified: string; +} + +function base(ctx: BoxContext): { scheme: 'gs' | 's3'; root: string } { + const url = parseBucketUrl(ctx.box.CELLD_BUCKET ?? ''); + return { + scheme: url.scheme, + root: url.scheme === 'gs' ? `gs://${bucketPath(url)}` : `src/${bucketPath(url)}`, + }; +} + +/** Every object whose key starts with `prefix` (e.g. `deploy/`). */ +export function listObjects(ctx: BoxContext, prefix: string): BucketObject[] { + const { scheme, root } = base(ctx); + if (scheme === 'gs') { + const result = ctx.run('gcloud', ['storage', 'ls', '--long', `${root}/${prefix}**`]); + if (result.status !== 0 && /matched no objects/i.test(result.stderr)) return []; + check(result, 'gcloud storage ls'); + const objects: BucketObject[] = []; + for (const line of result.stdout.split('\n')) { + const match = /^\s*(\d+)\s+(\S+)\s+(gs:\/\/\S+)\s*$/.exec(line); + if (!match?.[3]?.startsWith(`${root}/`)) continue; + objects.push({ + key: match[3].slice(root.length + 1), + size: Number(match[1]), + lastModified: match[2] ?? '', + }); + } + return objects; + } + const result = check( + ctx.run( + 'docker', + mcArgs(ctx, [], ['ls', '--recursive', '--json', `${root}/${prefix}`]), + mcEnv(ctx) + ), + 'mc ls' + ); + const objects: BucketObject[] = []; + for (const line of result.stdout.split('\n')) { + if (!line.trim()) continue; + const entry = JSON.parse(line) as unknown; + if (typeof entry !== 'object' || entry === null) continue; + const record = entry as Record; + if (record.type !== 'file' || typeof record.key !== 'string') continue; + objects.push({ + key: `${prefix}${record.key}`, + size: Number(record.size ?? 0), + lastModified: String(record.lastModified ?? ''), + }); + } + return objects; +} + +export function readObject(ctx: BoxContext, key: string): string { + const { scheme, root } = base(ctx); + if (scheme === 'gs') { + return check( + ctx.run('gcloud', ['storage', 'cat', `${root}/${key}`]), + `gcloud storage cat ${key}` + ).stdout; + } + return check( + ctx.run('docker', mcArgs(ctx, [], ['cat', `${root}/${key}`]), mcEnv(ctx)), + `mc cat ${key}` + ).stdout; +} + +/** Deletes exactly these objects (no prefix or wildcard deletion). */ +export function deleteObjects(ctx: BoxContext, keys: readonly string[]): void { + if (keys.length === 0) return; + const { scheme, root } = base(ctx); + const urls = keys.map((key) => `${root}/${key}`); + if (scheme === 'gs') { + check(ctx.run('gcloud', ['storage', 'rm', ...urls]), 'gcloud storage rm'); + return; + } + check(ctx.run('docker', mcArgs(ctx, [], ['rm', ...urls]), mcEnv(ctx)), 'mc rm'); +} diff --git a/scripts/selfhost/created-resources.test.ts b/scripts/selfhost/created-resources.test.ts new file mode 100644 index 0000000000..d29040af98 --- /dev/null +++ b/scripts/selfhost/created-resources.test.ts @@ -0,0 +1,88 @@ +/** + * deploy/selfhost/created-resources.mjs: what the record says after a resource a teardown removed + * is recorded again (security review of F3, M4: a re-added grant must not read as removed). + */ +import { mkdtempSync, rmSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; + +import { afterEach, beforeEach, describe, expect, it } from 'vitest'; + +import { addResource, markRemoved, readRecord } from '../../deploy/selfhost/created-resources.mjs'; + +let dir: string; +let file: string; +const GRANT = 'projects/p/locations/global/keyRings/r/cryptoKeys/k#roles/x#serviceAccount:box@p'; +const entry = (action: 'created' | 'reused') => ({ + cloud: 'gcp', + kind: 'iam-binding', + name: GRANT, + attributes: { project: 'p' }, + createdBy: 'gcp-bootstrap', + action, +}); +const only = () => readRecord(file).resources[0]; + +beforeEach(() => { + dir = mkdtempSync(join(tmpdir(), 'created-resources-')); + file = join(dir, 'created-resources.json'); +}); +afterEach(() => rmSync(dir, { recursive: true, force: true })); + +describe('addResource after a teardown removed the entry', () => { + it('recorded again as reused: exists again, as reused (a teardown lists it, never deletes it)', () => { + addResource(file, entry('created')); + markRemoved(file, 'gcp', 'iam-binding', GRANT); + addResource(file, entry('reused')); + expect(only()).toMatchObject({ action: 'reused' }); + expect(only()).not.toHaveProperty('removedAt'); + }); + + it('recorded again as created: exists again, as created', () => { + addResource(file, entry('created')); + markRemoved(file, 'gcp', 'iam-binding', GRANT); + addResource(file, entry('created')); + expect(only()).toMatchObject({ action: 'created' }); + expect(only()).not.toHaveProperty('removedAt'); + }); + + it('control: a live created entry never becomes reused', () => { + addResource(file, entry('created')); + addResource(file, entry('reused')); + expect(only()).toMatchObject({ action: 'created' }); + }); +}); + +it('a replacement found at a created name is reused, not adopted', () => { + addResource(file, { ...entry('created'), attributes: { identity: 'one' } }); + addResource(file, { ...entry('reused'), attributes: { identity: 'two' } }); + expect(only()).toMatchObject({ action: 'reused', attributes: { identity: 'two' } }); +}); +it('refuses duplicate receipts before any destructive decisions', () => { + writeFileSync( + file, + JSON.stringify({ + format: 'sam-created-resources/1', + resources: [entry('created'), entry('created')], + }) + ); + expect(() => readRecord(file)).toThrow('duplicate'); +}); +it('refuses malformed receipts', () => { + writeFileSync(file, JSON.stringify({ format: 'sam-created-resources/1', resources: [null] })); + expect(() => readRecord(file)).toThrow('invalid'); +}); + +it('never rewrites live creation proof for a second installation', () => { + addResource(file, { + ...entry('created'), + attributes: { identity: 'one', installation: 'first', environment: 'selfhost' }, + }); + expect(() => + addResource(file, { + ...entry('reused'), + attributes: { identity: 'one', installation: 'other', environment: 'selfhost' }, + }) + ).toThrow('ownership scope changed'); + expect(only().attributes?.installation).toBe('first'); +}); diff --git a/scripts/selfhost/deploy.ts b/scripts/selfhost/deploy.ts index 56210ac57d..a4a5ec3e34 100644 --- a/scripts/selfhost/deploy.ts +++ b/scripts/selfhost/deploy.ts @@ -93,6 +93,7 @@ import { type PlatformKeysMode, type PlatformKeysResult, } from './platform-keys.js'; +import { composeProjectFor, recordInstall } from './install-record.js'; import { assertPrivateFile, ensurePrivateDir, readSecretsFile } from './secret-files.js'; import { buildVmAgentBinaries, @@ -162,6 +163,7 @@ function buildApiDependencies(): void { } interface DeployInputs { + envFile: string; box: Record; stateDir: string; secretsPath: string; @@ -207,6 +209,7 @@ function readDeployInputs(): DeployInputs { if (!baseDomain) throw new Error(`${envFile}: SAM_DOMAIN is required`); if (!box.CELLD_BUCKET) throw new Error(`${envFile}: CELLD_BUCKET is required`); return { + envFile, box, stateDir, secretsPath, @@ -254,6 +257,10 @@ function prepareBoxState(inputs: DeployInputs): BoxState { ); return { keys, tunnelSettings, collectorPasswordPath, collectorPassword: null }; } + recordInstall(stateDir, inputs.envFile, box, keys.SAM_INSTALLATION_ID); + log( + `Compose project: ${composeProjectFor(box, stateDir)} (set COMPOSE_PROJECT_NAME to this name before starting Docker Compose)` + ); syncGatewayEnv( join(stateDir, 'gateway.env'), renderGatewayEnv(keys.REVERSE_TUNNEL_GATEWAY_SECRET, tunnelSettings), diff --git a/scripts/selfhost/gcp-bootstrap.test.ts b/scripts/selfhost/gcp-bootstrap.test.ts index 1890213b07..d56429d34e 100644 --- a/scripts/selfhost/gcp-bootstrap.test.ts +++ b/scripts/selfhost/gcp-bootstrap.test.ts @@ -603,3 +603,77 @@ describe('gcp-bootstrap.sh against the guided setup (drift)', () => { for (const role of Object.keys(OMITTED_ROLES)) expect(script, role).toContain(role); }); }); + +describe('bootstrap creation receipts', () => { + const args = () => [ + '--project', + 'sam-vm-test', + '--api-url', + ISSUER, + '--installation-id', + 'a'.repeat(32), + '--state-dir', + state, + ]; + const receipts = () => + JSON.parse(readFileSync(join(state, 'created-resources.json'), 'utf8')).resources as Array<{ + kind: string; + action: string; + attributes: Record; + }>; + it('records actual new resource identities and preserves the proof on repeat', () => { + expect(run(args()).status).toBe(0); + const before = receipts(); + expect(before).toHaveLength(5); + expect( + before.every( + (r) => + r.action === 'created' && + !!r.attributes.identity && + r.attributes.installation === 'a'.repeat(32) + ) + ).toBe(true); + expect(run(args()).status).toBe(0); + expect(receipts().every((r) => r.action === 'created')).toBe(true); + }); + it('records preexisting resources and grants as reused', () => { + expect(run(['--project', 'sam-vm-test', '--api-url', ISSUER]).status).toBe(0); + expect(run(args()).status).toBe(0); + expect(receipts().every((r) => r.action === 'reused')).toBe(true); + }); +}); + +it('creates absent firewall rules with identity receipts without adopting an existing shared rule', () => { + const args = [ + '--project', + 'sam-vm-test', + '--api-url', + ISSUER, + '--installation-id', + 'a'.repeat(32), + '--state-dir', + state, + '--create-firewalls', + '--agent-source-ranges', + '10.0.0.0/24', + ]; + const first = run(args); + expect(first.status, first.stderr).toBe(0); + const receipts = JSON.parse(readFileSync(join(state, 'created-resources.json'), 'utf8')) + .resources as Array<{ kind: string; name: string; attributes: Record }>; + const rules = receipts.filter((r) => r.kind === 'firewall-rule'); + expect(rules).toHaveLength(2); + expect( + rules.every((r) => r.attributes.identity && r.attributes.installation === 'a'.repeat(32)) + ).toBe(true); + // A second installation shares this account, existing rule names and environment. Its WIF + // bootstrap must record no ownership of either firewall, despite --create-firewalls. + const foreignState = join(state, 'other-install'); + const second = run( + args.map((v) => (v === state ? foreignState : v === 'a'.repeat(32) ? 'b'.repeat(32) : v)) + ); + expect(second.status, second.stderr).toBe(0); + const foreign = JSON.parse(readFileSync(join(foreignState, 'created-resources.json'), 'utf8')) + .resources as Array<{ kind: string }>; + expect(foreign.some((r) => r.kind === 'firewall-rule')).toBe(false); +}); diff --git a/scripts/selfhost/install-record.ts b/scripts/selfhost/install-record.ts new file mode 100644 index 0000000000..cd700984a4 --- /dev/null +++ b/scripts/selfhost/install-record.ts @@ -0,0 +1,111 @@ +/** + * What a self-hosted install itself creates, written into the same provider-neutral record the + * cloud bootstraps use (`/created-resources.json`, deploy/selfhost/created-resources.mjs), + * at the moment it is created, so `pnpm selfhost:teardown` never has to guess. No secrets: names, + * paths and the installation id only (SAM_INSTALLATION_ID is an identifier, not a secret; it is + * the `installation` label every node VM carries, node-provider-labels.ts). + * + * Cloud `box` entries: + * installation domain, environment, composeProject: the ownership anchor + * compose-project sam-selfhost containers, volumes and images compose made + * state-dir , env-file box state + * bucket created (bundled store, lives in a volume) or reused + * backup one per `pnpm selfhost:backup` / upgrade backup + */ +import { createHash } from 'node:crypto'; +import { existsSync, readFileSync } from 'node:fs'; +import { join, resolve } from 'node:path'; + +import { + addResource, + type CreatedResource, + readRecord, +} from '../../deploy/selfhost/created-resources.mjs'; + +export const RECORD_FILE = 'created-resources.json'; +/** docker-compose.yml `name:`; compose labels everything it creates with it. */ +export function expectedComposeProjectFor( + box: Readonly>, + stateDir: string +): string { + let installation = ''; + const keys=join(stateDir,'platform-keys.json'); + if(existsSync(keys)) { + try { + const value=JSON.parse(readFileSync(keys,'utf8')) as {SAM_INSTALLATION_ID?:unknown}; + if(typeof value.SAM_INSTALLATION_ID==='string' && /^[a-f0-9]{32}$/.test(value.SAM_INSTALLATION_ID)) installation=value.SAM_INSTALLATION_ID; + } catch { throw new Error('Cannot resolve installation Compose identity'); } + } + const suffix = createHash('sha256') + .update(`${box.SAM_DOMAIN ?? ''}\n${resolve(stateDir)}\n${installation}`) + .digest('hex') + .slice(0, 12); + return `sam-selfhost-${suffix}`; +} +/** Explicit legacy identity is usable by backup/upgrade, but never counts as creation proof. */ +export function composeProjectFor(box: Readonly>, stateDir: string): string { + const value = box.COMPOSE_PROJECT_NAME; + if (value !== undefined) { + if (!/^[a-z0-9][a-z0-9_-]*$/.test(value)) throw new Error('invalid COMPOSE_PROJECT_NAME'); + return value; + } + return expectedComposeProjectFor(box, stateDir); +} +/** The environment label celld-config.ts gives the Worker (ENVIRONMENT). */ +export const SELFHOST_ENVIRONMENT = 'selfhost'; + +export function recordPath(stateDir: string): string { + return join(stateDir, RECORD_FILE); +} + +export function usesBundledStore(box: Readonly>): boolean { + return (box.COMPOSE_PROFILES ?? '') + .split(',') + .map((p) => p.trim()) + .includes('local-store'); +} + +/** Called by `pnpm selfhost:deploy` (with and without --init) once the platform keys exist. */ +export function recordInstall( + stateDir: string, + envFile: string, + box: Readonly>, + installationId: string +): void { + const file = recordPath(stateDir); + const domain = box.SAM_DOMAIN ?? ''; + const project = composeProjectFor(box, stateDir); + const add = (kind: string, name: string, action: 'created' | 'reused', attributes = {}) => + addResource(file, { cloud: 'box', kind, name, action, createdBy: 'deploy', attributes }); + add('installation', installationId, 'created', { + domain, + environment: SELFHOST_ENVIRONMENT, + composeProject: project, + }); + if (project === expectedComposeProjectFor(box, stateDir)) + add('compose-project', project, 'created', { installation:installationId, environment:SELFHOST_ENVIRONMENT, stateDir:resolve(stateDir) }); + add('state-dir', stateDir, 'created'); + // The operator writes .env; the install only reads it, but it is the install's own file. + add('env-file', envFile, 'created'); + if (box.CELLD_BUCKET) { + // The bundled store's bucket is made by objectstore/init.sh; any other bucket is the operator's. + add('bucket', box.CELLD_BUCKET, usesBundledStore(box) ? 'created' : 'reused'); + // An operator-managed bucket/prefix is never claimed by reading its URL. + if (usesBundledStore(box)) add('bucket-contents', box.CELLD_BUCKET, 'created'); + } +} + +export function recordBackup(stateDir: string, dest: string): void { + addResource(recordPath(stateDir), { + cloud: 'box', + kind: 'backup', + name: dest, + action: 'created', + createdBy: 'backup', + attributes: {}, + }); +} + +export function readInstallRecord(stateDir: string): CreatedResource[] { + return readRecord(recordPath(stateDir)).resources; +} diff --git a/scripts/selfhost/live/backup-restore.live.test.ts b/scripts/selfhost/live/backup-restore.live.test.ts new file mode 100644 index 0000000000..98955c4b42 --- /dev/null +++ b/scripts/selfhost/live/backup-restore.live.test.ts @@ -0,0 +1,176 @@ +/** + * selfhost:backup -> selfhost:restore against the box's own object store: the MinIO image pinned + * in docker-compose.yml, run on loopback in Docker, driven by the real `mc mirror` commands in + * backup-lib.ts. Only `docker compose stop/start celld` is stubbed (there is no celld here). + * Round trip: seed a fleet bucket, back it up, restore into a second empty bucket, pull that + * bucket back and compare every object. Also proves restore refuses a non-empty bucket. + */ +import { spawnSync } from 'node:child_process'; +import { randomBytes } from 'node:crypto'; +import { mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs'; +import { join } from 'node:path'; + +import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest'; + +import { + type BoxContext, + OBJECTSTORE_IMAGE, + pullBucket, + pushBucket, + runBackup, + runRestore, + type RunResult, +} from '../backup-lib'; +import { freePort, LIVE_TMP } from './harness'; + +const KEY = 'sam-live-backup'; +const SECRET = 'live-backup-secret-0123456789'; +const hasDocker = spawnSync('docker', ['version'], { stdio: 'ignore' }).status === 0; + +let port = 0; +let container = ''; +let root = ''; +const composeCalls: string[] = []; + +function run(command: string, args: string[], env?: NodeJS.ProcessEnv): RunResult { + if (command === 'docker' && args[0] === 'compose') { + composeCalls.push(args.slice(-2).join(' ')); + return { status: 0, stdout: '', stderr: '' }; + } + const r = spawnSync(command, args, { env: env ?? process.env, encoding: 'utf8' }); + return { status: r.status ?? 1, stdout: r.stdout ?? '', stderr: r.stderr ?? '' }; +} + +function ctx(bucket: string, stateDir: string): BoxContext { + return { + box: { + CELLD_BUCKET: bucket, + R2_S3_REGION: 'us-east-1', + S3_ENDPOINT: `http://127.0.0.1:${port}`, + AWS_ACCESS_KEY_ID: KEY, + AWS_SECRET_ACCESS_KEY: SECRET, + }, + envFile: join(root, 'box.env'), + stateDir, + encryptionKeyFile: join(root, 'backup-key'), + composeFiles: ['/unused/docker-compose.yml'], + run, + now: () => Date.now(), + log: () => undefined, + user: `${process.getuid?.() ?? 0}:${process.getgid?.() ?? 0}`, + }; +} + +function tree(dir: string, base = dir): Record { + const out: Record = {}; + for (const entry of readdirSync(dir, { withFileTypes: true })) { + const path = join(dir, entry.name); + if (entry.isDirectory()) Object.assign(out, tree(path, base)); + else out[path.slice(base.length + 1)] = readFileSync(path, 'utf8'); + } + return out; +} + +describe.skipIf(!hasDocker && !process.env.CI)( + 'backup and restore on the bundled object store', + () => { + beforeAll(async () => { + port = await freePort(); + const consolePort = await freePort(); + mkdirSync(LIVE_TMP, { recursive: true }); + root = mkdtempSync(join(LIVE_TMP, 'backup-')); + for (const name of Object.keys(process.env)) { + if (name === 'CI' || name === 'GITHUB_ACTIONS' || name.startsWith('RUNNER_')) + vi.stubEnv(name, undefined); + } + writeFileSync(join(root, 'backup-key'), randomBytes(32), { mode: 0o600 }); + const started = run('docker', [ + 'run', + '-d', + '--rm', + '--network', + 'host', + '-e', + `MINIO_ROOT_USER=${KEY}`, + '-e', + `MINIO_ROOT_PASSWORD=${SECRET}`, + '--entrypoint', + 'minio', + OBJECTSTORE_IMAGE, + 'server', + '/data', + '--address', + `127.0.0.1:${port}`, + '--console-address', + `127.0.0.1:${consolePort}`, + ]); + expect(started.status, started.stderr).toBe(0); + container = started.stdout.trim(); + for (let i = 0; i < 60; i += 1) { + const res = await fetch(`http://127.0.0.1:${port}/minio/health/live`).catch(() => null); + if (res?.ok) break; + await new Promise((r) => setTimeout(r, 500)); + } + const env = { ...process.env, MC_HOST_src: `http://${KEY}:${SECRET}@127.0.0.1:${port}` }; + const mb = run( + 'docker', + [ + 'run', + '--rm', + '--network', + 'host', + '-e', + 'MC_HOST_src', + '-e', + 'MC_CONFIG_DIR=/tmp/mc', + '--entrypoint', + 'mc', + OBJECTSTORE_IMAGE, + 'mb', + 'src/fleet', + 'src/fresh', + ], + env + ); + expect(mb.status, mb.stderr).toBe(0); + }, 300_000); + + afterAll(() => { + vi.unstubAllEnvs(); + if (container) run('docker', ['rm', '-f', container]); + if (root) rmSync(root, { recursive: true, force: true }); + }); + + it('round-trips the fleet bucket and box state into an empty install', () => { + // Seed the "fleet" through the same push path restore uses. + const seed = join(root, 'seed'); + mkdirSync(join(seed, 'd1/main'), { recursive: true }); + writeFileSync(join(seed, 'd1/main/000001.ltx'), 'ltx-bytes'); + writeFileSync(join(seed, 'deploy-current.json'), '{"version":"v7"}'); + pushBucket(ctx('s3://fleet/celld', join(root, 'unused')), seed); + + const state = join(root, 'state'); + mkdirSync(state); + writeFileSync(join(state, 'platform-keys.json'), '{"k":1}'); + writeFileSync(join(root, 'box.env'), 'CELLD_BUCKET=s3://fleet/celld\n', { mode: 0o600 }); + + const dest = join(root, 'backup'); + const manifest = runBackup(ctx('s3://fleet/celld', state), dest, 'a'.repeat(40)); + expect(composeCalls).toEqual(['stop celld', 'start celld']); + expect(manifest.objectCount).toBe(2); + expect(manifest.downtimeMs).toBeGreaterThan(0); + + const newState = join(root, 'new-state'); + runRestore(ctx('s3://fresh/celld', newState), dest); + const check = join(root, 'check'); + pullBucket(ctx('s3://fresh/celld', newState), check); + expect(tree(check)).toEqual(tree(seed)); + expect(tree(newState)).toEqual({ 'platform-keys.json': '{"k":1}' }); + + // A second restore into the now non-empty bucket is refused. + expect(() => runRestore(ctx('s3://fresh/celld', join(root, 'other-state')), dest)).toThrow( + /not empty/ + ); + }); + } +); diff --git a/scripts/selfhost/operator-ci-guard.test.ts b/scripts/selfhost/operator-ci-guard.test.ts new file mode 100644 index 0000000000..7e69f2d9cc --- /dev/null +++ b/scripts/selfhost/operator-ci-guard.test.ts @@ -0,0 +1,79 @@ +/** Real CLI and public helper denial: nonexistent paths prove CI is refused before any read. */ +import { spawnSync } from 'node:child_process'; +import { resolve } from 'node:path'; + +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; + +import { loadBox } from './backup-cli'; +import { decryptBackupTree, encryptBackupTree, readBackupKey } from './backup-encryption'; +import { type BoxContext, runBackup, runRestore, runRollback } from './backup-lib'; + +const ROOT = resolve(import.meta.dirname, '../..'); +const ABSENT = resolve(ROOT, '.tmp/nonexistent-operator-guard-sentinel'); +const SIGNALS = ['GITHUB_ACTIONS', 'CI', 'RUNNER_NAME', 'RUNNER_TEMP'] as const; +beforeEach(() => { + for (const name of Object.keys(process.env)) { + if (name === 'CI' || name === 'GITHUB_ACTIONS' || name.startsWith('RUNNER_')) + vi.stubEnv(name, undefined); + } +}); +afterEach(() => vi.unstubAllEnvs()); + +describe('operator commands never read secret files in CI', () => { + it.each(SIGNALS)( + 'rejects even an empty %s at every public secret helper before reads or runner calls', + (signal) => { + vi.stubEnv(signal, ''); + const run = vi.fn(() => { + throw new Error('runner must not be called'); + }); + const context: BoxContext = { + box: {}, + envFile: ABSENT, + stateDir: ABSENT, + encryptionKeyFile: ABSENT, + composeFiles: [], + run, + now: Date.now, + log: vi.fn(), + }; + for (const invoke of [ + () => loadBox(ABSENT), + () => readBackupKey(ABSENT), + () => encryptBackupTree(ABSENT, ABSENT, ABSENT), + () => decryptBackupTree(ABSENT, ABSENT, ABSENT), + () => runBackup(context, ABSENT), + () => runRestore(context, ABSENT), + () => runRollback(context, ABSENT), + ]) + expect(invoke).toThrow('Operator secret commands are forbidden in CI'); + expect(run).not.toHaveBeenCalled(); + } + ); + + it.each(SIGNALS)( + 'rejects %s through real backup, restore and upgrade CLI entrypoints', + (signal) => { + for (const [script, args] of [ + ['backup.ts', ['--to', ABSENT]], + ['restore.ts', ['--from', ABSENT]], + ['upgrade.ts', ['--to', 'main']], + ] as const) { + const result = spawnSync( + resolve(ROOT, 'node_modules/.bin/tsx'), + [resolve(import.meta.dirname, script), ...args, '--box-env', ABSENT], + { + cwd: ROOT, + env: { ...process.env, [signal]: 'false' }, + encoding: 'utf8', + } + ); + expect(result.status).not.toBe(0); + expect(result.stderr).toContain('Operator secret commands are forbidden in CI'); + expect(result.stderr).not.toMatch(/ENOENT|does not exist/); + expect(result.stdout).toBe(''); + } + }, + 30_000 + ); +}); diff --git a/scripts/selfhost/operator-only.ts b/scripts/selfhost/operator-only.ts new file mode 100644 index 0000000000..02d8f1fa18 --- /dev/null +++ b/scripts/selfhost/operator-only.ts @@ -0,0 +1,10 @@ +/** L24 / policy 795e72a6: operator secrets must never enter a CI runner. */ +export function assertOperatorExecution(): void { + if ( + Object.keys(process.env).some( + (name) => name === 'CI' || name === 'GITHUB_ACTIONS' || name.startsWith('RUNNER_') + ) + ) { + throw new Error('Operator secret commands are forbidden in CI'); + } +} diff --git a/scripts/selfhost/restore.ts b/scripts/selfhost/restore.ts new file mode 100644 index 0000000000..e9e650cad8 --- /dev/null +++ b/scripts/selfhost/restore.ts @@ -0,0 +1,35 @@ +/** + * `pnpm selfhost:restore --from [--box-env ] [--state-dir ]` + * + * Restores a `pnpm selfhost:backup` into an EMPTY install (backup-lib.ts runRestore): the + * CELLD_BUCKET in the target .env must hold no objects and the target .state/ no platform keys. + * Supply an existing private target .env with its fresh bucket settings; it is never overwritten. + */ +import { join, resolve } from 'node:path'; +import { parseArgs } from 'node:util'; + +import { loadBox, log, SELFHOST_DIR } from './backup-cli'; +import { composeArgs, runRestore } from './backup-lib'; + +const { values } = parseArgs({ + options: { + from: { type: 'string' }, + 'encryption-key-file': { type: 'string' }, + 'box-env': { type: 'string' }, + 'state-dir': { type: 'string' }, + }, +}); +if (!values.from) throw new Error('--from is required'); +const from = resolve(values.from); +const envFile = resolve(values['box-env'] ?? join(SELFHOST_DIR, '.env')); +const ctx = loadBox(envFile, values['state-dir'], values['encryption-key-file']); +const manifest = runRestore(ctx, from); +log(`restored backup of ${manifest.createdAt} (SAM ${manifest.samCommit ?? 'unknown commit'})`); +log('start the stack with the SAME SAM checkout the backup was taken with:'); +if (manifest.samCommit) log(` git checkout ${manifest.samCommit}`); +log( + ` docker ${composeArgs(ctx, ['up', '-d']) + .map((arg) => `'${arg.replaceAll("'", "'\"'\"'")}'`) + .join(' ')}` +); +log(` curl -fsS https://api.$SAM_DOMAIN/health`); diff --git a/scripts/selfhost/teardown-box.ts b/scripts/selfhost/teardown-box.ts new file mode 100644 index 0000000000..f804fb2505 --- /dev/null +++ b/scripts/selfhost/teardown-box.ts @@ -0,0 +1,304 @@ +/** + * Teardown items on the box, in the object store and outside SAM (teardown.ts). Provider-neutral: + * the box is Docker Compose and files; the bucket goes through bucket-objects.ts, which already + * speaks gs:// and s3://. Cloud resources are teardown-gcp.ts's (and any later adapter's). + */ +import { existsSync, readdirSync, readFileSync, rmSync } from 'node:fs'; +import { isAbsolute, join, resolve } from 'node:path'; + +import type { CreatedResource } from '../../deploy/selfhost/created-resources.mjs'; +import { type BoxContext, composeArgs, MANIFEST_NAME, parseBucketUrl } from './backup-lib'; + +import { composeProjectFor, expectedComposeProjectFor, usesBundledStore } from './install-record'; +import { both, type Item, type Mode, STEPS } from './teardown-model'; +import { readComposeInventory, stopContainers, removeContainers } from './teardown-compose'; +import { isProtectedDir, stateItems } from './teardown-state-dir'; + +export interface TeardownOptions { + deleteBackups: boolean; + destroyKey: boolean; + adoptDiscovered: boolean; + gcpProjects: string[]; +} + +export interface TeardownContext extends BoxContext { + /** The mode being run; undefined for the inventory. */ + mode?: Mode; + options: TeardownOptions; + record: CreatedResource[]; + recordFile: string; + domain: string; + installationId: string | null; + /** deploy/selfhost: where backups go by default. */ + selfhostDir: string; + /** Removes one path under .state (tests inject a failure); default removeTree. */ + removeTree?: (path: string) => void; +} + +export function recorded(ctx: TeardownContext, kind: string, name?: string) { + return ctx.record.find( + (r) => r.cloud === 'box' && r.kind === kind && (name === undefined || r.name === name) + ); +} + +export function boxItems(ctx: TeardownContext): Item[] { + const items: Item[] = []; + const projectName = composeProjectFor(ctx.box, ctx.stateDir); + const project = recorded(ctx, 'compose-project', projectName); + const owned = + project?.action === 'created' && + projectName === expectedComposeProjectFor(ctx.box, ctx.stateDir); + const composeGone = project?.removedAt ?? (existsSync(ctx.envFile) ? undefined : 'no .env left'); + const composeCmd = `docker ${composeArgs(ctx, []).join(' ')}`; + const everything = ctx.mode === 'remove-everything'; + let inventory: ReturnType | undefined; + let inventoryError: Error | undefined; + if (owned) { try { inventory=readComposeInventory(ctx); } catch(error) { inventoryError=error instanceof Error ? error : new Error('Cannot verify Docker inventory'); } } + const proof = () => { if(inventoryError) throw inventoryError; if(!inventory) throw new Error('Missing Docker ownership inventory'); return inventory; }; + + items.push({ + id: 'box:stop', + place: 'on the box', + what: `services of compose project ${projectName} stopped (no new VMs or work start)`, + provenance: project ? 'recorded' : 'discovered, not recorded', + how: `${composeCmd} stop`, + step: STEPS.stop, + plan: both( + owned + ? { act: 'remove' } + : { act: 'refused', why: 'no creation record for this installation compose project' } + ), + removedAt: composeGone, + run: () => stopContainers(ctx,proof()), + }); + items.push({ + id: 'box:containers', + place: 'on the box', + what: `containers and network of compose project ${projectName}`, + provenance: project ? 'recorded' : 'discovered, not recorded', + how: 'revalidate exact container ids and configuration scope, remove those ids; remove everything also removes individually proven volume identities', + step: STEPS.box, + plan: both( + owned + ? { act: 'remove' } + : { act: 'refused', why: 'no creation record for this installation compose project' } + ), + removedAt: composeGone, + runKey: 'compose-down', + run: () => + removeContainers(ctx,proof(),everything), + record: everything ? { cloud: 'box', kind: 'compose-project', name: projectName } : undefined, + }); + const keepVolumes = { act: 'keep' as const, why: 'keep my data keeps volumes' }; + for (const volume of inventory?.volumes.map(v=>v.name) ?? []) { + const store = volume.endsWith('objectstore-data'); + items.push({ + id: `box:volume:${volume}`, + place: 'on the box', + what: `volume ${volume}${store ? ' (the bundled object store: the fleet bucket)' : ''}`, + provenance: 'discovered, not recorded', + how: 'docker compose down -v', + step: STEPS.box, + plan: { + 'keep-data': keepVolumes, + 'remove-everything': owned + ? { act: 'remove' } + : { act: 'refused', why: 'no project creation record' }, + }, + forGood: store + ? 'every project, chat, setting and hosted repository of this install' + : undefined, + removedAt: composeGone, + runKey: 'compose-down', + record: { cloud: 'box', kind: 'volume', name: volume, createdBy: 'compose' }, + }); + } + items.push({ + id: 'box:images', + place: 'on the box', + what: `images compose built for ${projectName} (key agent, egress fence, celld, ...)`, + provenance: 'discovered, not recorded', + how: 'docker compose down --rmi local', + step: STEPS.box, + plan: { + 'keep-data': { act: 'keep', why: 'rebuilt or reused on start' }, + 'remove-everything': { act: 'operator', why: 'images can be shared; remove unused images manually after inspecting their users' }, + }, + removedAt: composeGone, + }); + if (owned) items.push(...stateItems(ctx), ...backupItems(ctx)); + const env = recorded(ctx, 'env-file'); + items.push({ + id: 'box:env', + place: 'on the box', + what: `${ctx.envFile} (settings and the bucket credential)`, + provenance: env ? 'recorded' : 'discovered, not recorded', + how: `rm ${ctx.envFile} (last, so a failed run can be resumed)`, + step: STEPS.box, + plan: { + 'keep-data': { act: 'keep', why: 'needed to start the install again' }, + 'remove-everything': + owned && env?.action === 'created' && env.name === ctx.envFile + ? { act: 'remove' } + : { act: 'refused', why: 'no canonical install env-file creation proof' }, + }, + removedAt: env?.removedAt ?? (existsSync(ctx.envFile) ? undefined : 'already gone'), + run: () => rmSync(ctx.envFile, { force: true }), + record: { cloud: 'box', kind: 'env-file', name: ctx.envFile }, + }); + return items; +} + +/** A backup runBackup wrote: an absolute, unprotected directory with a version-1 manifest. */ +function isBackupDir(path: string, ctx: TeardownContext): boolean { + if (!isAbsolute(path) || isProtectedDir(path, ctx.selfhostDir)) return false; + if (resolve(path) === resolve(ctx.stateDir)) return false; + try { + return existsSync(join(path, '.sam-backup-manifest')); + } catch { + return false; + } +} + +function endpointHost(endpoint: string | undefined): string { + if (!endpoint) return 'your S3 endpoint'; + try { + return new URL(endpoint).host; // never userinfo + } catch { + return 'your S3 endpoint'; + } +} + +function backupItems(ctx: TeardownContext): Item[] { + const paths = new Map(); + for (const r of ctx.record) if (r.cloud === 'box' && r.kind === 'backup') paths.set(r.name, r); + const defaultDir = join(ctx.selfhostDir, 'backups'); + if (existsSync(defaultDir)) { + for (const entry of readdirSync(defaultDir)) { + const path = join(defaultDir, entry); + if (!paths.has(path) && existsSync(join(path, MANIFEST_NAME))) paths.set(path, undefined); + } + } + const items: Item[] = []; + for (const [path, entry] of paths) { + if (entry?.removedAt && !existsSync(path)) continue; + // Proof it is a backup: the manifest runBackup writes. A recorded path without one is refused. + const isBackup = entry?.action === 'created' && isBackupDir(path, ctx); + const gone = !existsSync(path); + items.push({ + id: `box:backup:${path}`, + place: 'on the box', + what: `backup ${path}${backupBucket(path)}`, + provenance: entry ? 'recorded' : 'discovered, not recorded', + how: `rm -r ${path}`, + step: STEPS.box, + plan: gone + ? both({ act: 'keep', why: 'no longer on disk' }) + : !isBackup + ? both({ + act: 'refused', + why: `not proven a backup (needs an absolute path, a version-1 ${MANIFEST_NAME}, and not /, home or the checkout)`, + }) + : { + 'keep-data': { act: 'keep', why: 'keep my data keeps backups' }, + 'remove-everything': ctx.options.deleteBackups + ? { act: 'remove' } + : { act: 'keep', why: 'pass --delete-backups to delete backups' }, + }, + forGood: 'this backup can never be restored', + run: () => rmSync(path, { recursive: true, force: true }), + record: { cloud: 'box', kind: 'backup', name: path, createdBy: 'backup' }, + }); + } + return items; +} + +function backupBucket(path: string): string { + try { + const manifest = JSON.parse(readFileSync(join(path, MANIFEST_NAME), 'utf8')) as unknown; + const created = (manifest as { createdAt?: unknown }).createdAt; + return typeof created === 'string' ? ` (taken ${created})` : ''; + } catch { + return ''; + } +} + +export function bucketItems(ctx: TeardownContext): Item[] { + const url = ctx.box.CELLD_BUCKET ?? recorded(ctx, 'bucket')?.name; + if (!url) return []; + const entry = recorded(ctx, 'bucket', url); + const contents = recorded(ctx, 'bucket-contents', url); + const project = recorded( + ctx, + 'compose-project', + expectedComposeProjectFor(ctx.box, ctx.stateDir) + ); + const owned = + project?.action === 'created' && composeProjectFor(ctx.box, ctx.stateDir) === project.name; + if (usesBundledStore(ctx.box)) { + return [ + { + id: 'bucket:bundled', + place: 'in the object store', + what: `fleet bucket ${url} in the bundled store (celld state, deploy versions, vm-agent releases, hosted git)`, + provenance: entry ? 'recorded' : 'discovered, not recorded', + how: 'removed with the objectstore-data volume', + step: STEPS.box, + plan: { + 'keep-data': { act: 'keep', why: 'keep my data keeps the bucket' }, + 'remove-everything': owned + ? { act: 'remove' } + : { act: 'refused', why: 'no canonical project creation proof' }, + }, + removedAt: entry?.removedAt, + runKey: 'compose-down', + record: { cloud: 'box', kind: 'bucket', name: url }, + }, + ]; + } + const parsed = parseBucketUrl(url); + const items: Item[] = [ + { + id: 'bucket:contents', + place: 'in the object store', + what: `every object under ${url} (celld state, deploy versions, vm-agent releases, hosted git)`, + provenance: entry ? 'recorded' : 'discovered, not recorded', + how: 'after verifying that no other installation uses these objects, remove this installation prefix in your object store console', + step: STEPS.bucket, + plan: { + 'keep-data': { act: 'keep', why: 'keep my data keeps the bucket' }, + // A configured URL/prefix is use, not creation proof. External data stays with the operator. + 'remove-everything': { + act: 'operator', + why: 'operator-managed store has no live creation proof; remove this installation data manually after verifying ownership', + }, + }, + forGood: + 'every project, chat, setting and hosted repository of this install (backups excepted)', + removedAt: contents?.removedAt, + + record: { cloud: 'box', kind: 'bucket-contents', name: url, createdBy: 'deploy' }, + }, + ]; + if (entry?.action !== 'created') { + items.push({ + id: 'bucket:itself', + place: 'in the object store', + what: `the bucket ${parsed.bucket} itself (you created it)`, + provenance: entry ? 'recorded' : 'discovered, not recorded', + how: + parsed.scheme === 'gs' + ? `gcloud storage buckets delete gs://${parsed.bucket} (only if nothing else uses it)` + : `delete bucket ${parsed.bucket} at ${endpointHost(ctx.box.S3_ENDPOINT)} in your provider's console`, + step: STEPS.outside, + plan: { + 'keep-data': { act: 'keep', why: 'keep my data keeps the bucket' }, + 'remove-everything': { + act: 'operator', + why: 'operator-managed bucket and contents are retained', + }, + }, + }); + } + return items; +} diff --git a/scripts/selfhost/teardown-compose.ts b/scripts/selfhost/teardown-compose.ts new file mode 100644 index 0000000000..a70c7c548f --- /dev/null +++ b/scripts/selfhost/teardown-compose.ts @@ -0,0 +1,69 @@ +/** Teardown acts on exact live identities, never Compose's broad project-name sweep. */ +import { dirname, resolve } from 'node:path'; +import { readRecord } from '../../deploy/selfhost/created-resources.mjs'; +import { check } from './backup-lib'; +import { composeProjectFor, expectedComposeProjectFor } from './install-record'; +import type { TeardownContext } from './teardown-box'; + +interface Container { id: string; labels: Record } +interface Volume { name: string; createdAt: string; labels: Record } +export interface ComposeInventory { containers: Container[]; volumes: Volume[] } +function labels(value: unknown): Record { + if (!value || typeof value !== 'object' || Array.isArray(value) || Object.values(value).some(v=>typeof v !== 'string')) throw new Error('Unreadable Docker ownership labels'); + return value as Record; +} +function result(ctx: TeardownContext, args: string[]): string { + return check(ctx.run('docker',args),'read Docker ownership metadata').stdout.trim(); +} +function parse(text: string): Record { + try { const value:unknown=JSON.parse(text); if(!value || typeof value!=='object' || Array.isArray(value)) throw new Error(); return value as Record; } + catch { throw new Error('Unreadable Docker ownership metadata'); } +} +function projectProof(ctx: TeardownContext): string { + const project=composeProjectFor(ctx.box,ctx.stateDir); + if(project!==expectedComposeProjectFor(ctx.box,ctx.stateDir) || !ctx.installationId) throw new Error('Refused: no exact installation Compose identity'); + const record=readRecord(ctx.recordFile).resources; + const installs=record.filter(r=>r.cloud==='box' && r.kind==='installation' && !r.removedAt); + const projects=record.filter(r=>r.cloud==='box' && r.kind==='compose-project' && r.name===project && r.action==='created' && r.attributes?.installation===ctx.installationId && r.attributes?.environment==='selfhost' && r.attributes?.stateDir===resolve(ctx.stateDir)); + if(installs.length!==1 || installs[0]?.name!==ctx.installationId || installs[0]?.attributes?.domain!==ctx.domain || installs[0]?.attributes?.environment!=='selfhost' || installs[0]?.attributes?.composeProject!==project || projects.length!==1) throw new Error('Refused: missing exact installation Compose receipt'); + return project; +} +export function readComposeInventory(ctx: TeardownContext): ComposeInventory { + const project=projectProof(ctx); + const names=(args:string[])=>result(ctx,args).split('\n').filter(Boolean); + const ids=names(['container','ls','--all','--no-trunc','--filter',`label=com.docker.compose.project=${project}`,'--format','{{.ID}}']); + if(new Set(ids).size!==ids.length || ids.some(id=>!/^[a-f0-9]{64}$/.test(id))) throw new Error('Refused: ambiguous Docker container inventory'); + const containers=ids.map(id=>{ + const raw=parse(result(ctx,['container','inspect','--format','{"id":{{json .Id}},"labels":{{json .Config.Labels}}}',id])); + const meta=labels(raw.labels); + const files=meta['com.docker.compose.project.config_files']?.split(',').map(file=>resolve(file)); + if(raw.id!==id || meta['com.docker.compose.project']!==project || !meta['com.docker.compose.service'] || meta['com.docker.compose.project.working_dir']!==dirname(ctx.composeFiles[0] ?? '') || JSON.stringify(files)!==JSON.stringify(ctx.composeFiles.map(file=>resolve(file)))) throw new Error('Refused: foreign Docker container configuration scope'); + return {id,labels:meta}; + }); + const volumes=names(['volume','ls','--filter',`label=com.docker.compose.project=${project}`,'--format','{{.Name}}']).map(name=>{ + if(!/^[a-zA-Z0-9][a-zA-Z0-9_.-]*$/.test(name)) throw new Error('Refused: invalid Docker volume name'); + const raw=parse(result(ctx,['volume','inspect','--format','{"name":{{json .Name}},"createdAt":{{json .CreatedAt}},"labels":{{json .Labels}}}',name])); + const meta=labels(raw.labels); + if(raw.name!==name || typeof raw.createdAt!=='string' || !raw.createdAt || meta['com.docker.compose.project']!==project || name!==`${project}_${meta['com.docker.compose.volume']}`) throw new Error('Refused: foreign Docker volume configuration scope'); + return {name,createdAt:raw.createdAt,labels:meta}; + }); + if(new Set(volumes.map(v=>v.name)).size!==volumes.length) throw new Error('Refused: duplicate Docker volume inventory'); + return {containers:containers.sort((a,b)=>a.id.localeCompare(b.id)),volumes:volumes.sort((a,b)=>a.name.localeCompare(b.name))}; +} +export function assertComposeInventory(ctx: TeardownContext, expected: ComposeInventory): void { + if(JSON.stringify(readComposeInventory(ctx))!==JSON.stringify(expected)) throw new Error('Refused: Docker identities or ownership changed since inventory'); +} +export function stopContainers(ctx: TeardownContext, inventory: ComposeInventory): void { + assertComposeInventory(ctx,inventory); + if(inventory.containers.length) check(ctx.run('docker',['container','stop',...inventory.containers.map(c=>c.id)]),'stop owned containers'); +} +export function removeContainers(ctx: TeardownContext, inventory: ComposeInventory, volumes: boolean): void { + assertComposeInventory(ctx,inventory); + // Exact ids, individually re-fetched just above, cannot select a replacement container. + if(inventory.containers.length) check(ctx.run('docker',['container','rm','--force',...inventory.containers.map(c=>c.id)]),'remove owned containers'); + if(volumes) for(const volume of inventory.volumes) { + const current=readComposeInventory(ctx); + if(!current.volumes.some(v=>JSON.stringify(v)===JSON.stringify(volume))) throw new Error('Refused: Docker volume identity changed before removal'); + check(ctx.run('docker',['volume','rm',volume.name]),'remove owned volume'); + } +} diff --git a/scripts/selfhost/teardown-gcp-bootstrap.ts b/scripts/selfhost/teardown-gcp-bootstrap.ts new file mode 100644 index 0000000000..4051d5c775 --- /dev/null +++ b/scripts/selfhost/teardown-gcp-bootstrap.ts @@ -0,0 +1,255 @@ +/** WIF cleanup uses only creation receipts. Existing resources are never adopted by name. */ +import { check } from './backup-lib'; +import type { TeardownContext } from './teardown-box'; +import { type Item, STEPS } from './teardown-model'; + +export const BOOTSTRAP = 'gcp-bootstrap'; +export function gcloudNotFound(stderr: string): boolean { + return /not found|NOT_FOUND|notFound|does not exist/i.test(stderr); +} +export function gcloudReason(_stderr: string): string { + return 'gcloud failed; check authentication and project permissions'; +} +export function gcloud(ctx: TeardownContext, args: string[]) { + try { + return ctx.run('gcloud', args); + } catch { + return { status: 127, stdout: '', stderr: 'gcloud unavailable' }; + } +} + +export function bootstrapItems(ctx: TeardownContext, project: string): Item[] { + const issuer = `https://api.${ctx.domain}`; + return ctx.record + .filter( + (r) => + r.cloud === 'gcp' && + r.createdBy === BOOTSTRAP && + r.attributes?.project === project && + r.kind !== 'firewall-rule' + ) + .sort( + (a, b) => + [ + 'iam-binding', + 'workload-identity-provider', + 'workload-identity-pool', + 'service-account', + ].indexOf(a.kind) - + [ + 'iam-binding', + 'workload-identity-provider', + 'workload-identity-pool', + 'service-account', + ].indexOf(b.kind) + ) + .map((entry) => { + const attrs = entry.attributes ?? {}; + const owned = + entry.action === 'created' && + attrs.install === issuer && + attrs.environment === 'selfhost' && + !!ctx.installationId && + attrs.installation === ctx.installationId; + return { + id: `gcp:${entry.kind}:${entry.name}`, + place: 'in your cloud, made by the bootstrap', + what: `${entry.kind} ${entry.name}`, + provenance: 'recorded', + how: 'revalidate the recorded identity, then delete with gcloud', + step: STEPS.identity, + removedAt: entry.removedAt, + plan: { + 'keep-data': { + act: 'keep', + why: 'the retained data needs its original workload identity and grants', + }, + 'remove-everything': owned + ? { act: 'remove' } + : { act: 'refused', why: 'not recorded as created for this issuer' }, + }, + run: () => { + if (!owned) throw new Error('refused: missing creation ownership'); + const where = [`--project=${project}`]; + const pool = attrs.pool; + let describe: string[]; + let remove: string[]; + let expected: Record; + switch (entry.kind) { + case 'workload-identity-pool': + describe = [ + 'iam', + 'workload-identity-pools', + 'describe', + entry.name, + ...where, + '--location=global', + ]; + remove = [ + 'iam', + 'workload-identity-pools', + 'delete', + entry.name, + ...where, + '--location=global', + '--quiet', + ]; + expected = { + name: attrs.identity, + description: `Dedicated to the SAM install whose token issuer is ${issuer}`, + }; + break; + case 'workload-identity-provider': + if (!pool) throw new Error('refused: missing recorded pool'); + describe = [ + 'iam', + 'workload-identity-pools', + 'providers', + 'describe', + entry.name, + ...where, + '--location=global', + `--workload-identity-pool=${pool}`, + ]; + remove = [ + 'iam', + 'workload-identity-pools', + 'providers', + 'delete', + entry.name, + ...where, + '--location=global', + `--workload-identity-pool=${pool}`, + '--quiet', + ]; + expected = { name: attrs.identity }; + break; + case 'service-account': + describe = ['iam', 'service-accounts', 'describe', entry.name, ...where]; + remove = ['iam', 'service-accounts', 'delete', entry.name, ...where, '--quiet']; + expected = { + uniqueId: attrs.identity, + description: `Creates and deletes SAM workspace VMs and their firewall rules for ${issuer}`, + }; + break; + case 'iam-binding': { + // Delete an exact grant only, never a project policy replacement. Creation receipt + // is linked to the service account's immutable id, checked immediately beforehand. + if (!attrs.member || !attrs.role || !attrs.account || !attrs.identity) + throw new Error('refused: incomplete grant receipt'); + describe = ['iam', 'service-accounts', 'describe', attrs.account, ...where]; + remove = [ + 'projects', + 'remove-iam-policy-binding', + project, + `--member=${attrs.member}`, + `--role=${attrs.role}`, + '--condition=None', + '--quiet', + '--format=none', + ]; + expected = { uniqueId: attrs.identity }; + break; + } + default: + throw new Error(`refused: unsupported recorded resource kind ${entry.kind}`); + } + const result = gcloud(ctx, [...describe, '--format=json']); + if (result.status !== 0 && gcloudNotFound(result.stderr)) return; + check(result, 'read recorded resource before deletion'); + let current: Record; + try { + current = JSON.parse(result.stdout) as Record; + } catch { + throw new Error('refused: unreadable ownership metadata'); + } + if (Object.entries(expected).some(([key, value]) => !value || current[key] !== value)) + throw new Error('refused: resource identity or ownership changed'); + if ( + entry.kind === 'workload-identity-provider' && + (current.oidc as { issuerUri?: string } | undefined)?.issuerUri !== issuer + ) + throw new Error('refused: provider issuer changed'); + if (entry.kind === 'workload-identity-pool') { + const providers = gcloud(ctx, [ + 'iam', + 'workload-identity-pools', + 'providers', + 'list', + ...where, + '--location=global', + `--workload-identity-pool=${entry.name}`, + '--show-deleted', + '--format=json', + ]); + check(providers, 'check pool providers before deletion'); + const parsed: unknown = JSON.parse(providers.stdout); + const known = ctx.record + .filter( + (r) => + r.cloud === 'gcp' && + r.kind === 'workload-identity-provider' && + r.action === 'created' && + r.attributes?.project === project && + r.attributes?.installation === ctx.installationId && + r.attributes?.environment === 'selfhost' && + r.attributes?.install === issuer + ) + .map((r) => r.attributes?.identity); + if ( + !Array.isArray(parsed) || + parsed.some((p) => !p || !known.includes(p.name) || p.oidc?.issuerUri !== issuer) + ) + throw new Error('refused: pool contains unowned or unreadable providers'); + } + if (entry.kind === 'service-account' || entry.kind === 'iam-binding') { + const account = entry.kind === 'service-account' ? entry.name : attrs.account; + const policy = gcloud(ctx, [ + 'iam', + 'service-accounts', + 'get-iam-policy', + account, + ...where, + '--format=json', + ]); + check(policy, 'check account grants before deletion'); + const parsed: unknown = JSON.parse(policy.stdout); + if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) + throw new Error('refused: unreadable account grants'); + const bindings = (parsed as { bindings?: unknown }).bindings ?? []; + const projectNumber = ctx.record + .find((r) => r.kind === 'workload-identity-pool' && r.attributes?.pool === pool) + ?.attributes?.identity?.split('/')[1]; + const member = `principalSet://iam.googleapis.com/projects/${projectNumber}/locations/global/workloadIdentityPools/${pool}/*`; + if ( + !Array.isArray(bindings) || + bindings.some( + (b) => + b.condition || + b.role !== 'roles/iam.workloadIdentityUser' || + !Array.isArray(b.members) || + b.members.some((m: unknown) => m !== member) + ) + ) + throw new Error('refused: account has foreign grants'); + const keys = gcloud(ctx, [ + 'iam', + 'service-accounts', + 'keys', + 'list', + `--iam-account=${account}`, + ...where, + '--managed-by=user', + '--format=json', + ]); + check(keys, 'check account keys before deletion'); + const parsedKeys: unknown = JSON.parse(keys.stdout); + if (!Array.isArray(parsedKeys) || parsedKeys.length) + throw new Error('refused: account has user-managed keys'); + } + check(gcloud(ctx, remove), 'delete recorded resource'); + }, + record: entry, + } satisfies Item; + }); +} diff --git a/scripts/selfhost/teardown-gcp-firewall.test.ts b/scripts/selfhost/teardown-gcp-firewall.test.ts new file mode 100644 index 0000000000..8b4eb2650a --- /dev/null +++ b/scripts/selfhost/teardown-gcp-firewall.test.ts @@ -0,0 +1,82 @@ +/** + * Teardown's advice on SAM's shared firewall rules (teardown-gcp.ts `firewallUsage`): which VMs a + * rule applies to, by network and target tag, as GCP applies it. Read-only advice; teardown never + * deletes these rules. Box round R15 (G5): labelled fixture VMs without the tag were reported as + * users. The CLI path is in teardown.test.ts; these cover the branches it does not reach. + */ +import { describe, expect, it } from 'vitest'; + +import { firewallUsage, parseFirewallTargets } from './teardown-gcp'; + +type Instance = Exclude[1], Error>[number]; +const OWN_INSTALL = 'a'.repeat(32); + +function vmOn( + name: string, + network: string, + tags: string[], + labels: Record = {} +): Instance { + return { id: name, name, zone: 'europe-west1-b', labels, disks: [], tags, networks: [network] }; +} + +const samLabels = (installation: string) => ({ + managed: 'simple-agent-manager', + installation, + env: 'selfhost', + node: 'n', +}); +const agentRule = parseFirewallTargets( + JSON.stringify({ + network: 'https://www.googleapis.com/compute/v1/projects/p/global/networks/default', + targetTags: ['sam-agent'], + }) +); + +describe('firewallUsage', () => { + it('a VM with the tag on another network does not use the rule', () => { + const other = vmOn('elsewhere', 'sam-selfhost', ['sam-agent']); + expect(firewallUsage(agentRule, [other], [], OWN_INSTALL)).toBe( + 'no existing VM in this project uses it (tag sam-agent; a VM made later may)' + ); + // Control: the same VM on the rule's network does. + const same = vmOn('here', 'default', ['sam-agent']); + expect(firewallUsage(agentRule, [same], [], OWN_INSTALL)).toBe( + '1 other VM(s) in this project use it (tag sam-agent: here), so keep it' + ); + }); + + it("leaves out this install's own node VMs (teardown removes them)", () => { + const own = vmOn('mine', 'default', ['sam-agent'], samLabels(OWN_INSTALL)); + expect(firewallUsage(agentRule, [own], [own], OWN_INSTALL)).toMatch(/^no existing VM/); + // Control: another install's labelled VM with the tag counts. + const theirs = vmOn('theirs', 'default', ['sam-agent'], samLabels('b'.repeat(32))); + expect(firewallUsage(agentRule, [own, theirs], [own, theirs], OWN_INSTALL)).toMatch( + /^1 other VM\(s\) .*theirs/ + ); + }); + + it('a rule without target tags applies to every VM on its network', () => { + const rule = parseFirewallTargets(JSON.stringify({ network: 'x/networks/default' })); + const untagged = vmOn('plain', 'default', []); + expect(firewallUsage(rule, [untagged], [], OWN_INSTALL)).toBe( + '1 other VM(s) in this project use it (every VM on network default: plain), so keep it' + ); + }); + + it.each([ + ['targets service accounts', JSON.stringify({ targetServiceAccounts: ['sa@x'] })], + ['is not JSON', 'not json'], + ['is a list', '[]'], + ])('says it cannot tell when the rule %s', (_case, json) => { + expect(firewallUsage(parseFirewallTargets(json), [], [], OWN_INSTALL)).toBe( + 'teardown could not read which VMs it applies to; check them before deleting it' + ); + }); + + it("says it cannot tell when the project's VMs cannot be listed", () => { + expect(firewallUsage(agentRule, new Error('PERMISSION_DENIED'), [], OWN_INSTALL)).toBe( + "teardown could not list the project's VMs to see which use it (PERMISSION_DENIED)" + ); + }); +}); diff --git a/scripts/selfhost/teardown-gcp.ts b/scripts/selfhost/teardown-gcp.ts new file mode 100644 index 0000000000..c4eba2f5ee --- /dev/null +++ b/scripts/selfhost/teardown-gcp.ts @@ -0,0 +1,499 @@ +/** Google Cloud teardown: exact installation labels + immutable ids before VM deletion; + * recorded creator scope + no remaining users before firewall deletion. Legacy shared + * resources remain operator-owned. WIF receipts are handled by teardown-gcp-bootstrap. + */ +import { + normalizeInstallationId, + SAM_ENVIRONMENT_LABEL_KEY, + SAM_INSTALLATION_LABEL_KEY, + SAM_MANAGED_LABEL_KEY, + SAM_MANAGED_LABEL_VALUE, + SAM_NODE_LABEL_KEY, +} from '../../apps/api/src/services/node-provider-labels'; +import { check } from './backup-lib'; +import { SELFHOST_ENVIRONMENT } from './install-record'; +import type { TeardownContext } from './teardown-box'; +import { + BOOTSTRAP, + bootstrapItems, + gcloud, + gcloudNotFound, + gcloudReason, +} from './teardown-gcp-bootstrap'; +import { both, type Item, STEPS } from './teardown-model'; + +/** + * The firewall rule names SAM's GCP provider ensures (SAM_AGENT_FIREWALL_RULE_NAME and + * SAM_APP_ROUTE_FIREWALL_RULE_NAME in packages/providers/src/gcp-metadata.ts). Not imported: that + * module needs @simple-agent-manager/shared built, and selfhost scripts typecheck and run without + * it. teardown-gcp-constants.test.ts pins them to the provider's values. + */ +export const SAM_AGENT_FIREWALL_RULE_NAME = 'sam-allow-agent'; +export const SAM_APP_ROUTE_FIREWALL_RULE_NAME = 'sam-allow-app-routes'; + +/** Compute Engine resource names (RFC 1035); never starts with `-`, so never read as a flag. */ +const GCE_NAME = /^[a-z]([-a-z0-9]{0,61}[a-z0-9])?$/; + +interface GcpInstance { + id: string; + name: string; + zone: string; + labels: Record; + disks: Array<{ source: string; autoDelete: boolean }>; + /** Network tags (`tags.items`): what a firewall rule's `targetTags` select. */ + tags: string[]; + /** Names (last path segment) of the networks its interfaces are on. */ + networks: string[]; +} + +/** What a firewall rule applies to (gcloud `firewall-rules describe --format=json`). */ +interface GcpFirewallTargets { + network: string | null; + targetTags: string[]; + /** Rules selecting by service account are not modelled: report them as unknown. */ + targetServiceAccounts: boolean; +} + +export function gcpItems(ctx: TeardownContext): Item[] { + const projects = new Set(ctx.options.gcpProjects); + for (const r of ctx.record) { + if (r.cloud === 'gcp' && r.createdBy === BOOTSTRAP && r.attributes?.project) { + projects.add(r.attributes.project); + } + } + if (projects.size === 0) { + return [ + { + id: 'gcp:none', + place: 'in your cloud, made by SAM at runtime', + what: 'Google Cloud: no project recorded', + provenance: 'discovered, not recorded', + how: 'if nodes ran in Google Cloud, set GCP_PROJECT in .env or run again with --gcp-project ', + step: STEPS.compute, + plan: both({ act: 'operator', why: 'teardown does not know the project' }), + }, + ]; + } + const items: Item[] = []; + for (const project of projects) { + if (!/^[a-z][a-z0-9-]{4,28}[a-z0-9]$/.test(project)) { + throw new Error(`invalid Google Cloud project id: ${project}`); + } + const listed = listInstances(ctx, project); + items.push(...instanceItems(ctx, project, listed)); + items.push(...firewallItems(ctx, project, listed)); + items.push(...bootstrapItems(ctx, project)); + } + return items; +} + +function listInstances(ctx: TeardownContext, project: string): GcpInstance[] | Error { + const result = gcloud(ctx, [ + 'compute', + 'instances', + 'list', + `--project=${project}`, + `--filter=labels.${SAM_MANAGED_LABEL_KEY}=${SAM_MANAGED_LABEL_VALUE}`, + '--format=json', + ]); + if (result.status !== 0) { + return new Error(`gcloud compute instances list failed: ${result.stderr.trim().slice(0, 400)}`); + } + try { + const parsed = JSON.parse(result.stdout) as unknown; + if (!Array.isArray(parsed)) throw new Error('not a list'); + return parseUniqueInstances(parsed); + } catch (error) { + return new Error( + `unreadable instance list: ${error instanceof Error ? error.message : String(error)}` + ); + } +} + +function parseUniqueInstances(values: unknown[]): GcpInstance[] { + const instances = values.map(parseInstance); + const ids = new Set(), + names = new Set(); + for (const instance of instances) { + const scope = `${instance.zone}/${instance.name}`; + if (ids.has(instance.id) || names.has(scope)) + throw new Error('duplicate or conflicting instance inventory'); + ids.add(instance.id); + names.add(scope); + } + return instances; +} + +function parseInstance(value: unknown): GcpInstance { + const v = value as Record; + if ( + typeof v?.name !== 'string' || + typeof v.zone !== 'string' || + typeof v.id !== 'string' || + !/^[0-9]+$/.test(v.id) + ) { + throw new Error('instance without name, zone or id'); + } + const labels: Record = {}; + if (v.labels && typeof v.labels === 'object') { + for (const [key, val] of Object.entries(v.labels as Record)) { + if (typeof val === 'string') labels[key] = val; + } + } + const disks = Array.isArray(v.disks) + ? v.disks + .map((d) => d as Record) + .filter((d) => typeof d?.source === 'string') + .map((d) => ({ source: d.source as string, autoDelete: d.autoDelete === true })) + : []; + if (!GCE_NAME.test(v.name) || !GCE_NAME.test(lastSegment(v.zone))) + throw new Error(`unexpected instance name ${JSON.stringify(v.name)}`); + const tagItems = (v.tags as { items?: unknown } | undefined)?.items; + const tags = Array.isArray(tagItems) ? tagItems.filter((t) => typeof t === 'string') : []; + const networks = Array.isArray(v.networkInterfaces) + ? v.networkInterfaces + .map((n) => (n as Record)?.network) + .filter((n): n is string => typeof n === 'string') + .map(lastSegment) + : []; + return { + id: v.id, + name: v.name, + zone: v.zone.split('/').pop() ?? v.zone, + labels, + disks, + tags, + networks, + }; +} + +function lastSegment(value: string): string { + return value.split('/').pop() ?? value; +} + +/** Why an instance is not this install's, or null when every ownership label matches. */ +export function ownershipRefusal( + instance: GcpInstance, + installationId: string | null +): string | null { + if (!installationId) { + return 'this install has no recorded installation id; run pnpm selfhost:deploy --init once to record it'; + } + const labels = instance.labels; + if (labels[SAM_MANAGED_LABEL_KEY] !== SAM_MANAGED_LABEL_VALUE) + return 'not labelled as SAM-managed'; + const owner = normalizeInstallationId(labels[SAM_INSTALLATION_LABEL_KEY] ?? ''); + if (owner !== installationId) { + return `labelled installation=${labels[SAM_INSTALLATION_LABEL_KEY] ?? '(none)'}, another install's`; + } + if (labels[SAM_ENVIRONMENT_LABEL_KEY] !== SELFHOST_ENVIRONMENT) { + return `labelled env=${labels[SAM_ENVIRONMENT_LABEL_KEY] ?? '(none)'}, not ${SELFHOST_ENVIRONMENT}`; + } + if (!labels[SAM_NODE_LABEL_KEY]) return 'no node label'; + return null; +} + +function instanceItems( + ctx: TeardownContext, + project: string, + listed: GcpInstance[] | Error +): Item[] { + if (listed instanceof Error) { + return [ + { + id: `gcp:${project}:instances`, + place: 'in your cloud, made by SAM at runtime', + what: `node VMs in ${project}: could not be listed (${listed.message})`, + provenance: 'discovered, not recorded', + how: 'log in with gcloud as a project owner (gcloud auth login) and run again', + step: STEPS.compute, + // Removal stops here rather than taking the identity that could still delete the VMs. + plan: both({ act: 'remove' }), + run: () => { + throw listed; + }, + }, + ]; + } + if (listed.length === 0) { + return [ + { + id: `gcp:${project}:instances`, + place: 'in your cloud, made by SAM at runtime', + what: `node VMs in ${project}: none labelled managed=${SAM_MANAGED_LABEL_VALUE}`, + provenance: 'discovered, not recorded', + how: 'nothing to remove', + step: STEPS.compute, + plan: both({ act: 'keep', why: 'nothing to remove' }), + }, + ]; + } + return listed.map((instance) => { + const refusal = ownershipRefusal(instance, ctx.installationId); + const path = `projects/${project}/zones/${instance.zone}/instances/${instance.name}`; + const keptDisks = instance.disks.filter((d) => !d.autoDelete); + return { + id: `gcp:${path}`, + place: 'in your cloud, made by SAM at runtime', + what: `node VM ${instance.name} (${project}, ${instance.zone}, node ${instance.labels[SAM_NODE_LABEL_KEY] ?? '?'})${keptDisks.length ? ` (${keptDisks.length} disk(s) without auto-delete are retained)` : ', boot disk with it'}`, + provenance: 'discovered, not recorded', + how: `gcloud compute instances delete ${instance.name} --zone=${instance.zone} --project=${project}, after checking its id and labels again`, + step: STEPS.compute, + plan: both(refusal ? { act: 'refused', why: refusal } : { act: 'remove' }), + run: () => deleteInstance(ctx, project, instance), + record: { + cloud: 'gcp', + kind: 'instance', + name: path, + createdBy: 'sam-app', + attributes: { + project, + node: instance.labels[SAM_NODE_LABEL_KEY] ?? '', + discovered: 'labels', + }, + }, + } satisfies Item; + }); +} + +function deleteInstance(ctx: TeardownContext, project: string, listed: GcpInstance): void { + const where = [`--zone=${listed.zone}`, `--project=${project}`]; + const described = gcloud(ctx, [ + 'compute', + 'instances', + 'describe', + listed.name, + ...where, + '--format=json', + ]); + if (described.status !== 0) { + if (/not found|was not found|404/i.test(described.stderr)) return; // already gone + check(described, `gcloud compute instances describe ${listed.name}`); + } + const current = parseInstance(JSON.parse(described.stdout) as unknown); + // The same VM (immutable id), still this install's, at the moment of deletion. + if (current.id !== listed.id) { + throw new Error( + `refused: ${listed.name} is now a different VM (id ${current.id}, listed ${listed.id})` + ); + } + const refusal = ownershipRefusal(current, ctx.installationId); + if (refusal) throw new Error(`refused: ${listed.name} ${refusal}`); + check( + gcloud(ctx, ['compute', 'instances', 'delete', listed.name, ...where, '--quiet']), + `gcloud compute instances delete ${listed.name}` + ); + // A disk attached without autoDelete may have been supplied by the operator. An attachment + // proves use, not creation: preserve it; only Compute Engine's autoDelete disks go with a VM. +} + +function firewallItems( + ctx: TeardownContext, + project: string, + listed: GcpInstance[] | Error +): Item[] { + const items: Item[] = []; + // Every VM in the project, labelled or not, read only when a rule exists: a rule is in use + // when it applies to a VM teardown does not remove, whoever made that VM. + let everyInstance: GcpInstance[] | Error | undefined; + for (const rule of [SAM_AGENT_FIREWALL_RULE_NAME, SAM_APP_ROUTE_FIREWALL_RULE_NAME]) { + const found = gcloud(ctx, [ + 'compute', + 'firewall-rules', + 'describe', + rule, + `--project=${project}`, + '--format=json', + ]); + if (found.status !== 0) { + if (gcloudNotFound(found.stderr)) continue; + // Permission denied (the box's own account cannot read firewalls) is not "absent". + items.push({ + id: `gcp:${project}:firewall:${rule}`, + place: 'in your cloud, made by SAM at runtime', + what: `firewall rule ${rule} (${project}): could not check (${gcloudReason(found.stderr)})`, + provenance: 'discovered, not recorded', + how: `gcloud compute firewall-rules describe ${rule} --project=${project} as a project owner; delete it only if no other SAM install uses ${project}`, + step: STEPS.compute, + plan: both({ + act: 'operator', + why: 'teardown could not check it with this gcloud account', + }), + }); + continue; + } + everyInstance ??= listAllInstances(ctx, project); + const usage = firewallUsage( + parseFirewallTargets(found.stdout), + everyInstance, + listed, + ctx.installationId + ); + const receipt = ctx.record.find( + (r) => + r.cloud === 'gcp' && + r.kind === 'firewall-rule' && + r.name === rule && + r.createdBy === BOOTSTRAP && + r.action === 'created' && + r.attributes?.project === project && + r.attributes?.installation === ctx.installationId && + r.attributes?.environment === SELFHOST_ENVIRONMENT && + r.attributes?.install === `https://api.${ctx.domain}` + ); + const description = `SAM installation=${ctx.installationId} environment=selfhost issuer=https://api.${ctx.domain}`; + const safe = + !!receipt?.attributes?.identity && + JSON.parse(found.stdout).id === receipt.attributes.identity && + JSON.parse(found.stdout).description === description && + usage.startsWith('no existing VM'); + items.push({ + id: `gcp:${project}:firewall:${rule}`, + place: 'in your cloud, made by SAM at runtime', + what: `firewall rule ${rule} (${project})`, + provenance: 'discovered, not recorded', + how: `gcloud compute firewall-rules delete ${rule} --project=${project}, only if no other SAM install uses ${project}; ${usage}`, + step: STEPS.compute, + plan: { + 'keep-data': { act: 'keep', why: 'the next node needs it' }, + 'remove-everything': { + ...(safe + ? { act: 'remove' as const } + : { + act: 'refused' as const, + why: 'no exclusive, current creation proof; shared or legacy rules are preserved', + }), + }, + }, + run: () => { + const current = gcloud(ctx, [ + 'compute', + 'firewall-rules', + 'describe', + rule, + `--project=${project}`, + '--format=json', + ]); + check(current, 'read firewall before deletion'); + const raw = JSON.parse(current.stdout) as { id?: string; description?: string }; + const users = firewallUsage( + parseFirewallTargets(current.stdout), + listAllInstances(ctx, project), + [], + ctx.installationId + ); + if ( + !receipt || + raw.id !== receipt.attributes?.identity || + raw.description !== description || + !users.startsWith('no existing VM') + ) + throw new Error('refused: firewall identity, owner or usage changed'); + check( + gcloud(ctx, [ + 'compute', + 'firewall-rules', + 'delete', + rule, + `--project=${project}`, + '--quiet', + ]), + 'delete owned firewall' + ); + }, + record: receipt, + }); + } + return items; +} + +function listAllInstances(ctx: TeardownContext, project: string): GcpInstance[] | Error { + const result = gcloud(ctx, [ + 'compute', + 'instances', + 'list', + `--project=${project}`, + '--format=json', + ]); + if (result.status !== 0) return new Error(gcloudReason(result.stderr)); + try { + const parsed = JSON.parse(result.stdout) as unknown; + if (!Array.isArray(parsed)) throw new Error('not a list'); + return parseUniqueInstances(parsed); + } catch (error) { + return new Error( + `unreadable instance list: ${error instanceof Error ? error.message : String(error)}` + ); + } +} + +export function parseFirewallTargets(json: string): GcpFirewallTargets | null { + try { + const raw: unknown = JSON.parse(json); + if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return null; + const v = raw as Record; + const targetTags = Array.isArray(v.targetTags) + ? v.targetTags.filter((t): t is string => typeof t === 'string') + : []; + return { + network: typeof v.network === 'string' ? lastSegment(v.network) : null, + targetTags, + targetServiceAccounts: + Array.isArray(v.targetServiceAccounts) && v.targetServiceAccounts.length > 0, + }; + } catch { + return null; + } +} + +/** + * Which VMs the rule applies to, as advice for the operator. A VM uses a rule when it is on the + * rule's network and, if the rule has target tags, carries one of them (GCP firewall semantics). + * This install's own node VMs are left out: teardown removes them. Read-only; never decides a + * deletion. + */ +export function firewallUsage( + rule: GcpFirewallTargets | null, + everyInstance: GcpInstance[] | Error, + labelled: GcpInstance[] | Error, + installationId: string | null +): string { + if (!rule || rule.targetServiceAccounts) { + return 'teardown could not read which VMs it applies to; check them before deleting it'; + } + if (everyInstance instanceof Error) { + return `teardown could not list the project's VMs to see which use it (${everyInstance.message})`; + } + const own = new Set( + (labelled instanceof Error ? [] : labelled) + .filter((i) => ownershipRefusal(i, installationId) === null) + .map((i) => i.id) + ); + const applies = (i: GcpInstance) => + (rule.network === null || i.networks.includes(rule.network)) && + (rule.targetTags.length === 0 || i.tags.some((t) => rule.targetTags.includes(t))); + const others = everyInstance.filter((i) => !own.has(i.id)); + const users = others.filter(applies); + const target = + rule.targetTags.length > 0 + ? `tag ${rule.targetTags.join(', ')}` + : `every VM on network ${rule.network ?? '?'}`; + if (users.length > 0) { + return `${users.length} other VM(s) in this project use it (${target}: ${names(users)}), so keep it`; + } + const lookalikes = others.filter( + (i) => i.labels[SAM_MANAGED_LABEL_KEY] === SAM_MANAGED_LABEL_VALUE + ); + const aside = + lookalikes.length > 0 + ? `; ${lookalikes.length} other SAM-labelled VM(s) do not carry it (${names(lookalikes)})` + : ''; + return `no existing VM in this project uses it (${target}; a VM made later may)${aside}`; +} + +function names(instances: GcpInstance[]): string { + const shown = instances.slice(0, 5).map((i) => i.name); + return instances.length > 5 + ? `${shown.join(', ')} and ${instances.length - 5} more` + : shown.join(', '); +} diff --git a/scripts/selfhost/teardown-model.ts b/scripts/selfhost/teardown-model.ts new file mode 100644 index 0000000000..7e4216bebc --- /dev/null +++ b/scripts/selfhost/teardown-model.ts @@ -0,0 +1,273 @@ +/** + * The provider-neutral core of `pnpm selfhost:teardown` (teardown.ts): what an item is, how a + * mode decides about it, and the order and bookkeeping of a removal. Nothing here knows a cloud; + * cloud specifics live in adapters (teardown-gcp.ts) that return items of this shape. + */ +import { addResource, markRemoved, readRecord } from '../../deploy/selfhost/created-resources.mjs'; + +export type Mode = 'keep-data' | 'remove-everything'; +export const MODES: readonly Mode[] = ['keep-data', 'remove-everything']; + +export type Place = + | 'on the box' + | 'in the object store' + | 'in your cloud, made by the bootstrap' + | 'in your cloud, made by SAM at runtime' + | 'outside SAM'; +export const PLACES: readonly Place[] = [ + 'on the box', + 'in the object store', + 'in your cloud, made by the bootstrap', + 'in your cloud, made by SAM at runtime', + 'outside SAM', +]; + +/** recorded: in created-resources.json. discovered: found using live exact installation/environment ownership labels. */ +/** setup steps: made by you following SAM's instructions, outside anything teardown can read. */ +export type Provenance = 'recorded' | 'discovered, not recorded' | 'from the setup steps'; + +export type Decision = + | { act: 'remove' } + /** Left by choice: the mode keeps it, or a flag it needs was not given. */ + | { act: 'keep'; why: string } + /** Left for you: teardown cannot remove it; `how` says where to click or what to run. */ + | { act: 'operator'; why: string } + /** Left because its ownership proof failed: never removed. */ + | { act: 'refused'; why: string }; + +/** Removal order: stop work, compute, cloud identity and keys, bucket contents, the box. */ +export const STEPS = { + stop: 1, + compute: 2, + identity: 3, + bucket: 4, + box: 5, + outside: 6, +} as const; +export const STEP_NAMES: Record = { + 1: 'stop taking new work', + 2: 'node VMs and disks', + 3: 'cloud identity and keys', + 4: 'bucket contents', + 5: 'the box', + 6: 'outside SAM', +}; + +export interface RecordRef { + cloud: string; + kind: string; + name: string; + /** For an entry teardown adds before acting (a discovered resource). */ + createdBy?: string; + attributes?: Record; +} + +export interface Item { + id: string; + place: Place; + what: string; + provenance: Provenance; + /** How it is removed: the command teardown runs, or what the operator does. */ + how: string; + step: number; + plan: Record; + /** Said before acting: what this destroys for good. */ + forGood?: string; + /** Items sharing a runKey share one action, run once. */ + runKey?: string; + run?: () => void; + /** + * For an item of a shared action (runKey): true when it is gone although the action failed on + * another item of the group, so the summary reports what is really left (a key file removed + * before an unrelated cache refused to go). + */ + goneDespiteGroupFailure?: () => boolean; + /** After the action: did it go? (default: yes when run() returned). */ + settle?: () => { removed: boolean; why?: string }; + /** Marked removed in the record once gone (added first when not recorded yet). */ + record?: RecordRef | RecordRef[]; + /** Already removed by an earlier run (the record's removedAt). */ + removedAt?: string; +} + +export interface Outcome { + item: Item; + status: + 'removed' | 'kept' | 'operator' | 'refused' | 'failed' | 'not attempted' | 'already removed'; + why?: string; +} + +export function decide(item: Item, mode: Mode): Decision { + return item.plan[mode]; +} + +/** + * Runs every item the mode removes, step by step. A failure ends the run after its step: later + * steps (which would remove the means to clean up what failed, such as the cloud identity behind + * undeleted VMs) are reported as not attempted, and a second run continues from there. + */ +export function execute(items: Item[], mode: Mode, recordFile: string): Outcome[] { + const outcomes: Outcome[] = []; + const ordered = [...items].sort((a, b) => a.step - b.step); + let failedStep: number | null = null; + const ran = new Map(); + for (const step of [...new Set(ordered.map((i) => i.step))]) { + const inStep = ordered.filter((i) => i.step === step); + for (const item of inStep) { + const decision = decide(item, mode); + if (decision.act !== 'remove') { + outcomes.push({ item, status: statusOf(decision), why: decision.why }); + continue; + } + if (item.removedAt) { + outcomes.push({ item, status: 'already removed', why: item.removedAt }); + continue; + } + if (failedStep !== null) { + outcomes.push({ item, status: 'not attempted', why: `step ${failedStep} failed` }); + continue; + } + const key = item.runKey ?? item.id; + if (!ran.has(key)) { + // The group's action may sit on another item of the group (a volume goes with compose down). + const runner = item.run ?? items.find((i) => (i.runKey ?? i.id) === key && i.run)?.run; + try { + runner?.(); + ran.set(key, null); + } catch (error) { + ran.set(key, error instanceof Error ? error : new Error(String(error))); + } + } + const error = ran.get(key); + if (error && !item.goneDespiteGroupFailure?.()) { + outcomes.push({ item, status: 'failed', why: error.message }); + continue; + } + const settled = item.settle?.() ?? { removed: true }; + if (!settled.removed) { + outcomes.push({ item, status: 'kept', why: settled.why }); + continue; + } + for (const ref of [item.record ?? []].flat()) markInRecord(recordFile, ref); + outcomes.push({ item, status: 'removed' }); + } + if (outcomes.some((o) => o.status === 'failed' && o.item.step === step)) failedStep = step; + } + return outcomes; +} + +function statusOf(decision: Exclude): Outcome['status'] { + return decision.act === 'keep' ? 'kept' : decision.act; +} + +function markInRecord(file: string, ref: RecordRef): void { + const known = readRecord(file).resources.some( + (r) => r.cloud === ref.cloud && r.kind === ref.kind && r.name === ref.name + ); + if (!known) { + addResource(file, { + cloud: ref.cloud, + kind: ref.kind, + name: ref.name, + action: 'created', + createdBy: ref.createdBy ?? 'discovered-by-teardown', + attributes: ref.attributes ?? {}, + }); + } + markRemoved(file, ref.cloud, ref.kind, ref.name); +} + +/** Inventory: everything found, where it is, how it would go, and what each mode does with it. */ +export function renderInventory(items: Item[]): string { + const lines: string[] = []; + for (const place of PLACES) { + const here = items.filter((i) => i.place === place); + if (here.length === 0) continue; + lines.push('', capitalise(place)); + for (const item of here) { + const gone = item.removedAt ? ` (removed ${item.removedAt})` : ''; + lines.push(` - ${item.what} [${item.provenance}]${gone}`); + lines.push(` how: ${item.how}`); + lines.push( + ` keep my data: ${describe(item.plan['keep-data'])}; remove everything: ${describe(item.plan['remove-everything'])}` + ); + if (item.forGood) lines.push(` destroys for good: ${item.forGood}`); + } + } + return lines.join('\n'); +} + +export function renderPlan(items: Item[], mode: Mode): string { + const lines: string[] = []; + for (const step of [...new Set(items.map((i) => i.step))].sort((a, b) => a - b)) { + const acting = items.filter((i) => i.step === step && decide(i, mode).act === 'remove'); + if (acting.length === 0) continue; + lines.push(`Step ${step}: ${STEP_NAMES[step] ?? ''}`); + for (const item of acting) { + lines.push(` - ${item.what}${item.removedAt ? ' (already removed)' : ''}: ${item.how}`); + if (item.forGood) lines.push(` destroys for good: ${item.forGood}`); + } + } + const left = items.filter((i) => decide(i, mode).act !== 'remove'); + if (left.length > 0) { + lines.push('Left in place:'); + for (const item of left) lines.push(` - ${item.what}: ${describe(decide(item, mode))}`); + } + return lines.join('\n'); +} + +export function renderSummary(outcomes: Outcome[]): string { + const groups: Array<[string, Outcome['status'][]]> = [ + ['Removed', ['removed', 'already removed']], + ['Left by choice', ['kept']], + ['Left for you', ['operator']], + ['Refused (ownership not proven)', ['refused']], + ['Failed', ['failed']], + ['Not attempted (an earlier step failed; run again)', ['not attempted']], + ]; + const lines: string[] = ['', 'Summary']; + const notRemoved = outcomes.filter( + (o) => o.status !== 'removed' && o.status !== 'already removed' + ); + for (const [title, statuses] of groups) { + const hits = outcomes.filter((o) => statuses.includes(o.status)); + if (hits.length === 0) continue; + lines.push(`${title}:`); + for (const { item, status, why } of hits) { + const extra = status === 'operator' ? `\n ${item.how}` : ''; + lines.push( + ` - ${item.what}${why ? ` (${status === 'already removed' ? 'earlier, ' : ''}${why})` : ''}${extra}` + ); + } + } + lines.push( + '', + notRemoved.length === 0 + ? 'Teardown removed everything it lists.' + : `Not removed: the ${notRemoved.length} item${notRemoved.length === 1 ? '' : 's'} above under Left by choice, Left for you, Refused, Failed and Not attempted; each says how to remove it.`, + 'Teardown knows only what .state/created-resources.json records and resources with live exact SAM ownership labels. Anything else you made by hand for this install (another bucket, for example one for backups) is not listed: remove it yourself.' + ); + return lines.join('\n'); +} + +function describe(decision: Decision): string { + switch (decision.act) { + case 'remove': + return 'removed'; + case 'keep': + return `kept (${decision.why})`; + case 'operator': + return `left for you (${decision.why})`; + case 'refused': + return `refused (${decision.why})`; + } +} + +function capitalise(text: string): string { + return text.charAt(0).toUpperCase() + text.slice(1); +} + +/** Same decision in both modes. */ +export function both(decision: Decision): Record { + return { 'keep-data': decision, 'remove-everything': decision }; +} diff --git a/scripts/selfhost/teardown-outside.ts b/scripts/selfhost/teardown-outside.ts new file mode 100644 index 0000000000..58abb66be2 --- /dev/null +++ b/scripts/selfhost/teardown-outside.ts @@ -0,0 +1,84 @@ +/** + * Teardown items outside SAM (teardown.ts): what the operator made by following the setup steps, + * which teardown cannot reach. Each is printed with the place to click or the command to run and + * listed as "left for you" in the summary. + */ +import type { TeardownContext } from './teardown-box'; +import { both, type Item, STEPS } from './teardown-model'; + +export function outsideItems(ctx: TeardownContext): Item[] { + const domain = ctx.domain || ''; + const keep = { act: 'keep' as const, why: 'needed to bring the install back' }; + const operator = (why: string) => ({ + 'keep-data': keep, + 'remove-everything': { act: 'operator' as const, why }, + }); + const items: Item[] = [ + { + id: 'outside:github-app', + place: 'outside SAM', + what: 'the GitHub App created through Admin → Integrations (manifest flow), if you made one', + provenance: 'from the setup steps', + how: `github.com → Settings → Developer settings → GitHub Apps (for an organization: its Settings → Developer settings → GitHub Apps) → the App whose URL is https://app.${domain} → Advanced → Delete GitHub App. Its installations go with it`, + step: STEPS.outside, + plan: operator('GitHub deletes Apps only in its own settings'), + }, + { + id: 'outside:dns', + place: 'outside SAM', + what: `DNS: the records you pointed at the box (the wildcard *.${domain}, and ${domain} itself if you made one)`, + provenance: 'from the setup steps', + how: `remove them at your DNS host (Google Cloud DNS: gcloud dns record-sets delete '*.${domain}.' --type=A --zone=, and the same for '${domain}.')`, + step: STEPS.outside, + plan: operator('teardown has no access to your DNS host'), + }, + { + id: 'outside:box', + place: 'outside SAM', + what: 'the machine itself and everything you made for it: its boot disk, its static IP, the network, subnet and firewall rules you opened for it (80/443, SSH), its service account and the bucket grant you gave it', + provenance: 'from the setup steps', + how: [ + 'delete them in your cloud console, for example on Google Cloud:', + 'gcloud compute instances delete --zone --delete-disks=all;', + 'gcloud compute addresses delete --region ;', + 'gcloud compute firewall-rules delete ;', + 'gcloud compute networks subnets delete --region ; gcloud compute networks delete (only a network you made for the box, never default);', + 'gcloud iam service-accounts delete ; and this checkout with rm -r.', + 'Teardown runs on the box, so it cannot delete the box, and it cannot tell which network or address you made for it', + ].join(' '), + step: STEPS.outside, + plan: operator('you created them; teardown runs on the box'), + }, + { + id: 'outside:accounts', + place: 'outside SAM', + what: 'OAuth clients and SMTP relay credentials you registered for this install', + provenance: 'from the setup steps', + how: 'delete or revoke them in each service (GitHub OAuth Apps, Google Cloud OAuth clients, your SMTP provider)', + step: STEPS.outside, + plan: operator('teardown has no access to those services'), + }, + { + id: 'outside:other-clouds', + place: 'in your cloud, made by SAM at runtime', + what: 'node VMs on any provider other than Google Cloud (Hetzner, Scaleway, AWS, ...)', + provenance: 'from the setup steps', + how: `before teardown, delete every node in Admin → Nodes while SAM runs; or in the provider's console delete servers labelled managed=simple-agent-manager and installation=${ctx.installationId ?? ''}`, + step: STEPS.compute, + plan: both({ act: 'operator', why: 'only the Google Cloud adapter exists so far' }), + }, + ]; + const profiles = (ctx.box.COMPOSE_PROFILES ?? '').split(',').map((p) => p.trim()); + if (profiles.includes('mail-in')) { + items.push({ + id: 'outside:mail', + place: 'outside SAM', + what: `inbound mail: the MX record agents.${domain} and the port 25 firewall rule you opened`, + provenance: 'from the setup steps', + how: `remove the MX record at your DNS host; Google Cloud: gcloud compute firewall-rules delete sam-smtp-in --project `, + step: STEPS.outside, + plan: operator('you created them by hand (README, Inbound agent email)'), + }); + } + return items; +} diff --git a/scripts/selfhost/teardown-state-dir.ts b/scripts/selfhost/teardown-state-dir.ts new file mode 100644 index 0000000000..a6aa3a1dfb --- /dev/null +++ b/scripts/selfhost/teardown-state-dir.ts @@ -0,0 +1,232 @@ +/** + * Teardown items for the box's state directory (teardown-box.ts lists them with the others): + * the key file, a legacy platform-keys.json, and everything else in `.state` except the record. + * Emptying it survives read-only trees (Go's module cache) and an entry it cannot remove, so the + * secrets always go first and the summary names what is left (box round R12). + */ +import { chmodSync, existsSync, lstatSync, readdirSync, realpathSync, rmSync } from 'node:fs'; +import { homedir } from 'node:os'; +import { basename, isAbsolute, join, relative, resolve } from 'node:path'; + +import { STATE_CACHE_EXCLUDES } from './backup-lib'; +import { RECORD_FILE } from './install-record'; +import type { TeardownContext } from './teardown-box'; +import { both, type Item, STEPS } from './teardown-model'; + +const KEY_FILE = join('key-agent', 'kek'); +const LEGACY_KEYS = 'platform-keys.json'; + +export function stateItems(ctx: TeardownContext): Item[] { + if (!existsSync(ctx.stateDir)) return []; + const items: Item[] = []; + const keyFile = join(ctx.stateDir, KEY_FILE); + const legacyKeys = join(ctx.stateDir, LEGACY_KEYS); + const keepKey = !ctx.options.destroyKey; + const keyDecision = { + 'keep-data': { act: 'keep' as const, why: 'keep my data keeps the key' }, + 'remove-everything': ctx.options.destroyKey + ? { act: 'remove' as const } + : { act: 'keep' as const, why: 'pass --destroy-key to delete it' }, + }; + if (existsSync(keyFile)) { + items.push({ + id: 'box:key-file', + place: 'on the box', + what: `key file ${keyFile} (opens the sealed bundles)`, + provenance: 'discovered, not recorded', + how: `rm ${keyFile}`, + step: STEPS.box, + plan: keyDecision, + forGood: + 'every sealed bundle and every backup of this box sealed with this key can never be opened again, unless you keep a copy', + runKey: 'state', + goneDespiteGroupFailure: () => isGone(keyFile), + record: { cloud: 'box', kind: 'key-file', name: keyFile, createdBy: 'deploy' }, + }); + } + if (existsSync(legacyKeys)) { + items.push({ + id: 'box:platform-keys', + place: 'on the box', + what: `${legacyKeys} (plaintext platform keys of a legacy-plaintext box)`, + provenance: 'discovered, not recorded', + how: `rm ${legacyKeys}`, + step: STEPS.box, + plan: keyDecision, + forGood: 'the box copy of the platform keys; backups hold their own copy', + runKey: 'state', + goneDespiteGroupFailure: () => isGone(legacyKeys), + record: { cloud: 'box', kind: 'platform-keys', name: legacyKeys, createdBy: 'deploy' }, + }); + } + const state = ctx.record.find((r) => r.cloud === 'box' && r.kind === 'state-dir'); + items.push({ + id: 'box:state', + place: 'on the box', + what: `${ctx.stateDir} (sealed bundles, generated config, deploy project, celld binary, caches, secrets.env)`, + provenance: state ? 'recorded' : 'discovered, not recorded', + how: `rm -r everything in ${ctx.stateDir} except ${RECORD_FILE} and a key that is kept`, + step: STEPS.box, + plan: { + 'keep-data': { act: 'keep', why: 'keep my data keeps the bundles and state' }, + 'remove-everything': { act: 'remove' }, + }, + removedAt: state?.removedAt, + runKey: 'state', + run: () => clearState(ctx, keepKey), + record: [ + { cloud: 'box', kind: 'state-dir', name: ctx.stateDir, createdBy: 'deploy' }, + // The install itself is gone with its state; the id stays readable for a resumed run. + ...ctx.record + .filter((r) => r.cloud === 'box' && r.kind === 'installation') + .map((r) => ({ cloud: 'box', kind: 'installation', name: r.name })), + ], + }); + items.push({ + id: 'box:record', + place: 'on the box', + what: `${ctx.recordFile} (this record: teardown's receipt)`, + provenance: 'recorded', + how: `rm ${ctx.recordFile} by hand once you no longer need it`, + step: STEPS.box, + plan: both({ act: 'keep', why: 'the receipt a second run resumes from' }), + }); + return items; +} + +/** + * True only when the path provably does not exist (ENOENT). existsSync also answers false for a + * path it may not look at (EACCES) and for a dangling link, which must not read as removed. + */ +function isGone(path: string): boolean { + try { + lstatSync(path); + return false; + } catch (error) { + return (error as NodeJS.ErrnoException).code === 'ENOENT'; + } +} + +/** Everything in .state except the record, and the keys when they are kept. */ +function clearState(ctx: TeardownContext, keepKey: boolean): void { + assertStateDir(ctx); + const left = clearStateEntries(ctx.stateDir, keepKey, ctx.removeTree); + if (left.length > 0) throw new Error(describeLeftovers(ctx.stateDir, left)); +} + +export interface Leftover { + path: string; + /** A rebuildable cache (STATE_CACHE_EXCLUDES): holds no secret. */ + cache: boolean; + error: string; +} + +/** + * Removes every entry of the state directory except the record (and the key, when kept), and + * returns what could not be removed. Caches go last and a failure does not stop the others, so + * an unremovable build cache can never leave the sealed bundles or key material behind + * (box round R12: the Go module cache's read-only directories stopped the whole removal). + */ +export function clearStateEntries( + stateDir: string, + keepKey: boolean, + remove: (path: string) => void = removeTree +): Leftover[] { + const isCache = (entry: string) => STATE_CACHE_EXCLUDES.includes(entry); + const entries = readdirSync(stateDir) + .filter((entry) => entry !== RECORD_FILE && !(keepKey && entry === LEGACY_KEYS)) + .sort((a, b) => Number(isCache(a)) - Number(isCache(b)) || a.localeCompare(b)); + const left: Leftover[] = []; + const attempt = (path: string, cache: boolean) => { + try { + remove(path); + } catch (error) { + left.push({ path, cache, error: error instanceof Error ? error.message : String(error) }); + } + }; + for (const entry of entries) { + const path = join(stateDir, entry); + if (entry === 'key-agent' && keepKey) { + // Not a plain directory (a link): left whole, since the kept key is behind it. + if (!lstatSync(path).isDirectory()) continue; + for (const inner of readdirSync(path)) { + if (inner !== basename(KEY_FILE)) attempt(join(path, inner), false); + } + continue; + } + attempt(path, isCache(entry)); + } + return left; +} + +function describeLeftovers(stateDir: string, left: Leftover[]): string { + const secretsLeft = left.some((l) => !l.cache); + const lines = left.map( + (l) => `${l.path}${l.cache ? ' (a build cache, no secrets)' : ''}: ${l.error}` + ); + return [ + `could not remove ${left.length} of the entries in ${stateDir}: ${lines.join('; ')}.`, + secretsLeft + ? 'Some of what is left is not a cache and may hold sealed bundles or keys.' + : 'Everything else in it is gone, including the sealed bundles and key material.', + `Remove what is left by hand: chmod -R u+w && rm -r , then run teardown again.`, + ].join(' '); +} + +/** + * `rm -r` that also removes trees with read-only directories. Go makes every module-cache + * directory 0555 (`go-cache/mod`), and deleting an entry needs write permission on its parent. + * Directories are made owner-writable first; symbolic links are never followed. + */ +export function removeTree(path: string): void { + makeDirsWritable(path); + rmSync(path, { recursive: true, force: true }); +} + +function makeDirsWritable(path: string): void { + const stat = lstatSync(path, { throwIfNoEntry: false }); + if (!stat?.isDirectory()) return; + if ((stat.mode & 0o700) !== 0o700) { + try { + chmodSync(path, (stat.mode & 0o7777) | 0o700); + } catch { + // Not ours to change (another owner): rmSync reports what it cannot remove. + } + } + for (const entry of readdirSync(path)) makeDirsWritable(join(path, entry)); +} + +/** True for `/`, the home directory, and any directory that contains the checkout. */ +export function isProtectedDir(path: string, selfhostDir: string): boolean { + const target = resolve(path); + if (target === '/' || target === resolve(homedir())) return true; + const rel = relative(target, resolve(selfhostDir)); + return rel === '' || (!rel.startsWith('..') && !isAbsolute(rel)); +} + +/** + * The state directory comes from .env or --state-dir, so prove it is SAM's before emptying it + * (security review M1): not a protected directory, and either recorded as this state dir or + * holding the key agent's files. + */ +function assertStateDir(ctx: TeardownContext): void { + // Also through symbolic links: a .state that links to the home directory is still refused. + if ( + isProtectedDir(ctx.stateDir, ctx.selfhostDir) || + isProtectedDir(realpathSync(ctx.stateDir), ctx.selfhostDir) + ) { + throw new Error(`refused: ${ctx.stateDir} is /, your home or contains the checkout`); + } + const recordedHere = ctx.record.some( + (r) => r.cloud === 'box' && r.kind === 'state-dir' && resolve(r.name) === resolve(ctx.stateDir) + ); + if ( + !recordedHere && + !existsSync(join(ctx.stateDir, 'key-agent')) && + !existsSync(join(ctx.stateDir, LEGACY_KEYS)) + ) { + throw new Error( + `refused: ${ctx.stateDir} is neither recorded as this install's state nor holds its keys` + ); + } +} diff --git a/scripts/selfhost/teardown-state.test.ts b/scripts/selfhost/teardown-state.test.ts new file mode 100644 index 0000000000..e4b152ce9b --- /dev/null +++ b/scripts/selfhost/teardown-state.test.ts @@ -0,0 +1,190 @@ +/** + * Emptying .state when something in it cannot be removed (box round R12: the Go module cache's + * read-only directories). The secrets must already be gone, and the summary must say exactly what + * is left. teardown.test.ts covers the real read-only tree through the real entry point; here a + * removal failure that no chmod can fix (another owner's file) is injected, through the same + * items and executor teardown.ts runs. + */ +import { + chmodSync, + existsSync, + mkdirSync, + mkdtempSync, + readdirSync, + rmSync, + symlinkSync, + writeFileSync, +} from 'node:fs'; +import { homedir, tmpdir } from 'node:os'; +import { join } from 'node:path'; + +import { afterEach, beforeEach, describe, expect, it } from 'vitest'; + +import { addResource } from '../../deploy/selfhost/created-resources.mjs'; +import { type TeardownContext } from './teardown-box'; +import { execute, renderSummary } from './teardown-model'; +import { clearStateEntries, removeTree, stateItems } from './teardown-state-dir'; + +let root: string; +let state: string; + +function seedState(): void { + mkdirSync(join(state, 'key-agent', 'bundles'), { recursive: true }); + writeFileSync(join(state, 'key-agent', 'kek'), 'fake-key-material'); + writeFileSync(join(state, 'key-agent', 'bundles', 'b1.sealed'), 'fake-sealed'); + writeFileSync(join(state, 'secrets.env'), 'BOOTSTRAP_OWNER_EMAIL=owner@example.com\n'); + mkdirSync(join(state, 'go-cache', 'mod'), { recursive: true }); + writeFileSync(join(state, 'go-cache', 'mod', 'x'), 'cache'); + mkdirSync(join(state, 'project'), { recursive: true }); +} + +function context(remove: (path: string) => void): TeardownContext { + const recordFile = join(state, 'created-resources.json'); + addResource(recordFile, { + cloud: 'box', + kind: 'state-dir', + name: state, + action: 'created', + createdBy: 'deploy', + attributes: {}, + }); + return { + box: {}, + envFile: join(root, '.env'), + stateDir: state, + composeFiles: [], + // No docker here: volume listing fails, so no volume items. + run: () => ({ status: 1, stdout: '', stderr: 'no docker' }), + now: () => 0, + log: () => {}, + mode: 'remove-everything', + options: { deleteBackups: false, destroyKey: true, adoptDiscovered: false, gcpProjects: [] }, + record: [ + { + cloud: 'box', + kind: 'state-dir', + name: state, + action: 'created', + createdBy: 'deploy', + attributes: {}, + }, + ], + recordFile, + domain: 'sam.example.com', + installationId: null, + selfhostDir: join(root, 'checkout', 'deploy', 'selfhost'), + removeTree: remove, + }; +} + +const failOn = (name: string) => (path: string) => { + if (path.endsWith(name)) throw new Error(`EPERM: operation not permitted, rmdir '${path}'`); + removeTree(path); +}; + +beforeEach(() => { + root = mkdtempSync(join(tmpdir(), 'teardown-state-')); + state = join(root, '.state'); + mkdirSync(state); + seedState(); +}); +afterEach(() => rmSync(root, { recursive: true, force: true })); + +describe('emptying .state when an entry cannot be removed', () => { + it('removes the secrets first and names the cache that is left', () => { + const ctx = context(failOn('go-cache')); + const outcomes = execute( + stateItems(ctx).filter((i) => i.id.startsWith('box:key') || i.id === 'box:state'), + 'remove-everything', + ctx.recordFile + ); + // Secrets and bundles are gone; only the cache and the record remain. + expect(readdirSync(state).sort()).toEqual(['created-resources.json', 'go-cache']); + const byId = new Map(outcomes.map((o) => [o.item.id, o])); + expect(byId.get('box:key-file')?.status).toBe('removed'); + const stateOutcome = byId.get('box:state'); + expect(stateOutcome?.status).toBe('failed'); + expect(stateOutcome?.why).toContain(`${join(state, 'go-cache')} (a build cache, no secrets)`); + expect(stateOutcome?.why).toContain('including the sealed bundles and key material'); + expect(stateOutcome?.why).toContain('chmod -R u+w'); + const summary = renderSummary(outcomes); + expect(summary).toMatch(/Removed:\n {2}- key file /); + expect(summary).toMatch(/Failed:\n {2}- .*\.state .*go-cache/); + }); + + it('says plainly when what is left is not a cache', () => { + const ctx = context(failOn('project')); + const outcomes = execute( + stateItems(ctx).filter((i) => i.id.startsWith('box:key') || i.id === 'box:state'), + 'remove-everything', + ctx.recordFile + ); + const stateOutcome = outcomes.find((o) => o.item.id === 'box:state'); + expect(stateOutcome?.why).toContain('may hold sealed bundles or keys'); + expect(existsSync(join(state, 'go-cache'))).toBe(false); + expect(existsSync(join(state, 'key-agent'))).toBe(false); + }); + + it('removes caches last, after every other entry', () => { + const order: string[] = []; + const left = clearStateEntries(state, false, (path) => { + order.push(path.slice(state.length + 1)); + removeTree(path); + }); + expect(left).toEqual([]); + expect(order.at(-1)).toBe('go-cache'); + expect(order).not.toContain('created-resources.json'); + }); + + it('does not report the key file removed when it cannot be looked at (security review L1)', () => { + const keyDir = join(state, 'key-agent'); + // The removal fails on key-agent and leaves it unsearchable: the key file is still there. + const blocked = context((path) => { + if (path.endsWith('key-agent')) { + chmodSync(keyDir, 0o000); + throw new Error(`EACCES: permission denied, rmdir '${path}'`); + } + removeTree(path); + }); + try { + const again = execute( + stateItems(blocked).filter((i) => i.id.startsWith('box:key') || i.id === 'box:state'), + 'remove-everything', + blocked.recordFile + ); + expect(again.find((o) => o.item.id === 'box:key-file')?.status).toBe('failed'); + } finally { + chmodSync(keyDir, 0o700); + } + }); + + it('refuses a .state that is a link to the home directory (security review L2)', () => { + const link = join(root, 'linked-state'); + symlinkSync(homedir(), link); + const ctx = { ...context(removeTree), stateDir: link }; + ctx.record = [ + ...ctx.record, + { + cloud: 'box', + kind: 'state-dir', + name: link, + action: 'created', + createdBy: 'deploy', + attributes: {}, + }, + ]; + const outcomes = execute( + stateItems(ctx).filter((i) => i.id === 'box:state'), + 'remove-everything', + ctx.recordFile + ); + expect(outcomes[0]?.status).toBe('failed'); + expect(outcomes[0]?.why).toContain('is /, your home or contains the checkout'); + }); + + it('keeps the key file when asked and still removes the rest of key-agent', () => { + const left = clearStateEntries(state, true); + expect(left).toEqual([]); + expect(readdirSync(join(state, 'key-agent'))).toEqual(['kek']); + }); +}); diff --git a/scripts/selfhost/teardown.test.ts b/scripts/selfhost/teardown.test.ts new file mode 100644 index 0000000000..38e7bea269 --- /dev/null +++ b/scripts/selfhost/teardown.test.ts @@ -0,0 +1,261 @@ +/** Real CLI trigger against disposable files and provider executables; no cloud calls. */ +import { + chmodSync, + existsSync, + mkdirSync, + mkdtempSync, + readFileSync, + rmSync, + writeFileSync, +} from 'node:fs'; +import { join, resolve } from 'node:path'; +import { afterEach, beforeEach, describe, expect, it } from 'vitest'; +import { addResource } from '../../deploy/selfhost/created-resources.mjs'; +import { runTsx } from './deploy-harness'; +import { composeProjectFor, recordInstall, recordPath } from './install-record'; + +const CLI = resolve(import.meta.dirname, 'teardown.ts'); +const OWN = 'a'.repeat(32); +const DOMAIN = 'sam.example.com'; +let dir: string, state: string, env: string, bin: string; +beforeEach(() => { + mkdirSync(resolve('.tmp'), { recursive: true }); + dir = mkdtempSync(resolve('.tmp/teardown-')); + state = join(dir, '.state'); + bin = join(dir, 'bin'); + mkdirSync(state); + mkdirSync(bin); + env = join(dir, '.env'); + writeFileSync(env, `SAM_DOMAIN=${DOMAIN}\nGCP_PROJECT=sam-test-proj\n`, { mode: 0o600 }); + writeFileSync(join(state, 'platform-keys.json'), JSON.stringify({ SAM_INSTALLATION_ID: OWN }), { + mode: 0o600, + }); + recordInstall(state, env, { SAM_DOMAIN: DOMAIN }, OWN); + executable( + 'docker', + `fs.appendFileSync(process.env.CALLS, 'docker '+process.argv.slice(2).join(' ')+'\\n');` + ); + executable( + 'gcloud', + ` + const args=process.argv.slice(2), cmd=args.join(' '); + fs.appendFileSync(process.env.CALLS, 'gcloud '+cmd+'\\n'); + if(cmd.startsWith('compute instances list')) console.log(process.env.VMS ?? '[]'); + else if(cmd.startsWith('compute instances describe')) console.log(process.env.DESCRIBED ?? process.env.VM); + else if(cmd.startsWith('compute instances delete')) {} + else if(cmd.startsWith('compute firewall-rules describe')) { + if(process.env.FIREWALL==='yes' && args[3]==='sam-allow-agent') console.log(JSON.stringify({id: process.env.CHANGED==='yes'?'999':'123',name:args[3],network:'x/networks/default',targetTags:['sam-agent'],description:'SAM installation=${OWN} environment=selfhost issuer=https://api.${DOMAIN}'})); + else {console.error('NOT_FOUND');process.exit(1);} + } + else if(cmd.startsWith('compute firewall-rules delete')) {} + else if(cmd.startsWith('iam workload-identity-pools providers list')) console.log(process.env.FOREIGN==='pool' ? '[{"name":"foreign","oidc":{"issuerUri":"foreign"}}]' : '[]'); + else if(cmd.startsWith('iam service-accounts get-iam-policy')) console.log(process.env.FOREIGN==='account' ? '{"bindings":[{"role":"foreign","members":["foreign"]}]}' : '{}'); + else if(cmd.startsWith('iam service-accounts keys list')) console.log('[]'); + else if(cmd.startsWith('iam service-accounts describe')) console.log(JSON.stringify({uniqueId:'acct-id',description:'Creates and deletes SAM workspace VMs and their firewall rules for https://api.${DOMAIN}'})); + else if(cmd.startsWith('iam workload-identity-pools providers describe')) console.log(JSON.stringify({name:'projects/123/locations/global/workloadIdentityPools/pool/providers/provider',oidc:{issuerUri:'https://api.${DOMAIN}'}})); + else if(cmd.includes('describe')) console.log(JSON.stringify({uniqueId:'acct-id',name:'projects/123/locations/global/workloadIdentityPools/pool',description:'Dedicated to the SAM install whose token issuer is https://api.${DOMAIN}'})); + else if(cmd.includes('delete')) {} + else { console.error('unsupported fake command'); process.exit(1); } + ` + ); +}); +afterEach(() => rmSync(dir, { recursive: true, force: true })); +function executable(name: string, script: string) { + const file = join(bin, name); + writeFileSync(file, `#!/usr/bin/env node\nimport * as fs from 'node:fs';\n${script}\n`); + chmodSync(file, 0o755); +} +function run(args: string[], extra: Record = {}) { + return runTsx(CLI, ['--box-env', env, '--state-dir', state, ...args], { + PATH: `${bin}:${process.env.PATH}`, + CALLS: join(dir, 'calls'), + ...extra, + }); +} +const calls = () => + existsSync(join(dir, 'calls')) ? readFileSync(join(dir, 'calls'), 'utf8') : ''; +function cloudReceipt(kind: string, name: string, extra: Record = {}) { + addResource(recordPath(state), { + cloud: 'gcp', + kind, + name, + action: 'created', + createdBy: 'gcp-bootstrap', + attributes: { + project: 'sam-test-proj', + install: `https://api.${DOMAIN}`, + environment: 'selfhost', + installation: OWN, + identity: '123', + ...extra, + }, + }); +} +describe('teardown ownership at the CLI boundary', () => { + it('inventory and dry run do not mutate files or provider resources', async () => { + expect((await run([])).status).toBe(0); + expect((await run(['--remove-everything', '--dry-run'])).status).toBe(0); + expect(existsSync(env)).toBe(true); + expect(calls()).not.toMatch(/docker compose .* (stop|down)|firewall-rules delete/); + }); + it('keeps data and all workload identities so the original install can restart', async () => { + cloudReceipt('workload-identity-pool', 'pool', { + identity: 'projects/123/locations/global/workloadIdentityPools/pool', + }); + cloudReceipt('workload-identity-provider', 'provider', { pool: 'pool' }); + cloudReceipt('service-account', 'acct'); + cloudReceipt('iam-binding', 'binding', { + account: 'acct', + member: 'serviceAccount:acct', + role: 'roles/compute.securityAdmin', + }); + const result = await run(['--keep-data', '--confirm', DOMAIN]); + expect(result.status, result.out).toBe(0); + expect(calls()).not.toContain('gcloud iam'); + expect(calls()).not.toContain('remove-iam-policy-binding'); + expect(existsSync(env)).toBe(true); + expect(existsSync(join(state, 'platform-keys.json'))).toBe(true); + expect(calls()).toContain(composeProjectFor({ SAM_DOMAIN: DOMAIN }, state)); + expect(calls()).toContain('stop'); + }); + it('deletes owned unused firewall rules with exact id and owner proof', async () => { + cloudReceipt('firewall-rule', 'sam-allow-agent'); + const result = await run(['--remove-everything', '--confirm', DOMAIN], { FIREWALL: 'yes' }); + expect(result.status, result.out).toBe(0); + expect(calls()).toContain('firewall-rules delete sam-allow-agent'); + expect(calls()).not.toContain('firewall-rules delete sam-allow-app-routes'); + expect(existsSync(env)).toBe(false); + }); + it.each(['unrecorded', 'foreign', 'replaced'])('preserves %s firewall rules', async (kind) => { + if (kind !== 'unrecorded') + cloudReceipt( + 'firewall-rule', + 'sam-allow-agent', + kind === 'foreign' ? { installation: 'b'.repeat(32) } : {} + ); + const result = await run(['--remove-everything', '--confirm', DOMAIN], { + FIREWALL: 'yes', + CHANGED: kind === 'replaced' ? 'yes' : 'no', + }); + expect(result.status, result.out).toBe(1); + expect(calls()).not.toContain('firewall-rules delete'); + }); + it('refuses the legacy compose project without a creation receipt', async () => { + rmSync(recordPath(state)); + const result = await run(['--keep-data', '--confirm', DOMAIN]); + expect(result.status, result.out).toBe(1); + expect(calls()).not.toMatch(/docker compose .* (stop|down)/); + }); + it('cannot adopt cloud resources by name', async () => { + const result = await run(['--remove-everything', '--adopt-discovered', '--confirm', DOMAIN]); + expect(result.status).toBe(1); + expect(calls()).toBe(''); + }); +}); + +it('never adopts an explicit legacy shared compose name during deploy recording', async () => { + const box = { SAM_DOMAIN: DOMAIN, COMPOSE_PROJECT_NAME: 'sam-selfhost' }; + rmSync(recordPath(state)); + recordInstall(state, env, box, OWN); + writeFileSync( + env, + `SAM_DOMAIN=${DOMAIN}\nCOMPOSE_PROJECT_NAME=sam-selfhost\nGCP_PROJECT=sam-test-proj\n`, + { mode: 0o600 } + ); + const result = await run(['--remove-everything', '--confirm', DOMAIN]); + expect(result.status, result.out).toBe(1); + expect(calls()).not.toContain(' down '); + expect(existsSync(env)).toBe(true); + expect(existsSync(join(state, 'platform-keys.json'))).toBe(true); +}); +it('different disposable install directories receive different compose identities', () => { + expect(composeProjectFor({ SAM_DOMAIN: DOMAIN }, state)).not.toBe( + composeProjectFor({ SAM_DOMAIN: DOMAIN }, join(dir, 'other')) + ); +}); + +function wifReceipts() { + cloudReceipt('workload-identity-pool', 'pool', { + identity: 'projects/123/locations/global/workloadIdentityPools/pool', + pool: 'pool', + }); + cloudReceipt('workload-identity-provider', 'provider', { + identity: 'projects/123/locations/global/workloadIdentityPools/pool/providers/provider', + pool: 'pool', + }); + cloudReceipt('service-account', 'acct', { identity: 'acct-id', pool: 'pool' }); +} +it('removes recorded owned WIF resources and rechecks their current identity', async () => { + wifReceipts(); + const result = await run(['--remove-everything', '--confirm', DOMAIN]); + expect(result.status, result.out).toBe(0); + expect(calls()).toContain('providers delete provider'); + expect(calls()).toContain('workload-identity-pools delete pool'); + expect(calls()).toContain('service-accounts delete acct'); + expect(calls().indexOf('providers delete provider')).toBeLessThan( + calls().indexOf('workload-identity-pools delete pool') + ); +}); +it.each(['pool', 'account'])( + 'preserves a recorded %s when foreign members appeared', + async (target) => { + wifReceipts(); + const result = await run(['--remove-everything', '--confirm', DOMAIN], { FOREIGN: target }); + expect(result.status, result.out).toBe(1); + expect(calls()).not.toContain( + target === 'pool' ? 'workload-identity-pools delete pool' : 'service-accounts delete acct' + ); + expect(existsSync(env)).toBe(true); + } +); + +function ownedVm() { + return { + id: '123456', + name: 'sam-node-same-prefix', + zone: 'projects/sam-test-proj/zones/europe-west1-b', + labels: { + managed: 'simple-agent-manager', + installation: OWN, + env: 'selfhost', + node: 'node-id', + }, + disks: [], + tags: { items: ['sam-agent'] }, + networkInterfaces: [{ network: 'x/networks/default' }], + }; +} +it('deletes a real-trigger owned node while preserving an identically named foreign installation', async () => { + const own = ownedVm(); + const foreign = { + ...ownedVm(), + id: '654321', + name: 'sam-node-same-prefix-other', + labels: { ...own.labels, installation: 'b'.repeat(32) }, + }; + const result = await run(['--keep-data', '--confirm', DOMAIN], { + VMS: JSON.stringify([own, foreign]), + VM: JSON.stringify(own), + }); + expect(result.status, result.out).toBe(1); // foreign explicitly refused and kept + expect(calls()).toContain('instances delete sam-node-same-prefix '); + expect(calls()).not.toContain('instances delete sam-node-same-prefix-other'); +}); +it.each(['changed-id', 'changed-owner', 'duplicate', 'malformed'])( + 'refuses %s VM inventory before destructive deletion', + async (kind) => { + const own = ownedVm(); + const described = { + ...own, + id: kind === 'changed-id' ? '999' : own.id, + labels: { ...own.labels, installation: kind === 'changed-owner' ? 'b'.repeat(32) : OWN }, + }; + const result = await run(['--keep-data', '--confirm', DOMAIN], { + VMS: kind === 'malformed' ? '{}' : JSON.stringify(kind === 'duplicate' ? [own, own] : [own]), + VM: JSON.stringify(own), + DESCRIBED: JSON.stringify(described), + }); + expect(result.status, result.out).toBe(1); + expect(calls()).not.toContain('instances delete'); + } +); diff --git a/scripts/selfhost/teardown.ts b/scripts/selfhost/teardown.ts new file mode 100644 index 0000000000..9ca626d26a --- /dev/null +++ b/scripts/selfhost/teardown.ts @@ -0,0 +1,264 @@ +/** + * `pnpm selfhost:teardown`: removes what a self-hosted install created or helped create. + * + * pnpm selfhost:teardown inventory (read only, the default) + * pnpm selfhost:teardown --keep-data [--dry-run] --confirm + * stop and delete owned node VMs; keep workload identity, bucket, backups, key file, + * bundles, .env and state, so `docker compose up -d` and the bootstrap bring it back + * pnpm selfhost:teardown --remove-everything [--dry-run] --confirm + * also the bucket contents, compose volumes and images, .state and .env + * --delete-backups also delete local backups (never without this flag) + * --destroy-key also delete the key file / schedule the cloud KMS key's destruction + * --gcp-project a Google Cloud project nodes ran in (default: GCP_PROJECT in .env, plus + * every project the bootstrap recorded); repeatable, replaces GCP_PROJECT + * --box-env , --state-dir as for the other selfhost commands + * + * What may be removed comes from `.state/created-resources.json` (install-record.ts and the + * bootstraps write it at creation time), or live exact installation/environment ownership labels. + * Legacy resources found only by name are preserved. Order and bookkeeping: teardown-model.ts. Items: teardown-box.ts + * (box, bucket, outside) and teardown-gcp.ts (Google Cloud). Re-running continues after a failure. + */ +import { existsSync, readFileSync } from 'node:fs'; +import { dirname, join, resolve } from 'node:path'; +import { createInterface } from 'node:readline/promises'; +import { parseArgs } from 'node:util'; + +import { normalizeInstallationId } from '../../apps/api/src/services/node-provider-labels'; +import { type CreatedResource, readRecord } from '../../deploy/selfhost/created-resources.mjs'; +import { log, runCommand, SELFHOST_DIR } from './backup-cli'; +import { composeFilesFor } from './backup-lib'; +import { recordPath } from './install-record'; +import { assertPrivateFile, parseDotenv } from './secret-files'; +import { boxItems, bucketItems, type TeardownContext } from './teardown-box'; +import { gcpItems } from './teardown-gcp'; +import { + execute, + type Item, + type Mode, + renderInventory, + renderPlan, + renderSummary, +} from './teardown-model'; +import { outsideItems } from './teardown-outside'; + +function parse() { + const { values } = parseArgs({ + options: { + 'keep-data': { type: 'boolean', default: false }, + 'remove-everything': { type: 'boolean', default: false }, + 'dry-run': { type: 'boolean', default: false }, + confirm: { type: 'string' }, + 'delete-backups': { type: 'boolean', default: false }, + 'destroy-key': { type: 'boolean', default: false }, + + 'gcp-project': { type: 'string', multiple: true }, + 'box-env': { type: 'string' }, + 'state-dir': { type: 'string' }, + }, + }); + if (values['keep-data'] && values['remove-everything']) { + throw new Error('choose one of --keep-data and --remove-everything'); + } + const mode: Mode | undefined = values['keep-data'] + ? 'keep-data' + : values['remove-everything'] + ? 'remove-everything' + : undefined; + if ((values['delete-backups'] || values['destroy-key']) && mode !== 'remove-everything') { + throw new Error('--delete-backups and --destroy-key go with --remove-everything only'); + } + return { values, mode }; +} + +function installationFromLegacyKeys(stateDir: string): string | null { + try { + const keys = JSON.parse(readFileSync(join(stateDir, 'platform-keys.json'), 'utf8')) as unknown; + const id = (keys as { SAM_INSTALLATION_ID?: unknown }).SAM_INSTALLATION_ID; + return typeof id === 'string' ? normalizeInstallationId(id) : null; + } catch { + return null; + } +} + +/** + * The installation id that proves node VM ownership. Only an unambiguous one counts (security + * review M2): exactly one recorded id, for this .env's domain, agreeing with platform-keys.json + * when that file exists. Anything else leaves the id unknown, so every VM is refused. + */ +function resolveInstallation( + record: CreatedResource[], + domain: string | undefined, + legacyId: string | null +): { entry?: CreatedResource; recordedId: string | null; id: string | null; problem?: string } { + const entries = record.filter((r) => r.cloud === 'box' && r.kind === 'installation'); + const ids = [...new Set(entries.map((r) => normalizeInstallationId(r.name)))]; + const entry = entries.at(-1); + if (entries.length === 0) return { recordedId: null, id: legacyId }; + if (ids.length !== 1 || !ids[0]) { + return { + entry, + recordedId: null, + id: null, + problem: `the record names ${ids.length} installation ids`, + }; + } + const id = ids[0]; + if (domain && entries.some((r) => r.attributes?.domain !== domain)) { + return { + entry, + recordedId: null, + id: null, + problem: `the record is for another domain than ${domain}`, + }; + } + if (legacyId && legacyId !== id) { + return { + entry, + recordedId: null, + id: null, + problem: 'platform-keys.json names another installation id', + }; + } + return { entry, recordedId: id, id }; +} + +/** + * The Google Cloud projects to look in besides the bootstrap's recorded ones: --gcp-project when + * given, else GCP_PROJECT from .env (the box's project, set at install for DNS and the node pool). + */ +function resolveGcpProjects( + flags: string[] | undefined, + fromEnv: string | undefined, + envFile: string +): { projects: string[]; source: string } { + if (flags && flags.length > 0) return { projects: flags, source: 'from --gcp-project' }; + const project = fromEnv?.trim(); + if (project) return { projects: [project], source: `from GCP_PROJECT in ${envFile}` }; + return { projects: [], source: 'none' }; +} + +async function confirm(expected: string, given: string | undefined): Promise { + if (given !== undefined) return given === expected; + if (!process.stdin.isTTY) return false; + const rl = createInterface({ input: process.stdin, output: process.stdout }); + try { + return ( + (await rl.question(`Type the install's name (${expected}) to continue: `)).trim() === expected + ); + } finally { + rl.close(); + } +} + +async function main(): Promise { + const { values, mode } = parse(); + const envFile = resolve(values['box-env'] ?? join(SELFHOST_DIR, '.env')); + let box: Record = {}; + if (existsSync(envFile)) { + assertPrivateFile(envFile); + box = parseDotenv(readFileSync(envFile, 'utf8'), envFile); + } + const stateDir = resolve( + dirname(envFile), + values['state-dir'] ?? box.SAM_SELFHOST_STATE_DIR ?? '.state' + ); + const recordFile = recordPath(stateDir); + const record = readRecord(recordFile).resources; + if (!existsSync(envFile) && record.length === 0) { + throw new Error(`neither ${envFile} nor ${recordFile} exists: nothing to inventory`); + } + const resolved = resolveInstallation( + record, + box.SAM_DOMAIN, + installationFromLegacyKeys(stateDir) + ); + const install = resolved.entry; + const recordedId = resolved.recordedId; + const installationId = resolved.id; + const domain = box.SAM_DOMAIN ?? install?.attributes?.domain ?? ''; + if (resolved.problem) log(`node VMs will not be touched: ${resolved.problem}`); + const gcpProjects = resolveGcpProjects(values['gcp-project'], box.GCP_PROJECT, envFile); + if (gcpProjects.projects.length > 0) { + log(`Google Cloud project ${gcpProjects.projects.join(', ')} (${gcpProjects.source})`); + } + const uid = process.getuid?.(); + const gid = process.getgid?.(); + const ctx: TeardownContext = { + box, + envFile, + stateDir, + composeFiles: composeFilesFor(box, SELFHOST_DIR), + run: runCommand, + now: () => Date.now(), + log, + user: uid !== undefined && gid !== undefined ? `${uid}:${gid}` : undefined, + mode, + options: { + deleteBackups: values['delete-backups'] ?? false, + destroyKey: values['destroy-key'] ?? false, + adoptDiscovered: false, + gcpProjects: gcpProjects.projects, + }, + record, + recordFile, + domain, + installationId, + selfhostDir: SELFHOST_DIR, + }; + const idSource = recordedId + ? 'recorded' + : installationId + ? 'discovered, not recorded: platform-keys.json' + : 'unknown'; + log( + `install ${domain || '(domain unknown)'}, installation ${installationId ?? '?'} (${idSource})` + ); + log(`record ${recordFile}${existsSync(recordFile) ? '' : ' (none yet)'}`); + const cloudItems = gcpItems(ctx); + const items: Item[] = [ + ...boxItems(ctx), + ...bucketItems(ctx), + ...cloudItems, + // The sealing key named in choice.json, unless the bootstrap's record or discovery lists it. + ...outsideItems(ctx).filter( + (i) => + !i.id.startsWith('outside:gcp-kms:') || + !cloudItems.some((c) => c.id === `gcp:kms-key:${i.id.slice('outside:gcp-kms:'.length)}`) + ), + ]; + + if (!mode) { + process.stdout.write( + `${renderInventory(items)}\n\nRead only: nothing was changed. Remove with --keep-data or --remove-everything (add --dry-run first).\n` + ); + return 0; + } + process.stdout.write( + `\nPlan (${mode === 'keep-data' ? 'keep my data' : 'remove everything'}):\n${renderPlan(items, mode)}\n` + ); + if (values['dry-run']) { + process.stdout.write('\nDry run: nothing was changed.\n'); + return 0; + } + const name = domain || installationId; + if (!name) + throw new Error( + 'cannot name this install (no SAM_DOMAIN, no record): refusing to remove anything' + ); + if (!(await confirm(name, values.confirm))) { + throw new Error( + `confirmation did not match: pass --confirm ${name} to remove what the plan lists` + ); + } + const outcomes = execute(items, mode, recordFile); + process.stdout.write(`${renderSummary(outcomes)}\n`); + return outcomes.some((o) => ['failed', 'refused', 'not attempted'].includes(o.status)) ? 1 : 0; +} + +main().then( + (code) => process.exit(code), + (error: unknown) => { + console.error(`[selfhost] ${error instanceof Error ? error.message : String(error)}`); + process.exit(1); + } +); diff --git a/scripts/selfhost/testdata/fake-docker.mjs b/scripts/selfhost/testdata/fake-docker.mjs new file mode 100755 index 0000000000..f4eca4d4b5 --- /dev/null +++ b/scripts/selfhost/testdata/fake-docker.mjs @@ -0,0 +1,30 @@ +#!/usr/bin/env node +// Fake `docker compose ... stop|start celld` for backup-entrypoint.test.ts. Stopping celld applies +// $FAKE_STATE/on-stop.json once: the writes celld made between the live pass and its shutdown. +import { + appendFileSync, + existsSync, + mkdirSync, + readFileSync, + rmSync, + writeFileSync, +} from 'node:fs'; +import { dirname, join } from 'node:path'; + +const state = process.env.FAKE_STATE; +const args = process.argv.slice(2); +appendFileSync(join(state, 'calls.log'), `docker ${args.join(' ')}\n`); +if (args[0] !== 'compose') process.exit(2); +const [action, service] = args.slice(-2); +if (service !== 'celld') process.exit(2); +writeFileSync(join(state, 'celld'), action === 'stop' ? 'stopped' : 'running'); +const onStop = join(state, 'on-stop.json'); +if (action === 'stop' && existsSync(onStop)) { + const { bucketDir, remove, write } = JSON.parse(readFileSync(onStop, 'utf8')); + for (const f of remove) rmSync(join(bucketDir, f)); + for (const [f, body] of Object.entries(write)) { + mkdirSync(dirname(join(bucketDir, f)), { recursive: true }); + writeFileSync(join(bucketDir, f), body); + } + rmSync(onStop); +} diff --git a/scripts/selfhost/testdata/fake-gcloud-iam.mjs b/scripts/selfhost/testdata/fake-gcloud-iam.mjs index 5cd406b9c2..837ea6358b 100644 --- a/scripts/selfhost/testdata/fake-gcloud-iam.mjs +++ b/scripts/selfhost/testdata/fake-gcloud-iam.mjs @@ -37,7 +37,26 @@ const format = flag('format') ?? ''; if (cmd.startsWith('projects describe')) out('123456789012'); else if (cmd.startsWith('services enable')) save(); -else if (cmd.startsWith('iam workload-identity-pools providers')) { +else if (cmd.startsWith('compute firewall-rules')) { + const [, , op, id] = words; + db.firewalls ??= {}; + if (op === 'describe') { + if (!db.firewalls[id]) fail('NOT_FOUND'); + if (format === 'value(id)') out(db.firewalls[id].id); + else out(JSON.stringify(db.firewalls[id])); + } else if (op === 'create') { + if (db.firewalls[id]) fail('already exists'); + db.firewalls[id] = { + id: String(Object.keys(db.firewalls).length + 100), + name: id, + description: flag('description'), + targetTags: flag('target-tags').split(','), + sourceRanges: flag('source-ranges').split(','), + allowed: flag('allow'), + }; + save(); + } else fail(`unexpected ${cmd}`); +} else if (cmd.startsWith('iam workload-identity-pools providers')) { const [, , , op, id] = words; const pool = flag('workload-identity-pool'); if (op === 'list') { @@ -49,6 +68,8 @@ else if (cmd.startsWith('iam workload-identity-pools providers')) { } } else if (op === 'describe') { if (!db.providers[id]) fail('not found'); + if (format === 'value(name)') + out(`projects/123456789012/locations/global/workloadIdentityPools/${pool}/providers/${id}`); if (format.includes('issuerUri')) out(db.providers[id].issuer); if (format.includes('state')) out(db.providers[id].state ?? 'ACTIVE'); if (format.includes('attributeCondition')) out(db.providers[id].condition ?? ''); @@ -73,6 +94,8 @@ else if (cmd.startsWith('iam workload-identity-pools providers')) { if (op === 'describe') { // A deleted pool still describes, with state DELETED, for 30 days (as Google keeps it). if (!db.pools[id]) fail('not found'); + if (format === 'value(name)') + out(`projects/123456789012/locations/global/workloadIdentityPools/${id}`); if (format.includes('state')) out(db.pools[id].state ?? 'ACTIVE'); if (format.includes('disabled')) out(db.pools[id].disabled ? 'True' : 'False'); } else if (op === 'create') { @@ -114,11 +137,17 @@ else if (cmd.startsWith('iam workload-identity-pools providers')) { const email = id.includes('@') ? id : `${id}@${flag('project')}.iam.gserviceaccount.com`; if (op === 'describe') { if (!db.accounts[email]) fail('not found'); + if (format === 'value(uniqueId)') out(db.accounts[email].uniqueId ?? '123456789'); if (format.includes('disabled')) out(db.accounts[email].disabled ? 'True' : 'False'); } else if (op === 'create') { db.accounts[email] = { description: flag('description') }; save(); } else fail(`unexpected ${cmd}`); +} else if (cmd.startsWith('projects get-iam-policy')) { + const bindings = db.bindings + .filter((x) => x.startsWith(`project:${words[2]} `)) + .map((x) => ({ role: x.split(' ')[1], members: [x.split(' ')[2]] })); + out(JSON.stringify({ bindings })); } else if (cmd.startsWith('projects add-iam-policy-binding')) { const entry = `project:${words[2]} ${flag('role')} ${flag('member')}`; if (!db.bindings.includes(entry)) db.bindings.push(entry); diff --git a/scripts/selfhost/testdata/fake-gcloud.mjs b/scripts/selfhost/testdata/fake-gcloud.mjs new file mode 100755 index 0000000000..ae1481112b --- /dev/null +++ b/scripts/selfhost/testdata/fake-gcloud.mjs @@ -0,0 +1,83 @@ +#!/usr/bin/env node +// Fake `gcloud storage` for backup-entrypoint.test.ts. gs:// maps to $FAKE_GCS_ROOT/. +// It models what the box showed (PR #2675): while celld runs, objects in $FAKE_STATE/churn.json +// vanish mid-copy (404) and the aborted download leaves a tracker keyed by its destination path; +// a later download to that same path fails with `[Errno 2] No such file or directory`. +import { + appendFileSync, + cpSync, + existsSync, + mkdirSync, + readdirSync, + readFileSync, + rmSync, + writeFileSync, +} from 'node:fs'; +import { dirname, join } from 'node:path'; + +const root = process.env.FAKE_GCS_ROOT; +const state = process.env.FAKE_STATE; +const args = process.argv.slice(2); +appendFileSync(join(state, 'calls.log'), `gcloud ${args.join(' ')}\n`); + +function files(dir) { + if (!existsSync(dir)) return []; + return readdirSync(dir, { withFileTypes: true }).flatMap((e) => + e.isDirectory() ? files(join(dir, e.name)).map((f) => `${e.name}/${f}`) : [e.name] + ); +} +const gs = (url) => join(root, url.replace(/^gs:\/\//, '').replace(/\/\*\*$/, '')); +const trackersFile = join(state, 'trackers.json'); +const trackers = existsSync(trackersFile) ? JSON.parse(readFileSync(trackersFile, 'utf8')) : []; +const celldRunning = readFileSync(join(state, 'celld'), 'utf8').trim() === 'running'; +const churn = existsSync(join(state, 'churn.json')) + ? JSON.parse(readFileSync(join(state, 'churn.json'), 'utf8')) + : []; + +if (args[0] !== 'storage') process.exit(2); +if (args[1] === 'ls') { + const listed = files(gs(args[2])); + if (listed.length === 0) { + process.stderr.write('ERROR: (gcloud.storage.ls) One or more URLs matched no objects.\n'); + process.exit(1); + } + process.stdout.write( + listed.map((f) => `${args[2].replace(/\/\*\*$/, '')}/${f}`).join('\n') + '\n' + ); + process.exit(0); +} +if (args[1] !== 'rsync') process.exit(2); +const [src, dst] = args.slice(-2); +const mirror = args.includes('--delete-unmatched-destination-objects'); +if (!src.startsWith('gs://')) { + // backup -> bucket + for (const f of files(src)) { + mkdirSync(dirname(join(gs(dst), f)), { recursive: true }); + cpSync(join(src, f), join(gs(dst), f)); + } + process.exit(0); +} +const source = files(gs(src)); +mkdirSync(dst, { recursive: true }); +if (mirror) for (const f of files(dst)) if (!source.includes(f)) rmSync(join(dst, f)); +const errors = []; +for (const f of source) { + const target = join(dst, f); + if (celldRunning && churn.includes(f)) { + // celld replaced this generation mid-copy: the download aborts and leaves its tracker + trackers.push(target); + errors.push(`ERROR: ${src}/${f}#1 not found: 404.`); + continue; + } + if (trackers.includes(target) && !existsSync(`${target}_.gstmp`)) { + errors.push(`ERROR: [Errno 2] No such file or directory: '${target}'`); + continue; + } + mkdirSync(dirname(target), { recursive: true }); + cpSync(join(gs(src), f), target); +} +writeFileSync(trackersFile, JSON.stringify(trackers)); +if (errors.length) { + process.stderr.write(`Copying...\n${errors.join('\n')}\n`); + process.exit(1); +} diff --git a/scripts/selfhost/upgrade-compose.ts b/scripts/selfhost/upgrade-compose.ts new file mode 100644 index 0000000000..633c032752 --- /dev/null +++ b/scripts/selfhost/upgrade-compose.ts @@ -0,0 +1,58 @@ +/** Compose inputs at two revisions, shared by upgrade planning and its regression tests. */ +import { createHash } from 'node:crypto'; +import { existsSync, readdirSync, readFileSync } from 'node:fs'; +import { isAbsolute, join, relative, resolve } from 'node:path'; + +import { REPO_ROOT } from './deploy-steps.js'; +import { COMPOSE_PATH, type ComposeOverlay } from './image-rebuilds.js'; + +/** + * True when the diff touches a compose input: a non-README file under deploy/selfhost/, or any + * compose file the box selects (COMPOSE_FILE may list one elsewhere in the repository). + */ +export function composeInputsChanged(changed: readonly string[], composeFiles: readonly string[]) { + const selected = new Set(composeFiles.map((file) => relative(REPO_ROOT, resolve(file)))); + return changed.some( + (f) => (f.startsWith('deploy/selfhost/') && !f.endsWith('.md')) || selected.has(f) + ); +} + +/** + * Every compose file the box selects other than docker-compose.yml, at both refs, for + * imageRebuilds: a tracked file is read from git at each ref; a file git does not have (an + * operator's untracked overlay, or one outside the repository) is the same at both, so it is read + * from disk once. + */ +export function composeOverlays( + composeFiles: readonly string[], + from: string, + to: string, + fileAt: (ref: string, path: string) => string | null +): ComposeOverlay[] { + return composeFiles + .map((file) => ({ file, rel: relative(REPO_ROOT, resolve(file)).split(/[\\/]/).join('/') })) + .filter(({ rel }) => rel !== COMPOSE_PATH) + .map(({ file, rel }) => { + const inRepo = !rel.startsWith('../') && !isAbsolute(rel); + const atFrom = inRepo ? fileAt(from, rel) : null; + const atTo = inRepo ? fileAt(to, rel) : null; + if (atFrom !== null || atTo !== null) return { from: atFrom, to: atTo }; + const onDisk = existsSync(file) ? readFileSync(file, 'utf8') : null; + return { from: onDisk, to: onDisk }; + }); +} +/** Generated env files are compose inputs, even when the compose source did not change. */ +const GENERATED_STATE_FILE_SUFFIX = '.env'; +export function stateFingerprint(stateDir: string): string { + const hash = createHash('sha256'); + if (!existsSync(stateDir)) return ''; + for (const name of readdirSync(stateDir).sort()) { + if (!name.endsWith(GENERATED_STATE_FILE_SUFFIX)) continue; + try { + hash.update(name).update(readFileSync(join(stateDir, name))); + } catch { + // a directory or unreadable entry is not a compose input + } + } + return hash.digest('hex'); +} diff --git a/scripts/selfhost/upgrade-lib.ts b/scripts/selfhost/upgrade-lib.ts index 6bc9a487b4..7335ddecd7 100644 --- a/scripts/selfhost/upgrade-lib.ts +++ b/scripts/selfhost/upgrade-lib.ts @@ -1,49 +1,36 @@ -/** - * `pnpm selfhost:upgrade --to `: move a one-box install to another SAM git ref. - * - * 1. Refuse a checkout with uncommitted tracked changes; fetch; resolve the ref. - * 2. Check out the ref (detached) and `pnpm install --frozen-lockfile`. - * 3. `pnpm selfhost:deploy --init`: regenerates gateway.env and the other generated state for the - * new code. It never regenerates platform keys. Every deploy call gets this box's - * `--env-file` and `--state-dir` (and `--secrets` when given): without them the deploy would - * read the checkout's default .env and .state, a different box. - * 4. Rebuild a locally built image (caddy, sam-mx) only when its build inputs changed - * (imageRebuilds: its build section, merged across every selected compose file, or a file in - * its build context), - * with an explicit `docker compose build `; then restart the stack - * (`docker compose up -d`, never `--build`) only when compose inputs changed: a non-README file - * under deploy/selfhost/, a compose file the box's COMPOSE_FILE selects, or a generated file - * in .state/ that step 3 changed. This must precede step 5: deploy refuses to update the - * Worker while gateway.env differs from what the running frps and Caddy read. - * 5. `pnpm selfhost:deploy`: applies D1 migrations (celld d1 migrations apply) and publishes the - * Worker with `celld deploy`, which applies Durable Object migrations (celld accepts only - * `new_sqlite_classes`); it waits for /health itself. - * 6. Verify /health once more, then print how to roll back. - * - * Before step 2 the upgrade records the ref it started from in `/upgrade-pending.json` - * and removes the record only after step 6 passes. A failed upgrade leaves the checkout at the - * target, so a retry with the same `--to` is not "already there": it resumes from the recorded - * ref, runs every step again (restarting the stack, since the failed run may have got that far), - * and its rollback still names the ref that was deployed before. - * - * The upgrade takes NO backup. Rollback depends on whether the upgrade carried a D1 migration: - * without one, the previous ref redeploys over the same fleet; with one, an older Worker must not - * run against the migrated data, so rollback needs the operator's own pre-upgrade copy of the - * fleet bucket and .state, restored into an empty bucket. +/** Upgrade a one-box install, checking DO history against active state and taking an encrypted + * snapshot before changes. Failures restore that snapshot and the previous ref automatically. + * Selective builds, compose overlays and explicit box/state/secrets selection remain shared + * with the normal deploy path. An interrupted recovery retains its snapshot in the pending + * record; retry recovers the old installation first, then starts a fresh upgrade. */ import { spawnSync } from 'node:child_process'; -import { createHash } from 'node:crypto'; -import { existsSync, mkdirSync, readdirSync, readFileSync, rmSync } from 'node:fs'; -import { dirname, isAbsolute, join, relative, resolve } from 'node:path'; +import { existsSync, mkdirSync, readFileSync, rmSync } from 'node:fs'; +import { dirname, isAbsolute, join, resolve } from 'node:path'; +import { + type BoxContext as BackupContext, + composeArgs, + runBackup, + runRollback, +} from './backup-lib.js'; import { loadBoxEnv } from './box-settings.js'; import { composeFilesFor } from './compose-env.js'; import { log, REPO_ROOT, SELFHOST_DIR } from './deploy-steps.js'; -import { COMPOSE_PATH, type ComposeOverlay, imageRebuilds } from './image-rebuilds.js'; +import { COMPOSE_PATH, imageRebuilds } from './image-rebuilds.js'; +import { assertOperatorExecution } from './operator-only.js'; import { assertPrivateFile, replacePrivateFile } from './secret-files.js'; +import { composeInputsChanged, composeOverlays, stateFingerprint } from './upgrade-compose.js'; +import { + assertMigrationProgression, + type DoMigration, + installedMigrations, + sourceMigrations, +} from './upgrade-migrations.js'; + +export { composeInputsChanged, composeOverlays } from './upgrade-compose.js'; +import { assertRollbackReady } from './upgrade-preflight.js'; -/** Suffix of the files under .state/ that docker compose services read (`env_file`). */ -const GENERATED_STATE_FILE_SUFFIX = '.env'; const MIGRATIONS_DIR = 'apps/api/src/db/migrations/'; /** In the state dir while an upgrade has not finished: `{ "from": "" }`. */ export const UPGRADE_PENDING_FILE = 'upgrade-pending.json'; @@ -54,7 +41,6 @@ export interface RunResult { stderr: string; } -/** Runs a command. `env` is the child's environment (secrets go here, never in `args`). */ export type Runner = (command: string, args: string[], env?: NodeJS.ProcessEnv) => RunResult; export interface BoxContext { @@ -64,6 +50,7 @@ export interface BoxContext { stateDir: string; /** The deploy's `--secrets` file, when not the default `/secrets.env`. */ secretsFile?: string; + encryptionKeyFile?: string; /** Every compose file the box runs with, in order (composeFilesFor). */ composeFiles: string[]; run: Runner; @@ -72,12 +59,14 @@ export interface BoxContext { export interface UpgradeOptions { to: string; + backupDir?: string | null; checkHealth: () => Promise; } export interface UpgradeResult { from: string; to: string; + backupDir: string | null; /** Locally built services this upgrade rebuilt (explicitly, before the restart). */ imagesRebuilt: string[]; composeRestarted: boolean; @@ -110,23 +99,14 @@ function composeStateDirOverride(ctx: Pick): str return resolve(ctx.stateDir) === composeReads ? null : resolve(ctx.stateDir); } -/** `docker compose` arguments for this box: every compose file, then its .env, then `args`. */ -function composeArgs(ctx: Pick, args: string[]): string[] { - return [ - 'compose', - ...ctx.composeFiles.flatMap((file) => ['-f', file]), - '--env-file', - ctx.envFile, - ...args, - ]; -} - /** The box context from an .env file (which must exist and be private: it holds the bucket key). */ export function loadBox( envFile: string, stateDirOverride?: string, - secretsFile?: string + secretsFile?: string, + encryptionKeyFile?: string ): BoxContext { + assertOperatorExecution(); if (!existsSync(envFile)) throw new Error(`${envFile} does not exist`); assertPrivateFile(envFile); // The box as docker compose runs it (a shell variable any compose file interpolates beats the @@ -137,6 +117,7 @@ export function loadBox( return { box, envFile, + encryptionKeyFile: encryptionKeyFile ?? box.SAM_BACKUP_KEY_FILE, // Same default and base directory deploy.ts uses; compose is pointed at it (composeStateDirOverride). stateDir: resolve(dirname(envFile), stateDirOverride ?? box.SAM_SELFHOST_STATE_DIR ?? '.state'), ...(secretsFile ? { secretsFile: resolve(secretsFile) } : {}), @@ -149,26 +130,12 @@ export function loadBox( function check(result: RunResult, what: string): string { if (result.status !== 0) { throw new Error( - `${what} failed (exit ${result.status}): ${result.stderr.trim().slice(0, 500)}` + `${what} failed (exit ${result.status}); command output withheld because it may contain secrets` ); } return result.stdout.trim(); } -function stateFingerprint(stateDir: string): string { - const hash = createHash('sha256'); - if (!existsSync(stateDir)) return ''; - for (const name of readdirSync(stateDir).sort()) { - if (!name.endsWith(GENERATED_STATE_FILE_SUFFIX)) continue; - try { - hash.update(name).update(readFileSync(join(stateDir, name))); - } catch { - // a directory or unreadable entry is not a compose input - } - } - return hash.digest('hex'); -} - /** The `pnpm selfhost:deploy` arguments that select this box (env file, state dir, secrets). */ function deployBoxArgs(ctx: Pick): string[] { return [ @@ -191,12 +158,10 @@ function shellWord(value: string): string { * is rolled back, not the default stack. */ function rollbackSteps( - ctx: Pick, + ctx: BoxContext, from: string, - migrationsChanged: boolean, - composeChanged: boolean, - boxArgs: readonly string[] = [], - imagesRebuilt: readonly string[] = [] + backupDir: string, + imagesRebuilt: readonly string[] ): string[] { const stateDir = composeStateDirOverride(ctx); const compose = (args: string[]) => @@ -204,67 +169,58 @@ function rollbackSteps( ...(stateDir === null ? [] : [`SAM_SELFHOST_STATE_DIR=${shellWord(stateDir)}`]), ['docker', ...composeArgs(ctx, args)].map(shellWord).join(' '), ].join(' '); - const deploy = ['pnpm selfhost:deploy', ...boxArgs.map(shellWord)].join(' '); - // The images the upgrade rebuilt are rebuilt again from the old ref, never with `up --build`. - const rebuild = imagesRebuilt.length > 0 ? [compose(['build', ...imagesRebuilt])] : []; - if (!migrationsChanged) { - return [ - `git checkout ${from}`, - 'pnpm install --frozen-lockfile', - ...(composeChanged || rebuild.length > 0 - ? [`${deploy} --init`, ...rebuild, compose(['up', '-d'])] - : []), - deploy, - ]; - } return [ - '# This upgrade applied D1 migrations: do NOT redeploy the old Worker over the migrated fleet.', - '# The upgrade took no backup. Rolling back needs your own copy of the fleet bucket and', - '# .state from before the upgrade:', - compose(['down']), - `# Point CELLD_BUCKET in ${ctx.envFile} at a new, empty bucket, copy your pre-upgrade`, - '# bucket contents into it, put your pre-upgrade .state back, then:', - `git checkout ${from}`, + '# Restore the encrypted snapshot into an empty installation; do not redeploy old code over migrated data.', + `git checkout --detach ${from}`, 'pnpm install --frozen-lockfile', - ...rebuild, + `pnpm selfhost:restore --from ${shellWord(backupDir)} --box-env ${shellWord(ctx.envFile)} --state-dir ${shellWord(ctx.stateDir)}` + + (ctx.encryptionKeyFile ? ` --encryption-key-file ${shellWord(ctx.encryptionKeyFile)}` : ''), + ...(imagesRebuilt.length ? [compose(['build', ...imagesRebuilt])] : []), compose(['up', '-d']), ]; } -/** - * True when the diff touches a compose input: a non-README file under deploy/selfhost/, or any - * compose file the box selects (COMPOSE_FILE may list one elsewhere in the repository). - */ -export function composeInputsChanged(changed: readonly string[], composeFiles: readonly string[]) { - const selected = new Set(composeFiles.map((file) => relative(REPO_ROOT, resolve(file)))); - return changed.some( - (f) => (f.startsWith('deploy/selfhost/') && !f.endsWith('.md')) || selected.has(f) - ); +function backupContext(ctx: BoxContext): BackupContext { + return { + ...ctx, + now: () => Date.now(), + user: process.getuid && process.getgid ? `${process.getuid()}:${process.getgid()}` : undefined, + }; } -/** - * Every compose file the box selects other than docker-compose.yml, at both refs, for - * imageRebuilds: a tracked file is read from git at each ref; a file git does not have (an - * operator's untracked overlay, or one outside the repository) is the same at both, so it is read - * from disk once. - */ -export function composeOverlays( - composeFiles: readonly string[], +/** Restore before starting old code: even a failed deployment can already have migrated data. */ +async function recoverUpgrade( + ctx: BoxContext, from: string, - to: string, - fileAt: (ref: string, path: string) => string | null -): ComposeOverlay[] { - return composeFiles - .map((file) => ({ file, rel: relative(REPO_ROOT, resolve(file)).split(/[\\/]/).join('/') })) - .filter(({ rel }) => rel !== COMPOSE_PATH) - .map(({ file, rel }) => { - const inRepo = !rel.startsWith('../') && !isAbsolute(rel); - const atFrom = inRepo ? fileAt(from, rel) : null; - const atTo = inRepo ? fileAt(to, rel) : null; - if (atFrom !== null || atTo !== null) return { from: atFrom, to: atTo }; - const onDisk = existsSync(file) ? readFileSync(file, 'utf8') : null; - return { from: onDisk, to: onDisk }; - }); + backupDir: string, + rebuilds: readonly string[], + opts: UpgradeOptions +): Promise { + runRollback(backupContext(ctx), backupDir); + replacePrivateFile( + join(ctx.stateDir, UPGRADE_PENDING_FILE), + `${JSON.stringify({ from, backupDir })}\n` + ); + check(ctx.run('git', ['checkout', '--detach', from]), 'restore previous checkout'); + check(ctx.run('pnpm', ['install', '--frozen-lockfile']), 'restore previous dependencies'); + const stateDir = composeStateDirOverride(ctx); + const env = stateDir === null ? undefined : { ...process.env, SAM_SELFHOST_STATE_DIR: stateDir }; + if (rebuilds.length) { + const active = new Set( + check( + ctx.run('docker', composeArgs(ctx, ['config', '--services']), env), + 'read previous active services' + ).split('\n') + ); + const selected = rebuilds.filter((service) => active.has(service)); + if (selected.length) + check( + ctx.run('docker', composeArgs(ctx, ['build', ...selected]), env), + 'rebuild previous images' + ); + } + check(ctx.run('docker', composeArgs(ctx, ['up', '-d']), env), 'restore previous stack'); + if (!(await opts.checkHealth())) throw new Error('previous version health check failed'); } /** The ref an unfinished upgrade started from (`UPGRADE_PENDING_FILE`), or null. */ @@ -305,10 +261,11 @@ interface UpgradePlan { /** Locally built services whose build inputs changed (imageRebuilds). */ rebuilds: string[]; boxArgs: string[]; + installed: DoMigration[]; } -/** What a (possibly failed) upgrade has done so far, for the rollback it prints. */ interface UpgradeProgress { + deploymentStarted: boolean; stateChanged: boolean; imagesRebuilt: string[]; } @@ -342,7 +299,10 @@ async function applyUpgrade( ); git(['checkout', '--detach', plan.to]); pnpm(['install', '--frozen-lockfile']); + assertMigrationProgression(plan.installed, sourceMigrations(backupContext(ctx))); + ctx.log('DO migration preflight passed against the active deployment and target checkout'); const before = stateFingerprint(ctx.stateDir); + progress.deploymentStarted = true; pnpm(['selfhost:deploy', '--init', ...plan.boxArgs]); const stateChanged = stateFingerprint(ctx.stateDir) !== before; progress.stateChanged = stateChanged; @@ -372,6 +332,8 @@ async function applyUpgrade( } export async function runUpgrade(ctx: BoxContext, opts: UpgradeOptions): Promise { + assertOperatorExecution(); + assertRollbackReady(ctx); const git: Git = (args, what = `git ${args.join(' ')}`) => check(ctx.run('git', args), what); if (git(['status', '--porcelain', '--untracked-files=no']) !== '') { @@ -391,6 +353,7 @@ export async function runUpgrade(ctx: BoxContext, opts: UpgradeOptions): Promise from, to, imagesRebuilt: [], + backupDir: null, composeRestarted: false, migrationsChanged: false, rollback: [], @@ -422,50 +385,101 @@ export async function runUpgrade(ctx: BoxContext, opts: UpgradeOptions): Promise `compose inputs ${composeFilesChanged ? 'changed' : 'unchanged'}, ` + `D1 migrations ${migrationsChanged ? 'included' : 'none'}` ); - ctx.log('no backup is taken: keep your own copy of the fleet bucket and .state before upgrading'); + const backupDir = + opts.backupDir === undefined + ? join( + dirname(ctx.stateDir), + 'backups', + `pre-upgrade-${new Date().toISOString().replace(/[:.]/g, '-')}` + ) + : opts.backupDir; + if (!backupDir) + throw new Error( + 'automatic rollback requires a fresh backup; --skip-backup is no longer supported' + ); + if (pendingFrom !== null) { + const pending: unknown = JSON.parse( + readFileSync(join(ctx.stateDir, UPGRADE_PENDING_FILE), 'utf8') + ); + if ( + typeof pending !== 'object' || + pending === null || + !('backupDir' in pending) || + typeof pending.backupDir !== 'string' || + !isAbsolute(pending.backupDir) + ) { + throw new Error( + 'unfinished upgrade has no recorded encrypted snapshot; recover the original installation before retrying' + ); + } + try { + await recoverUpgrade(ctx, pendingFrom, pending.backupDir, rebuilds, opts); + } catch { + try { + ctx.run('docker', composeArgs(ctx, ['stop', 'celld'])); + } catch { + /* best effort */ + } + throw new Error( + 'unfinished upgrade recovery failed; keep celld stopped and retry using the recorded encrypted snapshot' + ); + } + rmSync(join(ctx.stateDir, UPGRADE_PENDING_FILE), { force: true }); + return runUpgrade(ctx, opts); + } + const installed = installedMigrations(backupContext(ctx)); + runBackup(backupContext(ctx), backupDir, from); const boxArgs = deployBoxArgs(ctx); const pendingPath = join(ctx.stateDir, UPGRADE_PENDING_FILE); if (pendingFrom === null) { mkdirSync(ctx.stateDir, { recursive: true, mode: 0o700 }); - replacePrivateFile(pendingPath, `${JSON.stringify({ from })}\n`); + replacePrivateFile(pendingPath, `${JSON.stringify({ from, backupDir })}\n`); } - const progress: UpgradeProgress = { stateChanged: false, imagesRebuilt: [] }; + const progress: UpgradeProgress = { + deploymentStarted: false, + stateChanged: false, + imagesRebuilt: [], + }; let composeRestarted: boolean; try { composeRestarted = await applyUpgrade( ctx, opts, git, - { to, composeFilesChanged, rebuilds, boxArgs }, + { to, composeFilesChanged, rebuilds, boxArgs, installed }, progress ); } catch (error) { - ctx.log(`upgrade FAILED: ${error instanceof Error ? error.message : String(error)}`); - ctx.log('to retry, run the same selfhost:upgrade again; to roll back:'); - const rollback = rollbackSteps( - ctx, - from, - migrationsChanged, - composeFilesChanged || progress.stateChanged, - boxArgs, - progress.imagesRebuilt - ); - for (const step of rollback) ctx.log(` ${step}`); + ctx.log('upgrade failed; automatically restoring the previous version'); + try { + if (progress.deploymentStarted) { + await recoverUpgrade(ctx, from, backupDir, progress.imagesRebuilt, opts); + } else { + git(['checkout', '--detach', from]); + check(ctx.run('pnpm', ['install', '--frozen-lockfile']), 'restore previous dependencies'); + } + rmSync(pendingPath, { force: true }); + ctx.log('automatic rollback completed'); + } catch { + if (progress.deploymentStarted) { + try { + ctx.run('docker', composeArgs(ctx, ['stop', 'celld'])); + } catch { + /* best effort */ + } + } + throw new Error( + 'upgrade failed and automatic rollback did not complete; keep celld stopped and retry using the recorded encrypted snapshot' + ); + } throw error; } rmSync(pendingPath, { force: true }); const { imagesRebuilt } = progress; - const rollback = rollbackSteps( - ctx, - from, - migrationsChanged, - composeRestarted, - boxArgs, - imagesRebuilt - ); + const rollback = rollbackSteps(ctx, from, backupDir, imagesRebuilt); ctx.log(`upgraded to ${to}; healthy. To roll back:`); for (const step of rollback) ctx.log(` ${step}`); - return { from, to, imagesRebuilt, composeRestarted, migrationsChanged, rollback }; + return { from, to, backupDir, imagesRebuilt, composeRestarted, migrationsChanged, rollback }; } diff --git a/scripts/selfhost/upgrade-migrations.test.ts b/scripts/selfhost/upgrade-migrations.test.ts new file mode 100644 index 0000000000..799b18b01b --- /dev/null +++ b/scripts/selfhost/upgrade-migrations.test.ts @@ -0,0 +1,161 @@ +import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'; +import { join, resolve } from 'node:path'; + +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; + +import { runCommand } from './backup-cli'; +import type { BoxContext } from './backup-lib'; +import { installedMigrations, migrationsFrom, sourceMigrations } from './upgrade-migrations'; + +const HISTORY = [ + { tag: 'v1', new_sqlite_classes: ['ProjectData'] }, + { tag: 'selfhost-hosted-git-v1', new_sqlite_classes: ['HostedGitRepo'] }, +]; +let root: string; +let config: Record; +let pointer: Record; +let manifest: Record; +let requests: string[]; +let failRead: boolean; + +const context = (scheme = 'gs'): BoxContext => ({ + box: { CELLD_BUCKET: `${scheme}://fleet/owned`, S3_ENDPOINT: 'http://localhost:9000' }, + envFile: join(root, 'env'), + stateDir: root, + composeFiles: ['compose.yml'], + now: () => 0, + log: () => { + throw new Error('Migration preflight must not log any control object'); + }, + run: (command, args) => { + if (command === 'pnpm') return { status: 0, stdout: JSON.stringify(HISTORY), stderr: '' }; + const key = args.at(-1) ?? ''; + requests.push(key); + if (failRead) return { status: 1, stdout: '', stderr: 'do-not-print-secret' }; + return { + status: 0, + stdout: JSON.stringify(key.endsWith('current.json') ? pointer : manifest), + stderr: '', + }; + }, +}); +const installConfig = () => + writeFileSync(join(root, 'project/wrangler.json'), JSON.stringify(config)); + +beforeEach(() => { + for (const name of Object.keys(process.env)) { + if (name === 'CI' || name === 'GITHUB_ACTIONS' || name.startsWith('RUNNER_')) + vi.stubEnv(name, undefined); + } + mkdirSync(resolve('.tmp'), { recursive: true }); + root = mkdtempSync(join(resolve('.tmp'), 'migration-check-')); + mkdirSync(join(root, 'project')); + config = { + name: 'sam', + migrations: structuredClone(HISTORY), + vars: { secret: 'do-not-print-secret' }, + }; + pointer = { script_name: 'sam', version: 'abc', prefix: 'deploy/sam/abc' }; + manifest = { + script_name: 'sam', + version: 'abc', + sqlite_classes: [ + 'ProjectData', + 'HostedGitRepo', + '__D1Database', + '__KvNamespace', + '__Queue', + '__Workflow.sam', + ], + }; + requests = []; + failRead = false; + installConfig(); +}); +afterEach(() => { + vi.unstubAllEnvs(); + rmSync(root, { recursive: true, force: true }); +}); + +describe('installed migration state', () => { + it.each(['gs', 's3'])( + 'reads the exact %s active pointer and manifest and accepts deployed hosted git', + (scheme) => { + expect(installedMigrations(context(scheme))).toEqual(HISTORY); + expect(requests.map((key) => key.replace(/^(gs:\/\/|src\/)/, ''))).toEqual([ + 'fleet/owned/deploy/current.json', + 'fleet/owned/deploy/sam/abc/manifest.json', + ]); + } + ); + + it.each(['unknown-tag', 'out-of-order', 'hosted-git-tag'])( + 'rejects installed %s tampering before reading manifests', + (kind) => { + const history = config.migrations as typeof HISTORY; + if (kind === 'unknown-tag') history[0]!.tag = 'unknown'; + if (kind === 'out-of-order') history.reverse(); + if (kind === 'hosted-git-tag') history[1]!.tag = 'selfhost-hosted-git-v999'; + installConfig(); + expect(() => installedMigrations(context())).toThrow(/installed tags differ/); + expect(requests).toEqual([]); + } + ); + + it('refuses missing generated state rather than assuming source history was deployed', () => { + rmSync(join(root, 'project/wrangler.json')); + expect(() => installedMigrations(context())).toThrow(/missing installed generated config/); + }); + + it.each(['different-script', 'version-mismatch', 'missing-class', 'extra-class'])( + 'rejects %s in real deployment state', + (kind) => { + if (kind === 'different-script') manifest.script_name = 'foreign'; + if (kind === 'version-mismatch') manifest.version = 'other'; + if (kind === 'missing-class') manifest.sqlite_classes = ['ProjectData', '__D1Database']; + if (kind === 'extra-class') + manifest.sqlite_classes = ['ProjectData', 'HostedGitRepo', 'UnknownClass']; + expect(() => installedMigrations(context())).toThrow(/active deployment/); + expect(requests).toHaveLength(2); + } + ); + + it('rejects a pointer escaping its exact deployment prefix', () => { + pointer.prefix = '../foreign'; + expect(() => installedMigrations(context())).toThrow(/pointer does not match/); + expect(requests).toHaveLength(1); + }); + + it('withholds command diagnostics that may contain a secret', () => { + failRead = true; + expect(() => installedMigrations(context())).toThrow( + 'DO migration preflight refused: cannot read active deployment state' + ); + }); + + it('uses the real current translator and emits only migration declarations', () => { + const migrations = sourceMigrations({ ...context(), run: runCommand }); + expect(migrations.length).toBeGreaterThan(20); + expect(migrations[0]?.tag).toBe('v1'); + expect(migrations.flatMap((entry) => entry.new_sqlite_classes)).toContain('ProjectData'); + expect( + migrations.every((entry) => Object.keys(entry).sort().join(',') === 'new_sqlite_classes,tag') + ).toBe(true); + }); +}); + +it.each([ + [ + { tag: 'duplicate', new_sqlite_classes: [] }, + { tag: 'duplicate', new_sqlite_classes: [] }, + ], + [{ tag: 'v1', new_sqlite_classes: ['Same', 'Same'] }], + [ + { tag: 'v1', new_sqlite_classes: ['Same'] }, + { tag: 'v2', new_sqlite_classes: ['Same'] }, + ], + [{ tag: 'v1', new_classes: ['Unsafe'] }], + [{ tag: 'v1', new_sqlite_classes: [], deleted_classes: ['Data'] }], +])('rejects invalid migration declarations %#', (...history) => { + expect(() => migrationsFrom(history)).toThrow(/DO migration preflight refused/); +}); diff --git a/scripts/selfhost/upgrade-migrations.ts b/scripts/selfhost/upgrade-migrations.ts new file mode 100644 index 0000000000..2d34629c3b --- /dev/null +++ b/scripts/selfhost/upgrade-migrations.ts @@ -0,0 +1,162 @@ +/** Upgrade preflight for celld's tagless persisted deployment format (0.6.3). + * The generated config retains the tags; cross-check it with the source translator AND the + * active bucket manifest before trusting it. Never log a manifest: it contains Worker secrets. + */ +import { readFileSync } from 'node:fs'; +import { join } from 'node:path'; + +import type { BoxContext } from './backup-lib'; +import { bucketPath, mcArgs, mcEnv, parseBucketUrl } from './backup-lib'; +import { assertOperatorExecution } from './operator-only.js'; + +export interface DoMigration { + tag: string; + new_sqlite_classes: string[]; +} + +const fail = (reason: string): never => { + throw new Error(`DO migration preflight refused: ${reason}`); +}; + +export function migrationsFrom(value: unknown): DoMigration[] { + if (!Array.isArray(value)) return fail('missing or invalid migration history'); + const tags = new Set(); + const classes = new Set(); + return value.map((entry: unknown) => { + if (typeof entry !== 'object' || entry === null) return fail('invalid migration entry'); + const item = entry as Record; + if (typeof item.tag !== 'string' || !item.tag || tags.has(item.tag)) { + return fail('missing or duplicate migration tag'); + } + if (Object.keys(item).some((key) => !['tag', 'new_sqlite_classes'].includes(key))) { + return fail('unsupported migration operation'); + } + tags.add(item.tag); + if ( + !Array.isArray(item.new_sqlite_classes) || + item.new_sqlite_classes.some((name) => typeof name !== 'string' || !name || classes.has(name)) + ) { + return fail('invalid or duplicate SQLite class'); + } + const names = item.new_sqlite_classes as string[]; + for (const name of names) { + if (classes.has(name)) return fail('duplicate SQLite class'); + classes.add(name); + } + return { tag: item.tag, new_sqlite_classes: names }; + }); +} + +/** All existing tags and their class declarations are immutable; additions may occur between + * existing tags (shared vN migrations precede the selfhost-only tags in generated configs). + */ +export function assertMigrationProgression(installed: DoMigration[], target: DoMigration[]): void { + let last = -1; + for (const migration of installed) { + const index = target.findIndex((entry) => entry.tag === migration.tag); + if (index < 0) fail('unknown or removed migration tag'); + if (index <= last) fail('out-of-order migration tags'); + if ( + JSON.stringify(migration.new_sqlite_classes) !== + JSON.stringify(target[index]?.new_sqlite_classes) + ) { + fail('an existing migration changed its class declarations'); + } + last = index; + } +} + +/** Runs the checkout's actual translator, so selfhost-only tags use the same source as deploy. + * The probe has no box vars, secrets or deployment side effects; stdout contains only migrations. + */ +export function sourceMigrations(ctx: BoxContext): DoMigration[] { + const result = ctx.run('pnpm', [ + 'exec', + 'tsx', + '--eval', + [ + "import {readFileSync} from 'node:fs';", + "import * as TOML from '@iarna/toml';", + "import {buildCelldConfig} from './scripts/selfhost/celld-config.ts';", + "const source=TOML.parse(readFileSync('apps/api/wrangler.toml','utf8'));", + "const plan=buildCelldConfig(source,{main:'celld-main.ts',baseDomain:'upgrade.invalid'});", + 'process.stdout.write(JSON.stringify(plan.config.migrations));', + ].join(''), + ]); + if (result.status !== 0) fail('cannot read checkout migration declarations'); + try { + return migrationsFrom(JSON.parse(result.stdout)); + } catch { + return fail('invalid checkout migration declarations'); + } +} + +/** Read only the exact celld control objects, and never surface their contents or stderr. */ +function readControlObject(ctx: BoxContext, key: string): Record { + assertOperatorExecution(); + const url = parseBucketUrl(ctx.box.CELLD_BUCKET ?? ''); + const result = + url.scheme === 'gs' + ? ctx.run('gcloud', ['storage', 'cat', `gs://${bucketPath(url)}/${key}`]) + : ctx.run('docker', mcArgs(ctx, [], ['cat', `src/${bucketPath(url)}/${key}`]), mcEnv(ctx)); + if (result.status !== 0) fail('cannot read active deployment state'); + try { + const object: unknown = JSON.parse(result.stdout); + if (typeof object !== 'object' || object === null || Array.isArray(object)) + fail('invalid active deployment state'); + return object as Record; + } catch { + return fail('invalid active deployment state'); + } +} + +export function installedMigrations(ctx: BoxContext): DoMigration[] { + assertOperatorExecution(); + let config: Record; + try { + const parsed: unknown = JSON.parse( + readFileSync(join(ctx.stateDir, 'project', 'wrangler.json'), 'utf8') + ); + if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) + fail('invalid installed generated config'); + config = parsed as Record; + } catch { + return fail('missing installed generated config; deploy the current checkout before upgrading'); + } + const installed = migrationsFrom(config.migrations); + const source = sourceMigrations(ctx); + // An incomplete/edited local config cannot attest the migration state of this checkout. + if (JSON.stringify(installed) !== JSON.stringify(source)) + fail('installed tags differ from the current checkout'); + const pointer = readControlObject(ctx, 'deploy/current.json'); + if ( + typeof pointer.script_name !== 'string' || + typeof pointer.version !== 'string' || + !/^[a-zA-Z0-9_-]+$/.test(pointer.script_name) || + !/^[a-zA-Z0-9_-]+$/.test(pointer.version) || + pointer.prefix !== `deploy/${pointer.script_name}/${pointer.version}` || + pointer.script_name !== config.name + ) { + fail('active deployment pointer does not match the installation'); + } + const manifest = readControlObject(ctx, `${pointer.prefix}/manifest.json`); + if ( + manifest.script_name !== pointer.script_name || + manifest.version !== pointer.version || + !Array.isArray(manifest.sqlite_classes) || + manifest.sqlite_classes.some((name) => typeof name !== 'string') + ) { + fail('active deployment manifest does not match its pointer'); + } + // celld's reserved runtime classes are injected after the declared application classes. + const applicationClasses = (manifest.sqlite_classes as string[]).filter( + (name) => + !['__D1Database', '__KvNamespace', '__Queue', '__Workflow'].includes(name) && + !name.startsWith('__Workflow.') + ); + const expectedClasses = installed.flatMap((entry) => entry.new_sqlite_classes); + if (JSON.stringify(applicationClasses) !== JSON.stringify(expectedClasses)) { + fail('active deployment classes differ from installed migration declarations'); + } + return installed; +} diff --git a/scripts/selfhost/upgrade-preflight.test.ts b/scripts/selfhost/upgrade-preflight.test.ts new file mode 100644 index 0000000000..f131fd6c52 --- /dev/null +++ b/scripts/selfhost/upgrade-preflight.test.ts @@ -0,0 +1,117 @@ +import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'; +import { join, resolve } from 'node:path'; + +import { afterEach, beforeEach, describe, expect, it, type Mock, vi } from 'vitest'; + +import { composeProjectFor, expectedComposeProjectFor, recordInstall } from './install-record.js'; +import { type BoxContext, loadBox, type Runner, runUpgrade } from './upgrade-lib.js'; + +let root: string; +let context: BoxContext; +let runner: Mock; + +beforeEach(() => { + for (const name of Object.keys(process.env)) { + if (name === 'CI' || name === 'GITHUB_ACTIONS' || name.startsWith('RUNNER_')) + vi.stubEnv(name, undefined); + } + mkdirSync(resolve('.tmp'), { recursive: true }); + root = mkdtempSync(join(resolve('.tmp'), 'upgrade-ownership-')); + const stateDir = join(root, 'state'); + const envFile = join(root, 'box.env'); + mkdirSync(stateDir); + runner = vi.fn(() => ({ status: 0, stdout: '', stderr: '' })); + context = { + box: { SAM_DOMAIN: 'install.example', CELLD_BUCKET: 'gs://owned/fleet' }, + stateDir, + envFile, + composeFiles: ['compose.yml'], + run: runner, + log: vi.fn(), + }; + recordInstall(stateDir, envFile, context.box, 'installation-identity'); +}); +afterEach(() => { + vi.unstubAllEnvs(); + rmSync(root, { recursive: true, force: true }); +}); + +const upgrade = () => runUpgrade(context, { to: 'release', checkHealth: async () => true }); + +describe('upgrade rollback ownership preflight at the production trigger', () => { + it.each(['sam-selfhost', 'another-install'])( + 'refuses legacy/shared compose project %s before backup, checkout or any runner command', + async (project) => { + context.box = { ...context.box, COMPOSE_PROJECT_NAME: project }; + await expect(upgrade()).rejects.toThrow( + /migrate to an installation-specific compose project/ + ); + expect(runner).not.toHaveBeenCalled(); + } + ); + + it.each(['missing', 'removed', 'reused', 'foreign', 'duplicate', 'malformed'])( + 'refuses %s compose ownership receipt before runner commands', + async (kind) => { + const file = join(context.stateDir, 'created-resources.json'); + const receipt = { + cloud: 'box', + kind: 'compose-project', + name: composeProjectFor(context.box, context.stateDir), + action: 'created', + createdBy: 'deploy', + attributes: {}, + }; + let resources: Record[] = [receipt]; + if (kind === 'missing') resources = []; + if (kind === 'removed') resources[0] = { ...receipt, removedAt: new Date().toISOString() }; + if (kind === 'reused') resources[0] = { ...receipt, action: 'reused' }; + if (kind === 'foreign') resources[0] = { ...receipt, name: 'foreign-project' }; + if (kind === 'duplicate') resources.push({ ...receipt }); + writeFileSync( + file, + kind === 'malformed' + ? '{"secret":"do-not-print"' + : JSON.stringify({ format: 'sam-created-resources/1', resources }) + ); + await expect(upgrade()).rejects.toThrow(/Upgrade refused:.*receipt/); + expect(runner).not.toHaveBeenCalled(); + } + ); + + it('allows exact current installation receipt to reach git and a genuine no-op upgrade', async () => { + context.box = { + ...context.box, + COMPOSE_PROJECT_NAME: expectedComposeProjectFor(context.box, context.stateDir), + }; + const sha = 'a'.repeat(40); + runner.mockImplementation((_command, args: string[]) => ({ + status: 0, + stdout: args[0] === 'rev-parse' ? sha : '', + stderr: '', + })); + const result = await upgrade(); + expect(result.from).toBe(sha); + expect(result.to).toBe(sha); + expect(runner).toHaveBeenCalledWith('git', ['fetch', '--tags', 'origin']); + expect(result.backupDir).toBeNull(); + }); + + it.each(['GITHUB_ACTIONS', 'CI', 'RUNNER_TEMP', 'RUNNER_NAME'])( + 'runUpgrade rejects %s before receipt reads or runner commands', + async (signal) => { + vi.stubEnv(signal, 'true'); + rmSync(context.stateDir, { recursive: true, force: true }); + await expect(upgrade()).rejects.toThrow(/forbidden in CI/); + expect(runner).not.toHaveBeenCalled(); + } + ); + + it.each(['GITHUB_ACTIONS', 'CI', 'RUNNER_TEMP', 'RUNNER_NAME'])( + 'public loadBox rejects %s before reading env', + (signal) => { + vi.stubEnv(signal, 'true'); + expect(() => loadBox(join(root, 'does-not-exist'))).toThrow(/forbidden in CI/); + } + ); +}); diff --git a/scripts/selfhost/upgrade-preflight.ts b/scripts/selfhost/upgrade-preflight.ts new file mode 100644 index 0000000000..a287b676f6 --- /dev/null +++ b/scripts/selfhost/upgrade-preflight.ts @@ -0,0 +1,35 @@ +/** Refuse upgrades whose installation cannot safely remove its cache during rollback. */ +import type { BoxContext } from './backup-lib.js'; +import { + composeProjectFor, + expectedComposeProjectFor, + readInstallRecord, +} from './install-record.js'; + +export function assertRollbackReady(ctx: Pick): void { + const project = composeProjectFor(ctx.box, ctx.stateDir); + if (project !== expectedComposeProjectFor(ctx.box, ctx.stateDir)) { + throw new Error( + 'Upgrade refused: legacy shared compose project cannot safely roll back; migrate to an installation-specific compose project before upgrading' + ); + } + let records; + try { + records = readInstallRecord(ctx.stateDir); + } catch { + throw new Error('Upgrade refused: cannot verify installation compose creation receipt'); + } + const matches = records.filter( + (entry) => + entry.cloud === 'box' && + entry.kind === 'compose-project' && + entry.name === project && + entry.action === 'created' && + !entry.removedAt + ); + if (matches.length !== 1) { + throw new Error( + 'Upgrade refused: missing installation compose creation receipt; deploy the installation-specific project before upgrading' + ); + } +} diff --git a/scripts/selfhost/upgrade-safeguards.test.ts b/scripts/selfhost/upgrade-safeguards.test.ts new file mode 100644 index 0000000000..dd6d84352a --- /dev/null +++ b/scripts/selfhost/upgrade-safeguards.test.ts @@ -0,0 +1,244 @@ +/** Drive the production upgrade trigger with a deployed-state store and command runner. */ +import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'; +import { join, resolve } from 'node:path'; + +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; + +import { type BoxContext, runBackup, type RunResult, runRollback } from './backup-lib'; +import { runUpgrade } from './upgrade-lib'; + +vi.mock('./backup-lib', async (importOriginal) => ({ + ...(await importOriginal()), + runBackup: vi.fn(), + runRollback: vi.fn(), +})); + +vi.mock('./upgrade-preflight.js', () => ({ assertRollbackReady: vi.fn() })); + +const FROM = 'a'.repeat(40); +const TO = 'b'.repeat(40); +const HISTORY = [ + { tag: 'v1', new_sqlite_classes: ['ProjectData'] }, + { tag: 'selfhost-hosted-git-v1', new_sqlite_classes: ['HostedGitRepo'] }, +]; +let root: string; +let steps: string[]; +let logs: string[]; +let diff: string[]; +let dirty: boolean; +let target: typeof HISTORY; +let current: string; +let failCommand: string | undefined; +let generatedChange: boolean; + +function run(command: string, args: string[]): RunResult { + const ok = (stdout = '') => ({ status: 0, stdout, stderr: '' }); + const commandArgs = + command === 'pnpm' && args[0] === 'selfhost:deploy' + ? args.slice(0, args.indexOf('--env-file')) + : args; + const line = `${command} ${commandArgs.join(' ')}`; + steps.push(line); + if (command === 'git') { + if (args[0] === 'status') return ok(dirty ? ' M file' : ''); + if (args[0] === 'rev-parse' && args[1] === 'HEAD') return ok(FROM); + if (args[0] === 'rev-parse') return ok(TO); + if (args[0] === 'show') return ok('services:\n celld:\n image: celld:fixed\n'); + if (args[0] === 'diff') return ok(diff.join('\n')); + if (args[0] === 'checkout') current = args[2] ?? FROM; + } + if (command === 'gcloud') { + return ok( + JSON.stringify( + args.at(-1)?.endsWith('current.json') + ? { script_name: 'sam', version: 'abc', prefix: 'deploy/sam/abc' } + : { + script_name: 'sam', + version: 'abc', + sqlite_classes: ['ProjectData', 'HostedGitRepo', '__D1Database'], + } + ) + ); + } + if (command === 'pnpm' && args[0] === 'exec') + return ok(JSON.stringify(current === TO ? target : HISTORY)); + if (line === 'pnpm selfhost:deploy --init' && generatedChange) { + writeFileSync(join(root, 'state/gateway.env'), 'changed'); + } + if (line === failCommand) + return { status: 1, stdout: '', stderr: 'secret-value-must-never-appear' }; + return ok(); +} + +function context(): BoxContext { + return { + box: { CELLD_BUCKET: 'gs://fleet/celld', SAM_DOMAIN: 'box.example' }, + envFile: join(root, 'box.env'), + stateDir: join(root, 'state'), + composeFiles: ['compose.yml'], + run, + now: () => 0, + log: (message) => logs.push(message), + }; +} +const upgrade = (checkHealth = async () => true, backupDir: string | null = join(root, 'backup')) => + runUpgrade(context(), { to: 'release', backupDir, checkHealth }); + +beforeEach(() => { + for (const name of Object.keys(process.env)) { + if (name === 'CI' || name === 'GITHUB_ACTIONS' || name.startsWith('RUNNER_')) + vi.stubEnv(name, undefined); + } + mkdirSync(resolve('.tmp'), { recursive: true }); + root = mkdtempSync(join(resolve('.tmp'), 'upgrade-')); + mkdirSync(join(root, 'state/project'), { recursive: true }); + writeFileSync( + join(root, 'state/project/wrangler.json'), + JSON.stringify({ name: 'sam', migrations: HISTORY }) + ); + writeFileSync(join(root, 'state/gateway.env'), 'before'); + steps = []; + logs = []; + diff = ['apps/api/src/routes/projects.ts']; + dirty = false; + target = structuredClone(HISTORY); + current = FROM; + failCommand = undefined; + generatedChange = false; + vi.mocked(runBackup) + .mockReset() + .mockImplementation(() => { + steps.push('BACKUP'); + return {} as ReturnType; + }); + vi.mocked(runRollback) + .mockReset() + .mockImplementation(() => { + steps.push('RESTORE'); + }); +}); +afterEach(() => { + vi.unstubAllEnvs(); + rmSync(root, { recursive: true, force: true }); +}); + +const deployedSteps = () => steps.filter((step) => !step.startsWith('pnpm exec ')); + +describe('runUpgrade', () => { + it('backs up after checking active state, then checks target tags before any deployment', async () => { + const result = await upgrade(); + expect(steps.indexOf('BACKUP')).toBeGreaterThan( + steps.findIndex((step) => step.includes('deploy/sam/abc/manifest.json')) + ); + const targetProbe = steps + .map((step, index) => (step.startsWith('pnpm exec ') ? index : -1)) + .filter((index) => index >= 0) + .pop()!; + expect(targetProbe).toBeLessThan(steps.indexOf('pnpm selfhost:deploy --init')); + expect(result.composeRestarted).toBe(false); + expect(steps).toContain('pnpm selfhost:deploy'); + expect(logs.join('\n')).toContain('DO migration preflight passed'); + expect(runRollback).not.toHaveBeenCalled(); + }); + + it.each(['deploy/selfhost/docker-compose.yml', 'generated-state'])( + 'restarts between init and deploy when %s changes', + async (path) => { + if (path === 'generated-state') generatedChange = true; + else diff = [path]; + expect((await upgrade()).composeRestarted).toBe(true); + const up = steps.findIndex( + (step) => step.startsWith('docker compose ') && step.endsWith(' up -d') + ); + expect(up).toBeGreaterThan(steps.indexOf('pnpm selfhost:deploy --init')); + expect(up).toBeLessThan(steps.indexOf('pnpm selfhost:deploy')); + } + ); + + it('scopes every forward and recovery compose command to the selected installation', async () => { + diff = ['deploy/selfhost/docker-compose.yml']; + const box = { ...context(), box: { ...context().box, COMPOSE_PROJECT_NAME: 'owned-upgrade' } }; + failCommand = 'pnpm selfhost:deploy'; + await expect( + runUpgrade(box, { + to: 'release', + backupDir: join(root, 'backup'), + checkHealth: async () => true, + }) + ).rejects.toThrow(/command output withheld/); + const docker = steps.filter((step) => step.startsWith('docker compose ')); + expect(docker.length).toBeGreaterThanOrEqual(2); + expect( + docker.every((step) => step.startsWith('docker compose --project-name owned-upgrade ')) + ).toBe(true); + expect(runRollback).toHaveBeenCalledOnce(); + }); + + it('permits a new shared tag before the retained selfhost-only suffix', async () => { + target.splice(1, 0, { tag: 'v2', new_sqlite_classes: ['MoreData'] }); + await upgrade(); + expect(steps).toContain('pnpm selfhost:deploy'); + }); + + it.each(['unknown', 'out-of-order', 'missing-hosted-git', 'changed-class'])( + 'refuses %s target tags and restores checkout without touching cloud state', + async (kind) => { + if (kind === 'unknown') target[0] = { tag: 'unknown', new_sqlite_classes: ['ProjectData'] }; + if (kind === 'out-of-order') target.reverse(); + if (kind === 'missing-hosted-git') target.pop(); + if (kind === 'changed-class') target[0]!.new_sqlite_classes = ['Changed']; + await expect(upgrade()).rejects.toThrow(/DO migration preflight refused/); + expect(deployedSteps()).toContain(`git checkout --detach ${FROM}`); + expect(steps).not.toContain('pnpm selfhost:deploy --init'); + expect(runRollback).not.toHaveBeenCalled(); + } + ); + + it.each(['pnpm selfhost:deploy --init', 'pnpm selfhost:deploy'])( + 'automatically restores the snapshot before starting old code on failure of %s', + async (command) => { + diff = ['apps/api/src/db/migrations/0300_new.sql']; + failCommand = command; + await expect(upgrade()).rejects.toThrow(/command output withheld/); + expect(runRollback).toHaveBeenCalledWith(expect.anything(), join(root, 'backup')); + expect(steps.indexOf('RESTORE')).toBeLessThan(steps.indexOf(`git checkout --detach ${FROM}`)); + expect(steps.at(-1)).toMatch(/^docker compose .* up -d$/); + expect(logs.join('\n')).toContain('automatic rollback completed'); + expect(logs.join('\n')).not.toContain('secret-value'); + } + ); + + it('rolls back when upgraded health fails and verifies recovered health', async () => { + const health = vi.fn().mockResolvedValueOnce(false).mockResolvedValueOnce(true); + await expect(upgrade(health)).rejects.toThrow(/not healthy/); + expect(runRollback).toHaveBeenCalledOnce(); + expect(health).toHaveBeenCalledTimes(2); + expect(logs.join('\n')).toContain('automatic rollback completed'); + }); + + it('does not start old code if restoring the snapshot fails', async () => { + failCommand = 'pnpm selfhost:deploy'; + vi.mocked(runRollback).mockImplementation(() => { + throw new Error('secret-value'); + }); + await expect(upgrade()).rejects.toThrow(/automatic rollback did not complete/); + expect(steps).not.toContain(`git checkout --detach ${FROM}`); + expect(logs.join('\n')).not.toContain('secret-value'); + }); + + it('fails recovery if the restored installation is unhealthy', async () => { + await expect(upgrade(async () => false)).rejects.toThrow(/automatic rollback did not complete/); + expect(logs.join('\n')).not.toContain('automatic rollback completed'); + }); + + it('requires a fresh backup before upgrading', async () => { + await expect(upgrade(async () => true, null)).rejects.toThrow(/requires a fresh backup/); + expect(steps.some((step) => step.startsWith('git checkout'))).toBe(false); + }); + + it('refuses dirty tracked files before backup or fetch', async () => { + dirty = true; + await expect(upgrade()).rejects.toThrow(/uncommitted/); + expect(steps).toEqual(['git status --porcelain --untracked-files=no']); + }); +}); diff --git a/scripts/selfhost/upgrade.test.ts b/scripts/selfhost/upgrade.test.ts index 38ed28d3aa..4019ee565b 100644 --- a/scripts/selfhost/upgrade.test.ts +++ b/scripts/selfhost/upgrade.test.ts @@ -1,17 +1,17 @@ /** * selfhost:upgrade orchestration (upgrade-lib.ts) with git, pnpm and docker answered by a fake - * runner. Asserts the order of the steps, that no backup is taken, that the stack restarts only + * runner. Asserts the order of the steps, that an encrypted backup is taken, that the stack restarts only * when compose inputs change (files in deploy/selfhost/, selected compose files or generated * .state/ files), that an image is rebuilt only by an explicit `docker compose build` of a service - * whose build inputs changed (never `up --build`), that a failed upgrade can be retried, and that + * whose build inputs changed (never `up --build`), that interrupted recovery retains its original snapshot for retry, and that * the printed rollback selects the same box and matches whether the upgrade carried a D1 migration. */ import { existsSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'; -import { tmpdir } from 'node:os'; -import { join } from 'node:path'; +import { join, resolve } from 'node:path'; -import { afterEach, beforeEach, describe, expect, it } from 'vitest'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { runBackup, runRollback } from './backup-lib.js'; import { composeFilesFor } from './compose-env.js'; import { SELFHOST_DIR } from './deploy-steps.js'; import { imageRebuilds } from './image-rebuilds.js'; @@ -23,6 +23,19 @@ import { UPGRADE_PENDING_FILE, } from './upgrade-lib.js'; +vi.mock('./backup-lib.js', async (original) => ({ + ...(await original()), + runBackup: vi.fn(), + runRollback: vi.fn(), +})); +vi.mock('./upgrade-migrations.js', async (original) => ({ + ...(await original()), + sourceMigrations: vi.fn(() => [{ tag: 'v1', new_sqlite_classes: ['ProjectData'] }]), + installedMigrations: vi.fn(() => [{ tag: 'v1', new_sqlite_classes: ['ProjectData'] }]), +})); + +vi.mock('./upgrade-preflight.js', () => ({ assertRollbackReady: vi.fn() })); + const FROM = 'a'.repeat(40); const TO = 'b'.repeat(40); let root: string; @@ -103,6 +116,7 @@ function ctx(): BoxContext { // The .env names the state dir, so docker compose reads the same one the upgrade does. box: { CELLD_BUCKET: 'gs://fleet/celld', + COMPOSE_PROJECT_NAME: 'sam-test', SAM_DOMAIN: 'box.example', SAM_SELFHOST_STATE_DIR: join(root, 'state'), }, @@ -118,7 +132,14 @@ const upgrade = (health = true) => runUpgrade(ctx(), { to: 'v2026.11.12', checkHealth: async () => health }); beforeEach(() => { - root = mkdtempSync(join(tmpdir(), 'sam-upgrade-')); + for (const name of Object.keys(process.env)) { + if (name === 'CI' || name === 'GITHUB_ACTIONS' || name.startsWith('RUNNER_')) + vi.stubEnv(name, undefined); + } + vi.mocked(runBackup).mockReset(); + vi.mocked(runRollback).mockReset(); + mkdirSync(resolve('.tmp'), { recursive: true }); + root = mkdtempSync(join(resolve('.tmp'), 'sam-upgrade-')); mkdirSync(join(root, 'state')); writeFileSync(join(root, 'state/gateway.env'), 'FRPS_PORT_RANGE=20000-29999\n'); writeFileSync(join(root, 'box.env'), 'x=1\n', { mode: 0o600 }); @@ -135,17 +156,23 @@ beforeEach(() => { activeServices = ['celld', 'caddy']; }); -afterEach(() => rmSync(root, { recursive: true, force: true })); +afterEach(() => { + vi.unstubAllEnvs(); + rmSync(root, { recursive: true, force: true }); +}); /** The deploy arguments the fake box (ctx()) must be deployed with. */ const BOX_ARGS = '--env-file /box.env --state-dir /state'; const compact = () => - steps.map((s) => (s.startsWith('docker compose') ? s.replace(/ -f .* --env-file \S+/, '') : s)); + steps.map((s) => + s.startsWith('docker compose') + ? s.replace(/ --project-name \S+/, '').replace(/ -f .* --env-file \S+/, '') + : s + ); describe('runUpgrade', () => { - it('checks out, migrates and deploys with no backup, and leaves the stack running when compose inputs are unchanged', async () => { + it('checks out, backs up, migrates and deploys, and leaves the stack running when compose inputs are unchanged', async () => { const result = await upgrade(); - // No backup step: nothing touches the bucket and the celld container is never stopped. expect(compact()).toEqual([ 'git fetch --tags origin', `git checkout --detach ${TO}`, @@ -154,12 +181,8 @@ describe('runUpgrade', () => { `pnpm selfhost:deploy ${BOX_ARGS}`, ]); expect(result.composeRestarted).toBe(false); - expect(logs.join('\n')).toContain('no backup is taken'); - expect(result.rollback.map((step) => step.replaceAll(root, ''))).toEqual([ - `git checkout ${FROM}`, - 'pnpm install --frozen-lockfile', - `pnpm selfhost:deploy ${BOX_ARGS}`, - ]); + expect(runBackup).toHaveBeenCalledOnce(); + expect(result.rollback.join('\n')).toContain('selfhost:restore'); }); it('restarts the stack between --init and the deploy when a compose file changed', async () => { @@ -179,7 +202,7 @@ describe('runUpgrade', () => { mkdirSync(join(root, 'custom')); writeFileSync( envFile, - `CELLD_BUCKET=gs://fleet/celld\nSAM_SELFHOST_STATE_DIR=${join(root, 'state')}\n`, + `CELLD_BUCKET=gs://fleet/celld\nCOMPOSE_PROJECT_NAME=sam-test\nSAM_SELFHOST_STATE_DIR=${join(root, 'state')}\n`, { mode: 0o600 } ); const secrets = join(root, 'custom', 'secrets.env'); @@ -198,8 +221,12 @@ describe('runUpgrade', () => { `pnpm selfhost:deploy ${expected}`, ]); const rollback = result.rollback.map((step) => step.replaceAll(root, '')); - expect(rollback).toContain(`pnpm selfhost:deploy ${expected} --init`); - expect(rollback).toContain(`pnpm selfhost:deploy ${expected}`); + expect( + rollback.some( + (step) => + step.includes('selfhost:restore') && step.includes('--box-env /custom/box.env') + ) + ).toBe(true); }); it('restarts the stack when --init rewrote a generated state file (gateway.env)', async () => { @@ -217,47 +244,35 @@ describe('runUpgrade', () => { diff = ['apps/api/src/db/migrations/0300_new.sql']; const result = await upgrade(); expect(result.migrationsChanged).toBe(true); - expect(result.rollback.join('\n')).toContain('do NOT redeploy the old Worker'); - expect(result.rollback.join('\n')).toContain('The upgrade took no backup'); - // There is no restore command to point at in this version. - expect(result.rollback.join('\n')).not.toContain('selfhost:restore'); + expect(result.rollback.join('\n')).toContain('do not redeploy old code'); + expect(result.rollback.join('\n')).toContain('selfhost:restore'); }); it('stops at a failed deploy and prints the rollback', async () => { failDeploy = true; - await expect(upgrade()).rejects.toThrow(/migration 0219 failed/); - expect(logs.join('\n')).toContain('to roll back:'); - expect(logs.join('\n')).toContain(`git checkout ${FROM}`); + await expect(upgrade()).rejects.toThrow(/command output withheld/); + expect(runRollback).toHaveBeenCalledOnce(); + expect(head).toBe(FROM); + expect(logs.join('\n')).toContain('automatic rollback completed'); }); // The failed run leaves the checkout at the target: equal refs must not read as "deployed". it('retries a failed upgrade with the same --to, from the ref deployed before it', async () => { failDeploy = true; - await expect(upgrade()).rejects.toThrow(/migration 0219 failed/); + vi.mocked(runRollback).mockImplementationOnce(() => { + throw new Error('interrupted'); + }); + await expect(upgrade()).rejects.toThrow(/automatic rollback did not complete/); expect(head).toBe(TO); expect(existsSync(join(root, 'state', UPGRADE_PENDING_FILE))).toBe(true); - failDeploy = false; - steps = []; const retry = await upgrade(); - expect(compact()).toEqual([ - 'git fetch --tags origin', - `git checkout --detach ${TO}`, - 'pnpm install --frozen-lockfile', - `pnpm selfhost:deploy --init ${BOX_ARGS}`, - // The failed run may have restarted the stack already, so the retry restarts it too. - 'docker compose up -d', - `pnpm selfhost:deploy ${BOX_ARGS}`, - ]); + expect(runRollback).toHaveBeenCalledTimes(2); expect(retry.from).toBe(FROM); - expect(retry.rollback[0]).toBe(`git checkout ${FROM}`); expect(existsSync(join(root, 'state', UPGRADE_PENDING_FILE))).toBe(false); - - // Control: once it has succeeded, the same --to is a no-op. steps = []; expect((await upgrade()).rollback).toEqual([]); expect(steps).toEqual(['git fetch --tags origin']); - expect(logs.at(-1)).toBe('already at that ref; nothing to do'); }); it('refuses a pending record it did not write before touching the checkout', async () => { @@ -278,23 +293,19 @@ describe('runUpgrade', () => { it('rolls back generated state that --init changed, on failure and on success', async () => { initRewritesState = true; failDeploy = true; - await expect(upgrade()).rejects.toThrow(/migration 0219 failed/); - const printed = logs.join('\n').replaceAll(root, ''); - expect(printed).toContain(`pnpm selfhost:deploy ${BOX_ARGS} --init`); - expect(printed).toMatch(/docker compose .* up -d$/m); - - // A fresh box at FROM for the success case. - rmSync(join(root, 'state', UPGRADE_PENDING_FILE)); - writeFileSync(join(root, 'state/gateway.env'), 'FRPS_PORT_RANGE=20000-29999\n'); - head = FROM; + await expect(upgrade()).rejects.toThrow(/command output withheld/); + expect(runRollback).toHaveBeenCalledOnce(); + expect(compact().at(-1)).toBe('docker compose up -d'); + expect(head).toBe(FROM); + writeFileSync(join(root, 'state/gateway.env'), 'before'); failDeploy = false; - const rollback = (await upgrade()).rollback.map((step) => step.replaceAll(root, '')); - expect(rollback).toContain(`pnpm selfhost:deploy ${BOX_ARGS} --init`); + const rollback = (await upgrade()).rollback; + expect(rollback.some((step) => step.includes('selfhost:restore'))).toBe(true); expect(rollback.some((step) => /^docker compose .* up -d$/.test(step))).toBe(true); }); it('fails when the API is unhealthy after the deploy', async () => { - await expect(upgrade(false)).rejects.toThrow(/not healthy/); + await expect(upgrade(false)).rejects.toThrow(/automatic rollback did not complete/); }); it('refuses a checkout with uncommitted tracked changes before touching anything', async () => { @@ -305,14 +316,18 @@ describe('runUpgrade', () => { }); // Seen on a box, 2026-11-12: .env had COMPOSE_FILE listing an override file. The upgrade's -// `docker compose -f docker-compose.yml up -d --build` replaced that list and recreated celld +// `docker compose --project-name sam-test -f docker-compose.yml up -d --build` replaced that list and recreated celld // without what the override added. // S4: the box's ports are checked against the lease range when the upgrade loads the box, before it // fetches, checks out or runs docker compose (not only inside Caddy's start.sh once it is up). describe('loadBox refuses a box port inside the lease range', () => { const envWith = (line: string) => { const envFile = join(root, 'ports.env'); - writeFileSync(envFile, `CELLD_BUCKET=gs://fleet/celld\n${line}\n`, { mode: 0o600 }); + writeFileSync( + envFile, + `CELLD_BUCKET=gs://fleet/celld\nCOMPOSE_PROJECT_NAME=sam-test\n${line}\n`, + { mode: 0o600 } + ); return envFile; }; @@ -333,9 +348,19 @@ describe('runUpgrade with the box .env COMPOSE_FILE', () => { const boxFromEnv = (lines: string[]): BoxContext => { const envFile = join(root, 'real.env'); const stateLine = `SAM_SELFHOST_STATE_DIR=${join(root, 'state')}`; - writeFileSync(envFile, [`CELLD_BUCKET=gs://fleet/celld`, stateLine, ...lines, ''].join('\n'), { - mode: 0o600, - }); + writeFileSync( + envFile, + [ + `CELLD_BUCKET=gs://fleet/celld`, + 'COMPOSE_PROJECT_NAME=sam-test', + stateLine, + ...lines, + '', + ].join('\n'), + { + mode: 0o600, + } + ); // The real loader reads the .env; only the commands are answered by the fake runner. return { ...loadBox(envFile, join(root, 'state')), run, log: (m) => logs.push(m) }; }; @@ -347,7 +372,7 @@ describe('runUpgrade with the box .env COMPOSE_FILE', () => { const ctx = boxFromEnv(['COMPOSE_FILE=docker-compose.yml:docker-compose.override.yml']); await runUpgrade(ctx, { to: 'v1', checkHealth: async () => true }); expect(restartCommand()).toBe( - `docker compose -f ${join(SELFHOST_DIR, 'docker-compose.yml')} ` + + `docker compose --project-name sam-test -f ${join(SELFHOST_DIR, 'docker-compose.yml')} ` + `-f ${join(SELFHOST_DIR, 'docker-compose.override.yml')} ` + `--env-file /real.env up -d` ); @@ -358,7 +383,7 @@ describe('runUpgrade with the box .env COMPOSE_FILE', () => { const ctx = boxFromEnv([]); await runUpgrade(ctx, { to: 'v1', checkHealth: async () => true }); expect(restartCommand()).toBe( - `docker compose -f ${join(SELFHOST_DIR, 'docker-compose.yml')} --env-file /real.env up -d` + `docker compose --project-name sam-test -f ${join(SELFHOST_DIR, 'docker-compose.yml')} --env-file /real.env up -d` ); }); @@ -368,7 +393,7 @@ describe('runUpgrade with the box .env COMPOSE_FILE', () => { const result = await runUpgrade(ctx, { to: 'v1', checkHealth: async () => true }); const composeSteps = result.rollback.filter((step) => step.includes('docker compose')); expect(composeSteps.map((step) => step.replaceAll(root, ''))).toEqual([ - `docker compose -f ${join(SELFHOST_DIR, 'docker-compose.yml')} ` + + `docker compose --project-name sam-test -f ${join(SELFHOST_DIR, 'docker-compose.yml')} ` + `-f ${join(SELFHOST_DIR, 'docker-compose.override.yml')} ` + `--env-file /real.env up -d`, ]); @@ -379,15 +404,17 @@ describe('runUpgrade with the box .env COMPOSE_FILE', () => { const envFile = join(root, 'my box.env'); writeFileSync( envFile, - `CELLD_BUCKET=gs://fleet/celld\nSAM_SELFHOST_STATE_DIR=${join(root, 'state')}\n`, + `CELLD_BUCKET=gs://fleet/celld\nCOMPOSE_PROJECT_NAME=sam-test\nSAM_SELFHOST_STATE_DIR=${join(root, 'state')}\n`, { mode: 0o600 } ); const ctx = { ...loadBox(envFile, join(root, 'state')), run, log: (m: string) => logs.push(m) }; const { rollback } = await runUpgrade(ctx, { to: 'v1', checkHealth: async () => true }); const file = join(SELFHOST_DIR, 'docker-compose.yml'); - expect(rollback).toContain(`docker compose -f ${file} --env-file '${envFile}' down`); - expect(rollback).toContain(`docker compose -f ${file} --env-file '${envFile}' up -d`); - expect(rollback.join('\n')).toContain(`Point CELLD_BUCKET in ${envFile} at a new`); + expect(rollback.join('\n')).toContain(`--box-env '${envFile}'`); + expect(rollback).toContain( + `docker compose --project-name sam-test -f ${file} --env-file '${envFile}' up -d` + ); + expect(rollback.join('\n')).toContain('empty installation'); }); // COMPOSE_FILE may list a file outside deploy/selfhost; a change to it alone must restart. @@ -413,7 +440,7 @@ describe('runUpgrade with the box .env COMPOSE_FILE', () => { const ctx = boxFromEnv(['COMPOSE_FILE=docker-compose.yml:docker-compose.override.yml']); const result = await runUpgrade(ctx, { to: 'v1', checkHealth: async () => true }); const build = - `docker compose -f ${join(SELFHOST_DIR, 'docker-compose.yml')} ` + + `docker compose --project-name sam-test -f ${join(SELFHOST_DIR, 'docker-compose.yml')} ` + `-f ${join(SELFHOST_DIR, 'docker-compose.override.yml')} ` + `--env-file /real.env build caddy`; expect(steps).toContain(build); @@ -428,9 +455,15 @@ describe('runUpgrade with the box .env COMPOSE_FILE', () => { describe('runUpgrade with a state dir docker compose would not read on its own', () => { const box = (stateLine: string[]): BoxContext => { const envFile = join(root, 'real.env'); - writeFileSync(envFile, ['CELLD_BUCKET=gs://fleet/celld', ...stateLine, ''].join('\n'), { - mode: 0o600, - }); + writeFileSync( + envFile, + ['COMPOSE_PROJECT_NAME=sam-test', 'CELLD_BUCKET=gs://fleet/celld', ...stateLine, ''].join( + '\n' + ), + { + mode: 0o600, + } + ); return { ...loadBox(envFile, join(root, 'state')), run, log: (m) => logs.push(m) }; }; @@ -474,7 +507,7 @@ services: const envFile = join(root, 'real.env'); writeFileSync( envFile, - `CELLD_BUCKET=gs://fleet/celld\nSAM_SELFHOST_STATE_DIR=${join(root, 'state')}\n` + + `CELLD_BUCKET=gs://fleet/celld\nCOMPOSE_PROJECT_NAME=sam-test\nSAM_SELFHOST_STATE_DIR=${join(root, 'state')}\n` + `COMPOSE_FILE=docker-compose.yml:${file}\n`, { mode: 0o600 } ); @@ -528,14 +561,19 @@ describe('runUpgrade image builds', () => { ); expect(result.imagesRebuilt).toEqual(['caddy']); // Rolling back rebuilds the old image the same explicit way. - expect(result.rollback.map((step) => step.replaceAll(root, ''))).toEqual([ - `git checkout ${FROM}`, - 'pnpm install --frozen-lockfile', - `pnpm selfhost:deploy ${BOX_ARGS} --init`, - 'docker compose -f compose.yml --env-file /box.env build caddy', - 'docker compose -f compose.yml --env-file /box.env up -d', - `pnpm selfhost:deploy ${BOX_ARGS}`, - ]); + const rollback = result.rollback.map((step) => step.replaceAll(root, '')); + expect(rollback).toContain( + 'docker compose --project-name sam-test -f compose.yml --env-file /box.env build caddy' + ); + expect( + rollback.indexOf( + 'docker compose --project-name sam-test -f compose.yml --env-file /box.env build caddy' + ) + ).toBeLessThan( + rollback.indexOf( + 'docker compose --project-name sam-test -f compose.yml --env-file /box.env up -d' + ) + ); }); it('rebuilds caddy when the compose build args changed (a new pinned module)', async () => { @@ -569,11 +607,9 @@ describe('runUpgrade image builds', () => { it('prints the rebuild in the rollback when the deploy after it fails', async () => { diff = ['deploy/selfhost/caddy/Dockerfile']; failDeploy = true; - await expect(upgrade()).rejects.toThrow(/migration 0219 failed/); - const printed = logs.join('\n').replaceAll(root, ''); - expect(printed).toContain( - 'docker compose -f compose.yml --env-file /box.env build caddy' - ); + await expect(upgrade()).rejects.toThrow(/command output withheld/); + expect(compact().filter((step) => step === 'docker compose build caddy')).toHaveLength(2); + expect(runRollback).toHaveBeenCalledOnce(); }); it('never passes --build to docker compose', async () => { diff --git a/scripts/selfhost/upgrade.ts b/scripts/selfhost/upgrade.ts index a45bf8b0d6..7b8c60a54e 100644 --- a/scripts/selfhost/upgrade.ts +++ b/scripts/selfhost/upgrade.ts @@ -4,44 +4,46 @@ * Fetch and check out a SAM git ref, migrate, deploy, restart the stack only when its compose * inputs changed, verify health and print how to roll back (upgrade-lib.ts). * - * It takes NO automatic backup. Copy the fleet bucket (CELLD_BUCKET) and the .state directory - * yourself first: an upgrade that carries a D1 migration can only be rolled back from such a copy. + * Every upgrade takes an encrypted snapshot and automatically restores it on failure. */ import { join, resolve } from 'node:path'; import { parseArgs } from 'node:util'; -import { celldPort, SELFHOST_DIR } from './deploy-steps.js'; +import { celldPort, SELFHOST_DIR, waitForHealth } from './deploy-steps.js'; +import { assertOperatorExecution } from './operator-only.js'; import { loadBox, runUpgrade } from './upgrade-lib.js'; +assertOperatorExecution(); + const { values } = parseArgs({ options: { to: { type: 'string' }, 'box-env': { type: 'string' }, 'state-dir': { type: 'string' }, secrets: { type: 'string' }, + 'backup-to': { type: 'string' }, + 'encryption-key-file': { type: 'string' }, }, }); -if (!values.to) { - throw new Error( - '--to is required (a tag, branch or commit). selfhost:upgrade takes no automatic ' + - 'backup: copy the fleet bucket and .state first' - ); -} +if (!values.to) throw new Error('--to is required (a tag, branch or commit)'); // Each is passed on to every `pnpm selfhost:deploy` the upgrade runs (upgrade-lib.ts). const ctx = loadBox( resolve(values['box-env'] ?? join(SELFHOST_DIR, '.env')), values['state-dir'], - values.secrets + values.secrets, + values['encryption-key-file'] ); const port = celldPort(ctx.box); await runUpgrade(ctx, { to: values.to, + ...(values['backup-to'] ? { backupDir: resolve(values['backup-to']) } : {}), checkHealth: async () => { - // Same probe selfhost:deploy uses: the Worker on loopback, addressed as api.. - const res = await fetch(`http://127.0.0.1:${port}/health`, { - headers: { host: `api.${ctx.box.SAM_DOMAIN ?? ''}`, 'x-forwarded-proto': 'https' }, - }).catch(() => null); - return res?.ok ?? false; + try { + await waitForHealth(port, ctx.box.SAM_DOMAIN ?? ''); + return true; + } catch { + return false; + } }, }); diff --git a/tasks/active/2026-11-19-l24-selfhost-operations.md b/tasks/active/2026-11-19-l24-selfhost-operations.md new file mode 100644 index 0000000000..760bce7b32 --- /dev/null +++ b/tasks/active/2026-11-19-l24-selfhost-operations.md @@ -0,0 +1,49 @@ +# L24 self-host operations + +## Problem + +Land backup, restore, upgrade checks and teardown from `sam/selfhost-pass-2` onto fresh main without importing unrelated self-host features. Fix F22/F23/F24 and include #2703 teardown error handling. + +## Research and preflight + +- Classes: security-sensitive, infrastructure, cross-component, business logic, documentation. +- Main base `917077fef` includes L22 deploy/upgrade harness; operations are otherwise only on integration. Paths imported with `git checkout origin/sam/selfhost-pass-2 -- `, never cherry-picked. +- Backup directory contains Worker secrets in bucket manifests, platform keys, environment and state. Encrypt complete backup tree with separate operator key, reject CI use, sanitize failures. Policy 795e72a6 applies. +- Historical backup live-copy races and gcloud tracker failures are hypotheses until reproduced on BOX (#2675/#2677). +- celld native manifests flatten DO migrations; compare deployed classes and canonical generated migration history before deployment. Include H2 `selfhost-hosted-git-v1`. +- Shared unowned firewalls cannot be deleted safely; new self-host creation receipts must prove immutable resource identity and installation/environment scope before delete. No name adoption. +- `--keep-data` must retain WIF identities, data and key access. Compose identity must be unique per install. +- s3 operator signing region is already validated by main box-settings.ts; retain regression coverage/docs. + +## Implementation checklist + +- [ ] Port and trim operations paths only; keep all self-host code under deploy/selfhost or scripts/selfhost. +- [ ] Encrypt all persisted backup payloads; external key, authentication, failure cleanup and secret-free diagnostics. +- [ ] Restore only into empty target, validate all encrypted payloads before mutation; verify actual data round trip. +- [ ] Reproduce backup failure on BOX, fix evidence-based cause and add regression. +- [ ] Upgrade preflight rejects unknown/reordered DO tags, including H2; valid check passes. +- [ ] Automatic upgrade rollback restores previous consistent state and reports rollback failure clearly. +- [ ] Unique compose projects, exact ownership proof for destructive operations; no legacy adoption. +- [ ] Keep-data retains data plus needed identity; permission errors remain visible, never treated as absence. +- [ ] Documentation and CLI command wiring updated, including S3 region. +- [ ] Relevant automated checks; independent security and task-completion reviews on current head. +- [ ] BOX claimed after FREE; real backup, disposable restore with data verified, passing/refused upgrades. +- [ ] Disposable owned teardown proven; all resources cleaned, BOX healthy, BOX FREE posted. +- [ ] Merge latest main, current-head CI/CodeRabbit/reviews, announce merge, merge, real production deploy success, SHIPPED idea note. + +## Acceptance criteria + +Each checklist item is required. BOX evidence must come from real operations and disposable owned resources; never teardown shared box data. No secret values in output, PR, Actions or scratch logs. Stop for any missing secret/permission. Local scratch only `.tmp/`; no sudo/apt. + +## References + +Idea 01M72M9AEB933ZY8269D376DKC LANDING PLAN part 6; policy 795e72a6; rule 56 destructive ownership; /do; task 01M7TTKAS78AMJ3853S5N4BYAK; channel feature.selfhost-landing. + +## BOX reproduction 1 (2026-11-19 21:44–21:47 UTC) + +- Claimed before access: channel sequence412/event8ef78fe4. Original BOX checkout e7ac643b, four legacy sam-selfhost containers. +- Current BOX has no backup CLI/package script after L22 trimming: first invocation exits254 (command missing), no data operation. Used historical f09a294ae backup algorithm copied to private `.tmp/l24` and actual gcloud/docker against original store. +- Historical backup failed: live pre-copy incomplete; stopped delta `gcloud storage rsync` failed; structured safe result `{ok:false, reasonClass:rsync, liveIncomplete:true}`. Wrapper captured neither exact gcloud exit code nor full stderr before yielding, so underlying F23 cause remains UNCONFIRMED. Do not infer the old tracker hypothesis is proved. +- finally restarted celld; verified all four original containers running, API health200, checkout unchanged. No config/bucket writes or candidate deploy. +- Coordinator mistakenly gave L23 overlapping claim413 from frozen history; acknowledged L24 claim412 was first. L24 yielded, BOX FREE414. L24 explicitly next after L23 releases. +- Own partial backup/code/log removed, metadata SSH key absence and own firewall404 verified, local token/private key removed. Existing saml24 OS account has no key. From 4c41531c4f17d0a77411cf06645266e424673d6d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rapha=C3=ABl=20Titsworth-Morin?= Date: Thu, 19 Nov 2026 22:21:44 +0000 Subject: [PATCH 02/17] fix(selfhost): prove rollback and teardown ownership at deletion --- deploy/selfhost/README.md | 19 +- scripts/quality/check-no-secret-readback.ts | 4 + .../operator-backup-exceptions.test.ts | 92 +++++++ scripts/quality/operator-backup-exceptions.ts | 149 ++++++++++ scripts/selfhost/backup-cli.ts | 9 +- scripts/selfhost/backup-encryption.ts | 2 +- scripts/selfhost/backup-entrypoint.test.ts | 49 +++- scripts/selfhost/backup-lib.ts | 92 +++---- scripts/selfhost/backup-manifest.ts | 37 +++ scripts/selfhost/backup-paths.ts | 3 +- scripts/selfhost/backup-recovery.ts | 165 ++++++++--- scripts/selfhost/backup.test.ts | 257 +++++++++++++++++- scripts/selfhost/deploy.ts | 4 +- scripts/selfhost/install-record.ts | 70 ++++- .../selfhost/live/backup-cache.live.test.ts | 96 +++++++ .../selfhost/live/backup-restore.live.test.ts | 8 +- scripts/selfhost/operator-ci-guard.test.ts | 9 +- scripts/selfhost/restore.ts | 20 +- scripts/selfhost/teardown-box.ts | 33 ++- scripts/selfhost/teardown-compose.ts | 203 +++++++++++--- scripts/selfhost/teardown-gcp-bootstrap.ts | 4 +- scripts/selfhost/teardown-gcp.ts | 21 +- scripts/selfhost/teardown-model.ts | 8 +- scripts/selfhost/teardown-state-dir.ts | 89 +++++- scripts/selfhost/teardown-state.test.ts | 69 +++-- scripts/selfhost/teardown.test.ts | 148 +++++++++- scripts/selfhost/teardown.ts | 2 + scripts/selfhost/testdata/fake-docker.mjs | 6 + scripts/selfhost/upgrade-lib.ts | 2 + scripts/selfhost/upgrade-preflight.test.ts | 7 +- scripts/selfhost/upgrade-safeguards.test.ts | 49 ++++ scripts/selfhost/upgrade.test.ts | 1 + .../2026-11-19-l24-selfhost-operations.md | 16 +- 33 files changed, 1489 insertions(+), 254 deletions(-) create mode 100644 scripts/quality/operator-backup-exceptions.test.ts create mode 100644 scripts/quality/operator-backup-exceptions.ts create mode 100644 scripts/selfhost/backup-manifest.ts create mode 100644 scripts/selfhost/live/backup-cache.live.test.ts diff --git a/deploy/selfhost/README.md b/deploy/selfhost/README.md index e94296a33b..1a77a8b8b5 100644 --- a/deploy/selfhost/README.md +++ b/deploy/selfhost/README.md @@ -102,7 +102,8 @@ The fleet bucket contains Worker secrets as well as application data. The backup It briefly stops celld for a consistent second bucket copy and restarts it even if that copy fails (`scripts/selfhost/backup-lib.ts:runBackup`, `runPlainBackup`). Temporary plaintext lives under the private `.tmp/selfhost-backups/` directory and is removed on success or failure. -Backup, restore and upgrade are operator-box commands; they refuse GitHub Actions. +Backup, restore, upgrade and teardown are operator-box commands. They refuse execution whenever +`CI`, `GITHUB_ACTIONS` or any `RUNNER_*` variable is present, even with an empty or false value. Create a separate raw 32-byte key once. These commands write the key directly to a private file; they do not print it, and refuse to overwrite an existing key: @@ -124,7 +125,7 @@ bucket deployment manifests when diagnosing a failure. Restore into a fresh disposable or replacement installation using the same SAM checkout/ref as the original backup. Prepare an existing mode-0600 target `.env` with its own domain, object-store -settings, absolute state path and installation-specific Compose project. Its state directory +settings and absolute state path. Its state directory must be empty or absent, and its bucket/prefix must contain no objects. For an `s3://` store, set `R2_S3_REGION` as well as `S3_ENDPOINT` and its credentials. @@ -135,9 +136,13 @@ pnpm selfhost:restore --from /absolute/path/to/backup \ ``` Restore authenticates the complete encrypted inventory and every file before touching the target. -It copies state and bucket data, keeps the target `.env`, strips the source installation's -creation receipts, and leaves celld stopped. Follow the printed checkout and Compose commands -to start the recovered install, then verify its data (`scripts/selfhost/backup-lib.ts:runRestore`). +It refuses a target project with existing containers, copies state and bucket data, keeps the +target `.env`, strips the source installation's creation receipts, and does not start celld. On the original SAM ref, run `selfhost:deploy --init` +to retain the restored keys and establish new target ownership receipts. Set the target `.env`'s +`COMPOSE_PROJECT_NAME` to the canonical project name init prints; the name incorporates the +persisted installation id, domain and state directory. Repeat init with that setting, then start +that target's Compose stack, deploy and verify its data (`scripts/selfhost/backup-lib.ts:runRestore`, +`scripts/selfhost/install-record.ts:recordInstall`). This command refuses an occupied target; it does not overwrite an existing fleet. ## Upgrade @@ -198,7 +203,9 @@ account and IAM grants. The retained data keeps the identity needed to use it ag `--remove-everything` also removes proven-owned local volumes/state and cloud resources recorded as created for this installation. It preserves backups unless `--delete-backups` is explicit, -and preserves local platform key material unless `--destroy-key` is explicit. It does not adopt +and preserves local platform key material unless `--destroy-key` is explicit. Images and custom networks remain manual cleanup steps because they may be shared. Docker cleanup +checks live container ids, configuration paths and volume creation identities immediately before +removing those exact resources; it does not run a broad Compose project sweep. It does not adopt resources because their names look familiar. Foreign, ambiguous, replaced and unrecorded resources are preserved; a refusal/failure returns a nonzero exit status. The summary lists retained data and manual cleanup steps (`scripts/selfhost/teardown.ts`, `teardown-model.ts:execute`). diff --git a/scripts/quality/check-no-secret-readback.ts b/scripts/quality/check-no-secret-readback.ts index 41043d2a68..405c703a25 100644 --- a/scripts/quality/check-no-secret-readback.ts +++ b/scripts/quality/check-no-secret-readback.ts @@ -37,6 +37,8 @@ import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs'; import { join, relative, resolve, sep } from 'node:path'; +import { operatorBackupAllowances } from './operator-backup-exceptions'; + export type RuleId = 'show-secrets' | 'decryption' | 'xtrace' | 'env-dump'; export interface Finding { @@ -250,7 +252,9 @@ export function scanText( ): ScanResult { const lines = text.split(/\r?\n/); const result: ScanResult = { findings: [], allowed: [], invalidMarkers: [] }; + const operatorDecryptLines = operatorBackupAllowances(file, text); const report = (index: number, rule: RuleId): void => { + if (rule === 'decryption' && operatorDecryptLines.has(index)) return; const finding: Finding = { file, line: index + 1, rule, text: lines[index].trim() }; const task = EXCUSABLE_RULES.has(rule) ? markerTask(lines, index, isAllowed) : null; if (task) result.allowed.push({ ...finding, task }); diff --git a/scripts/quality/operator-backup-exceptions.test.ts b/scripts/quality/operator-backup-exceptions.test.ts new file mode 100644 index 0000000000..d953d4ea2d --- /dev/null +++ b/scripts/quality/operator-backup-exceptions.test.ts @@ -0,0 +1,92 @@ +import { readFileSync } from 'node:fs'; +import { resolve } from 'node:path'; + +import ts from 'typescript'; +import { describe, expect, it } from 'vitest'; + +import { scanText } from './check-no-secret-readback'; + +const CASES = [ + ['scripts/selfhost/backup-encryption.ts', 'transformFile'], + ['scripts/selfhost/backup-lib.ts', 'runRestore'], + ['scripts/selfhost/backup-recovery.ts', 'runRollback'], +] as const; +const scan = (file: string, text: string) => scanText(file, text, () => false).findings; + +/** Delete the real first guard, so this control proves a missing failfast becomes a finding. */ +function removeGuard(text: string, name: string): string { + const source = ts.createSourceFile('operator.ts', text, ts.ScriptTarget.Latest, true); + const fn = source.statements.find( + (s) => ts.isFunctionDeclaration(s) && s.name?.text === name + ) as ts.FunctionDeclaration; + const guard = fn.body!.statements[0]; + expect(guard.getText(source)).toBe('assertOperatorExecution();'); + return text.slice(0, guard.getStart(source)) + text.slice(guard.end); +} + +describe('L24 operator-only backup scanner exception (policy 795e72a6)', () => { + it.each(CASES)( + 'permits only the approved shape in %s and makes guard deletion red', + (file, fn) => { + const text = readFileSync(resolve(file), 'utf8'); + expect(scan(file, text)).toEqual([]); + expect(scan(file, removeGuard(text, fn)).some((f) => f.rule === 'decryption')).toBe(true); + expect( + scan(`scripts/ci/${file.split('/').at(-1)}`, text).some((f) => f.rule === 'decryption') + ).toBe(true); + } + ); + + it.each(CASES)('still flags unrelated decryption, Pulumi reads and tracing in %s', (file) => { + const text = readFileSync(resolve(file), 'utf8'); + const additions = [ + 'crypto.subtle.decrypt(params, key, data);', + "const extra = createDecipheriv('aes-256-gcm', otherKey, nonce);", + "import { decryptToken } from './other-credentials';", + 'pulumi stack output --show-secrets', + 'set -x', + ]; + for (const addition of additions) expect(scan(file, `${text}\n${addition}\n`)).toHaveLength(1); + expect(scan(file.replace('.ts', '.sh'), 'printenv\n')).toMatchObject([{ rule: 'env-dump' }]); + }); + + it('pins envelope decryption to transformFile, AES-GCM arguments and one exact line', () => { + const file = CASES[0][0]; + const text = readFileSync(resolve(file), 'utf8'); + for (const changed of [ + text.replace('function transformFile(', 'function unrelated('), + text.replace( + "? createDecipheriv('aes-256-gcm', key, nonce)", + "? createDecipheriv('aes-256-gcm', otherKey, nonce)" + ), + text.replace( + "? createDecipheriv('aes-256-gcm', key, nonce)", + "? createDecipheriv('aes-256-gcm', key, nonce); crypto.subtle.decrypt(p, k, d)" + ), + ]) + expect(scan(file, changed).some((f) => f.rule === 'decryption')).toBe(true); + }); + + it.each(CASES.slice(1))( + 'refuses imported helper use outside its exact guarded function in %s', + (file, fn) => { + const text = readFileSync(resolve(file), 'utf8'); + const attached = text.replace( + /(from ['"]\.\/backup-encryption(?:\.js)?['"];)/, + '$1 crypto.subtle.decrypt(params, key, data);' + ); + expect(scan(file, attached).some((f) => f.rule === 'decryption')).toBe(true); + + expect( + scan(file, text.replace(`function ${fn}(`, 'function differentFunction(')).some( + (f) => f.rule === 'decryption' + ) + ).toBe(true); + expect( + scan(file, `${text}\nfunction other() { decryptBackupTree(from, dest, key); }`).some( + (f) => f.rule === 'decryption' + ) + ).toBe(true); + } + ); +}); diff --git a/scripts/quality/operator-backup-exceptions.ts b/scripts/quality/operator-backup-exceptions.ts new file mode 100644 index 0000000000..874d81fb45 --- /dev/null +++ b/scripts/quality/operator-backup-exceptions.ts @@ -0,0 +1,149 @@ +/** + * L24, policy 795e72a6: encrypted backups are operator-only. Pin exact files, functions, + * import bindings and AES-GCM arguments; require entry guards. This grants no CI decryption. + * operator-ci-guard.test.ts proves every CI signal refuses before filesystem reads. + */ +import ts from 'typescript'; + +export function operatorBackupAllowances(file: string, text: string): ReadonlySet { + const allowed = new Set(); + if ( + ![ + 'scripts/selfhost/backup-encryption.ts', + 'scripts/selfhost/backup-lib.ts', + 'scripts/selfhost/backup-recovery.ts', + ].includes(file) + ) + return allowed; + const source = ts.createSourceFile(file, text, ts.ScriptTarget.Latest, true); + const functions = new Map(); + for (const statement of source.statements) { + if (ts.isFunctionDeclaration(statement) && statement.name) + functions.set(statement.name.text, statement); + } + const guarded = (name: string): boolean => { + const first = functions.get(name)?.body?.statements[0]; + return ( + first !== undefined && + ts.isExpressionStatement(first) && + ts.isCallExpression(first.expression) && + ts.isIdentifier(first.expression.expression) && + first.expression.expression.text === 'assertOperatorExecution' && + first.expression.arguments.length === 0 + ); + }; + const guardImport = source.statements.some( + (statement) => + ts.isImportDeclaration(statement) && + ts.isStringLiteral(statement.moduleSpecifier) && + ['./operator-only', './operator-only.js'].includes(statement.moduleSpecifier.text) && + statement.importClause?.namedBindings && + ts.isNamedImports(statement.importClause.namedBindings) && + statement.importClause.namedBindings.elements.some( + (binding) => binding.name.text === 'assertOperatorExecution' && !binding.propertyName + ) + ); + if (!guardImport) return allowed; + const lineOf = (node: ts.Node) => + source.getLineAndCharacterOfPosition(node.getStart(source)).line; + if (file === 'scripts/selfhost/backup-encryption.ts') { + if ( + !['readBackupKey', 'encryptBackupTree', 'decryptBackupTree', 'transformFile'].every(guarded) + ) + return allowed; + const body = functions.get('transformFile')?.body; + if (!body) return allowed; + const candidates: ts.CallExpression[] = []; + const visit = (node: ts.Node): void => { + if ( + ts.isCallExpression(node) && + ts.isIdentifier(node.expression) && + node.expression.text === 'createDecipheriv' + ) + candidates.push(node); + ts.forEachChild(node, visit); + }; + visit(body); + if (candidates.length !== 1) return allowed; + const call = candidates[0]; + let owner: ts.Node = call; + while (owner.parent && !ts.isFunctionLike(owner)) owner = owner.parent; + if (owner !== functions.get('transformFile')) return allowed; + const args = call.arguments; + const line = text.split(/\r?\n/)[lineOf(call)].trim(); + if ( + args.length === 3 && + ts.isStringLiteral(args[0]) && + args[0].text === 'aes-256-gcm' && + ts.isIdentifier(args[1]) && + args[1].text === 'key' && + ts.isIdentifier(args[2]) && + args[2].text === 'nonce' && + line === `? ${call.getText(source)}` + ) + allowed.add(lineOf(call)); + return allowed; + } + const functionName = file === 'scripts/selfhost/backup-lib.ts' ? 'runRestore' : 'runRollback'; + if (!guarded(functionName)) return allowed; + const expectedNames = + functionName === 'runRestore' + ? ['decryptBackupTree', 'encryptBackupTree', 'readBackupKey'] + : ['decryptBackupTree']; + let importNode: ts.ImportDeclaration | undefined; + for (const statement of source.statements) { + if ( + !ts.isImportDeclaration(statement) || + !ts.isStringLiteral(statement.moduleSpecifier) || + !['./backup-encryption', './backup-encryption.js'].includes(statement.moduleSpecifier.text) + ) + continue; + const bindings = statement.importClause?.namedBindings; + if ( + !bindings || + !ts.isNamedImports(bindings) || + bindings.elements.some((binding) => binding.propertyName) + ) + return allowed; + if ( + bindings.elements + .map((binding) => binding.name.text) + .sort() + .join(',') !== expectedNames.sort().join(',') || + importNode + ) + return allowed; + importNode = statement; + } + if (!importNode) return allowed; + const endLine = source.getLineAndCharacterOfPosition(importNode.end).line; + if ( + text + .split(/\r?\n/) + .slice(lineOf(importNode), endLine + 1) + .join('\n') + .trim() !== importNode.getText(source) + ) + return allowed; + let valid = true; + let calls = 0; + const visit = (node: ts.Node): void => { + if ( + ts.isIdentifier(node) && + node.text === 'decryptBackupTree' && + !ts.isImportSpecifier(node.parent) + ) { + if (!ts.isCallExpression(node.parent) || node.parent.expression !== node) valid = false; + else { + calls++; + let parent: ts.Node = node.parent; + while (parent.parent && !ts.isFunctionLike(parent)) parent = parent.parent; + if (parent !== functions.get(functionName)) valid = false; + } + } + ts.forEachChild(node, visit); + }; + visit(source); + if (valid && calls === 1) allowed.add(lineOf(importNode)); + return allowed; +} diff --git a/scripts/selfhost/backup-cli.ts b/scripts/selfhost/backup-cli.ts index 8560dbb2a4..0e3771199e 100644 --- a/scripts/selfhost/backup-cli.ts +++ b/scripts/selfhost/backup-cli.ts @@ -1,13 +1,14 @@ -import { assertOperatorExecution } from './operator-only'; /** * Shared CLI plumbing for `pnpm selfhost:backup` and `pnpm selfhost:restore` (backup-lib.ts). */ import { spawnSync } from 'node:child_process'; -import { existsSync, readFileSync } from 'node:fs'; +import { existsSync } from 'node:fs'; import { dirname, join, resolve } from 'node:path'; import { type BoxContext, composeFilesFor, type RunResult } from './backup-lib'; -import { assertPrivateFile, parseDotenv } from './secret-files'; +import { loadBoxEnv } from './box-settings'; +import { assertOperatorExecution } from './operator-only'; +import { assertPrivateFile } from './secret-files'; export const REPO_ROOT = resolve(import.meta.dirname, '../..'); export const SELFHOST_DIR = join(REPO_ROOT, 'deploy/selfhost'); @@ -42,7 +43,7 @@ export function loadBox( assertOperatorExecution(); if (!existsSync(envFile)) throw new Error(`${envFile} does not exist`); assertPrivateFile(envFile); - const box = parseDotenv(readFileSync(envFile, 'utf8'), envFile); + const box = loadBoxEnv(envFile, SELFHOST_DIR); if (box.CELLD_BUCKET?.startsWith('s3://') && !box.R2_S3_REGION?.trim()) throw new Error('R2_S3_REGION is required for an s3:// operator store'); if (!box.CELLD_BUCKET) throw new Error(`${envFile}: CELLD_BUCKET is required`); diff --git a/scripts/selfhost/backup-encryption.ts b/scripts/selfhost/backup-encryption.ts index c5f08d1182..9a7b438ee7 100644 --- a/scripts/selfhost/backup-encryption.ts +++ b/scripts/selfhost/backup-encryption.ts @@ -1,4 +1,3 @@ -import { assertOperatorExecution } from './operator-only'; /** Operator-only backup encryption. The 32-byte key must be stored separately from backups. */ import { type CipherGCM, @@ -25,6 +24,7 @@ import { } from 'node:fs'; import { dirname, isAbsolute, join, relative, resolve, sep } from 'node:path'; +import { assertOperatorExecution } from './operator-only'; import { assertPrivateFile } from './secret-files.js'; // Versioned wire format: magic | 12-byte nonce | ciphertext | 16-byte GCM tag. diff --git a/scripts/selfhost/backup-entrypoint.test.ts b/scripts/selfhost/backup-entrypoint.test.ts index cfa7789121..9fe2b02c0b 100644 --- a/scripts/selfhost/backup-entrypoint.test.ts +++ b/scripts/selfhost/backup-entrypoint.test.ts @@ -24,6 +24,10 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import { decryptBackupTree } from './backup-encryption'; +const PLATFORM_KEYS = JSON.stringify({ + SAM_INSTALLATION_ID: 'a'.repeat(32), + ENCRYPTION_KEY: 'fixture-encryption-key', +}); const REPO = resolve(import.meta.dirname, '../..'); const TSX = join(REPO, 'node_modules/.bin/tsx'); let root: string; @@ -111,7 +115,7 @@ beforeEach(() => { ); mkdirSync(join(root, 'state')); - writeFileSync(join(root, 'state/platform-keys.json'), '{"k":"v"}'); + writeFileSync(join(root, 'state/platform-keys.json'), PLATFORM_KEYS); writeFileSync(join(root, 'box.env'), `CELLD_BUCKET=${FLEET}\n`, { mode: 0o600 }); }); @@ -121,6 +125,47 @@ afterEach(() => { }); describe('selfhost:backup and selfhost:restore (real entry points, fake gcloud)', () => { + it('uses shell bucket overrides and the explicit custom state directory through real child commands', () => { + env.CELLD_BUCKET = 'gs://override/celld'; + env.SAM_SELFHOST_STATE_DIR = join(root, 'wrong-state'); + put(join(root, 'gcs/override/celld'), { 'd1/main.ltx': 'shell-override-rows' }); + const custom = join(root, 'custom-state'); + mkdirSync(custom); + writeFileSync( + join(custom, 'platform-keys.json'), + JSON.stringify({ SAM_INSTALLATION_ID: 'a'.repeat(32) }) + ); + const dest = join(root, 'custom-backup'); + const result = run('backup.ts', [ + '--to', + dest, + '--box-env', + join(root, 'box.env'), + '--state-dir', + custom, + '--encryption-key-file', + join(root, 'backup-key'), + ]); + expect(result.status).toBe(0); + expect(result.stderr).toBe(''); + const plain = join(root, 'custom-inspection'); + decryptBackupTree(dest, plain, join(root, 'backup-key')); + try { + expect(tree(join(plain, 'bucket'))).toEqual({ 'd1/main.ltx': 'shell-override-rows' }); + expect(readFileSync(join(plain, 'state/platform-keys.json'), 'utf8')).toBe( + readFileSync(join(custom, 'platform-keys.json'), 'utf8') + ); + expect(JSON.parse(readFileSync(join(plain, 'backup-manifest.json'), 'utf8')).bucket).toBe( + env.CELLD_BUCKET + ); + } finally { + rmSync(plain, { recursive: true, force: true }); + } + expect( + readFileSync(join(root, 'fake/compose-state-dirs.log'), 'utf8').trim().split('\n') + ).toEqual([custom, custom]); + }, 60_000); + // Runs the real backup and restore entry points as child processes: give them room under load. it( 'backs up exactly the post-stop bucket when objects vanish between the passes, and restores it into an empty install', @@ -182,7 +227,7 @@ describe('selfhost:backup and selfhost:restore (real entry points, fake gcloud)' expect(restore.stderr).toBe(''); expect(restore.status).toBe(0); expect(tree(join(root, 'gcs/fresh/celld'))).toEqual(afterStop); - expect(tree(join(root, 'new-state'))).toEqual({ 'platform-keys.json': '{"k":"v"}' }); + expect(tree(join(root, 'new-state'))).toEqual({ 'platform-keys.json': PLATFORM_KEYS }); } ); }); diff --git a/scripts/selfhost/backup-lib.ts b/scripts/selfhost/backup-lib.ts index 9cd04fa0b9..2d7143f814 100644 --- a/scripts/selfhost/backup-lib.ts +++ b/scripts/selfhost/backup-lib.ts @@ -1,24 +1,24 @@ -import { assertOperatorExecution } from './operator-only'; /** Encrypted operator backups with a stopped-writer consistency boundary. */ import { cpSync, - lstatSync, - mkdtempSync, - realpathSync, existsSync, + lstatSync, mkdirSync, + mkdtempSync, readdirSync, - readFileSync, + realpathSync, renameSync, rmSync, writeFileSync, } from 'node:fs'; -import { join, relative, resolve, dirname } from 'node:path'; +import { dirname, join, relative, resolve } from 'node:path'; -import { recordBackup, composeProjectFor } from './install-record'; -import { assertOperationPaths, assertBackupOutside } from './backup-paths'; import { decryptBackupTree, encryptBackupTree, readBackupKey } from './backup-encryption'; -import { ensurePrivateDir } from './secret-files'; +import { readManifest } from './backup-manifest'; +import { assertBackupOutside, assertOperationPaths } from './backup-paths'; +import { composeProjectFor, expectedComposeProjectFor, recordBackup } from './install-record'; +import { assertOperatorExecution } from './operator-only'; +import { ensurePrivateDir, readPrivateJson } from './secret-files'; /** * Rebuildable caches under the state dir, left out of every backup. `go-cache` is the vm-agent @@ -219,8 +219,15 @@ export function composeArgs( ]; } +export function composeRunEnv(ctx: Pick): NodeJS.ProcessEnv { + return { ...process.env, SAM_SELFHOST_STATE_DIR: resolve(ctx.stateDir) }; +} + function compose(ctx: BoxContext, args: string[]): void { - check(ctx.run('docker', composeArgs(ctx, args)), `docker compose ${args.join(' ')}`); + check( + ctx.run('docker', composeArgs(ctx, args), composeRunEnv(ctx)), + `docker compose ${args.join(' ')}` + ); } export interface BackupManifest { @@ -282,10 +289,9 @@ function runPlainBackup( // // The pre-copy goes to its own directory. An aborted gcloud pass leaves state keyed by the // destination path it was writing (resumable-download tracker files, `_.gstmp` temporaries), and - // a second rsync into the SAME paths tripped over it on the box: `[Errno 2] No such file or - // directory: /bucket/nodes/node_.json` for objects celld removed between the passes. - // Renaming the tree before the delta copy means gcloud has no state for any destination path it - // is about to write; only the bytes carry over. + // the historical box failure reported a missing local nodes/node_.json path. Tracker + // reuse is a hypothesis requiring live confirmation, so isolate the second pass from the + // first pass's destination paths and retain a clean-copy fallback. Only bytes carry over. try { pullBucket(ctx, liveDir); } catch (err) { @@ -362,39 +368,6 @@ function runPlainBackup( return manifest; } -export function readManifest(dir: string): BackupManifest { - const path = join(dir, MANIFEST_NAME); - if (!existsSync(path)) throw new Error(`${dir} has no ${MANIFEST_NAME}; not a backup`); - let parsed: unknown; - try { - parsed = JSON.parse(readFileSync(path, 'utf8')); - } catch { - throw new Error('Invalid backup manifest'); - } - if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) - throw new Error('Invalid backup manifest'); - const item = parsed as Record; - if ( - item.version !== 1 || - typeof item.createdAt !== 'string' || - !/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/.test(item.createdAt) || - !Number.isFinite(Date.parse(item.createdAt)) || - !( - item.samCommit === null || - (typeof item.samCommit === 'string' && /^[0-9a-f]{40}$/.test(item.samCommit)) - ) || - typeof item.bucket !== 'string' || - ['precopyMs', 'downtimeMs', 'deltaCopyMs', 'objectCount'].some( - (name) => - typeof item[name] !== 'number' || !Number.isFinite(item[name]) || (item[name] as number) < 0 - ) - ) { - throw new Error('Invalid backup manifest'); - } - parseBucketUrl(item.bucket); - return parsed as BackupManifest; -} - /** * Restore `from` into an empty install: the target bucket (the CELLD_BUCKET in ctx.box) must be * empty and the target `.state/` must have no platform keys. celld stays stopped; the caller @@ -408,8 +381,25 @@ function runPlainRestore(ctx: BoxContext, from: string): BackupManifest { if (!bucketIsEmpty(ctx)) { throw new Error(`${ctx.box.CELLD_BUCKET} is not empty: restore only into an empty bucket`); } - // Harmless when the stack is not up; required so no celld writes while the bucket fills. - compose(ctx, ['stop', 'celld']); + // Fresh state has no gateway.env, so even 'compose stop' would fail config validation. + // Refuse any existing target runtime without parsing a not-yet-created Compose stack. + const sourceIdentity = readPrivateJson( + join(from, STATE_DIR, 'platform-keys.json') + ).SAM_INSTALLATION_ID; + if (typeof sourceIdentity !== 'string' || !/^[a-f0-9]{32}$/.test(sourceIdentity)) + throw new Error('Invalid backup installation identity'); + const projects = new Set([ + composeProjectFor(ctx.box, ctx.stateDir), + expectedComposeProjectFor(ctx.box, ctx.stateDir, sourceIdentity), + ]); + for (const project of projects) { + const containers = check( + ctx.run('docker', ['ps', '-aq', '--filter', `label=com.docker.compose.project=${project}`]), + 'check empty restore runtime' + ); + if (containers.stdout.trim()) + throw new Error('Restore target already has containers; use a fresh installation'); + } ctx.log(`copying ${manifest.objectCount} objects into ${ctx.box.CELLD_BUCKET}`); pushBucket(ctx, join(from, BUCKET_DIR)); ensurePrivateDir(ctx.stateDir); @@ -487,6 +477,6 @@ export function runRestore(ctx: BoxContext, from: string): BackupManifest { } } -export { runRollback } from './backup-recovery'; - +export { readManifest } from './backup-manifest'; export { assertBackupOutside } from './backup-paths'; +export { assertRollbackCacheReady, runRollback } from './backup-recovery'; diff --git a/scripts/selfhost/backup-manifest.ts b/scripts/selfhost/backup-manifest.ts new file mode 100644 index 0000000000..d34eae7920 --- /dev/null +++ b/scripts/selfhost/backup-manifest.ts @@ -0,0 +1,37 @@ +/** Validate decrypted backup metadata without reflecting arbitrary payloads into logs. */ +import { existsSync, readFileSync } from 'node:fs'; +import { join } from 'node:path'; + +import { type BackupManifest, MANIFEST_NAME, parseBucketUrl } from './backup-lib'; +export function readManifest(dir: string): BackupManifest { + const path = join(dir, MANIFEST_NAME); + if (!existsSync(path)) throw new Error(`${dir} has no ${MANIFEST_NAME}; not a backup`); + let parsed: unknown; + try { + parsed = JSON.parse(readFileSync(path, 'utf8')); + } catch { + throw new Error('Invalid backup manifest'); + } + if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) + throw new Error('Invalid backup manifest'); + const item = parsed as Record; + if ( + item.version !== 1 || + typeof item.createdAt !== 'string' || + !/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/.test(item.createdAt) || + !Number.isFinite(Date.parse(item.createdAt)) || + !( + item.samCommit === null || + (typeof item.samCommit === 'string' && /^[0-9a-f]{40}$/.test(item.samCommit)) + ) || + typeof item.bucket !== 'string' || + ['precopyMs', 'downtimeMs', 'deltaCopyMs', 'objectCount'].some( + (name) => + typeof item[name] !== 'number' || !Number.isFinite(item[name]) || (item[name] as number) < 0 + ) + ) { + throw new Error('Invalid backup manifest'); + } + parseBucketUrl(item.bucket); + return parsed as BackupManifest; +} diff --git a/scripts/selfhost/backup-paths.ts b/scripts/selfhost/backup-paths.ts index 080986ff68..b353986bf9 100644 --- a/scripts/selfhost/backup-paths.ts +++ b/scripts/selfhost/backup-paths.ts @@ -1,7 +1,8 @@ /** Validate backup/restore filesystem boundaries before any mutation. */ import { existsSync, lstatSync, realpathSync } from 'node:fs'; -import { dirname, resolve } from 'node:path'; import { homedir } from 'node:os'; +import { dirname, resolve } from 'node:path'; + import type { BoxContext } from './backup-lib'; /** Refuse ambiguous paths before reading a bucket or changing any local/cloud state. */ export function assertOperationPaths(ctx: BoxContext): void { diff --git a/scripts/selfhost/backup-recovery.ts b/scripts/selfhost/backup-recovery.ts index efec38b3d0..d31363f0d8 100644 --- a/scripts/selfhost/backup-recovery.ts +++ b/scripts/selfhost/backup-recovery.ts @@ -1,29 +1,34 @@ -import { assertOperatorExecution } from './operator-only'; /** Restore an upgrade's authenticated snapshot to the same owned installation. */ -import { cpSync, readFileSync, rmSync } from 'node:fs'; +import { cpSync, lstatSync, readFileSync, rmSync } from 'node:fs'; import { join, resolve } from 'node:path'; + +import { readRecord } from '../../deploy/selfhost/created-resources.mjs'; import { decryptBackupTree } from './backup-encryption'; import { - type BoxContext, assertBackupOutside, backupKey, backupScratch, + type BoxContext, BUCKET_DIR, - STATE_DIR, - ENV_FILE, - readManifest, + bucketPath, check, composeArgs, - parseBucketUrl, - bucketPath, + composeRunEnv, + ENV_FILE, mcArgs, mcEnv, + parseBucketUrl, + readManifest, + STATE_DIR, } from './backup-lib'; -import { readRecord } from '../../deploy/selfhost/created-resources.mjs'; +import { composeProjectFor, recordInstall } from './install-record'; +import { assertOperatorExecution } from './operator-only'; import { assertRollbackReady } from './upgrade-preflight'; -import { composeProjectFor } from './install-record'; function compose(ctx: BoxContext, args: string[]): void { - check(ctx.run('docker', composeArgs(ctx, args)), 'rollback compose operation'); + check( + ctx.run('docker', composeArgs(ctx, args), composeRunEnv(ctx)), + 'rollback compose operation' + ); } function readIdentity(path: string): Record { try { @@ -34,7 +39,7 @@ function readIdentity(path: string): Record { throw new Error('Cannot verify rollback installation identity'); } } -function assertStateReceipt(path: string, expected: string, id: unknown): void { +function assertStateReceipt(path: string, expected: string, id: unknown, live = false): void { let record; try { record = readRecord(join(path, 'created-resources.json')); @@ -55,39 +60,112 @@ function assertStateReceipt(path: string, expected: string, id: unknown): void { ) { throw new Error('Rollback state directory has no exact installation ownership receipt'); } + const attributes = states[0]?.attributes; + if (attributes?.installation !== id) + throw new Error('Rollback state receipt has a foreign installation'); + if (live) { + const stat = lstatSync(path); + if ( + !stat.isDirectory() || + stat.isSymbolicLink() || + attributes.device !== String(stat.dev) || + attributes.inode !== String(stat.ino) + ) { + throw new Error('Rollback state directory identity changed; refusing removal'); + } + } +} + +export interface RollbackCacheProof { + name: string; + createdAt: string; + container: string; } -/** Drop only this compose project's disposable celld cache, never its fleet store. */ -function discardCelldCache(ctx: BoxContext): void { +function inspectCacheVolume(ctx: BoxContext): { name: string; createdAt: string } { const project = composeProjectFor(ctx.box, ctx.stateDir); - assertRollbackReady(ctx); const name = `${project}_celld-data`; - const inspect = () => { - const result = check( - ctx.run('docker', ['volume', 'inspect', name]), - 'inspect celld cache ownership' - ); - let value: unknown; - try { - value = JSON.parse(result.stdout); - } catch { - throw new Error('Cannot verify celld cache ownership'); - } - if (!Array.isArray(value) || value.length !== 1) - throw new Error('Ambiguous celld cache ownership'); - const volume = value[0] as { Name?: unknown; Labels?: Record }; - if ( - volume?.Name !== name || - volume.Labels?.['com.docker.compose.project'] !== project || - volume.Labels?.['com.docker.compose.volume'] !== 'celld-data' - ) { - throw new Error('Foreign celld cache; refusing rollback cache removal'); - } + const result = check( + ctx.run('docker', ['volume', 'inspect', name]), + 'inspect celld cache ownership' + ); + let value: unknown; + try { + value = JSON.parse(result.stdout); + } catch { + throw new Error('Cannot verify celld cache ownership'); + } + if (!Array.isArray(value) || value.length !== 1) + throw new Error('Ambiguous celld cache ownership'); + const volume = value[0] as { + Name?: unknown; + Labels?: Record; + CreatedAt?: unknown; }; - inspect(); - compose(ctx, ['rm', '--stop', '--force', 'celld']); - inspect(); - check(ctx.run('docker', ['volume', 'rm', name]), 'remove owned celld cache'); + if ( + volume?.Name !== name || + volume.Labels?.['com.docker.compose.project'] !== project || + volume.Labels?.['com.docker.compose.volume'] !== 'celld-data' + ) + throw new Error('Foreign celld cache; refusing rollback cache removal'); + if (typeof volume.CreatedAt !== 'string' || !Number.isFinite(Date.parse(volume.CreatedAt))) + throw new Error('Cannot verify celld cache creation identity'); + return { name, createdAt: volume.CreatedAt }; +} + +/** Prove the actual selected celld container uses the canonical owned cache before an upgrade. */ +export function assertRollbackCacheReady(ctx: BoxContext): RollbackCacheProof { + assertOperatorExecution(); + assertRollbackReady(ctx); + const selected = check( + ctx.run( + 'docker', + composeArgs(ctx, ['ps', '--all', '--no-trunc', '-q', 'celld']), + composeRunEnv(ctx) + ), + 'inspect rollback celld container' + ) + .stdout.trim() + .split(/\s+/); + if (selected.length !== 1 || !/^[a-f0-9]{64}$/.test(selected[0] ?? '')) + throw new Error('Cannot verify one rollback celld container'); + const container = selected[0] ?? ''; + const result = check( + ctx.run('docker', ['inspect', '--format', '{{json .Mounts}}', container]), + 'inspect rollback celld cache mount' + ); + let mounts: unknown; + try { + mounts = JSON.parse(result.stdout); + } catch { + throw new Error('Cannot verify rollback celld cache mount'); + } + if (!Array.isArray(mounts) || mounts.some((mount) => typeof mount !== 'object' || mount === null)) + throw new Error('Cannot verify rollback celld cache mount'); + const caches = mounts.filter((mount) => mount.Destination === '/var/lib/celld'); + const proof = inspectCacheVolume(ctx); + if (caches.length !== 1 || caches[0]?.Type !== 'volume' || caches[0]?.Name !== proof.name) + throw new Error('Selected celld cache mount is not the canonical owned volume'); + return { ...proof, container }; +} + +/** Re-prove the active mount and immutable volume creation identity immediately before removal. */ +function discardCelldCache(ctx: BoxContext, expected: RollbackCacheProof): void { + const current = assertRollbackCacheReady(ctx); + if ( + current.name !== expected.name || + current.createdAt !== expected.createdAt || + current.container !== expected.container + ) + throw new Error('Rollback celld cache identity changed; refusing removal'); + check( + ctx.run('docker', ['container', 'rm', '--force', expected.container]), + 'remove exact rollback celld container' + ); + const after = inspectCacheVolume(ctx); + if (after.name !== expected.name || after.createdAt !== expected.createdAt) + throw new Error('Rollback celld cache identity changed; refusing removal'); + check(ctx.run('docker', ['volume', 'rm', expected.name]), 'remove owned celld cache'); } /** @@ -114,9 +192,10 @@ export function runRollback(ctx: BoxContext, from: string): void { throw new Error('Rollback snapshot belongs to a different installation'); } assertStateReceipt(join(plain, STATE_DIR), ctx.stateDir, oldKeys.SAM_INSTALLATION_ID); - assertStateReceipt(ctx.stateDir, ctx.stateDir, currentKeys.SAM_INSTALLATION_ID); + assertStateReceipt(ctx.stateDir, ctx.stateDir, currentKeys.SAM_INSTALLATION_ID, true); + const cache = assertRollbackCacheReady(ctx); compose(ctx, ['stop', 'celld']); - discardCelldCache(ctx); + discardCelldCache(ctx, cache); const url = parseBucketUrl(ctx.box.CELLD_BUCKET ?? ''); const source = join(plain, BUCKET_DIR); if (url.scheme === 'gs') { @@ -146,9 +225,11 @@ export function runRollback(ctx: BoxContext, from: string): void { ); } // State may hold new generated files: replace it, retaining the source ownership receipts. + assertStateReceipt(ctx.stateDir, ctx.stateDir, currentKeys.SAM_INSTALLATION_ID, true); rmSync(ctx.stateDir, { recursive: true, force: true }); cpSync(join(plain, STATE_DIR), ctx.stateDir, { recursive: true }); cpSync(join(plain, ENV_FILE), ctx.envFile); + recordInstall(ctx.stateDir, ctx.envFile, ctx.box, oldKeys.SAM_INSTALLATION_ID as string); } finally { rmSync(temp, { recursive: true, force: true }); } diff --git a/scripts/selfhost/backup.test.ts b/scripts/selfhost/backup.test.ts index a9a4b1c989..02e946b270 100644 --- a/scripts/selfhost/backup.test.ts +++ b/scripts/selfhost/backup.test.ts @@ -8,10 +8,12 @@ import { randomBytes } from 'node:crypto'; import { cpSync, existsSync, + lstatSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, + renameSync, rmSync, statSync, symlinkSync, @@ -19,10 +21,13 @@ import { } from 'node:fs'; import { basename, join, resolve } from 'node:path'; +import * as TOML from '@iarna/toml'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import type { WranglerToml } from '../deploy/types'; import { decryptBackupTree, encryptBackupTree } from './backup-encryption'; import { + assertRollbackCacheReady, type BoxContext, MANIFEST_NAME, OBJECTSTORE_IMAGE, @@ -31,9 +36,11 @@ import { type RunResult, runRollback, } from './backup-lib'; -import { recordInstall } from './install-record'; +import { buildCelldConfig } from './celld-config'; +import { prepareCelldProject, writeCelldConfig } from './celld-project'; +import { composeProjectFor, expectedComposeProjectFor, recordInstall } from './install-record'; -const PLATFORM_KEYS = JSON.stringify({ SAM_INSTALLATION_ID: 'test-installation' }); +const PLATFORM_KEYS = JSON.stringify({ SAM_INSTALLATION_ID: 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' }); const SECRET = 'store-secret-value-123'; let root: string; let calls: Array<{ command: string; args: string[]; env?: NodeJS.ProcessEnv }>; @@ -41,8 +48,16 @@ let clock: number; /** How many pulls after the live one fail (1: the delta copy; 2: the delta and the full copy). */ let failDeltaCopy: number; let failLiveCopy: boolean; -let cacheProof: 'owned' | 'foreign' | 'ambiguous' | 'changed'; +let cacheProof: + 'owned' | 'foreign' | 'ambiguous' | 'changed' | 'replaced' | 'replaced-after-remove'; +let cacheMount: 'canonical' | 'wrong' | 'duplicate' | 'bind' | 'changed'; +let mountInspections: number; +let selectedProject: string; +let replaceStateOnPush: boolean; +let celldStopped: boolean; let cacheInspections: number; +let targetContainers: string; +let occupiedProject: string | undefined; function tree(dir: string, base = dir): Record { const out: Record = {}; @@ -64,7 +79,38 @@ function fakeRun(command: string, args: string[], env?: NodeJS.ProcessEnv): RunR calls.push({ command, args, env }); clock += 1000; // every command takes one second of fake time const ok = { status: 0, stdout: '', stderr: '' }; - if (command === 'docker' && args[0] === 'compose') return ok; + if (command === 'docker' && args[0] === 'compose') { + if (args.includes('ps') && args.includes('-q') && args.at(-1) === 'celld') { + if (celldStopped && !args.includes('--all')) return ok; + selectedProject = args[args.indexOf('--project-name') + 1] ?? ''; + return { ...ok, stdout: 'c'.repeat(64) }; + } + if (args.at(-2) === 'stop') celldStopped = true; + if (args.at(-2) === 'start') celldStopped = false; + return ok; + } + if (command === 'docker' && args[0] === 'container' && args[1] === 'rm') return ok; + if (command === 'docker' && args[0] === 'inspect') { + mountInspections += 1; + const name = + cacheMount === 'wrong' || (cacheMount === 'changed' && mountInspections > 1) + ? 'overlay-other-cache' + : `${selectedProject}_celld-data`; + const mount = { + Destination: '/var/lib/celld', + Type: cacheMount === 'bind' ? 'bind' : 'volume', + Name: name, + }; + return { ...ok, stdout: JSON.stringify(cacheMount === 'duplicate' ? [mount, mount] : [mount]) }; + } + if (command === 'docker' && args[0] === 'ps') + return { + ...ok, + stdout: + !occupiedProject || args.includes(`label=com.docker.compose.project=${occupiedProject}`) + ? targetContainers + : '', + }; if (command === 'docker' && args[0] === 'volume') { if (args[1] === 'rm') return ok; if (args[1] === 'inspect') { @@ -75,6 +121,11 @@ function fakeRun(command: string, args: string[], env?: NodeJS.ProcessEnv): RunR cacheProof === 'foreign' || (cacheProof === 'changed' && cacheInspections > 1); const volume = { Name: name, + CreatedAt: + (cacheProof === 'replaced' && cacheInspections > 1) || + (cacheProof === 'replaced-after-remove' && cacheInspections > 2) + ? '2026-11-19T02:00:00Z' + : '2026-11-19T01:00:00Z', Labels: { 'com.docker.compose.project': foreign ? 'another-installation' : project, 'com.docker.compose.volume': 'celld-data', @@ -95,6 +146,15 @@ function fakeRun(command: string, args: string[], env?: NodeJS.ProcessEnv): RunR rmSync(to, { recursive: true, force: true }); mkdirSync(to, { recursive: true }); cpSync(from, to, { recursive: true }); + if (replaceStateOnPush && dst.startsWith('gs://')) { + const state = join(root, 'state'); + const previous = join(root, 'previous-state'); + renameSync(state, previous); + mkdirSync(state); + cpSync(join(previous, 'platform-keys.json'), join(state, 'platform-keys.json')); + cpSync(join(previous, 'created-resources.json'), join(state, 'created-resources.json')); + writeFileSync(join(state, 'foreign-marker'), 'must-survive'); + } return ok; } @@ -168,7 +228,14 @@ beforeEach(() => { failDeltaCopy = 0; failLiveCopy = false; cacheProof = 'owned'; + cacheMount = 'canonical'; + mountInspections = 0; + selectedProject = ''; + replaceStateOnPush = false; + celldStopped = false; cacheInspections = 0; + targetContainers = ''; + occupiedProject = undefined; const fleet = join(root, 'store/fleet/celld'); mkdirSync(join(fleet, 'd1'), { recursive: true }); writeFileSync(join(fleet, 'd1/main.ltx'), 'rows'); @@ -194,6 +261,42 @@ function inspectBackup(dest: string, part: string): Record { } describe('runBackup', () => { + it('backs up the real generated celld project while omitting its rebuildable source/migration symlinks', () => { + const apiDir = resolve(import.meta.dirname, '../../apps/api'); + const source = TOML.parse(readFileSync(join(apiDir, 'wrangler.toml'), 'utf8')) as WranglerToml; + const plan = buildCelldConfig(source, { main: 'src/index.ts', baseDomain: 'test.example.com' }); + const projectDir = join(root, 'state/project'); + prepareCelldProject({ apiDir, projectDir, plan }); + writeCelldConfig(projectDir, plan.config); + expect(lstatSync(join(projectDir, 'src')).isSymbolicLink()).toBe(true); + const migration = plan.migrationDirs[0]!; + const migrationDir = join(projectDir, migration.projectRelativeDir); + expect(lstatSync(join(migrationDir, readdirSync(migrationDir)[0]!)).isSymbolicLink()).toBe( + true + ); + const snapshot = join(root, 'generated-project-backup'); + runBackup(ctx('s3://fleet/celld', join(root, 'state')), snapshot); + const state = inspectBackup(snapshot, 'state'); + expect(state['project/wrangler.json']).toBe( + readFileSync(join(projectDir, 'wrangler.json'), 'utf8') + ); + expect(Object.keys(state).some((name) => name.startsWith('project/src/'))).toBe(false); + expect(Object.keys(state).some((name) => name.endsWith('.sql'))).toBe(false); + runRestore(ctx('s3://fresh/celld', join(root, 'restored-generated-state')), snapshot); + expect(readFileSync(join(root, 'restored-generated-state/project/wrangler.json'), 'utf8')).toBe( + state['project/wrangler.json'] + ); + expect(existsSync(join(root, 'restored-generated-state/project/src'))).toBe(false); + }); + + it('refuses arbitrary state symlinks and cleans incomplete backups', () => { + symlinkSync(join(root, 'box.env'), join(root, 'state/operator-secret-link')); + const snapshot = join(root, 'invalid-state-backup'); + expect(() => runBackup(ctx('s3://fleet/celld', join(root, 'state')), snapshot)).toThrow(); + expect(existsSync(snapshot)).toBe(false); + expect(calls.at(-1)?.args.slice(-2)).toEqual(['start', 'celld']); + }); + it('pre-copies live, stops celld only for the delta, restarts it, and records the downtime', () => { const dest = join(root, 'backups/b1'); const manifest = runBackup(ctx('s3://fleet/celld', join(root, 'state')), dest, 'a'.repeat(40)); @@ -332,6 +435,40 @@ describe('runBackup', () => { }); describe('runRestore', () => { + it('refuses containers under the final restored identity even when the pre-key project is empty', () => { + const snapshot = join(root, 'post-restore-project-backup'); + runBackup(ctx('s3://fleet/celld', join(root, 'state')), snapshot); + const target = ctx('s3://fresh/celld', join(root, 'new-state')); + const preKey = composeProjectFor(target.box, target.stateDir); + const finalProject = expectedComposeProjectFor(target.box, target.stateDir, 'a'.repeat(32)); + expect(finalProject).not.toBe(preKey); + occupiedProject = finalProject; + targetContainers = 'fixture-final-project-container\n'; + calls = []; + expect(() => runRestore(target, snapshot)).toThrow(/already has containers/); + expect(calls.filter((call) => call.args[0] === 'ps').map((call) => call.args.at(-1))).toEqual([ + `label=com.docker.compose.project=${preKey}`, + `label=com.docker.compose.project=${finalProject}`, + ]); + expect(calls.some((call) => call.args.includes('mirror'))).toBe(false); + expect(existsSync(target.stateDir)).toBe(false); + expect(existsSync(join(root, 'store/fresh/celld'))).toBe(false); + }); + + it('refuses any existing target project containers before bucket or state writes', () => { + const snapshot = join(root, 'occupied-target-backup'); + runBackup(ctx('s3://fleet/celld', join(root, 'state')), snapshot); + targetContainers = 'fixture-existing-container\n'; + calls = []; + expect(() => runRestore(ctx('s3://fresh/celld', join(root, 'new-state')), snapshot)).toThrow( + /container|empty install/i + ); + expect(calls.some((call) => call.args.includes('mirror'))).toBe(false); + expect(calls.some((call) => call.args[0] === 'compose')).toBe(false); + expect(existsSync(join(root, 'new-state'))).toBe(false); + expect(existsSync(join(root, 'store/fresh/celld'))).toBe(false); + }); + it.each(['createdAt', 'samCommit', 'objectCount', 'downtimeMs'] as const)( 'refuses authenticated invalid %s manifest metadata before cloud operations', (field) => { @@ -426,7 +563,82 @@ describe('runRestore', () => { describe('runRollback', () => { beforeEach(() => { const context = ctx('gs://fleet/celld', join(root, 'state')); - recordInstall(context.stateDir, context.envFile, context.box, 'test-installation'); + recordInstall( + context.stateDir, + context.envFile, + context.box, + 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' + ); + }); + + it.each(['wrong', 'duplicate', 'bind'] as const)( + 'refuses a selected overlay with %s celld cache mount before rollback bucket writes', + (mount) => { + const context = ctx('gs://fleet/celld', join(root, 'state')); + const snapshot = join(root, 'overlay-cache-snapshot'); + runBackup(context, snapshot); + calls = []; + cacheMount = mount; + expect(() => assertRollbackCacheReady(context)).toThrow(/canonical owned volume/); + expect(() => runRollback(context, snapshot)).toThrow(/canonical owned volume/); + expect(calls.some((call) => call.command === 'gcloud')).toBe(false); + expect(calls.some((call) => call.args[0] === 'volume' && call.args[1] === 'rm')).toBe(false); + expect( + calls.some((call) => call.args.includes('stop') || call.args.includes('--force')) + ).toBe(false); + } + ); + + it.each(['mount', 'creation-time'] as const)( + 'refuses a changed cache %s between ownership checks', + (changed) => { + const context = ctx('gs://fleet/celld', join(root, 'state')); + const snapshot = join(root, 'replaced-cache-snapshot'); + runBackup(context, snapshot); + calls = []; + if (changed === 'mount') cacheMount = 'changed'; + else cacheProof = 'replaced'; + expect(() => runRollback(context, snapshot)).toThrow(/cache mount|cache identity changed/); + expect(calls.some((call) => call.command === 'gcloud')).toBe(false); + expect(calls.some((call) => call.args[0] === 'volume' && call.args[1] === 'rm')).toBe(false); + } + ); + + it('refuses a same-label cache replaced after container removal, before deleting the new volume', () => { + const context = ctx('gs://fleet/celld', join(root, 'state')); + const snapshot = join(root, 'post-remove-cache-snapshot'); + runBackup(context, snapshot); + cacheProof = 'replaced-after-remove'; + calls = []; + expect(() => runRollback(context, snapshot)).toThrow(/cache identity changed/); + expect(cacheInspections).toBe(3); + expect(calls.some((call) => call.args.includes('--force'))).toBe(true); + expect(calls.some((call) => call.args[0] === 'volume' && call.args[1] === 'rm')).toBe(false); + expect(calls.some((call) => call.command === 'gcloud')).toBe(false); + }); + + it('rechecks the live state inode immediately before removal after the bucket copy', () => { + const context = ctx('gs://fleet/celld', join(root, 'state')); + const snapshot = join(root, 'state-race-snapshot'); + runBackup(context, snapshot); + replaceStateOnPush = true; + expect(() => runRollback(context, snapshot)).toThrow(/state directory identity changed/); + expect(readFileSync(join(context.stateDir, 'foreign-marker'), 'utf8')).toBe('must-survive'); + }); + + it('refuses a live state receipt whose directory inode changed before any rollback operation', () => { + const context = ctx('gs://fleet/celld', join(root, 'state')); + const snapshot = join(root, 'state-inode-snapshot'); + runBackup(context, snapshot); + const path = join(context.stateDir, 'created-resources.json'); + const receipt = JSON.parse(readFileSync(path, 'utf8')) as { + resources: Array<{ kind: string; attributes: Record }>; + }; + receipt.resources.find((resource) => resource.kind === 'state-dir')!.attributes.inode = '0'; + writeFileSync(path, JSON.stringify(receipt)); + calls = []; + expect(() => runRollback(context, snapshot)).toThrow(/state directory identity changed/); + expect(calls).toHaveLength(0); }); it.each([ @@ -474,18 +686,25 @@ describe('runRollback', () => { 'sanitizes malformed %s platform key JSON before any runner call', (location) => { const context = ctx('gs://fleet/celld', join(root, 'state')); - const snapshot = join(root, 'malformed-identity-snapshot'); + let snapshot = join(root, 'malformed-identity-snapshot'); const fragment = 'fixture-token-that-must-never-appear'; - if (location === 'snapshot') + runBackup(context, snapshot); + if (location === 'snapshot') { + const plain = join(root, 'malformed-identity-plain'); + decryptBackupTree(snapshot, plain, context.encryptionKeyFile!); + try { + writeFileSync(join(plain, 'state/platform-keys.json'), `{"ENCRYPTION_KEY":"${fragment}`); + snapshot = join(root, 'malformed-identity-altered'); + encryptBackupTree(plain, snapshot, context.encryptionKeyFile!); + } finally { + rmSync(plain, { recursive: true, force: true }); + } + } else { writeFileSync( join(context.stateDir, 'platform-keys.json'), `{"ENCRYPTION_KEY":"${fragment}` ); - runBackup(context, snapshot); - writeFileSync( - join(context.stateDir, 'platform-keys.json'), - location === 'current' ? `{"ENCRYPTION_KEY":"${fragment}` : PLATFORM_KEYS - ); + } calls = []; let error: unknown; try { @@ -553,20 +772,28 @@ describe('runRollback', () => { 'current.json': '{"v":3}', 'd1/main.ltx': 'rows', }); - expect(tree(join(root, 'state'))).toEqual(expectedState); + const actualState = tree(join(root, 'state')); + const restoredRecord = JSON.parse(actualState['created-resources.json']!) as { + resources: Array<{ kind: string; attributes: Record }>; + }; + const stateReceipt = restoredRecord.resources.find((resource) => resource.kind === 'state-dir'); + expect(stateReceipt?.attributes.inode).toBe(String(statSync(join(root, 'state')).ino)); + delete actualState['created-resources.json']; + delete expectedState['created-resources.json']; + expect(actualState).toEqual(expectedState); expect(readFileSync(join(root, 'box.env'), 'utf8')).toBe(`AWS_SECRET_ACCESS_KEY=${SECRET}\n`); expect(calls.find((c) => c.command === 'gcloud')?.args).toContain( '--delete-unmatched-destination-objects' ); expect(calls.some((c) => c.args.includes('stop'))).toBe(true); - expect(cacheInspections).toBe(2); + expect(cacheInspections).toBe(3); const volumeDelete = calls.find( (c) => c.command === 'docker' && c.args[0] === 'volume' && c.args[1] === 'rm' ); expect(volumeDelete?.args[2]).toMatch(/^sam-selfhost-[a-f0-9]{12}_celld-data$/); expect( calls.find((c) => c.command === 'docker' && c.args.includes('--force'))?.args.slice(-4) - ).toEqual(['rm', '--stop', '--force', 'celld']); + ).toEqual(['container', 'rm', '--force', 'c'.repeat(64)]); }); }); diff --git a/scripts/selfhost/deploy.ts b/scripts/selfhost/deploy.ts index a4a5ec3e34..0a8ab1d9f9 100644 --- a/scripts/selfhost/deploy.ts +++ b/scripts/selfhost/deploy.ts @@ -79,6 +79,7 @@ import { syncGatewayEnv, } from './deploy-steps.js'; import { inboundMailWorkerVars } from './inbound-mail-settings.js'; +import { expectedComposeProjectFor, recordInstall } from './install-record.js'; import { ensureMailCollectorPassword, MAIL_COLLECTOR_PASSWORD_FILE, @@ -93,7 +94,6 @@ import { type PlatformKeysMode, type PlatformKeysResult, } from './platform-keys.js'; -import { composeProjectFor, recordInstall } from './install-record.js'; import { assertPrivateFile, ensurePrivateDir, readSecretsFile } from './secret-files.js'; import { buildVmAgentBinaries, @@ -259,7 +259,7 @@ function prepareBoxState(inputs: DeployInputs): BoxState { } recordInstall(stateDir, inputs.envFile, box, keys.SAM_INSTALLATION_ID); log( - `Compose project: ${composeProjectFor(box, stateDir)} (set COMPOSE_PROJECT_NAME to this name before starting Docker Compose)` + `Compose project: ${expectedComposeProjectFor(box, stateDir, keys.SAM_INSTALLATION_ID)} (set COMPOSE_PROJECT_NAME to this name before starting Docker Compose)` ); syncGatewayEnv( join(stateDir, 'gateway.env'), diff --git a/scripts/selfhost/install-record.ts b/scripts/selfhost/install-record.ts index cd700984a4..6fa415bbaf 100644 --- a/scripts/selfhost/install-record.ts +++ b/scripts/selfhost/install-record.ts @@ -7,13 +7,14 @@ * * Cloud `box` entries: * installation domain, environment, composeProject: the ownership anchor - * compose-project sam-selfhost containers, volumes and images compose made + * compose-project installation scope for exact container/volume cleanup + * (shared images and networks are retained) * state-dir , env-file box state * bucket created (bundled store, lives in a volume) or reused * backup one per `pnpm selfhost:backup` / upgrade backup */ import { createHash } from 'node:crypto'; -import { existsSync, readFileSync } from 'node:fs'; +import { existsSync, lstatSync, readFileSync } from 'node:fs'; import { join, resolve } from 'node:path'; import { @@ -21,21 +22,52 @@ import { type CreatedResource, readRecord, } from '../../deploy/selfhost/created-resources.mjs'; +import { assertOperatorExecution } from './operator-only'; export const RECORD_FILE = 'created-resources.json'; /** docker-compose.yml `name:`; compose labels everything it creates with it. */ export function expectedComposeProjectFor( box: Readonly>, - stateDir: string + stateDir: string, + installationId?: string ): string { - let installation = ''; - const keys=join(stateDir,'platform-keys.json'); - if(existsSync(keys)) { + let installation = installationId ?? ''; + const keys = join(stateDir, 'platform-keys.json'); + if (installationId === undefined && existsSync(keys)) { + assertOperatorExecution(); try { - const value=JSON.parse(readFileSync(keys,'utf8')) as {SAM_INSTALLATION_ID?:unknown}; - if(typeof value.SAM_INSTALLATION_ID==='string' && /^[a-f0-9]{32}$/.test(value.SAM_INSTALLATION_ID)) installation=value.SAM_INSTALLATION_ID; - } catch { throw new Error('Cannot resolve installation Compose identity'); } + const raw: unknown = JSON.parse(readFileSync(keys, 'utf8')); + if (!raw || typeof raw !== 'object' || Array.isArray(raw)) throw new Error(); + const value = raw as { SAM_INSTALLATION_ID?: unknown }; + if ( + typeof value.SAM_INSTALLATION_ID !== 'string' || + !/^[a-f0-9]{32}$/.test(value.SAM_INSTALLATION_ID) + ) + throw new Error(); + installation = value.SAM_INSTALLATION_ID; + } catch { + throw new Error('Cannot resolve installation Compose identity'); + } + } + if (installationId === undefined && !existsSync(keys)) { + const entries = readRecord(recordPath(stateDir)).resources.filter( + (r) => + r.cloud === 'box' && + r.kind === 'installation' && + r.action === 'created' && + !r.removedAt && + r.attributes?.domain === (box.SAM_DOMAIN ?? '') && + r.attributes?.environment === SELFHOST_ENVIRONMENT + ); + if ( + entries.length > 1 || + (entries.length === 1 && !/^[a-f0-9]{32}$/.test(entries[0]?.name ?? '')) + ) + throw new Error('Ambiguous persisted installation Compose identity'); + installation = entries[0]?.name ?? ''; } + if (installationId !== undefined && !/^[a-f0-9]{32}$/.test(installationId)) + throw new Error('Invalid persisted installation identity for Compose'); const suffix = createHash('sha256') .update(`${box.SAM_DOMAIN ?? ''}\n${resolve(stateDir)}\n${installation}`) .digest('hex') @@ -74,7 +106,9 @@ export function recordInstall( ): void { const file = recordPath(stateDir); const domain = box.SAM_DOMAIN ?? ''; - const project = composeProjectFor(box, stateDir); + const canonical = expectedComposeProjectFor(box, stateDir, installationId); + const project = + box.COMPOSE_PROJECT_NAME === undefined ? canonical : composeProjectFor(box, stateDir); const add = (kind: string, name: string, action: 'created' | 'reused', attributes = {}) => addResource(file, { cloud: 'box', kind, name, action, createdBy: 'deploy', attributes }); add('installation', installationId, 'created', { @@ -82,9 +116,19 @@ export function recordInstall( environment: SELFHOST_ENVIRONMENT, composeProject: project, }); - if (project === expectedComposeProjectFor(box, stateDir)) - add('compose-project', project, 'created', { installation:installationId, environment:SELFHOST_ENVIRONMENT, stateDir:resolve(stateDir) }); - add('state-dir', stateDir, 'created'); + if (project === canonical) + add('compose-project', project, 'created', { + installation: installationId, + environment: SELFHOST_ENVIRONMENT, + stateDir: resolve(stateDir), + }); + const stat = lstatSync(stateDir); + add('state-dir', stateDir, 'created', { + installation: installationId, + environment: SELFHOST_ENVIRONMENT, + device: String(stat.dev), + inode: String(stat.ino), + }); // The operator writes .env; the install only reads it, but it is the install's own file. add('env-file', envFile, 'created'); if (box.CELLD_BUCKET) { diff --git a/scripts/selfhost/live/backup-cache.live.test.ts b/scripts/selfhost/live/backup-cache.live.test.ts new file mode 100644 index 0000000000..9f3d9d6dce --- /dev/null +++ b/scripts/selfhost/live/backup-cache.live.test.ts @@ -0,0 +1,96 @@ +/** Actual Docker Compose mount selection, including an operator overlay replacing the cache. */ +import { spawnSync } from 'node:child_process'; +import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'; +import { join } from 'node:path'; + +import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest'; + +import { + assertRollbackCacheReady, + type BoxContext, + composeArgs, + composeRunEnv, + OBJECTSTORE_IMAGE, +} from '../backup-lib'; +import { recordInstall } from '../install-record'; +import { LIVE_TMP, skipWithoutDocker } from './harness'; + +let root = ''; +let context: BoxContext | undefined; +function docker(args: string[]): void { + const result = context!.run('docker', composeArgs(context!, args), composeRunEnv(context!)); + if (result.status !== 0) throw new Error('Disposable cache fixture Docker command failed'); +} + +describe.skipIf(skipWithoutDocker)( + 'rollback cache proof against real selected Compose mounts', + () => { + beforeAll(() => { + for (const name of Object.keys(process.env)) { + if (name === 'CI' || name === 'GITHUB_ACTIONS' || name.startsWith('RUNNER_')) + vi.stubEnv(name, undefined); + } + mkdirSync(LIVE_TMP, { recursive: true }); + root = mkdtempSync(join(LIVE_TMP, 'cache-proof-')); + const stateDir = join(root, 'state'); + mkdirSync(stateDir, { mode: 0o700 }); + writeFileSync( + join(stateDir, 'platform-keys.json'), + JSON.stringify({ SAM_INSTALLATION_ID: 'a'.repeat(32) }), + { mode: 0o600 } + ); + const envFile = join(root, 'box.env'); + writeFileSync(envFile, 'CELLD_BUCKET=gs://unused/celld\n', { mode: 0o600 }); + const compose = join(root, 'compose.yml'); + writeFileSync( + compose, + `services:\n celld:\n image: ${OBJECTSTORE_IMAGE}\n entrypoint: /bin/sh\n command: ["-c", "sleep 300"]\n volumes:\n - celld-data:/var/lib/celld\nvolumes:\n celld-data: {}\n` + ); + context = { + box: { CELLD_BUCKET: 'gs://unused/celld' }, + stateDir, + envFile, + composeFiles: [compose], + now: Date.now, + log: () => undefined, + run(command, args, env) { + if (command !== 'docker') + throw new Error('Cloud commands forbidden in disposable cache fixture'); + const result = spawnSync(command, args, { env: env ?? process.env, encoding: 'utf8' }); + return { + status: result.status ?? 1, + stdout: result.stdout ?? '', + stderr: result.stderr ?? '', + }; + }, + }; + recordInstall(stateDir, envFile, context.box, 'a'.repeat(32)); + docker(['up', '-d', 'celld']); + }); + afterAll(() => { + try { + if (context) docker(['down', '--volumes', '--remove-orphans']); + } finally { + if (root) rmSync(root, { recursive: true, force: true }); + vi.unstubAllEnvs(); + } + }); + it('accepts canonical cache and rejects an overlay replacing the actual container mount', () => { + const proof = assertRollbackCacheReady(context!); + expect(proof.name).toMatch(/^sam-selfhost-[a-f0-9]{12}_celld-data$/); + expect(proof.container).toMatch(/^[a-f0-9]{64}$/); + docker(['stop', 'celld']); + expect(assertRollbackCacheReady(context!).container).toBe(proof.container); + const overlay = join(root, 'override.yml'); + writeFileSync( + overlay, + 'services:\n celld:\n volumes:\n - other-cache:/var/lib/celld\nvolumes:\n other-cache: {}\n' + ); + context!.composeFiles.push(overlay); + docker(['up', '-d', 'celld']); + expect(() => assertRollbackCacheReady(context!)).toThrow( + 'Selected celld cache mount is not the canonical owned volume' + ); + }); + } +); diff --git a/scripts/selfhost/live/backup-restore.live.test.ts b/scripts/selfhost/live/backup-restore.live.test.ts index 98955c4b42..e23645aa7e 100644 --- a/scripts/selfhost/live/backup-restore.live.test.ts +++ b/scripts/selfhost/live/backup-restore.live.test.ts @@ -23,6 +23,10 @@ import { } from '../backup-lib'; import { freePort, LIVE_TMP } from './harness'; +const PLATFORM_KEYS = JSON.stringify({ + SAM_INSTALLATION_ID: 'a'.repeat(32), + ENCRYPTION_KEY: 'fixture-encryption-key', +}); const KEY = 'sam-live-backup'; const SECRET = 'live-backup-secret-0123456789'; const hasDocker = spawnSync('docker', ['version'], { stdio: 'ignore' }).status === 0; @@ -151,7 +155,7 @@ describe.skipIf(!hasDocker && !process.env.CI)( const state = join(root, 'state'); mkdirSync(state); - writeFileSync(join(state, 'platform-keys.json'), '{"k":1}'); + writeFileSync(join(state, 'platform-keys.json'), PLATFORM_KEYS); writeFileSync(join(root, 'box.env'), 'CELLD_BUCKET=s3://fleet/celld\n', { mode: 0o600 }); const dest = join(root, 'backup'); @@ -165,7 +169,7 @@ describe.skipIf(!hasDocker && !process.env.CI)( const check = join(root, 'check'); pullBucket(ctx('s3://fresh/celld', newState), check); expect(tree(check)).toEqual(tree(seed)); - expect(tree(newState)).toEqual({ 'platform-keys.json': '{"k":1}' }); + expect(tree(newState)).toEqual({ 'platform-keys.json': PLATFORM_KEYS }); // A second restore into the now non-empty bucket is refused. expect(() => runRestore(ctx('s3://fresh/celld', join(root, 'other-state')), dest)).toThrow( diff --git a/scripts/selfhost/operator-ci-guard.test.ts b/scripts/selfhost/operator-ci-guard.test.ts index 7e69f2d9cc..1069c98e9b 100644 --- a/scripts/selfhost/operator-ci-guard.test.ts +++ b/scripts/selfhost/operator-ci-guard.test.ts @@ -6,7 +6,13 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import { loadBox } from './backup-cli'; import { decryptBackupTree, encryptBackupTree, readBackupKey } from './backup-encryption'; -import { type BoxContext, runBackup, runRestore, runRollback } from './backup-lib'; +import { + assertRollbackCacheReady, + type BoxContext, + runBackup, + runRestore, + runRollback, +} from './backup-lib'; const ROOT = resolve(import.meta.dirname, '../..'); const ABSENT = resolve(ROOT, '.tmp/nonexistent-operator-guard-sentinel'); @@ -42,6 +48,7 @@ describe('operator commands never read secret files in CI', () => { () => readBackupKey(ABSENT), () => encryptBackupTree(ABSENT, ABSENT, ABSENT), () => decryptBackupTree(ABSENT, ABSENT, ABSENT), + () => assertRollbackCacheReady(context), () => runBackup(context, ABSENT), () => runRestore(context, ABSENT), () => runRollback(context, ABSENT), diff --git a/scripts/selfhost/restore.ts b/scripts/selfhost/restore.ts index e9e650cad8..4bb5d8b33b 100644 --- a/scripts/selfhost/restore.ts +++ b/scripts/selfhost/restore.ts @@ -10,6 +10,7 @@ import { parseArgs } from 'node:util'; import { loadBox, log, SELFHOST_DIR } from './backup-cli'; import { composeArgs, runRestore } from './backup-lib'; +import { expectedComposeProjectFor } from './install-record'; const { values } = parseArgs({ options: { @@ -25,11 +26,26 @@ const envFile = resolve(values['box-env'] ?? join(SELFHOST_DIR, '.env')); const ctx = loadBox(envFile, values['state-dir'], values['encryption-key-file']); const manifest = runRestore(ctx, from); log(`restored backup of ${manifest.createdAt} (SAM ${manifest.samCommit ?? 'unknown commit'})`); -log('start the stack with the SAME SAM checkout the backup was taken with:'); +log('Recover with the SAME SAM checkout the backup was taken with:'); if (manifest.samCommit) log(` git checkout ${manifest.samCommit}`); log( - ` docker ${composeArgs(ctx, ['up', '-d']) + ` pnpm selfhost:deploy --init --env-file '${envFile.replaceAll("'", "'\"'\"'")}' --state-dir '${ctx.stateDir.replaceAll("'", "'\"'\"'")}'` +); +log( + ` Set COMPOSE_PROJECT_NAME in the target .env to ${expectedComposeProjectFor(ctx.box, ctx.stateDir)}, then repeat --init to record the target identity` +); +log( + ` SAM_SELFHOST_STATE_DIR='${ctx.stateDir.replaceAll("'", "'\"'\"'")}' docker ${composeArgs( + { + ...ctx, + box: { ...ctx.box, COMPOSE_PROJECT_NAME: expectedComposeProjectFor(ctx.box, ctx.stateDir) }, + }, + ['up', '-d'] + ) .map((arg) => `'${arg.replaceAll("'", "'\"'\"'")}'`) .join(' ')}` ); +log( + ` pnpm selfhost:deploy --env-file '${envFile.replaceAll("'", "'\"'\"'")}' --state-dir '${ctx.stateDir.replaceAll("'", "'\"'\"'")}'` +); log(` curl -fsS https://api.$SAM_DOMAIN/health`); diff --git a/scripts/selfhost/teardown-box.ts b/scripts/selfhost/teardown-box.ts index f804fb2505..06446c88ee 100644 --- a/scripts/selfhost/teardown-box.ts +++ b/scripts/selfhost/teardown-box.ts @@ -8,10 +8,9 @@ import { isAbsolute, join, resolve } from 'node:path'; import type { CreatedResource } from '../../deploy/selfhost/created-resources.mjs'; import { type BoxContext, composeArgs, MANIFEST_NAME, parseBucketUrl } from './backup-lib'; - import { composeProjectFor, expectedComposeProjectFor, usesBundledStore } from './install-record'; +import { readComposeInventory, removeContainers,stopContainers } from './teardown-compose'; import { both, type Item, type Mode, STEPS } from './teardown-model'; -import { readComposeInventory, stopContainers, removeContainers } from './teardown-compose'; import { isProtectedDir, stateItems } from './teardown-state-dir'; export interface TeardownOptions { @@ -53,8 +52,18 @@ export function boxItems(ctx: TeardownContext): Item[] { const everything = ctx.mode === 'remove-everything'; let inventory: ReturnType | undefined; let inventoryError: Error | undefined; - if (owned) { try { inventory=readComposeInventory(ctx); } catch(error) { inventoryError=error instanceof Error ? error : new Error('Cannot verify Docker inventory'); } } - const proof = () => { if(inventoryError) throw inventoryError; if(!inventory) throw new Error('Missing Docker ownership inventory'); return inventory; }; + if (owned) { + try { + inventory = readComposeInventory(ctx); + } catch (error) { + inventoryError = error instanceof Error ? error : new Error('Cannot verify Docker inventory'); + } + } + const proof = () => { + if (inventoryError) throw inventoryError; + if (!inventory) throw new Error('Missing Docker ownership inventory'); + return inventory; + }; items.push({ id: 'box:stop', @@ -69,7 +78,7 @@ export function boxItems(ctx: TeardownContext): Item[] { : { act: 'refused', why: 'no creation record for this installation compose project' } ), removedAt: composeGone, - run: () => stopContainers(ctx,proof()), + run: () => stopContainers(ctx, proof()), }); items.push({ id: 'box:containers', @@ -85,12 +94,11 @@ export function boxItems(ctx: TeardownContext): Item[] { ), removedAt: composeGone, runKey: 'compose-down', - run: () => - removeContainers(ctx,proof(),everything), + run: () => removeContainers(ctx, proof(), everything), record: everything ? { cloud: 'box', kind: 'compose-project', name: projectName } : undefined, }); const keepVolumes = { act: 'keep' as const, why: 'keep my data keeps volumes' }; - for (const volume of inventory?.volumes.map(v=>v.name) ?? []) { + for (const volume of inventory?.volumes.map((v) => v.name) ?? []) { const store = volume.endsWith('objectstore-data'); items.push({ id: `box:volume:${volume}`, @@ -122,7 +130,10 @@ export function boxItems(ctx: TeardownContext): Item[] { step: STEPS.box, plan: { 'keep-data': { act: 'keep', why: 'rebuilt or reused on start' }, - 'remove-everything': { act: 'operator', why: 'images can be shared; remove unused images manually after inspecting their users' }, + 'remove-everything': { + act: 'operator', + why: 'images can be shared; remove unused images manually after inspecting their users', + }, }, removedAt: composeGone, }); @@ -134,7 +145,7 @@ export function boxItems(ctx: TeardownContext): Item[] { what: `${ctx.envFile} (settings and the bucket credential)`, provenance: env ? 'recorded' : 'discovered, not recorded', how: `rm ${ctx.envFile} (last, so a failed run can be resumed)`, - step: STEPS.box, + step: STEPS.cleanup, plan: { 'keep-data': { act: 'keep', why: 'needed to start the install again' }, 'remove-everything': @@ -191,7 +202,7 @@ function backupItems(ctx: TeardownContext): Item[] { what: `backup ${path}${backupBucket(path)}`, provenance: entry ? 'recorded' : 'discovered, not recorded', how: `rm -r ${path}`, - step: STEPS.box, + step: STEPS.cleanup, plan: gone ? both({ act: 'keep', why: 'no longer on disk' }) : !isBackup diff --git a/scripts/selfhost/teardown-compose.ts b/scripts/selfhost/teardown-compose.ts index a70c7c548f..0bb6db0ab9 100644 --- a/scripts/selfhost/teardown-compose.ts +++ b/scripts/selfhost/teardown-compose.ts @@ -1,69 +1,182 @@ /** Teardown acts on exact live identities, never Compose's broad project-name sweep. */ import { dirname, resolve } from 'node:path'; + import { readRecord } from '../../deploy/selfhost/created-resources.mjs'; import { check } from './backup-lib'; import { composeProjectFor, expectedComposeProjectFor } from './install-record'; import type { TeardownContext } from './teardown-box'; -interface Container { id: string; labels: Record } -interface Volume { name: string; createdAt: string; labels: Record } -export interface ComposeInventory { containers: Container[]; volumes: Volume[] } -function labels(value: unknown): Record { - if (!value || typeof value !== 'object' || Array.isArray(value) || Object.values(value).some(v=>typeof v !== 'string')) throw new Error('Unreadable Docker ownership labels'); - return value as Record; +interface Container { + id: string; + labels: Record; +} +interface Volume { + name: string; + createdAt: string; + labels: Record; +} +export interface ComposeInventory { + containers: Container[]; + volumes: Volume[]; +} +function labels(value: unknown): Record { + if ( + !value || + typeof value !== 'object' || + Array.isArray(value) || + Object.values(value).some((v) => typeof v !== 'string') + ) + throw new Error('Unreadable Docker ownership labels'); + return value as Record; } function result(ctx: TeardownContext, args: string[]): string { - return check(ctx.run('docker',args),'read Docker ownership metadata').stdout.trim(); + return check(ctx.run('docker', args), 'read Docker ownership metadata').stdout.trim(); } -function parse(text: string): Record { - try { const value:unknown=JSON.parse(text); if(!value || typeof value!=='object' || Array.isArray(value)) throw new Error(); return value as Record; } - catch { throw new Error('Unreadable Docker ownership metadata'); } +function parse(text: string): Record { + try { + const value: unknown = JSON.parse(text); + if (!value || typeof value !== 'object' || Array.isArray(value)) throw new Error(); + return value as Record; + } catch { + throw new Error('Unreadable Docker ownership metadata'); + } } function projectProof(ctx: TeardownContext): string { - const project=composeProjectFor(ctx.box,ctx.stateDir); - if(project!==expectedComposeProjectFor(ctx.box,ctx.stateDir) || !ctx.installationId) throw new Error('Refused: no exact installation Compose identity'); - const record=readRecord(ctx.recordFile).resources; - const installs=record.filter(r=>r.cloud==='box' && r.kind==='installation' && !r.removedAt); - const projects=record.filter(r=>r.cloud==='box' && r.kind==='compose-project' && r.name===project && r.action==='created' && r.attributes?.installation===ctx.installationId && r.attributes?.environment==='selfhost' && r.attributes?.stateDir===resolve(ctx.stateDir)); - if(installs.length!==1 || installs[0]?.name!==ctx.installationId || installs[0]?.attributes?.domain!==ctx.domain || installs[0]?.attributes?.environment!=='selfhost' || installs[0]?.attributes?.composeProject!==project || projects.length!==1) throw new Error('Refused: missing exact installation Compose receipt'); + const project = composeProjectFor(ctx.box, ctx.stateDir); + if (project !== expectedComposeProjectFor(ctx.box, ctx.stateDir) || !ctx.installationId) + throw new Error('Refused: no exact installation Compose identity'); + const record = readRecord(ctx.recordFile).resources; + const installs = record.filter( + (r) => r.cloud === 'box' && r.kind === 'installation' && !r.removedAt + ); + const projects = record.filter( + (r) => + r.cloud === 'box' && + r.kind === 'compose-project' && + r.name === project && + r.action === 'created' && + r.attributes?.installation === ctx.installationId && + r.attributes?.environment === 'selfhost' && + r.attributes?.stateDir === resolve(ctx.stateDir) + ); + if ( + installs.length !== 1 || + installs[0]?.name !== ctx.installationId || + installs[0]?.attributes?.domain !== ctx.domain || + installs[0]?.attributes?.environment !== 'selfhost' || + installs[0]?.attributes?.composeProject !== project || + projects.length !== 1 + ) + throw new Error('Refused: missing exact installation Compose receipt'); return project; } export function readComposeInventory(ctx: TeardownContext): ComposeInventory { - const project=projectProof(ctx); - const names=(args:string[])=>result(ctx,args).split('\n').filter(Boolean); - const ids=names(['container','ls','--all','--no-trunc','--filter',`label=com.docker.compose.project=${project}`,'--format','{{.ID}}']); - if(new Set(ids).size!==ids.length || ids.some(id=>!/^[a-f0-9]{64}$/.test(id))) throw new Error('Refused: ambiguous Docker container inventory'); - const containers=ids.map(id=>{ - const raw=parse(result(ctx,['container','inspect','--format','{"id":{{json .Id}},"labels":{{json .Config.Labels}}}',id])); - const meta=labels(raw.labels); - const files=meta['com.docker.compose.project.config_files']?.split(',').map(file=>resolve(file)); - if(raw.id!==id || meta['com.docker.compose.project']!==project || !meta['com.docker.compose.service'] || meta['com.docker.compose.project.working_dir']!==dirname(ctx.composeFiles[0] ?? '') || JSON.stringify(files)!==JSON.stringify(ctx.composeFiles.map(file=>resolve(file)))) throw new Error('Refused: foreign Docker container configuration scope'); - return {id,labels:meta}; + const project = projectProof(ctx); + const names = (args: string[]) => result(ctx, args).split('\n').filter(Boolean); + const ids = names([ + 'container', + 'ls', + '--all', + '--no-trunc', + '--filter', + `label=com.docker.compose.project=${project}`, + '--format', + '{{.ID}}', + ]); + if (new Set(ids).size !== ids.length || ids.some((id) => !/^[a-f0-9]{64}$/.test(id))) + throw new Error('Refused: ambiguous Docker container inventory'); + const containers = ids.map((id) => { + const raw = parse( + result(ctx, [ + 'container', + 'inspect', + '--format', + '{"id":{{json .Id}},"labels":{{json .Config.Labels}}}', + id, + ]) + ); + const meta = labels(raw.labels); + const files = meta['com.docker.compose.project.config_files'] + ?.split(',') + .map((file) => resolve(file)); + if ( + raw.id !== id || + meta['com.docker.compose.project'] !== project || + !meta['com.docker.compose.service'] || + meta['com.docker.compose.project.working_dir'] !== dirname(ctx.composeFiles[0] ?? '') || + JSON.stringify(files) !== JSON.stringify(ctx.composeFiles.map((file) => resolve(file))) + ) + throw new Error('Refused: foreign Docker container configuration scope'); + return { id, labels: meta }; }); - const volumes=names(['volume','ls','--filter',`label=com.docker.compose.project=${project}`,'--format','{{.Name}}']).map(name=>{ - if(!/^[a-zA-Z0-9][a-zA-Z0-9_.-]*$/.test(name)) throw new Error('Refused: invalid Docker volume name'); - const raw=parse(result(ctx,['volume','inspect','--format','{"name":{{json .Name}},"createdAt":{{json .CreatedAt}},"labels":{{json .Labels}}}',name])); - const meta=labels(raw.labels); - if(raw.name!==name || typeof raw.createdAt!=='string' || !raw.createdAt || meta['com.docker.compose.project']!==project || name!==`${project}_${meta['com.docker.compose.volume']}`) throw new Error('Refused: foreign Docker volume configuration scope'); - return {name,createdAt:raw.createdAt,labels:meta}; + const volumes = names([ + 'volume', + 'ls', + '--filter', + `label=com.docker.compose.project=${project}`, + '--format', + '{{.Name}}', + ]).map((name) => { + if (!/^[a-zA-Z0-9][a-zA-Z0-9_.-]*$/.test(name)) + throw new Error('Refused: invalid Docker volume name'); + const raw = parse( + result(ctx, [ + 'volume', + 'inspect', + '--format', + '{"name":{{json .Name}},"createdAt":{{json .CreatedAt}},"labels":{{json .Labels}}}', + name, + ]) + ); + const meta = labels(raw.labels); + if ( + raw.name !== name || + typeof raw.createdAt !== 'string' || + !raw.createdAt || + meta['com.docker.compose.project'] !== project || + typeof meta['com.docker.compose.volume'] !== 'string' || + !meta['com.docker.compose.volume'] || + name !== `${project}_${meta['com.docker.compose.volume']}` + ) + throw new Error('Refused: foreign Docker volume configuration scope'); + return { name, createdAt: raw.createdAt, labels: meta }; }); - if(new Set(volumes.map(v=>v.name)).size!==volumes.length) throw new Error('Refused: duplicate Docker volume inventory'); - return {containers:containers.sort((a,b)=>a.id.localeCompare(b.id)),volumes:volumes.sort((a,b)=>a.name.localeCompare(b.name))}; + if (new Set(volumes.map((v) => v.name)).size !== volumes.length) + throw new Error('Refused: duplicate Docker volume inventory'); + return { + containers: containers.sort((a, b) => a.id.localeCompare(b.id)), + volumes: volumes.sort((a, b) => a.name.localeCompare(b.name)), + }; } export function assertComposeInventory(ctx: TeardownContext, expected: ComposeInventory): void { - if(JSON.stringify(readComposeInventory(ctx))!==JSON.stringify(expected)) throw new Error('Refused: Docker identities or ownership changed since inventory'); + if (JSON.stringify(readComposeInventory(ctx)) !== JSON.stringify(expected)) + throw new Error('Refused: Docker identities or ownership changed since inventory'); } export function stopContainers(ctx: TeardownContext, inventory: ComposeInventory): void { - assertComposeInventory(ctx,inventory); - if(inventory.containers.length) check(ctx.run('docker',['container','stop',...inventory.containers.map(c=>c.id)]),'stop owned containers'); + assertComposeInventory(ctx, inventory); + if (inventory.containers.length) + check( + ctx.run('docker', ['container', 'stop', ...inventory.containers.map((c) => c.id)]), + 'stop owned containers' + ); } -export function removeContainers(ctx: TeardownContext, inventory: ComposeInventory, volumes: boolean): void { - assertComposeInventory(ctx,inventory); +export function removeContainers( + ctx: TeardownContext, + inventory: ComposeInventory, + volumes: boolean +): void { + assertComposeInventory(ctx, inventory); // Exact ids, individually re-fetched just above, cannot select a replacement container. - if(inventory.containers.length) check(ctx.run('docker',['container','rm','--force',...inventory.containers.map(c=>c.id)]),'remove owned containers'); - if(volumes) for(const volume of inventory.volumes) { - const current=readComposeInventory(ctx); - if(!current.volumes.some(v=>JSON.stringify(v)===JSON.stringify(volume))) throw new Error('Refused: Docker volume identity changed before removal'); - check(ctx.run('docker',['volume','rm',volume.name]),'remove owned volume'); - } + if (inventory.containers.length) + check( + ctx.run('docker', ['container', 'rm', '--force', ...inventory.containers.map((c) => c.id)]), + 'remove owned containers' + ); + if (volumes) + for (const volume of inventory.volumes) { + const current = readComposeInventory(ctx); + if (!current.volumes.some((v) => JSON.stringify(v) === JSON.stringify(volume))) + throw new Error('Refused: Docker volume identity changed before removal'); + check(ctx.run('docker', ['volume', 'rm', volume.name]), 'remove owned volume'); + } } diff --git a/scripts/selfhost/teardown-gcp-bootstrap.ts b/scripts/selfhost/teardown-gcp-bootstrap.ts index 4051d5c775..3e827dd8b1 100644 --- a/scripts/selfhost/teardown-gcp-bootstrap.ts +++ b/scripts/selfhost/teardown-gcp-bootstrap.ts @@ -159,7 +159,9 @@ export function bootstrapItems(ctx: TeardownContext, project: string): Item[] { check(result, 'read recorded resource before deletion'); let current: Record; try { - current = JSON.parse(result.stdout) as Record; + const parsed: unknown = JSON.parse(result.stdout); + if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) throw new Error(); + current = parsed as Record; } catch { throw new Error('refused: unreadable ownership metadata'); } diff --git a/scripts/selfhost/teardown-gcp.ts b/scripts/selfhost/teardown-gcp.ts index c4eba2f5ee..08689b6967 100644 --- a/scripts/selfhost/teardown-gcp.ts +++ b/scripts/selfhost/teardown-gcp.ts @@ -342,10 +342,18 @@ function firewallItems( r.attributes?.install === `https://api.${ctx.domain}` ); const description = `SAM installation=${ctx.installationId} environment=selfhost issuer=https://api.${ctx.domain}`; + let metadata: Record = {}; + try { + const parsed: unknown = JSON.parse(found.stdout); + if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) + metadata = parsed as Record; + } catch { + /* malformed metadata never authorizes deletion */ + } const safe = !!receipt?.attributes?.identity && - JSON.parse(found.stdout).id === receipt.attributes.identity && - JSON.parse(found.stdout).description === description && + metadata.id === receipt.attributes.identity && + metadata.description === description && usage.startsWith('no existing VM'); items.push({ id: `gcp:${project}:firewall:${rule}`, @@ -375,7 +383,14 @@ function firewallItems( '--format=json', ]); check(current, 'read firewall before deletion'); - const raw = JSON.parse(current.stdout) as { id?: string; description?: string }; + let raw: Record; + try { + const parsed: unknown = JSON.parse(current.stdout); + if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) throw new Error(); + raw = parsed as Record; + } catch { + throw new Error('Refused: unreadable firewall identity'); + } const users = firewallUsage( parseFirewallTargets(current.stdout), listAllInstances(ctx, project), diff --git a/scripts/selfhost/teardown-model.ts b/scripts/selfhost/teardown-model.ts index 7e4216bebc..095a2db6fe 100644 --- a/scripts/selfhost/teardown-model.ts +++ b/scripts/selfhost/teardown-model.ts @@ -42,7 +42,9 @@ export const STEPS = { identity: 3, bucket: 4, box: 5, - outside: 6, + state: 6, + cleanup: 7, + outside: 8, } as const; export const STEP_NAMES: Record = { 1: 'stop taking new work', @@ -50,7 +52,9 @@ export const STEP_NAMES: Record = { 3: 'cloud identity and keys', 4: 'bucket contents', 5: 'the box', - 6: 'outside SAM', + 6: 'installation state', + 7: 'local cleanup', + 8: 'outside SAM', }; export interface RecordRef { diff --git a/scripts/selfhost/teardown-state-dir.ts b/scripts/selfhost/teardown-state-dir.ts index a6aa3a1dfb..9305c5c451 100644 --- a/scripts/selfhost/teardown-state-dir.ts +++ b/scripts/selfhost/teardown-state-dir.ts @@ -4,10 +4,19 @@ * Emptying it survives read-only trees (Go's module cache) and an entry it cannot remove, so the * secrets always go first and the summary names what is left (box round R12). */ -import { chmodSync, existsSync, lstatSync, readdirSync, realpathSync, rmSync } from 'node:fs'; +import { + chmodSync, + existsSync, + lstatSync, + readdirSync, + readFileSync, + realpathSync, + rmSync, +} from 'node:fs'; import { homedir } from 'node:os'; import { basename, isAbsolute, join, relative, resolve } from 'node:path'; +import { readRecord } from '../../deploy/selfhost/created-resources.mjs'; import { STATE_CACHE_EXCLUDES } from './backup-lib'; import { RECORD_FILE } from './install-record'; import type { TeardownContext } from './teardown-box'; @@ -35,7 +44,7 @@ export function stateItems(ctx: TeardownContext): Item[] { what: `key file ${keyFile} (opens the sealed bundles)`, provenance: 'discovered, not recorded', how: `rm ${keyFile}`, - step: STEPS.box, + step: STEPS.state, plan: keyDecision, forGood: 'every sealed bundle and every backup of this box sealed with this key can never be opened again, unless you keep a copy', @@ -51,12 +60,18 @@ export function stateItems(ctx: TeardownContext): Item[] { what: `${legacyKeys} (plaintext platform keys of a legacy-plaintext box)`, provenance: 'discovered, not recorded', how: `rm ${legacyKeys}`, - step: STEPS.box, + step: STEPS.state, plan: keyDecision, forGood: 'the box copy of the platform keys; backups hold their own copy', runKey: 'state', goneDespiteGroupFailure: () => isGone(legacyKeys), - record: { cloud: 'box', kind: 'platform-keys', name: legacyKeys, createdBy: 'deploy' }, + record: { + cloud: 'box', + kind: 'platform-keys', + name: legacyKeys, + createdBy: 'deploy', + attributes: { installation: ctx.installationId ?? '', environment: 'selfhost' }, + }, }); } const state = ctx.record.find((r) => r.cloud === 'box' && r.kind === 'state-dir'); @@ -66,7 +81,7 @@ export function stateItems(ctx: TeardownContext): Item[] { what: `${ctx.stateDir} (sealed bundles, generated config, deploy project, celld binary, caches, secrets.env)`, provenance: state ? 'recorded' : 'discovered, not recorded', how: `rm -r everything in ${ctx.stateDir} except ${RECORD_FILE} and a key that is kept`, - step: STEPS.box, + step: STEPS.state, plan: { 'keep-data': { act: 'keep', why: 'keep my data keeps the bundles and state' }, 'remove-everything': { act: 'remove' }, @@ -88,7 +103,7 @@ export function stateItems(ctx: TeardownContext): Item[] { what: `${ctx.recordFile} (this record: teardown's receipt)`, provenance: 'recorded', how: `rm ${ctx.recordFile} by hand once you no longer need it`, - step: STEPS.box, + step: STEPS.state, plan: both({ act: 'keep', why: 'the receipt a second run resumes from' }), }); return items; @@ -206,8 +221,8 @@ export function isProtectedDir(path: string, selfhostDir: string): boolean { /** * The state directory comes from .env or --state-dir, so prove it is SAM's before emptying it - * (security review M1): not a protected directory, and either recorded as this state dir or - * holding the key agent's files. + * Require its exact active creation receipt, live directory identity, and matching installation + * and platform identity. Protected paths and symlink roots are always refused. */ function assertStateDir(ctx: TeardownContext): void { // Also through symbolic links: a .state that links to the home directory is still refused. @@ -217,16 +232,62 @@ function assertStateDir(ctx: TeardownContext): void { ) { throw new Error(`refused: ${ctx.stateDir} is /, your home or contains the checkout`); } - const recordedHere = ctx.record.some( - (r) => r.cloud === 'box' && r.kind === 'state-dir' && resolve(r.name) === resolve(ctx.stateDir) + if ( + realpathSync(ctx.stateDir) !== resolve(ctx.stateDir) || + lstatSync(ctx.stateDir).isSymbolicLink() + ) + throw new Error('Refused: state path uses symlinks'); + const record = readRecord(ctx.recordFile).resources; + const states = record.filter( + (r) => + r.cloud === 'box' && + r.kind === 'state-dir' && + r.name === resolve(ctx.stateDir) && + r.action === 'created' && + !r.removedAt + ); + const installs = record.filter( + (r) => r.cloud === 'box' && r.kind === 'installation' && r.action === 'created' && !r.removedAt ); + const stat = lstatSync(ctx.stateDir); if ( - !recordedHere && - !existsSync(join(ctx.stateDir, 'key-agent')) && - !existsSync(join(ctx.stateDir, LEGACY_KEYS)) + !ctx.installationId || + installs.length !== 1 || + installs[0]?.name !== ctx.installationId || + installs[0]?.attributes?.environment !== 'selfhost' || + installs[0]?.attributes?.domain !== ctx.domain || + states.length !== 1 || + states[0]?.attributes?.installation !== ctx.installationId || + states[0]?.attributes?.environment !== 'selfhost' || + states[0]?.attributes?.device !== String(stat.dev) || + states[0]?.attributes?.inode !== String(stat.ino) + ) + throw new Error('Refused: missing exact active installation state creation receipt'); + const keys = join(ctx.stateDir, LEGACY_KEYS); + if (existsSync(keys)) { + let identity: unknown; + try { + const parsed: unknown = JSON.parse(readFileSync(keys, 'utf8')); + if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) throw new Error(); + identity = (parsed as { SAM_INSTALLATION_ID?: unknown }).SAM_INSTALLATION_ID; + } catch { + throw new Error('Refused: unreadable installation identity'); + } + if (identity !== ctx.installationId) + throw new Error('Refused: platform identity disagrees with installation receipt'); + } else if ( + !record.some( + (r) => + r.cloud === 'box' && + r.kind === 'platform-keys' && + r.name === keys && + r.removedAt && + r.attributes?.installation === ctx.installationId && + r.attributes?.environment === 'selfhost' + ) ) { throw new Error( - `refused: ${ctx.stateDir} is neither recorded as this install's state nor holds its keys` + 'Refused: missing platform identity and no receipt that this teardown removed it' ); } } diff --git a/scripts/selfhost/teardown-state.test.ts b/scripts/selfhost/teardown-state.test.ts index e4b152ce9b..87832d6f6c 100644 --- a/scripts/selfhost/teardown-state.test.ts +++ b/scripts/selfhost/teardown-state.test.ts @@ -20,7 +20,8 @@ import { join } from 'node:path'; import { afterEach, beforeEach, describe, expect, it } from 'vitest'; -import { addResource } from '../../deploy/selfhost/created-resources.mjs'; +import { readRecord } from '../../deploy/selfhost/created-resources.mjs'; +import { recordInstall } from './install-record'; import { type TeardownContext } from './teardown-box'; import { execute, renderSummary } from './teardown-model'; import { clearStateEntries, removeTree, stateItems } from './teardown-state-dir'; @@ -29,6 +30,10 @@ let root: string; let state: string; function seedState(): void { + writeFileSync( + join(state, 'platform-keys.json'), + JSON.stringify({ SAM_INSTALLATION_ID: 'a'.repeat(32) }) + ); mkdirSync(join(state, 'key-agent', 'bundles'), { recursive: true }); writeFileSync(join(state, 'key-agent', 'kek'), 'fake-key-material'); writeFileSync(join(state, 'key-agent', 'bundles', 'b1.sealed'), 'fake-sealed'); @@ -40,14 +45,7 @@ function seedState(): void { function context(remove: (path: string) => void): TeardownContext { const recordFile = join(state, 'created-resources.json'); - addResource(recordFile, { - cloud: 'box', - kind: 'state-dir', - name: state, - action: 'created', - createdBy: 'deploy', - attributes: {}, - }); + recordInstall(state, join(root, '.env'), { SAM_DOMAIN: 'sam.example.com' }, 'a'.repeat(32)); return { box: {}, envFile: join(root, '.env'), @@ -59,19 +57,10 @@ function context(remove: (path: string) => void): TeardownContext { log: () => {}, mode: 'remove-everything', options: { deleteBackups: false, destroyKey: true, adoptDiscovered: false, gcpProjects: [] }, - record: [ - { - cloud: 'box', - kind: 'state-dir', - name: state, - action: 'created', - createdBy: 'deploy', - attributes: {}, - }, - ], + record: readRecord(recordFile).resources, recordFile, domain: 'sam.example.com', - installationId: null, + installationId: 'a'.repeat(32), selfhostDir: join(root, 'checkout', 'deploy', 'selfhost'), removeTree: remove, }; @@ -94,7 +83,9 @@ describe('emptying .state when an entry cannot be removed', () => { it('removes the secrets first and names the cache that is left', () => { const ctx = context(failOn('go-cache')); const outcomes = execute( - stateItems(ctx).filter((i) => i.id.startsWith('box:key') || i.id === 'box:state'), + stateItems(ctx).filter( + (i) => i.id.startsWith('box:key') || i.id === 'box:platform-keys' || i.id === 'box:state' + ), 'remove-everything', ctx.recordFile ); @@ -115,7 +106,9 @@ describe('emptying .state when an entry cannot be removed', () => { it('says plainly when what is left is not a cache', () => { const ctx = context(failOn('project')); const outcomes = execute( - stateItems(ctx).filter((i) => i.id.startsWith('box:key') || i.id === 'box:state'), + stateItems(ctx).filter( + (i) => i.id.startsWith('box:key') || i.id === 'box:platform-keys' || i.id === 'box:state' + ), 'remove-everything', ctx.recordFile ); @@ -148,7 +141,9 @@ describe('emptying .state when an entry cannot be removed', () => { }); try { const again = execute( - stateItems(blocked).filter((i) => i.id.startsWith('box:key') || i.id === 'box:state'), + stateItems(blocked).filter( + (i) => i.id.startsWith('box:key') || i.id === 'box:platform-keys' || i.id === 'box:state' + ), 'remove-everything', blocked.recordFile ); @@ -188,3 +183,31 @@ describe('emptying .state when an entry cannot be removed', () => { expect(readdirSync(join(state, 'key-agent'))).toEqual(['kek']); }); }); + +it.each(['missing', 'inactive', 'foreign', 'replaced-directory', 'foreign-platform'])( + 'refuses %s state ownership before removing any file', + (defect) => { + const ctx = context(removeTree); + const file = ctx.recordFile; + const data = readRecord(file); + const stateReceipt = data.resources.find((r) => r.kind === 'state-dir')!; + if (defect === 'missing') data.resources = data.resources.filter((r) => r !== stateReceipt); + else if (defect === 'inactive') stateReceipt.removedAt = new Date().toISOString(); + else if (defect === 'foreign') stateReceipt.attributes!.installation = 'b'.repeat(32); + else if (defect === 'replaced-directory') stateReceipt.attributes!.inode = 'invalid'; + else + writeFileSync( + join(state, 'platform-keys.json'), + JSON.stringify({ SAM_INSTALLATION_ID: 'b'.repeat(32) }) + ); + writeFileSync(file, JSON.stringify(data)); + const outcomes = execute( + stateItems(ctx).filter((i) => i.id === 'box:state'), + 'remove-everything', + file + ); + expect(outcomes[0]?.status).toBe('failed'); + expect(existsSync(join(state, 'secrets.env'))).toBe(true); + expect(existsSync(join(state, 'platform-keys.json'))).toBe(true); + } +); diff --git a/scripts/selfhost/teardown.test.ts b/scripts/selfhost/teardown.test.ts index 38e7bea269..ca03ddd7e0 100644 --- a/scripts/selfhost/teardown.test.ts +++ b/scripts/selfhost/teardown.test.ts @@ -9,16 +9,28 @@ import { writeFileSync, } from 'node:fs'; import { join, resolve } from 'node:path'; -import { afterEach, beforeEach, describe, expect, it } from 'vitest'; + +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; + import { addResource } from '../../deploy/selfhost/created-resources.mjs'; -import { runTsx } from './deploy-harness'; -import { composeProjectFor, recordInstall, recordPath } from './install-record'; +import { CHILD_TEST_TIMEOUT_MS, runTsx } from './deploy-harness'; +import { + composeProjectFor, + expectedComposeProjectFor, + recordInstall, + recordPath, +} from './install-record'; + +vi.setConfig({ testTimeout: CHILD_TEST_TIMEOUT_MS }); const CLI = resolve(import.meta.dirname, 'teardown.ts'); const OWN = 'a'.repeat(32); const DOMAIN = 'sam.example.com'; let dir: string, state: string, env: string, bin: string; beforeEach(() => { + for (const name of Object.keys(process.env)) + if (name === 'CI' || name === 'GITHUB_ACTIONS' || name.startsWith('RUNNER_')) + vi.stubEnv(name, undefined); mkdirSync(resolve('.tmp'), { recursive: true }); dir = mkdtempSync(resolve('.tmp/teardown-')); state = join(dir, '.state'); @@ -33,7 +45,26 @@ beforeEach(() => { recordInstall(state, env, { SAM_DOMAIN: DOMAIN }, OWN); executable( 'docker', - `fs.appendFileSync(process.env.CALLS, 'docker '+process.argv.slice(2).join(' ')+'\\n');` + ` + const args=process.argv.slice(2),cmd=args.join(' '),project=process.env.PROJECT; + fs.appendFileSync(process.env.CALLS,'docker '+cmd+'\\n'); + const removed=process.env.CALLS+'.removed',gone=process.env.CALLS+'.volume-removed',live=process.env.LIVE_DOCKER==='yes' || !!process.env.DOCKER_CASE; + if(cmd.startsWith('container ls')) { + if(live && !fs.existsSync(removed)) console.log('f'.repeat(64)); + } else if(cmd.startsWith('container inspect')) { + if(process.env.DOCKER_CASE==='malformed') console.log('{}'); + else console.log(JSON.stringify({id:'f'.repeat(64),labels:{'com.docker.compose.project':process.env.DOCKER_CASE==='foreign'?'foreign':project,'com.docker.compose.service':'celld','com.docker.compose.project.config_files':process.env.CONFIG_FILES,'com.docker.compose.project.working_dir':process.env.CONFIG_DIR}})); + } else if(cmd.startsWith('volume ls')) { + if(live && !fs.existsSync(gone)) console.log(project+(process.env.DOCKER_CASE==='missing-volume-label'?'_undefined':'_celld-data')); + } else if(cmd.startsWith('volume inspect')) { + const counter=process.env.CALLS+'.volume-checks'; + const count=fs.existsSync(counter)?Number(fs.readFileSync(counter,'utf8')):0; + fs.writeFileSync(counter,String(count+1)); + console.log(JSON.stringify({name:project+(process.env.DOCKER_CASE==='missing-volume-label'?'_undefined':'_celld-data'),createdAt:process.env.DOCKER_CASE==='replaced' && count>0?'2026-11-02T00:00:00Z':'2026-11-01T00:00:00Z',labels:{'com.docker.compose.project':project,...(process.env.DOCKER_CASE==='missing-volume-label'?{}:{'com.docker.compose.volume':'celld-data'})}})); + } else if(cmd.startsWith('container rm')) fs.writeFileSync(removed,'yes'); + else if(cmd.startsWith('volume rm')) fs.writeFileSync(gone,'yes'); + else if(!cmd.startsWith('container stop')) {console.error('unexpected Docker command');process.exit(1);} + ` ); executable( 'gcloud', @@ -59,7 +90,10 @@ beforeEach(() => { ` ); }); -afterEach(() => rmSync(dir, { recursive: true, force: true })); +afterEach(() => { + rmSync(dir, { recursive: true, force: true }); + vi.unstubAllEnvs(); +}); function executable(name: string, script: string) { const file = join(bin, name); writeFileSync(file, `#!/usr/bin/env node\nimport * as fs from 'node:fs';\n${script}\n`); @@ -69,6 +103,9 @@ function run(args: string[], extra: Record = {}) { return runTsx(CLI, ['--box-env', env, '--state-dir', state, ...args], { PATH: `${bin}:${process.env.PATH}`, CALLS: join(dir, 'calls'), + PROJECT: composeProjectFor({ SAM_DOMAIN: DOMAIN }, state), + CONFIG_FILES: resolve(import.meta.dirname, '../../deploy/selfhost/docker-compose.yml'), + CONFIG_DIR: resolve(import.meta.dirname, '../../deploy/selfhost'), ...extra, }); } @@ -87,6 +124,13 @@ function cloudReceipt(kind: string, name: string, extra: Record environment: 'selfhost', installation: OWN, identity: '123', + ...Object.fromEntries( + Object.keys(process.env) + .filter( + (name) => name === 'CI' || name === 'GITHUB_ACTIONS' || name.startsWith('RUNNER_') + ) + .map((name) => [name, undefined]) + ), ...extra, }, }); @@ -109,14 +153,14 @@ describe('teardown ownership at the CLI boundary', () => { member: 'serviceAccount:acct', role: 'roles/compute.securityAdmin', }); - const result = await run(['--keep-data', '--confirm', DOMAIN]); + const result = await run(['--keep-data', '--confirm', DOMAIN], { LIVE_DOCKER: 'yes' }); expect(result.status, result.out).toBe(0); expect(calls()).not.toContain('gcloud iam'); expect(calls()).not.toContain('remove-iam-policy-binding'); expect(existsSync(env)).toBe(true); expect(existsSync(join(state, 'platform-keys.json'))).toBe(true); expect(calls()).toContain(composeProjectFor({ SAM_DOMAIN: DOMAIN }, state)); - expect(calls()).toContain('stop'); + expect(calls()).toContain('container stop'); }); it('deletes owned unused firewall rules with exact id and owner proof', async () => { cloudReceipt('firewall-rule', 'sam-allow-agent'); @@ -259,3 +303,93 @@ it.each(['changed-id', 'changed-owner', 'duplicate', 'malformed'])( expect(calls()).not.toContain('instances delete'); } ); + +it.each(['foreign', 'malformed', 'replaced', 'missing-volume-label'])( + 'refuses %s live Docker ownership without touching state', + async (defect) => { + const result = await run(['--remove-everything', '--destroy-key', '--confirm', DOMAIN], { + DOCKER_CASE: defect, + }); + expect(result.status, result.out).toBe(1); + expect(calls()).not.toContain('container rm'); + expect(calls()).not.toContain('volume rm'); + expect(existsSync(join(state, 'platform-keys.json'))).toBe(true); + expect(existsSync(env)).toBe(true); + } +); +it('a reinstall at the same domain and state path gets a different Compose namespace', () => { + const first = composeProjectFor({ SAM_DOMAIN: DOMAIN }, state); + writeFileSync( + join(state, 'platform-keys.json'), + JSON.stringify({ SAM_INSTALLATION_ID: 'b'.repeat(32) }) + ); + expect(composeProjectFor({ SAM_DOMAIN: DOMAIN }, state)).not.toBe(first); +}); + +it.each(['CI', 'GITHUB_ACTIONS', 'RUNNER_NAME'])( + 'refuses %s presence before reading environment or Docker metadata', + async (marker) => { + writeFileSync(env, 'INVALID PRIVATE CONFIG', { mode: 0o600 }); + const result = await run([], { [marker]: '' }); + expect(result.status).toBe(1); + expect(result.out).toContain('forbidden in CI'); + expect(result.out).not.toContain('expected NAME=value'); + expect(calls()).toBe(''); + } +); + +it('removes only exact live owned container and volume identities, without a Compose sweep', async () => { + const result = await run(['--remove-everything', '--confirm', DOMAIN], { LIVE_DOCKER: 'yes' }); + expect(result.status, result.out).toBe(0); + expect(calls()).toContain(`container rm --force ${'f'.repeat(64)}`); + expect(calls()).toContain( + `volume rm ${composeProjectFor({ SAM_DOMAIN: DOMAIN }, state)}_celld-data` + ); + expect(calls()).not.toContain(' down '); + expect(existsSync(env)).toBe(false); +}); + +it('computes the final restore project from an authenticated id before copying keys', () => { + const final = expectedComposeProjectFor({ SAM_DOMAIN: DOMAIN }, state, OWN); + rmSync(join(state, 'platform-keys.json')); + expect(expectedComposeProjectFor({ SAM_DOMAIN: DOMAIN }, state, OWN)).toBe(final); + expect(() => expectedComposeProjectFor({ SAM_DOMAIN: DOMAIN }, state, 'invalid')).toThrow( + 'Invalid persisted' + ); + writeFileSync( + join(state, 'platform-keys.json'), + JSON.stringify({ SAM_INSTALLATION_ID: 'invalid' }) + ); + expect(() => expectedComposeProjectFor({ SAM_DOMAIN: DOMAIN }, state)).toThrow('Cannot resolve'); +}); + +it('retains the scoped installation project after teardown removed platform keys', () => { + const previous = expectedComposeProjectFor({ SAM_DOMAIN: DOMAIN }, state); + rmSync(join(state, 'platform-keys.json')); + expect(expectedComposeProjectFor({ SAM_DOMAIN: DOMAIN }, state)).toBe(previous); +}); + +it('retries --destroy-key safely after a real CLI state-cache removal failure', async () => { + const cache = join(state, 'go-cache'); + mkdirSync(cache); + writeFileSync(join(cache, 'fixture'), 'cache'); + const hook = join(dir, 'fail-cache.mjs'); + writeFileSync( + hook, + `import fs from 'node:fs'; import {syncBuiltinESMExports} from 'node:module'; +const original=fs.rmSync;fs.rmSync=function(path,...rest){if(process.env.FAIL_CACHE==='yes' && String(path)===process.env.PROTECTED_CACHE){const err=new Error('fixture removal denied');err.code='EPERM';throw err;}return original.call(this,path,...rest);};syncBuiltinESMExports();` + ); + const first = await run(['--remove-everything', '--destroy-key', '--confirm', DOMAIN], { + NODE_OPTIONS: `--import=${hook}`, + FAIL_CACHE: 'yes', + PROTECTED_CACHE: cache, + }); + expect(first.status, first.out).toBe(1); + expect(existsSync(join(state, 'platform-keys.json'))).toBe(false); + expect(existsSync(cache)).toBe(true); + expect(existsSync(env)).toBe(true); + const second = await run(['--remove-everything', '--destroy-key', '--confirm', DOMAIN]); + expect(second.status, second.out).toBe(0); + expect(existsSync(cache)).toBe(false); + expect(existsSync(env)).toBe(false); +}); diff --git a/scripts/selfhost/teardown.ts b/scripts/selfhost/teardown.ts index 9ca626d26a..d4b019975e 100644 --- a/scripts/selfhost/teardown.ts +++ b/scripts/selfhost/teardown.ts @@ -28,6 +28,7 @@ import { type CreatedResource, readRecord } from '../../deploy/selfhost/created- import { log, runCommand, SELFHOST_DIR } from './backup-cli'; import { composeFilesFor } from './backup-lib'; import { recordPath } from './install-record'; +import { assertOperatorExecution } from './operator-only'; import { assertPrivateFile, parseDotenv } from './secret-files'; import { boxItems, bucketItems, type TeardownContext } from './teardown-box'; import { gcpItems } from './teardown-gcp'; @@ -151,6 +152,7 @@ async function confirm(expected: string, given: string | undefined): Promise { + assertOperatorExecution(); const { values, mode } = parse(); const envFile = resolve(values['box-env'] ?? join(SELFHOST_DIR, '.env')); let box: Record = {}; diff --git a/scripts/selfhost/testdata/fake-docker.mjs b/scripts/selfhost/testdata/fake-docker.mjs index f4eca4d4b5..00756cc077 100755 --- a/scripts/selfhost/testdata/fake-docker.mjs +++ b/scripts/selfhost/testdata/fake-docker.mjs @@ -14,7 +14,13 @@ import { dirname, join } from 'node:path'; const state = process.env.FAKE_STATE; const args = process.argv.slice(2); appendFileSync(join(state, 'calls.log'), `docker ${args.join(' ')}\n`); +if (args[0] === 'ps') process.exit(0); if (args[0] !== 'compose') process.exit(2); +// Record only this non-secret path, so the entrypoint test observes compose's selected state. +appendFileSync( + join(state, 'compose-state-dirs.log'), + `${process.env.SAM_SELFHOST_STATE_DIR ?? ''}\n` +); const [action, service] = args.slice(-2); if (service !== 'celld') process.exit(2); writeFileSync(join(state, 'celld'), action === 'stop' ? 'stopped' : 'running'); diff --git a/scripts/selfhost/upgrade-lib.ts b/scripts/selfhost/upgrade-lib.ts index 7335ddecd7..861023d7c0 100644 --- a/scripts/selfhost/upgrade-lib.ts +++ b/scripts/selfhost/upgrade-lib.ts @@ -9,6 +9,7 @@ import { existsSync, mkdirSync, readFileSync, rmSync } from 'node:fs'; import { dirname, isAbsolute, join, resolve } from 'node:path'; import { + assertRollbackCacheReady, type BoxContext as BackupContext, composeArgs, runBackup, @@ -427,6 +428,7 @@ export async function runUpgrade(ctx: BoxContext, opts: UpgradeOptions): Promise rmSync(join(ctx.stateDir, UPGRADE_PENDING_FILE), { force: true }); return runUpgrade(ctx, opts); } + assertRollbackCacheReady(backupContext(ctx)); const installed = installedMigrations(backupContext(ctx)); runBackup(backupContext(ctx), backupDir, from); diff --git a/scripts/selfhost/upgrade-preflight.test.ts b/scripts/selfhost/upgrade-preflight.test.ts index f131fd6c52..e4e374c24f 100644 --- a/scripts/selfhost/upgrade-preflight.test.ts +++ b/scripts/selfhost/upgrade-preflight.test.ts @@ -29,7 +29,12 @@ beforeEach(() => { run: runner, log: vi.fn(), }; - recordInstall(stateDir, envFile, context.box, 'installation-identity'); + writeFileSync( + join(stateDir, 'platform-keys.json'), + JSON.stringify({ SAM_INSTALLATION_ID: 'a'.repeat(32) }), + { mode: 0o600 } + ); + recordInstall(stateDir, envFile, context.box, 'a'.repeat(32)); }); afterEach(() => { vi.unstubAllEnvs(); diff --git a/scripts/selfhost/upgrade-safeguards.test.ts b/scripts/selfhost/upgrade-safeguards.test.ts index dd6d84352a..cd8c9fef45 100644 --- a/scripts/selfhost/upgrade-safeguards.test.ts +++ b/scripts/selfhost/upgrade-safeguards.test.ts @@ -30,6 +30,8 @@ let target: typeof HISTORY; let current: string; let failCommand: string | undefined; let generatedChange: boolean; +let cacheProject: string; +let invalidCacheMount: boolean; function run(command: string, args: string[]): RunResult { const ok = (stdout = '') => ({ status: 0, stdout, stderr: '' }); @@ -47,6 +49,35 @@ function run(command: string, args: string[]): RunResult { if (args[0] === 'diff') return ok(diff.join('\n')); if (args[0] === 'checkout') current = args[2] ?? FROM; } + if (command === 'docker' && args.includes('ps')) { + cacheProject = args[args.indexOf('--project-name') + 1] ?? ''; + return ok('c'.repeat(64)); + } + if (command === 'docker' && args[0] === 'inspect') { + return ok( + JSON.stringify([ + { + Type: invalidCacheMount ? 'bind' : 'volume', + Name: `${cacheProject}_celld-data`, + Destination: '/var/lib/celld', + }, + ]) + ); + } + if (command === 'docker' && args[0] === 'volume' && args[1] === 'inspect') { + return ok( + JSON.stringify([ + { + Name: `${cacheProject}_celld-data`, + CreatedAt: '2026-11-19T00:00:00Z', + Labels: { + 'com.docker.compose.project': cacheProject, + 'com.docker.compose.volume': 'celld-data', + }, + }, + ]) + ); + } if (command === 'gcloud') { return ok( JSON.stringify( @@ -105,6 +136,8 @@ beforeEach(() => { current = FROM; failCommand = undefined; generatedChange = false; + cacheProject = ''; + invalidCacheMount = false; vi.mocked(runBackup) .mockReset() .mockImplementation(() => { @@ -174,6 +207,22 @@ describe('runUpgrade', () => { expect(runRollback).toHaveBeenCalledOnce(); }); + it('proves the real celld cache mount before snapshotting or changing the checkout', async () => { + await upgrade(); + const proof = steps.findIndex((step) => step.startsWith('docker volume inspect ')); + expect(proof).toBeGreaterThan(-1); + expect(proof).toBeLessThan(steps.indexOf('BACKUP')); + expect(steps.indexOf('BACKUP')).toBeLessThan(steps.indexOf(`git checkout --detach ${TO}`)); + }); + + it('refuses an unowned bind-mounted cache before backup or checkout', async () => { + invalidCacheMount = true; + await expect(upgrade()).rejects.toThrow(/not the canonical owned volume/); + expect(runBackup).not.toHaveBeenCalled(); + expect(steps.some((step) => step.startsWith('git checkout'))).toBe(false); + expect(steps).not.toContain('pnpm selfhost:deploy --init'); + }); + it('permits a new shared tag before the retained selfhost-only suffix', async () => { target.splice(1, 0, { tag: 'v2', new_sqlite_classes: ['MoreData'] }); await upgrade(); diff --git a/scripts/selfhost/upgrade.test.ts b/scripts/selfhost/upgrade.test.ts index 4019ee565b..6ae9a26e2b 100644 --- a/scripts/selfhost/upgrade.test.ts +++ b/scripts/selfhost/upgrade.test.ts @@ -26,6 +26,7 @@ import { vi.mock('./backup-lib.js', async (original) => ({ ...(await original()), runBackup: vi.fn(), + assertRollbackCacheReady: vi.fn(), runRollback: vi.fn(), })); vi.mock('./upgrade-migrations.js', async (original) => ({ diff --git a/tasks/active/2026-11-19-l24-selfhost-operations.md b/tasks/active/2026-11-19-l24-selfhost-operations.md index 760bce7b32..43c8392e6c 100644 --- a/tasks/active/2026-11-19-l24-selfhost-operations.md +++ b/tasks/active/2026-11-19-l24-selfhost-operations.md @@ -17,15 +17,15 @@ Land backup, restore, upgrade checks and teardown from `sam/selfhost-pass-2` ont ## Implementation checklist -- [ ] Port and trim operations paths only; keep all self-host code under deploy/selfhost or scripts/selfhost. -- [ ] Encrypt all persisted backup payloads; external key, authentication, failure cleanup and secret-free diagnostics. +- [x] Port and trim operations paths only; keep all self-host code under deploy/selfhost or scripts/selfhost. +- [x] Encrypt all persisted backup payloads; external key, authentication, failure cleanup and secret-free diagnostics. - [ ] Restore only into empty target, validate all encrypted payloads before mutation; verify actual data round trip. - [ ] Reproduce backup failure on BOX, fix evidence-based cause and add regression. - [ ] Upgrade preflight rejects unknown/reordered DO tags, including H2; valid check passes. - [ ] Automatic upgrade rollback restores previous consistent state and reports rollback failure clearly. -- [ ] Unique compose projects, exact ownership proof for destructive operations; no legacy adoption. -- [ ] Keep-data retains data plus needed identity; permission errors remain visible, never treated as absence. -- [ ] Documentation and CLI command wiring updated, including S3 region. +- [x] Unique compose projects, exact ownership proof for destructive operations; no legacy adoption. +- [x] Keep-data retains data plus needed identity; permission errors remain visible, never treated as absence. +- [x] Documentation and CLI command wiring updated, including S3 region. - [ ] Relevant automated checks; independent security and task-completion reviews on current head. - [ ] BOX claimed after FREE; real backup, disposable restore with data verified, passing/refused upgrades. - [ ] Disposable owned teardown proven; all resources cleaned, BOX healthy, BOX FREE posted. @@ -47,3 +47,9 @@ Idea 01M72M9AEB933ZY8269D376DKC LANDING PLAN part 6; policy 795e72a6; rule 56 de - finally restarted celld; verified all four original containers running, API health200, checkout unchanged. No config/bucket writes or candidate deploy. - Coordinator mistakenly gave L23 overlapping claim413 from frozen history; acknowledged L24 claim412 was first. L24 yielded, BOX FREE414. L24 explicitly next after L23 releases. - Own partial backup/code/log removed, metadata SSH key absence and own firewall404 verified, local token/private key removed. Existing saml24 OS account has no key. + +## Local validation and review update + +Root lint (23 packages), typecheck (38), build (19) pass. Root tests remain in flight. Encryption/operator focused68, scanner187 and realDocker2 pass (synthetic test data, disposable volumes cleaned). Final full self-host run:541pass/17fail, all upgrade-preflight setup affected by stricter CI guard; fixture repair under review. Security reviewer caught real stopped-container selection bug and service-reselection deletion; fixed with Compose --all/full IDs and exact container deletion, real stopped-container/overlay controls pass. Final candidate review and BOX gates still pending. + +Final local suite after upgrade preflight wiring/fixture repairs:560tests/30filesPASS, upgrade96PASS, tsc/eslintPASS. One remaining final review volume-label control being added; live criteria still unfulfilled. Root timeout retry12/12PASS; scanner0findings, type-boundary0blocking. From faf03e4c8b9026179290985c62da9581b87c23fd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rapha=C3=ABl=20Titsworth-Morin?= Date: Thu, 19 Nov 2026 22:36:00 +0000 Subject: [PATCH 03/17] refactor(selfhost): address operations analysis findings --- deploy/selfhost/gcp-bootstrap.sh | 6 +- scripts/quality/operator-backup-exceptions.ts | 260 +++++++------ scripts/selfhost/backup-lib.ts | 22 +- scripts/selfhost/backup-recovery.ts | 3 +- scripts/selfhost/bucket-objects.test.ts | 86 +++++ scripts/selfhost/bucket-objects.ts | 56 +-- scripts/selfhost/install-record.ts | 5 +- scripts/selfhost/teardown-box.ts | 153 ++++---- scripts/selfhost/teardown-compose.ts | 10 +- scripts/selfhost/teardown-gcp-bootstrap.ts | 357 ++++++++++-------- scripts/selfhost/teardown-gcp.ts | 18 +- scripts/selfhost/teardown-model.ts | 114 +++--- scripts/selfhost/teardown-state-dir.ts | 65 ++-- scripts/selfhost/teardown.ts | 35 +- scripts/selfhost/upgrade-compose.ts | 2 +- scripts/selfhost/upgrade-lib.ts | 113 +++--- scripts/selfhost/upgrade-preflight.ts | 18 + scripts/selfhost/upgrade-safeguards.test.ts | 13 +- scripts/selfhost/upgrade.test.ts | 5 +- .../2026-11-19-l24-selfhost-operations.md | 4 + 20 files changed, 801 insertions(+), 544 deletions(-) create mode 100644 scripts/selfhost/bucket-objects.test.ts diff --git a/deploy/selfhost/gcp-bootstrap.sh b/deploy/selfhost/gcp-bootstrap.sh index 13ead3e14a..c9000f05ab 100755 --- a/deploy/selfhost/gcp-bootstrap.sh +++ b/deploy/selfhost/gcp-bootstrap.sh @@ -156,9 +156,11 @@ command -v gcloud >/dev/null 2>&1 || die "gcloud is not installed or not on PATH # Receipts contain public resource identifiers only, never credentials. Reuse never becomes # creation proof; teardown will preserve resources that existed before this install. record_resource() { + local resource_kind="$1" resource_name="$2" resource_action="$3" resource_identity="$4" + local resource_member="${5:-}" resource_role="${6:-}" [[ "$DRY_RUN" -eq 0 && -n "$INSTALLATION_ID" ]] || return 0 - node "$SCRIPT_DIR/created-resources.mjs" add "$STATE_DIR/created-resources.json" gcp "$1" "$2" "$3" gcp-bootstrap \ - "project=$PROJECT" "install=$ISSUER" "identity=$4" "pool=$POOL_ID" "environment=selfhost" "installation=$INSTALLATION_ID" "account=$SA_EMAIL" "member=${5:-}" "role=${6:-}" + node "$SCRIPT_DIR/created-resources.mjs" add "$STATE_DIR/created-resources.json" gcp "$resource_kind" "$resource_name" "$resource_action" gcp-bootstrap \ + "project=$PROJECT" "install=$ISSUER" "identity=$resource_identity" "pool=$POOL_ID" "environment=selfhost" "installation=$INSTALLATION_ID" "account=$SA_EMAIL" "member=$resource_member" "role=$resource_role" } # The OIDC provider trusts the issuer the install advertises: check it before trusting it. diff --git a/scripts/quality/operator-backup-exceptions.ts b/scripts/quality/operator-backup-exceptions.ts index 874d81fb45..739d29eb5c 100644 --- a/scripts/quality/operator-backup-exceptions.ts +++ b/scripts/quality/operator-backup-exceptions.ts @@ -5,34 +5,38 @@ */ import ts from 'typescript'; -export function operatorBackupAllowances(file: string, text: string): ReadonlySet { - const allowed = new Set(); - if ( - ![ - 'scripts/selfhost/backup-encryption.ts', - 'scripts/selfhost/backup-lib.ts', - 'scripts/selfhost/backup-recovery.ts', - ].includes(file) - ) - return allowed; +interface Context { + source: ts.SourceFile; + text: string; + functions: Map; +} +const FILES = [ + 'scripts/selfhost/backup-encryption.ts', + 'scripts/selfhost/backup-lib.ts', + 'scripts/selfhost/backup-recovery.ts', +]; +function context(file: string, text: string): Context { const source = ts.createSourceFile(file, text, ts.ScriptTarget.Latest, true); const functions = new Map(); for (const statement of source.statements) { if (ts.isFunctionDeclaration(statement) && statement.name) functions.set(statement.name.text, statement); } - const guarded = (name: string): boolean => { - const first = functions.get(name)?.body?.statements[0]; - return ( - first !== undefined && - ts.isExpressionStatement(first) && - ts.isCallExpression(first.expression) && - ts.isIdentifier(first.expression.expression) && - first.expression.expression.text === 'assertOperatorExecution' && - first.expression.arguments.length === 0 - ); - }; - const guardImport = source.statements.some( + return { source, text, functions }; +} +function guarded(ctx: Context, name: string): boolean { + const first = ctx.functions.get(name)?.body?.statements[0]; + return ( + first !== undefined && + ts.isExpressionStatement(first) && + ts.isCallExpression(first.expression) && + ts.isIdentifier(first.expression.expression) && + first.expression.expression.text === 'assertOperatorExecution' && + first.expression.arguments.length === 0 + ); +} +function hasGuardImport(ctx: Context): boolean { + return ctx.source.statements.some( (statement) => ts.isImportDeclaration(statement) && ts.isStringLiteral(statement.moduleSpecifier) && @@ -43,107 +47,139 @@ export function operatorBackupAllowances(file: string, text: string): ReadonlySe (binding) => binding.name.text === 'assertOperatorExecution' && !binding.propertyName ) ); - if (!guardImport) return allowed; - const lineOf = (node: ts.Node) => - source.getLineAndCharacterOfPosition(node.getStart(source)).line; - if (file === 'scripts/selfhost/backup-encryption.ts') { - if ( - !['readBackupKey', 'encryptBackupTree', 'decryptBackupTree', 'transformFile'].every(guarded) - ) - return allowed; - const body = functions.get('transformFile')?.body; - if (!body) return allowed; - const candidates: ts.CallExpression[] = []; - const visit = (node: ts.Node): void => { - if ( - ts.isCallExpression(node) && - ts.isIdentifier(node.expression) && - node.expression.text === 'createDecipheriv' - ) - candidates.push(node); - ts.forEachChild(node, visit); - }; - visit(body); - if (candidates.length !== 1) return allowed; - const call = candidates[0]; - let owner: ts.Node = call; - while (owner.parent && !ts.isFunctionLike(owner)) owner = owner.parent; - if (owner !== functions.get('transformFile')) return allowed; - const args = call.arguments; - const line = text.split(/\r?\n/)[lineOf(call)].trim(); - if ( - args.length === 3 && - ts.isStringLiteral(args[0]) && - args[0].text === 'aes-256-gcm' && - ts.isIdentifier(args[1]) && - args[1].text === 'key' && - ts.isIdentifier(args[2]) && - args[2].text === 'nonce' && - line === `? ${call.getText(source)}` - ) - allowed.add(lineOf(call)); - return allowed; - } - const functionName = file === 'scripts/selfhost/backup-lib.ts' ? 'runRestore' : 'runRollback'; - if (!guarded(functionName)) return allowed; - const expectedNames = - functionName === 'runRestore' - ? ['decryptBackupTree', 'encryptBackupTree', 'readBackupKey'] - : ['decryptBackupTree']; - let importNode: ts.ImportDeclaration | undefined; - for (const statement of source.statements) { - if ( - !ts.isImportDeclaration(statement) || - !ts.isStringLiteral(statement.moduleSpecifier) || - !['./backup-encryption', './backup-encryption.js'].includes(statement.moduleSpecifier.text) - ) - continue; - const bindings = statement.importClause?.namedBindings; +} +function lineOf(ctx: Context, node: ts.Node): number { + return ctx.source.getLineAndCharacterOfPosition(node.getStart(ctx.source)).line; +} +function ownerOf(node: ts.Node): ts.Node { + let owner = node; + while (owner.parent && !ts.isFunctionLike(owner)) owner = owner.parent; + return owner; +} +function namedCalls(body: ts.Node, name: string): ts.CallExpression[] { + const calls: ts.CallExpression[] = []; + const visit = (node: ts.Node): void => { if ( - !bindings || - !ts.isNamedImports(bindings) || - bindings.elements.some((binding) => binding.propertyName) + ts.isCallExpression(node) && + ts.isIdentifier(node.expression) && + node.expression.text === name ) - return allowed; - if ( - bindings.elements - .map((binding) => binding.name.text) - .sort() - .join(',') !== expectedNames.sort().join(',') || - importNode + calls.push(node); + ts.forEachChild(node, visit); + }; + visit(body); + return calls; +} +function envelopeArguments(call: ts.CallExpression): boolean { + const args = call.arguments; + return ( + args.length === 3 && + ts.isStringLiteral(args[0]) && + args[0].text === 'aes-256-gcm' && + ts.isIdentifier(args[1]) && + args[1].text === 'key' && + ts.isIdentifier(args[2]) && + args[2].text === 'nonce' + ); +} +function envelopeLine(ctx: Context): number | undefined { + if ( + !['readBackupKey', 'encryptBackupTree', 'decryptBackupTree', 'transformFile'].every((name) => + guarded(ctx, name) ) - return allowed; - importNode = statement; - } - if (!importNode) return allowed; - const endLine = source.getLineAndCharacterOfPosition(importNode.end).line; + ) + return undefined; + const body = ctx.functions.get('transformFile')?.body; + if (!body) return undefined; + const calls = namedCalls(body, 'createDecipheriv'); + if (calls.length !== 1) return undefined; + const call = calls[0]; + if (ownerOf(call) !== ctx.functions.get('transformFile') || !envelopeArguments(call)) + return undefined; + const line = lineOf(ctx, call); + return ctx.text.split(/\r?\n/)[line].trim() === `? ${call.getText(ctx.source)}` + ? line + : undefined; +} +function isBackupImport(statement: ts.Statement): statement is ts.ImportDeclaration { + return ( + ts.isImportDeclaration(statement) && + ts.isStringLiteral(statement.moduleSpecifier) && + ['./backup-encryption', './backup-encryption.js'].includes(statement.moduleSpecifier.text) + ); +} +function sortedNames(names: readonly string[]): string { + const sorted = [...names]; + sorted.sort((left, right) => left.localeCompare(right)); + return sorted.join(','); +} +function expectedBindings(statement: ts.ImportDeclaration, names: readonly string[]): boolean { + const bindings = statement.importClause?.namedBindings; if ( - text + !bindings || + !ts.isNamedImports(bindings) || + bindings.elements.some((binding) => binding.propertyName) + ) + return false; + return sortedNames(bindings.elements.map((binding) => binding.name.text)) === sortedNames(names); +} +function importIsWholeLine(ctx: Context, statement: ts.ImportDeclaration): boolean { + const endLine = ctx.source.getLineAndCharacterOfPosition(statement.end).line; + return ( + ctx.text .split(/\r?\n/) - .slice(lineOf(importNode), endLine + 1) + .slice(lineOf(ctx, statement), endLine + 1) .join('\n') - .trim() !== importNode.getText(source) - ) - return allowed; - let valid = true; - let calls = 0; + .trim() === statement.getText(ctx.source) + ); +} +function helperReferences(ctx: Context): ts.Identifier[] { + const references: ts.Identifier[] = []; const visit = (node: ts.Node): void => { if ( ts.isIdentifier(node) && node.text === 'decryptBackupTree' && !ts.isImportSpecifier(node.parent) - ) { - if (!ts.isCallExpression(node.parent) || node.parent.expression !== node) valid = false; - else { - calls++; - let parent: ts.Node = node.parent; - while (parent.parent && !ts.isFunctionLike(parent)) parent = parent.parent; - if (parent !== functions.get(functionName)) valid = false; - } - } + ) + references.push(node); ts.forEachChild(node, visit); }; - visit(source); - if (valid && calls === 1) allowed.add(lineOf(importNode)); - return allowed; + visit(ctx.source); + return references; +} +function importedHelperLine(ctx: Context, functionName: string): number | undefined { + if (!guarded(ctx, functionName)) return undefined; + const names = + functionName === 'runRestore' + ? ['decryptBackupTree', 'encryptBackupTree', 'readBackupKey'] + : ['decryptBackupTree']; + const imports = ctx.source.statements.filter(isBackupImport); + if ( + imports.length !== 1 || + !expectedBindings(imports[0], names) || + !importIsWholeLine(ctx, imports[0]) + ) + return undefined; + const references = helperReferences(ctx); + if (references.length !== 1) return undefined; + const reference = references[0]; + if ( + !ts.isCallExpression(reference.parent) || + reference.parent.expression !== reference || + ownerOf(reference.parent) !== ctx.functions.get(functionName) + ) + return undefined; + return lineOf(ctx, imports[0]); +} + +export function operatorBackupAllowances(file: string, text: string): ReadonlySet { + if (!FILES.includes(file)) return new Set(); + const ctx = context(file, text); + if (!hasGuardImport(ctx)) return new Set(); + const functionName = file === 'scripts/selfhost/backup-lib.ts' ? 'runRestore' : 'runRollback'; + const line = + file === 'scripts/selfhost/backup-encryption.ts' + ? envelopeLine(ctx) + : importedHelperLine(ctx, functionName); + return line === undefined ? new Set() : new Set([line]); } diff --git a/scripts/selfhost/backup-lib.ts b/scripts/selfhost/backup-lib.ts index 2d7143f814..68d269b8be 100644 --- a/scripts/selfhost/backup-lib.ts +++ b/scripts/selfhost/backup-lib.ts @@ -77,13 +77,21 @@ export interface BucketUrl { } export function parseBucketUrl(url: string): BucketUrl { - const match = /^(gs|s3):\/\/([^/]+)\/?(.*)$/.exec(url.trim()); - if (!match) throw new Error(`CELLD_BUCKET must be gs://bucket[/prefix] or s3://bucket[/prefix]`); - return { - scheme: match[1] as 'gs' | 's3', - bucket: match[2] as string, - prefix: (match[3] ?? '').replace(/\/+$/, ''), - }; + const value = url.trim(); + let scheme: 'gs' | 's3'; + if (value.startsWith('gs://')) scheme = 'gs'; + else if (value.startsWith('s3://')) scheme = 's3'; + else throw new Error('CELLD_BUCKET must be gs://bucket[/prefix] or s3://bucket[/prefix]'); + if (/[\r\n\u2028\u2029]/.test(value)) + throw new Error('CELLD_BUCKET must be gs://bucket[/prefix] or s3://bucket[/prefix]'); + const rest = value.slice(5); + const slash = rest.indexOf('/'); + const bucket = slash === -1 ? rest : rest.slice(0, slash); + if (!bucket) throw new Error('CELLD_BUCKET must be gs://bucket[/prefix] or s3://bucket[/prefix]'); + const prefix = slash === -1 ? '' : rest.slice(slash + 1); + let end = prefix.length; + while (end > 0 && prefix[end - 1] === '/') end--; + return { scheme, bucket, prefix: prefix.slice(0, end) }; } export function check(result: RunResult, what: string): RunResult { diff --git a/scripts/selfhost/backup-recovery.ts b/scripts/selfhost/backup-recovery.ts index d31363f0d8..1707780077 100644 --- a/scripts/selfhost/backup-recovery.ts +++ b/scripts/selfhost/backup-recovery.ts @@ -33,7 +33,8 @@ function compose(ctx: BoxContext, args: string[]): void { function readIdentity(path: string): Record { try { const value: unknown = JSON.parse(readFileSync(path, 'utf8')); - if (typeof value !== 'object' || value === null || Array.isArray(value)) throw new Error(); + if (typeof value !== 'object' || value === null || Array.isArray(value)) + throw new Error('Invalid rollback identity object'); return value as Record; } catch { throw new Error('Cannot verify rollback installation identity'); diff --git a/scripts/selfhost/bucket-objects.test.ts b/scripts/selfhost/bucket-objects.test.ts new file mode 100644 index 0000000000..d5c33af6fa --- /dev/null +++ b/scripts/selfhost/bucket-objects.test.ts @@ -0,0 +1,86 @@ +import { describe, expect, it, vi } from 'vitest'; + +import { type BoxContext, parseBucketUrl } from './backup-lib'; +import { listObjects } from './bucket-objects'; + +function context(bucket: string, stdout: string): BoxContext { + return { + box: { + CELLD_BUCKET: bucket, + S3_ENDPOINT: 'http://store.example', + AWS_ACCESS_KEY_ID: 'fixture', + AWS_SECRET_ACCESS_KEY: 'fixture', + }, + envFile: '/unused', + stateDir: '/unused', + composeFiles: [], + now: Date.now, + log: vi.fn(), + run: vi.fn(() => ({ status: 0, stdout, stderr: '' })), + }; +} + +describe('fleet object listings', () => { + it('parses GCS listing records and ignores totals, unrelated roots and malformed records', () => { + const ctx = context( + 'gs://fleet/celld', + ' 12 2026-11-19T00:00:00Z gs://fleet/celld/deploy/file.json\nTOTAL: 1 objects\n5 now gs://other/file\n5 now gs://fleet/celld/x extra\n' + ); + expect(listObjects(ctx, 'deploy/')).toEqual([ + { key: 'deploy/file.json', size: 12, lastModified: '2026-11-19T00:00:00Z' }, + ]); + expect(ctx.run).toHaveBeenCalledWith('gcloud', [ + 'storage', + 'ls', + '--long', + 'gs://fleet/celld/deploy/**', + ]); + }); + it('preserves S3 string timestamps and missing timestamps without object stringification', () => { + const ctx = context( + 's3://fleet/celld', + [ + JSON.stringify({ + type: 'file', + key: 'a.json', + size: 7, + lastModified: '2026-11-19T00:00:00Z', + }), + JSON.stringify({ type: 'file', key: 'b.json', size: 2 }), + JSON.stringify({ type: 'folder', key: 'ignored' }), + ].join('\n') + ); + expect(listObjects(ctx, 'deploy/')).toEqual([ + { key: 'deploy/a.json', size: 7, lastModified: '2026-11-19T00:00:00Z' }, + { key: 'deploy/b.json', size: 2, lastModified: '' }, + ]); + }); + it.each([{}, [], 1, true])('refuses a non-string S3 timestamp %j', (lastModified) => { + const ctx = context( + 's3://fleet/celld', + JSON.stringify({ type: 'file', key: 'a', lastModified }) + ); + expect(() => listObjects(ctx, '')).toThrow('Invalid object timestamp from store'); + }); + it('sanitizes malformed object listing errors', () => { + const ctx = context('s3://fleet/celld', '{"fixture-sensitive-fragment'); + expect(() => listObjects(ctx, '')).toThrow('Invalid object listing from store'); + }); +}); + +describe('bucket URL parsing', () => { + it('parses optional prefixes and strips a long run of trailing slashes with bounded scanning', () => { + expect(parseBucketUrl(' gs://fleet ')).toEqual({ scheme: 'gs', bucket: 'fleet', prefix: '' }); + expect(parseBucketUrl('s3://fleet/a/b' + '/'.repeat(100_000))).toEqual({ + scheme: 's3', + bucket: 'fleet', + prefix: 'a/b', + }); + }); + it.each(['gs:///prefix', 'https://fleet', 's3://', 'gs://fleet/path\nextra'])( + 'refuses invalid bucket URL %j', + (value) => { + expect(() => parseBucketUrl(value)).toThrow('CELLD_BUCKET must be'); + } + ); +}); diff --git a/scripts/selfhost/bucket-objects.ts b/scripts/selfhost/bucket-objects.ts index b8888835a9..be89af2acc 100644 --- a/scripts/selfhost/bucket-objects.ts +++ b/scripts/selfhost/bucket-objects.ts @@ -21,6 +21,29 @@ function base(ctx: BoxContext): { scheme: 'gs' | 's3'; root: string } { }; } +function gcsObject(line: string, root: string): BucketObject | undefined { + const fields = line.trim().split(/\s+/); + const [size, modified, url] = fields; + if (fields.length !== 3 || !size || !/^\d+$/.test(size) || !url?.startsWith(`${root}/`)) + return undefined; + return { key: url.slice(root.length + 1), size: Number(size), lastModified: modified ?? '' }; +} +function s3Object(line: string, prefix: string): BucketObject | undefined { + if (!line.trim()) return undefined; + let entry: unknown; + try { + entry = JSON.parse(line); + } catch { + throw new Error('Invalid object listing from store'); + } + if (typeof entry !== 'object' || entry === null) return undefined; + const record = entry as Record; + if (record.type !== 'file' || typeof record.key !== 'string') return undefined; + const lastModified = record.lastModified ?? ''; + if (typeof lastModified !== 'string') throw new Error('Invalid object timestamp from store'); + return { key: `${prefix}${record.key}`, size: Number(record.size ?? 0), lastModified }; +} + /** Every object whose key starts with `prefix` (e.g. `deploy/`). */ export function listObjects(ctx: BoxContext, prefix: string): BucketObject[] { const { scheme, root } = base(ctx); @@ -28,17 +51,10 @@ export function listObjects(ctx: BoxContext, prefix: string): BucketObject[] { const result = ctx.run('gcloud', ['storage', 'ls', '--long', `${root}/${prefix}**`]); if (result.status !== 0 && /matched no objects/i.test(result.stderr)) return []; check(result, 'gcloud storage ls'); - const objects: BucketObject[] = []; - for (const line of result.stdout.split('\n')) { - const match = /^\s*(\d+)\s+(\S+)\s+(gs:\/\/\S+)\s*$/.exec(line); - if (!match?.[3]?.startsWith(`${root}/`)) continue; - objects.push({ - key: match[3].slice(root.length + 1), - size: Number(match[1]), - lastModified: match[2] ?? '', - }); - } - return objects; + return result.stdout.split('\n').flatMap((line) => { + const object = gcsObject(line, root); + return object ? [object] : []; + }); } const result = check( ctx.run( @@ -48,20 +64,10 @@ export function listObjects(ctx: BoxContext, prefix: string): BucketObject[] { ), 'mc ls' ); - const objects: BucketObject[] = []; - for (const line of result.stdout.split('\n')) { - if (!line.trim()) continue; - const entry = JSON.parse(line) as unknown; - if (typeof entry !== 'object' || entry === null) continue; - const record = entry as Record; - if (record.type !== 'file' || typeof record.key !== 'string') continue; - objects.push({ - key: `${prefix}${record.key}`, - size: Number(record.size ?? 0), - lastModified: String(record.lastModified ?? ''), - }); - } - return objects; + return result.stdout.split('\n').flatMap((line) => { + const object = s3Object(line, prefix); + return object ? [object] : []; + }); } export function readObject(ctx: BoxContext, key: string): string { diff --git a/scripts/selfhost/install-record.ts b/scripts/selfhost/install-record.ts index 6fa415bbaf..93fafb74d3 100644 --- a/scripts/selfhost/install-record.ts +++ b/scripts/selfhost/install-record.ts @@ -37,13 +37,14 @@ export function expectedComposeProjectFor( assertOperatorExecution(); try { const raw: unknown = JSON.parse(readFileSync(keys, 'utf8')); - if (!raw || typeof raw !== 'object' || Array.isArray(raw)) throw new Error(); + if (!raw || typeof raw !== 'object' || Array.isArray(raw)) + throw new Error('Invalid ownership metadata shape'); const value = raw as { SAM_INSTALLATION_ID?: unknown }; if ( typeof value.SAM_INSTALLATION_ID !== 'string' || !/^[a-f0-9]{32}$/.test(value.SAM_INSTALLATION_ID) ) - throw new Error(); + throw new Error('Invalid ownership metadata shape'); installation = value.SAM_INSTALLATION_ID; } catch { throw new Error('Cannot resolve installation Compose identity'); diff --git a/scripts/selfhost/teardown-box.ts b/scripts/selfhost/teardown-box.ts index 06446c88ee..e83d15e41b 100644 --- a/scripts/selfhost/teardown-box.ts +++ b/scripts/selfhost/teardown-box.ts @@ -9,7 +9,7 @@ import { isAbsolute, join, resolve } from 'node:path'; import type { CreatedResource } from '../../deploy/selfhost/created-resources.mjs'; import { type BoxContext, composeArgs, MANIFEST_NAME, parseBucketUrl } from './backup-lib'; import { composeProjectFor, expectedComposeProjectFor, usesBundledStore } from './install-record'; -import { readComposeInventory, removeContainers,stopContainers } from './teardown-compose'; +import { readComposeInventory, removeContainers, stopContainers } from './teardown-compose'; import { both, type Item, type Mode, STEPS } from './teardown-model'; import { isProtectedDir, stateItems } from './teardown-state-dir'; @@ -40,7 +40,7 @@ export function recorded(ctx: TeardownContext, kind: string, name?: string) { ); } -export function boxItems(ctx: TeardownContext): Item[] { +function composeItems(ctx: TeardownContext): { items: Item[]; owned: boolean } { const items: Item[] = []; const projectName = composeProjectFor(ctx.box, ctx.stateDir); const project = recorded(ctx, 'compose-project', projectName); @@ -50,53 +50,42 @@ export function boxItems(ctx: TeardownContext): Item[] { const composeGone = project?.removedAt ?? (existsSync(ctx.envFile) ? undefined : 'no .env left'); const composeCmd = `docker ${composeArgs(ctx, []).join(' ')}`; const everything = ctx.mode === 'remove-everything'; - let inventory: ReturnType | undefined; - let inventoryError: Error | undefined; - if (owned) { - try { - inventory = readComposeInventory(ctx); - } catch (error) { - inventoryError = error instanceof Error ? error : new Error('Cannot verify Docker inventory'); - } - } - const proof = () => { - if (inventoryError) throw inventoryError; - if (!inventory) throw new Error('Missing Docker ownership inventory'); - return inventory; - }; + const { inventory, proof } = composeProof(ctx, owned); - items.push({ - id: 'box:stop', - place: 'on the box', - what: `services of compose project ${projectName} stopped (no new VMs or work start)`, - provenance: project ? 'recorded' : 'discovered, not recorded', - how: `${composeCmd} stop`, - step: STEPS.stop, - plan: both( - owned - ? { act: 'remove' } - : { act: 'refused', why: 'no creation record for this installation compose project' } - ), - removedAt: composeGone, - run: () => stopContainers(ctx, proof()), - }); - items.push({ - id: 'box:containers', - place: 'on the box', - what: `containers and network of compose project ${projectName}`, - provenance: project ? 'recorded' : 'discovered, not recorded', - how: 'revalidate exact container ids and configuration scope, remove those ids; remove everything also removes individually proven volume identities', - step: STEPS.box, - plan: both( - owned - ? { act: 'remove' } - : { act: 'refused', why: 'no creation record for this installation compose project' } - ), - removedAt: composeGone, - runKey: 'compose-down', - run: () => removeContainers(ctx, proof(), everything), - record: everything ? { cloud: 'box', kind: 'compose-project', name: projectName } : undefined, - }); + items.push( + { + id: 'box:stop', + place: 'on the box', + what: `services of compose project ${projectName} stopped (no new VMs or work start)`, + provenance: project ? 'recorded' : 'discovered, not recorded', + how: `${composeCmd} stop`, + step: STEPS.stop, + plan: both( + owned + ? { act: 'remove' } + : { act: 'refused', why: 'no creation record for this installation compose project' } + ), + removedAt: composeGone, + run: () => stopContainers(ctx, proof()), + }, + { + id: 'box:containers', + place: 'on the box', + what: `containers of compose project ${projectName}`, + provenance: project ? 'recorded' : 'discovered, not recorded', + how: 'revalidate exact container ids and configuration scope, remove those ids; remove everything also removes individually proven volume identities', + step: STEPS.box, + plan: both( + owned + ? { act: 'remove' } + : { act: 'refused', why: 'no creation record for this installation compose project' } + ), + removedAt: composeGone, + runKey: 'compose-down', + run: () => removeContainers(ctx, proof(), everything), + record: everything ? { cloud: 'box', kind: 'compose-project', name: projectName } : undefined, + } + ); const keepVolumes = { act: 'keep' as const, why: 'keep my data keeps volumes' }; for (const volume of inventory?.volumes.map((v) => v.name) ?? []) { const store = volume.endsWith('objectstore-data'); @@ -105,7 +94,7 @@ export function boxItems(ctx: TeardownContext): Item[] { place: 'on the box', what: `volume ${volume}${store ? ' (the bundled object store: the fleet bucket)' : ''}`, provenance: 'discovered, not recorded', - how: 'docker compose down -v', + how: `revalidate ownership and creation identity, then docker volume rm ${volume}`, step: STEPS.box, plan: { 'keep-data': keepVolumes, @@ -126,7 +115,7 @@ export function boxItems(ctx: TeardownContext): Item[] { place: 'on the box', what: `images compose built for ${projectName} (key agent, egress fence, celld, ...)`, provenance: 'discovered, not recorded', - how: 'docker compose down --rmi local', + how: 'inspect image users and remove only unused image ids manually', step: STEPS.box, plan: { 'keep-data': { act: 'keep', why: 'rebuilt or reused on start' }, @@ -137,6 +126,29 @@ export function boxItems(ctx: TeardownContext): Item[] { }, removedAt: composeGone, }); + return { items, owned }; +} + +function composeProof(ctx: TeardownContext, owned: boolean) { + let inventory: ReturnType | undefined; + let inventoryError: Error | undefined; + if (owned) { + try { + inventory = readComposeInventory(ctx); + } catch (error) { + inventoryError = error instanceof Error ? error : new Error('Cannot verify Docker inventory'); + } + } + const proof = () => { + if (inventoryError) throw inventoryError; + if (!inventory) throw new Error('Missing Docker ownership inventory'); + return inventory; + }; + return { inventory, proof }; +} + +export function boxItems(ctx: TeardownContext): Item[] { + const { items, owned } = composeItems(ctx); if (owned) items.push(...stateItems(ctx), ...backupItems(ctx)); const env = recorded(ctx, 'env-file'); items.push({ @@ -180,7 +192,7 @@ function endpointHost(endpoint: string | undefined): string { } } -function backupItems(ctx: TeardownContext): Item[] { +function backupPaths(ctx: TeardownContext): Map { const paths = new Map(); for (const r of ctx.record) if (r.cloud === 'box' && r.kind === 'backup') paths.set(r.name, r); const defaultDir = join(ctx.selfhostDir, 'backups'); @@ -190,12 +202,29 @@ function backupItems(ctx: TeardownContext): Item[] { if (!paths.has(path) && existsSync(join(path, MANIFEST_NAME))) paths.set(path, undefined); } } + return paths; +} + +function backupPlan(ctx: TeardownContext, path: string, entry?: CreatedResource): Item['plan'] { + if (!existsSync(path)) return both({ act: 'keep', why: 'no longer on disk' }); + if (entry?.action !== 'created' || !isBackupDir(path, ctx)) { + return both({ + act: 'refused', + why: `not proven a backup (needs an absolute path, a version-1 ${MANIFEST_NAME}, and not /, home or the checkout)`, + }); + } + return { + 'keep-data': { act: 'keep', why: 'keep my data keeps backups' }, + 'remove-everything': ctx.options.deleteBackups + ? { act: 'remove' } + : { act: 'keep', why: 'pass --delete-backups to delete backups' }, + }; +} + +function backupItems(ctx: TeardownContext): Item[] { const items: Item[] = []; - for (const [path, entry] of paths) { + for (const [path, entry] of backupPaths(ctx)) { if (entry?.removedAt && !existsSync(path)) continue; - // Proof it is a backup: the manifest runBackup writes. A recorded path without one is refused. - const isBackup = entry?.action === 'created' && isBackupDir(path, ctx); - const gone = !existsSync(path); items.push({ id: `box:backup:${path}`, place: 'on the box', @@ -203,19 +232,7 @@ function backupItems(ctx: TeardownContext): Item[] { provenance: entry ? 'recorded' : 'discovered, not recorded', how: `rm -r ${path}`, step: STEPS.cleanup, - plan: gone - ? both({ act: 'keep', why: 'no longer on disk' }) - : !isBackup - ? both({ - act: 'refused', - why: `not proven a backup (needs an absolute path, a version-1 ${MANIFEST_NAME}, and not /, home or the checkout)`, - }) - : { - 'keep-data': { act: 'keep', why: 'keep my data keeps backups' }, - 'remove-everything': ctx.options.deleteBackups - ? { act: 'remove' } - : { act: 'keep', why: 'pass --delete-backups to delete backups' }, - }, + plan: backupPlan(ctx, path, entry), forGood: 'this backup can never be restored', run: () => rmSync(path, { recursive: true, force: true }), record: { cloud: 'box', kind: 'backup', name: path, createdBy: 'backup' }, diff --git a/scripts/selfhost/teardown-compose.ts b/scripts/selfhost/teardown-compose.ts index 0bb6db0ab9..d3fb2d38fa 100644 --- a/scripts/selfhost/teardown-compose.ts +++ b/scripts/selfhost/teardown-compose.ts @@ -35,7 +35,8 @@ function result(ctx: TeardownContext, args: string[]): string { function parse(text: string): Record { try { const value: unknown = JSON.parse(text); - if (!value || typeof value !== 'object' || Array.isArray(value)) throw new Error(); + if (!value || typeof value !== 'object' || Array.isArray(value)) + throw new Error('Invalid ownership metadata shape'); return value as Record; } catch { throw new Error('Unreadable Docker ownership metadata'); @@ -143,10 +144,9 @@ export function readComposeInventory(ctx: TeardownContext): ComposeInventory { }); if (new Set(volumes.map((v) => v.name)).size !== volumes.length) throw new Error('Refused: duplicate Docker volume inventory'); - return { - containers: containers.sort((a, b) => a.id.localeCompare(b.id)), - volumes: volumes.sort((a, b) => a.name.localeCompare(b.name)), - }; + containers.sort((a, b) => a.id.localeCompare(b.id)); + volumes.sort((a, b) => a.name.localeCompare(b.name)); + return { containers, volumes }; } export function assertComposeInventory(ctx: TeardownContext, expected: ComposeInventory): void { if (JSON.stringify(readComposeInventory(ctx)) !== JSON.stringify(expected)) diff --git a/scripts/selfhost/teardown-gcp-bootstrap.ts b/scripts/selfhost/teardown-gcp-bootstrap.ts index 3e827dd8b1..450b523a2e 100644 --- a/scripts/selfhost/teardown-gcp-bootstrap.ts +++ b/scripts/selfhost/teardown-gcp-bootstrap.ts @@ -1,4 +1,5 @@ /** WIF cleanup uses only creation receipts. Existing resources are never adopted by name. */ +import type { CreatedResource } from '../../deploy/selfhost/created-resources.mjs'; import { check } from './backup-lib'; import type { TeardownContext } from './teardown-box'; import { type Item, STEPS } from './teardown-model'; @@ -70,97 +71,16 @@ export function bootstrapItems(ctx: TeardownContext, project: string): Item[] { }, run: () => { if (!owned) throw new Error('refused: missing creation ownership'); - const where = [`--project=${project}`]; const pool = attrs.pool; - let describe: string[]; - let remove: string[]; - let expected: Record; - switch (entry.kind) { - case 'workload-identity-pool': - describe = [ - 'iam', - 'workload-identity-pools', - 'describe', - entry.name, - ...where, - '--location=global', - ]; - remove = [ - 'iam', - 'workload-identity-pools', - 'delete', - entry.name, - ...where, - '--location=global', - '--quiet', - ]; - expected = { - name: attrs.identity, - description: `Dedicated to the SAM install whose token issuer is ${issuer}`, - }; - break; - case 'workload-identity-provider': - if (!pool) throw new Error('refused: missing recorded pool'); - describe = [ - 'iam', - 'workload-identity-pools', - 'providers', - 'describe', - entry.name, - ...where, - '--location=global', - `--workload-identity-pool=${pool}`, - ]; - remove = [ - 'iam', - 'workload-identity-pools', - 'providers', - 'delete', - entry.name, - ...where, - '--location=global', - `--workload-identity-pool=${pool}`, - '--quiet', - ]; - expected = { name: attrs.identity }; - break; - case 'service-account': - describe = ['iam', 'service-accounts', 'describe', entry.name, ...where]; - remove = ['iam', 'service-accounts', 'delete', entry.name, ...where, '--quiet']; - expected = { - uniqueId: attrs.identity, - description: `Creates and deletes SAM workspace VMs and their firewall rules for ${issuer}`, - }; - break; - case 'iam-binding': { - // Delete an exact grant only, never a project policy replacement. Creation receipt - // is linked to the service account's immutable id, checked immediately beforehand. - if (!attrs.member || !attrs.role || !attrs.account || !attrs.identity) - throw new Error('refused: incomplete grant receipt'); - describe = ['iam', 'service-accounts', 'describe', attrs.account, ...where]; - remove = [ - 'projects', - 'remove-iam-policy-binding', - project, - `--member=${attrs.member}`, - `--role=${attrs.role}`, - '--condition=None', - '--quiet', - '--format=none', - ]; - expected = { uniqueId: attrs.identity }; - break; - } - default: - throw new Error(`refused: unsupported recorded resource kind ${entry.kind}`); - } + const { describe, remove, expected } = bootstrapOperation(entry, project, issuer); const result = gcloud(ctx, [...describe, '--format=json']); if (result.status !== 0 && gcloudNotFound(result.stderr)) return; check(result, 'read recorded resource before deletion'); let current: Record; try { const parsed: unknown = JSON.parse(result.stdout); - if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) throw new Error(); + if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) + throw new Error('Invalid ownership metadata shape'); current = parsed as Record; } catch { throw new Error('refused: unreadable ownership metadata'); @@ -172,86 +92,201 @@ export function bootstrapItems(ctx: TeardownContext, project: string): Item[] { (current.oidc as { issuerUri?: string } | undefined)?.issuerUri !== issuer ) throw new Error('refused: provider issuer changed'); - if (entry.kind === 'workload-identity-pool') { - const providers = gcloud(ctx, [ - 'iam', - 'workload-identity-pools', - 'providers', - 'list', - ...where, - '--location=global', - `--workload-identity-pool=${entry.name}`, - '--show-deleted', - '--format=json', - ]); - check(providers, 'check pool providers before deletion'); - const parsed: unknown = JSON.parse(providers.stdout); - const known = ctx.record - .filter( - (r) => - r.cloud === 'gcp' && - r.kind === 'workload-identity-provider' && - r.action === 'created' && - r.attributes?.project === project && - r.attributes?.installation === ctx.installationId && - r.attributes?.environment === 'selfhost' && - r.attributes?.install === issuer - ) - .map((r) => r.attributes?.identity); - if ( - !Array.isArray(parsed) || - parsed.some((p) => !p || !known.includes(p.name) || p.oidc?.issuerUri !== issuer) - ) - throw new Error('refused: pool contains unowned or unreadable providers'); - } - if (entry.kind === 'service-account' || entry.kind === 'iam-binding') { - const account = entry.kind === 'service-account' ? entry.name : attrs.account; - const policy = gcloud(ctx, [ - 'iam', - 'service-accounts', - 'get-iam-policy', - account, - ...where, - '--format=json', - ]); - check(policy, 'check account grants before deletion'); - const parsed: unknown = JSON.parse(policy.stdout); - if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) - throw new Error('refused: unreadable account grants'); - const bindings = (parsed as { bindings?: unknown }).bindings ?? []; - const projectNumber = ctx.record - .find((r) => r.kind === 'workload-identity-pool' && r.attributes?.pool === pool) - ?.attributes?.identity?.split('/')[1]; - const member = `principalSet://iam.googleapis.com/projects/${projectNumber}/locations/global/workloadIdentityPools/${pool}/*`; - if ( - !Array.isArray(bindings) || - bindings.some( - (b) => - b.condition || - b.role !== 'roles/iam.workloadIdentityUser' || - !Array.isArray(b.members) || - b.members.some((m: unknown) => m !== member) - ) - ) - throw new Error('refused: account has foreign grants'); - const keys = gcloud(ctx, [ - 'iam', - 'service-accounts', - 'keys', - 'list', - `--iam-account=${account}`, - ...where, - '--managed-by=user', - '--format=json', - ]); - check(keys, 'check account keys before deletion'); - const parsedKeys: unknown = JSON.parse(keys.stdout); - if (!Array.isArray(parsedKeys) || parsedKeys.length) - throw new Error('refused: account has user-managed keys'); - } + if (entry.kind === 'workload-identity-pool') + assertPoolProviders(ctx, project, entry.name, issuer); + if (entry.kind === 'service-account' || entry.kind === 'iam-binding') + assertAccountExclusive( + ctx, + project, + pool, + entry.kind === 'service-account' ? entry.name : attrs.account + ); check(gcloud(ctx, remove), 'delete recorded resource'); }, record: entry, } satisfies Item; }); } + +function assertPoolProviders( + ctx: TeardownContext, + project: string, + poolName: string, + issuer: string +): void { + const where = [`--project=${project}`]; + const providers = gcloud(ctx, [ + 'iam', + 'workload-identity-pools', + 'providers', + 'list', + ...where, + '--location=global', + `--workload-identity-pool=${poolName}`, + '--show-deleted', + '--format=json', + ]); + check(providers, 'check pool providers before deletion'); + const parsed: unknown = JSON.parse(providers.stdout); + const known = new Set( + ctx.record + .filter( + (r) => + r.cloud === 'gcp' && + r.kind === 'workload-identity-provider' && + r.action === 'created' && + r.attributes?.project === project && + r.attributes?.installation === ctx.installationId && + r.attributes?.environment === 'selfhost' && + r.attributes?.install === issuer + ) + .map((r) => r.attributes?.identity) + .filter((name): name is string => typeof name === 'string' && !!name) + ); + if ( + !Array.isArray(parsed) || + parsed.some( + (p) => !p || typeof p.name !== 'string' || !known.has(p.name) || p.oidc?.issuerUri !== issuer + ) + ) + throw new Error('refused: pool contains unowned or unreadable providers'); +} +function assertAccountExclusive( + ctx: TeardownContext, + project: string, + pool: string | undefined, + account: string +): void { + const where = [`--project=${project}`]; + const policy = gcloud(ctx, [ + 'iam', + 'service-accounts', + 'get-iam-policy', + account, + ...where, + '--format=json', + ]); + check(policy, 'check account grants before deletion'); + const parsed: unknown = JSON.parse(policy.stdout); + if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) + throw new Error('refused: unreadable account grants'); + const bindings = (parsed as { bindings?: unknown }).bindings ?? []; + const projectNumber = ctx.record + .find((r) => r.kind === 'workload-identity-pool' && r.attributes?.pool === pool) + ?.attributes?.identity?.split('/')[1]; + const member = `principalSet://iam.googleapis.com/projects/${projectNumber}/locations/global/workloadIdentityPools/${pool}/*`; + if ( + !Array.isArray(bindings) || + bindings.some( + (b) => + b.condition || + b.role !== 'roles/iam.workloadIdentityUser' || + !Array.isArray(b.members) || + b.members.some((m: unknown) => m !== member) + ) + ) + throw new Error('refused: account has foreign grants'); + const keys = gcloud(ctx, [ + 'iam', + 'service-accounts', + 'keys', + 'list', + `--iam-account=${account}`, + ...where, + '--managed-by=user', + '--format=json', + ]); + check(keys, 'check account keys before deletion'); + const parsedKeys: unknown = JSON.parse(keys.stdout); + if (!Array.isArray(parsedKeys) || parsedKeys.length) + throw new Error('refused: account has user-managed keys'); +} + +function bootstrapOperation(entry: CreatedResource, project: string, issuer: string) { + const attrs = entry.attributes ?? {}; + const pool = attrs.pool; + const where = [`--project=${project}`]; + let describe: string[]; + let remove: string[]; + let expected: Record; + switch (entry.kind) { + case 'workload-identity-pool': + describe = [ + 'iam', + 'workload-identity-pools', + 'describe', + entry.name, + ...where, + '--location=global', + ]; + remove = [ + 'iam', + 'workload-identity-pools', + 'delete', + entry.name, + ...where, + '--location=global', + '--quiet', + ]; + expected = { + name: attrs.identity, + description: `Dedicated to the SAM install whose token issuer is ${issuer}`, + }; + break; + case 'workload-identity-provider': + if (!pool) throw new Error('refused: missing recorded pool'); + describe = [ + 'iam', + 'workload-identity-pools', + 'providers', + 'describe', + entry.name, + ...where, + '--location=global', + `--workload-identity-pool=${pool}`, + ]; + remove = [ + 'iam', + 'workload-identity-pools', + 'providers', + 'delete', + entry.name, + ...where, + '--location=global', + `--workload-identity-pool=${pool}`, + '--quiet', + ]; + expected = { name: attrs.identity }; + break; + case 'service-account': + describe = ['iam', 'service-accounts', 'describe', entry.name, ...where]; + remove = ['iam', 'service-accounts', 'delete', entry.name, ...where, '--quiet']; + expected = { + uniqueId: attrs.identity, + description: `Creates and deletes SAM workspace VMs and their firewall rules for ${issuer}`, + }; + break; + case 'iam-binding': { + // Delete an exact grant only, never a project policy replacement. Creation receipt + // is linked to the service account's immutable id, checked immediately beforehand. + if (!attrs.member || !attrs.role || !attrs.account || !attrs.identity) + throw new Error('refused: incomplete grant receipt'); + describe = ['iam', 'service-accounts', 'describe', attrs.account, ...where]; + remove = [ + 'projects', + 'remove-iam-policy-binding', + project, + `--member=${attrs.member}`, + `--role=${attrs.role}`, + '--condition=None', + '--quiet', + '--format=none', + ]; + expected = { uniqueId: attrs.identity }; + break; + } + default: + throw new Error(`refused: unsupported recorded resource kind ${entry.kind}`); + } + return { describe, remove, expected }; +} diff --git a/scripts/selfhost/teardown-gcp.ts b/scripts/selfhost/teardown-gcp.ts index 08689b6967..eac2d4f118 100644 --- a/scripts/selfhost/teardown-gcp.ts +++ b/scripts/selfhost/teardown-gcp.ts @@ -80,9 +80,11 @@ export function gcpItems(ctx: TeardownContext): Item[] { throw new Error(`invalid Google Cloud project id: ${project}`); } const listed = listInstances(ctx, project); - items.push(...instanceItems(ctx, project, listed)); - items.push(...firewallItems(ctx, project, listed)); - items.push(...bootstrapItems(ctx, project)); + items.push( + ...instanceItems(ctx, project, listed), + ...firewallItems(ctx, project, listed), + ...bootstrapItems(ctx, project) + ); } return items; } @@ -130,7 +132,7 @@ function parseInstance(value: unknown): GcpInstance { typeof v?.name !== 'string' || typeof v.zone !== 'string' || typeof v.id !== 'string' || - !/^[0-9]+$/.test(v.id) + !/^\d+$/.test(v.id) ) { throw new Error('instance without name, zone or id'); } @@ -232,10 +234,13 @@ function instanceItems( const refusal = ownershipRefusal(instance, ctx.installationId); const path = `projects/${project}/zones/${instance.zone}/instances/${instance.name}`; const keptDisks = instance.disks.filter((d) => !d.autoDelete); + const diskDescription = keptDisks.length + ? ` (${keptDisks.length} disk(s) without auto-delete are retained)` + : ', boot disk with it'; return { id: `gcp:${path}`, place: 'in your cloud, made by SAM at runtime', - what: `node VM ${instance.name} (${project}, ${instance.zone}, node ${instance.labels[SAM_NODE_LABEL_KEY] ?? '?'})${keptDisks.length ? ` (${keptDisks.length} disk(s) without auto-delete are retained)` : ', boot disk with it'}`, + what: `node VM ${instance.name} (${project}, ${instance.zone}, node ${instance.labels[SAM_NODE_LABEL_KEY] ?? '?'})${diskDescription}`, provenance: 'discovered, not recorded', how: `gcloud compute instances delete ${instance.name} --zone=${instance.zone} --project=${project}, after checking its id and labels again`, step: STEPS.compute, @@ -386,7 +391,8 @@ function firewallItems( let raw: Record; try { const parsed: unknown = JSON.parse(current.stdout); - if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) throw new Error(); + if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) + throw new Error('Invalid ownership metadata shape'); raw = parsed as Record; } catch { throw new Error('Refused: unreadable firewall identity'); diff --git a/scripts/selfhost/teardown-model.ts b/scripts/selfhost/teardown-model.ts index 095a2db6fe..11970abab3 100644 --- a/scripts/selfhost/teardown-model.ts +++ b/scripts/selfhost/teardown-model.ts @@ -112,54 +112,60 @@ export function decide(item: Item, mode: Mode): Decision { */ export function execute(items: Item[], mode: Mode, recordFile: string): Outcome[] { const outcomes: Outcome[] = []; - const ordered = [...items].sort((a, b) => a.step - b.step); + const ordered = [...items]; + ordered.sort((a, b) => a.step - b.step); let failedStep: number | null = null; const ran = new Map(); - for (const step of [...new Set(ordered.map((i) => i.step))]) { - const inStep = ordered.filter((i) => i.step === step); - for (const item of inStep) { - const decision = decide(item, mode); - if (decision.act !== 'remove') { - outcomes.push({ item, status: statusOf(decision), why: decision.why }); - continue; - } - if (item.removedAt) { - outcomes.push({ item, status: 'already removed', why: item.removedAt }); - continue; - } - if (failedStep !== null) { - outcomes.push({ item, status: 'not attempted', why: `step ${failedStep} failed` }); - continue; - } - const key = item.runKey ?? item.id; - if (!ran.has(key)) { - // The group's action may sit on another item of the group (a volume goes with compose down). - const runner = item.run ?? items.find((i) => (i.runKey ?? i.id) === key && i.run)?.run; - try { - runner?.(); - ran.set(key, null); - } catch (error) { - ran.set(key, error instanceof Error ? error : new Error(String(error))); - } - } - const error = ran.get(key); - if (error && !item.goneDespiteGroupFailure?.()) { - outcomes.push({ item, status: 'failed', why: error.message }); - continue; - } - const settled = item.settle?.() ?? { removed: true }; - if (!settled.removed) { - outcomes.push({ item, status: 'kept', why: settled.why }); - continue; - } - for (const ref of [item.record ?? []].flat()) markInRecord(recordFile, ref); - outcomes.push({ item, status: 'removed' }); + for (const step of new Set(ordered.map((i) => i.step))) { + for (const item of ordered.filter((i) => i.step === step)) { + outcomes.push(executeItem(item, items, mode, recordFile, failedStep, ran)); } if (outcomes.some((o) => o.status === 'failed' && o.item.step === step)) failedStep = step; } return outcomes; } +function runAction( + item: Item, + items: Item[], + ran: Map +): Error | null | undefined { + const key = item.runKey ?? item.id; + if (!ran.has(key)) { + // A group's runner may live on another item (a volume shares its container cleanup). + const runner = item.run ?? items.find((i) => (i.runKey ?? i.id) === key && i.run)?.run; + try { + runner?.(); + ran.set(key, null); + } catch (error) { + ran.set(key, error instanceof Error ? error : new Error(String(error))); + } + } + return ran.get(key); +} + +function executeItem( + item: Item, + items: Item[], + mode: Mode, + recordFile: string, + failedStep: number | null, + ran: Map +): Outcome { + const decision = decide(item, mode); + if (decision.act !== 'remove') return { item, status: statusOf(decision), why: decision.why }; + if (item.removedAt) return { item, status: 'already removed', why: item.removedAt }; + if (failedStep !== null) + return { item, status: 'not attempted', why: `step ${failedStep} failed` }; + const error = runAction(item, items, ran); + if (error && !item.goneDespiteGroupFailure?.()) + return { item, status: 'failed', why: error.message }; + const settled = item.settle?.() ?? { removed: true }; + if (!settled.removed) return { item, status: 'kept', why: settled.why }; + for (const ref of [item.record ?? []].flat()) markInRecord(recordFile, ref); + return { item, status: 'removed' }; +} + function statusOf(decision: Exclude): Outcome['status'] { return decision.act === 'keep' ? 'kept' : decision.act; } @@ -190,9 +196,9 @@ export function renderInventory(items: Item[]): string { lines.push('', capitalise(place)); for (const item of here) { const gone = item.removedAt ? ` (removed ${item.removedAt})` : ''; - lines.push(` - ${item.what} [${item.provenance}]${gone}`); - lines.push(` how: ${item.how}`); lines.push( + ` - ${item.what} [${item.provenance}]${gone}`, + ` how: ${item.how}`, ` keep my data: ${describe(item.plan['keep-data'])}; remove everything: ${describe(item.plan['remove-everything'])}` ); if (item.forGood) lines.push(` destroys for good: ${item.forGood}`); @@ -237,23 +243,29 @@ export function renderSummary(outcomes: Outcome[]): string { const hits = outcomes.filter((o) => statuses.includes(o.status)); if (hits.length === 0) continue; lines.push(`${title}:`); - for (const { item, status, why } of hits) { - const extra = status === 'operator' ? `\n ${item.how}` : ''; - lines.push( - ` - ${item.what}${why ? ` (${status === 'already removed' ? 'earlier, ' : ''}${why})` : ''}${extra}` - ); - } + for (const outcome of hits) lines.push(renderOutcome(outcome)); } lines.push( '', - notRemoved.length === 0 - ? 'Teardown removed everything it lists.' - : `Not removed: the ${notRemoved.length} item${notRemoved.length === 1 ? '' : 's'} above under Left by choice, Left for you, Refused, Failed and Not attempted; each says how to remove it.`, + removalSummary(notRemoved.length), 'Teardown knows only what .state/created-resources.json records and resources with live exact SAM ownership labels. Anything else you made by hand for this install (another bucket, for example one for backups) is not listed: remove it yourself.' ); return lines.join('\n'); } +function renderOutcome({ item, status, why }: Outcome): string { + const extra = status === 'operator' ? `\n ${item.how}` : ''; + const earlier = status === 'already removed' ? 'earlier, ' : ''; + const reason = why ? ` (${earlier}${why})` : ''; + return ` - ${item.what}${reason}${extra}`; +} + +function removalSummary(count: number): string { + if (count === 0) return 'Teardown removed everything it lists.'; + const plural = count === 1 ? '' : 's'; + return `Not removed: the ${count} item${plural} above under Left by choice, Left for you, Refused, Failed and Not attempted; each says how to remove it.`; +} + function describe(decision: Decision): string { switch (decision.act) { case 'remove': diff --git a/scripts/selfhost/teardown-state-dir.ts b/scripts/selfhost/teardown-state-dir.ts index 9305c5c451..436a0cb9b9 100644 --- a/scripts/selfhost/teardown-state-dir.ts +++ b/scripts/selfhost/teardown-state-dir.ts @@ -75,37 +75,39 @@ export function stateItems(ctx: TeardownContext): Item[] { }); } const state = ctx.record.find((r) => r.cloud === 'box' && r.kind === 'state-dir'); - items.push({ - id: 'box:state', - place: 'on the box', - what: `${ctx.stateDir} (sealed bundles, generated config, deploy project, celld binary, caches, secrets.env)`, - provenance: state ? 'recorded' : 'discovered, not recorded', - how: `rm -r everything in ${ctx.stateDir} except ${RECORD_FILE} and a key that is kept`, - step: STEPS.state, - plan: { - 'keep-data': { act: 'keep', why: 'keep my data keeps the bundles and state' }, - 'remove-everything': { act: 'remove' }, + items.push( + { + id: 'box:state', + place: 'on the box', + what: `${ctx.stateDir} (sealed bundles, generated config, deploy project, celld binary, caches, secrets.env)`, + provenance: state ? 'recorded' : 'discovered, not recorded', + how: `rm -r everything in ${ctx.stateDir} except ${RECORD_FILE} and a key that is kept`, + step: STEPS.state, + plan: { + 'keep-data': { act: 'keep', why: 'keep my data keeps the bundles and state' }, + 'remove-everything': { act: 'remove' }, + }, + removedAt: state?.removedAt, + runKey: 'state', + run: () => clearState(ctx, keepKey), + record: [ + { cloud: 'box', kind: 'state-dir', name: ctx.stateDir, createdBy: 'deploy' }, + // The install itself is gone with its state; the id stays readable for a resumed run. + ...ctx.record + .filter((r) => r.cloud === 'box' && r.kind === 'installation') + .map((r) => ({ cloud: 'box', kind: 'installation', name: r.name })), + ], }, - removedAt: state?.removedAt, - runKey: 'state', - run: () => clearState(ctx, keepKey), - record: [ - { cloud: 'box', kind: 'state-dir', name: ctx.stateDir, createdBy: 'deploy' }, - // The install itself is gone with its state; the id stays readable for a resumed run. - ...ctx.record - .filter((r) => r.cloud === 'box' && r.kind === 'installation') - .map((r) => ({ cloud: 'box', kind: 'installation', name: r.name })), - ], - }); - items.push({ - id: 'box:record', - place: 'on the box', - what: `${ctx.recordFile} (this record: teardown's receipt)`, - provenance: 'recorded', - how: `rm ${ctx.recordFile} by hand once you no longer need it`, - step: STEPS.state, - plan: both({ act: 'keep', why: 'the receipt a second run resumes from' }), - }); + { + id: 'box:record', + place: 'on the box', + what: `${ctx.recordFile} (this record: teardown's receipt)`, + provenance: 'recorded', + how: `rm ${ctx.recordFile} by hand once you no longer need it`, + step: STEPS.state, + plan: both({ act: 'keep', why: 'the receipt a second run resumes from' }), + } + ); return items; } @@ -268,7 +270,8 @@ function assertStateDir(ctx: TeardownContext): void { let identity: unknown; try { const parsed: unknown = JSON.parse(readFileSync(keys, 'utf8')); - if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) throw new Error(); + if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) + throw new Error('Invalid ownership metadata shape'); identity = (parsed as { SAM_INSTALLATION_ID?: unknown }).SAM_INSTALLATION_ID; } catch { throw new Error('Refused: unreadable installation identity'); diff --git a/scripts/selfhost/teardown.ts b/scripts/selfhost/teardown.ts index d4b019975e..87a10f3513 100644 --- a/scripts/selfhost/teardown.ts +++ b/scripts/selfhost/teardown.ts @@ -6,7 +6,7 @@ * stop and delete owned node VMs; keep workload identity, bucket, backups, key file, * bundles, .env and state, so `docker compose up -d` and the bootstrap bring it back * pnpm selfhost:teardown --remove-everything [--dry-run] --confirm - * also the bucket contents, compose volumes and images, .state and .env + * also proven-owned compose volumes, .state and .env; external stores/images stay manual * --delete-backups also delete local backups (never without this flag) * --destroy-key also delete the key file / schedule the cloud KMS key's destruction * --gcp-project a Google Cloud project nodes ran in (default: GCP_PROJECT in .env, plus @@ -60,11 +60,9 @@ function parse() { if (values['keep-data'] && values['remove-everything']) { throw new Error('choose one of --keep-data and --remove-everything'); } - const mode: Mode | undefined = values['keep-data'] - ? 'keep-data' - : values['remove-everything'] - ? 'remove-everything' - : undefined; + let mode: Mode | undefined; + if (values['keep-data']) mode = 'keep-data'; + else if (values['remove-everything']) mode = 'remove-everything'; if ((values['delete-backups'] || values['destroy-key']) && mode !== 'remove-everything') { throw new Error('--delete-backups and --destroy-key go with --remove-everything only'); } @@ -151,6 +149,12 @@ async function confirm(expected: string, given: string | undefined): Promise { assertOperatorExecution(); const { values, mode } = parse(); @@ -207,11 +211,7 @@ async function main(): Promise { installationId, selfhostDir: SELFHOST_DIR, }; - const idSource = recordedId - ? 'recorded' - : installationId - ? 'discovered, not recorded: platform-keys.json' - : 'unknown'; + const idSource = installationSource(recordedId, installationId); log( `install ${domain || '(domain unknown)'}, installation ${installationId ?? '?'} (${idSource})` ); @@ -257,10 +257,9 @@ async function main(): Promise { return outcomes.some((o) => ['failed', 'refused', 'not attempted'].includes(o.status)) ? 1 : 0; } -main().then( - (code) => process.exit(code), - (error: unknown) => { - console.error(`[selfhost] ${error instanceof Error ? error.message : String(error)}`); - process.exit(1); - } -); +try { + process.exit(await main()); +} catch (error: unknown) { + console.error(`[selfhost] ${error instanceof Error ? error.message : String(error)}`); + process.exit(1); +} diff --git a/scripts/selfhost/upgrade-compose.ts b/scripts/selfhost/upgrade-compose.ts index 633c032752..cc727944fd 100644 --- a/scripts/selfhost/upgrade-compose.ts +++ b/scripts/selfhost/upgrade-compose.ts @@ -30,7 +30,7 @@ export function composeOverlays( fileAt: (ref: string, path: string) => string | null ): ComposeOverlay[] { return composeFiles - .map((file) => ({ file, rel: relative(REPO_ROOT, resolve(file)).split(/[\\/]/).join('/') })) + .map((file) => ({ file, rel: relative(REPO_ROOT, resolve(file)).replaceAll('\\', '/') })) .filter(({ rel }) => rel !== COMPOSE_PATH) .map(({ file, rel }) => { const inRepo = !rel.startsWith('../') && !isAbsolute(rel); diff --git a/scripts/selfhost/upgrade-lib.ts b/scripts/selfhost/upgrade-lib.ts index 861023d7c0..a3c5833149 100644 --- a/scripts/selfhost/upgrade-lib.ts +++ b/scripts/selfhost/upgrade-lib.ts @@ -6,12 +6,13 @@ */ import { spawnSync } from 'node:child_process'; import { existsSync, mkdirSync, readFileSync, rmSync } from 'node:fs'; -import { dirname, isAbsolute, join, resolve } from 'node:path'; +import { dirname, join, resolve } from 'node:path'; import { assertRollbackCacheReady, type BoxContext as BackupContext, composeArgs, + composeRunEnv, runBackup, runRollback, } from './backup-lib.js'; @@ -30,7 +31,7 @@ import { } from './upgrade-migrations.js'; export { composeInputsChanged, composeOverlays } from './upgrade-compose.js'; -import { assertRollbackReady } from './upgrade-preflight.js'; +import { assertRollbackReady, pendingBackupDirectory } from './upgrade-preflight.js'; const MIGRATIONS_DIR = 'apps/api/src/db/migrations/'; /** In the state dir while an upgrade has not finished: `{ "from": "" }`. */ @@ -332,6 +333,62 @@ async function applyUpgrade( return composeRestarted; } +/** Resume from the original snapshot, never from a new snapshot of partially migrated data. */ +async function recoverPendingUpgrade( + ctx: BoxContext, + opts: UpgradeOptions, + from: string, + rebuilds: string[] +): Promise { + const pendingPath = join(ctx.stateDir, UPGRADE_PENDING_FILE); + const pending: unknown = JSON.parse(readFileSync(pendingPath, 'utf8')); + const backupDir = pendingBackupDirectory(pending); + try { + await recoverUpgrade(ctx, from, backupDir, rebuilds, opts); + } catch { + stopCelldAfterFailure(ctx); + throw new Error( + 'unfinished upgrade recovery failed; keep celld stopped and retry using the recorded encrypted snapshot' + ); + } + rmSync(pendingPath, { force: true }); +} + +function stopCelldAfterFailure(ctx: BoxContext): void { + const env = composeRunEnv(ctx); + try { + ctx.run('docker', composeArgs(ctx, ['stop', 'celld']), env); + } catch { + /* best effort */ + } +} + +async function rollbackFailedUpgrade( + ctx: BoxContext, + opts: UpgradeOptions, + git: Git, + from: string, + backupDir: string, + progress: UpgradeProgress +): Promise { + ctx.log('upgrade failed; automatically restoring the previous version'); + try { + if (progress.deploymentStarted) { + await recoverUpgrade(ctx, from, backupDir, progress.imagesRebuilt, opts); + } else { + git(['checkout', '--detach', from]); + check(ctx.run('pnpm', ['install', '--frozen-lockfile']), 'restore previous dependencies'); + } + rmSync(join(ctx.stateDir, UPGRADE_PENDING_FILE), { force: true }); + ctx.log('automatic rollback completed'); + } catch { + if (progress.deploymentStarted) stopCelldAfterFailure(ctx); + throw new Error( + 'upgrade failed and automatic rollback did not complete; keep celld stopped and retry using the recorded encrypted snapshot' + ); + } +} + export async function runUpgrade(ctx: BoxContext, opts: UpgradeOptions): Promise { assertOperatorExecution(); assertRollbackReady(ctx); @@ -399,33 +456,7 @@ export async function runUpgrade(ctx: BoxContext, opts: UpgradeOptions): Promise 'automatic rollback requires a fresh backup; --skip-backup is no longer supported' ); if (pendingFrom !== null) { - const pending: unknown = JSON.parse( - readFileSync(join(ctx.stateDir, UPGRADE_PENDING_FILE), 'utf8') - ); - if ( - typeof pending !== 'object' || - pending === null || - !('backupDir' in pending) || - typeof pending.backupDir !== 'string' || - !isAbsolute(pending.backupDir) - ) { - throw new Error( - 'unfinished upgrade has no recorded encrypted snapshot; recover the original installation before retrying' - ); - } - try { - await recoverUpgrade(ctx, pendingFrom, pending.backupDir, rebuilds, opts); - } catch { - try { - ctx.run('docker', composeArgs(ctx, ['stop', 'celld'])); - } catch { - /* best effort */ - } - throw new Error( - 'unfinished upgrade recovery failed; keep celld stopped and retry using the recorded encrypted snapshot' - ); - } - rmSync(join(ctx.stateDir, UPGRADE_PENDING_FILE), { force: true }); + await recoverPendingUpgrade(ctx, opts, pendingFrom, rebuilds); return runUpgrade(ctx, opts); } assertRollbackCacheReady(backupContext(ctx)); @@ -453,30 +484,10 @@ export async function runUpgrade(ctx: BoxContext, opts: UpgradeOptions): Promise progress ); } catch (error) { - ctx.log('upgrade failed; automatically restoring the previous version'); - try { - if (progress.deploymentStarted) { - await recoverUpgrade(ctx, from, backupDir, progress.imagesRebuilt, opts); - } else { - git(['checkout', '--detach', from]); - check(ctx.run('pnpm', ['install', '--frozen-lockfile']), 'restore previous dependencies'); - } - rmSync(pendingPath, { force: true }); - ctx.log('automatic rollback completed'); - } catch { - if (progress.deploymentStarted) { - try { - ctx.run('docker', composeArgs(ctx, ['stop', 'celld'])); - } catch { - /* best effort */ - } - } - throw new Error( - 'upgrade failed and automatic rollback did not complete; keep celld stopped and retry using the recorded encrypted snapshot' - ); - } + await rollbackFailedUpgrade(ctx, opts, git, from, backupDir, progress); throw error; } + rmSync(pendingPath, { force: true }); const { imagesRebuilt } = progress; diff --git a/scripts/selfhost/upgrade-preflight.ts b/scripts/selfhost/upgrade-preflight.ts index a287b676f6..178dd5e5fd 100644 --- a/scripts/selfhost/upgrade-preflight.ts +++ b/scripts/selfhost/upgrade-preflight.ts @@ -1,3 +1,5 @@ +import { isAbsolute } from 'node:path'; + /** Refuse upgrades whose installation cannot safely remove its cache during rollback. */ import type { BoxContext } from './backup-lib.js'; import { @@ -33,3 +35,19 @@ export function assertRollbackReady(ctx: Pick): ); } } + +/** A pending record without its original snapshot cannot safely authorize another deployment. */ +export function pendingBackupDirectory(pending: unknown): string { + if ( + typeof pending !== 'object' || + pending === null || + !('backupDir' in pending) || + typeof pending.backupDir !== 'string' || + !isAbsolute(pending.backupDir) + ) { + throw new Error( + 'unfinished upgrade has no recorded encrypted snapshot; recover the original installation before retrying' + ); + } + return pending.backupDir; +} diff --git a/scripts/selfhost/upgrade-safeguards.test.ts b/scripts/selfhost/upgrade-safeguards.test.ts index cd8c9fef45..672953ae9a 100644 --- a/scripts/selfhost/upgrade-safeguards.test.ts +++ b/scripts/selfhost/upgrade-safeguards.test.ts @@ -13,7 +13,10 @@ vi.mock('./backup-lib', async (importOriginal) => ({ runRollback: vi.fn(), })); -vi.mock('./upgrade-preflight.js', () => ({ assertRollbackReady: vi.fn() })); +vi.mock('./upgrade-preflight.js', async (original) => ({ + ...(await original()), + assertRollbackReady: vi.fn(), +})); const FROM = 'a'.repeat(40); const TO = 'b'.repeat(40); @@ -32,8 +35,11 @@ let failCommand: string | undefined; let generatedChange: boolean; let cacheProject: string; let invalidCacheMount: boolean; +let failureStopStateDirs: (string | undefined)[]; -function run(command: string, args: string[]): RunResult { +function run(command: string, args: string[], env?: NodeJS.ProcessEnv): RunResult { + if (command === 'docker' && args.slice(-2).join(' ') === 'stop celld') + failureStopStateDirs.push(env?.SAM_SELFHOST_STATE_DIR); const ok = (stdout = '') => ({ status: 0, stdout, stderr: '' }); const commandArgs = command === 'pnpm' && args[0] === 'selfhost:deploy' @@ -138,6 +144,7 @@ beforeEach(() => { generatedChange = false; cacheProject = ''; invalidCacheMount = false; + failureStopStateDirs = []; vi.mocked(runBackup) .mockReset() .mockImplementation(() => { @@ -273,6 +280,8 @@ describe('runUpgrade', () => { await expect(upgrade()).rejects.toThrow(/automatic rollback did not complete/); expect(steps).not.toContain(`git checkout --detach ${FROM}`); expect(logs.join('\n')).not.toContain('secret-value'); + // --state-dir differs from Compose's default; failed recovery must still stop this box. + expect(failureStopStateDirs).toEqual([join(root, 'state')]); }); it('fails recovery if the restored installation is unhealthy', async () => { diff --git a/scripts/selfhost/upgrade.test.ts b/scripts/selfhost/upgrade.test.ts index 6ae9a26e2b..d5916f7655 100644 --- a/scripts/selfhost/upgrade.test.ts +++ b/scripts/selfhost/upgrade.test.ts @@ -35,7 +35,10 @@ vi.mock('./upgrade-migrations.js', async (original) => ({ installedMigrations: vi.fn(() => [{ tag: 'v1', new_sqlite_classes: ['ProjectData'] }]), })); -vi.mock('./upgrade-preflight.js', () => ({ assertRollbackReady: vi.fn() })); +vi.mock('./upgrade-preflight.js', async (original) => ({ + ...(await original()), + assertRollbackReady: vi.fn(), +})); const FROM = 'a'.repeat(40); const TO = 'b'.repeat(40); diff --git a/tasks/active/2026-11-19-l24-selfhost-operations.md b/tasks/active/2026-11-19-l24-selfhost-operations.md index 43c8392e6c..ec4e0d74ad 100644 --- a/tasks/active/2026-11-19-l24-selfhost-operations.md +++ b/tasks/active/2026-11-19-l24-selfhost-operations.md @@ -53,3 +53,7 @@ Idea 01M72M9AEB933ZY8269D376DKC LANDING PLAN part 6; policy 795e72a6; rule 56 de Root lint (23 packages), typecheck (38), build (19) pass. Root tests remain in flight. Encryption/operator focused68, scanner187 and realDocker2 pass (synthetic test data, disposable volumes cleaned). Final full self-host run:541pass/17fail, all upgrade-preflight setup affected by stricter CI guard; fixture repair under review. Security reviewer caught real stopped-container selection bug and service-reselection deletion; fixed with Compose --all/full IDs and exact container deletion, real stopped-container/overlay controls pass. Final candidate review and BOX gates still pending. Final local suite after upgrade preflight wiring/fixture repairs:560tests/30filesPASS, upgrade96PASS, tsc/eslintPASS. One remaining final review volume-label control being added; live criteria still unfulfilled. Root timeout retry12/12PASS; scanner0findings, type-boundary0blocking. + +## Sonar followup + +Quick CI at4c41531c4 passed lint, build/typecheck, code quality, secret scan and smoke. Sonar raised45 issues (mostly function complexity/style, plus an alphabetical sort comparator bug). Refactored operations into private helpers without changing ownership/failure ordering; replaced ambiguous regex/string conversions and added parser regressions. Also fixed failure-stop customstate environment propagation with a runner-boundary assertion. Final selfhost573tests/31filesPASS, scanner187PASS/0findings, focusedWIF/teardown101PASS, upgrade96PASS, tsc/eslint/typeboundaryPASS. Independent teardown/WIF refactor reviewPASS; final security delta review running. BOX still L23; H2 newly queued afterL24 (event0c37c5db). From f546d917b57fc2a1412ee7123f3688725120d7fd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rapha=C3=ABl=20Titsworth-Morin?= Date: Thu, 19 Nov 2026 22:59:52 +0000 Subject: [PATCH 04/17] fix(selfhost): require the selected backup writer to be running --- deploy/selfhost/README.md | 3 +- scripts/selfhost/backup-entrypoint.test.ts | 47 +++++++++- scripts/selfhost/backup-lib.ts | 12 +-- scripts/selfhost/backup-runtime.ts | 21 +++++ scripts/selfhost/backup.test.ts | 85 ++++++++++++++++--- scripts/selfhost/box-settings.test.ts | 29 ++++++- scripts/selfhost/box-settings.ts | 3 +- .../selfhost/live/backup-cache.live.test.ts | 3 + .../selfhost/live/backup-restore.live.test.ts | 3 +- scripts/selfhost/testdata/fake-docker.mjs | 9 ++ .../2026-11-19-l24-selfhost-operations.md | 8 ++ 11 files changed, 200 insertions(+), 23 deletions(-) create mode 100644 scripts/selfhost/backup-runtime.ts diff --git a/deploy/selfhost/README.md b/deploy/selfhost/README.md index 1a77a8b8b5..dde7b6d988 100644 --- a/deploy/selfhost/README.md +++ b/deploy/selfhost/README.md @@ -99,7 +99,8 @@ From the repository root on the VM: The fleet bucket contains Worker secrets as well as application data. The backup command encrypts **the entire backup**, including the bucket, `.state/`, `.env` and its manifest, with AES-256-GCM. -It briefly stops celld for a consistent second bucket copy and restarts it even if that copy +It first requires exactly one running celld in the selected Compose project, then briefly stops +it for a consistent second bucket copy and restarts it even if that copy fails (`scripts/selfhost/backup-lib.ts:runBackup`, `runPlainBackup`). Temporary plaintext lives under the private `.tmp/selfhost-backups/` directory and is removed on success or failure. Backup, restore, upgrade and teardown are operator-box commands. They refuse execution whenever diff --git a/scripts/selfhost/backup-entrypoint.test.ts b/scripts/selfhost/backup-entrypoint.test.ts index 9fe2b02c0b..dbb5694b1d 100644 --- a/scripts/selfhost/backup-entrypoint.test.ts +++ b/scripts/selfhost/backup-entrypoint.test.ts @@ -125,6 +125,43 @@ afterEach(() => { }); describe('selfhost:backup and selfhost:restore (real entry points, fake gcloud)', () => { + it('backs up the actual legacy shell-selected project when its YAML has only a static name', () => { + const compose = join(root, 'legacy-compose.yml'); + writeFileSync(compose, 'name: sam-selfhost\nservices:\n celld:\n image: fixture/celld\n'); + env.COMPOSE_FILE = compose; + env.COMPOSE_PROJECT_NAME = 'sam-selfhost'; + env.FAKE_COMPOSE_PROJECT = 'sam-selfhost'; + const dest = join(root, 'legacy-project-backup'); + const result = run('backup.ts', [ + '--to', + dest, + '--box-env', + join(root, 'box.env'), + '--state-dir', + join(root, 'state'), + '--encryption-key-file', + join(root, 'backup-key'), + ]); + expect(result.status).toBe(0); + expect(result.stderr).toBe(''); + const calls = readFileSync(join(root, 'fake/calls.log'), 'utf8').trim().split('\n'); + const composeCalls = calls.filter((call) => call.startsWith('docker compose')); + expect(composeCalls).toHaveLength(3); + for (const call of composeCalls) + expect(call).toContain(`--project-name sam-selfhost -f ${compose}`); + expect(composeCalls[0]).toContain('ps --status running --quiet --no-trunc celld'); + expect(composeCalls[1]).toMatch(/stop celld$/); + expect(composeCalls[2]).toMatch(/start celld$/); + const plain = join(root, 'legacy-inspection'); + decryptBackupTree(dest, plain, join(root, 'backup-key')); + try { + expect(readFileSync(join(plain, 'bucket/nodes/node_live.json'), 'utf8')).toBe('{"lease":2}'); + } finally { + rmSync(plain, { recursive: true, force: true }); + } + expect(readFileSync(join(root, 'fake/celld'), 'utf8')).toBe('running'); + }, 60_000); + it('uses shell bucket overrides and the explicit custom state directory through real child commands', () => { env.CELLD_BUCKET = 'gs://override/celld'; env.SAM_SELFHOST_STATE_DIR = join(root, 'wrong-state'); @@ -163,7 +200,7 @@ describe('selfhost:backup and selfhost:restore (real entry points, fake gcloud)' } expect( readFileSync(join(root, 'fake/compose-state-dirs.log'), 'utf8').trim().split('\n') - ).toEqual([custom, custom]); + ).toEqual([custom, custom, custom]); }, 60_000); // Runs the real backup and restore entry points as child processes: give them room under load. @@ -203,14 +240,16 @@ describe('selfhost:backup and selfhost:restore (real entry points, fake gcloud)' rmSync(inspection, { recursive: true, force: true }); const calls = readFileSync(join(root, 'fake/calls.log'), 'utf8').trim().split('\n'); - expect(calls.map((c) => c.split(' ').slice(0, 3).join(' '))).toEqual([ + expect(calls[0]).toContain('ps --status running --quiet --no-trunc celld'); + const operations = calls.filter((call) => !call.includes(' ps --status running ')); + expect(operations.map((c) => c.split(' ').slice(0, 3).join(' '))).toEqual([ 'gcloud storage rsync', // live 'docker compose --project-name', 'gcloud storage rsync', // delta, celld stopped 'docker compose --project-name', ]); - expect(calls[1]).toMatch(/stop celld$/); - expect(calls[3]).toMatch(/start celld$/); + expect(operations[1]).toMatch(/stop celld$/); + expect(operations[3]).toMatch(/start celld$/); // Restore into an empty install: new bucket, no platform keys yet. writeFileSync(join(root, 'new.env'), 'CELLD_BUCKET=gs://fresh/celld\n', { mode: 0o600 }); diff --git a/scripts/selfhost/backup-lib.ts b/scripts/selfhost/backup-lib.ts index 68d269b8be..9b4b58ac61 100644 --- a/scripts/selfhost/backup-lib.ts +++ b/scripts/selfhost/backup-lib.ts @@ -16,6 +16,7 @@ import { dirname, join, relative, resolve } from 'node:path'; import { decryptBackupTree, encryptBackupTree, readBackupKey } from './backup-encryption'; import { readManifest } from './backup-manifest'; import { assertBackupOutside, assertOperationPaths } from './backup-paths'; +import { requireRunningCelld } from './backup-runtime'; import { composeProjectFor, expectedComposeProjectFor, recordBackup } from './install-record'; import { assertOperatorExecution } from './operator-only'; import { ensurePrivateDir, readPrivateJson } from './secret-files'; @@ -295,11 +296,11 @@ function runPlainBackup( // The pre-copy only shortens the downtime; the delta copy below, with celld stopped, is the one // that must succeed, and it fails loudly if the store itself is unreachable. // - // The pre-copy goes to its own directory. An aborted gcloud pass leaves state keyed by the - // destination path it was writing (resumable-download tracker files, `_.gstmp` temporaries), and - // the historical box failure reported a missing local nodes/node_.json path. Tracker - // reuse is a hypothesis requiring live confirmation, so isolate the second pass from the - // first pass's destination paths and retain a clean-copy fallback. Only bytes carry over. + // BOX's failed stopped pass reached gcloud's POSIX-metadata step with a missing local node + // JSON file (SDK 523: finalize_download can return false, but its caller still stats the file). + // Keep partial live downloads and their destination-keyed resumable state out of the stopped + // pass: remove temporary files, move only completed bytes to fresh paths, and retain the + // untouched-directory fallback if that pass still fails. try { pullBucket(ctx, liveDir); } catch (err) { @@ -454,6 +455,7 @@ export function runBackup( throw new Error('Keep the backup key outside installation state and backups'); } ensurePrivateDir(dirname(resolve(dest))); + requireRunningCelld(ctx); const temp = backupScratch(); try { const plain = join(temp, 'plain'); diff --git a/scripts/selfhost/backup-runtime.ts b/scripts/selfhost/backup-runtime.ts new file mode 100644 index 0000000000..00aa66d662 --- /dev/null +++ b/scripts/selfhost/backup-runtime.ts @@ -0,0 +1,21 @@ +/** Refuse an unobserved writer: Compose stop on a nonexistent project succeeds without action. */ +import { type BoxContext, check, composeArgs, composeRunEnv } from './backup-lib'; +import { assertOperatorExecution } from './operator-only'; + +export function requireRunningCelld(ctx: BoxContext): void { + assertOperatorExecution(); + const result = check( + ctx.run( + 'docker', + composeArgs(ctx, ['ps', '--status', 'running', '--quiet', '--no-trunc', 'celld']), + composeRunEnv(ctx) + ), + 'verify running celld before backup' + ); + const ids = result.stdout.trim().split(/\s+/); + if (ids.length !== 1 || !/^[a-f0-9]{64}$/.test(ids[0] ?? '')) { + throw new Error( + 'Backup refused: selected Compose project must have exactly one running celld container' + ); + } +} diff --git a/scripts/selfhost/backup.test.ts b/scripts/selfhost/backup.test.ts index 02e946b270..a5826d81ac 100644 --- a/scripts/selfhost/backup.test.ts +++ b/scripts/selfhost/backup.test.ts @@ -55,6 +55,7 @@ let mountInspections: number; let selectedProject: string; let replaceStateOnPush: boolean; let celldStopped: boolean; +let runningCelldIds: string; let cacheInspections: number; let targetContainers: string; let occupiedProject: string | undefined; @@ -80,6 +81,8 @@ function fakeRun(command: string, args: string[], env?: NodeJS.ProcessEnv): RunR clock += 1000; // every command takes one second of fake time const ok = { status: 0, stdout: '', stderr: '' }; if (command === 'docker' && args[0] === 'compose') { + if (args.includes('ps') && args.includes('--status')) + return { ...ok, stdout: celldStopped ? '' : runningCelldIds }; if (args.includes('ps') && args.includes('-q') && args.at(-1) === 'celld') { if (celldStopped && !args.includes('--all')) return ok; selectedProject = args[args.indexOf('--project-name') + 1] ?? ''; @@ -233,6 +236,7 @@ beforeEach(() => { selectedProject = ''; replaceStateOnPush = false; celldStopped = false; + runningCelldIds = 'c'.repeat(64); cacheInspections = 0; targetContainers = ''; occupiedProject = undefined; @@ -261,6 +265,21 @@ function inspectBackup(dest: string, part: string): Record { } describe('runBackup', () => { + it.each(['', `${'c'.repeat(64)}\n${'d'.repeat(64)}`, 'short-id'])( + 'refuses missing or ambiguous running celld before any bucket copy (%s)', + (ids) => { + runningCelldIds = ids; + const snapshot = join(root, 'unobserved-writer-backup'); + expect(() => runBackup(ctx('gs://fleet/celld', join(root, 'state')), snapshot)).toThrow( + /exactly one running celld/ + ); + expect(calls).toHaveLength(1); + expect(calls[0]?.args).toContain('--status'); + expect(calls.some((call) => call.command === 'gcloud')).toBe(false); + expect(existsSync(snapshot)).toBe(false); + } + ); + it('backs up the real generated celld project while omitting its rebuildable source/migration symlinks', () => { const apiDir = resolve(import.meta.dirname, '../../apps/api'); const source = TOML.parse(readFileSync(join(apiDir, 'wrangler.toml'), 'utf8')) as WranglerToml; @@ -301,11 +320,13 @@ describe('runBackup', () => { const dest = join(root, 'backups/b1'); const manifest = runBackup(ctx('s3://fleet/celld', join(root, 'state')), dest, 'a'.repeat(40)); - const sequence = calls.map((c) => - c.args[0] === 'compose' - ? `compose ${c.args.slice(-2).join(' ')}` - : `${c.command} ${c.args[0]}` - ); + const sequence = calls + .filter((c) => !c.args.includes('--status')) + .map((c) => + c.args[0] === 'compose' + ? `compose ${c.args.slice(-2).join(' ')}` + : `${c.command} ${c.args[0]}` + ); expect(sequence).toEqual([ 'docker run', // live pre-copy 'compose stop celld', @@ -323,7 +344,7 @@ describe('runBackup', () => { // The store credential travels in the environment only, and never into the manifest. for (const call of calls) expect(call.args.join(' ')).not.toContain(SECRET); - expect(calls[0]!.env?.MC_HOST_src).toContain(SECRET); + expect(calls.find((c) => c.args[0] === 'run')!.env?.MC_HOST_src).toContain(SECRET); expect(readFileSync(join(dest, MANIFEST_NAME), 'utf8')).not.toContain(SECRET); }); @@ -391,7 +412,12 @@ describe('runBackup', () => { 'current.json': '{"v":3}', }); // celld stays stopped through both copies, and the downtime records both. - expect(calls.map((c) => c.args.at(-1)).filter((a) => a === 'celld')).toHaveLength(2); + expect( + calls + .filter((c) => !c.args.includes('--status')) + .map((c) => c.args.at(-1)) + .filter((a) => a === 'celld') + ).toHaveLength(2); expect(manifest.downtimeMs).toBe(3000); // stop t+2s, failed delta t+3s, whole copy t+4s, start t+5s }); @@ -412,15 +438,54 @@ describe('runBackup', () => { expect(calls).toHaveLength(0); }); - it('uses gcloud storage rsync for a gs:// bucket', () => { + it('recovers the BOX gcloud post-download POSIX ENOENT without retaining a partial node file', () => { + let pulls = 0; + let running = true; const run = (command: string, args: string[]) => { calls.push({ command, args }); + if (command === 'docker') { + if (args.includes('--status')) return { status: 0, stdout: 'c'.repeat(64), stderr: '' }; + if (args.includes('stop')) running = false; + if (args.includes('start')) running = true; + return { status: 0, stdout: '', stderr: '' }; + } + const directory = args.at(-1)!; + mkdirSync(join(directory, 'nodes'), { recursive: true }); + pulls++; + if (pulls === 1) { + writeFileSync(join(directory, 'nodes/stale.json_.gstmp'), 'partial download'); + return { status: 1, stdout: '', stderr: 'HTTP 404: live object generation vanished' }; + } + expect(running).toBe(false); + if (pulls === 2) { + expect(existsSync(join(directory, 'nodes/stale.json_.gstmp'))).toBe(false); + return { + status: 1, + stdout: '', + stderr: 'FileNotFoundError: POSIX os.stat destination nodes/stale.json [Errno 2]', + }; + } + writeFileSync(join(directory, 'nodes/current.json'), 'consistent node data'); return { status: 0, stdout: '', stderr: '' }; }; + const dest = join(root, 'backups/gcloud-posix'); + const manifest = runBackup({ ...ctx('gs://fleet/celld', join(root, 'state')), run }, dest); + expect(manifest.objectCount).toBe(1); + expect(inspectBackup(dest, 'bucket')).toEqual({ 'nodes/current.json': 'consistent node data' }); + expect(running).toBe(true); + }); + + it('uses gcloud storage rsync for a gs:// bucket', () => { + const run = (command: string, args: string[]) => { + calls.push({ command, args }); + return { status: 0, stdout: args.includes('--status') ? 'c'.repeat(64) : '', stderr: '' }; + }; runBackup({ ...ctx('gs://my-bucket/celld', join(root, 'state')), run }, join(root, 'b3')); // live pass into its own directory; the delta pass into `bucket`, a path gcloud never wrote - expect(basename(calls[2]?.args.at(-1) ?? '')).toBe('bucket'); - expect(calls[0]).toMatchObject({ + expect(basename(calls.filter((c) => c.command === 'gcloud')[1]?.args.at(-1) ?? '')).toBe( + 'bucket' + ); + expect(calls.find((c) => c.command === 'gcloud')).toMatchObject({ command: 'gcloud', args: [ 'storage', diff --git a/scripts/selfhost/box-settings.test.ts b/scripts/selfhost/box-settings.test.ts index 98e61deb9b..206b3eb2c2 100644 --- a/scripts/selfhost/box-settings.test.ts +++ b/scripts/selfhost/box-settings.test.ts @@ -1,15 +1,17 @@ import { closeSync, + mkdirSync, mkdtempSync, openSync, readdirSync, readFileSync, readSync, + rmSync, statSync, writeFileSync, } from 'node:fs'; import { tmpdir } from 'node:os'; -import { join } from 'node:path'; +import { join, resolve } from 'node:path'; import { describe, expect, it } from 'vitest'; import { parse } from 'yaml'; @@ -429,6 +431,31 @@ describe('sam-mx listen address and unprivileged listeners (S4)', () => { }); describe('loadBoxEnv (S4: checked before anything starts)', () => { + it('honors shell COMPOSE_PROJECT_NAME even when selected legacy YAML has only a static name', () => { + mkdirSync(resolve('.tmp'), { recursive: true }); + const root = mkdtempSync(resolve('.tmp/legacy-compose-project-')); + try { + const compose = join(root, 'legacy.yml'); + writeFileSync(compose, 'name: sam-selfhost\nservices:\n celld:\n image: fixture/celld\n'); + const env = join(root, 'box.env'); + writeFileSync(env, `COMPOSE_FILE=${compose}\nCOMPOSE_PROJECT_NAME=env-project\n`, { + mode: 0o600, + }); + expect(composeFileVariables({ COMPOSE_FILE: compose }, root)).not.toContain( + 'COMPOSE_PROJECT_NAME' + ); + const overrides: string[] = []; + const selected = loadBoxEnv(env, root, { COMPOSE_PROJECT_NAME: 'sam-selfhost' }, (name) => + overrides.push(name) + ); + expect(selected.COMPOSE_PROJECT_NAME).toBe('sam-selfhost'); + expect(overrides).toContain('COMPOSE_PROJECT_NAME'); + expect(loadBoxEnv(env, root, {}).COMPOSE_PROJECT_NAME).toBe('env-project'); + } finally { + rmSync(root, { recursive: true, force: true }); + } + }); + const box = (lines: string[]) => { const file = join(mkdtempSync(join(tmpdir(), 'sam-box-env-')), '.env'); writeFileSync(file, `${lines.join('\n')}\n`, { mode: 0o600 }); diff --git a/scripts/selfhost/box-settings.ts b/scripts/selfhost/box-settings.ts index 92f6f4ba9c..0ca530d5f5 100644 --- a/scripts/selfhost/box-settings.ts +++ b/scripts/selfhost/box-settings.ts @@ -68,12 +68,13 @@ const UNPRIVILEGED_LISTENERS: ReadonlySet = new Set([ /** * Compose's own control variables that the box .env may set and the scripts read: which files - * (COMPOSE_FILE, COMPOSE_PATH_SEPARATOR) and which profiles (COMPOSE_PROFILES: the mail collector, + * (COMPOSE_FILE, COMPOSE_PATH_SEPARATOR), the project (COMPOSE_PROJECT_NAME), and profiles (COMPOSE_PROFILES: the mail collector, * inbound mail) the stack runs with. Compose takes them from the shell before the .env, like an * interpolated variable, but no compose file references them, so they are named here. */ export const COMPOSE_CONTROL_VARIABLES: readonly string[] = [ 'COMPOSE_FILE', + 'COMPOSE_PROJECT_NAME', 'COMPOSE_PATH_SEPARATOR', 'COMPOSE_PROFILES', ]; diff --git a/scripts/selfhost/live/backup-cache.live.test.ts b/scripts/selfhost/live/backup-cache.live.test.ts index 9f3d9d6dce..1d18262a93 100644 --- a/scripts/selfhost/live/backup-cache.live.test.ts +++ b/scripts/selfhost/live/backup-cache.live.test.ts @@ -12,6 +12,7 @@ import { composeRunEnv, OBJECTSTORE_IMAGE, } from '../backup-lib'; +import { requireRunningCelld } from '../backup-runtime'; import { recordInstall } from '../install-record'; import { LIVE_TMP, skipWithoutDocker } from './harness'; @@ -76,10 +77,12 @@ describe.skipIf(skipWithoutDocker)( } }); it('accepts canonical cache and rejects an overlay replacing the actual container mount', () => { + requireRunningCelld(context!); const proof = assertRollbackCacheReady(context!); expect(proof.name).toMatch(/^sam-selfhost-[a-f0-9]{12}_celld-data$/); expect(proof.container).toMatch(/^[a-f0-9]{64}$/); docker(['stop', 'celld']); + expect(() => requireRunningCelld(context!)).toThrow('exactly one running celld container'); expect(assertRollbackCacheReady(context!).container).toBe(proof.container); const overlay = join(root, 'override.yml'); writeFileSync( diff --git a/scripts/selfhost/live/backup-restore.live.test.ts b/scripts/selfhost/live/backup-restore.live.test.ts index e23645aa7e..abdf0026fb 100644 --- a/scripts/selfhost/live/backup-restore.live.test.ts +++ b/scripts/selfhost/live/backup-restore.live.test.ts @@ -1,7 +1,7 @@ /** * selfhost:backup -> selfhost:restore against the box's own object store: the MinIO image pinned * in docker-compose.yml, run on loopback in Docker, driven by the real `mc mirror` commands in - * backup-lib.ts. Only `docker compose stop/start celld` is stubbed (there is no celld here). + * backup-lib.ts. Compose celld lifecycle and inventory are stubbed (there is no celld here). * Round trip: seed a fleet bucket, back it up, restore into a second empty bucket, pull that * bucket back and compare every object. Also proves restore refuses a non-empty bucket. */ @@ -38,6 +38,7 @@ const composeCalls: string[] = []; function run(command: string, args: string[], env?: NodeJS.ProcessEnv): RunResult { if (command === 'docker' && args[0] === 'compose') { + if (args.includes('ps')) return { status: 0, stdout: 'c'.repeat(64), stderr: '' }; composeCalls.push(args.slice(-2).join(' ')); return { status: 0, stdout: '', stderr: '' }; } diff --git a/scripts/selfhost/testdata/fake-docker.mjs b/scripts/selfhost/testdata/fake-docker.mjs index 00756cc077..0569bc2dd5 100755 --- a/scripts/selfhost/testdata/fake-docker.mjs +++ b/scripts/selfhost/testdata/fake-docker.mjs @@ -21,7 +21,16 @@ appendFileSync( join(state, 'compose-state-dirs.log'), `${process.env.SAM_SELFHOST_STATE_DIR ?? ''}\n` ); +const selectedProject = args[args.indexOf('--project-name') + 1]; +const matches = + !process.env.FAKE_COMPOSE_PROJECT || process.env.FAKE_COMPOSE_PROJECT === selectedProject; +if (args.includes('ps')) { + if (matches && readFileSync(join(state, 'celld'), 'utf8').trim() === 'running') + process.stdout.write('c'.repeat(64) + '\n'); + process.exit(0); +} const [action, service] = args.slice(-2); +if (!matches) process.exit(action === 'stop' ? 0 : 1); if (service !== 'celld') process.exit(2); writeFileSync(join(state, 'celld'), action === 'stop' ? 'stopped' : 'running'); const onStop = join(state, 'on-stop.json'); diff --git a/tasks/active/2026-11-19-l24-selfhost-operations.md b/tasks/active/2026-11-19-l24-selfhost-operations.md index ec4e0d74ad..044aec6eff 100644 --- a/tasks/active/2026-11-19-l24-selfhost-operations.md +++ b/tasks/active/2026-11-19-l24-selfhost-operations.md @@ -57,3 +57,11 @@ Final local suite after upgrade preflight wiring/fixture repairs:560tests/30file ## Sonar followup Quick CI at4c41531c4 passed lint, build/typecheck, code quality, secret scan and smoke. Sonar raised45 issues (mostly function complexity/style, plus an alphabetical sort comparator bug). Refactored operations into private helpers without changing ownership/failure ordering; replaced ambiguous regex/string conversions and added parser regressions. Also fixed failure-stop customstate environment propagation with a runner-boundary assertion. Final selfhost573tests/31filesPASS, scanner187PASS/0findings, focusedWIF/teardown101PASS, upgrade96PASS, tsc/eslint/typeboundaryPASS. Independent teardown/WIF refactor reviewPASS; final security delta review running. BOX still L23; H2 newly queued afterL24 (event0c37c5db). + +## BOX slot418 evidence (in progress) + +Claim987d8996 after L23FREE2a876ebc. Original shared checkoute7ac643b/fourcontainers/API200. Own SSH firewall sam-l24-ssh-slot418 immutableid7663373354569745545 +metadata key, cleanup owed. Store root uniquely owned gs://sam-selfhost-vmtest-fleet/l24-01m7ttkas78amj3853s5n4byak-slot418 has random ownership marker and was proven empty before creation; never shared/celld. + +F23: retrieved the original failed stopped-copy gcloud log2026.11.19/21.46.12.578974.log read-only. Trace reaches SDK523 file_download_task.execute -> posix_util.run_if_setting_posix -> set_posix_attributes_on_file_if_valid -> get_posix_attributes_from_file/os.stat, then ENOENT for local nodes/node_*.json. Log has9HTTP404 occurrences, atime/mtime POSIX metadata, no hash mismatch. SDK source proves finalize_download returnsFalse when temporary download missing, but caller ignores return and applies POSIX metadata/stat. Root failure mechanism is missing download followed by POSIX stat; tracker reuse alone remains unproved. Historical fresh retry succeeded4251objects, confirming intermittent behavior. Old plaintext diagnostic tree removed. New isolated live paths/temp cleanup/fresh full-copy fallback avoid partial-download reuse; targeted GCS POSIX ENOENT regression verifies complete final data/no partial node artifact and restarted writer. + +Live found adjacent writer-selection bug: shell COMPOSE_PROJECT_NAME ignored with a legacy YAML whose name was static. Compose stop on nonexistent derived project returns0, so no writer had stopped. Fixed always-control precedence and fail-before-copy singleton running-writer observation;114 focused and full578tests, realDocker2, scanner187,tsc/eslint pass. Finalcommit/retest pending. Explicit private target env instead of shared edit yielded real encrypted backup4270objects, down4919ms, authentication success, original API200. Restore to fresh owned /restore prefix complete;4270objects including3701LTX +476statefiles SHA256 compared exactly, source receipts stripped. Restore app not started (avoid shared background alarms). Init/disposableupgrade/teardown/refusal still owed. From 761662d8438e9d0ce4138c47f20a9b838cdbda87 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rapha=C3=ABl=20Titsworth-Morin?= Date: Thu, 19 Nov 2026 23:20:37 +0000 Subject: [PATCH 05/17] fix(selfhost): make recovery retryable and receipt identity grants --- deploy/selfhost/README.md | 18 ++ deploy/selfhost/gcp-bootstrap.sh | 18 ++ scripts/selfhost/backup-recovery.ts | 174 +++++++++++++++--- scripts/selfhost/backup.test.ts | 93 +++++++++- scripts/selfhost/gcp-bootstrap.test.ts | 20 +- scripts/selfhost/teardown-gcp-bootstrap.ts | 86 +++++++++ scripts/selfhost/teardown-gcp-targets.ts | 26 +++ scripts/selfhost/teardown-gcp.ts | 49 ++--- scripts/selfhost/teardown.test.ts | 93 +++++++++- scripts/selfhost/tsconfig.json | 7 + scripts/selfhost/upgrade-instructions.ts | 33 ++++ scripts/selfhost/upgrade-lib.ts | 39 +--- scripts/selfhost/upgrade-rollback-cli.test.ts | 123 +++++++++++++ scripts/selfhost/upgrade-rollback.test.ts | 165 +++++++++++++++++ scripts/selfhost/upgrade-rollback.ts | 60 ++++++ scripts/selfhost/upgrade-safeguards.test.ts | 2 +- scripts/selfhost/upgrade.test.ts | 57 ++---- scripts/selfhost/upgrade.ts | 39 ++-- .../2026-11-19-l24-selfhost-operations.md | 10 + 19 files changed, 960 insertions(+), 152 deletions(-) create mode 100644 scripts/selfhost/teardown-gcp-targets.ts create mode 100644 scripts/selfhost/upgrade-instructions.ts create mode 100644 scripts/selfhost/upgrade-rollback-cli.test.ts create mode 100644 scripts/selfhost/upgrade-rollback.test.ts create mode 100644 scripts/selfhost/upgrade-rollback.ts diff --git a/deploy/selfhost/README.md b/deploy/selfhost/README.md index dde7b6d988..a8f50f5983 100644 --- a/deploy/selfhost/README.md +++ b/deploy/selfhost/README.md @@ -177,6 +177,24 @@ snapshot path. Keep celld stopped if automatic recovery fails; retain the snapsh retry the same upgrade command to recover the original install before attempting a new upgrade. Do not delete the pending record to bypass a failed recovery. +After a successful upgrade, its printed rollback command restores the populated installation +in place. Run it from the upgraded checkout, keeping the original full commit SHA, snapshot, +key and any printed `--rebuild` arguments: + +```sh +pnpm selfhost:upgrade --to \ + --rollback-from /absolute/path/to/pre-upgrade-backup \ + --encryption-key-file /secure/path/to/backup.key +``` + +This command verifies that the authenticated snapshot belongs to that revision and installation, +restores its data before starting the old code, and checks health. Keep celld stopped and retry +the same rollback command if recovery fails. Failure restores the operator checkout and dependencies +without starting the application. If the process was killed or that checkout recovery fails, +restore the newer operator checkout and run `pnpm install --frozen-lockfile` before retrying. +`selfhost:restore` requires an empty replacement +target; use the printed upgrade rollback command for an existing installation. + For a nondefault install, use `--box-env`, `--state-dir` and, if needed, `--secrets`. Every deploy and Compose operation uses that installation's environment and overlays. Set `SAM_SELFHOST_STATE_DIR` to an absolute path when running Compose manually. diff --git a/deploy/selfhost/gcp-bootstrap.sh b/deploy/selfhost/gcp-bootstrap.sh index c9000f05ab..07c7f02946 100755 --- a/deploy/selfhost/gcp-bootstrap.sh +++ b/deploy/selfhost/gcp-bootstrap.sh @@ -399,9 +399,27 @@ done # credential and no user's. SAM also refuses a user credential that names a pool the platform # credential holds (gcp-wif-pool-ownership.ts). Any provider added to this pool later would # inherit the service account too, so do not add providers to it. +sa_grant_action=created +if [[ "$DRY_RUN" -eq 0 && -n "$INSTALLATION_ID" && "$sa_existed" -eq 1 ]]; then + sa_grant_status=0 + printf '%s' "$sa_policy" | POOL_PRINCIPAL="$POOL_PRINCIPAL" node -e ' + let text=""; process.stdin.on("data", x=>text+=x); process.stdin.on("end", ()=>{ + let p; try {p=JSON.parse(text)} catch {process.exit(2)}; + if (!p || !Array.isArray(p.bindings ?? [])) process.exit(2); + process.exit((p.bindings ?? []).some(b=>!b.condition && b.role==="roles/iam.workloadIdentityUser" && b.members?.includes(process.env.POOL_PRINCIPAL)) ? 0 : 10); + });' || sa_grant_status=$? + case "$sa_grant_status" in + 0) sa_grant_action=reused ;; + 10) ;; + *) die "cannot parse service account IAM policy" ;; + esac +fi change_retry iam service-accounts add-iam-policy-binding "$SA_EMAIL" --project="$PROJECT" \ --role=roles/iam.workloadIdentityUser --member="$POOL_PRINCIPAL" \ --condition=None --quiet --format=none +if [[ "$DRY_RUN" -eq 0 && -n "$INSTALLATION_ID" ]]; then + record_resource service-account-iam-binding "$SA_EMAIL#roles/iam.workloadIdentityUser#$POOL_PRINCIPAL" "$sa_grant_action" "$sa_identity" "$POOL_PRINCIPAL" roles/iam.workloadIdentityUser +fi # Optional: make only rules absent at creation time, preserving an ownership receipt. # Existing same-name rules belong to whoever created them and are never adopted. diff --git a/scripts/selfhost/backup-recovery.ts b/scripts/selfhost/backup-recovery.ts index 1707780077..ae6e2f20a2 100644 --- a/scripts/selfhost/backup-recovery.ts +++ b/scripts/selfhost/backup-recovery.ts @@ -1,6 +1,14 @@ /** Restore an upgrade's authenticated snapshot to the same owned installation. */ -import { cpSync, lstatSync, readFileSync, rmSync } from 'node:fs'; -import { join, resolve } from 'node:path'; +import { + cpSync, + existsSync, + lstatSync, + mkdtempSync, + readFileSync, + renameSync, + rmSync, +} from 'node:fs'; +import { dirname, join, resolve } from 'node:path'; import { readRecord } from '../../deploy/selfhost/created-resources.mjs'; import { decryptBackupTree } from './backup-encryption'; @@ -23,6 +31,7 @@ import { } from './backup-lib'; import { composeProjectFor, recordInstall } from './install-record'; import { assertOperatorExecution } from './operator-only'; +import { assertPrivateFile, replacePrivateFile } from './secret-files'; import { assertRollbackReady } from './upgrade-preflight'; function compose(ctx: BoxContext, args: string[]): void { check( @@ -150,30 +159,135 @@ export function assertRollbackCacheReady(ctx: BoxContext): RollbackCacheProof { return { ...proof, container }; } -/** Re-prove the active mount and immutable volume creation identity immediately before removal. */ -function discardCelldCache(ctx: BoxContext, expected: RollbackCacheProof): void { - const current = assertRollbackCacheReady(ctx); +/** A private receipt permits retry after this process removed only part of the cache. */ +const CACHE_PENDING = 'rollback-cache-pending.json'; +function pendingCache(ctx: BoxContext, from: string): RollbackCacheProof | null { + const path = join(ctx.stateDir, CACHE_PENDING); + if (!existsSync(path)) return null; + assertPrivateFile(path); + let value: { snapshot?: unknown; name?: unknown; createdAt?: unknown; container?: unknown }; + try { + value = JSON.parse(readFileSync(path, 'utf8')); + } catch { + throw new Error('Invalid rollback cache recovery receipt'); + } if ( - current.name !== expected.name || - current.createdAt !== expected.createdAt || - current.container !== expected.container + value.snapshot !== resolve(from) || + value.name !== `${composeProjectFor(ctx.box, ctx.stateDir)}_celld-data` || + typeof value.createdAt !== 'string' || + !Number.isFinite(Date.parse(value.createdAt)) || + typeof value.container !== 'string' || + !/^[a-f0-9]{64}$/.test(value.container) ) + throw new Error('Invalid rollback cache recovery receipt'); + return { name: value.name, createdAt: value.createdAt, container: value.container }; +} +function cachePresence( + ctx: BoxContext, + expected: RollbackCacheProof +): { container: boolean; volume: boolean } { + assertRollbackReady(ctx); + const selected = check( + ctx.run( + 'docker', + composeArgs(ctx, ['ps', '--all', '--no-trunc', '-q', 'celld']), + composeRunEnv(ctx) + ), + 'inspect recovering celld' + ).stdout.trim(); + if (selected && selected !== expected.container) throw new Error('Rollback celld cache identity changed; refusing removal'); - check( - ctx.run('docker', ['container', 'rm', '--force', expected.container]), - 'remove exact rollback celld container' + const volumes = check( + ctx.run('docker', [ + 'volume', + 'ls', + '--filter', + `name=^${expected.name}$`, + '--format', + '{{.Name}}', + ]), + 'inspect recovering cache' + ).stdout.trim(); + if (volumes && volumes !== expected.name) throw new Error('Ambiguous recovering celld cache'); + if (volumes) { + const current = inspectCacheVolume(ctx); + if (current.createdAt !== expected.createdAt) + throw new Error('Rollback celld cache identity changed; refusing removal'); + } + if (selected) { + const current = assertRollbackCacheReady(ctx); + if (!volumes || current.createdAt !== expected.createdAt) + throw new Error('Rollback celld cache identity changed; refusing removal'); + } + return { container: Boolean(selected), volume: Boolean(volumes) }; +} +/** Keep the proof durable until both exact resources have disappeared. */ +function discardCelldCache(ctx: BoxContext, expected: RollbackCacheProof, from: string): void { + replacePrivateFile( + join(ctx.stateDir, CACHE_PENDING), + JSON.stringify({ ...expected, snapshot: resolve(from) }) ); - const after = inspectCacheVolume(ctx); - if (after.name !== expected.name || after.createdAt !== expected.createdAt) - throw new Error('Rollback celld cache identity changed; refusing removal'); - check(ctx.run('docker', ['volume', 'rm', expected.name]), 'remove owned celld cache'); + const present = cachePresence(ctx, expected); + if (present.container) + check( + ctx.run('docker', ['container', 'rm', '--force', expected.container]), + 'remove exact rollback celld container' + ); + if (present.volume) { + const after = inspectCacheVolume(ctx); + if (after.createdAt !== expected.createdAt) + throw new Error('Rollback celld cache identity changed; refusing removal'); + check(ctx.run('docker', ['volume', 'rm', expected.name]), 'remove owned celld cache'); + } + rmSync(join(ctx.stateDir, CACHE_PENDING)); +} +/** Stage the full replacement before swapping directories; failed copying retains live state. */ +function restoreState( + ctx: BoxContext, + source: string, + id: string, + pending: RollbackCacheProof | null, + from: string +): void { + const stage = mkdtempSync(join(dirname(ctx.stateDir), '.rollback-state-')); + const staged = join(stage, 'restored'); + const previous = join(stage, 'previous'); + try { + cpSync(source, staged, { recursive: true }); + // Keep the original upgrade's recovery pointer until recoverUpgrade verifies health. + const upgradePending = join(ctx.stateDir, 'upgrade-pending.json'); + if (existsSync(upgradePending)) { + assertPrivateFile(upgradePending); + replacePrivateFile( + join(staged, 'upgrade-pending.json'), + readFileSync(upgradePending, 'utf8') + ); + } + if (pending) + replacePrivateFile( + join(staged, CACHE_PENDING), + JSON.stringify({ ...pending, snapshot: resolve(from) }) + ); + assertStateReceipt(ctx.stateDir, ctx.stateDir, id, true); + renameSync(ctx.stateDir, previous); + try { + renameSync(staged, ctx.stateDir); + recordInstall(ctx.stateDir, ctx.envFile, ctx.box, id); + } catch (error) { + rmSync(ctx.stateDir, { recursive: true, force: true }); + renameSync(previous, ctx.stateDir); + throw error; + } + } finally { + rmSync(stage, { recursive: true, force: true }); + } } /** * Compensate only an upgrade of this exact install using its own pre-upgrade snapshot. * The target is the original scoped bucket, never an arbitrary restore destination. */ -export function runRollback(ctx: BoxContext, from: string): void { +export function runRollback(ctx: BoxContext, from: string, expectedSamCommit?: string): void { assertOperatorExecution(); const key = backupKey(ctx); assertBackupOutside(ctx, from); @@ -182,6 +296,8 @@ export function runRollback(ctx: BoxContext, from: string): void { const plain = join(temp, 'plain'); decryptBackupTree(from, plain, key); const manifest = readManifest(plain); + if (expectedSamCommit && manifest.samCommit !== expectedSamCommit) + throw new Error('Rollback snapshot belongs to a different code revision'); if (manifest.bucket !== ctx.box.CELLD_BUCKET) throw new Error('Rollback snapshot belongs to a different bucket'); const oldKeys = readIdentity(join(plain, STATE_DIR, 'platform-keys.json')); @@ -194,9 +310,16 @@ export function runRollback(ctx: BoxContext, from: string): void { } assertStateReceipt(join(plain, STATE_DIR), ctx.stateDir, oldKeys.SAM_INSTALLATION_ID); assertStateReceipt(ctx.stateDir, ctx.stateDir, currentKeys.SAM_INSTALLATION_ID, true); - const cache = assertRollbackCacheReady(ctx); + const pending = pendingCache(ctx, from); + const cache = pending ?? assertRollbackCacheReady(ctx); + if (pending) cachePresence(ctx, pending); compose(ctx, ['stop', 'celld']); - discardCelldCache(ctx, cache); + // Recheck before bucket mutation, retaining the stopped cache until all data is restored. + if (!pending) { + const current = assertRollbackCacheReady(ctx); + if (JSON.stringify(current) !== JSON.stringify(cache)) + throw new Error('Rollback cache identity changed; refusing removal'); + } const url = parseBucketUrl(ctx.box.CELLD_BUCKET ?? ''); const source = join(plain, BUCKET_DIR); if (url.scheme === 'gs') { @@ -225,12 +348,15 @@ export function runRollback(ctx: BoxContext, from: string): void { 'restore pre-upgrade bucket' ); } - // State may hold new generated files: replace it, retaining the source ownership receipts. - assertStateReceipt(ctx.stateDir, ctx.stateDir, currentKeys.SAM_INSTALLATION_ID, true); - rmSync(ctx.stateDir, { recursive: true, force: true }); - cpSync(join(plain, STATE_DIR), ctx.stateDir, { recursive: true }); - cpSync(join(plain, ENV_FILE), ctx.envFile); - recordInstall(ctx.stateDir, ctx.envFile, ctx.box, oldKeys.SAM_INSTALLATION_ID as string); + restoreState(ctx, join(plain, STATE_DIR), oldKeys.SAM_INSTALLATION_ID as string, pending, from); + // A previous partial cache deletion must remain retryable even if copying the env fails. + if (pending) + replacePrivateFile( + join(ctx.stateDir, CACHE_PENDING), + JSON.stringify({ ...cache, snapshot: resolve(from) }) + ); + replacePrivateFile(ctx.envFile, readFileSync(join(plain, ENV_FILE), 'utf8')); + discardCelldCache(ctx, cache, from); } finally { rmSync(temp, { recursive: true, force: true }); } diff --git a/scripts/selfhost/backup.test.ts b/scripts/selfhost/backup.test.ts index a5826d81ac..8b8ec13bb5 100644 --- a/scripts/selfhost/backup.test.ts +++ b/scripts/selfhost/backup.test.ts @@ -5,6 +5,7 @@ * round trip is live/backup-restore.live.test.ts (pinned MinIO image, Docker). */ import { randomBytes } from 'node:crypto'; +import * as fs from 'node:fs'; import { cpSync, existsSync, @@ -40,6 +41,10 @@ import { buildCelldConfig } from './celld-config'; import { prepareCelldProject, writeCelldConfig } from './celld-project'; import { composeProjectFor, expectedComposeProjectFor, recordInstall } from './install-record'; +vi.mock('node:fs', async (importOriginal) => ({ + ...(await importOriginal()), +})); + const PLATFORM_KEYS = JSON.stringify({ SAM_INSTALLATION_ID: 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' }); const SECRET = 'store-secret-value-123'; let root: string; @@ -115,6 +120,7 @@ function fakeRun(command: string, args: string[], env?: NodeJS.ProcessEnv): RunR : '', }; if (command === 'docker' && args[0] === 'volume') { + if (args[1] === 'ls') return { ...ok, stdout: `${selectedProject}_celld-data` }; if (args[1] === 'rm') return ok; if (args[1] === 'inspect') { cacheInspections += 1; @@ -126,7 +132,8 @@ function fakeRun(command: string, args: string[], env?: NodeJS.ProcessEnv): RunR Name: name, CreatedAt: (cacheProof === 'replaced' && cacheInspections > 1) || - (cacheProof === 'replaced-after-remove' && cacheInspections > 2) + (cacheProof === 'replaced-after-remove' && + calls.some((c) => c.args[0] === 'container' && c.args[1] === 'rm')) ? '2026-11-19T02:00:00Z' : '2026-11-19T01:00:00Z', Labels: { @@ -636,6 +643,84 @@ describe('runRollback', () => { ); }); + it('binds a manual rollback to the authenticated source commit before mutation', () => { + const context = ctx('gs://fleet/celld', join(root, 'state')); + const snapshot = join(root, 'wrong-code-snapshot'); + runBackup(context, snapshot); + calls = []; + expect(() => runRollback(context, snapshot, 'f'.repeat(40))).toThrow(/different code revision/); + expect(calls).toHaveLength(0); + }); + + it('retains original owned state and cache when staging restored files fails, then retries', () => { + const context = ctx('gs://fleet/celld', join(root, 'state')); + const snapshot = join(root, 'retry-state-copy'); + runBackup(context, snapshot); + writeFileSync(join(context.stateDir, 'retained-until-swap'), 'original'); + const original = fs.cpSync; + const copy = vi.spyOn(fs, 'cpSync').mockImplementation((source, destination, options) => { + if (String(destination).includes('.rollback-state-')) + throw new Error('transient state copy failure'); + return original(source, destination, options); + }); + calls = []; + expect(() => runRollback(context, snapshot)).toThrow(/transient state copy failure/); + copy.mockRestore(); + expect(readFileSync(join(context.stateDir, 'retained-until-swap'), 'utf8')).toBe('original'); + expect(calls.some((call) => call.args[0] === 'container' && call.args[1] === 'rm')).toBe(false); + expect(() => runRollback(context, snapshot)).not.toThrow(); + expect(existsSync(join(context.stateDir, 'retained-until-swap'))).toBe(false); + }); + + it.each(['bucket', 'volume'] as const)( + 'retries recovery after a transient %s failure', + (phase) => { + const context = ctx('gs://fleet/celld', join(root, 'state')); + const snapshot = join(root, `retry-${phase}`); + runBackup(context, snapshot); + writeFileSync(join(root, 'store/fleet/celld/current.json'), 'new data'); + writeFileSync( + join(context.stateDir, 'upgrade-pending.json'), + JSON.stringify({ from: 'a'.repeat(40), backupDir: snapshot }), + { mode: 0o600 } + ); + let containerRemoved = false; + let failed = false; + context.run = (command, args, env) => { + if ( + command === 'docker' && + args[0] === 'compose' && + args.includes('ps') && + args.includes('-q') && + containerRemoved + ) + return { status: 0, stdout: '', stderr: '' }; + const bucket = + command === 'gcloud' && args.includes('--delete-unmatched-destination-objects'); + const volume = command === 'docker' && args[0] === 'volume' && args[1] === 'rm'; + if (!failed && ((phase === 'bucket' && bucket) || (phase === 'volume' && volume))) { + failed = true; + return { status: 1, stdout: '', stderr: 'transient failure' }; + } + if (command === 'docker' && args[0] === 'container' && args[1] === 'rm') + containerRemoved = true; + return fakeRun(command, args, env); + }; + expect(() => runRollback(context, snapshot)).toThrow( + /restore pre-upgrade bucket|remove owned celld cache/ + ); + expect(containerRemoved).toBe(phase === 'volume'); + expect( + JSON.parse(readFileSync(join(context.stateDir, 'upgrade-pending.json'), 'utf8')).backupDir + ).toBe(snapshot); + expect(existsSync(join(context.stateDir, 'platform-keys.json'))).toBe(true); + expect(() => runRollback(context, snapshot)).not.toThrow(); + expect(failed).toBe(true); + expect(readFileSync(join(root, 'store/fleet/celld/current.json'), 'utf8')).toBe('{"v":3}'); + expect(existsSync(join(context.stateDir, 'rollback-cache-pending.json'))).toBe(false); + } + ); + it.each(['wrong', 'duplicate', 'bind'] as const)( 'refuses a selected overlay with %s celld cache mount before rollback bucket writes', (mount) => { @@ -676,10 +761,10 @@ describe('runRollback', () => { cacheProof = 'replaced-after-remove'; calls = []; expect(() => runRollback(context, snapshot)).toThrow(/cache identity changed/); - expect(cacheInspections).toBe(3); + expect(cacheInspections).toBe(5); expect(calls.some((call) => call.args.includes('--force'))).toBe(true); expect(calls.some((call) => call.args[0] === 'volume' && call.args[1] === 'rm')).toBe(false); - expect(calls.some((call) => call.command === 'gcloud')).toBe(false); + expect(calls.some((call) => call.command === 'gcloud')).toBe(true); }); it('rechecks the live state inode immediately before removal after the bucket copy', () => { @@ -851,7 +936,7 @@ describe('runRollback', () => { '--delete-unmatched-destination-objects' ); expect(calls.some((c) => c.args.includes('stop'))).toBe(true); - expect(cacheInspections).toBe(3); + expect(cacheInspections).toBe(5); const volumeDelete = calls.find( (c) => c.command === 'docker' && c.args[0] === 'volume' && c.args[1] === 'rm' ); diff --git a/scripts/selfhost/gcp-bootstrap.test.ts b/scripts/selfhost/gcp-bootstrap.test.ts index d56429d34e..6a47760ef7 100644 --- a/scripts/selfhost/gcp-bootstrap.test.ts +++ b/scripts/selfhost/gcp-bootstrap.test.ts @@ -624,7 +624,7 @@ describe('bootstrap creation receipts', () => { it('records actual new resource identities and preserves the proof on repeat', () => { expect(run(args()).status).toBe(0); const before = receipts(); - expect(before).toHaveLength(5); + expect(before).toHaveLength(6); expect( before.every( (r) => @@ -636,6 +636,24 @@ describe('bootstrap creation receipts', () => { expect(run(args()).status).toBe(0); expect(receipts().every((r) => r.action === 'created')).toBe(true); }); + it('records only a newly added pool grant on a reused service account as created', () => { + expect(run(['--project', 'sam-vm-test', '--api-url', ISSUER]).status).toBe(0); + setGcp((db) => { + db.saBindings = {}; + }); + expect(run(args()).status).toBe(0); + const grant = receipts().find((r) => r.kind === 'service-account-iam-binding'); + expect(grant?.action).toBe('created'); + expect(grant?.attributes.role).toBe('roles/iam.workloadIdentityUser'); + expect(grant?.attributes.member).toMatch( + /^principalSet:\/\/iam.googleapis.com\/projects\/123456789012\/locations\/global\/workloadIdentityPools\/[^/]+\/\*$/ + ); + expect(receipts().find((r) => r.kind === 'service-account')?.action).toBe('reused'); + expect(run(args()).status).toBe(0); + expect(receipts().find((r) => r.kind === 'service-account-iam-binding')?.action).toBe( + 'created' + ); + }); it('records preexisting resources and grants as reused', () => { expect(run(['--project', 'sam-vm-test', '--api-url', ISSUER]).status).toBe(0); expect(run(args()).status).toBe(0); diff --git a/scripts/selfhost/teardown-gcp-bootstrap.ts b/scripts/selfhost/teardown-gcp-bootstrap.ts index 450b523a2e..d683d0da6e 100644 --- a/scripts/selfhost/teardown-gcp-bootstrap.ts +++ b/scripts/selfhost/teardown-gcp-bootstrap.ts @@ -33,12 +33,14 @@ export function bootstrapItems(ctx: TeardownContext, project: string): Item[] { (a, b) => [ 'iam-binding', + 'service-account-iam-binding', 'workload-identity-provider', 'workload-identity-pool', 'service-account', ].indexOf(a.kind) - [ 'iam-binding', + 'service-account-iam-binding', 'workload-identity-provider', 'workload-identity-pool', 'service-account', @@ -101,6 +103,8 @@ export function bootstrapItems(ctx: TeardownContext, project: string): Item[] { pool, entry.kind === 'service-account' ? entry.name : attrs.account ); + if (entry.kind === 'service-account-iam-binding') + assertServiceAccountGrant(ctx, project, entry); check(gcloud(ctx, remove), 'delete recorded resource'); }, record: entry, @@ -266,6 +270,29 @@ function bootstrapOperation(entry: CreatedResource, project: string, issuer: str description: `Creates and deletes SAM workspace VMs and their firewall rules for ${issuer}`, }; break; + case 'service-account-iam-binding': + if ( + !attrs.account || + !attrs.identity || + !attrs.member || + attrs.role !== 'roles/iam.workloadIdentityUser' + ) + throw new Error('refused: incomplete service account grant receipt'); + describe = ['iam', 'service-accounts', 'describe', attrs.account, ...where]; + remove = [ + 'iam', + 'service-accounts', + 'remove-iam-policy-binding', + attrs.account, + ...where, + `--member=${attrs.member}`, + `--role=${attrs.role}`, + '--condition=None', + '--quiet', + '--format=none', + ]; + expected = { uniqueId: attrs.identity }; + break; case 'iam-binding': { // Delete an exact grant only, never a project policy replacement. Creation receipt // is linked to the service account's immutable id, checked immediately beforehand. @@ -290,3 +317,62 @@ function bootstrapOperation(entry: CreatedResource, project: string, issuer: str } return { describe, remove, expected }; } + +/** Remove only the receipted unconditional member, even when the account itself was reused. */ +function assertServiceAccountGrant( + ctx: TeardownContext, + project: string, + entry: CreatedResource +): void { + const attrs = entry.attributes ?? {}; + const pools = ctx.record.filter( + (r) => + r.kind === 'workload-identity-pool' && + r.cloud === 'gcp' && + r.createdBy === BOOTSTRAP && + !r.removedAt && + r.name === attrs.pool && + r.attributes?.project === project && + r.attributes?.installation === ctx.installationId && + r.attributes?.environment === 'selfhost' && + r.attributes?.install === `https://api.${ctx.domain}` + ); + const identity = pools.length === 1 ? pools[0].attributes?.identity : undefined; + if ( + !identity || + !/^projects\/\d+\/locations\/global\/workloadIdentityPools\/[^/]+$/.test(identity) || + attrs.member !== `principalSet://iam.googleapis.com/${identity}/*` + ) + throw new Error('refused: service account grant pool identity changed'); + const policy = check( + gcloud(ctx, [ + 'iam', + 'service-accounts', + 'get-iam-policy', + attrs.account, + `--project=${project}`, + '--format=json', + ]), + 'read service account grant before deletion' + ); + try { + const value: unknown = JSON.parse(policy.stdout); + if (!value || typeof value !== 'object' || Array.isArray(value)) + throw new Error('Invalid policy'); + const bindings = (value as { bindings?: unknown }).bindings ?? []; + if ( + !Array.isArray(bindings) || + bindings.some( + (b) => + !b || + typeof b.role !== 'string' || + !Array.isArray(b.members) || + b.members.some((m: unknown) => typeof m !== 'string') || + (b.role === attrs.role && b.members.includes(attrs.member) && !!b.condition) + ) + ) + throw new Error('Invalid grant'); + } catch { + throw new Error('refused: unreadable or conditional service account grant'); + } +} diff --git a/scripts/selfhost/teardown-gcp-targets.ts b/scripts/selfhost/teardown-gcp-targets.ts new file mode 100644 index 0000000000..8da1799c39 --- /dev/null +++ b/scripts/selfhost/teardown-gcp-targets.ts @@ -0,0 +1,26 @@ +/** What a firewall rule applies to (gcloud `firewall-rules describe --format=json`). */ +export interface GcpFirewallTargets { + network: string | null; + targetTags: string[]; + /** Rules selecting by service account are not modelled: report them as unknown. */ + targetServiceAccounts: boolean; +} + +export function parseFirewallTargets(json: string): GcpFirewallTargets | null { + try { + const raw: unknown = JSON.parse(json); + if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return null; + const v = raw as Record; + const targetTags = Array.isArray(v.targetTags) + ? v.targetTags.filter((t): t is string => typeof t === 'string') + : []; + return { + network: typeof v.network === 'string' ? (v.network.split('/').pop() ?? v.network) : null, + targetTags, + targetServiceAccounts: + Array.isArray(v.targetServiceAccounts) && v.targetServiceAccounts.length > 0, + }; + } catch { + return null; + } +} diff --git a/scripts/selfhost/teardown-gcp.ts b/scripts/selfhost/teardown-gcp.ts index eac2d4f118..193cc569f3 100644 --- a/scripts/selfhost/teardown-gcp.ts +++ b/scripts/selfhost/teardown-gcp.ts @@ -20,8 +20,11 @@ import { gcloudNotFound, gcloudReason, } from './teardown-gcp-bootstrap'; +import { type GcpFirewallTargets, parseFirewallTargets } from './teardown-gcp-targets'; import { both, type Item, STEPS } from './teardown-model'; +export { parseFirewallTargets } from './teardown-gcp-targets'; + /** * The firewall rule names SAM's GCP provider ensures (SAM_AGENT_FIREWALL_RULE_NAME and * SAM_APP_ROUTE_FIREWALL_RULE_NAME in packages/providers/src/gcp-metadata.ts). Not imported: that @@ -46,14 +49,6 @@ interface GcpInstance { networks: string[]; } -/** What a firewall rule applies to (gcloud `firewall-rules describe --format=json`). */ -interface GcpFirewallTargets { - network: string | null; - targetTags: string[]; - /** Rules selecting by service account are not modelled: report them as unknown. */ - targetServiceAccounts: boolean; -} - export function gcpItems(ctx: TeardownContext): Item[] { const projects = new Set(ctx.options.gcpProjects); for (const r of ctx.record) { @@ -99,16 +94,14 @@ function listInstances(ctx: TeardownContext, project: string): GcpInstance[] | E '--format=json', ]); if (result.status !== 0) { - return new Error(`gcloud compute instances list failed: ${result.stderr.trim().slice(0, 400)}`); + return new Error(`gcloud compute instances list failed: ${gcloudReason(result.stderr)}`); } try { const parsed = JSON.parse(result.stdout) as unknown; if (!Array.isArray(parsed)) throw new Error('not a list'); return parseUniqueInstances(parsed); - } catch (error) { - return new Error( - `unreadable instance list: ${error instanceof Error ? error.message : String(error)}` - ); + } catch { + return new Error('unreadable instance list: invalid inventory metadata'); } } @@ -275,7 +268,12 @@ function deleteInstance(ctx: TeardownContext, project: string, listed: GcpInstan if (/not found|was not found|404/i.test(described.stderr)) return; // already gone check(described, `gcloud compute instances describe ${listed.name}`); } - const current = parseInstance(JSON.parse(described.stdout) as unknown); + let current: GcpInstance; + try { + current = parseInstance(JSON.parse(described.stdout) as unknown); + } catch { + throw new Error('refused: unreadable instance ownership metadata'); + } // The same VM (immutable id), still this install's, at the moment of deletion. if (current.id !== listed.id) { throw new Error( @@ -441,29 +439,8 @@ function listAllInstances(ctx: TeardownContext, project: string): GcpInstance[] const parsed = JSON.parse(result.stdout) as unknown; if (!Array.isArray(parsed)) throw new Error('not a list'); return parseUniqueInstances(parsed); - } catch (error) { - return new Error( - `unreadable instance list: ${error instanceof Error ? error.message : String(error)}` - ); - } -} - -export function parseFirewallTargets(json: string): GcpFirewallTargets | null { - try { - const raw: unknown = JSON.parse(json); - if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return null; - const v = raw as Record; - const targetTags = Array.isArray(v.targetTags) - ? v.targetTags.filter((t): t is string => typeof t === 'string') - : []; - return { - network: typeof v.network === 'string' ? lastSegment(v.network) : null, - targetTags, - targetServiceAccounts: - Array.isArray(v.targetServiceAccounts) && v.targetServiceAccounts.length > 0, - }; } catch { - return null; + return new Error('unreadable instance list: invalid inventory metadata'); } } diff --git a/scripts/selfhost/teardown.test.ts b/scripts/selfhost/teardown.test.ts index ca03ddd7e0..f6ad89c266 100644 --- a/scripts/selfhost/teardown.test.ts +++ b/scripts/selfhost/teardown.test.ts @@ -71,7 +71,10 @@ beforeEach(() => { ` const args=process.argv.slice(2), cmd=args.join(' '); fs.appendFileSync(process.env.CALLS, 'gcloud '+cmd+'\\n'); - if(cmd.startsWith('compute instances list')) console.log(process.env.VMS ?? '[]'); + if(cmd.startsWith('compute instances list')) { + if(process.env.LIST_ERROR) { console.error(process.env.LIST_ERROR);process.exit(1); } + console.log(process.env.VMS ?? '[]'); + } else if(cmd.startsWith('compute instances describe')) console.log(process.env.DESCRIBED ?? process.env.VM); else if(cmd.startsWith('compute instances delete')) {} else if(cmd.startsWith('compute firewall-rules describe')) { @@ -80,7 +83,8 @@ beforeEach(() => { } else if(cmd.startsWith('compute firewall-rules delete')) {} else if(cmd.startsWith('iam workload-identity-pools providers list')) console.log(process.env.FOREIGN==='pool' ? '[{"name":"foreign","oidc":{"issuerUri":"foreign"}}]' : '[]'); - else if(cmd.startsWith('iam service-accounts get-iam-policy')) console.log(process.env.FOREIGN==='account' ? '{"bindings":[{"role":"foreign","members":["foreign"]}]}' : '{}'); + else if(cmd.startsWith('iam service-accounts remove-iam-policy-binding')) {} + else if(cmd.startsWith('iam service-accounts get-iam-policy')) console.log(process.env.SA_POLICY ?? (process.env.FOREIGN==='account' ? '{"bindings":[{"role":"foreign","members":["foreign"]}]}' : '{}')); else if(cmd.startsWith('iam service-accounts keys list')) console.log('[]'); else if(cmd.startsWith('iam service-accounts describe')) console.log(JSON.stringify({uniqueId:'acct-id',description:'Creates and deletes SAM workspace VMs and their firewall rules for https://api.${DOMAIN}'})); else if(cmd.startsWith('iam workload-identity-pools providers describe')) console.log(JSON.stringify({name:'projects/123/locations/global/workloadIdentityPools/pool/providers/provider',oidc:{issuerUri:'https://api.${DOMAIN}'}})); @@ -229,6 +233,72 @@ function wifReceipts() { }); cloudReceipt('service-account', 'acct', { identity: 'acct-id', pool: 'pool' }); } +it.each(['keep-data', 'remove-everything', 'replaced', 'conditional', 'reused'])( + 'handles a receipted service account grant safely in %s mode', + async (mode) => { + const member = + 'principalSet://iam.googleapis.com/projects/123/locations/global/workloadIdentityPools/pool/*'; + cloudReceipt('workload-identity-pool', 'pool', { + identity: 'projects/123/locations/global/workloadIdentityPools/pool', + pool: 'pool', + }); + cloudReceipt('service-account-iam-binding', `acct#roles/iam.workloadIdentityUser#${member}`, { + account: 'acct', + identity: mode === 'replaced' ? 'old-account-id' : 'acct-id', + pool: 'pool', + member, + role: 'roles/iam.workloadIdentityUser', + }); + addResource(recordPath(state), { + cloud: 'gcp', + kind: 'service-account', + name: 'acct', + action: 'reused', + createdBy: 'gcp-bootstrap', + attributes: { + project: 'sam-test-proj', + install: `https://api.${DOMAIN}`, + environment: 'selfhost', + installation: OWN, + identity: 'acct-id', + pool: 'pool', + }, + }); + if (mode === 'reused') { + const record = JSON.parse(readFileSync(recordPath(state), 'utf8')); + record.resources.find( + (r: { kind: string }) => r.kind === 'service-account-iam-binding' + ).action = 'reused'; + writeFileSync(recordPath(state), JSON.stringify(record)); + } + const policy = { + bindings: [ + { + role: 'roles/iam.workloadIdentityUser', + members: [member], + ...(mode === 'conditional' ? { condition: { expression: 'true' } } : {}), + }, + ], + }; + const result = await run( + [mode === 'keep-data' ? '--keep-data' : '--remove-everything', '--confirm', DOMAIN], + { SA_POLICY: JSON.stringify(policy) } + ); + const removed = calls().includes('service-accounts remove-iam-policy-binding acct'); + expect(removed).toBe(mode === 'remove-everything'); + expect(result.status, result.out).toBe(mode === 'keep-data' ? 0 : 1); + expect(calls()).not.toContain('service-accounts delete acct'); + if (removed) { + expect(calls()).toContain( + `--member=${member} --role=roles/iam.workloadIdentityUser --condition=None` + ); + expect(calls().indexOf('service-accounts remove-iam-policy-binding acct')).toBeLessThan( + calls().indexOf('workload-identity-pools delete pool') + ); + } + } +); + it('removes recorded owned WIF resources and rechecks their current identity', async () => { wifReceipts(); const result = await run(['--remove-everything', '--confirm', DOMAIN]); @@ -285,6 +355,25 @@ it('deletes a real-trigger owned node while preserving an identically named fore expect(calls()).toContain('instances delete sam-node-same-prefix '); expect(calls()).not.toContain('instances delete sam-node-same-prefix-other'); }); +it.each(['list-error', 'invalid-list-json', 'invalid-describe-json'])( + 'sanitizes %s provider diagnostics at the real CLI boundary and retains state', + async (failure) => { + const sentinel = 'credential-sentinel-never-print-0123456789'; + const own = ownedVm(); + const result = await run(['--remove-everything', '--destroy-key', '--confirm', DOMAIN], { + VMS: failure === 'invalid-list-json' ? `{"${sentinel}` : JSON.stringify([own]), + VM: JSON.stringify(own), + ...(failure === 'list-error' ? { LIST_ERROR: `Authorization: Bearer ${sentinel}` } : {}), + ...(failure === 'invalid-describe-json' ? { DESCRIBED: `{"${sentinel}` } : {}), + }); + expect(result.status, result.out).toBe(1); + expect(result.out).not.toContain(sentinel); + expect(calls()).not.toMatch(/instances delete|firewall-rules delete/); + expect(existsSync(join(state, 'platform-keys.json'))).toBe(true); + expect(existsSync(env)).toBe(true); + } +); + it.each(['changed-id', 'changed-owner', 'duplicate', 'malformed'])( 'refuses %s VM inventory before destructive deletion', async (kind) => { diff --git a/scripts/selfhost/tsconfig.json b/scripts/selfhost/tsconfig.json index e27c50787b..1d38663b14 100644 --- a/scripts/selfhost/tsconfig.json +++ b/scripts/selfhost/tsconfig.json @@ -1,6 +1,13 @@ { "$schema": "https://json.schemastore.org/tsconfig", "extends": "../deploy/tsconfig.json", + "compilerOptions": { + "paths": { + "@/*": ["./*"], + "@simple-agent-manager/providers": ["../../packages/providers/src/index.ts"], + "@simple-agent-manager/shared": ["../../packages/shared/src/index.ts"] + } + }, "include": ["**/*.ts"], // live/ imports API modules that resolve workspace packages through their built dist/, so it // has its own project, checked by the Self-host Live job after it builds them. diff --git a/scripts/selfhost/upgrade-instructions.ts b/scripts/selfhost/upgrade-instructions.ts new file mode 100644 index 0000000000..dd10ae0888 --- /dev/null +++ b/scripts/selfhost/upgrade-instructions.ts @@ -0,0 +1,33 @@ +/** One executable recovery command for the current, populated, owned installation. */ +import type { BoxContext } from './upgrade-lib.js'; + +function shellWord(value: string): string { + return /^[\w@%+=:,./-]+$/.test(value) ? value : `'${value.replaceAll("'", `'\\''`)}'`; +} + +export function rollbackSteps( + ctx: Pick, + from: string, + backupDir: string, + imagesRebuilt: readonly string[] +): string[] { + return [ + [ + 'pnpm', + 'selfhost:upgrade', + '--to', + from, + '--rollback-from', + backupDir, + '--box-env', + ctx.envFile, + '--state-dir', + ctx.stateDir, + ...(ctx.secretsFile ? ['--secrets', ctx.secretsFile] : []), + ...(ctx.encryptionKeyFile ? ['--encryption-key-file', ctx.encryptionKeyFile] : []), + ...imagesRebuilt.flatMap((service) => ['--rebuild', service]), + ] + .map(shellWord) + .join(' '), + ]; +} diff --git a/scripts/selfhost/upgrade-lib.ts b/scripts/selfhost/upgrade-lib.ts index a3c5833149..ded10d72d6 100644 --- a/scripts/selfhost/upgrade-lib.ts +++ b/scripts/selfhost/upgrade-lib.ts @@ -23,6 +23,7 @@ import { COMPOSE_PATH, imageRebuilds } from './image-rebuilds.js'; import { assertOperatorExecution } from './operator-only.js'; import { assertPrivateFile, replacePrivateFile } from './secret-files.js'; import { composeInputsChanged, composeOverlays, stateFingerprint } from './upgrade-compose.js'; +import { rollbackSteps } from './upgrade-instructions.js'; import { assertMigrationProgression, type DoMigration, @@ -149,39 +150,6 @@ function deployBoxArgs(ctx: Pick - [ - ...(stateDir === null ? [] : [`SAM_SELFHOST_STATE_DIR=${shellWord(stateDir)}`]), - ['docker', ...composeArgs(ctx, args)].map(shellWord).join(' '), - ].join(' '); - return [ - '# Restore the encrypted snapshot into an empty installation; do not redeploy old code over migrated data.', - `git checkout --detach ${from}`, - 'pnpm install --frozen-lockfile', - `pnpm selfhost:restore --from ${shellWord(backupDir)} --box-env ${shellWord(ctx.envFile)} --state-dir ${shellWord(ctx.stateDir)}` + - (ctx.encryptionKeyFile ? ` --encryption-key-file ${shellWord(ctx.encryptionKeyFile)}` : ''), - ...(imagesRebuilt.length ? [compose(['build', ...imagesRebuilt])] : []), - compose(['up', '-d']), - ]; -} - function backupContext(ctx: BoxContext): BackupContext { return { ...ctx, @@ -191,14 +159,15 @@ function backupContext(ctx: BoxContext): BackupContext { } /** Restore before starting old code: even a failed deployment can already have migrated data. */ -async function recoverUpgrade( +export async function recoverUpgrade( ctx: BoxContext, from: string, backupDir: string, rebuilds: readonly string[], opts: UpgradeOptions ): Promise { - runRollback(backupContext(ctx), backupDir); + assertOperatorExecution(); + runRollback(backupContext(ctx), backupDir, from); replacePrivateFile( join(ctx.stateDir, UPGRADE_PENDING_FILE), `${JSON.stringify({ from, backupDir })}\n` diff --git a/scripts/selfhost/upgrade-rollback-cli.test.ts b/scripts/selfhost/upgrade-rollback-cli.test.ts new file mode 100644 index 0000000000..f9fc43d5c1 --- /dev/null +++ b/scripts/selfhost/upgrade-rollback-cli.test.ts @@ -0,0 +1,123 @@ +/** Execute the printed command through the real CLI and authenticated in-place recovery. */ +import { spawnSync } from 'node:child_process'; +import { randomBytes } from 'node:crypto'; +import { cpSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'; +import { join, resolve } from 'node:path'; + +import { afterEach, beforeEach, expect, it, vi } from 'vitest'; + +import { encryptBackupTree } from './backup-encryption'; +import { expectedComposeProjectFor, recordInstall } from './install-record'; +import { rollbackSteps } from './upgrade-instructions'; + +const FROM = 'a'.repeat(40); +let root: string; +beforeEach(() => { + for (const name of Object.keys(process.env)) { + if (name === 'CI' || name === 'GITHUB_ACTIONS' || name.startsWith('RUNNER_')) + vi.stubEnv(name, undefined); + } + mkdirSync(resolve('.tmp'), { recursive: true }); + root = mkdtempSync(resolve('.tmp/rollback-cli-')); +}); +afterEach(() => { + vi.unstubAllEnvs(); + rmSync(root, { recursive: true, force: true }); +}); + +it('executes the emitted populated-target rollback with real decryption, state restore and old checkout', () => { + const stateDir = join(root, 'custom state'); + const envFile = join(root, 'box.env'); + const key = join(root, 'backup-key'); + const snapshot = join(root, 'snapshot'); + const plain = join(root, 'plain'); + const bucket = join(root, 'bucket'); + mkdirSync(stateDir); + mkdirSync(bucket); + const box = { CELLD_BUCKET: 'gs://test/owned', SAM_DOMAIN: 'rollback.test' }; + writeFileSync(envFile, 'CELLD_BUCKET=gs://test/owned\nSAM_DOMAIN=rollback.test\n', { + mode: 0o600, + }); + writeFileSync(key, randomBytes(32), { mode: 0o600 }); + const id = 'b'.repeat(32); + writeFileSync(join(stateDir, 'platform-keys.json'), JSON.stringify({ SAM_INSTALLATION_ID: id })); + writeFileSync(join(stateDir, 'data'), 'old-state'); + recordInstall(stateDir, envFile, box, id); + mkdirSync(plain); + cpSync(stateDir, join(plain, 'state'), { recursive: true }); + cpSync(envFile, join(plain, 'env')); + mkdirSync(join(plain, 'bucket')); + writeFileSync(join(plain, 'bucket/data'), 'old-rows'); + writeFileSync( + join(plain, 'backup-manifest.json'), + JSON.stringify({ + version: 1, + createdAt: new Date().toISOString(), + bucket: box.CELLD_BUCKET, + samCommit: FROM, + precopyMs: 0, + downtimeMs: 0, + deltaCopyMs: 0, + objectCount: 1, + }) + ); + encryptBackupTree(plain, snapshot, key); + writeFileSync(join(stateDir, 'data'), 'new-state'); + writeFileSync(join(bucket, 'data'), 'new-rows'); + writeFileSync(join(bucket, 'new-only'), 'must disappear'); + const project = expectedComposeProjectFor(box, stateDir); + const preload = join(root, 'boundary.cjs'); + writeFileSync( + preload, + ` +const fs = require('node:fs'); +const cp = require('node:child_process'); +const { syncBuiltinESMExports } = require('node:module'); +const original = cp.spawnSync; +cp.spawnSync = (command, args, options) => { + if (!['git', 'pnpm', 'docker', 'gcloud'].includes(command)) return original(command,args,options); + fs.appendFileSync(${JSON.stringify(join(root, 'calls'))}, command+' '+args.join(' ')+'\\n'); + let stdout = ''; + if(command === 'git' && args[0] === 'rev-parse') stdout = 'b'.repeat(40); + if (command === 'docker') { + if(args.includes('ps')) stdout = 'c'.repeat(64); + if(args[0]==='inspect') stdout = JSON.stringify([{Destination:'/var/lib/celld', Type:'volume', Name:${JSON.stringify(`${project}_celld-data`)}}]); + if(args[0]==='volume' && args[1]==='ls') stdout = ${JSON.stringify(`${project}_celld-data`)}; + if(args[0]==='volume' && args[1]==='inspect') stdout = JSON.stringify([{Name:${JSON.stringify(`${project}_celld-data`)},CreatedAt:'2026-11-19T00:00:00Z',Labels:{'com.docker.compose.project':${JSON.stringify(project)},'com.docker.compose.volume':'celld-data'}}]); + if(args.includes('config')) stdout='celld\\ncaddy'; + } + if(command === 'gcloud') { + fs.rmSync(${JSON.stringify(bucket)}, {recursive:true,force:true}); + fs.cpSync(args.at(-2), ${JSON.stringify(bucket)}, {recursive:true}); + } + return {status:0,stdout,stderr:''}; +}; +syncBuiltinESMExports(); +globalThis.fetch = async () => new Response('healthy', {status:200}); +` + ); + const ctx = { box, stateDir, envFile, encryptionKeyFile: key }; + const command = rollbackSteps(ctx, FROM, snapshot, ['caddy'])[0]; + const tsx = resolve('node_modules/.bin/tsx'); + const cli = resolve('scripts/selfhost/upgrade.ts'); + const result = spawnSync( + 'bash', + ['-c', `pnpm() { shift; '${tsx}' '${cli}' "$@"; }; ${command}`], + { + encoding: 'utf8', + env: { ...process.env, NODE_OPTIONS: `--require=${preload}` }, + } + ); + expect(result.stderr).toBe(''); + expect(result.status).toBe(0); + expect(result.stdout).toContain('manual rollback completed'); + expect(readFileSync(join(stateDir, 'data'), 'utf8')).toBe('old-state'); + expect(readFileSync(join(bucket, 'data'), 'utf8')).toBe('old-rows'); + const calls = readFileSync(join(root, 'calls'), 'utf8'); + expect(calls.indexOf('gcloud storage rsync')).toBeLessThan( + calls.indexOf(`git checkout --detach ${FROM}`) + ); + expect(calls).toContain(`--project-name ${project}`); + expect(calls).toContain(' build caddy'); + expect(calls).toContain('container rm --force ' + 'c'.repeat(64)); +}, 60_000); diff --git a/scripts/selfhost/upgrade-rollback.test.ts b/scripts/selfhost/upgrade-rollback.test.ts new file mode 100644 index 0000000000..01250c1fe5 --- /dev/null +++ b/scripts/selfhost/upgrade-rollback.test.ts @@ -0,0 +1,165 @@ +/** The manual command enters the same populated-install recovery path as automatic rollback. */ +import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'; +import { join, resolve } from 'node:path'; + +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; + +import { runRollback } from './backup-lib.js'; +import { rollbackSteps } from './upgrade-instructions.js'; +import { type BoxContext, UPGRADE_PENDING_FILE } from './upgrade-lib.js'; +import { runManualRollback } from './upgrade-rollback.js'; + +vi.mock('./backup-lib.js', async (original) => ({ + ...(await original()), + runRollback: vi.fn(), +})); +vi.mock('./upgrade-preflight.js', async (original) => ({ + ...(await original()), + assertRollbackReady: vi.fn(), +})); + +const FROM = 'a'.repeat(40); +const OPERATOR_REF = 'b'.repeat(40); +let root: string; +let ctx: BoxContext; +let steps: string[]; +let stateEnvs: (string | undefined)[]; +let dirty: boolean; + +beforeEach(() => { + for (const name of Object.keys(process.env)) { + if (name === 'CI' || name === 'GITHUB_ACTIONS' || name.startsWith('RUNNER_')) + vi.stubEnv(name, undefined); + } + mkdirSync(resolve('.tmp'), { recursive: true }); + root = mkdtempSync(join(resolve('.tmp'), 'manual-rollback-')); + mkdirSync(join(root, 'state')); + writeFileSync(join(root, 'state/populated-data'), 'current installation data'); + steps = []; + stateEnvs = []; + dirty = false; + ctx = { + box: { COMPOSE_PROJECT_NAME: 'owned-manual' }, + envFile: join(root, 'box.env'), + stateDir: join(root, 'state'), + composeFiles: ['base.yml', 'overlay.yml'], + secretsFile: join(root, 'custom secrets'), + encryptionKeyFile: join(root, 'backup key'), + log: vi.fn(), + run: (command, args, env) => { + if (args[0] === 'status') return { status: 0, stdout: dirty ? ' M tracked' : '', stderr: '' }; + if (args[0] === 'rev-parse') return { status: 0, stdout: OPERATOR_REF, stderr: '' }; + steps.push(`${command} ${args.join(' ')}`); + if (command === 'docker') stateEnvs.push(env?.SAM_SELFHOST_STATE_DIR); + return { status: 0, stdout: args.includes('config') ? 'celld\ncaddy' : '', stderr: '' }; + }, + }; + vi.mocked(runRollback) + .mockReset() + .mockImplementation(() => { + steps.push('OWNED_SNAPSHOT_RESTORE'); + }); +}); +afterEach(() => { + vi.unstubAllEnvs(); + rmSync(root, { recursive: true, force: true }); +}); +const rollback = (checkHealth = async () => true) => + runManualRollback(ctx, { + from: FROM, + backupDir: join(root, 'snapshot'), + rebuilds: ['caddy', 'inactive-mail'], + checkHealth, + }); + +describe('manual owned rollback', () => { + it('recovers a populated install before old code starts, builds only active images and verifies health', async () => { + const health = vi.fn(async () => { + steps.push('HEALTH'); + return true; + }); + await rollback(health); + expect(runRollback).toHaveBeenCalledWith(expect.anything(), join(root, 'snapshot'), FROM); + expect(steps[0]).toBe('OWNED_SNAPSHOT_RESTORE'); + expect(steps[1]).toBe(`git checkout --detach ${FROM}`); + expect(steps[2]).toBe('pnpm install --frozen-lockfile'); + expect(steps.filter((step) => step.includes(' build '))).toEqual([ + expect.stringContaining(' build caddy'), + ]); + expect(steps.some((step) => step.includes('inactive-mail'))).toBe(false); + expect(steps.at(-2)).toMatch(/--project-name owned-manual .* -f overlay.yml .* up -d$/); + expect(steps.at(-1)).toBe('HEALTH'); + expect(stateEnvs.every((value) => value === ctx.stateDir)).toBe(true); + expect(existsSync(join(ctx.stateDir, UPGRADE_PENDING_FILE))).toBe(false); + expect(health).toHaveBeenCalledOnce(); + }); + + it('keeps pending recovery and stops this custom state install if restored health fails', async () => { + await expect(rollback(async () => false)).rejects.toThrow(/Manual rollback did not complete/); + const pending = JSON.parse( + readFileSync(join(ctx.stateDir, UPGRADE_PENDING_FILE), 'utf8') + ) as unknown; + expect(pending).toEqual({ from: FROM, backupDir: join(root, 'snapshot') }); + expect(steps.at(-3)).toMatch(/ stop celld$/); + expect(steps.slice(-2)).toEqual([ + `git checkout --detach ${OPERATOR_REF}`, + 'pnpm install --frozen-lockfile', + ]); + expect(stateEnvs.at(-1)).toBe(ctx.stateDir); + }); + + it('never starts old code when owned snapshot restoration refuses', async () => { + vi.mocked(runRollback).mockImplementation(() => { + throw new Error('private-value-never-print'); + }); + await expect(rollback()).rejects.toThrow( + 'Manual rollback did not complete; keep celld stopped and retry the same rollback command' + ); + expect(steps).not.toContain(`git checkout --detach ${FROM}`); + expect(steps.at(-3)).toMatch(/ stop celld$/); + expect(JSON.stringify(vi.mocked(ctx.log).mock.calls)).not.toContain('private-value'); + }); + + it('refuses a dirty checkout before restoring any data', async () => { + dirty = true; + await expect(rollback()).rejects.toThrow(/clean tracked checkout/); + expect(runRollback).not.toHaveBeenCalled(); + expect(steps).toEqual([]); + }); + + it.each([ + { from: 'main', rebuilds: [] }, + { from: FROM, rebuilds: ['--unsafe'] }, + ])('refuses ambiguous commit/service parameters before mutation', async (options) => { + await expect( + runManualRollback(ctx, { + ...options, + backupDir: join(root, 'snapshot'), + checkHealth: async () => true, + }) + ).rejects.toThrow(/original full commit SHA/); + expect(runRollback).not.toHaveBeenCalled(); + expect(steps).toEqual([]); + }); + + it.each(['CI', 'GITHUB_ACTIONS', 'RUNNER_TEMP'])( + 'refuses %s before touching a populated installation', + async (name) => { + vi.stubEnv(name, ''); + await expect(rollback()).rejects.toThrow(/forbidden in CI/); + expect(runRollback).not.toHaveBeenCalled(); + expect(steps).toEqual([]); + } + ); + + it('prints one executable in-place rollback command with exact commit, snapshot, box, state, key, secrets and affected images', () => { + const [command] = rollbackSteps(ctx, FROM, join(root, "snap's hot"), ['caddy']); + expect(command).toContain(`pnpm selfhost:upgrade --to ${FROM} --rollback-from`); + expect(command).toContain(`--box-env ${ctx.envFile} --state-dir ${ctx.stateDir}`); + expect(command).toContain( + `--secrets '${ctx.secretsFile}' --encryption-key-file '${ctx.encryptionKeyFile}' --rebuild caddy` + ); + expect(command).toContain("'\\''"); + expect(command).not.toMatch(/selfhost:restore|git checkout|docker compose/); + }); +}); diff --git a/scripts/selfhost/upgrade-rollback.ts b/scripts/selfhost/upgrade-rollback.ts new file mode 100644 index 0000000000..1fc1eaa629 --- /dev/null +++ b/scripts/selfhost/upgrade-rollback.ts @@ -0,0 +1,60 @@ +/** Explicit in-place rollback reuses upgrade's owned snapshot recovery and health checks. */ +import { rmSync } from 'node:fs'; +import { join } from 'node:path'; + +import { composeArgs, composeRunEnv } from './backup-lib.js'; +import { assertOperatorExecution } from './operator-only.js'; +import { type BoxContext, recoverUpgrade, UPGRADE_PENDING_FILE } from './upgrade-lib.js'; +import { assertRollbackReady } from './upgrade-preflight.js'; + +export interface ManualRollbackOptions { + from: string; + backupDir: string; + rebuilds: string[]; + checkHealth: () => Promise; +} + +export async function runManualRollback( + ctx: BoxContext, + opts: ManualRollbackOptions +): Promise { + assertOperatorExecution(); + if ( + !/^[a-f0-9]{40}$/.test(opts.from) || + opts.rebuilds.some((name) => !/^[a-zA-Z0-9][a-zA-Z0-9_.-]*$/.test(name)) + ) { + throw new Error('Rollback needs the original full commit SHA and valid service names'); + } + assertRollbackReady(ctx); + const status = ctx.run('git', ['status', '--porcelain', '--untracked-files=no']); + if (status.status !== 0 || status.stdout.trim()) + throw new Error('Rollback requires a clean tracked checkout'); + const head = ctx.run('git', ['rev-parse', 'HEAD']); + const operatorRef = head.stdout.trim(); + if (head.status !== 0 || !/^[a-f0-9]{40}$/.test(operatorRef)) + throw new Error('Cannot verify the operator checkout for rollback retry'); + try { + await recoverUpgrade(ctx, opts.from, opts.backupDir, opts.rebuilds, { + to: opts.from, + checkHealth: opts.checkHealth, + }); + rmSync(join(ctx.stateDir, UPGRADE_PENDING_FILE), { force: true }); + ctx.log('manual rollback completed; previous installation is healthy'); + } catch { + try { + ctx.run('docker', composeArgs(ctx, ['stop', 'celld']), composeRunEnv(ctx)); + } catch { + /* best effort */ + } + try { + const checkout = ctx.run('git', ['checkout', '--detach', operatorRef]); + if (checkout.status === 0) ctx.run('pnpm', ['install', '--frozen-lockfile']); + } catch { + /* best effort; keep the application stopped */ + } + throw new Error( + 'Manual rollback did not complete; keep celld stopped and retry the same rollback command. ' + + `If the helper is unavailable, restore operator checkout ${operatorRef} and run pnpm install --frozen-lockfile first` + ); + } +} diff --git a/scripts/selfhost/upgrade-safeguards.test.ts b/scripts/selfhost/upgrade-safeguards.test.ts index 672953ae9a..ea64f36b94 100644 --- a/scripts/selfhost/upgrade-safeguards.test.ts +++ b/scripts/selfhost/upgrade-safeguards.test.ts @@ -256,7 +256,7 @@ describe('runUpgrade', () => { diff = ['apps/api/src/db/migrations/0300_new.sql']; failCommand = command; await expect(upgrade()).rejects.toThrow(/command output withheld/); - expect(runRollback).toHaveBeenCalledWith(expect.anything(), join(root, 'backup')); + expect(runRollback).toHaveBeenCalledWith(expect.anything(), join(root, 'backup'), FROM); expect(steps.indexOf('RESTORE')).toBeLessThan(steps.indexOf(`git checkout --detach ${FROM}`)); expect(steps.at(-1)).toMatch(/^docker compose .* up -d$/); expect(logs.join('\n')).toContain('automatic rollback completed'); diff --git a/scripts/selfhost/upgrade.test.ts b/scripts/selfhost/upgrade.test.ts index d5916f7655..5c13e827e2 100644 --- a/scripts/selfhost/upgrade.test.ts +++ b/scripts/selfhost/upgrade.test.ts @@ -186,7 +186,7 @@ describe('runUpgrade', () => { ]); expect(result.composeRestarted).toBe(false); expect(runBackup).toHaveBeenCalledOnce(); - expect(result.rollback.join('\n')).toContain('selfhost:restore'); + expect(result.rollback.join('\n')).toContain('--rollback-from'); }); it('restarts the stack between --init and the deploy when a compose file changed', async () => { @@ -228,7 +228,7 @@ describe('runUpgrade', () => { expect( rollback.some( (step) => - step.includes('selfhost:restore') && step.includes('--box-env /custom/box.env') + step.includes('--rollback-from') && step.includes('--box-env /custom/box.env') ) ).toBe(true); }); @@ -248,8 +248,8 @@ describe('runUpgrade', () => { diff = ['apps/api/src/db/migrations/0300_new.sql']; const result = await upgrade(); expect(result.migrationsChanged).toBe(true); - expect(result.rollback.join('\n')).toContain('do not redeploy old code'); - expect(result.rollback.join('\n')).toContain('selfhost:restore'); + expect(result.rollback.join('\n')).toContain(`selfhost:upgrade --to ${FROM}`); + expect(result.rollback.join('\n')).toContain('--rollback-from'); }); it('stops at a failed deploy and prints the rollback', async () => { @@ -304,8 +304,9 @@ describe('runUpgrade', () => { writeFileSync(join(root, 'state/gateway.env'), 'before'); failDeploy = false; const rollback = (await upgrade()).rollback; - expect(rollback.some((step) => step.includes('selfhost:restore'))).toBe(true); - expect(rollback.some((step) => /^docker compose .* up -d$/.test(step))).toBe(true); + expect(rollback.some((step) => step.includes('--rollback-from'))).toBe(true); + expect(rollback).toHaveLength(1); + expect(rollback[0]).toContain(`--to ${FROM}`); }); it('fails when the API is unhealthy after the deploy', async () => { @@ -395,12 +396,10 @@ describe('runUpgrade with the box .env COMPOSE_FILE', () => { diff = ['deploy/selfhost/docker-compose.yml']; const ctx = boxFromEnv(['COMPOSE_FILE=docker-compose.yml:docker-compose.override.yml']); const result = await runUpgrade(ctx, { to: 'v1', checkHealth: async () => true }); - const composeSteps = result.rollback.filter((step) => step.includes('docker compose')); - expect(composeSteps.map((step) => step.replaceAll(root, ''))).toEqual([ - `docker compose --project-name sam-test -f ${join(SELFHOST_DIR, 'docker-compose.yml')} ` + - `-f ${join(SELFHOST_DIR, 'docker-compose.override.yml')} ` + - `--env-file /real.env up -d`, - ]); + expect(result.rollback).toHaveLength(1); + expect(result.rollback[0]).toContain(`--box-env ${ctx.envFile}`); + expect(result.rollback[0]).toContain(`--state-dir ${ctx.stateDir}`); + expect(result.rollback[0]).not.toContain('selfhost:restore'); }); it('selects the same box in the restore-based rollback, quoting a path with a space', async () => { @@ -413,12 +412,10 @@ describe('runUpgrade with the box .env COMPOSE_FILE', () => { ); const ctx = { ...loadBox(envFile, join(root, 'state')), run, log: (m: string) => logs.push(m) }; const { rollback } = await runUpgrade(ctx, { to: 'v1', checkHealth: async () => true }); - const file = join(SELFHOST_DIR, 'docker-compose.yml'); expect(rollback.join('\n')).toContain(`--box-env '${envFile}'`); - expect(rollback).toContain( - `docker compose --project-name sam-test -f ${file} --env-file '${envFile}' up -d` - ); - expect(rollback.join('\n')).toContain('empty installation'); + expect(rollback.join('\n')).toContain(`--to ${FROM}`); + expect(rollback.join('\n')).toContain('--rollback-from'); + expect(rollback.join('\n')).not.toContain('selfhost:restore'); }); // COMPOSE_FILE may list a file outside deploy/selfhost; a change to it alone must restart. @@ -449,8 +446,8 @@ describe('runUpgrade with the box .env COMPOSE_FILE', () => { `--env-file /real.env build caddy`; expect(steps).toContain(build); const rollback = result.rollback.map((step) => step.replaceAll(root, '')); - expect(rollback.indexOf(build)).toBeGreaterThan(-1); - expect(rollback.indexOf(build)).toBeLessThan(rollback.findIndex((s) => s.endsWith(' up -d'))); + expect(rollback[0]).toContain('--rebuild caddy'); + expect(rollback[0]).toContain('--box-env /real.env'); }); }); @@ -477,11 +474,7 @@ describe('runUpgrade with a state dir docker compose would not read on its own', const state = join(root, 'state'); expect(dockerStateEnv.length).toBeGreaterThan(1); expect(dockerStateEnv.every((value) => value === state)).toBe(true); - const printed = result.rollback.filter((step) => step.includes('docker compose')); - expect(printed.length).toBeGreaterThan(0); - expect(printed.every((step) => step.startsWith(`SAM_SELFHOST_STATE_DIR=${state} docker`))).toBe( - true - ); + expect(result.rollback[0]).toContain(`--state-dir ${state}`); }); it('control: sets nothing when the .env already names that state dir', async () => { @@ -492,7 +485,7 @@ describe('runUpgrade with a state dir docker compose would not read on its own', }); expect(dockerStateEnv.length).toBeGreaterThan(1); expect(dockerStateEnv.every((value) => value === undefined)).toBe(true); - expect(result.rollback.some((step) => step.startsWith('docker compose'))).toBe(true); + expect(result.rollback[0]).toContain(`--state-dir ${join(root, 'state')}`); expect(result.rollback.some((step) => step.includes('SAM_SELFHOST_STATE_DIR='))).toBe(false); }); }); @@ -566,18 +559,8 @@ describe('runUpgrade image builds', () => { expect(result.imagesRebuilt).toEqual(['caddy']); // Rolling back rebuilds the old image the same explicit way. const rollback = result.rollback.map((step) => step.replaceAll(root, '')); - expect(rollback).toContain( - 'docker compose --project-name sam-test -f compose.yml --env-file /box.env build caddy' - ); - expect( - rollback.indexOf( - 'docker compose --project-name sam-test -f compose.yml --env-file /box.env build caddy' - ) - ).toBeLessThan( - rollback.indexOf( - 'docker compose --project-name sam-test -f compose.yml --env-file /box.env up -d' - ) - ); + expect(rollback[0]).toContain('--rebuild caddy'); + expect(rollback[0]).toContain('--box-env /box.env'); }); it('rebuilds caddy when the compose build args changed (a new pinned module)', async () => { diff --git a/scripts/selfhost/upgrade.ts b/scripts/selfhost/upgrade.ts index 7b8c60a54e..0a2eb82f2f 100644 --- a/scripts/selfhost/upgrade.ts +++ b/scripts/selfhost/upgrade.ts @@ -12,6 +12,7 @@ import { parseArgs } from 'node:util'; import { celldPort, SELFHOST_DIR, waitForHealth } from './deploy-steps.js'; import { assertOperatorExecution } from './operator-only.js'; import { loadBox, runUpgrade } from './upgrade-lib.js'; +import { runManualRollback } from './upgrade-rollback.js'; assertOperatorExecution(); @@ -22,6 +23,8 @@ const { values } = parseArgs({ 'state-dir': { type: 'string' }, secrets: { type: 'string' }, 'backup-to': { type: 'string' }, + 'rollback-from': { type: 'string' }, + rebuild: { type: 'string', multiple: true }, 'encryption-key-file': { type: 'string' }, }, }); @@ -35,15 +38,27 @@ const ctx = loadBox( ); const port = celldPort(ctx.box); -await runUpgrade(ctx, { - to: values.to, - ...(values['backup-to'] ? { backupDir: resolve(values['backup-to']) } : {}), - checkHealth: async () => { - try { - await waitForHealth(port, ctx.box.SAM_DOMAIN ?? ''); - return true; - } catch { - return false; - } - }, -}); +const checkHealth = async () => { + try { + await waitForHealth(port, ctx.box.SAM_DOMAIN ?? ''); + return true; + } catch { + return false; + } +}; + +if (values['rollback-from']) { + await runManualRollback(ctx, { + from: values.to, + backupDir: resolve(values['rollback-from']), + rebuilds: values.rebuild ?? [], + checkHealth, + }); +} else { + if (values.rebuild?.length) throw new Error('--rebuild is only used with --rollback-from'); + await runUpgrade(ctx, { + to: values.to, + ...(values['backup-to'] ? { backupDir: resolve(values['backup-to']) } : {}), + checkHealth, + }); +} diff --git a/tasks/active/2026-11-19-l24-selfhost-operations.md b/tasks/active/2026-11-19-l24-selfhost-operations.md index 044aec6eff..95032ddfb9 100644 --- a/tasks/active/2026-11-19-l24-selfhost-operations.md +++ b/tasks/active/2026-11-19-l24-selfhost-operations.md @@ -65,3 +65,13 @@ Claim987d8996 after L23FREE2a876ebc. Original shared checkoute7ac643b/fourcontai F23: retrieved the original failed stopped-copy gcloud log2026.11.19/21.46.12.578974.log read-only. Trace reaches SDK523 file_download_task.execute -> posix_util.run_if_setting_posix -> set_posix_attributes_on_file_if_valid -> get_posix_attributes_from_file/os.stat, then ENOENT for local nodes/node_*.json. Log has9HTTP404 occurrences, atime/mtime POSIX metadata, no hash mismatch. SDK source proves finalize_download returnsFalse when temporary download missing, but caller ignores return and applies POSIX metadata/stat. Root failure mechanism is missing download followed by POSIX stat; tracker reuse alone remains unproved. Historical fresh retry succeeded4251objects, confirming intermittent behavior. Old plaintext diagnostic tree removed. New isolated live paths/temp cleanup/fresh full-copy fallback avoid partial-download reuse; targeted GCS POSIX ENOENT regression verifies complete final data/no partial node artifact and restarted writer. Live found adjacent writer-selection bug: shell COMPOSE_PROJECT_NAME ignored with a legacy YAML whose name was static. Compose stop on nonexistent derived project returns0, so no writer had stopped. Fixed always-control precedence and fail-before-copy singleton running-writer observation;114 focused and full578tests, realDocker2, scanner187,tsc/eslint pass. Finalcommit/retest pending. Explicit private target env instead of shared edit yielded real encrypted backup4270objects, down4919ms, authentication success, original API200. Restore to fresh owned /restore prefix complete;4270objects including3701LTX +476statefiles SHA256 compared exactly, source receipts stripped. Restore app not started (avoid shared background alarms). Init/disposableupgrade/teardown/refusal still owed. + +## BOX final backup/restore and valid upgrade + +Final f546 backup:4,324objects,5,824ms downtime, authenticated encrypted tree. Fresh /restore-final prefix and fresh state:4,324objects/3,756LTX/476statefiles exactly match SHA256 inventories. No restored shared alarms started. Actual shared H2 live deployment manifest and source tags reject main's unknown/removed selfhost-hosted-git-v1 before mutation. Separate fresh main worktree/state/env/project sam-selfhost-062a6279cc37 deployed4c415, then actual upgrade to f546 passed encrypted806object snapshot, installed-vs-live-vs-target DO check and API health. Shared checkout e7ac and four original services remain unchanged/healthy. + +## Ready review followup + +CodeRabbit requested23:03UTC via trusted label workflow, returned review limit/rate-limit; wait ended, no findings from it. Codex review found3 issues, fixed before final candidate: retry cache deletion after transient restoration failure; executable populated-install manual rollback bound to authenticated snapshot source SHA; exact created/reused workloadIdentityUser service-account grant receipts and cleanup. Recovery now stages state before swap, retains upgrade recovery pointer, writes private exact cache-deletion progress so partial deletion can retry, refuses replacement cache identities. 53backup tests pass; deleting pending-cache consumption makes the transient-volume retry control fail (RED), source restored. Independent recovery security review PASS. Teardown diagnostic stderr/JSON never surfaces raw cloud content;3actualCLI sentinel controls pass. Clean CI deploy validation exposed unbuilt providers dependency from existing node-provider-labels import; selfhost-only tsconfig resolves provider/shared sources directly, no runtime/Worker change. + +Full current review suite602tests/32filesPASS; latest manual command tests add real emitted CLI entrypoint and operator-checkout recovery on failed rollback. Disposable final rollback/teardown/cleanup and exact-head release gates pending. From cd2e646af11a6b721397932f6b6a2ad09ed6ee13 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rapha=C3=ABl=20Titsworth-Morin?= Date: Thu, 19 Nov 2026 23:28:03 +0000 Subject: [PATCH 06/17] fix(selfhost): retain rollback progress until recovered service is healthy --- scripts/selfhost/backup-lib.ts | 7 +- scripts/selfhost/backup-recovery.ts | 22 +++++- scripts/selfhost/backup.test.ts | 33 ++++++++ scripts/selfhost/upgrade-lib.ts | 20 ++++- scripts/selfhost/upgrade-rollback.test.ts | 76 ++++++++++++++++++- scripts/selfhost/upgrade-safeguards.test.ts | 2 + scripts/selfhost/upgrade.test.ts | 2 + .../2026-11-19-l24-selfhost-operations.md | 2 + 8 files changed, 160 insertions(+), 4 deletions(-) diff --git a/scripts/selfhost/backup-lib.ts b/scripts/selfhost/backup-lib.ts index 9b4b58ac61..46bd6737bf 100644 --- a/scripts/selfhost/backup-lib.ts +++ b/scripts/selfhost/backup-lib.ts @@ -489,4 +489,9 @@ export function runRestore(ctx: BoxContext, from: string): BackupManifest { export { readManifest } from './backup-manifest'; export { assertBackupOutside } from './backup-paths'; -export { assertRollbackCacheReady, runRollback } from './backup-recovery'; +export { + assertRollbackCacheReady, + finishRollbackCache, + refreshRollbackCacheReceipt, + runRollback, +} from './backup-recovery'; diff --git a/scripts/selfhost/backup-recovery.ts b/scripts/selfhost/backup-recovery.ts index ae6e2f20a2..c558625b63 100644 --- a/scripts/selfhost/backup-recovery.ts +++ b/scripts/selfhost/backup-recovery.ts @@ -239,7 +239,27 @@ function discardCelldCache(ctx: BoxContext, expected: RollbackCacheProof, from: throw new Error('Rollback celld cache identity changed; refusing removal'); check(ctx.run('docker', ['volume', 'rm', expected.name]), 'remove owned celld cache'); } - rmSync(join(ctx.stateDir, CACHE_PENDING)); + // recoverUpgrade keeps this receipt until old code and dependencies are healthy. +} + +/** After an authorized Compose recreation, bind retry to its newly observed exact cache. */ +export function refreshRollbackCacheReceipt(ctx: BoxContext, from: string): void { + assertOperatorExecution(); + if (!pendingCache(ctx, from)) throw new Error('Missing rollback cache recovery receipt'); + const proof = assertRollbackCacheReady(ctx); + replacePrivateFile( + join(ctx.stateDir, CACHE_PENDING), + JSON.stringify({ ...proof, snapshot: resolve(from) }) + ); +} + +/** Clear progress only after the recovered installation has passed its health check. */ +export function finishRollbackCache(ctx: BoxContext): void { + assertOperatorExecution(); + assertRollbackReady(ctx); + const path = join(ctx.stateDir, CACHE_PENDING); + assertPrivateFile(path); + rmSync(path); } /** Stage the full replacement before swapping directories; failed copying retains live state. */ function restoreState( diff --git a/scripts/selfhost/backup.test.ts b/scripts/selfhost/backup.test.ts index 8b8ec13bb5..c88b9e27b4 100644 --- a/scripts/selfhost/backup.test.ts +++ b/scripts/selfhost/backup.test.ts @@ -37,6 +37,7 @@ import { type RunResult, runRollback, } from './backup-lib'; +import { finishRollbackCache, refreshRollbackCacheReceipt } from './backup-recovery'; import { buildCelldConfig } from './celld-config'; import { prepareCelldProject, writeCelldConfig } from './celld-project'; import { composeProjectFor, expectedComposeProjectFor, recordInstall } from './install-record'; @@ -643,6 +644,34 @@ describe('runRollback', () => { ); }); + it('keeps completed cache progress until recovered code is healthy and refreshes a recreated cache', () => { + const context = ctx('gs://fleet/celld', join(root, 'state')); + const snapshot = join(root, 'post-data-retry'); + runBackup(context, snapshot); + runRollback(context, snapshot); + const journal = join(context.stateDir, 'rollback-cache-pending.json'); + expect(existsSync(journal)).toBe(true); + const invoke = context.run; + context.run = (command, args, env) => { + if ( + command === 'docker' && + args[0] === 'compose' && + args.includes('ps') && + args.includes('-q') + ) + return { status: 0, stdout: '', stderr: '' }; + if (command === 'docker' && args[0] === 'volume' && args[1] === 'ls') + return { status: 0, stdout: '', stderr: '' }; + return invoke(command, args, env); + }; + expect(() => runRollback(context, snapshot)).not.toThrow(); + context.run = invoke; + expect(() => refreshRollbackCacheReceipt(context, snapshot)).not.toThrow(); + expect(JSON.parse(readFileSync(journal, 'utf8')).container).toBe('c'.repeat(64)); + finishRollbackCache(context); + expect(existsSync(journal)).toBe(false); + }); + it('binds a manual rollback to the authenticated source commit before mutation', () => { const context = ctx('gs://fleet/celld', join(root, 'state')); const snapshot = join(root, 'wrong-code-snapshot'); @@ -717,6 +746,8 @@ describe('runRollback', () => { expect(() => runRollback(context, snapshot)).not.toThrow(); expect(failed).toBe(true); expect(readFileSync(join(root, 'store/fleet/celld/current.json'), 'utf8')).toBe('{"v":3}'); + expect(existsSync(join(context.stateDir, 'rollback-cache-pending.json'))).toBe(true); + finishRollbackCache(context); expect(existsSync(join(context.stateDir, 'rollback-cache-pending.json'))).toBe(false); } ); @@ -928,6 +959,8 @@ describe('runRollback', () => { }; const stateReceipt = restoredRecord.resources.find((resource) => resource.kind === 'state-dir'); expect(stateReceipt?.attributes.inode).toBe(String(statSync(join(root, 'state')).ino)); + expect(actualState['rollback-cache-pending.json']).toBeDefined(); + delete actualState['rollback-cache-pending.json']; delete actualState['created-resources.json']; delete expectedState['created-resources.json']; expect(actualState).toEqual(expectedState); diff --git a/scripts/selfhost/upgrade-lib.ts b/scripts/selfhost/upgrade-lib.ts index ded10d72d6..2cb690971d 100644 --- a/scripts/selfhost/upgrade-lib.ts +++ b/scripts/selfhost/upgrade-lib.ts @@ -13,6 +13,8 @@ import { type BoxContext as BackupContext, composeArgs, composeRunEnv, + finishRollbackCache, + refreshRollbackCacheReceipt, runBackup, runRollback, } from './backup-lib.js'; @@ -190,8 +192,24 @@ export async function recoverUpgrade( 'rebuild previous images' ); } - check(ctx.run('docker', composeArgs(ctx, ['up', '-d']), env), 'restore previous stack'); + startRecoveredStack(ctx, backupDir, env); if (!(await opts.checkHealth())) throw new Error('previous version health check failed'); + finishRollbackCache(backupContext(ctx)); +} + +/** A partial start may have replaced the cache; retain its exact identity for another retry. */ +function startRecoveredStack(ctx: BoxContext, backupDir: string, env?: NodeJS.ProcessEnv): void { + try { + check(ctx.run('docker', composeArgs(ctx, ['up', '-d']), env), 'restore previous stack'); + } catch (error) { + try { + refreshRollbackCacheReceipt(backupContext(ctx), backupDir); + } catch { + // Preserve the original start error when no replacement cache can yet be proven. + } + throw error; + } + refreshRollbackCacheReceipt(backupContext(ctx), backupDir); } /** The ref an unfinished upgrade started from (`UPGRADE_PENDING_FILE`), or null. */ diff --git a/scripts/selfhost/upgrade-rollback.test.ts b/scripts/selfhost/upgrade-rollback.test.ts index 01250c1fe5..03696d41de 100644 --- a/scripts/selfhost/upgrade-rollback.test.ts +++ b/scripts/selfhost/upgrade-rollback.test.ts @@ -4,7 +4,7 @@ import { join, resolve } from 'node:path'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; -import { runRollback } from './backup-lib.js'; +import { finishRollbackCache, refreshRollbackCacheReceipt, runRollback } from './backup-lib.js'; import { rollbackSteps } from './upgrade-instructions.js'; import { type BoxContext, UPGRADE_PENDING_FILE } from './upgrade-lib.js'; import { runManualRollback } from './upgrade-rollback.js'; @@ -12,6 +12,8 @@ import { runManualRollback } from './upgrade-rollback.js'; vi.mock('./backup-lib.js', async (original) => ({ ...(await original()), runRollback: vi.fn(), + refreshRollbackCacheReceipt: vi.fn(), + finishRollbackCache: vi.fn(), })); vi.mock('./upgrade-preflight.js', async (original) => ({ ...(await original()), @@ -38,6 +40,8 @@ beforeEach(() => { steps = []; stateEnvs = []; dirty = false; + vi.mocked(refreshRollbackCacheReceipt).mockReset(); + vi.mocked(finishRollbackCache).mockReset(); ctx = { box: { COMPOSE_PROJECT_NAME: 'owned-manual' }, envFile: join(root, 'box.env'), @@ -73,6 +77,76 @@ const rollback = (checkHealth = async () => true) => }); describe('manual owned rollback', () => { + it('retries after dependency failure with the removed cache receipt still retained', async () => { + const receipt = join(ctx.stateDir, 'rollback-cache-pending.json'); + let removed = false; + vi.mocked(runRollback).mockImplementation(() => { + if (removed && !existsSync(receipt)) throw new Error('cache absent without proof'); + removed = true; + writeFileSync(receipt, 'exact original cache proof'); + }); + vi.mocked(finishRollbackCache).mockImplementation(() => rmSync(receipt)); + const runner = ctx.run; + let failInstall = true; + ctx.run = (command, args, env) => { + if (command === 'pnpm' && args[0] === 'install' && failInstall) { + failInstall = false; + return { status: 1, stdout: '', stderr: 'withheld' }; + } + return runner(command, args, env); + }; + await expect(rollback()).rejects.toThrow(/Manual rollback did not complete/); + expect(existsSync(receipt)).toBe(true); + expect(refreshRollbackCacheReceipt).not.toHaveBeenCalled(); + expect(finishRollbackCache).not.toHaveBeenCalled(); + await rollback(); + expect(runRollback).toHaveBeenCalledTimes(2); + expect(finishRollbackCache).toHaveBeenCalledOnce(); + expect(existsSync(receipt)).toBe(false); + }); + + it('retains the new cache proof through a failed health check and finishes only after healthy retry', async () => { + const receipt = join(ctx.stateDir, 'rollback-cache-pending.json'); + vi.mocked(refreshRollbackCacheReceipt).mockImplementation(() => { + expect(steps.at(-1)).toMatch(/ up -d$/); + writeFileSync(receipt, 'new container and cache creation proof'); + }); + vi.mocked(finishRollbackCache).mockImplementation(() => rmSync(receipt)); + await expect(rollback(async () => false)).rejects.toThrow(/Manual rollback did not complete/); + expect(readFileSync(receipt, 'utf8')).toContain('new container'); + expect(finishRollbackCache).not.toHaveBeenCalled(); + await rollback(async () => { + expect(existsSync(receipt)).toBe(true); + return true; + }); + expect(refreshRollbackCacheReceipt).toHaveBeenCalledTimes(2); + expect(existsSync(receipt)).toBe(false); + }); + + it('refreshes ownership after partial Compose startup but never finishes its failed recovery', async () => { + const runner = ctx.run; + ctx.run = (command, args, env) => { + const result = runner(command, args, env); + return args.includes('up') ? { ...result, status: 1 } : result; + }; + await expect(rollback()).rejects.toThrow(/Manual rollback did not complete/); + expect(refreshRollbackCacheReceipt).toHaveBeenCalledWith( + expect.anything(), + join(root, 'snapshot') + ); + expect(finishRollbackCache).not.toHaveBeenCalled(); + }); + + it('does not declare a healthy rollback when the replacement cache identity cannot be proven', async () => { + vi.mocked(refreshRollbackCacheReceipt).mockImplementation(() => { + throw new Error('foreign cache'); + }); + const health = vi.fn(async () => true); + await expect(rollback(health)).rejects.toThrow(/Manual rollback did not complete/); + expect(health).not.toHaveBeenCalled(); + expect(finishRollbackCache).not.toHaveBeenCalled(); + }); + it('recovers a populated install before old code starts, builds only active images and verifies health', async () => { const health = vi.fn(async () => { steps.push('HEALTH'); diff --git a/scripts/selfhost/upgrade-safeguards.test.ts b/scripts/selfhost/upgrade-safeguards.test.ts index ea64f36b94..38ee0bf094 100644 --- a/scripts/selfhost/upgrade-safeguards.test.ts +++ b/scripts/selfhost/upgrade-safeguards.test.ts @@ -11,6 +11,8 @@ vi.mock('./backup-lib', async (importOriginal) => ({ ...(await importOriginal()), runBackup: vi.fn(), runRollback: vi.fn(), + refreshRollbackCacheReceipt: vi.fn(), + finishRollbackCache: vi.fn(), })); vi.mock('./upgrade-preflight.js', async (original) => ({ diff --git a/scripts/selfhost/upgrade.test.ts b/scripts/selfhost/upgrade.test.ts index 5c13e827e2..7d5067a671 100644 --- a/scripts/selfhost/upgrade.test.ts +++ b/scripts/selfhost/upgrade.test.ts @@ -28,6 +28,8 @@ vi.mock('./backup-lib.js', async (original) => ({ runBackup: vi.fn(), assertRollbackCacheReady: vi.fn(), runRollback: vi.fn(), + refreshRollbackCacheReceipt: vi.fn(), + finishRollbackCache: vi.fn(), })); vi.mock('./upgrade-migrations.js', async (original) => ({ ...(await original()), diff --git a/tasks/active/2026-11-19-l24-selfhost-operations.md b/tasks/active/2026-11-19-l24-selfhost-operations.md index 95032ddfb9..89616bb9e7 100644 --- a/tasks/active/2026-11-19-l24-selfhost-operations.md +++ b/tasks/active/2026-11-19-l24-selfhost-operations.md @@ -75,3 +75,5 @@ Final f546 backup:4,324objects,5,824ms downtime, authenticated encrypted tree. F CodeRabbit requested23:03UTC via trusted label workflow, returned review limit/rate-limit; wait ended, no findings from it. Codex review found3 issues, fixed before final candidate: retry cache deletion after transient restoration failure; executable populated-install manual rollback bound to authenticated snapshot source SHA; exact created/reused workloadIdentityUser service-account grant receipts and cleanup. Recovery now stages state before swap, retains upgrade recovery pointer, writes private exact cache-deletion progress so partial deletion can retry, refuses replacement cache identities. 53backup tests pass; deleting pending-cache consumption makes the transient-volume retry control fail (RED), source restored. Independent recovery security review PASS. Teardown diagnostic stderr/JSON never surfaces raw cloud content;3actualCLI sentinel controls pass. Clean CI deploy validation exposed unbuilt providers dependency from existing node-provider-labels import; selfhost-only tsconfig resolves provider/shared sources directly, no runtime/Worker change. Full current review suite602tests/32filesPASS; latest manual command tests add real emitted CLI entrypoint and operator-checkout recovery on failed rollback. Disposable final rollback/teardown/cleanup and exact-head release gates pending. + +Live deliberate failure at761662d84 did not complete automatic recovery; direct authenticated runRollback retry restored the disposable data. Initial failing boundary was not captured, so do not label it a confirmed bucket cause. Review of retry sequence found journal was removed before old dependency install/start; fixed to retain exact proof through restored checkout, dependency installation, partial Compose start, replacement cache proof and final health. Four restart/health retry controls plus completed-data/no-cache retry regression pass. Full608tests/33files,111upgrade tests,54backup tests, tsc/eslint and independent security delta PASS. Disposable manually restarted after diagnostic retry, shared install unchanged. Full automatic proof rerun required on next head. From c47839706b77d055f8e819cee92361997b1b5881 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rapha=C3=ABl=20Titsworth-Morin?= Date: Thu, 19 Nov 2026 23:39:42 +0000 Subject: [PATCH 07/17] fix(selfhost): clean readonly Go caches during rollback --- scripts/selfhost/backup-recovery.ts | 19 ++++++++++++++++++- scripts/selfhost/backup.test.ts | 14 ++++++++++++++ .../2026-11-19-l24-selfhost-operations.md | 2 ++ 3 files changed, 34 insertions(+), 1 deletion(-) diff --git a/scripts/selfhost/backup-recovery.ts b/scripts/selfhost/backup-recovery.ts index c558625b63..c7072424e2 100644 --- a/scripts/selfhost/backup-recovery.ts +++ b/scripts/selfhost/backup-recovery.ts @@ -1,9 +1,11 @@ /** Restore an upgrade's authenticated snapshot to the same owned installation. */ import { + chmodSync, cpSync, existsSync, lstatSync, mkdtempSync, + readdirSync, readFileSync, renameSync, rmSync, @@ -261,6 +263,21 @@ export function finishRollbackCache(ctx: BoxContext): void { assertPrivateFile(path); rmSync(path); } +/** Go module caches contain read-only directories. Only chmod directories in our private, + * just-created stage; never follow a symlink or change a directory owned by another uid. */ +function removeRollbackStage(path: string): void { + const writable = (directory: string): void => { + const stat = lstatSync(directory); + if (!stat.isDirectory() || stat.isSymbolicLink()) return; + if (process.getuid && stat.uid !== process.getuid()) + throw new Error('Rollback cleanup directory belongs to another user'); + if ((stat.mode & 0o700) !== 0o700) chmodSync(directory, stat.mode | 0o700); + for (const entry of readdirSync(directory)) writable(join(directory, entry)); + }; + writable(path); + rmSync(path, { recursive: true, force: true }); +} + /** Stage the full replacement before swapping directories; failed copying retains live state. */ function restoreState( ctx: BoxContext, @@ -299,7 +316,7 @@ function restoreState( throw error; } } finally { - rmSync(stage, { recursive: true, force: true }); + removeRollbackStage(stage); } } diff --git a/scripts/selfhost/backup.test.ts b/scripts/selfhost/backup.test.ts index c88b9e27b4..1df878c084 100644 --- a/scripts/selfhost/backup.test.ts +++ b/scripts/selfhost/backup.test.ts @@ -7,6 +7,7 @@ import { randomBytes } from 'node:crypto'; import * as fs from 'node:fs'; import { + chmodSync, cpSync, existsSync, lstatSync, @@ -644,6 +645,19 @@ describe('runRollback', () => { ); }); + it('restores after a real Go module cache made read-only directories in the old state', () => { + const context = ctx('gs://fleet/celld', join(root, 'state')); + const cache = join(context.stateDir, 'go-cache/module/pkg'); + mkdirSync(cache, { recursive: true }); + writeFileSync(join(cache, 'module.go'), 'rebuildable cache', { mode: 0o444 }); + chmodSync(cache, 0o555); + const snapshot = join(root, 'readonly-go-cache'); + runBackup(context, snapshot); + expect(() => runRollback(context, snapshot)).not.toThrow(); + expect(existsSync(join(context.stateDir, 'go-cache'))).toBe(false); + expect(readdirSync(root).some((name) => name.startsWith('.rollback-state-'))).toBe(false); + }); + it('keeps completed cache progress until recovered code is healthy and refreshes a recreated cache', () => { const context = ctx('gs://fleet/celld', join(root, 'state')); const snapshot = join(root, 'post-data-retry'); diff --git a/tasks/active/2026-11-19-l24-selfhost-operations.md b/tasks/active/2026-11-19-l24-selfhost-operations.md index 89616bb9e7..ca316b8d22 100644 --- a/tasks/active/2026-11-19-l24-selfhost-operations.md +++ b/tasks/active/2026-11-19-l24-selfhost-operations.md @@ -77,3 +77,5 @@ CodeRabbit requested23:03UTC via trusted label workflow, returned review limit/r Full current review suite602tests/32filesPASS; latest manual command tests add real emitted CLI entrypoint and operator-checkout recovery on failed rollback. Disposable final rollback/teardown/cleanup and exact-head release gates pending. Live deliberate failure at761662d84 did not complete automatic recovery; direct authenticated runRollback retry restored the disposable data. Initial failing boundary was not captured, so do not label it a confirmed bucket cause. Review of retry sequence found journal was removed before old dependency install/start; fixed to retain exact proof through restored checkout, dependency installation, partial Compose start, replacement cache proof and final health. Four restart/health retry controls plus completed-data/no-cache retry regression pass. Full608tests/33files,111upgrade tests,54backup tests, tsc/eslint and independent security delta PASS. Disposable manually restarted after diagnostic retry, shared install unchanged. Full automatic proof rerun required on next head. + +Confirmed live rollback cleanup root cause: after restoring state, private old-state staging cleanup encountered Go module cache directories with mode0555. Two real leftover stages each contain688directories/642read-only and go-cache. Direct retry succeeds because the already-restored state excludes rebuildable go-cache. Added private-stage-only lstat/no-symlink traversal and uid check, adding owner permissions only before cleanup. Real0555directory/0444file regression passes; removing chmod produces EACCES/RED. Full609tests33files/55backup/111upgrade, tsc/eslint pass; independent security delta PASS. Target deployment's separate exit1 before health remains under safe diagnostic investigation; no claim automatic rollback gate passed yet. From 8f7882d180ba06bda2bc98bda3e4f9019c9fbabf Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rapha=C3=ABl=20Titsworth-Morin?= Date: Thu, 19 Nov 2026 23:57:31 +0000 Subject: [PATCH 08/17] fix(selfhost): preserve restore ownership and recover interrupted operations --- deploy/selfhost/.gitignore | 1 + deploy/selfhost/README.md | 12 +- scripts/selfhost/backup-destination.test.ts | 71 +++++++ scripts/selfhost/backup-destination.ts | 31 +++ scripts/selfhost/backup-encryption.test.ts | 12 ++ scripts/selfhost/backup-encryption.ts | 42 ++-- scripts/selfhost/backup-entrypoint.test.ts | 38 +++- scripts/selfhost/backup-lib.ts | 53 +---- scripts/selfhost/backup-recovery.ts | 26 ++- scripts/selfhost/backup-restore.ts | 69 +++++++ scripts/selfhost/backup.test.ts | 186 ++++++++++++++++++ .../selfhost/live/backup-restore.live.test.ts | 74 ++++++- scripts/selfhost/operator-ci-guard.test.ts | 5 + scripts/selfhost/restore-progress.ts | 146 ++++++++++++++ scripts/selfhost/teardown-model.test.ts | 158 +++++++++++++++ scripts/selfhost/teardown-model.ts | 13 +- scripts/selfhost/testdata/fake-gcloud.mjs | 28 ++- 17 files changed, 889 insertions(+), 76 deletions(-) create mode 100644 scripts/selfhost/backup-destination.test.ts create mode 100644 scripts/selfhost/backup-destination.ts create mode 100644 scripts/selfhost/backup-restore.ts create mode 100644 scripts/selfhost/restore-progress.ts create mode 100644 scripts/selfhost/teardown-model.test.ts diff --git a/deploy/selfhost/.gitignore b/deploy/selfhost/.gitignore index 4f694befa4..6c1c30c430 100644 --- a/deploy/selfhost/.gitignore +++ b/deploy/selfhost/.gitignore @@ -1,4 +1,5 @@ # Operator configuration and box state (platform keys, secrets.env, gateway.env): never commit. .env .state/ +*.restore-progress.json backups/ diff --git a/deploy/selfhost/README.md b/deploy/selfhost/README.md index a8f50f5983..6088daacdc 100644 --- a/deploy/selfhost/README.md +++ b/deploy/selfhost/README.md @@ -99,6 +99,8 @@ From the repository root on the VM: The fleet bucket contains Worker secrets as well as application data. The backup command encrypts **the entire backup**, including the bucket, `.state/`, `.env` and its manifest, with AES-256-GCM. +Restored files retain owner execution when needed, with mode 0700 for tools and 0600 for other +files; group and world access are never restored. Rebuildable `go-cache` data is excluded. It first requires exactly one running celld in the selected Compose project, then briefly stops it for a consistent second bucket copy and restarts it even if that copy fails (`scripts/selfhost/backup-lib.ts:runBackup`, `runPlainBackup`). Temporary plaintext lives @@ -116,7 +118,8 @@ pnpm selfhost:backup --encryption-key-file "$HOME/.config/sam/backup.key" ``` Use `--to /absolute/path/to/new-backup` for a specific destination; the default is -`deploy/selfhost/backups/`. Keep the key outside installation state and all backup +`deploy/selfhost/backups/`. Existing parent directory permissions are preserved; only +new dedicated directories are created private, and symlinked parents are refused. Keep the key outside installation state and all backup folders. Alternatively set `SAM_BACKUP_KEY_FILE` in the private `.env` to the key's **absolute** path. The file must be owned by the operator, mode 0600, exactly 32 raw bytes, and have no symlinks or hard links (`scripts/selfhost/backup-encryption.ts:readBackupKey`). Store a separate offline @@ -137,6 +140,10 @@ pnpm selfhost:restore --from /absolute/path/to/backup \ ``` Restore authenticates the complete encrypted inventory and every file before touching the target. +If a copy fails, retain `.restore-progress.json` and retry the exact same command and +backup. This private journal binds the original empty target and authenticated snapshot. A retry +refuses changed, additional, linked or foreign-owned partial files before copying again; do not +start the target or remove its journal to bypass a refusal. The journal is removed after success. It refuses a target project with existing containers, copies state and bucket data, keeps the target `.env`, strips the source installation's creation receipts, and does not start celld. On the original SAM ref, run `selfhost:deploy --init` to retain the restored keys and establish new target ownership receipts. Set the target `.env`'s @@ -168,7 +175,8 @@ creation receipts. It checks out the target, runs `deploy --init`, rebuilds chan restarts Compose when its inputs changed, deploys and checks health. Failure automatically restores the encrypted snapshot and previous code/dependencies before starting the previous version. The recovery checks the original installation, bucket, state and Compose ownership before removing -its disposable celld cache (`scripts/selfhost/upgrade-lib.ts:runUpgrade`, `recoverUpgrade`; +its disposable celld cache. The recovery journal remains until the old service is healthy, and +current resource creation/removal receipts survive rollback (`scripts/selfhost/upgrade-lib.ts:runUpgrade`, `recoverUpgrade`; `scripts/selfhost/backup-recovery.ts:runRollback`). Redeploying an old Worker alone cannot undo a migration. diff --git a/scripts/selfhost/backup-destination.test.ts b/scripts/selfhost/backup-destination.test.ts new file mode 100644 index 0000000000..6094a5e96a --- /dev/null +++ b/scripts/selfhost/backup-destination.test.ts @@ -0,0 +1,71 @@ +import { + chmodSync, + chownSync, + existsSync, + mkdirSync, + mkdtempSync, + rmSync, + statSync, + symlinkSync, +} from 'node:fs'; +import { join, resolve } from 'node:path'; + +import { afterEach, beforeEach, describe, expect, it } from 'vitest'; + +import { prepareBackupParent } from './backup-destination'; + +let root: string; +beforeEach(() => { + mkdirSync(resolve('.tmp'), { recursive: true }); + root = mkdtempSync(resolve('.tmp/backup-parent-')); +}); +afterEach(() => rmSync(root, { recursive: true, force: true })); + +describe('operator backup destination parent', () => { + it('preserves existing mode1777 and ownership and creates only private new child directories', () => { + chmodSync(root, 0o1777); + const before = statSync(root); + prepareBackupParent(join(root, 'new/backups/snapshot')); + const after = statSync(root); + expect(after.mode & 0o7777).toBe(0o1777); + expect(after.uid).toBe(before.uid); + expect(after.ino).toBe(before.ino); + expect(statSync(join(root, 'new/backups')).mode & 0o777).toBe(0o700); + expect(statSync(join(root, 'new/backups')).uid).toBe(process.getuid?.()); + }); + it('rejects symlink parents before changing the pointed-to directory', () => { + const actual = join(root, 'actual'); + mkdirSync(actual, { mode: 0o755 }); + const before = statSync(actual); + symlinkSync(actual, join(root, 'linked')); + expect(() => prepareBackupParent(join(root, 'linked/nested/snapshot'))).toThrow( + 'without symlinks' + ); + expect(statSync(actual).mode & 0o777).toBe(before.mode & 0o777); + expect(statSync(actual).ino).toBe(before.ino); + }); + it.skipIf(process.getuid?.() === statSync('/tmp').uid)( + 'does not claim or chmod the actual foreign-owned temporary directory', + () => { + const before = statSync('/tmp'); + const absent = join('/tmp', `sam-parent-control-no-write-${process.pid}-${Date.now()}`); + expect(existsSync(absent)).toBe(false); + prepareBackupParent(absent); + const after = statSync('/tmp'); + expect(after.uid).toBe(before.uid); + expect(after.mode).toBe(before.mode); + expect(existsSync(absent)).toBe(false); + } + ); + it.skipIf(process.getuid?.() !== 0)( + 'preserves a foreign-owned existing parent instead of claiming it', + () => { + chownSync(root, 65534, 65534); + chmodSync(root, 0o1777); + prepareBackupParent(join(root, 'owned-child/snapshot')); + expect(statSync(root).uid).toBe(65534); + expect(statSync(root).mode & 0o7777).toBe(0o1777); + expect(statSync(join(root, 'owned-child')).uid).toBe(0); + } + ); +}); diff --git a/scripts/selfhost/backup-destination.ts b/scripts/selfhost/backup-destination.ts new file mode 100644 index 0000000000..c45d6c7511 --- /dev/null +++ b/scripts/selfhost/backup-destination.ts @@ -0,0 +1,31 @@ +/** Validate operator-selected destinations without changing permissions on reused directories. */ +import { lstatSync, mkdirSync, realpathSync } from 'node:fs'; +import { dirname, resolve } from 'node:path'; + +export function prepareBackupParent(destination: string): void { + if (lstatSync(destination, { throwIfNoEntry: false })?.isSymbolicLink()) + throw new Error('Backup destination must not use symlinks'); + const parent = dirname(resolve(destination)); + const missing: string[] = []; + let ancestor = parent; + while (!lstatSync(ancestor, { throwIfNoEntry: false })) { + missing.unshift(ancestor); + ancestor = dirname(ancestor); + } + const existing = lstatSync(ancestor); + if (!existing.isDirectory() || existing.isSymbolicLink() || realpathSync(ancestor) !== ancestor) { + throw new Error('Backup destination parent must be a directory without symlinks'); + } + // mkdir's mode applies only to newly-created directories. Never chmod an operator's parent. + for (const path of missing) { + mkdirSync(path, { mode: 0o700 }); + const created = lstatSync(path); + if ( + !created.isDirectory() || + created.isSymbolicLink() || + (process.getuid !== undefined && created.uid !== process.getuid()) + ) { + throw new Error('Cannot verify ownership of new backup directory'); + } + } +} diff --git a/scripts/selfhost/backup-encryption.test.ts b/scripts/selfhost/backup-encryption.test.ts index af3d6c6024..4b3cbc7396 100644 --- a/scripts/selfhost/backup-encryption.test.ts +++ b/scripts/selfhost/backup-encryption.test.ts @@ -42,6 +42,18 @@ afterEach(() => { }); describe('operator encrypted backup trees', () => { + it('authenticates and preserves owner execution for restored tools while keeping all files private', () => { + const f = fixture(); + writeFileSync(join(f.source, 'celld'), 'operator binary', { mode: 0o755 }); + writeFileSync(join(f.source, 'other-execute-only'), 'private content', { mode: 0o655 }); + encryptBackupTree(f.source, f.encrypted, f.key); + expect(statSync(join(f.encrypted, 'celld')).mode & 0o777).toBe(0o600); + decryptBackupTree(f.encrypted, f.restored, f.key); + expect(statSync(join(f.restored, 'celld')).mode & 0o777).toBe(0o700); + expect(statSync(join(f.restored, 'secrets.env')).mode & 0o777).toBe(0o600); + expect(statSync(join(f.restored, 'other-execute-only')).mode & 0o777).toBe(0o600); + }); + it('round trips binary archives larger than the chunk size, empty files and directories without storing plaintext', () => { const f = fixture(); const archive = randomBytes(8 * 1024 * 1024 + 7); diff --git a/scripts/selfhost/backup-encryption.ts b/scripts/selfhost/backup-encryption.ts index 9a7b438ee7..3fe60c9f5a 100644 --- a/scripts/selfhost/backup-encryption.ts +++ b/scripts/selfhost/backup-encryption.ts @@ -7,6 +7,7 @@ import { randomBytes, } from 'node:crypto'; import { + chmodSync, closeSync, constants, existsSync, @@ -174,13 +175,13 @@ function transformFile( } } -function sealManifest(tree: Tree, snapshot: string, key: Buffer): Buffer { +function sealManifest(tree: Tree, snapshot: string, key: Buffer, executable: string): Buffer { const prefix = header(); const cipher = createCipheriv('aes-256-gcm', key, prefix.subarray(MAGIC.length)); cipher.setAAD(aad(prefix, `\0${MANIFEST}`)); return Buffer.concat([ prefix, - cipher.update(JSON.stringify({ snapshot, tree })), + cipher.update(JSON.stringify({ snapshot, tree, executable })), cipher.final(), cipher.getAuthTag(), ]); @@ -201,7 +202,10 @@ export function encryptBackupTree(source: string, destination: string, keyFile: for (const dir of tree.directories) mkdirSync(join(destination, dir), { mode: 0o700 }); for (const file of tree.files) transformFile(join(source, file), join(destination, file), file, key, false, snapshot); - writeFileSync(join(destination, MANIFEST), sealManifest(tree, snapshot, key), { + const executable = tree.files + .map((file) => (lstatSync(join(source, file)).mode & 0o100 ? '1' : '0')) + .join(''); + writeFileSync(join(destination, MANIFEST), sealManifest(tree, snapshot, key, executable), { mode: 0o600, flag: 'wx', }); @@ -231,12 +235,16 @@ export function decryptBackupTree(source: string, destination: string, keyFile: directories: tree.directories, }; const expected = JSON.stringify(inventory); - const manifestSize = - Buffer.byteLength(JSON.stringify({ snapshot: '0'.repeat(32), tree: inventory })) + - MAGIC.length + - NONCE_BYTES + - TAG_BYTES; - if (lstatSync(join(source, MANIFEST)).size !== manifestSize) + const manifestSizes = [undefined, '0'.repeat(inventory.files.length)].map( + (executable) => + Buffer.byteLength( + JSON.stringify({ snapshot: '0'.repeat(32), tree: inventory, executable }) + ) + + MAGIC.length + + NONCE_BYTES + + TAG_BYTES + ); + if (!manifestSizes.includes(lstatSync(join(source, MANIFEST)).size)) throw new Error('Backup inventory size mismatch'); mkdirSync(destination, { mode: 0o700 }); created = true; @@ -250,13 +258,17 @@ export function decryptBackupTree(source: string, destination: string, keyFile: typeof manifest.snapshot !== 'string' || !/^[a-f0-9]{32}$/.test(manifest.snapshot) || !('tree' in manifest) || - JSON.stringify(manifest.tree) !== expected + JSON.stringify(manifest.tree) !== expected || + ('executable' in manifest && + (typeof manifest.executable !== 'string' || + manifest.executable.length !== inventory.files.length || + [...manifest.executable].some((bit) => bit !== '0' && bit !== '1'))) ) { throw new Error('Backup inventory mismatch'); } rmSync(join(destination, MANIFEST)); for (const dir of tree.directories) mkdirSync(join(destination, dir), { mode: 0o700 }); - for (const file of tree.files.filter((f) => f !== MANIFEST)) + for (const [index, file] of inventory.files.entries()) { transformFile( join(source, file), join(destination, file), @@ -265,6 +277,14 @@ export function decryptBackupTree(source: string, destination: string, keyFile: true, manifest.snapshot ); + // Preserve owner execution only, after this file authenticates; all other access stays private. + if ( + 'executable' in manifest && + typeof manifest.executable === 'string' && + manifest.executable[index] === '1' + ) + chmodSync(join(destination, file), 0o700); + } } catch { if (created) rmSync(destination, { recursive: true, force: true }); throw new Error('Backup authentication failed; incomplete plaintext removed'); diff --git a/scripts/selfhost/backup-entrypoint.test.ts b/scripts/selfhost/backup-entrypoint.test.ts index dbb5694b1d..d49bf005c7 100644 --- a/scripts/selfhost/backup-entrypoint.test.ts +++ b/scripts/selfhost/backup-entrypoint.test.ts @@ -1,9 +1,9 @@ /** * `pnpm selfhost:backup` then `pnpm selfhost:restore`, run as the real commands (tsx backup.ts, * tsx restore.ts) with fake `gcloud` and `docker` binaries first on PATH (testdata/). The fake - * gcloud reproduces the box failure from PR #2675: objects celld rewrites while running vanish - * mid-copy in the live pass, and the aborted pass leaves state that broke the delta pass with - * `[Errno 2] No such file or directory: /bucket/nodes/node_.json`. + * gcloud models generation churn and the confirmed box failure from PR #2675: SDK523 can + * reach its POSIX-metadata stat after finalize_download returned false and no local file exists. + * Destination-keyed partial-state isolation and a clean full-copy fallback are both exercised. */ import { spawnSync } from 'node:child_process'; import { randomBytes } from 'node:crypto'; @@ -125,6 +125,38 @@ afterEach(() => { }); describe('selfhost:backup and selfhost:restore (real entry points, fake gcloud)', () => { + it('uses a clean full copy after the stopped pass hits the confirmed POSIX stat of a missing finalized file', () => { + writeFileSync( + join(root, 'fake/posix-fail-once.json'), + JSON.stringify({ key: 'nodes/node_live.json', metadata: { atime: '1', mtime: '2' } }) + ); + const dest = join(root, 'posix-fallback-backup'); + const result = run('backup.ts', [ + '--to', + dest, + '--box-env', + join(root, 'box.env'), + '--state-dir', + join(root, 'state'), + '--encryption-key-file', + join(root, 'backup-key'), + ]); + expect(result.status).toBe(0); + expect(result.stderr).toBe(''); + expect(result.stdout).toContain('delta copy failed'); + expect(result.stdout).not.toContain('set_posix_attributes'); + const calls = readFileSync(join(root, 'fake/calls.log'), 'utf8').trim().split('\n'); + expect(calls.filter((call) => call.startsWith('gcloud storage rsync'))).toHaveLength(3); + const plain = join(root, 'posix-inspection'); + decryptBackupTree(dest, plain, join(root, 'backup-key')); + try { + expect(tree(join(plain, 'bucket'))).toEqual(tree(join(root, 'gcs/fleet/celld'))); + } finally { + rmSync(plain, { recursive: true, force: true }); + } + expect(readFileSync(join(root, 'fake/celld'), 'utf8')).toBe('running'); + }, 60_000); + it('backs up the actual legacy shell-selected project when its YAML has only a static name', () => { const compose = join(root, 'legacy-compose.yml'); writeFileSync(compose, 'name: sam-selfhost\nservices:\n celld:\n image: fixture/celld\n'); diff --git a/scripts/selfhost/backup-lib.ts b/scripts/selfhost/backup-lib.ts index 46bd6737bf..0dc0b5dee9 100644 --- a/scripts/selfhost/backup-lib.ts +++ b/scripts/selfhost/backup-lib.ts @@ -13,13 +13,14 @@ import { } from 'node:fs'; import { dirname, join, relative, resolve } from 'node:path'; +import { prepareBackupParent } from './backup-destination'; import { decryptBackupTree, encryptBackupTree, readBackupKey } from './backup-encryption'; -import { readManifest } from './backup-manifest'; import { assertBackupOutside, assertOperationPaths } from './backup-paths'; +import { restoreBackup } from './backup-restore'; import { requireRunningCelld } from './backup-runtime'; -import { composeProjectFor, expectedComposeProjectFor, recordBackup } from './install-record'; +import { composeProjectFor, recordBackup } from './install-record'; import { assertOperatorExecution } from './operator-only'; -import { ensurePrivateDir, readPrivateJson } from './secret-files'; +import { ensurePrivateDir } from './secret-files'; /** * Rebuildable caches under the state dir, left out of every backup. `go-cache` is the vm-agent @@ -377,45 +378,6 @@ function runPlainBackup( return manifest; } -/** - * Restore `from` into an empty install: the target bucket (the CELLD_BUCKET in ctx.box) must be - * empty and the target `.state/` must have no platform keys. celld stays stopped; the caller - * prints how to start the stack. - */ -function runPlainRestore(ctx: BoxContext, from: string): BackupManifest { - const manifest = readManifest(from); - if (existsSync(ctx.stateDir) && readdirSync(ctx.stateDir).length > 0) { - throw new Error(`${ctx.stateDir} is not empty: restore only into an empty install`); - } - if (!bucketIsEmpty(ctx)) { - throw new Error(`${ctx.box.CELLD_BUCKET} is not empty: restore only into an empty bucket`); - } - // Fresh state has no gateway.env, so even 'compose stop' would fail config validation. - // Refuse any existing target runtime without parsing a not-yet-created Compose stack. - const sourceIdentity = readPrivateJson( - join(from, STATE_DIR, 'platform-keys.json') - ).SAM_INSTALLATION_ID; - if (typeof sourceIdentity !== 'string' || !/^[a-f0-9]{32}$/.test(sourceIdentity)) - throw new Error('Invalid backup installation identity'); - const projects = new Set([ - composeProjectFor(ctx.box, ctx.stateDir), - expectedComposeProjectFor(ctx.box, ctx.stateDir, sourceIdentity), - ]); - for (const project of projects) { - const containers = check( - ctx.run('docker', ['ps', '-aq', '--filter', `label=com.docker.compose.project=${project}`]), - 'check empty restore runtime' - ); - if (containers.stdout.trim()) - throw new Error('Restore target already has containers; use a fresh installation'); - } - ctx.log(`copying ${manifest.objectCount} objects into ${ctx.box.CELLD_BUCKET}`); - pushBucket(ctx, join(from, BUCKET_DIR)); - ensurePrivateDir(ctx.stateDir); - cpSync(join(from, STATE_DIR), ctx.stateDir, { recursive: true, preserveTimestamps: true }); - return manifest; -} - /** Backups are operator-only: no secret-bearing reads or decryptions in CI. */ export function backupKey(ctx: BoxContext): string { assertOperatorExecution(); @@ -454,7 +416,7 @@ export function runBackup( if (!rel.startsWith('..') && !rel.startsWith('/')) throw new Error('Keep the backup key outside installation state and backups'); } - ensurePrivateDir(dirname(resolve(dest))); + prepareBackupParent(dest); requireRunningCelld(ctx); const temp = backupScratch(); try { @@ -478,10 +440,7 @@ export function runRestore(ctx: BoxContext, from: string): BackupManifest { try { const plain = join(temp, 'plain'); decryptBackupTree(from, plain, key); - const manifest = runPlainRestore(ctx, plain); - // Creation receipts belong to the source install, never to a fresh restore target. - rmSync(join(ctx.stateDir, 'created-resources.json'), { force: true }); - return manifest; + return restoreBackup(ctx, plain, from); } finally { rmSync(temp, { recursive: true, force: true }); } diff --git a/scripts/selfhost/backup-recovery.ts b/scripts/selfhost/backup-recovery.ts index c7072424e2..4c06ca55b2 100644 --- a/scripts/selfhost/backup-recovery.ts +++ b/scripts/selfhost/backup-recovery.ts @@ -31,7 +31,7 @@ import { readManifest, STATE_DIR, } from './backup-lib'; -import { composeProjectFor, recordInstall } from './install-record'; +import { composeProjectFor, recordInstall, SELFHOST_ENVIRONMENT } from './install-record'; import { assertOperatorExecution } from './operator-only'; import { assertPrivateFile, replacePrivateFile } from './secret-files'; import { assertRollbackReady } from './upgrade-preflight'; @@ -88,6 +88,26 @@ function assertStateReceipt(path: string, expected: string, id: unknown, live = } } +/** Ownership history follows the live installation, including post-backup removals/creations. */ +function currentLedger(ctx: BoxContext, id: string): string { + assertStateReceipt(ctx.stateDir, ctx.stateDir, id, true); + const path = join(ctx.stateDir, 'created-resources.json'); + const stat = lstatSync(path); + if (!stat.isFile() || stat.isSymbolicLink()) throw new Error('Invalid rollback ownership ledger'); + assertPrivateFile(path); + const record = readRecord(path); + const installation = record.resources.find( + (r) => r.cloud === 'box' && r.kind === 'installation' && r.name === id + ); + if ( + installation?.attributes?.domain !== (ctx.box.SAM_DOMAIN ?? '') || + installation.attributes.environment !== SELFHOST_ENVIRONMENT || + installation.attributes.composeProject !== composeProjectFor(ctx.box, ctx.stateDir) + ) + throw new Error('Rollback ownership ledger belongs to a different installation scope'); + return `${JSON.stringify(record, null, 2)}\n`; +} + export interface RollbackCacheProof { name: string; createdAt: string; @@ -305,7 +325,7 @@ function restoreState( join(staged, CACHE_PENDING), JSON.stringify({ ...pending, snapshot: resolve(from) }) ); - assertStateReceipt(ctx.stateDir, ctx.stateDir, id, true); + replacePrivateFile(join(staged, 'created-resources.json'), currentLedger(ctx, id)); renameSync(ctx.stateDir, previous); try { renameSync(staged, ctx.stateDir); @@ -346,7 +366,7 @@ export function runRollback(ctx: BoxContext, from: string, expectedSamCommit?: s throw new Error('Rollback snapshot belongs to a different installation'); } assertStateReceipt(join(plain, STATE_DIR), ctx.stateDir, oldKeys.SAM_INSTALLATION_ID); - assertStateReceipt(ctx.stateDir, ctx.stateDir, currentKeys.SAM_INSTALLATION_ID, true); + currentLedger(ctx, oldKeys.SAM_INSTALLATION_ID); const pending = pendingCache(ctx, from); const cache = pending ?? assertRollbackCacheReady(ctx); if (pending) cachePresence(ctx, pending); diff --git a/scripts/selfhost/backup-restore.ts b/scripts/selfhost/backup-restore.ts new file mode 100644 index 0000000000..10d041458e --- /dev/null +++ b/scripts/selfhost/backup-restore.ts @@ -0,0 +1,69 @@ +/** Restore into a fresh target, or resume only proven partial output from this exact snapshot. */ +import { cpSync, existsSync, lstatSync, readdirSync, rmSync } from 'node:fs'; +import { join } from 'node:path'; + +import { + type BackupManifest, + type BoxContext, + BUCKET_DIR, + bucketIsEmpty, + check, + pullBucket, + pushBucket, + readManifest, + STATE_DIR, +} from './backup-lib'; +import { composeProjectFor, expectedComposeProjectFor } from './install-record'; +import { assertOperatorExecution } from './operator-only'; +import { assertRestoreSubset, restoreProgress } from './restore-progress'; +import { ensurePrivateDir, readPrivateJson } from './secret-files'; + +function assertEmptyRuntime(ctx: BoxContext, from: string): void { + const identity = readPrivateJson(join(from, STATE_DIR, 'platform-keys.json')).SAM_INSTALLATION_ID; + if (typeof identity !== 'string' || !/^[a-f0-9]{32}$/.test(identity)) + throw new Error('Invalid backup installation identity'); + const projects = new Set([ + composeProjectFor(ctx.box, ctx.stateDir), + expectedComposeProjectFor(ctx.box, ctx.stateDir, identity), + ]); + for (const project of projects) { + const containers = check( + ctx.run('docker', ['ps', '-aq', '--filter', `label=com.docker.compose.project=${project}`]), + 'check empty restore runtime' + ); + if (containers.stdout.trim()) + throw new Error('Restore target already has containers; use a fresh installation'); + } +} + +export function restoreBackup(ctx: BoxContext, plain: string, encrypted: string): BackupManifest { + assertOperatorExecution(); + const manifest = readManifest(plain); + const progress = restoreProgress(ctx, encrypted); + const state = lstatSync(ctx.stateDir, { throwIfNoEntry: false }); + if (state && process.getuid !== undefined && state.uid !== process.getuid()) + throw new Error('Restore target state is owned by another user'); + if (!progress.resume) { + if (existsSync(ctx.stateDir) && readdirSync(ctx.stateDir).length > 0) + throw new Error('Restore state is not empty: restore only into an empty install'); + if (!bucketIsEmpty(ctx)) + throw new Error('Restore bucket is not empty: restore only into an empty bucket'); + } + // Inspect by labels: parsing Compose before gateway.env exists would reject a fresh install. + assertEmptyRuntime(ctx, plain); + if (progress.resume) { + assertRestoreSubset(ctx.stateDir, join(plain, STATE_DIR)); + const current = join(plain, '.restore-current-bucket'); + pullBucket(ctx, current); + assertRestoreSubset(current, join(plain, BUCKET_DIR)); + } + // Durable ownership is recorded before the first target write. Failures retain it for retry. + progress.begin(); + ctx.log(`copying ${manifest.objectCount} objects into ${ctx.box.CELLD_BUCKET}`); + pushBucket(ctx, join(plain, BUCKET_DIR)); + ensurePrivateDir(ctx.stateDir); + cpSync(join(plain, STATE_DIR), ctx.stateDir, { recursive: true, preserveTimestamps: true }); + rmSync(join(ctx.stateDir, 'created-resources.json'), { force: true }); + progress.finish(); + return manifest; +} diff --git a/scripts/selfhost/backup.test.ts b/scripts/selfhost/backup.test.ts index 1df878c084..cfe51eb892 100644 --- a/scripts/selfhost/backup.test.ts +++ b/scripts/selfhost/backup.test.ts @@ -10,6 +10,7 @@ import { chmodSync, cpSync, existsSync, + linkSync, lstatSync, mkdirSync, mkdtempSync, @@ -26,6 +27,7 @@ import { basename, join, resolve } from 'node:path'; import * as TOML from '@iarna/toml'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { addResource, markRemoved, readRecord } from '../../deploy/selfhost/created-resources.mjs'; import type { WranglerToml } from '../deploy/types'; import { decryptBackupTree, encryptBackupTree } from './backup-encryption'; import { @@ -63,6 +65,8 @@ let selectedProject: string; let replaceStateOnPush: boolean; let celldStopped: boolean; let runningCelldIds: string; +let failRestorePush: boolean; +let replaceRestoreJournalOnPull: boolean; let cacheInspections: number; let targetContainers: string; let occupiedProject: string | undefined; @@ -197,9 +201,22 @@ function fakeRun(command: string, args: string[], env?: NodeJS.ProcessEnv): RunR } rmSync(hostDir, { recursive: true, force: true }); cpSync(storePath(src), hostDir, { recursive: true }); + if (replaceRestoreJournalOnPull && src === 'src/fresh/celld') { + const journal = join(root, 'new-state.restore-progress.json'); + writeFileSync(`${journal}.replacement`, readFileSync(journal), { mode: 0o600 }); + renameSync(`${journal}.replacement`, journal); + } } else { if (mc.includes('--remove')) rmSync(storePath(dst), { recursive: true, force: true }); mkdirSync(storePath(dst), { recursive: true }); + if (failRestorePush) { + failRestorePush = false; + replaceRestoreJournalOnPull = false; + const first = Object.keys(tree(hostDir))[0]!; + mkdirSync(join(storePath(dst), first, '..'), { recursive: true }); + cpSync(join(hostDir, first), join(storePath(dst), first)); + return { status: 1, stdout: '', stderr: 'fixture provider failure must not be echoed' }; + } cpSync(hostDir, storePath(dst), { recursive: true }); } return ok; @@ -246,6 +263,8 @@ beforeEach(() => { replaceStateOnPush = false; celldStopped = false; runningCelldIds = 'c'.repeat(64); + failRestorePush = false; + replaceRestoreJournalOnPull = false; cacheInspections = 0; targetContainers = ''; occupiedProject = undefined; @@ -274,6 +293,24 @@ function inspectBackup(dest: string, part: string): Record { } describe('runBackup', () => { + it('preserves an operator parent mode1777 through the public backup entry', () => { + const parent = join(root, 'operator-parent'); + mkdirSync(parent); + chmodSync(parent, 0o1777); + runBackup(ctx('s3://fleet/celld', join(root, 'state')), join(parent, 'snapshot')); + expect(statSync(parent).mode & 0o7777).toBe(0o1777); + }); + it('refuses a symlink parent before copying or stopping anything and preserves its mode', () => { + const parent = join(root, 'operator-parent'); + mkdirSync(parent, { mode: 0o755 }); + symlinkSync(parent, join(root, 'linked-parent')); + expect(() => + runBackup(ctx('s3://fleet/celld', join(root, 'state')), join(root, 'linked-parent/snapshot')) + ).toThrow(/without symlinks/); + expect(calls).toHaveLength(0); + expect(statSync(parent).mode & 0o777).toBe(0o755); + }); + it.each(['', `${'c'.repeat(64)}\n${'d'.repeat(64)}`, 'short-id'])( 'refuses missing or ambiguous running celld before any bucket copy (%s)', (ids) => { @@ -509,6 +546,99 @@ describe('runBackup', () => { }); describe('runRestore', () => { + it('refuses a hard-linked partial state file before copying over an external inode', () => { + const snapshot = join(root, 'retry-hardlink-snapshot'); + runBackup(ctx('s3://fleet/celld', join(root, 'state')), snapshot); + const target = ctx('s3://fresh/celld', join(root, 'new-state')); + failRestorePush = true; + expect(() => runRestore(target, snapshot)).toThrow(); + mkdirSync(target.stateDir, { mode: 0o700 }); + const external = join(root, 'external-key-file'); + writeFileSync(external, PLATFORM_KEYS, { mode: 0o600 }); + linkSync(external, join(target.stateDir, 'platform-keys.json')); + calls = []; + expect(() => runRestore(target, snapshot)).toThrow(/unsafe data/); + expect(readFileSync(external, 'utf8')).toBe(PLATFORM_KEYS); + expect(statSync(external).nlink).toBe(2); + expect( + calls.some((call) => call.args.includes('mirror') && call.args.at(-2) === '/backup') + ).toBe(false); + }); + it('revalidates retry journal identity immediately before the resumed write phase', () => { + const snapshot = join(root, 'retry-journal-race-snapshot'); + runBackup(ctx('s3://fleet/celld', join(root, 'state')), snapshot); + const target = ctx('s3://fresh/celld', join(root, 'new-state')); + failRestorePush = true; + expect(() => runRestore(target, snapshot)).toThrow(); + replaceRestoreJournalOnPull = true; + calls = []; + expect(() => runRestore(target, snapshot)).toThrow('Restore retry ownership changed'); + expect( + calls.some((call) => call.args.includes('mirror') && call.args.at(-2) === '/backup') + ).toBe(false); + }); + + it('resumes a real partial bucket copy from the same authenticated backup without deleting data', () => { + const snapshot = join(root, 'retry-snapshot'); + runBackup(ctx('s3://fleet/celld', join(root, 'state')), snapshot); + const target = ctx('s3://fresh/celld', join(root, 'new-state')); + failRestorePush = true; + expect(() => runRestore(target, snapshot)).toThrow(/mc mirror/); + expect(Object.keys(tree(join(root, 'store/fresh/celld')))).toHaveLength(1); + expect(existsSync(`${target.stateDir}.restore-progress.json`)).toBe(true); + // Simulate a prior interrupted state copy as an exact subset of the same authenticated state. + mkdirSync(target.stateDir, { mode: 0o700 }); + writeFileSync(join(target.stateDir, 'platform-keys.json'), PLATFORM_KEYS, { mode: 0o600 }); + runRestore(target, snapshot); + expect(tree(join(root, 'store/fresh/celld'))).toEqual(tree(join(root, 'store/fleet/celld'))); + expect(tree(target.stateDir)).toEqual({ 'platform-keys.json': PLATFORM_KEYS }); + expect(existsSync(`${target.stateDir}.restore-progress.json`)).toBe(false); + }); + + it.each(['foreign-object', 'changed-object', 'foreign-state'] as const)( + 'refuses retry with %s and preserves it instead of overwriting or deleting', + (defect) => { + const snapshot = join(root, 'retry-refusal-snapshot'); + runBackup(ctx('s3://fleet/celld', join(root, 'state')), snapshot); + const target = ctx('s3://fresh/celld', join(root, 'new-state')); + failRestorePush = true; + expect(() => runRestore(target, snapshot)).toThrow(/mc mirror/); + let path: string; + if (defect === 'foreign-state') { + mkdirSync(target.stateDir, { mode: 0o700 }); + path = join(target.stateDir, 'foreign-file'); + } else + path = join( + root, + 'store/fresh/celld', + defect === 'changed-object' + ? Object.keys(tree(join(root, 'store/fresh/celld')))[0]! + : 'foreign-file' + ); + writeFileSync(path, 'foreign-data-must-survive'); + calls = []; + expect(() => runRestore(target, snapshot)).toThrow(/Restore retry contains/); + expect(readFileSync(path, 'utf8')).toBe('foreign-data-must-survive'); + expect( + calls.some((call) => call.args.includes('mirror') && call.args.at(-2) === '/backup') + ).toBe(false); + expect(existsSync(`${target.stateDir}.restore-progress.json`)).toBe(true); + } + ); + + it('binds retry ownership to the exact target bucket before any runner call', () => { + const snapshot = join(root, 'retry-target-snapshot'); + runBackup(ctx('s3://fleet/celld', join(root, 'state')), snapshot); + const target = ctx('s3://fresh/celld', join(root, 'new-state')); + failRestorePush = true; + expect(() => runRestore(target, snapshot)).toThrow(); + calls = []; + expect(() => + runRestore({ ...target, box: { ...target.box, CELLD_BUCKET: 's3://other/celld' } }, snapshot) + ).toThrow('Cannot verify restore retry ownership'); + expect(calls).toHaveLength(0); + }); + it('refuses containers under the final restored identity even when the pre-key project is empty', () => { const snapshot = join(root, 'post-restore-project-backup'); runBackup(ctx('s3://fleet/celld', join(root, 'state')), snapshot); @@ -645,6 +775,62 @@ describe('runRollback', () => { ); }); + it('retains current backup/cloud receipts and removal markers instead of reviving snapshot history', () => { + const context = ctx('gs://fleet/celld', join(root, 'state')); + const ledger = join(context.stateDir, 'created-resources.json'); + const cloud = (name: string, action: 'created' | 'reused' = 'created') => ({ + cloud: 'gcp', + kind: 'firewall', + name, + action, + createdBy: 'gcp-bootstrap', + attributes: { installation: 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', identity: name + '-id' }, + }); + addResource(ledger, cloud('removed-after-snapshot')); + addResource(ledger, cloud('replaced-after-snapshot')); + const snapshot = join(root, 'ledger-snapshot'); + runBackup(context, snapshot); + markRemoved(ledger, 'gcp', 'firewall', 'removed-after-snapshot'); + markRemoved(ledger, 'gcp', 'firewall', 'replaced-after-snapshot'); + addResource(ledger, cloud('replaced-after-snapshot', 'reused')); + addResource(ledger, cloud('created-after-snapshot')); + const before = readRecord(ledger); + runRollback(context, snapshot); + const after = readRecord(ledger); + expect(after.resources.filter((r) => r.cloud === 'gcp')).toEqual( + before.resources.filter((r) => r.cloud === 'gcp') + ); + expect(after.resources.find((r) => r.kind === 'backup' && r.name === snapshot)).toEqual( + before.resources.find((r) => r.kind === 'backup' && r.name === snapshot) + ); + expect( + after.resources.find((r) => r.name === 'removed-after-snapshot')?.removedAt + ).toBeTruthy(); + expect(after.resources.find((r) => r.name === 'replaced-after-snapshot')?.action).toBe( + 'reused' + ); + expect(after.resources.find((r) => r.kind === 'state-dir')?.attributes?.inode).toBe( + String(statSync(context.stateDir).ino) + ); + }); + + it.each(['domain', 'environment', 'composeProject'])( + 'refuses a foreign current ledger %s before mutation', + (field) => { + const context = ctx('gs://fleet/celld', join(root, 'state')); + const snapshot = join(root, 'foreign-ledger'); + runBackup(context, snapshot); + const ledger = join(context.stateDir, 'created-resources.json'); + const record = readRecord(ledger); + const installation = record.resources.find((r) => r.kind === 'installation'); + installation!.attributes![field] = 'foreign'; + writeFileSync(ledger, JSON.stringify(record)); + calls = []; + expect(() => runRollback(context, snapshot)).toThrow(/different installation scope/); + expect(calls).toEqual([]); + } + ); + it('restores after a real Go module cache made read-only directories in the old state', () => { const context = ctx('gs://fleet/celld', join(root, 'state')); const cache = join(context.stateDir, 'go-cache/module/pkg'); diff --git a/scripts/selfhost/live/backup-restore.live.test.ts b/scripts/selfhost/live/backup-restore.live.test.ts index abdf0026fb..7292c60863 100644 --- a/scripts/selfhost/live/backup-restore.live.test.ts +++ b/scripts/selfhost/live/backup-restore.live.test.ts @@ -7,7 +7,15 @@ */ import { spawnSync } from 'node:child_process'; import { randomBytes } from 'node:crypto'; -import { mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs'; +import { + existsSync, + mkdirSync, + mkdtempSync, + readdirSync, + readFileSync, + rmSync, + writeFileSync, +} from 'node:fs'; import { join } from 'node:path'; import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest'; @@ -134,6 +142,7 @@ describe.skipIf(!hasDocker && !process.env.CI)( 'mb', 'src/fleet', 'src/fresh', + 'src/retry', ], env ); @@ -146,7 +155,70 @@ describe.skipIf(!hasDocker && !process.env.CI)( if (root) rmSync(root, { recursive: true, force: true }); }); + it('retries after a real partial MinIO upload without deleting the partial target', () => { + const seed = join(root, 'retry-seed'); + mkdirSync(join(seed, 'data'), { recursive: true }); + writeFileSync(join(seed, 'current.json'), '{"v":1}'); + writeFileSync(join(seed, 'data/second.bin'), Buffer.from([0, 1, 2, 255])); + pushBucket(ctx('s3://fleet/celld-retry', join(root, 'retry-unused')), seed); + const state = join(root, 'retry-source-state'); + mkdirSync(state, { mode: 0o700 }); + writeFileSync(join(state, 'platform-keys.json'), PLATFORM_KEYS, { mode: 0o600 }); + writeFileSync(join(root, 'box.env'), 'CELLD_BUCKET=s3://fleet/celld-retry\n', { + mode: 0o600, + }); + const snapshot = join(root, 'retry-backup'); + runBackup(ctx('s3://fleet/celld-retry', state), snapshot); + const target = ctx('s3://retry/celld', join(root, 'retry-state')); + let fail = true; + const partial: BoxContext = { + ...target, + run(command, args, env) { + if ( + fail && + command === 'docker' && + args.includes('mirror') && + args.at(-2) === '/backup' && + args.at(-1) === 'src/retry/celld' + ) { + fail = false; + const image = args.indexOf(OBJECTSTORE_IMAGE); + const result = run( + command, + [ + ...args.slice(0, image + 1), + 'cp', + '--quiet', + '/backup/current.json', + 'src/retry/celld/current.json', + ], + env + ); + if (result.status !== 0) return result; + return { + status: 1, + stdout: '', + stderr: 'injected network failure after one actual upload', + }; + } + return run(command, args, env); + }, + }; + expect(() => runRestore(partial, snapshot)).toThrow(/mc mirror/); + const first = join(root, 'retry-partial-check'); + pullBucket(target, first); + expect(tree(first)).toEqual({ 'current.json': '{"v":1}' }); + expect(existsSync(`${target.stateDir}.restore-progress.json`)).toBe(true); + runRestore(partial, snapshot); + const complete = join(root, 'retry-complete-check'); + pullBucket(target, complete); + expect(tree(complete)).toEqual(tree(seed)); + expect(tree(target.stateDir)).toEqual({ 'platform-keys.json': PLATFORM_KEYS }); + expect(existsSync(`${target.stateDir}.restore-progress.json`)).toBe(false); + }); + it('round-trips the fleet bucket and box state into an empty install', () => { + composeCalls.length = 0; // Seed the "fleet" through the same push path restore uses. const seed = join(root, 'seed'); mkdirSync(join(seed, 'd1/main'), { recursive: true }); diff --git a/scripts/selfhost/operator-ci-guard.test.ts b/scripts/selfhost/operator-ci-guard.test.ts index 1069c98e9b..d90fe5bbbe 100644 --- a/scripts/selfhost/operator-ci-guard.test.ts +++ b/scripts/selfhost/operator-ci-guard.test.ts @@ -13,6 +13,8 @@ import { runRestore, runRollback, } from './backup-lib'; +import { restoreBackup } from './backup-restore'; +import { assertRestoreSubset, restoreProgress } from './restore-progress'; const ROOT = resolve(import.meta.dirname, '../..'); const ABSENT = resolve(ROOT, '.tmp/nonexistent-operator-guard-sentinel'); @@ -45,6 +47,9 @@ describe('operator commands never read secret files in CI', () => { }; for (const invoke of [ () => loadBox(ABSENT), + () => restoreBackup(context, ABSENT, ABSENT), + () => restoreProgress(context, ABSENT), + () => assertRestoreSubset(ABSENT, ABSENT), () => readBackupKey(ABSENT), () => encryptBackupTree(ABSENT, ABSENT, ABSENT), () => decryptBackupTree(ABSENT, ABSENT, ABSENT), diff --git a/scripts/selfhost/restore-progress.ts b/scripts/selfhost/restore-progress.ts new file mode 100644 index 0000000000..d8762ea370 --- /dev/null +++ b/scripts/selfhost/restore-progress.ts @@ -0,0 +1,146 @@ +/** Private retry ownership for a restore that started from an empty bucket and state directory. */ +import { createHash } from 'node:crypto'; +import { + closeSync, + constants, + fstatSync, + fsyncSync, + lstatSync, + openSync, + readdirSync, + readFileSync, + readSync, + rmSync, + type Stats, + writeSync, +} from 'node:fs'; +import { dirname, join, resolve } from 'node:path'; + +import { prepareBackupParent } from './backup-destination'; +import { assertBackupOutside, type BoxContext } from './backup-lib'; +import { assertOperatorExecution } from './operator-only'; +import { assertPrivateFile } from './secret-files'; + +function digest(path: string): string { + const input = openSync(path, constants.O_RDONLY | constants.O_NOFOLLOW); + try { + if (!fstatSync(input).isFile()) throw new Error('Restore retry requires regular files'); + const hash = createHash('sha256'); + const chunk = Buffer.alloc(64 * 1024); + let count: number; + while ((count = readSync(input, chunk, 0, chunk.length, null)) > 0) + hash.update(chunk.subarray(0, count)); + return hash.digest('hex'); + } finally { + closeSync(input); + } +} + +function assertOwned(stat: Stats): void { + if (process.getuid !== undefined && stat.uid !== process.getuid()) + throw new Error('Restore retry contains foreign-owned data'); +} +/** Existing partial output must be an exact subset of the authenticated snapshot. Never delete it. */ +export function assertRestoreSubset(current: string, expected: string): void { + assertOperatorExecution(); + const stat = lstatSync(current, { throwIfNoEntry: false }); + if (!stat) return; + assertOwned(stat); + if (!stat.isDirectory() || stat.isSymbolicLink()) + throw new Error('Restore retry contains an unsafe directory'); + for (const name of readdirSync(current)) { + const path = join(current, name); + const source = join(expected, name); + const found = lstatSync(path); + assertOwned(found); + const original = lstatSync(source, { throwIfNoEntry: false }); + if (!original) throw new Error('Restore retry contains data outside its snapshot'); + if (found.isDirectory() && original.isDirectory()) assertRestoreSubset(path, source); + else if ( + !found.isFile() || + !original.isFile() || + found.nlink !== 1 || + original.nlink !== 1 || + digest(path) !== digest(source) + ) { + throw new Error('Restore retry contains changed or unsafe data'); + } + } +} + +export interface RestoreProgress { + resume: boolean; + begin(): void; + finish(): void; +} +export function restoreProgress(ctx: BoxContext, backup: string): RestoreProgress { + assertOperatorExecution(); + const journal = `${resolve(ctx.stateDir)}.restore-progress.json`; + assertBackupOutside(ctx, journal); + const expected = JSON.stringify({ + format: 'sam-restore-progress/1', + bucket: ctx.box.CELLD_BUCKET, + state: resolve(ctx.stateDir), + backup: resolve(backup), + snapshot: digest(join(backup, '.sam-backup-manifest')), + }); + const existing = lstatSync(journal, { throwIfNoEntry: false }); + const validate = (): void => { + try { + if (lstatSync(journal).isSymbolicLink()) throw new Error('Invalid journal'); + assertPrivateFile(journal); + if (readFileSync(journal, 'utf8') !== expected) throw new Error('Different restore'); + } catch { + throw new Error( + 'Cannot verify restore retry ownership; preserve the partial target for inspection' + ); + } + }; + if (existing) validate(); + let identity = existing; + const syncParent = (): void => { + const fd = openSync(dirname(journal), 'r'); + try { + fsyncSync(fd); + } finally { + closeSync(fd); + } + }; + return { + resume: Boolean(existing), + begin() { + if (existing) { + validate(); + const current = lstatSync(journal); + if (current.dev !== identity?.dev || current.ino !== identity?.ino) + throw new Error('Restore retry ownership changed'); + return; + } + prepareBackupParent(journal); + const fd = openSync(journal, 'wx', 0o600); + try { + const data = Buffer.from(expected); + let offset = 0; + while (offset < data.length) { + const written = writeSync(fd, data, offset, data.length - offset); + if (written === 0) throw new Error('Cannot persist restore retry ownership'); + offset += written; + } + fsyncSync(fd); + } finally { + closeSync(fd); + } + identity = lstatSync(journal); + syncParent(); + validate(); + }, + finish() { + validate(); + const current = lstatSync(journal); + if (current.dev !== identity?.dev || current.ino !== identity?.ino) + throw new Error('Restore retry ownership changed'); + rmSync(journal); + syncParent(); + }, + }; +} diff --git a/scripts/selfhost/teardown-model.test.ts b/scripts/selfhost/teardown-model.test.ts new file mode 100644 index 0000000000..d9ec363ea4 --- /dev/null +++ b/scripts/selfhost/teardown-model.test.ts @@ -0,0 +1,158 @@ +/** Stop on the real identity adapter's failed grant before removing its dependent account. */ +import { mkdirSync, mkdtempSync, rmSync } from 'node:fs'; +import { join, resolve } from 'node:path'; + +import { afterEach, beforeEach, expect, it } from 'vitest'; + +import { addResource, readRecord } from '../../deploy/selfhost/created-resources.mjs'; +import type { TeardownContext } from './teardown-box'; +import { bootstrapItems } from './teardown-gcp-bootstrap'; +import { both, execute, type Item, STEPS } from './teardown-model'; + +let root: string; +beforeEach(() => { + mkdirSync(resolve('.tmp'), { recursive: true }); + root = mkdtempSync(resolve('.tmp/teardown-order-')); +}); +afterEach(() => rmSync(root, { recursive: true, force: true })); + +it('preserves provider, pool and account after a failed binding, then completes cleanup on retry', () => { + const file = join(root, 'created-resources.json'); + const installation = 'a'.repeat(32); + const issuer = 'https://api.sam.example.com'; + const poolIdentity = 'projects/123/locations/global/workloadIdentityPools/pool'; + const resources = [ + { kind: 'service-account', name: 'acct', identity: 'acct-id' }, + { kind: 'workload-identity-pool', name: 'pool', identity: poolIdentity }, + { + kind: 'workload-identity-provider', + name: 'provider', + identity: `${poolIdentity}/providers/provider`, + }, + { kind: 'iam-binding', name: 'grant', identity: 'acct-id' }, + ]; + for (const resource of resources) + addResource(file, { + cloud: 'gcp', + kind: resource.kind, + name: resource.name, + action: 'created', + createdBy: 'gcp-bootstrap', + attributes: { + identity: resource.identity, + installation, + install: issuer, + project: 'sam-test-proj', + environment: 'selfhost', + pool: 'pool', + account: 'acct', + member: 'serviceAccount:acct', + role: 'roles/compute.securityAdmin', + }, + }); + let failBinding = true; + const deleted: string[] = []; + const context: TeardownContext = { + box: {}, + envFile: join(root, 'box.env'), + stateDir: root, + composeFiles: [], + now: Date.now, + log: () => undefined, + selfhostDir: root, + recordFile: file, + options: { + deleteBackups: false, + destroyKey: false, + adoptDiscovered: false, + gcpProjects: ['sam-test-proj'], + }, + domain: 'sam.example.com', + installationId: installation, + record: readRecord(file).resources, + run: (_command: string, args: string[]) => { + const cmd = args.join(' '); + const ok = (value: unknown = {}) => ({ + status: 0, + stdout: JSON.stringify(value), + stderr: '', + }); + if (cmd.startsWith('projects remove-iam-policy-binding')) { + if (failBinding) { + failBinding = false; + return { status: 1, stdout: '', stderr: 'permission denied' }; + } + deleted.push('binding'); + return ok(); + } + if (args.includes('delete')) { + deleted.push(args[args.indexOf('delete') + 1]!); + return ok(); + } + if (cmd.startsWith('iam service-accounts get-iam-policy')) return ok({}); + if (cmd.startsWith('iam service-accounts keys list')) return ok([]); + if (cmd.startsWith('iam workload-identity-pools providers list')) return ok([]); + if (cmd.startsWith('iam service-accounts describe')) + return ok({ + uniqueId: 'acct-id', + description: `Creates and deletes SAM workspace VMs and their firewall rules for ${issuer}`, + }); + if (cmd.startsWith('iam workload-identity-pools providers describe')) + return ok({ name: `${poolIdentity}/providers/provider`, oidc: { issuerUri: issuer } }); + if (cmd.startsWith('iam workload-identity-pools describe')) + return ok({ + name: poolIdentity, + description: `Dedicated to the SAM install whose token issuer is ${issuer}`, + }); + throw new Error('Unexpected test provider command'); + }, + }; + const first = execute(bootstrapItems(context, 'sam-test-proj'), 'remove-everything', file); + expect(first.map((outcome) => outcome.status)).toEqual([ + 'failed', + 'not attempted', + 'not attempted', + 'not attempted', + ]); + expect(deleted).toEqual([]); + expect(readRecord(file).resources.every((resource) => !resource.removedAt)).toBe(true); + context.record = readRecord(file).resources; + const retried = execute(bootstrapItems(context, 'sam-test-proj'), 'remove-everything', file); + expect(retried.every((outcome) => outcome.status === 'removed')).toBe(true); + expect(deleted).toEqual(['binding', 'provider', 'pool', 'acct']); + expect(readRecord(file).resources.every((resource) => !!resource.removedAt)).toBe(true); +}); + +it('settles effects of an already-run failed group without starting another action', () => { + let actions = 0; + const item = (id: string): Item => ({ + id, + place: 'on the box', + what: id, + provenance: 'recorded', + how: 'test boundary', + step: STEPS.state, + plan: both({ act: 'remove' }), + }); + const items: Item[] = [ + { + ...item('cache'), + runKey: 'state', + run: () => { + actions++; + throw new Error('cache removal failed'); + }, + }, + { ...item('key'), runKey: 'state', goneDespiteGroupFailure: () => true }, + { + ...item('later'), + run: () => { + actions++; + }, + }, + ]; + expect( + execute(items, 'remove-everything', join(root, 'record.json')).map((outcome) => outcome.status) + ).toEqual(['failed', 'removed', 'not attempted']); + expect(actions).toBe(1); +}); diff --git a/scripts/selfhost/teardown-model.ts b/scripts/selfhost/teardown-model.ts index 11970abab3..e135627c9f 100644 --- a/scripts/selfhost/teardown-model.ts +++ b/scripts/selfhost/teardown-model.ts @@ -106,9 +106,9 @@ export function decide(item: Item, mode: Mode): Decision { } /** - * Runs every item the mode removes, step by step. A failure ends the run after its step: later - * steps (which would remove the means to clean up what failed, such as the cloud identity behind - * undeleted VMs) are reported as not attempted, and a second run continues from there. + * Runs every item the mode removes, step by step. A failure stops new actions immediately, + * including dependent resources in the same step. Already-run shared actions still settle their + * individual results; unattempted actions remain available for a later retry. */ export function execute(items: Item[], mode: Mode, recordFile: string): Outcome[] { const outcomes: Outcome[] = []; @@ -118,9 +118,10 @@ export function execute(items: Item[], mode: Mode, recordFile: string): Outcome[ const ran = new Map(); for (const step of new Set(ordered.map((i) => i.step))) { for (const item of ordered.filter((i) => i.step === step)) { - outcomes.push(executeItem(item, items, mode, recordFile, failedStep, ran)); + const outcome = executeItem(item, items, mode, recordFile, failedStep, ran); + outcomes.push(outcome); + if (outcome.status === 'failed') failedStep = step; } - if (outcomes.some((o) => o.status === 'failed' && o.item.step === step)) failedStep = step; } return outcomes; } @@ -155,7 +156,7 @@ function executeItem( const decision = decide(item, mode); if (decision.act !== 'remove') return { item, status: statusOf(decision), why: decision.why }; if (item.removedAt) return { item, status: 'already removed', why: item.removedAt }; - if (failedStep !== null) + if (failedStep !== null && !ran.has(item.runKey ?? item.id)) return { item, status: 'not attempted', why: `step ${failedStep} failed` }; const error = runAction(item, items, ran); if (error && !item.goneDespiteGroupFailure?.()) diff --git a/scripts/selfhost/testdata/fake-gcloud.mjs b/scripts/selfhost/testdata/fake-gcloud.mjs index ae1481112b..d79c7a8f3a 100755 --- a/scripts/selfhost/testdata/fake-gcloud.mjs +++ b/scripts/selfhost/testdata/fake-gcloud.mjs @@ -1,8 +1,8 @@ #!/usr/bin/env node // Fake `gcloud storage` for backup-entrypoint.test.ts. gs:// maps to $FAKE_GCS_ROOT/. -// It models what the box showed (PR #2675): while celld runs, objects in $FAKE_STATE/churn.json -// vanish mid-copy (404) and the aborted download leaves a tracker keyed by its destination path; -// a later download to that same path fails with `[Errno 2] No such file or directory`. +// Models live generation churn (404) and the confirmed SDK523 failure: an absent finalized +// download still reaches the POSIX-metadata stat step. A destination-keyed tracker model also +// exercises isolation of partial download state; it is not claimed as the confirmed root cause. import { appendFileSync, cpSync, @@ -11,6 +11,7 @@ import { readdirSync, readFileSync, rmSync, + statSync, writeFileSync, } from 'node:fs'; import { dirname, join } from 'node:path'; @@ -69,6 +70,27 @@ for (const f of source) { errors.push(`ERROR: ${src}/${f}#1 not found: 404.`); continue; } + const posixFailure = join(state, 'posix-fail-once.json'); + if ( + !celldRunning && + existsSync(posixFailure) && + JSON.parse(readFileSync(posixFailure, 'utf8')).key === f + ) { + // SDK523 finalize_download(false): the vanished temp yields no final file, yet POSIX follows. + mkdirSync(dirname(target), { recursive: true }); + writeFileSync(`${target}_.gstmp`, 'incomplete-download'); + rmSync(`${target}_.gstmp`); + rmSync(target, { force: true }); + rmSync(posixFailure); + try { + statSync(target); + } catch { + errors.push( + `FileDownloadTask.execute -> set_posix_attributes_on_file_if_valid: [Errno 2] No such file or directory: '${target}'` + ); + } + continue; + } if (trackers.includes(target) && !existsSync(`${target}_.gstmp`)) { errors.push(`ERROR: [Errno 2] No such file or directory: '${target}'`); continue; From 39f3fa951c104e410d1feb43123c8166580da727 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rapha=C3=ABl=20Titsworth-Morin?= Date: Fri, 20 Nov 2026 00:16:55 +0000 Subject: [PATCH 09/17] fix(selfhost): isolate restore identity and bind destructive retries --- deploy/selfhost/README.md | 18 +- package.json | 2 +- scripts/selfhost/backup-entrypoint.test.ts | 9 +- scripts/selfhost/backup-ownership.ts | 92 +++++++++ scripts/selfhost/backup-restore.ts | 17 +- scripts/selfhost/backup.test.ts | 158 ++++++++++++++- scripts/selfhost/deploy-harness.ts | 6 +- scripts/selfhost/install-record.ts | 3 +- .../selfhost/live/backup-restore.live.test.ts | 18 +- scripts/selfhost/operator-ci-guard.test.ts | 3 + scripts/selfhost/restore-identity.ts | 68 +++++++ scripts/selfhost/teardown-box.ts | 40 +++- scripts/selfhost/teardown-retry.test.ts | 185 ++++++++++++++++++ scripts/selfhost/teardown-state-dir.ts | 18 +- scripts/selfhost/teardown.ts | 2 + scripts/selfhost/upgrade-lib.ts | 22 ++- scripts/selfhost/upgrade-preflight.ts | 13 ++ scripts/selfhost/upgrade.test.ts | 48 ++++- scripts/selfhost/vitest.config.ts | 10 + .../2026-11-19-l24-selfhost-operations.md | 8 + 20 files changed, 698 insertions(+), 42 deletions(-) create mode 100644 scripts/selfhost/backup-ownership.ts create mode 100644 scripts/selfhost/restore-identity.ts create mode 100644 scripts/selfhost/teardown-retry.test.ts diff --git a/deploy/selfhost/README.md b/deploy/selfhost/README.md index 6088daacdc..d7f02eee0c 100644 --- a/deploy/selfhost/README.md +++ b/deploy/selfhost/README.md @@ -145,7 +145,17 @@ backup. This private journal binds the original empty target and authenticated s refuses changed, additional, linked or foreign-owned partial files before copying again; do not start the target or remove its journal to bypass a refusal. The journal is removed after success. It refuses a target project with existing containers, copies state and bucket data, keeps the -target `.env`, strips the source installation's creation receipts, and does not start celld. On the original SAM ref, run `selfhost:deploy --init` +target `.env`, strips the source installation's creation receipts, and does not start celld. +A fresh restore assigns a distinct `SAM_INSTALLATION_ID`, stable for retries of the same target, +while preserving all cryptographic keys needed to read the restored data. The generated local +config receives that new ID. Restore omits the source bucket's active `deploy/current.json` +pointer but retains immutable deployment objects and application data, so starting celld cannot +execute source Worker code or its Durable Object alarms. Run a fresh deploy before serving the +restored application; that deploy creates the target's active pointer and Worker identity. Do not set an installation +ID in the target environment; restore refuses explicit overrides. Source VMs and their ownership +labels are retained: the replacement must provision its own nodes, and its teardown cannot adopt or +delete the source fleet. This also applies to disaster recovery; retire surviving source resources +separately using their original installation records. On the original SAM ref, run `selfhost:deploy --init` to retain the restored keys and establish new target ownership receipts. Set the target `.env`'s `COMPOSE_PROJECT_NAME` to the canonical project name init prints; the name incorporates the persisted installation id, domain and state directory. Repeat init with that setting, then start @@ -181,8 +191,10 @@ current resource creation/removal receipts survive rollback (`scripts/selfhost/u migration. An unfinished operation retains `.state/upgrade-pending.json` with the previous ref and encrypted -snapshot path. Keep celld stopped if automatic recovery fails; retain the snapshot and key, and -retry the same upgrade command to recover the original install before attempting a new upgrade. +snapshot path and resolved target SHA. Keep celld stopped if automatic recovery fails; retain the +snapshot and key, and retry the same resolved target to recover the original install. A changed +`--to`, a moved branch/tag, or an older journal without a target requires the explicit rollback +command before choosing another target. Do not delete the pending record to bypass a failed recovery. After a successful upgrade, its printed rollback command restores the populated installation diff --git a/package.json b/package.json index 95d94097f8..fc3277be9c 100644 --- a/package.json +++ b/package.json @@ -43,7 +43,7 @@ "selfhost:live-test": "vitest run --config scripts/selfhost/live/vitest.config.ts", "selfhost:backup": "tsx scripts/selfhost/backup.ts", "selfhost:restore": "tsx scripts/selfhost/restore.ts", - "selfhost:teardown": "tsx scripts/selfhost/teardown.ts", + "selfhost:teardown": "tsx --tsconfig scripts/selfhost/tsconfig.json scripts/selfhost/teardown.ts", "selfhost:upgrade": "tsx scripts/selfhost/upgrade.ts", "quality:preflight": "tsx scripts/quality/check-preflight-evidence.ts", "test:acp-c2-remote-service": "node tests/fixtures/acp-c2-remote-service.test.mjs", diff --git a/scripts/selfhost/backup-entrypoint.test.ts b/scripts/selfhost/backup-entrypoint.test.ts index d49bf005c7..d1601bf96d 100644 --- a/scripts/selfhost/backup-entrypoint.test.ts +++ b/scripts/selfhost/backup-entrypoint.test.ts @@ -298,7 +298,14 @@ describe('selfhost:backup and selfhost:restore (real entry points, fake gcloud)' expect(restore.stderr).toBe(''); expect(restore.status).toBe(0); expect(tree(join(root, 'gcs/fresh/celld'))).toEqual(afterStop); - expect(tree(join(root, 'new-state'))).toEqual({ 'platform-keys.json': PLATFORM_KEYS }); + const restoredKeys = JSON.parse(tree(join(root, 'new-state'))['platform-keys.json']!); + expect(restoredKeys).toEqual({ + ...JSON.parse(PLATFORM_KEYS), + SAM_INSTALLATION_ID: expect.stringMatching(/^[a-f0-9]{32}$/), + }); + expect(restoredKeys.SAM_INSTALLATION_ID).not.toBe( + JSON.parse(PLATFORM_KEYS).SAM_INSTALLATION_ID + ); } ); }); diff --git a/scripts/selfhost/backup-ownership.ts b/scripts/selfhost/backup-ownership.ts new file mode 100644 index 0000000000..01807619a5 --- /dev/null +++ b/scripts/selfhost/backup-ownership.ts @@ -0,0 +1,92 @@ +/** Public filesystem identities for an encrypted backup created by this installation. */ +import { createHash } from 'node:crypto'; +import { + closeSync, + constants, + fstatSync, + lstatSync, + openSync, + readSync, + realpathSync, +} from 'node:fs'; +import { isAbsolute, join, resolve } from 'node:path'; + +import type { CreatedResource } from '../../deploy/selfhost/created-resources.mjs'; + +export function backupOwnership(path: string): Record { + if (!isAbsolute(path) || realpathSync(path) !== resolve(path)) + throw new Error('Backup ownership requires an exact directory without symlinks'); + const directory = lstatSync(path); + if ( + !directory.isDirectory() || + directory.isSymbolicLink() || + (process.getuid !== undefined && directory.uid !== process.getuid()) + ) + throw new Error('Backup directory ownership cannot be verified'); + const fd = openSync( + join(path, '.sam-backup-manifest'), + constants.O_RDONLY | constants.O_NOFOLLOW + ); + try { + const manifest = fstatSync(fd); + if ( + !manifest.isFile() || + manifest.nlink !== 1 || + manifest.size < 36 || + (process.getuid !== undefined && manifest.uid !== process.getuid()) + ) + throw new Error('Backup encrypted inventory ownership cannot be verified'); + const magic = Buffer.alloc(8); + if (readSync(fd, magic, 0, magic.length, 0) !== magic.length || magic.toString() !== 'SAMBAK01') + throw new Error('Backup has no encrypted inventory'); + const hash = createHash('sha256'); + const chunk = Buffer.alloc(64 * 1024); + let offset = 0; + while (offset < manifest.size) { + const count = readSync(fd, chunk, 0, Math.min(chunk.length, manifest.size - offset), offset); + if (count === 0) throw new Error('Backup encrypted inventory changed'); + hash.update(chunk.subarray(0, count)); + offset += count; + } + const liveDirectory = lstatSync(path); + const liveManifest = lstatSync(join(path, '.sam-backup-manifest')); + if ( + realpathSync(path) !== resolve(path) || + liveDirectory.dev !== directory.dev || + liveDirectory.ino !== directory.ino || + liveManifest.dev !== manifest.dev || + liveManifest.ino !== manifest.ino || + liveManifest.size !== manifest.size || + liveManifest.nlink !== 1 + ) + throw new Error('Backup directory or encrypted inventory changed during ownership proof'); + const proof = { + device: String(directory.dev), + inode: String(directory.ino), + manifestDevice: String(manifest.dev), + manifestInode: String(manifest.ino), + manifestHash: hash.digest('hex'), + }; + return { ...proof, identity: createHash('sha256').update(JSON.stringify(proof)).digest('hex') }; + } finally { + closeSync(fd); + } +} + +export function assertBackupOwnership(path: string, entry?: CreatedResource): void { + if ( + !entry || + entry.cloud !== 'box' || + entry.kind !== 'backup' || + entry.name !== path || + entry.createdBy !== 'backup' || + entry.action !== 'created' || + entry.removedAt + ) + throw new Error('Refused: backup has no active creation receipt'); + const current = backupOwnership(path); + if (Object.entries(current).some(([name, value]) => entry.attributes?.[name] !== value)) + throw new Error( + 'Refused: backup path or encrypted inventory identity changed or was never recorded' + ); +} diff --git a/scripts/selfhost/backup-restore.ts b/scripts/selfhost/backup-restore.ts index 10d041458e..f045c0a28d 100644 --- a/scripts/selfhost/backup-restore.ts +++ b/scripts/selfhost/backup-restore.ts @@ -15,13 +15,11 @@ import { } from './backup-lib'; import { composeProjectFor, expectedComposeProjectFor } from './install-record'; import { assertOperatorExecution } from './operator-only'; +import { projectRestoreIdentity } from './restore-identity'; import { assertRestoreSubset, restoreProgress } from './restore-progress'; -import { ensurePrivateDir, readPrivateJson } from './secret-files'; +import { ensurePrivateDir } from './secret-files'; -function assertEmptyRuntime(ctx: BoxContext, from: string): void { - const identity = readPrivateJson(join(from, STATE_DIR, 'platform-keys.json')).SAM_INSTALLATION_ID; - if (typeof identity !== 'string' || !/^[a-f0-9]{32}$/.test(identity)) - throw new Error('Invalid backup installation identity'); +function assertEmptyRuntime(ctx: BoxContext, identity: string): void { const projects = new Set([ composeProjectFor(ctx.box, ctx.stateDir), expectedComposeProjectFor(ctx.box, ctx.stateDir, identity), @@ -39,6 +37,9 @@ function assertEmptyRuntime(ctx: BoxContext, from: string): void { export function restoreBackup(ctx: BoxContext, plain: string, encrypted: string): BackupManifest { assertOperatorExecution(); const manifest = readManifest(plain); + const identity = projectRestoreIdentity(ctx, join(plain, STATE_DIR)); + // No source Worker (including its Durable Object alarms) may run before a fresh target deploy. + rmSync(join(plain, BUCKET_DIR, 'deploy', 'current.json'), { force: true }); const progress = restoreProgress(ctx, encrypted); const state = lstatSync(ctx.stateDir, { throwIfNoEntry: false }); if (state && process.getuid !== undefined && state.uid !== process.getuid()) @@ -50,7 +51,7 @@ export function restoreBackup(ctx: BoxContext, plain: string, encrypted: string) throw new Error('Restore bucket is not empty: restore only into an empty bucket'); } // Inspect by labels: parsing Compose before gateway.env exists would reject a fresh install. - assertEmptyRuntime(ctx, plain); + assertEmptyRuntime(ctx, identity); if (progress.resume) { assertRestoreSubset(ctx.stateDir, join(plain, STATE_DIR)); const current = join(plain, '.restore-current-bucket'); @@ -59,7 +60,9 @@ export function restoreBackup(ctx: BoxContext, plain: string, encrypted: string) } // Durable ownership is recorded before the first target write. Failures retain it for retry. progress.begin(); - ctx.log(`copying ${manifest.objectCount} objects into ${ctx.box.CELLD_BUCKET}`); + ctx.log( + `copying restored data without the source active deployment into ${ctx.box.CELLD_BUCKET}` + ); pushBucket(ctx, join(plain, BUCKET_DIR)); ensurePrivateDir(ctx.stateDir); cpSync(join(plain, STATE_DIR), ctx.stateDir, { recursive: true, preserveTimestamps: true }); diff --git a/scripts/selfhost/backup.test.ts b/scripts/selfhost/backup.test.ts index cfe51eb892..22adbc335c 100644 --- a/scripts/selfhost/backup.test.ts +++ b/scripts/selfhost/backup.test.ts @@ -43,7 +43,9 @@ import { import { finishRollbackCache, refreshRollbackCacheReceipt } from './backup-recovery'; import { buildCelldConfig } from './celld-config'; import { prepareCelldProject, writeCelldConfig } from './celld-project'; +import { runDeploy, runTsx, writeBox } from './deploy-harness'; import { composeProjectFor, expectedComposeProjectFor, recordInstall } from './install-record'; +import { restoredInstallationId } from './restore-identity'; vi.mock('node:fs', async (importOriginal) => ({ ...(await importOriginal()), @@ -588,10 +590,18 @@ describe('runRestore', () => { expect(existsSync(`${target.stateDir}.restore-progress.json`)).toBe(true); // Simulate a prior interrupted state copy as an exact subset of the same authenticated state. mkdirSync(target.stateDir, { mode: 0o700 }); - writeFileSync(join(target.stateDir, 'platform-keys.json'), PLATFORM_KEYS, { mode: 0o600 }); + writeFileSync( + join(target.stateDir, 'platform-keys.json'), + JSON.stringify({ SAM_INSTALLATION_ID: restoredInstallationId(target, 'a'.repeat(32)) }), + { mode: 0o600 } + ); runRestore(target, snapshot); expect(tree(join(root, 'store/fresh/celld'))).toEqual(tree(join(root, 'store/fleet/celld'))); - expect(tree(target.stateDir)).toEqual({ 'platform-keys.json': PLATFORM_KEYS }); + expect(tree(target.stateDir)).toEqual({ + 'platform-keys.json': JSON.stringify({ + SAM_INSTALLATION_ID: restoredInstallationId(target, 'a'.repeat(32)), + }), + }); expect(existsSync(`${target.stateDir}.restore-progress.json`)).toBe(false); }); @@ -644,7 +654,11 @@ describe('runRestore', () => { runBackup(ctx('s3://fleet/celld', join(root, 'state')), snapshot); const target = ctx('s3://fresh/celld', join(root, 'new-state')); const preKey = composeProjectFor(target.box, target.stateDir); - const finalProject = expectedComposeProjectFor(target.box, target.stateDir, 'a'.repeat(32)); + const finalProject = expectedComposeProjectFor( + target.box, + target.stateDir, + restoredInstallationId(target, 'a'.repeat(32)) + ); expect(finalProject).not.toBe(preKey); occupiedProject = finalProject; targetContainers = 'fixture-final-project-container\n'; @@ -734,6 +748,135 @@ describe('runRestore', () => { expect(existsSync(join(root, 'new-state'))).toBe(false); }); + it.each(['box', 'shell', 'secrets'] as const)( + 'refuses a %s installation identity override before target writes', + (kind) => { + const snapshot = join(root, 'identity-override'); + runBackup(ctx('s3://fleet/celld', join(root, 'state')), snapshot); + const target = ctx('s3://fresh/celld', join(root, 'new-state')); + if (kind === 'box') target.box = { ...target.box, SAM_INSTALLATION_ID: 'a'.repeat(32) }; + else if (kind === 'shell') vi.stubEnv('SAM_INSTALLATION_ID', 'a'.repeat(32)); + else { + const plain = join(root, 'override-plain'); + decryptBackupTree(snapshot, plain, join(root, 'backup-key')); + writeFileSync(join(plain, 'state/secrets.env'), 'SAM_INSTALLATION_ID=' + 'a'.repeat(32), { + mode: 0o600, + }); + rmSync(snapshot, { recursive: true }); + encryptBackupTree(plain, snapshot, join(root, 'backup-key')); + } + calls = []; + expect(() => runRestore(target, snapshot)).toThrow('explicit installation identity override'); + expect(calls).toHaveLength(0); + expect(existsSync(target.stateDir)).toBe(false); + } + ); + + it('fresh restore and real deploy init establish ownership that refuses the source VM at teardown', async () => { + rmSync(join(root, 'state/platform-keys.json')); + const sourceEnv = writeBox(root); + const sourceInit = await runDeploy(sourceEnv, ['--init', '--state-dir', join(root, 'state')]); + expect(sourceInit.status, sourceInit.out).toBe(0); + const sourceKeys = JSON.parse(readFileSync(join(root, 'state/platform-keys.json'), 'utf8')); + mkdirSync(join(root, 'store/fleet/celld/deploy/version'), { recursive: true }); + writeFileSync( + join(root, 'store/fleet/celld/deploy/current.json'), + JSON.stringify({ prefix: 'deploy/version' }) + ); + writeFileSync( + join(root, 'store/fleet/celld/deploy/version/manifest.json'), + JSON.stringify({ vars: { SAM_INSTALLATION_ID: sourceKeys.SAM_INSTALLATION_ID } }) + ); + mkdirSync(join(root, 'state/project'), { recursive: true }); + writeFileSync( + join(root, 'state/project/wrangler.json'), + JSON.stringify({ + vars: { + SAM_INSTALLATION_ID: sourceKeys.SAM_INSTALLATION_ID, + ENCRYPTION_KEY: sourceKeys.ENCRYPTION_KEY, + }, + }), + { mode: 0o600 } + ); + const snapshot = join(root, 'clone-snapshot'); + runBackup({ ...ctx('s3://fleet/celld', join(root, 'state')), envFile: sourceEnv }, snapshot); + const targetDir = join(root, 'clone'); + mkdirSync(targetDir); + const targetEnv = writeBox(targetDir, [ + 'GCP_PROJECT=sam-test-proj', + 'CELLD_BUCKET=s3://fresh/celld', + ]); + const targetState = join(targetDir, '.state'); + runRestore({ ...ctx('s3://fresh/celld', targetState), envFile: targetEnv }, snapshot); + expect(existsSync(join(root, 'store/fresh/celld/deploy/current.json'))).toBe(false); + expect( + readFileSync(join(root, 'store/fresh/celld/deploy/version/manifest.json'), 'utf8') + ).toContain(sourceKeys.SAM_INSTALLATION_ID); + expect(inspectBackup(snapshot, 'bucket')).toHaveProperty('deploy/current.json'); + const cloneKeys = JSON.parse(readFileSync(join(targetState, 'platform-keys.json'), 'utf8')); + expect(cloneKeys.SAM_INSTALLATION_ID).not.toBe(sourceKeys.SAM_INSTALLATION_ID); + const projectedConfig = JSON.parse( + readFileSync(join(targetState, 'project/wrangler.json'), 'utf8') + ); + expect(projectedConfig.vars.SAM_INSTALLATION_ID).toBe(cloneKeys.SAM_INSTALLATION_ID); + expect(projectedConfig.vars.ENCRYPTION_KEY).toBe(sourceKeys.ENCRYPTION_KEY); + expect({ ...cloneKeys, SAM_INSTALLATION_ID: sourceKeys.SAM_INSTALLATION_ID }).toEqual( + sourceKeys + ); + const initialized = await runDeploy(targetEnv, ['--init']); + expect(initialized.status, initialized.out).toBe(0); + expect( + readRecord(join(targetState, 'created-resources.json')).resources.find( + (r) => r.kind === 'installation' + )?.name + ).toBe(cloneKeys.SAM_INSTALLATION_ID); + const bin = join(root, 'clone-bin'); + mkdirSync(bin); + const cloudCalls = join(root, 'clone-cloud-calls'); + const vm = { + id: '123456', + name: 'sam-source-node', + zone: 'projects/sam-test-proj/zones/europe-west1-b', + labels: { + managed: 'simple-agent-manager', + installation: sourceKeys.SAM_INSTALLATION_ID, + env: 'selfhost', + node: 'node-id', + }, + disks: [], + tags: { items: ['sam-agent'] }, + networkInterfaces: [{ network: 'x/networks/default' }], + }; + writeFileSync( + join(bin, 'gcloud'), + `#!/usr/bin/env node +import fs from 'node:fs'; const a=process.argv.slice(2).join(' ');fs.appendFileSync(process.env.CLONE_CALLS,a+'\\n');if(a.startsWith('compute instances list'))console.log(process.env.SOURCE_VM);else if(a.includes('delete'))process.exit(99);else process.exit(98);`, + { mode: 0o755 } + ); + writeFileSync(join(bin, 'docker'), '#!/usr/bin/env node\n', { mode: 0o755 }); + const teardown = await runTsx( + resolve(import.meta.dirname, 'teardown.ts'), + [ + '--box-env', + targetEnv, + '--state-dir', + targetState, + '--keep-data', + '--confirm', + 'sam.example.com', + ], + { PATH: `${bin}:${process.env.PATH}`, CLONE_CALLS: cloudCalls, SOURCE_VM: JSON.stringify(vm) } + ); + expect(teardown.status, teardown.out).toBe(1); + expect(teardown.out).toContain('installation'); + expect(existsSync(cloudCalls), teardown.out).toBe(true); + expect(readFileSync(cloudCalls, 'utf8')).toContain('compute instances list'); + expect(readFileSync(cloudCalls, 'utf8')).not.toContain('delete'); + expect(readFileSync(join(root, 'state/platform-keys.json'), 'utf8')).toContain( + sourceKeys.SAM_INSTALLATION_ID + ); + }, 120_000); + it('restores bucket and state into an empty install (round trip)', () => { const dest = join(root, 'backups/b1'); runBackup(ctx('s3://fleet/celld', join(root, 'state')), dest); @@ -742,7 +885,14 @@ describe('runRestore', () => { runRestore(ctx('s3://fresh/celld', newState), dest); expect(tree(join(root, 'store/fresh/celld'))).toEqual(tree(join(root, 'store/fleet/celld'))); - expect(tree(newState)).toEqual({ 'platform-keys.json': PLATFORM_KEYS }); + expect(tree(newState)).toEqual({ + 'platform-keys.json': JSON.stringify({ + SAM_INSTALLATION_ID: restoredInstallationId( + ctx('s3://fresh/celld', newState), + 'a'.repeat(32) + ), + }), + }); }); it('refuses a bucket that already holds objects', () => { diff --git a/scripts/selfhost/deploy-harness.ts b/scripts/selfhost/deploy-harness.ts index fe65739667..657c78b601 100644 --- a/scripts/selfhost/deploy-harness.ts +++ b/scripts/selfhost/deploy-harness.ts @@ -47,7 +47,11 @@ export function runTsx( ...Object.keys(BOX_RESERVED_PORTS), ]; for (const name of composeNames) delete inherited[name]; - const child = spawn(TSX, [script, ...args], { env: { ...inherited, ...env } }); + const child = spawn( + TSX, + ['--tsconfig', resolve(import.meta.dirname, 'tsconfig.json'), script, ...args], + { env: { ...inherited, ...env } } + ); let out = ''; child.stdout.on('data', (chunk: Buffer) => (out += chunk.toString())); child.stderr.on('data', (chunk: Buffer) => (out += chunk.toString())); diff --git a/scripts/selfhost/install-record.ts b/scripts/selfhost/install-record.ts index 93fafb74d3..0a19754757 100644 --- a/scripts/selfhost/install-record.ts +++ b/scripts/selfhost/install-record.ts @@ -22,6 +22,7 @@ import { type CreatedResource, readRecord, } from '../../deploy/selfhost/created-resources.mjs'; +import { backupOwnership } from './backup-ownership'; import { assertOperatorExecution } from './operator-only'; export const RECORD_FILE = 'created-resources.json'; @@ -147,7 +148,7 @@ export function recordBackup(stateDir: string, dest: string): void { name: dest, action: 'created', createdBy: 'backup', - attributes: {}, + attributes: backupOwnership(dest), }); } diff --git a/scripts/selfhost/live/backup-restore.live.test.ts b/scripts/selfhost/live/backup-restore.live.test.ts index 7292c60863..0132d4e0aa 100644 --- a/scripts/selfhost/live/backup-restore.live.test.ts +++ b/scripts/selfhost/live/backup-restore.live.test.ts @@ -213,7 +213,14 @@ describe.skipIf(!hasDocker && !process.env.CI)( const complete = join(root, 'retry-complete-check'); pullBucket(target, complete); expect(tree(complete)).toEqual(tree(seed)); - expect(tree(target.stateDir)).toEqual({ 'platform-keys.json': PLATFORM_KEYS }); + const restoredKeys = JSON.parse(tree(target.stateDir)['platform-keys.json']!); + expect(restoredKeys).toEqual({ + ...JSON.parse(PLATFORM_KEYS), + SAM_INSTALLATION_ID: expect.stringMatching(/^[a-f0-9]{32}$/), + }); + expect(restoredKeys.SAM_INSTALLATION_ID).not.toBe( + JSON.parse(PLATFORM_KEYS).SAM_INSTALLATION_ID + ); expect(existsSync(`${target.stateDir}.restore-progress.json`)).toBe(false); }); @@ -242,7 +249,14 @@ describe.skipIf(!hasDocker && !process.env.CI)( const check = join(root, 'check'); pullBucket(ctx('s3://fresh/celld', newState), check); expect(tree(check)).toEqual(tree(seed)); - expect(tree(newState)).toEqual({ 'platform-keys.json': PLATFORM_KEYS }); + const restoredKeys = JSON.parse(tree(newState)['platform-keys.json']!); + expect(restoredKeys).toEqual({ + ...JSON.parse(PLATFORM_KEYS), + SAM_INSTALLATION_ID: expect.stringMatching(/^[a-f0-9]{32}$/), + }); + expect(restoredKeys.SAM_INSTALLATION_ID).not.toBe( + JSON.parse(PLATFORM_KEYS).SAM_INSTALLATION_ID + ); // A second restore into the now non-empty bucket is refused. expect(() => runRestore(ctx('s3://fresh/celld', join(root, 'other-state')), dest)).toThrow( diff --git a/scripts/selfhost/operator-ci-guard.test.ts b/scripts/selfhost/operator-ci-guard.test.ts index d90fe5bbbe..7d554d033f 100644 --- a/scripts/selfhost/operator-ci-guard.test.ts +++ b/scripts/selfhost/operator-ci-guard.test.ts @@ -14,6 +14,7 @@ import { runRollback, } from './backup-lib'; import { restoreBackup } from './backup-restore'; +import { projectRestoreIdentity, restoredInstallationId } from './restore-identity'; import { assertRestoreSubset, restoreProgress } from './restore-progress'; const ROOT = resolve(import.meta.dirname, '../..'); @@ -48,6 +49,8 @@ describe('operator commands never read secret files in CI', () => { for (const invoke of [ () => loadBox(ABSENT), () => restoreBackup(context, ABSENT, ABSENT), + () => projectRestoreIdentity(context, ABSENT), + () => restoredInstallationId(context, ''), () => restoreProgress(context, ABSENT), () => assertRestoreSubset(ABSENT, ABSENT), () => readBackupKey(ABSENT), diff --git a/scripts/selfhost/restore-identity.ts b/scripts/selfhost/restore-identity.ts new file mode 100644 index 0000000000..d0ee92bafd --- /dev/null +++ b/scripts/selfhost/restore-identity.ts @@ -0,0 +1,68 @@ +/** A restored fleet gets its own ownership identity while retaining its data encryption keys. */ +import { createHash } from 'node:crypto'; +import { existsSync, readFileSync } from 'node:fs'; +import { join, resolve } from 'node:path'; + +import type { BoxContext } from './backup-lib'; +import { assertOperatorExecution } from './operator-only'; +import { readPrivateJson, readSecretsFile, writePrivateFile } from './secret-files'; + +/** Stable for a retry of this target; never adopts the source fleet's VM ownership labels. */ +export function restoredInstallationId(ctx: BoxContext, source: string): string { + assertOperatorExecution(); + if (!/^[a-f0-9]{32}$/.test(source)) throw new Error('Invalid backup installation identity'); + const identity = createHash('sha256') + .update( + JSON.stringify([ + 'sam-restored-installation/1', + source, + resolve(ctx.stateDir), + ctx.box.CELLD_BUCKET, + ]) + ) + .digest('hex') + .slice(0, 32); + if (identity === source) throw new Error('Restore installation identity collision'); + return identity; +} + +/** Mutates only private decrypted scratch. Target output remains journal-owned and retryable. */ +export function projectRestoreIdentity(ctx: BoxContext, state: string): string { + assertOperatorExecution(); + if (ctx.box.SAM_INSTALLATION_ID !== undefined || process.env.SAM_INSTALLATION_ID !== undefined) + throw new Error('Restore refuses an explicit installation identity override'); + let operatorSecrets: Record; + try { + operatorSecrets = readSecretsFile(join(state, 'secrets.env')); + } catch { + throw new Error('Invalid restored operator secrets'); + } + if (operatorSecrets.SAM_INSTALLATION_ID !== undefined) + throw new Error('Restore refuses an explicit installation identity override'); + const path = join(state, 'platform-keys.json'); + const keys = readPrivateJson(path); + const identity = restoredInstallationId(ctx, keys.SAM_INSTALLATION_ID ?? ''); + writePrivateFile(path, JSON.stringify({ ...keys, SAM_INSTALLATION_ID: identity })); + const configPath = join(state, 'project', 'wrangler.json'); + if (existsSync(configPath)) { + let config: { vars?: Record }; + try { + config = JSON.parse(readFileSync(configPath, 'utf8')); + } catch { + throw new Error('Invalid restored generated config'); + } + if ( + !config || + typeof config !== 'object' || + Array.isArray(config) || + (config.vars !== undefined && + (!config.vars || typeof config.vars !== 'object' || Array.isArray(config.vars))) + ) + throw new Error('Invalid restored generated config'); + if (config.vars && Object.hasOwn(config.vars, 'SAM_INSTALLATION_ID')) { + config.vars.SAM_INSTALLATION_ID = identity; + writePrivateFile(configPath, JSON.stringify(config)); + } + } + return identity; +} diff --git a/scripts/selfhost/teardown-box.ts b/scripts/selfhost/teardown-box.ts index e83d15e41b..e1036e59b6 100644 --- a/scripts/selfhost/teardown-box.ts +++ b/scripts/selfhost/teardown-box.ts @@ -6,8 +6,9 @@ import { existsSync, readdirSync, readFileSync, rmSync } from 'node:fs'; import { isAbsolute, join, resolve } from 'node:path'; -import type { CreatedResource } from '../../deploy/selfhost/created-resources.mjs'; +import { type CreatedResource, readRecord } from '../../deploy/selfhost/created-resources.mjs'; import { type BoxContext, composeArgs, MANIFEST_NAME, parseBucketUrl } from './backup-lib'; +import { assertBackupOwnership } from './backup-ownership'; import { composeProjectFor, expectedComposeProjectFor, usesBundledStore } from './install-record'; import { readComposeInventory, removeContainers, stopContainers } from './teardown-compose'; import { both, type Item, type Mode, STEPS } from './teardown-model'; @@ -205,18 +206,29 @@ function backupPaths(ctx: TeardownContext): Map rmSync(path, { recursive: true, force: true }), + run: () => { + const live = readRecord(ctx.recordFile).resources.find( + (r) => r.cloud === 'box' && r.kind === 'backup' && r.name === path + ); + if (!isBackupDir(path, ctx) || live?.attributes?.identity !== entry?.attributes?.identity) + throw new Error('Refused: backup ownership changed after inventory'); + assertBackupOwnership(path, live); + rmSync(path, { recursive: true, force: true }); + }, record: { cloud: 'box', kind: 'backup', name: path, createdBy: 'backup' }, }); } diff --git a/scripts/selfhost/teardown-retry.test.ts b/scripts/selfhost/teardown-retry.test.ts new file mode 100644 index 0000000000..05d4deaf8e --- /dev/null +++ b/scripts/selfhost/teardown-retry.test.ts @@ -0,0 +1,185 @@ +/** Real CLI retry after retaining keys, and exact encrypted-backup receipt deletion boundaries. */ +import { + chmodSync, + existsSync, + mkdirSync, + mkdtempSync, + readFileSync, + renameSync, + rmSync, + writeFileSync, +} from 'node:fs'; +import { join, resolve } from 'node:path'; + +import { afterEach, beforeEach, expect, it, vi } from 'vitest'; + +import { markRemoved, readRecord } from '../../deploy/selfhost/created-resources.mjs'; +import { encryptBackupTree } from './backup-encryption'; +import { CHILD_TEST_TIMEOUT_MS, runTsx } from './deploy-harness'; +import { recordBackup, recordInstall, recordPath } from './install-record'; +import { boxItems, type TeardownContext } from './teardown-box'; +import { execute } from './teardown-model'; + +vi.setConfig({ testTimeout: CHILD_TEST_TIMEOUT_MS }); +const DOMAIN = 'retry.example.com'; +const INSTALLATION = 'a'.repeat(32); +let root: string, state: string, envFile: string; +beforeEach(() => { + for (const name of Object.keys(process.env)) + if (name === 'CI' || name === 'GITHUB_ACTIONS' || name.startsWith('RUNNER_')) + vi.stubEnv(name, undefined); + mkdirSync(resolve('.tmp'), { recursive: true }); + root = mkdtempSync(resolve('.tmp/teardown-retry-')); + state = join(root, 'state'); + mkdirSync(state); + envFile = join(root, 'box.env'); + writeFileSync(envFile, `SAM_DOMAIN=${DOMAIN}\n`, { mode: 0o600 }); + writeFileSync( + join(state, 'platform-keys.json'), + JSON.stringify({ SAM_INSTALLATION_ID: INSTALLATION }), + { mode: 0o600 } + ); + recordInstall(state, envFile, { SAM_DOMAIN: DOMAIN }, INSTALLATION); +}); +afterEach(() => { + vi.unstubAllEnvs(); + rmSync(root, { recursive: true, force: true }); +}); + +it('retains active ownership with kept keys, then completes --destroy-key through the real CLI', async () => { + const bin = join(root, 'bin'); + mkdirSync(bin); + const docker = join(bin, 'docker'); + writeFileSync(docker, '#!/usr/bin/env node\nprocess.exit(0);\n'); + chmodSync(docker, 0o755); + const args = [ + '--box-env', + envFile, + '--state-dir', + state, + '--remove-everything', + '--confirm', + DOMAIN, + ]; + writeFileSync(join(state, 'payload'), 'owned payload'); + const first = await runTsx(resolve(import.meta.dirname, 'teardown.ts'), args, { + PATH: `${bin}:${process.env.PATH}`, + }); + expect(first.status, first.out).toBe(0); + expect(existsSync(envFile)).toBe(false); + expect(existsSync(join(state, 'platform-keys.json'))).toBe(true); + expect(existsSync(join(state, 'payload'))).toBe(false); + const ownership = readRecord(recordPath(state)).resources.filter((r) => + ['state-dir', 'installation'].includes(r.kind) + ); + expect(ownership).toHaveLength(2); + expect(ownership.every((r) => !r.removedAt)).toBe(true); + const second = await runTsx( + resolve(import.meta.dirname, 'teardown.ts'), + [...args, '--destroy-key'], + { PATH: `${bin}:${process.env.PATH}` } + ); + expect(second.status, second.out).toBe(0); + expect(existsSync(join(state, 'platform-keys.json'))).toBe(false); + expect( + readRecord(recordPath(state)) + .resources.filter((r) => ['state-dir', 'installation'].includes(r.kind)) + .every((r) => !!r.removedAt) + ).toBe(true); +}); + +function context(): TeardownContext { + return { + box: { SAM_DOMAIN: DOMAIN }, + envFile, + stateDir: state, + composeFiles: [], + now: Date.now, + log: () => undefined, + domain: DOMAIN, + installationId: INSTALLATION, + record: readRecord(recordPath(state)).resources, + recordFile: recordPath(state), + selfhostDir: join(root, 'checkout/deploy/selfhost'), + options: { deleteBackups: true, destroyKey: false, adoptDiscovered: false, gcpProjects: [] }, + run: () => ({ status: 0, stdout: '', stderr: '' }), + }; +} +function backup(): string { + const source = join(root, 'source'); + mkdirSync(source); + writeFileSync(join(source, 'fixture'), 'private fixture', { mode: 0o600 }); + const key = join(root, 'backup.key'); + writeFileSync(key, Buffer.alloc(32, 17), { mode: 0o600 }); + const destination = join(root, 'backup'); + encryptBackupTree(source, destination, key); + recordBackup(state, destination); + return destination; +} +function backupItem() { + return boxItems(context()).filter((item) => item.id.startsWith('box:backup:')); +} + +it('removes an active exact recorded backup and tombstones its receipt', () => { + const path = backup(); + expect(execute(backupItem(), 'remove-everything', recordPath(state))[0]?.status).toBe('removed'); + expect(existsSync(path)).toBe(false); + expect( + readRecord(recordPath(state)).resources.find((r) => r.kind === 'backup')?.removedAt + ).toBeDefined(); +}); +it.each(['removed-receipt', 'replaced-directory', 'changed-inventory', 'legacy-receipt'])( + 'preserves %s backup paths before deletion', + (defect) => { + const path = backup(); + if (defect === 'removed-receipt') markRemoved(recordPath(state), 'box', 'backup', path); + if (defect === 'replaced-directory' || defect === 'removed-receipt') { + renameSync(path, join(root, 'original-backup')); + encryptBackupTree(join(root, 'source'), path, join(root, 'backup.key')); + } + if (defect === 'changed-inventory') + writeFileSync( + join(path, '.sam-backup-manifest'), + Buffer.concat([Buffer.from('SAMBAK01'), Buffer.alloc(64)]) + ); + if (defect === 'legacy-receipt') { + const record = JSON.parse(readFileSync(recordPath(state), 'utf8')); + record.resources.find((r: { kind: string }) => r.kind === 'backup').attributes = {}; + writeFileSync(recordPath(state), JSON.stringify(record)); + } + expect(execute(backupItem(), 'remove-everything', recordPath(state))[0]?.status).toBe( + 'refused' + ); + expect(existsSync(path)).toBe(true); + } +); +it.each(['removed-receipt', 'replaced-directory', 'changed-inventory'])( + 'revalidates %s immediately before deleting an already-inventoried backup', + (defect) => { + const path = backup(); + const items = backupItem(); + if (defect === 'removed-receipt') markRemoved(recordPath(state), 'box', 'backup', path); + if (defect === 'replaced-directory' || defect === 'removed-receipt') { + renameSync(path, join(root, 'original-backup')); + encryptBackupTree(join(root, 'source'), path, join(root, 'backup.key')); + } + if (defect === 'changed-inventory') + writeFileSync( + join(path, '.sam-backup-manifest'), + Buffer.concat([Buffer.from('SAMBAK01'), Buffer.alloc(64)]) + ); + expect(execute(items, 'remove-everything', recordPath(state))[0]?.status).toBe('failed'); + expect(existsSync(path)).toBe(true); + } +); + +it('keeps unproved backups when deletion was not requested', () => { + const path = backup(); + markRemoved(recordPath(state), 'box', 'backup', path); + expect(execute(backupItem(), 'keep-data', recordPath(state))[0]?.status).toBe('kept'); + const ctx = context(); + ctx.options.deleteBackups = false; + const items = boxItems(ctx).filter((item) => item.id.startsWith('box:backup:')); + expect(execute(items, 'remove-everything', recordPath(state))[0]?.status).toBe('kept'); + expect(existsSync(path)).toBe(true); +}); diff --git a/scripts/selfhost/teardown-state-dir.ts b/scripts/selfhost/teardown-state-dir.ts index 436a0cb9b9..77fd000201 100644 --- a/scripts/selfhost/teardown-state-dir.ts +++ b/scripts/selfhost/teardown-state-dir.ts @@ -90,13 +90,17 @@ export function stateItems(ctx: TeardownContext): Item[] { removedAt: state?.removedAt, runKey: 'state', run: () => clearState(ctx, keepKey), - record: [ - { cloud: 'box', kind: 'state-dir', name: ctx.stateDir, createdBy: 'deploy' }, - // The install itself is gone with its state; the id stays readable for a resumed run. - ...ctx.record - .filter((r) => r.cloud === 'box' && r.kind === 'installation') - .map((r) => ({ cloud: 'box', kind: 'installation', name: r.name })), - ], + // Retained keys still need the active state/installation proof for a later --destroy-key. + record: + keepKey && (existsSync(keyFile) || existsSync(legacyKeys)) + ? [] + : [ + { cloud: 'box', kind: 'state-dir', name: ctx.stateDir, createdBy: 'deploy' }, + // The install itself is gone with its state; the id stays readable for a resumed run. + ...ctx.record + .filter((r) => r.cloud === 'box' && r.kind === 'installation') + .map((r) => ({ cloud: 'box', kind: 'installation', name: r.name })), + ], }, { id: 'box:record', diff --git a/scripts/selfhost/teardown.ts b/scripts/selfhost/teardown.ts index 87a10f3513..a5ea814f70 100644 --- a/scripts/selfhost/teardown.ts +++ b/scripts/selfhost/teardown.ts @@ -182,6 +182,8 @@ async function main(): Promise { const recordedId = resolved.recordedId; const installationId = resolved.id; const domain = box.SAM_DOMAIN ?? install?.attributes?.domain ?? ''; + // A first teardown may remove .env while deliberately keeping keys and their active proof. + if (!existsSync(envFile) && domain) box.SAM_DOMAIN = domain; if (resolved.problem) log(`node VMs will not be touched: ${resolved.problem}`); const gcpProjects = resolveGcpProjects(values['gcp-project'], box.GCP_PROJECT, envFile); if (gcpProjects.projects.length > 0) { diff --git a/scripts/selfhost/upgrade-lib.ts b/scripts/selfhost/upgrade-lib.ts index 2cb690971d..221487128b 100644 --- a/scripts/selfhost/upgrade-lib.ts +++ b/scripts/selfhost/upgrade-lib.ts @@ -34,10 +34,15 @@ import { } from './upgrade-migrations.js'; export { composeInputsChanged, composeOverlays } from './upgrade-compose.js'; -import { assertRollbackReady, pendingBackupDirectory } from './upgrade-preflight.js'; +import { + assertPendingUpgradeTarget, + assertRollbackReady, + pendingBackupDirectory, + pendingUpgradeTarget, +} from './upgrade-preflight.js'; const MIGRATIONS_DIR = 'apps/api/src/db/migrations/'; -/** In the state dir while an upgrade has not finished: `{ "from": "" }`. */ +/** Pending original source/target SHAs and encrypted snapshot path, retained through recovery. */ export const UPGRADE_PENDING_FILE = 'upgrade-pending.json'; export interface RunResult { @@ -169,10 +174,14 @@ export async function recoverUpgrade( opts: UpgradeOptions ): Promise { assertOperatorExecution(); + const pendingPath = join(ctx.stateDir, UPGRADE_PENDING_FILE); + const to = existsSync(pendingPath) + ? pendingUpgradeTarget(JSON.parse(readFileSync(pendingPath, 'utf8'))) + : null; runRollback(backupContext(ctx), backupDir, from); replacePrivateFile( join(ctx.stateDir, UPGRADE_PENDING_FILE), - `${JSON.stringify({ from, backupDir })}\n` + `${JSON.stringify({ from, backupDir, ...(to ? { to } : {}) })}\n` ); check(ctx.run('git', ['checkout', '--detach', from]), 'restore previous checkout'); check(ctx.run('pnpm', ['install', '--frozen-lockfile']), 'restore previous dependencies'); @@ -392,6 +401,11 @@ export async function runUpgrade(ctx: BoxContext, opts: UpgradeOptions): Promise // A pending record means the checkout may be ahead of what is deployed: start from the record. const from = pendingFrom ?? head; const to = resolveUpgradeTarget(git, opts.to); + if (pendingFrom !== null) + assertPendingUpgradeTarget( + JSON.parse(readFileSync(join(ctx.stateDir, UPGRADE_PENDING_FILE), 'utf8')), + to + ); if (pendingFrom === null && head === to) { ctx.log('already at that ref; nothing to do'); return { @@ -454,7 +468,7 @@ export async function runUpgrade(ctx: BoxContext, opts: UpgradeOptions): Promise const pendingPath = join(ctx.stateDir, UPGRADE_PENDING_FILE); if (pendingFrom === null) { mkdirSync(ctx.stateDir, { recursive: true, mode: 0o700 }); - replacePrivateFile(pendingPath, `${JSON.stringify({ from, backupDir })}\n`); + replacePrivateFile(pendingPath, `${JSON.stringify({ from, backupDir, to })}\n`); } const progress: UpgradeProgress = { deploymentStarted: false, diff --git a/scripts/selfhost/upgrade-preflight.ts b/scripts/selfhost/upgrade-preflight.ts index 178dd5e5fd..085177a392 100644 --- a/scripts/selfhost/upgrade-preflight.ts +++ b/scripts/selfhost/upgrade-preflight.ts @@ -51,3 +51,16 @@ export function pendingBackupDirectory(pending: unknown): string { } return pending.backupDir; } + +/** Legacy records cannot prove which image changes an interrupted deployment applied. */ +export function pendingUpgradeTarget(pending: unknown): string | null { + if (typeof pending !== 'object' || pending === null || !('to' in pending)) return null; + return typeof pending.to === 'string' && /^[a-f0-9]{40}$/.test(pending.to) ? pending.to : null; +} + +export function assertPendingUpgradeTarget(pending: unknown, to: string): void { + if (pendingUpgradeTarget(pending) !== to) + throw new Error( + 'Unfinished upgrade target differs or is unrecorded; recover with the explicit rollback command before choosing another target' + ); +} diff --git a/scripts/selfhost/upgrade.test.ts b/scripts/selfhost/upgrade.test.ts index 7d5067a671..913255a4b3 100644 --- a/scripts/selfhost/upgrade.test.ts +++ b/scripts/selfhost/upgrade.test.ts @@ -6,7 +6,7 @@ * whose build inputs changed (never `up --build`), that interrupted recovery retains its original snapshot for retry, and that * the printed rollback selects the same box and matches whether the upgrade carried a D1 migration. */ -import { existsSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'; +import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'; import { join, resolve } from 'node:path'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; @@ -281,6 +281,52 @@ describe('runUpgrade', () => { expect(steps).toEqual(['git fetch --tags origin']); }); + it('refuses A-to-C retry after an interrupted A-to-B image rebuild before starting A with B images', async () => { + diff = ['deploy/selfhost/caddy/Dockerfile']; + failDeploy = true; + vi.mocked(runRollback).mockImplementationOnce(() => { + throw new Error('interrupted'); + }); + await expect(upgrade()).rejects.toThrow(/automatic rollback did not complete/); + expect(steps.some((step) => step.includes('build caddy'))).toBe(true); + const pending = JSON.parse(readFileSync(join(root, 'state', UPGRADE_PENDING_FILE), 'utf8')); + expect(pending.to).toBe(TO); + const priorRestores = vi.mocked(runRollback).mock.calls.length; + steps = []; + const next = ctx(); + next.run = (command, args, env) => + command === 'git' && args[0] === 'rev-parse' && args[1] !== 'HEAD' + ? { status: 0, stdout: 'c'.repeat(40), stderr: '' } + : run(command, args, env); + await expect( + runUpgrade(next, { to: 'release-c', checkHealth: async () => true }) + ).rejects.toThrow(/target differs/); + expect(vi.mocked(runRollback).mock.calls.length).toBe(priorRestores); + expect(steps).toEqual(['git fetch --tags origin']); + expect(head).toBe(TO); + }); + + it('retains the original target if snapshot recovery succeeds but old health fails', async () => { + failDeploy = true; + await expect(upgrade(false)).rejects.toThrow(/automatic rollback did not complete/); + const pending = JSON.parse(readFileSync(join(root, 'state', UPGRADE_PENDING_FILE), 'utf8')); + expect(pending.to).toBe(TO); + }); + + it.each([undefined, 'main', 'unknown'])( + 'refuses legacy or malformed pending target %s before any recovery or checkout', + async (to) => { + writeFileSync( + join(root, 'state', UPGRADE_PENDING_FILE), + JSON.stringify({ from: FROM, backupDir: join(root, 'snapshot'), to }) + ); + await expect(upgrade()).rejects.toThrow(/target differs or is unrecorded/); + expect(runRollback).not.toHaveBeenCalled(); + expect(steps).toEqual(['git fetch --tags origin']); + expect(head).toBe(FROM); + } + ); + it('refuses a pending record it did not write before touching the checkout', async () => { writeFileSync(join(root, 'state', UPGRADE_PENDING_FILE), '{"from":"HEAD~1"}\n'); await expect(upgrade()).rejects.toThrow(/not a record this upgrade wrote/); diff --git a/scripts/selfhost/vitest.config.ts b/scripts/selfhost/vitest.config.ts index bd142ba7c6..e74426edb5 100644 --- a/scripts/selfhost/vitest.config.ts +++ b/scripts/selfhost/vitest.config.ts @@ -1,6 +1,16 @@ import { defineConfig } from 'vitest/config'; export default defineConfig({ + resolve: { + alias: { + '@simple-agent-manager/providers': new URL( + '../../packages/providers/src/index.ts', + import.meta.url + ).pathname, + '@simple-agent-manager/shared': new URL('../../packages/shared/src/index.ts', import.meta.url) + .pathname, + }, + }, test: { root: import.meta.dirname, include: ['**/*.test.ts'], diff --git a/tasks/active/2026-11-19-l24-selfhost-operations.md b/tasks/active/2026-11-19-l24-selfhost-operations.md index ca316b8d22..26adda7a1e 100644 --- a/tasks/active/2026-11-19-l24-selfhost-operations.md +++ b/tasks/active/2026-11-19-l24-selfhost-operations.md @@ -79,3 +79,11 @@ Full current review suite602tests/32filesPASS; latest manual command tests add r Live deliberate failure at761662d84 did not complete automatic recovery; direct authenticated runRollback retry restored the disposable data. Initial failing boundary was not captured, so do not label it a confirmed bucket cause. Review of retry sequence found journal was removed before old dependency install/start; fixed to retain exact proof through restored checkout, dependency installation, partial Compose start, replacement cache proof and final health. Four restart/health retry controls plus completed-data/no-cache retry regression pass. Full608tests/33files,111upgrade tests,54backup tests, tsc/eslint and independent security delta PASS. Disposable manually restarted after diagnostic retry, shared install unchanged. Full automatic proof rerun required on next head. Confirmed live rollback cleanup root cause: after restoring state, private old-state staging cleanup encountered Go module cache directories with mode0555. Two real leftover stages each contain688directories/642read-only and go-cache. Direct retry succeeds because the already-restored state excludes rebuildable go-cache. Added private-stage-only lstat/no-symlink traversal and uid check, adding owner permissions only before cleanup. Real0555directory/0444file regression passes; removing chmod produces EACCES/RED. Full609tests33files/55backup/111upgrade, tsc/eslint pass; independent security delta PASS. Target deployment's separate exit1 before health remains under safe diagnostic investigation; no claim automatic rollback gate passed yet. + +## Final ownership and retry review + +On8f7882d, all requested live backup/restore/upgrade/refusal and automatic rollback gates passed:4477objects and476statefiles byteverified, executablebitpreserved,10,338ms backup downtime; deliberate failedhealth modified ownedmarker then automatically restored originaldata+f546code+health; subsequent actualupgrade8f healthy/dataretained. SharedoriginalH2checkout/containerIDs/receiptbytes+mode preserved andAPI200. Disposable teardown and cleanup remain owed. + +Four additional review findings fixed before release: freshrestore projects a distinct retry-stable installation ID while retaining all encryption/signing keys, removes copied active deploy/current.json until freshdeploy, refuses identity overrides; two-step remove-everything then destroy-key retains activeownership receipts and reconstructs only publicdomain after envremoval; backup deletion requires active exactdirectory+encryptedmanifest inode/hash receipts checked again atdeleteboundary; interruptedupgrades persist originalresolvedtarget and refuse changed/moved/unrecordedtargets before recovery mutation. Realrestore→init→teardown refuses sourceVM; realCLI retainedkeyretry and replacement/tombstone controls pass. Surgical projection deletion control RED then restoredGREEN. Independentsecurity reviews PASS. + +Clean-checkout regression: CI had failed because teardown's canonical API label helper imports unbuilt providers. Self-host Vitest aliases use source and realCLI harness/teardown command select selfhosttsconfig paths. With actual packages/providers/dist moved away for the whole suite (restored afterward),648testsPASS/1conditionalskip across36files; tsc/eslint/format/scanner0findings PASS. Currenthead live rerun and final release evidence pending. From a29aadf84aa109e86c59f5a074f834b3d005ddee Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rapha=C3=ABl=20Titsworth-Morin?= Date: Fri, 20 Nov 2026 00:31:17 +0000 Subject: [PATCH 10/17] docs(selfhost): archive verified L24 operations evidence --- .../2026-11-19-l24-selfhost-operations.md | 89 ------------------- .../2026-11-19-l24-selfhost-operations.md | 64 +++++++++++++ 2 files changed, 64 insertions(+), 89 deletions(-) delete mode 100644 tasks/active/2026-11-19-l24-selfhost-operations.md create mode 100644 tasks/archive/2026-11-19-l24-selfhost-operations.md diff --git a/tasks/active/2026-11-19-l24-selfhost-operations.md b/tasks/active/2026-11-19-l24-selfhost-operations.md deleted file mode 100644 index 26adda7a1e..0000000000 --- a/tasks/active/2026-11-19-l24-selfhost-operations.md +++ /dev/null @@ -1,89 +0,0 @@ -# L24 self-host operations - -## Problem - -Land backup, restore, upgrade checks and teardown from `sam/selfhost-pass-2` onto fresh main without importing unrelated self-host features. Fix F22/F23/F24 and include #2703 teardown error handling. - -## Research and preflight - -- Classes: security-sensitive, infrastructure, cross-component, business logic, documentation. -- Main base `917077fef` includes L22 deploy/upgrade harness; operations are otherwise only on integration. Paths imported with `git checkout origin/sam/selfhost-pass-2 -- `, never cherry-picked. -- Backup directory contains Worker secrets in bucket manifests, platform keys, environment and state. Encrypt complete backup tree with separate operator key, reject CI use, sanitize failures. Policy 795e72a6 applies. -- Historical backup live-copy races and gcloud tracker failures are hypotheses until reproduced on BOX (#2675/#2677). -- celld native manifests flatten DO migrations; compare deployed classes and canonical generated migration history before deployment. Include H2 `selfhost-hosted-git-v1`. -- Shared unowned firewalls cannot be deleted safely; new self-host creation receipts must prove immutable resource identity and installation/environment scope before delete. No name adoption. -- `--keep-data` must retain WIF identities, data and key access. Compose identity must be unique per install. -- s3 operator signing region is already validated by main box-settings.ts; retain regression coverage/docs. - -## Implementation checklist - -- [x] Port and trim operations paths only; keep all self-host code under deploy/selfhost or scripts/selfhost. -- [x] Encrypt all persisted backup payloads; external key, authentication, failure cleanup and secret-free diagnostics. -- [ ] Restore only into empty target, validate all encrypted payloads before mutation; verify actual data round trip. -- [ ] Reproduce backup failure on BOX, fix evidence-based cause and add regression. -- [ ] Upgrade preflight rejects unknown/reordered DO tags, including H2; valid check passes. -- [ ] Automatic upgrade rollback restores previous consistent state and reports rollback failure clearly. -- [x] Unique compose projects, exact ownership proof for destructive operations; no legacy adoption. -- [x] Keep-data retains data plus needed identity; permission errors remain visible, never treated as absence. -- [x] Documentation and CLI command wiring updated, including S3 region. -- [ ] Relevant automated checks; independent security and task-completion reviews on current head. -- [ ] BOX claimed after FREE; real backup, disposable restore with data verified, passing/refused upgrades. -- [ ] Disposable owned teardown proven; all resources cleaned, BOX healthy, BOX FREE posted. -- [ ] Merge latest main, current-head CI/CodeRabbit/reviews, announce merge, merge, real production deploy success, SHIPPED idea note. - -## Acceptance criteria - -Each checklist item is required. BOX evidence must come from real operations and disposable owned resources; never teardown shared box data. No secret values in output, PR, Actions or scratch logs. Stop for any missing secret/permission. Local scratch only `.tmp/`; no sudo/apt. - -## References - -Idea 01M72M9AEB933ZY8269D376DKC LANDING PLAN part 6; policy 795e72a6; rule 56 destructive ownership; /do; task 01M7TTKAS78AMJ3853S5N4BYAK; channel feature.selfhost-landing. - -## BOX reproduction 1 (2026-11-19 21:44–21:47 UTC) - -- Claimed before access: channel sequence412/event8ef78fe4. Original BOX checkout e7ac643b, four legacy sam-selfhost containers. -- Current BOX has no backup CLI/package script after L22 trimming: first invocation exits254 (command missing), no data operation. Used historical f09a294ae backup algorithm copied to private `.tmp/l24` and actual gcloud/docker against original store. -- Historical backup failed: live pre-copy incomplete; stopped delta `gcloud storage rsync` failed; structured safe result `{ok:false, reasonClass:rsync, liveIncomplete:true}`. Wrapper captured neither exact gcloud exit code nor full stderr before yielding, so underlying F23 cause remains UNCONFIRMED. Do not infer the old tracker hypothesis is proved. -- finally restarted celld; verified all four original containers running, API health200, checkout unchanged. No config/bucket writes or candidate deploy. -- Coordinator mistakenly gave L23 overlapping claim413 from frozen history; acknowledged L24 claim412 was first. L24 yielded, BOX FREE414. L24 explicitly next after L23 releases. -- Own partial backup/code/log removed, metadata SSH key absence and own firewall404 verified, local token/private key removed. Existing saml24 OS account has no key. - -## Local validation and review update - -Root lint (23 packages), typecheck (38), build (19) pass. Root tests remain in flight. Encryption/operator focused68, scanner187 and realDocker2 pass (synthetic test data, disposable volumes cleaned). Final full self-host run:541pass/17fail, all upgrade-preflight setup affected by stricter CI guard; fixture repair under review. Security reviewer caught real stopped-container selection bug and service-reselection deletion; fixed with Compose --all/full IDs and exact container deletion, real stopped-container/overlay controls pass. Final candidate review and BOX gates still pending. - -Final local suite after upgrade preflight wiring/fixture repairs:560tests/30filesPASS, upgrade96PASS, tsc/eslintPASS. One remaining final review volume-label control being added; live criteria still unfulfilled. Root timeout retry12/12PASS; scanner0findings, type-boundary0blocking. - -## Sonar followup - -Quick CI at4c41531c4 passed lint, build/typecheck, code quality, secret scan and smoke. Sonar raised45 issues (mostly function complexity/style, plus an alphabetical sort comparator bug). Refactored operations into private helpers without changing ownership/failure ordering; replaced ambiguous regex/string conversions and added parser regressions. Also fixed failure-stop customstate environment propagation with a runner-boundary assertion. Final selfhost573tests/31filesPASS, scanner187PASS/0findings, focusedWIF/teardown101PASS, upgrade96PASS, tsc/eslint/typeboundaryPASS. Independent teardown/WIF refactor reviewPASS; final security delta review running. BOX still L23; H2 newly queued afterL24 (event0c37c5db). - -## BOX slot418 evidence (in progress) - -Claim987d8996 after L23FREE2a876ebc. Original shared checkoute7ac643b/fourcontainers/API200. Own SSH firewall sam-l24-ssh-slot418 immutableid7663373354569745545 +metadata key, cleanup owed. Store root uniquely owned gs://sam-selfhost-vmtest-fleet/l24-01m7ttkas78amj3853s5n4byak-slot418 has random ownership marker and was proven empty before creation; never shared/celld. - -F23: retrieved the original failed stopped-copy gcloud log2026.11.19/21.46.12.578974.log read-only. Trace reaches SDK523 file_download_task.execute -> posix_util.run_if_setting_posix -> set_posix_attributes_on_file_if_valid -> get_posix_attributes_from_file/os.stat, then ENOENT for local nodes/node_*.json. Log has9HTTP404 occurrences, atime/mtime POSIX metadata, no hash mismatch. SDK source proves finalize_download returnsFalse when temporary download missing, but caller ignores return and applies POSIX metadata/stat. Root failure mechanism is missing download followed by POSIX stat; tracker reuse alone remains unproved. Historical fresh retry succeeded4251objects, confirming intermittent behavior. Old plaintext diagnostic tree removed. New isolated live paths/temp cleanup/fresh full-copy fallback avoid partial-download reuse; targeted GCS POSIX ENOENT regression verifies complete final data/no partial node artifact and restarted writer. - -Live found adjacent writer-selection bug: shell COMPOSE_PROJECT_NAME ignored with a legacy YAML whose name was static. Compose stop on nonexistent derived project returns0, so no writer had stopped. Fixed always-control precedence and fail-before-copy singleton running-writer observation;114 focused and full578tests, realDocker2, scanner187,tsc/eslint pass. Finalcommit/retest pending. Explicit private target env instead of shared edit yielded real encrypted backup4270objects, down4919ms, authentication success, original API200. Restore to fresh owned /restore prefix complete;4270objects including3701LTX +476statefiles SHA256 compared exactly, source receipts stripped. Restore app not started (avoid shared background alarms). Init/disposableupgrade/teardown/refusal still owed. - -## BOX final backup/restore and valid upgrade - -Final f546 backup:4,324objects,5,824ms downtime, authenticated encrypted tree. Fresh /restore-final prefix and fresh state:4,324objects/3,756LTX/476statefiles exactly match SHA256 inventories. No restored shared alarms started. Actual shared H2 live deployment manifest and source tags reject main's unknown/removed selfhost-hosted-git-v1 before mutation. Separate fresh main worktree/state/env/project sam-selfhost-062a6279cc37 deployed4c415, then actual upgrade to f546 passed encrypted806object snapshot, installed-vs-live-vs-target DO check and API health. Shared checkout e7ac and four original services remain unchanged/healthy. - -## Ready review followup - -CodeRabbit requested23:03UTC via trusted label workflow, returned review limit/rate-limit; wait ended, no findings from it. Codex review found3 issues, fixed before final candidate: retry cache deletion after transient restoration failure; executable populated-install manual rollback bound to authenticated snapshot source SHA; exact created/reused workloadIdentityUser service-account grant receipts and cleanup. Recovery now stages state before swap, retains upgrade recovery pointer, writes private exact cache-deletion progress so partial deletion can retry, refuses replacement cache identities. 53backup tests pass; deleting pending-cache consumption makes the transient-volume retry control fail (RED), source restored. Independent recovery security review PASS. Teardown diagnostic stderr/JSON never surfaces raw cloud content;3actualCLI sentinel controls pass. Clean CI deploy validation exposed unbuilt providers dependency from existing node-provider-labels import; selfhost-only tsconfig resolves provider/shared sources directly, no runtime/Worker change. - -Full current review suite602tests/32filesPASS; latest manual command tests add real emitted CLI entrypoint and operator-checkout recovery on failed rollback. Disposable final rollback/teardown/cleanup and exact-head release gates pending. - -Live deliberate failure at761662d84 did not complete automatic recovery; direct authenticated runRollback retry restored the disposable data. Initial failing boundary was not captured, so do not label it a confirmed bucket cause. Review of retry sequence found journal was removed before old dependency install/start; fixed to retain exact proof through restored checkout, dependency installation, partial Compose start, replacement cache proof and final health. Four restart/health retry controls plus completed-data/no-cache retry regression pass. Full608tests/33files,111upgrade tests,54backup tests, tsc/eslint and independent security delta PASS. Disposable manually restarted after diagnostic retry, shared install unchanged. Full automatic proof rerun required on next head. - -Confirmed live rollback cleanup root cause: after restoring state, private old-state staging cleanup encountered Go module cache directories with mode0555. Two real leftover stages each contain688directories/642read-only and go-cache. Direct retry succeeds because the already-restored state excludes rebuildable go-cache. Added private-stage-only lstat/no-symlink traversal and uid check, adding owner permissions only before cleanup. Real0555directory/0444file regression passes; removing chmod produces EACCES/RED. Full609tests33files/55backup/111upgrade, tsc/eslint pass; independent security delta PASS. Target deployment's separate exit1 before health remains under safe diagnostic investigation; no claim automatic rollback gate passed yet. - -## Final ownership and retry review - -On8f7882d, all requested live backup/restore/upgrade/refusal and automatic rollback gates passed:4477objects and476statefiles byteverified, executablebitpreserved,10,338ms backup downtime; deliberate failedhealth modified ownedmarker then automatically restored originaldata+f546code+health; subsequent actualupgrade8f healthy/dataretained. SharedoriginalH2checkout/containerIDs/receiptbytes+mode preserved andAPI200. Disposable teardown and cleanup remain owed. - -Four additional review findings fixed before release: freshrestore projects a distinct retry-stable installation ID while retaining all encryption/signing keys, removes copied active deploy/current.json until freshdeploy, refuses identity overrides; two-step remove-everything then destroy-key retains activeownership receipts and reconstructs only publicdomain after envremoval; backup deletion requires active exactdirectory+encryptedmanifest inode/hash receipts checked again atdeleteboundary; interruptedupgrades persist originalresolvedtarget and refuse changed/moved/unrecordedtargets before recovery mutation. Realrestore→init→teardown refuses sourceVM; realCLI retainedkeyretry and replacement/tombstone controls pass. Surgical projection deletion control RED then restoredGREEN. Independentsecurity reviews PASS. - -Clean-checkout regression: CI had failed because teardown's canonical API label helper imports unbuilt providers. Self-host Vitest aliases use source and realCLI harness/teardown command select selfhosttsconfig paths. With actual packages/providers/dist moved away for the whole suite (restored afterward),648testsPASS/1conditionalskip across36files; tsc/eslint/format/scanner0findings PASS. Currenthead live rerun and final release evidence pending. diff --git a/tasks/archive/2026-11-19-l24-selfhost-operations.md b/tasks/archive/2026-11-19-l24-selfhost-operations.md new file mode 100644 index 0000000000..74b85d92c4 --- /dev/null +++ b/tasks/archive/2026-11-19-l24-selfhost-operations.md @@ -0,0 +1,64 @@ +# L24 self-host operations + +## Outcome and scope + +Land backup, restore, upgrade checks and teardown from `sam/selfhost-pass-2`, fixing F22/F23/F24 and #2703. Fresh main base917077fef contained L22. Imported selected paths with `git checkout origin/sam/selfhost-pass-2 -- `, trimmed them, and never cherry-picked. Runtime code remains under `scripts/selfhost/` and `deploy/selfhost/`; no Worker-loaded code, bindings or migrations change. + +Implementation and live verification are complete. Release administration (current-head CI, merge, production deployment and SHIPPED note) remains tracked in `.do-state.md` and PR2918 until complete. + +## Research and findings + +Security-sensitive infrastructure and cross-component change. Policy795e72a6 forbids secret readback/decryption in CI and secret-bearing output. Rule56 requires exact installation/environment and immutable resource ownership before destruction. Main's S3 region validation is preserved and documented: `s3://` operator stores require `R2_S3_REGION`. + +The historical backup failed on the actual BOX during a stopped gcloud copy. Retained SDK523 evidence traces `file_download_task.execute` through POSIX metadata application to ENOENT for a vanished local node JSON destination. `finalize_download` can return false when its temporary download vanished, but the caller still stats the destination. Running-writer404s and incomplete copies are real; tracker reuse alone remains unproved. A fresh historical retry succeeded4251objects, confirming intermittency. The fix uses isolated live-copy paths, removes temporary download artifacts, and falls back to a fresh full copy with the writer stopped. Helper and actual CLI regressions exercise the exact POSIX ENOENT shape and data completeness; surgical fault controls go red. + +## Implementation checklist + +- [x] Port only the operations paths and command wiring from integration. +- [x] Encrypt all persisted backup payloads and authenticated inventory with a separate operator key; preserve owner-execute permissions, private payload modes and existing parent ownership/modes. +- [x] Refuse CI before secret reads, sanitize command failures and authenticate the entire backup before target mutation. +- [x] Restore into a fresh target; durable identity-bound progress allows only exact authenticated partial retries and refuses foreign ownership, hard links, symlinks and changed data. +- [x] Give restored targets a distinct, retry-stable installation identity while preserving cryptographic keys; project generated config and omit the active deployment pointer until fresh deploy. Source ownership receipts are stripped. +- [x] Pre-upgrade check refuses unknown/out-of-order DO tags, including H2 `selfhost-hosted-git-v1`; compare installed history, live manifest and target source. +- [x] Automatic rollback restores snapshot data/cache, code/dependencies and health. Preserve current creation/removal receipts and durable recovery proof through successful health. Handle read-only Go cache staging safely. +- [x] Persist the interrupted upgrade's resolved target; refuse changed, moved or unrecorded targets before recovery. Provide an executable authenticated populated-install manual rollback command. +- [x] Use unique Compose projects and exact live container/volume/provider identity checks; never adopt legacy names. +- [x] Keep-data retains storage, keys and WIF/service-account access; same-step failure blocks new destructive actions immediately. +- [x] Retained keys keep active ownership receipts for a later env-absent destroy-key retry. Backup deletion requires active exact directory/inventory inode/hash proof, rechecked at deletion. +- [x] Documentation matches actual key separation, restore identity, retry, migration, rollback and teardown behavior. +- [x] Independent security, documentation and implementation-completion review passed on tested source39f3fa951c104e410d1feb43123c8166580da727. +- [x] Required real BOX backup, fresh restore/data verification, valid/refused upgrade and automatic rollback passed. +- [x] Disposable keep-data/restart and two-step full teardown passed; all created resources cleaned; shared BOX healthy and BOX FREE posted. + +## Automated validation + +Full self-host suite648PASS/1conditional skip across36files. The root-only foreign-owner setup skips for an unprivileged runner; the actual foreign-owned `/tmp` preservation control passes. The entire suite also passed with `packages/providers/dist` physically absent, proving clean-checkout CLI/Vitest resolution through the explicit self-host source configuration. Typecheck, focused lint, formatting and diff checks pass. Secret scanner reports zero findings;187 scanner/exception controls passed. Real MinIO backup/restore and injected partial upload/resume tests passed and cleaned their resources. Projection, guard removal, cache retry and read-only cleanup fault controls fail when their respective protections are removed. + +Repository lint23packages, typecheck38packages and build19packages passed. Root tests40/41tasks passed, with API17902passed and one timeout in an unchanged test; that entire file passed12/12 on retry. Type-boundary ratchet has zero blocking findings. Current-head CI is tracked separately before merge. + +All11 Codex findings were fixed with focused regressions and replies; their threads were resolved. CodeRabbit was requested through the trusted label workflow at ready23:03UTC Nov19 and returned a review-limit/rate-limit response; the wait ended on that response, with no CodeRabbit finding or waiver. + +## BOX evidence and cleanup + +Claim slot418/event987d8996 only after L23 FREE417. Shared BOX is `app.vmtest.sam2.party`, GCP sam-box immutableid6620627785558986265. The coordinator explicitly required retaining original H2 checkoute7ac643b18f4ca864e403d33f7fbcf7a1a5e8fe8 because main lacks its migration tag. No shared teardown, rebuild, downgrade or app-data change occurred. + +Final tested operations source39f3fa951c104e410d1feb43123c8166580da727: + +- Real authenticated encrypted backup4521objects; writer downtime5423ms. +- Fresh disposable restore4520objects and474unchanged state files matched exact SHA256 inventories, including3951LTX files and immutable deployment objects. Separately verified new distinct/stable ID, unchanged cryptographic keys, generated-config ID projection, omitted active `deploy/current.json`, stripped source receipts and preserved executable modes. Restored shared alarms were never started. +- Actual shared H2 manifest/history refused target main's unknown/removed `selfhost-hosted-git-v1` before mutation. +- Actual disposable8f7882d→39f3fa951 upgrade passed migration preflight, encrypted snapshot and API health with data retained. +- Deliberate failed health check modified an owned GCS marker; automatic rollback restored old8f code, original marker data and health. Two health checks reached the real recovery path. +- Disposable project `sam-selfhost-062a6279cc37`: keep-data removed only own containers, retained exact volumes/state/keys/store; restart passed health/data and exact volume identity. Full removal without destroy-key retained key and active receipts; a later env-absent destroy-key invocation removed key/state payload successfully. Foreign containers and shared images stayed intact. + +All18547 objects under the uniquely owned task prefix were deleted with generation conditions; existing shared bucket and `/celld` data were preserved. Removed the owned worktree, scratch tree, decrypted plaintext, backups, key,14 uploaded files, exact metadata SSH key and immutable-id-verified SSH firewall. Verified metadata-key absence and firewall404, then deleted local token/private key. Final shared checkout and four original services were unchanged, APIHTTP200. BOX FREE sequence422/eventef041954-cde5-4ebb-951f-4bbd9d95adeb; coordinator and next H2 task notified. + +Latest main20675016f (Claude action dependency bump only) was merged before release. Self-host source after synchronization is byte-identical to the tested39f source; final evidence/archive changes are documentation only. Current-head specialist/CI evidence and merge/deploy receipts live in PR2918 and `.do-state.md`. + +## Post-mortem + +Plaintext backups, missing rollback/history validation and name-based lifecycle assumptions were unsafe. Real SDK failure evidence replaced the unconfirmed tracker hypothesis. Real disposable execution exposed read-only cache cleanup and executable-mode loss; both have discriminating regressions. Review added clone identity isolation, inactive restore deployment, durable retries, exact backup deletion proof and retained-key retry ownership. Clean CI exposed an unbuilt workspace-package dependency that locally built output had hidden; the full suite now proves source resolution with that output absent. + +## References + +PR https://github.com/raphaeltm/simple-agent-manager/pull/2918; idea01M72M9AEB933ZY8269D376DKC LANDING PLAN part6; SAM task01M7TTKAS78AMJ3853S5N4BYAK; coordinator01M7JMXS2JRW6QQMB1356ENPM3; policy795e72a6; rule56; `/do`. From 99960ba8ec58e219b5e5276a86fd6dca2f2e447f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rapha=C3=ABl=20Titsworth-Morin?= Date: Fri, 20 Nov 2026 01:05:06 +0000 Subject: [PATCH 11/17] fix(selfhost): make interrupted operations safely retryable --- deploy/selfhost/README.md | 46 +++- deploy/selfhost/docker-compose.yml | 10 +- scripts/selfhost/backup-entrypoint.test.ts | 35 +++ scripts/selfhost/backup-interruptions.test.ts | 154 +++++++++++ scripts/selfhost/backup-lib.ts | 28 +- scripts/selfhost/backup-recovery.ts | 81 ++++-- scripts/selfhost/backup-restore.ts | 22 +- scripts/selfhost/backup.test.ts | 99 +++++++ scripts/selfhost/install-record.ts | 14 + .../live/restore-local-store.live.test.ts | 165 ++++++++++++ scripts/selfhost/operator-ci-guard.test.ts | 5 + scripts/selfhost/private-tree.ts | 23 ++ scripts/selfhost/restore-completion.test.ts | 243 ++++++++++++++++++ scripts/selfhost/restore-progress.ts | 119 +++++++-- scripts/selfhost/restore-runtime.test.ts | 106 ++++++++ scripts/selfhost/restore-runtime.ts | 161 ++++++++++++ scripts/selfhost/restore.ts | 5 + .../rollback-cache-transition.test.ts | 155 +++++++++++ scripts/selfhost/rollback-cache-transition.ts | 107 ++++++++ scripts/selfhost/teardown-box.ts | 84 ++++-- scripts/selfhost/teardown-compose-progress.ts | 86 +++++++ .../selfhost/teardown-compose-retry.test.ts | 149 +++++++++++ scripts/selfhost/teardown-compose.ts | 20 +- scripts/selfhost/teardown-gcp-bootstrap.ts | 62 ++--- scripts/selfhost/teardown-gcp-grants.test.ts | 106 ++++++++ scripts/selfhost/teardown-gcp-grants.ts | 43 ++++ scripts/selfhost/teardown-identity.ts | 12 + .../selfhost/teardown-interruption.test.ts | 148 +++++++++++ scripts/selfhost/teardown-model.test.ts | 4 + scripts/selfhost/teardown-model.ts | 35 +-- scripts/selfhost/teardown-record.ts | 46 ++++ scripts/selfhost/teardown-state-dir.ts | 6 + scripts/selfhost/upgrade-lib.ts | 3 +- scripts/selfhost/upgrade-rollback-cli.test.ts | 16 +- scripts/selfhost/upgrade-rollback.test.ts | 65 ++++- scripts/selfhost/upgrade-safeguards.test.ts | 1 + scripts/selfhost/upgrade.test.ts | 1 + .../2026-11-19-l24-selfhost-operations.md | 18 +- 38 files changed, 2305 insertions(+), 178 deletions(-) create mode 100644 scripts/selfhost/backup-interruptions.test.ts create mode 100644 scripts/selfhost/live/restore-local-store.live.test.ts create mode 100644 scripts/selfhost/private-tree.ts create mode 100644 scripts/selfhost/restore-completion.test.ts create mode 100644 scripts/selfhost/restore-runtime.test.ts create mode 100644 scripts/selfhost/restore-runtime.ts create mode 100644 scripts/selfhost/rollback-cache-transition.test.ts create mode 100644 scripts/selfhost/rollback-cache-transition.ts create mode 100644 scripts/selfhost/teardown-compose-progress.ts create mode 100644 scripts/selfhost/teardown-compose-retry.test.ts create mode 100644 scripts/selfhost/teardown-gcp-grants.test.ts create mode 100644 scripts/selfhost/teardown-gcp-grants.ts create mode 100644 scripts/selfhost/teardown-identity.ts create mode 100644 scripts/selfhost/teardown-interruption.test.ts create mode 100644 scripts/selfhost/teardown-record.ts diff --git a/deploy/selfhost/README.md b/deploy/selfhost/README.md index d7f02eee0c..4d3114e1b0 100644 --- a/deploy/selfhost/README.md +++ b/deploy/selfhost/README.md @@ -132,6 +132,29 @@ the original backup. Prepare an existing mode-0600 target `.env` with its own do settings and absolute state path. Its state directory must be empty or absent, and its bucket/prefix must contain no objects. For an `s3://` store, set `R2_S3_REGION` as well as `S3_ENDPOINT` and its credentials. +For the bundled store, first authenticate the backup and print the final target Compose project: + +```sh +pnpm --silent selfhost:restore --from /absolute/path/to/backup --print-project \ + --box-env /absolute/path/to/target.env --state-dir /absolute/path/to/fresh-state \ + --encryption-key-file "$HOME/.config/sam/backup.key" +``` + +This prints only the public project name; it makes no target, runtime or store changes. Put that +name in the target `.env` as `COMPOSE_PROJECT_NAME`, keep `COMPOSE_PROFILES=local-store` (plus any +other desired profiles), and start only the bundled store and its initializer: + +```sh +docker compose --env-file /absolute/path/to/target.env \ + -f deploy/selfhost/docker-compose.yml --profile local-store up -d objectstore objectstore-init +``` + +Wait for the store to be healthy and the initializer to exit successfully, then run the restore +below. Its store-only exception verifies the final canonical project, selected canonical Compose +file, pinned image, ownership labels and exact data/script mounts. It refuses application or +foreign containers, overlays and a store started under the pre-key project. The same project +keeps the restored store volume when you initialize and start the application afterward. The +store healthcheck uses IPv4 loopback and `OBJECTSTORE_PORT`, including a custom port. ```sh pnpm selfhost:restore --from /absolute/path/to/backup \ @@ -143,8 +166,15 @@ Restore authenticates the complete encrypted inventory and every file before tou If a copy fails, retain `.restore-progress.json` and retry the exact same command and backup. This private journal binds the original empty target and authenticated snapshot. A retry refuses changed, additional, linked or foreign-owned partial files before copying again; do not -start the target or remove its journal to bypass a refusal. The journal is removed after success. -It refuses a target project with existing containers, copies state and bucket data, keeps the +start the target or remove its journal to bypass a refusal. State files interrupted mid-copy may +be retried only when their bytes are an exact prefix of the authenticated source; bucket objects +still require complete byte equality. Before removing the progress journal, restore durably links +a private `.restore-complete.json` receipt. Keep that completion receipt until a fresh +deploy and health/data checks succeed: the same restore can safely retry after a completion error, +even when progress-journal removal succeeded but its directory sync failed. Both receipts must +match if present. A completed retry still refuses changed data or an application runtime. After +verification, remove these exact operator-owned metadata files manually; teardown retains them. +It permits only the verified bundled-store bootstrap described above, copies state and bucket data, keeps the target `.env`, strips the source installation's creation receipts, and does not start celld. A fresh restore assigns a distinct `SAM_INSTALLATION_ID`, stable for retries of the same target, while preserving all cryptographic keys needed to read the restored data. The generated local @@ -161,7 +191,17 @@ to retain the restored keys and establish new target ownership receipts. Set the persisted installation id, domain and state directory. Repeat init with that setting, then start that target's Compose stack, deploy and verify its data (`scripts/selfhost/backup-lib.ts:runRestore`, `scripts/selfhost/install-record.ts:recordInstall`). -This command refuses an occupied target; it does not overwrite an existing fleet. +This command refuses an occupied application target; it does not overwrite an existing fleet. + +A killed backup process cannot run its restart handler. If interrupted while celld was stopped, +inspect the exact installation's containers and restart only that installation's celld explicitly, +then use a fresh backup destination. Normal backup refuses a missing or stopped writer; it never +guesses which other installation to start. A partial ciphertext directory is not reusable, and a +fully encrypted backup whose receipt write failed is retained for operator inspection and restore; +it is not automatically adopted for destructive cleanup. An interrupted initial journal write +before target writes can leave an invalid progress receipt: restore refuses to adopt it. Verify +that both target state and bucket are still empty before manually removing that exact receipt and +retrying. Preserve populated or unverified targets for inspection instead of bypassing ownership. ## Upgrade diff --git a/deploy/selfhost/docker-compose.yml b/deploy/selfhost/docker-compose.yml index cfe8e3157e..e29c3bcc13 100644 --- a/deploy/selfhost/docker-compose.yml +++ b/deploy/selfhost/docker-compose.yml @@ -332,7 +332,15 @@ services: volumes: - objectstore-data:/data healthcheck: - test: ['CMD', 'mc', 'ready', 'local'] + test: + [ + 'CMD', + 'curl', + '--fail', + '--silent', + '--show-error', + 'http://127.0.0.1:${OBJECTSTORE_PORT:-9000}/minio/health/ready', + ] interval: 5s retries: 30 stop_grace_period: 30s diff --git a/scripts/selfhost/backup-entrypoint.test.ts b/scripts/selfhost/backup-entrypoint.test.ts index d1601bf96d..3970c399ac 100644 --- a/scripts/selfhost/backup-entrypoint.test.ts +++ b/scripts/selfhost/backup-entrypoint.test.ts @@ -125,6 +125,41 @@ afterEach(() => { }); describe('selfhost:backup and selfhost:restore (real entry points, fake gcloud)', () => { + it('prints only the authenticated final project without target writes or runtime/store calls', () => { + const dest = join(root, 'project-backup'); + expect( + run('backup.ts', [ + '--to', + dest, + '--box-env', + join(root, 'box.env'), + '--state-dir', + join(root, 'state'), + '--encryption-key-file', + join(root, 'backup-key'), + ]).status + ).toBe(0); + writeFileSync(join(root, 'fresh.env'), 'CELLD_BUCKET=gs://fresh/celld\n', { mode: 0o600 }); + writeFileSync(join(root, 'fake/calls.log'), ''); + const output = run('restore.ts', [ + '--from', + dest, + '--print-project', + '--box-env', + join(root, 'fresh.env'), + '--state-dir', + join(root, 'fresh-state'), + '--encryption-key-file', + join(root, 'backup-key'), + ]); + expect(output.status).toBe(0); + expect(output.stderr).toBe(''); + expect(output.stdout).toMatch(/^sam-selfhost-[a-f0-9]{12}\n$/); + expect(readFileSync(join(root, 'fake/calls.log'), 'utf8')).toBe(''); + expect(existsSync(join(root, 'fresh-state'))).toBe(false); + expect(existsSync(join(root, 'gcs/fresh'))).toBe(false); + expect(existsSync(join(root, 'fresh-state.restore-progress.json'))).toBe(false); + }); it('uses a clean full copy after the stopped pass hits the confirmed POSIX stat of a missing finalized file', () => { writeFileSync( join(root, 'fake/posix-fail-once.json'), diff --git a/scripts/selfhost/backup-interruptions.test.ts b/scripts/selfhost/backup-interruptions.test.ts new file mode 100644 index 0000000000..9a27641358 --- /dev/null +++ b/scripts/selfhost/backup-interruptions.test.ts @@ -0,0 +1,154 @@ +/** Backup failure boundaries operate on real files; the runner models only external commands. */ +import { randomBytes } from 'node:crypto'; +import * as fs from 'node:fs'; +import { dirname, join, resolve } from 'node:path'; + +import { afterEach, beforeEach, expect, it, vi } from 'vitest'; + +import { decryptBackupTree } from './backup-encryption'; +import { type BoxContext, runBackup } from './backup-lib'; +import { removePrivateTree } from './private-tree'; + +vi.mock('node:fs', async (original) => ({ ...(await original()) })); + +let root: string; +let ctx: BoxContext; +let stopped: boolean; +let starts: number; +let pulls: number; +let fail: 'none' | 'stop' | 'copy' | 'start'; +let scratch: string; +const SECRET = 'synthetic-backup-interruption-secret'; + +beforeEach(() => { + for (const name of Object.keys(process.env)) + if (name === 'CI' || name === 'GITHUB_ACTIONS' || name.startsWith('RUNNER_')) + vi.stubEnv(name, undefined); + fs.mkdirSync(resolve('.tmp'), { recursive: true }); + root = fs.mkdtempSync(resolve('.tmp/backup-interruption-')); + const stateDir = join(root, 'state'); + fs.mkdirSync(stateDir, { mode: 0o700 }); + fs.mkdirSync(join(root, 'store')); + fs.writeFileSync(join(root, 'store', 'data'), 'original data'); + fs.writeFileSync(join(stateDir, 'secrets.env'), SECRET, { mode: 0o600 }); + const envFile = join(root, 'box.env'); + fs.writeFileSync(envFile, 'SAM_DOMAIN=backup.example.com\n', { mode: 0o600 }); + const encryptionKeyFile = join(root, 'backup.key'); + fs.writeFileSync(encryptionKeyFile, randomBytes(32), { mode: 0o600 }); + stopped = false; + starts = 0; + pulls = 0; + scratch = ''; + fail = 'none'; + ctx = { + box: { CELLD_BUCKET: 'gs://synthetic-bucket/backup', SAM_DOMAIN: 'backup.example.com' }, + envFile, + stateDir, + encryptionKeyFile, + composeFiles: [], + now: () => Date.now(), + log: () => {}, + run(command, args) { + const ok = { status: 0, stdout: '', stderr: '' }; + const bad = { status: 1, stdout: SECRET, stderr: SECRET }; + if (command === 'docker' && args.includes('ps')) + return { ...ok, stdout: stopped ? '' : 'a'.repeat(64) }; + if (command === 'docker' && args.includes('stop')) { + stopped = true; + return fail === 'stop' ? bad : ok; + } + if (command === 'docker' && args.includes('start')) { + starts++; + stopped = false; + return fail === 'start' ? bad : ok; + } + if (command === 'gcloud' && args[1] === 'rsync') { + pulls++; + const destination = args.at(-1)!; + scratch = dirname(destination); + if (fail === 'copy' && stopped) return bad; + fs.cpSync(join(root, 'store'), destination, { recursive: true }); + } + return ok; + }, + }; +}); +afterEach(() => { + vi.restoreAllMocks(); + if (scratch && fs.existsSync(scratch)) removePrivateTree(scratch); + removePrivateTree(root); + vi.unstubAllEnvs(); +}); + +it('restarts the selected writer when stop reports failure after stopping it, then retries fresh', () => { + fail = 'stop'; + expect(() => runBackup(ctx, join(root, 'failed'))).toThrow('compose stop celld failed'); + expect(stopped).toBe(false); + expect(starts).toBe(1); + expect(pulls).toBe(1); // No stopped copy ran after stop failed. + expect(fs.existsSync(scratch)).toBe(false); + expect(fs.existsSync(join(root, 'failed'))).toBe(false); + fail = 'none'; + expect(runBackup(ctx, join(root, 'retry')).objectCount).toBe(1); +}); + +it.each(['copy', 'start'] as const)( + 'preserves restart and secret-free failure on %s, then retries', + (boundary) => { + fail = boundary; + let message = ''; + try { + runBackup(ctx, join(root, 'failed')); + } catch (error) { + message = String(error); + } + expect(message).toContain('failed'); + expect(message).not.toContain(SECRET); + expect(stopped).toBe(false); + expect(starts).toBe(1); + expect(fs.existsSync(scratch)).toBe(false); + fail = 'none'; + expect(runBackup(ctx, join(root, 'retry')).objectCount).toBe(1); + } +); + +it('cleans copied read-only secret directories after success and an encryption error', () => { + const protectedDir = join(ctx.stateDir, 'private-read-only'); + fs.mkdirSync(protectedDir); + fs.writeFileSync(join(protectedDir, 'secret'), SECRET, { mode: 0o400 }); + fs.chmodSync(protectedDir, 0o500); + const first = join(root, 'first'); + runBackup(ctx, first); + expect(fs.existsSync(scratch)).toBe(false); + const restored = join(root, 'decrypted'); + decryptBackupTree(first, restored, ctx.encryptionKeyFile!); + expect(fs.readFileSync(join(restored, 'state', 'private-read-only', 'secret'), 'utf8')).toBe( + SECRET + ); + const open = fs.openSync; + vi.spyOn(fs, 'openSync').mockImplementation((...args: Parameters) => { + if (String(args[0]).startsWith(join(root, 'failed-encryption'))) throw new Error(SECRET); + return open(...args); + }); + expect(() => runBackup(ctx, join(root, 'failed-encryption'))).toThrow('Backup encryption failed'); + expect(fs.existsSync(scratch)).toBe(false); + expect(fs.existsSync(join(root, 'failed-encryption'))).toBe(false); + expect(stopped).toBe(false); +}); + +it('never follows scratch symlinks or accepts a symlink root', () => { + const outside = join(root, 'outside'); + const privateDir = join(root, 'scratch'); + fs.mkdirSync(outside); + fs.mkdirSync(privateDir); + fs.writeFileSync(join(outside, 'keep'), 'foreign data'); + fs.chmodSync(outside, 0o500); + fs.symlinkSync(outside, join(privateDir, 'link')); + removePrivateTree(privateDir); + expect(fs.readFileSync(join(outside, 'keep'), 'utf8')).toBe('foreign data'); + expect(fs.statSync(outside).mode & 0o777).toBe(0o500); + const link = join(root, 'link'); + fs.symlinkSync(outside, link); + expect(() => removePrivateTree(link)).toThrow('original directory'); + expect(fs.existsSync(outside)).toBe(true); +}); diff --git a/scripts/selfhost/backup-lib.ts b/scripts/selfhost/backup-lib.ts index 0dc0b5dee9..619dcb177e 100644 --- a/scripts/selfhost/backup-lib.ts +++ b/scripts/selfhost/backup-lib.ts @@ -15,11 +15,14 @@ import { dirname, join, relative, resolve } from 'node:path'; import { prepareBackupParent } from './backup-destination'; import { decryptBackupTree, encryptBackupTree, readBackupKey } from './backup-encryption'; +import { readManifest } from './backup-manifest'; import { assertBackupOutside, assertOperationPaths } from './backup-paths'; import { restoreBackup } from './backup-restore'; import { requireRunningCelld } from './backup-runtime'; -import { composeProjectFor, recordBackup } from './install-record'; +import { composeProjectFor, expectedComposeProjectFor, recordBackup } from './install-record'; import { assertOperatorExecution } from './operator-only'; +import { removePrivateTree } from './private-tree'; +import { projectRestoreIdentity } from './restore-identity'; import { ensurePrivateDir } from './secret-files'; /** @@ -319,11 +322,12 @@ function runPlainBackup( } ctx.log('stopping celld for the delta copy'); - compose(ctx, ['stop', 'celld']); - const stoppedAt = ctx.now(); + let stoppedAt = ctx.now(); let deltaCopyMs = 0; let startedAt = stoppedAt; try { + compose(ctx, ['stop', 'celld']); + stoppedAt = ctx.now(); // With celld stopped the bucket is the consistent state. The mirror (with deletion) converges // the local tree on exactly that: objects celld removed after the pre-copy are deleted here. try { @@ -427,12 +431,18 @@ export function runBackup( ctx.log(`encrypted backup complete -> ${dest}`); return manifest; } finally { - rmSync(temp, { recursive: true, force: true }); + removePrivateTree(temp); } } /** Authenticate every byte before any target bucket or compose operation. */ -export function runRestore(ctx: BoxContext, from: string): BackupManifest { +export function runRestore(ctx: BoxContext, from: string): BackupManifest; +export function runRestore(ctx: BoxContext, from: string, mode: 'project'): string; +export function runRestore( + ctx: BoxContext, + from: string, + mode?: 'project' +): BackupManifest | string { assertOperatorExecution(); const key = backupKey(ctx); assertBackupOutside(ctx, from); @@ -440,9 +450,14 @@ export function runRestore(ctx: BoxContext, from: string): BackupManifest { try { const plain = join(temp, 'plain'); decryptBackupTree(from, plain, key); + if (mode === 'project') { + readManifest(plain); + const identity = projectRestoreIdentity(ctx, join(plain, STATE_DIR)); + return expectedComposeProjectFor(ctx.box, ctx.stateDir, identity); + } return restoreBackup(ctx, plain, from); } finally { - rmSync(temp, { recursive: true, force: true }); + removePrivateTree(temp); } } @@ -450,6 +465,7 @@ export { readManifest } from './backup-manifest'; export { assertBackupOutside } from './backup-paths'; export { assertRollbackCacheReady, + beginRollbackCacheStart, finishRollbackCache, refreshRollbackCacheReceipt, runRollback, diff --git a/scripts/selfhost/backup-recovery.ts b/scripts/selfhost/backup-recovery.ts index 4c06ca55b2..3711dc617b 100644 --- a/scripts/selfhost/backup-recovery.ts +++ b/scripts/selfhost/backup-recovery.ts @@ -1,11 +1,9 @@ /** Restore an upgrade's authenticated snapshot to the same owned installation. */ import { - chmodSync, cpSync, existsSync, lstatSync, mkdtempSync, - readdirSync, readFileSync, renameSync, rmSync, @@ -33,6 +31,12 @@ import { } from './backup-lib'; import { composeProjectFor, recordInstall, SELFHOST_ENVIRONMENT } from './install-record'; import { assertOperatorExecution } from './operator-only'; +import { removePrivateTree } from './private-tree'; +import { + type CacheStartProof, + cacheStartTime, + recoverCacheStart, +} from './rollback-cache-transition'; import { assertPrivateFile, replacePrivateFile } from './secret-files'; import { assertRollbackReady } from './upgrade-preflight'; function compose(ctx: BoxContext, args: string[]): void { @@ -183,11 +187,17 @@ export function assertRollbackCacheReady(ctx: BoxContext): RollbackCacheProof { /** A private receipt permits retry after this process removed only part of the cache. */ const CACHE_PENDING = 'rollback-cache-pending.json'; -function pendingCache(ctx: BoxContext, from: string): RollbackCacheProof | null { +function pendingCache(ctx: BoxContext, from: string): CacheStartProof | null { const path = join(ctx.stateDir, CACHE_PENDING); if (!existsSync(path)) return null; assertPrivateFile(path); - let value: { snapshot?: unknown; name?: unknown; createdAt?: unknown; container?: unknown }; + let value: { + snapshot?: unknown; + name?: unknown; + createdAt?: unknown; + container?: unknown; + startingAt?: unknown; + }; try { value = JSON.parse(readFileSync(path, 'utf8')); } catch { @@ -199,10 +209,17 @@ function pendingCache(ctx: BoxContext, from: string): RollbackCacheProof | null typeof value.createdAt !== 'string' || !Number.isFinite(Date.parse(value.createdAt)) || typeof value.container !== 'string' || - !/^[a-f0-9]{64}$/.test(value.container) + !/^[a-f0-9]{64}$/.test(value.container) || + (value.startingAt !== undefined && + (typeof value.startingAt !== 'string' || !Number.isFinite(Date.parse(value.startingAt)))) ) throw new Error('Invalid rollback cache recovery receipt'); - return { name: value.name, createdAt: value.createdAt, container: value.container }; + return { + name: value.name, + createdAt: value.createdAt, + container: value.container, + ...(typeof value.startingAt === 'string' ? { startingAt: value.startingAt } : {}), + }; } function cachePresence( ctx: BoxContext, @@ -265,10 +282,30 @@ function discardCelldCache(ctx: BoxContext, expected: RollbackCacheProof, from: } /** After an authorized Compose recreation, bind retry to its newly observed exact cache. */ +export function beginRollbackCacheStart(ctx: BoxContext, from: string): void { + assertOperatorExecution(); + const pending = pendingCache(ctx, from); + if (!pending) throw new Error('Missing rollback cache recovery receipt'); + const present = cachePresence(ctx, pending); + if (present.container || present.volume) + throw new Error('Recovery start requires the previous cache to be absent'); + currentLedger( + ctx, + String(readIdentity(join(ctx.stateDir, 'platform-keys.json')).SAM_INSTALLATION_ID) + ); + replacePrivateFile( + join(ctx.stateDir, CACHE_PENDING), + JSON.stringify({ ...pending, snapshot: resolve(from), startingAt: cacheStartTime() }) + ); +} + export function refreshRollbackCacheReceipt(ctx: BoxContext, from: string): void { assertOperatorExecution(); - if (!pendingCache(ctx, from)) throw new Error('Missing rollback cache recovery receipt'); - const proof = assertRollbackCacheReady(ctx); + const pending = pendingCache(ctx, from); + if (!pending) throw new Error('Missing rollback cache recovery receipt'); + const proof = pending.startingAt + ? recoverCacheStart(ctx, pending, inspectCacheVolume, assertRollbackCacheReady, true) + : assertRollbackCacheReady(ctx); replacePrivateFile( join(ctx.stateDir, CACHE_PENDING), JSON.stringify({ ...proof, snapshot: resolve(from) }) @@ -283,21 +320,6 @@ export function finishRollbackCache(ctx: BoxContext): void { assertPrivateFile(path); rmSync(path); } -/** Go module caches contain read-only directories. Only chmod directories in our private, - * just-created stage; never follow a symlink or change a directory owned by another uid. */ -function removeRollbackStage(path: string): void { - const writable = (directory: string): void => { - const stat = lstatSync(directory); - if (!stat.isDirectory() || stat.isSymbolicLink()) return; - if (process.getuid && stat.uid !== process.getuid()) - throw new Error('Rollback cleanup directory belongs to another user'); - if ((stat.mode & 0o700) !== 0o700) chmodSync(directory, stat.mode | 0o700); - for (const entry of readdirSync(directory)) writable(join(directory, entry)); - }; - writable(path); - rmSync(path, { recursive: true, force: true }); -} - /** Stage the full replacement before swapping directories; failed copying retains live state. */ function restoreState( ctx: BoxContext, @@ -336,7 +358,7 @@ function restoreState( throw error; } } finally { - removeRollbackStage(stage); + removePrivateTree(stage); } } @@ -367,7 +389,14 @@ export function runRollback(ctx: BoxContext, from: string, expectedSamCommit?: s } assertStateReceipt(join(plain, STATE_DIR), ctx.stateDir, oldKeys.SAM_INSTALLATION_ID); currentLedger(ctx, oldKeys.SAM_INSTALLATION_ID); - const pending = pendingCache(ctx, from); + let pending = pendingCache(ctx, from); + if (pending?.startingAt) { + pending = recoverCacheStart(ctx, pending, inspectCacheVolume, assertRollbackCacheReady); + replacePrivateFile( + join(ctx.stateDir, CACHE_PENDING), + JSON.stringify({ ...pending, snapshot: resolve(from) }) + ); + } const cache = pending ?? assertRollbackCacheReady(ctx); if (pending) cachePresence(ctx, pending); compose(ctx, ['stop', 'celld']); @@ -415,6 +444,6 @@ export function runRollback(ctx: BoxContext, from: string, expectedSamCommit?: s replacePrivateFile(ctx.envFile, readFileSync(join(plain, ENV_FILE), 'utf8')); discardCelldCache(ctx, cache, from); } finally { - rmSync(temp, { recursive: true, force: true }); + removePrivateTree(temp); } } diff --git a/scripts/selfhost/backup-restore.ts b/scripts/selfhost/backup-restore.ts index f045c0a28d..e607d5fc58 100644 --- a/scripts/selfhost/backup-restore.ts +++ b/scripts/selfhost/backup-restore.ts @@ -7,33 +7,17 @@ import { type BoxContext, BUCKET_DIR, bucketIsEmpty, - check, pullBucket, pushBucket, readManifest, STATE_DIR, } from './backup-lib'; -import { composeProjectFor, expectedComposeProjectFor } from './install-record'; import { assertOperatorExecution } from './operator-only'; import { projectRestoreIdentity } from './restore-identity'; import { assertRestoreSubset, restoreProgress } from './restore-progress'; +import { assertRestoreRuntime } from './restore-runtime'; import { ensurePrivateDir } from './secret-files'; -function assertEmptyRuntime(ctx: BoxContext, identity: string): void { - const projects = new Set([ - composeProjectFor(ctx.box, ctx.stateDir), - expectedComposeProjectFor(ctx.box, ctx.stateDir, identity), - ]); - for (const project of projects) { - const containers = check( - ctx.run('docker', ['ps', '-aq', '--filter', `label=com.docker.compose.project=${project}`]), - 'check empty restore runtime' - ); - if (containers.stdout.trim()) - throw new Error('Restore target already has containers; use a fresh installation'); - } -} - export function restoreBackup(ctx: BoxContext, plain: string, encrypted: string): BackupManifest { assertOperatorExecution(); const manifest = readManifest(plain); @@ -51,9 +35,9 @@ export function restoreBackup(ctx: BoxContext, plain: string, encrypted: string) throw new Error('Restore bucket is not empty: restore only into an empty bucket'); } // Inspect by labels: parsing Compose before gateway.env exists would reject a fresh install. - assertEmptyRuntime(ctx, identity); + assertRestoreRuntime(ctx, identity); if (progress.resume) { - assertRestoreSubset(ctx.stateDir, join(plain, STATE_DIR)); + assertRestoreSubset(ctx.stateDir, join(plain, STATE_DIR), true); const current = join(plain, '.restore-current-bucket'); pullBucket(ctx, current); assertRestoreSubset(current, join(plain, BUCKET_DIR)); diff --git a/scripts/selfhost/backup.test.ts b/scripts/selfhost/backup.test.ts index 22adbc335c..21f900e0bc 100644 --- a/scripts/selfhost/backup.test.ts +++ b/scripts/selfhost/backup.test.ts @@ -46,6 +46,7 @@ import { prepareCelldProject, writeCelldConfig } from './celld-project'; import { runDeploy, runTsx, writeBox } from './deploy-harness'; import { composeProjectFor, expectedComposeProjectFor, recordInstall } from './install-record'; import { restoredInstallationId } from './restore-identity'; +import { recoverUpgrade } from './upgrade-lib'; vi.mock('node:fs', async (importOriginal) => ({ ...(await importOriginal()), @@ -925,6 +926,104 @@ describe('runRollback', () => { ); }); + it.each(['replacement', 'volume-only', 'no-resources'])( + 'retries partial Compose %s creation after a failed start and ownership refresh', + async (partial) => { + const context = ctx('gs://fleet/celld', join(root, 'state')); + const snapshot = join(root, 'partial-compose-snapshot'); + const source = 'a'.repeat(40); + runBackup(context, snapshot, source); + const invoke = context.run; + let container = 'c'.repeat(64); + let volume = true; + let created = '2026-11-19T01:00:00Z'; + let starts = 0; + let inspectFailure = partial === 'replacement'; + const deleted: string[] = []; + context.run = (command, args, env) => { + if (command === 'git' || command === 'pnpm') return { status: 0, stdout: '', stderr: '' }; + const result = invoke(command, args, env); + if (command !== 'docker') return result; + if (args.includes('up')) { + starts++; + container = (starts === 1 ? 'd' : 'e').repeat(64); + created = new Date().toISOString(); + volume = true; + if (starts === 1 && partial !== 'replacement') container = ''; + if (starts === 1 && partial === 'no-resources') volume = false; + return { ...result, status: starts === 1 ? 1 : 0 }; + } + if (args[0] === 'compose' && args.includes('ps')) return { ...result, stdout: container }; + if (args[0] === 'container' && args[1] === 'rm') { + deleted.push(args[3]!); + container = ''; + } + if (args[0] === 'volume' && args[1] === 'rm') volume = false; + if (args[0] === 'volume' && args[1] === 'ls') + return { ...result, stdout: volume ? `${selectedProject}_celld-data` : '' }; + if (args[0] === 'volume' && args[1] === 'inspect') { + const value = JSON.parse(result.stdout); + value[0].CreatedAt = created; + return { ...result, stdout: JSON.stringify(value) }; + } + if (args[0] === 'inspect' && args[2]?.includes('{{json .Id}}')) { + if (inspectFailure) { + inspectFailure = false; + return { ...result, status: 1 }; + } + return { + ...result, + stdout: JSON.stringify({ + Id: container, + Created: created, + Config: { + Labels: { + 'com.docker.compose.project': selectedProject, + 'com.docker.compose.service': 'celld', + 'com.docker.compose.project.config_files': context.composeFiles + .map((p) => resolve(p)) + .join(','), + 'com.docker.compose.project.working_dir': resolve(context.composeFiles[0]!, '..'), + }, + }, + }), + }; + } + return result; + }; + const upgradeContext = { ...context, composeFiles: context.composeFiles }; + const health = vi.fn(async () => true); + await expect( + recoverUpgrade(upgradeContext, source, snapshot, [], { to: source, checkHealth: health }) + ).rejects.toThrow(/restore previous stack failed/); + const receipt = join(context.stateDir, 'rollback-cache-pending.json'); + const authorized = readFileSync(receipt, 'utf8'); + const unstarted = JSON.parse(authorized); + expect(unstarted.startingAt).toBeTruthy(); + expect(health).not.toHaveBeenCalled(); + // Negative control: without durable start authorization the replacement must remain foreign. + if (partial !== 'no-resources') { + delete unstarted.startingAt; + writeFileSync(receipt, JSON.stringify(unstarted)); + await expect( + recoverUpgrade(upgradeContext, source, snapshot, [], { to: source, checkHealth: health }) + ).rejects.toThrow(/cache identity changed/); + expect(deleted).toEqual(['c'.repeat(64)]); + writeFileSync(receipt, authorized); + } + await recoverUpgrade(upgradeContext, source, snapshot, [], { + to: source, + checkHealth: health, + }); + expect(starts).toBe(2); + expect(deleted).toEqual( + partial === 'replacement' ? ['c'.repeat(64), 'd'.repeat(64)] : ['c'.repeat(64)] + ); + expect(health).toHaveBeenCalledOnce(); + expect(existsSync(receipt)).toBe(false); + } + ); + it('retains current backup/cloud receipts and removal markers instead of reviving snapshot history', () => { const context = ctx('gs://fleet/celld', join(root, 'state')); const ledger = join(context.stateDir, 'created-resources.json'); diff --git a/scripts/selfhost/install-record.ts b/scripts/selfhost/install-record.ts index 0a19754757..8321eb776a 100644 --- a/scripts/selfhost/install-record.ts +++ b/scripts/selfhost/install-record.ts @@ -70,6 +70,20 @@ export function expectedComposeProjectFor( } if (installationId !== undefined && !/^[a-f0-9]{32}$/.test(installationId)) throw new Error('Invalid persisted installation identity for Compose'); + return projectForIdentity(box, stateDir, installation); +} +/** Empty-state canonical project without reading a possibly interrupted restored keys file. */ +export function uninitializedComposeProjectFor( + box: Readonly>, + stateDir: string +): string { + return projectForIdentity(box, stateDir, ''); +} +function projectForIdentity( + box: Readonly>, + stateDir: string, + installation: string +): string { const suffix = createHash('sha256') .update(`${box.SAM_DOMAIN ?? ''}\n${resolve(stateDir)}\n${installation}`) .digest('hex') diff --git a/scripts/selfhost/live/restore-local-store.live.test.ts b/scripts/selfhost/live/restore-local-store.live.test.ts new file mode 100644 index 0000000000..0622490c5c --- /dev/null +++ b/scripts/selfhost/live/restore-local-store.live.test.ts @@ -0,0 +1,165 @@ +/** Actual canonical Compose bootstrap, encrypted restore, and refusal of a real celld-labelled runtime. */ +import { spawnSync } from 'node:child_process'; +import { randomBytes } from 'node:crypto'; +import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'; +import { join, resolve } from 'node:path'; + +import { afterEach, expect, it, vi } from 'vitest'; + +import { encryptBackupTree } from '../backup-encryption'; +import { type BoxContext, composeArgs, composeRunEnv, pullBucket, runRestore } from '../backup-lib'; +import { runDeploy } from '../deploy-harness'; +import { freePort, LIVE_TMP, skipWithoutDocker } from './harness'; + +let root = '', + project = '', + runtime = ''; +const run: BoxContext['run'] = (command, args, env) => { + const r = spawnSync(command, args, { env: env ?? process.env, encoding: 'utf8' }); + return { status: r.status ?? 1, stdout: r.stdout ?? '', stderr: r.stderr ?? '' }; +}; +afterEach(() => { + if (runtime) run('docker', ['rm', '-f', '-v', runtime]); + if (project) { + for (const role of ['objectstore', 'objectstore-init']) + run('docker', ['rm', '-f', '-v', `${project}-${role}-1`]); + run('docker', ['volume', 'rm', `${project}_objectstore-data`]); + } + if (root) rmSync(root, { recursive: true, force: true }); + vi.unstubAllEnvs(); +}); +it.skipIf(skipWithoutDocker)( + 'restores through actual canonical store-only Compose and keeps its volume across init; refuses real celld', + async () => { + for (const n of Object.keys(process.env)) + if (n === 'CI' || n === 'GITHUB_ACTIONS' || n.startsWith('RUNNER_')) vi.stubEnv(n, undefined); + mkdirSync(LIVE_TMP, { recursive: true }); + root = mkdtempSync(join(LIVE_TMP, 'restore-canonical-')); + const port = await freePort(), + consolePort = await freePort(), + plain = join(root, 'plain'), + snapshot = join(root, 'encrypted'); + mkdirSync(join(plain, 'state'), { recursive: true }); + mkdirSync(join(plain, 'bucket/data'), { recursive: true }); + writeFileSync(join(root, 'key'), randomBytes(32), { mode: 0o600 }); + writeFileSync( + join(plain, 'state/platform-keys.json'), + JSON.stringify({ SAM_INSTALLATION_ID: 'a'.repeat(32), ENCRYPTION_KEY: 'preserved-fixture' }), + { mode: 0o600 } + ); + writeFileSync(join(plain, 'bucket/data/value'), 'actual restored bytes'); + writeFileSync( + join(plain, 'backup-manifest.json'), + JSON.stringify({ + version: 1, + createdAt: new Date().toISOString(), + bucket: 's3://source/celld', + samCommit: null, + precopyMs: 0, + downtimeMs: 0, + deltaCopyMs: 0, + objectCount: 1, + }) + ); + encryptBackupTree(plain, snapshot, join(root, 'key')); + const box: Record = { + SAM_DOMAIN: 'restore.example.com', + SAM_TLS_MODE: 'internal', + COMPOSE_PROFILES: 'local-store', + CELLD_BUCKET: 's3://restore/celld', + R2_S3_REGION: 'us-east-1', + S3_ENDPOINT: `http://127.0.0.1:${port}`, + AWS_ACCESS_KEY_ID: 'restore-local-fixture', + AWS_SECRET_ACCESS_KEY: 'restore-local-secret-at-least24chars', + OBJECTSTORE_PORT: String(port), + OBJECTSTORE_CONSOLE_PORT: String(consolePort), + }; + const context: BoxContext = { + box, + stateDir: join(root, 'state'), + envFile: join(root, 'target.env'), + encryptionKeyFile: join(root, 'key'), + composeFiles: [resolve(import.meta.dirname, '../../../deploy/selfhost/docker-compose.yml')], + run, + now: Date.now, + log: () => {}, + user: `${process.getuid?.() ?? 0}:${process.getgid?.() ?? 0}`, + }; + writeFileSync( + context.envFile, + Object.entries(box) + .map(([k, v]) => `${k}=${v}`) + .join('\n'), + { mode: 0o600 } + ); + project = runRestore(context, snapshot, 'project'); + box.COMPOSE_PROJECT_NAME = project; + writeFileSync( + context.envFile, + Object.entries(box) + .map(([k, v]) => `${k}=${v}`) + .join('\n') + ); + const started = run( + 'docker', + composeArgs(context, ['up', '-d', 'objectstore', 'objectstore-init']), + composeRunEnv(context) + ); + expect(started.status, started.stderr).toBe(0); + for (let i = 0; i < 60; i++) { + const done = run('docker', [ + 'inspect', + '--format', + '{{.State.Status}}', + `${project}-objectstore-init-1`, + ]); + if (done.stdout.trim() === 'exited') break; + await new Promise((r) => setTimeout(r, 500)); + } + runRestore(context, snapshot); + const checked = join(root, 'verified'); + pullBucket(context, checked); + expect(readFileSync(join(checked, 'data/value'), 'utf8')).toBe('actual restored bytes'); + const volume = run('docker', [ + 'volume', + 'inspect', + '--format', + '{{.Name}}', + `${project}_objectstore-data`, + ]); + expect(volume.status).toBe(0); + expect(volume.stdout.trim()).toBe(`${project}_objectstore-data`); + const initialized = await runDeploy(context.envFile, [ + '--init', + '--state-dir', + context.stateDir, + ]); + expect(initialized.status, initialized.out).toBe(0); + const repeated = run( + 'docker', + composeArgs(context, ['up', '-d', 'objectstore', 'objectstore-init']), + composeRunEnv(context) + ); + expect(repeated.status, repeated.stderr).toBe(0); + const afterInit = join(root, 'verified-after-init'); + pullBucket(context, afterInit); + expect(readFileSync(join(afterInit, 'data/value'), 'utf8')).toBe('actual restored bytes'); + const blocked = run('docker', [ + 'run', + '-d', + '--label', + `com.docker.compose.project=${project}`, + '--label', + 'com.docker.compose.service=celld', + '--entrypoint', + 'sleep', + 'pgsty/minio@sha256:b6bfe7239bfc83fb90d31612d9704d86039dd714f7904b3f1ad68f211e602372', + '300', + ]); + expect(blocked.status).toBe(0); + runtime = blocked.stdout.trim(); + expect(() => runRestore(context, snapshot)).toThrow(/already has containers/); + expect(readFileSync(join(checked, 'data/value'), 'utf8')).toBe('actual restored bytes'); + }, + 120_000 +); diff --git a/scripts/selfhost/operator-ci-guard.test.ts b/scripts/selfhost/operator-ci-guard.test.ts index 7d554d033f..3e4e8b49d9 100644 --- a/scripts/selfhost/operator-ci-guard.test.ts +++ b/scripts/selfhost/operator-ci-guard.test.ts @@ -8,6 +8,7 @@ import { loadBox } from './backup-cli'; import { decryptBackupTree, encryptBackupTree, readBackupKey } from './backup-encryption'; import { assertRollbackCacheReady, + beginRollbackCacheStart, type BoxContext, runBackup, runRestore, @@ -16,6 +17,7 @@ import { import { restoreBackup } from './backup-restore'; import { projectRestoreIdentity, restoredInstallationId } from './restore-identity'; import { assertRestoreSubset, restoreProgress } from './restore-progress'; +import { assertRestoreRuntime } from './restore-runtime'; const ROOT = resolve(import.meta.dirname, '../..'); const ABSENT = resolve(ROOT, '.tmp/nonexistent-operator-guard-sentinel'); @@ -57,6 +59,8 @@ describe('operator commands never read secret files in CI', () => { () => encryptBackupTree(ABSENT, ABSENT, ABSENT), () => decryptBackupTree(ABSENT, ABSENT, ABSENT), () => assertRollbackCacheReady(context), + () => beginRollbackCacheStart(context, ABSENT), + () => assertRestoreRuntime(context, 'a'.repeat(32)), () => runBackup(context, ABSENT), () => runRestore(context, ABSENT), () => runRollback(context, ABSENT), @@ -72,6 +76,7 @@ describe('operator commands never read secret files in CI', () => { for (const [script, args] of [ ['backup.ts', ['--to', ABSENT]], ['restore.ts', ['--from', ABSENT]], + ['restore.ts', ['--from', ABSENT, '--print-project']], ['upgrade.ts', ['--to', 'main']], ] as const) { const result = spawnSync( diff --git a/scripts/selfhost/private-tree.ts b/scripts/selfhost/private-tree.ts new file mode 100644 index 0000000000..4f71430960 --- /dev/null +++ b/scripts/selfhost/private-tree.ts @@ -0,0 +1,23 @@ +/** Cleanup of newly created private operation scratch, including copied read-only directories. */ +import { chmodSync, lstatSync, readdirSync, rmSync } from 'node:fs'; +import { join } from 'node:path'; + +import { assertOperatorExecution } from './operator-only'; + +export function removePrivateTree(path: string): void { + assertOperatorExecution(); + const root = lstatSync(path, { throwIfNoEntry: false }); + if (!root) return; + if (!root.isDirectory() || root.isSymbolicLink()) + throw new Error('Private scratch cleanup requires its original directory'); + const writable = (directory: string): void => { + const info = lstatSync(directory); + if (!info.isDirectory() || info.isSymbolicLink()) return; + if (process.getuid !== undefined && info.uid !== process.getuid()) + throw new Error('Private scratch cleanup refuses a foreign-owned directory'); + if ((info.mode & 0o700) !== 0o700) chmodSync(directory, info.mode | 0o700); + for (const entry of readdirSync(directory)) writable(join(directory, entry)); + }; + writable(path); + rmSync(path, { recursive: true, force: true }); +} diff --git a/scripts/selfhost/restore-completion.test.ts b/scripts/selfhost/restore-completion.test.ts new file mode 100644 index 0000000000..86c47de75a --- /dev/null +++ b/scripts/selfhost/restore-completion.test.ts @@ -0,0 +1,243 @@ +/** Real encrypted restore with a filesystem-backed fake GCS; inject each completion boundary. */ +import { spawnSync } from 'node:child_process'; +import { randomBytes } from 'node:crypto'; +import * as fs from 'node:fs'; +import { join, resolve } from 'node:path'; + +import { afterEach, beforeEach, expect, it, vi } from 'vitest'; + +import { encryptBackupTree } from './backup-encryption'; +import { type BoxContext, runRestore } from './backup-lib'; +vi.mock('node:fs', async (original) => ({ ...(await original()) })); +let root: string, context: BoxContext, snapshot: string; +beforeEach(() => { + for (const n of Object.keys(process.env)) + if (n === 'CI' || n === 'GITHUB_ACTIONS' || n.startsWith('RUNNER_')) vi.stubEnv(n, undefined); + fs.mkdirSync(resolve('.tmp'), { recursive: true }); + root = fs.mkdtempSync(resolve('.tmp/restore-complete-')); + const plain = join(root, 'plain'); + snapshot = join(root, 'snapshot'); + fs.mkdirSync(join(plain, 'state'), { recursive: true }); + fs.mkdirSync(join(plain, 'bucket/data'), { recursive: true }); + fs.mkdirSync(join(root, 'fake')); + fs.writeFileSync(join(root, 'fake/celld'), 'running'); + fs.writeFileSync(join(root, 'key'), randomBytes(32), { mode: 0o600 }); + fs.writeFileSync(join(root, 'target.env'), 'CELLD_BUCKET=gs://fresh/celld\n', { mode: 0o600 }); + fs.writeFileSync( + join(plain, 'state/platform-keys.json'), + JSON.stringify({ SAM_INSTALLATION_ID: 'a'.repeat(32), ENCRYPTION_KEY: 'retained' }), + { mode: 0o600 } + ); + fs.writeFileSync(join(plain, 'bucket/data/value'), 'actual bytes'); + fs.writeFileSync( + join(plain, 'backup-manifest.json'), + JSON.stringify({ + version: 1, + createdAt: new Date().toISOString(), + bucket: 'gs://source/celld', + samCommit: null, + precopyMs: 0, + downtimeMs: 0, + deltaCopyMs: 0, + objectCount: 1, + }) + ); + encryptBackupTree(plain, snapshot, join(root, 'key')); + context = { + box: { CELLD_BUCKET: 'gs://fresh/celld' }, + stateDir: join(root, 'state'), + envFile: join(root, 'target.env'), + encryptionKeyFile: join(root, 'key'), + composeFiles: [], + now: Date.now, + log: () => {}, + run: (command, args) => { + if (command === 'docker') return { status: 0, stdout: '', stderr: '' }; + const r = spawnSync( + process.execPath, + [resolve(import.meta.dirname, 'testdata/fake-gcloud.mjs'), ...args], + { + env: { + ...process.env, + FAKE_STATE: join(root, 'fake'), + FAKE_GCS_ROOT: join(root, 'store'), + }, + encoding: 'utf8', + } + ); + return { status: r.status ?? 1, stdout: r.stdout ?? '', stderr: r.stderr ?? '' }; + }, + }; +}); +afterEach(() => { + vi.restoreAllMocks(); + vi.unstubAllEnvs(); + fs.rmSync(root, { recursive: true, force: true }); +}); +it.each(['write', 'file-sync', 'parent-sync'] as const)( + 'retries initial journal %s failure only after reestablishing durability before target writes', + (boundary) => { + const progress = `${context.stateDir}.restore-progress.json`; + let failed = false; + const originalWrite = fs.writeSync, + originalSync = fs.fsyncSync; + vi.spyOn(fs, 'writeSync').mockImplementation((...args: Parameters) => { + if (!failed && boundary === 'write' && fs.existsSync(progress)) { + failed = true; + originalWrite(args[0], Buffer.from('partial')); + throw Error('Injected initial journal write'); + } + return Reflect.apply(originalWrite, fs, args); + }); + vi.spyOn(fs, 'fsyncSync').mockImplementation((fd) => { + if ( + !failed && + fs.existsSync(progress) && + (fs.fstatSync(fd).isDirectory() ? boundary === 'parent-sync' : boundary === 'file-sync') + ) { + failed = true; + throw Error('Injected initial journal sync'); + } + return originalSync(fd); + }); + expect(() => runRestore(context, snapshot)).toThrow(/Injected initial journal/); + expect(failed).toBe(true); + expect(fs.existsSync(context.stateDir)).toBe(false); + expect(fs.existsSync(join(root, 'store/fresh/celld/data/value'))).toBe(false); + vi.restoreAllMocks(); + let fileSynced = false, + parentSynced = false; + vi.spyOn(fs, 'fsyncSync').mockImplementation((fd) => { + if (fs.existsSync(progress)) { + if (fs.fstatSync(fd).isDirectory()) parentSynced = true; + else fileSynced = true; + } + return originalSync(fd); + }); + const originalRun = context.run; + context.run = (command, args, env) => { + if (command === 'gcloud' && args[1] === 'rsync' && !args.at(-2)?.startsWith('gs://')) { + expect(fileSynced).toBe(true); + expect(parentSynced).toBe(true); + } + return originalRun(command, args, env); + }; + runRestore(context, snapshot); + expect(fs.readFileSync(join(root, 'store/fresh/celld/data/value'), 'utf8')).toBe( + 'actual bytes' + ); + } +); +it.each(['link', 'before-unlink-fsync', 'unlink', 'after-unlink-fsync'] as const)( + 'retries safely after actual completion %s boundary failure', + (boundary) => { + const progress = `${context.stateDir}.restore-progress.json`, + complete = `${context.stateDir}.restore-complete.json`; + let failed = false; + const originalLink = fs.linkSync, + originalRm = fs.rmSync, + originalSync = fs.fsyncSync; + vi.spyOn(fs, 'linkSync').mockImplementation((a, b) => { + if (!failed && boundary === 'link' && String(b) === complete) { + failed = true; + throw Error('Injected link failure'); + } + return originalLink(a, b); + }); + vi.spyOn(fs, 'rmSync').mockImplementation((p, o) => { + if (!failed && boundary === 'unlink' && String(p) === progress) { + failed = true; + throw Error('Injected unlink failure'); + } + return originalRm(p, o); + }); + vi.spyOn(fs, 'fsyncSync').mockImplementation((fd) => { + if ( + !failed && + fs.fstatSync(fd).isDirectory() && + fs.existsSync(complete) && + ((boundary === 'before-unlink-fsync' && fs.existsSync(progress)) || + (boundary === 'after-unlink-fsync' && !fs.existsSync(progress))) + ) { + failed = true; + throw Error('Injected parent sync failure'); + } + return originalSync(fd); + }); + expect(() => runRestore(context, snapshot)).toThrow(/Injected/); + expect(failed).toBe(true); + expect(fs.readFileSync(join(root, 'store/fresh/celld/data/value'), 'utf8')).toBe( + 'actual bytes' + ); + expect(fs.existsSync(progress) || fs.existsSync(complete)).toBe(true); + vi.restoreAllMocks(); + runRestore(context, snapshot); + expect(fs.existsSync(progress)).toBe(false); + expect(fs.existsSync(complete)).toBe(true); + expect(fs.readFileSync(join(root, 'store/fresh/celld/data/value'), 'utf8')).toBe( + 'actual bytes' + ); + runRestore(context, snapshot); // a completed retry is idempotent while target output is unchanged + } +); +it('completed ownership never permits changed output, a different target, or a running application', () => { + runRestore(context, snapshot); + fs.writeFileSync(join(root, 'store/fresh/celld/data/value'), 'foreign changed bytes'); + expect(() => runRestore(context, snapshot)).toThrow(/changed or unsafe/); + expect(fs.readFileSync(join(root, 'store/fresh/celld/data/value'), 'utf8')).toBe( + 'foreign changed bytes' + ); + expect(() => + runRestore({ ...context, box: { CELLD_BUCKET: 'gs://other/celld' } }, snapshot) + ).toThrow(/Cannot verify restore retry ownership/); + expect(() => + runRestore( + { + ...context, + run: (cmd, args, env) => + cmd === 'docker' + ? { status: 0, stdout: 'c'.repeat(64), stderr: '' } + : context.run(cmd, args, env), + }, + snapshot + ) + ).toThrow(/already has containers/); +}); + +it.each([0, 7, -1])( + 'recovers actual torn state output of %s bytes only when it matches the authenticated prefix', + (length) => { + const copy = fs.cpSync; + let failed = false; + vi.spyOn(fs, 'cpSync').mockImplementation((source, destination, options) => { + if (!failed && String(destination) === context.stateDir) { + failed = true; + fs.mkdirSync(context.stateDir, { recursive: true, mode: 0o700 }); + const sourceBytes = fs.readFileSync(join(String(source), 'platform-keys.json')); + fs.writeFileSync( + join(context.stateDir, 'platform-keys.json'), + length < 0 ? 'foreign-prefix' : sourceBytes.subarray(0, length), + { mode: 0o600 } + ); + throw Error('Injected partial state copy'); + } + return copy(source, destination, options); + }); + expect(() => runRestore(context, snapshot)).toThrow('Injected partial state copy'); + vi.restoreAllMocks(); + if (length < 0) { + expect(() => runRestore(context, snapshot)).toThrow(/changed or unsafe/); + expect(fs.readFileSync(join(context.stateDir, 'platform-keys.json'), 'utf8')).toBe( + 'foreign-prefix' + ); + } else { + runRestore(context, snapshot); + const keys = JSON.parse( + fs.readFileSync(join(context.stateDir, 'platform-keys.json'), 'utf8') + ); + expect(keys.ENCRYPTION_KEY).toBe('retained'); + expect(keys.SAM_INSTALLATION_ID).not.toBe('a'.repeat(32)); + expect(fs.existsSync(`${context.stateDir}.restore-complete.json`)).toBe(true); + } + } +); diff --git a/scripts/selfhost/restore-progress.ts b/scripts/selfhost/restore-progress.ts index d8762ea370..c85ef0ce29 100644 --- a/scripts/selfhost/restore-progress.ts +++ b/scripts/selfhost/restore-progress.ts @@ -5,6 +5,7 @@ import { constants, fstatSync, fsyncSync, + linkSync, lstatSync, openSync, readdirSync, @@ -36,12 +37,41 @@ function digest(path: string): string { } } +/** A torn state copy may contain only the exact leading bytes of its authenticated source. */ +function exactPrefix(current: string, expected: string): boolean { + const input = openSync(current, constants.O_RDONLY | constants.O_NOFOLLOW); + const source = openSync(expected, constants.O_RDONLY | constants.O_NOFOLLOW); + try { + const actual = fstatSync(input), + original = fstatSync(source); + assertOwned(actual); + if (!actual.isFile() || actual.nlink !== 1 || !original.isFile() || actual.size > original.size) + return false; + const a = Buffer.alloc(64 * 1024), + b = Buffer.alloc(64 * 1024); + let count: number; + while ((count = readSync(input, a, 0, a.length, null)) > 0) { + let offset = 0; + while (offset < count) { + const n = readSync(source, b, offset, count - offset, null); + if (!n) return false; + offset += n; + } + if (!a.subarray(0, count).equals(b.subarray(0, count))) return false; + } + return true; + } finally { + closeSync(input); + closeSync(source); + } +} + function assertOwned(stat: Stats): void { if (process.getuid !== undefined && stat.uid !== process.getuid()) throw new Error('Restore retry contains foreign-owned data'); } /** Existing partial output must be an exact subset of the authenticated snapshot. Never delete it. */ -export function assertRestoreSubset(current: string, expected: string): void { +export function assertRestoreSubset(current: string, expected: string, partialState = false): void { assertOperatorExecution(); const stat = lstatSync(current, { throwIfNoEntry: false }); if (!stat) return; @@ -55,13 +85,14 @@ export function assertRestoreSubset(current: string, expected: string): void { assertOwned(found); const original = lstatSync(source, { throwIfNoEntry: false }); if (!original) throw new Error('Restore retry contains data outside its snapshot'); - if (found.isDirectory() && original.isDirectory()) assertRestoreSubset(path, source); + if (found.isDirectory() && original.isDirectory()) + assertRestoreSubset(path, source, partialState); else if ( !found.isFile() || !original.isFile() || found.nlink !== 1 || original.nlink !== 1 || - digest(path) !== digest(source) + (partialState ? !exactPrefix(path, source) : digest(path) !== digest(source)) ) { throw new Error('Restore retry contains changed or unsafe data'); } @@ -75,8 +106,15 @@ export interface RestoreProgress { } export function restoreProgress(ctx: BoxContext, backup: string): RestoreProgress { assertOperatorExecution(); - const journal = `${resolve(ctx.stateDir)}.restore-progress.json`; - assertBackupOutside(ctx, journal); + const progressPath = `${resolve(ctx.stateDir)}.restore-progress.json`; + const complete = `${resolve(ctx.stateDir)}.restore-complete.json`; + let journal = + lstatSync(progressPath, { throwIfNoEntry: false }) || + !lstatSync(complete, { throwIfNoEntry: false }) + ? progressPath + : complete; + assertBackupOutside(ctx, progressPath); + assertBackupOutside(ctx, complete); const expected = JSON.stringify({ format: 'sam-restore-progress/1', bucket: ctx.box.CELLD_BUCKET, @@ -85,11 +123,11 @@ export function restoreProgress(ctx: BoxContext, backup: string): RestoreProgres snapshot: digest(join(backup, '.sam-backup-manifest')), }); const existing = lstatSync(journal, { throwIfNoEntry: false }); - const validate = (): void => { + const validate = (path = journal): void => { try { - if (lstatSync(journal).isSymbolicLink()) throw new Error('Invalid journal'); - assertPrivateFile(journal); - if (readFileSync(journal, 'utf8') !== expected) throw new Error('Different restore'); + if (lstatSync(path).isSymbolicLink()) throw new Error('Invalid journal'); + assertPrivateFile(path); + if (readFileSync(path, 'utf8') !== expected) throw new Error('Different restore'); } catch { throw new Error( 'Cannot verify restore retry ownership; preserve the partial target for inspection' @@ -97,6 +135,7 @@ export function restoreProgress(ctx: BoxContext, backup: string): RestoreProgres } }; if (existing) validate(); + if (lstatSync(complete, { throwIfNoEntry: false })) validate(complete); let identity = existing; const syncParent = (): void => { const fd = openSync(dirname(journal), 'r'); @@ -106,6 +145,28 @@ export function restoreProgress(ctx: BoxContext, backup: string): RestoreProgres closeSync(fd); } }; + const persist = (path: string): void => { + prepareBackupParent(path); + const fd = openSync(path, 'wx', 0o600); + const created = fstatSync(fd); + try { + const data = Buffer.from(expected); + let offset = 0; + while (offset < data.length) { + const written = writeSync(fd, data, offset, data.length - offset); + if (written === 0) throw new Error('Cannot persist restore retry ownership'); + offset += written; + } + fsyncSync(fd); + } catch (error) { + // No target writes precede this initial receipt. Remove only this attempt's fresh inode. + const current = lstatSync(path, { throwIfNoEntry: false }); + if (current?.dev === created.dev && current.ino === created.ino) rmSync(path); + throw error; + } finally { + closeSync(fd); + } + }; return { resume: Boolean(existing), begin() { @@ -114,22 +175,20 @@ export function restoreProgress(ctx: BoxContext, backup: string): RestoreProgres const current = lstatSync(journal); if (current.dev !== identity?.dev || current.ino !== identity?.ino) throw new Error('Restore retry ownership changed'); - return; - } - prepareBackupParent(journal); - const fd = openSync(journal, 'wx', 0o600); - try { - const data = Buffer.from(expected); - let offset = 0; - while (offset < data.length) { - const written = writeSync(fd, data, offset, data.length - offset); - if (written === 0) throw new Error('Cannot persist restore retry ownership'); - offset += written; + const fd = openSync(journal, constants.O_RDONLY | constants.O_NOFOLLOW); + try { + const opened = fstatSync(fd); + if (opened.dev !== identity?.dev || opened.ino !== identity?.ino) + throw new Error('Restore retry ownership changed'); + fsyncSync(fd); + } finally { + closeSync(fd); } - fsyncSync(fd); - } finally { - closeSync(fd); + syncParent(); + validate(); + return; } + persist(journal); identity = lstatSync(journal); syncParent(); validate(); @@ -139,8 +198,20 @@ export function restoreProgress(ctx: BoxContext, backup: string): RestoreProgres const current = lstatSync(journal); if (current.dev !== identity?.dev || current.ino !== identity?.ino) throw new Error('Restore retry ownership changed'); - rmSync(journal); + if (!lstatSync(complete, { throwIfNoEntry: false })) linkSync(journal, complete); + validate(complete); + // Make completion durable before unlinking progress: every error leaves a retry receipt. syncParent(); + if (journal === progressPath) { + validate(); + const live = lstatSync(journal); + if (live.dev !== identity?.dev || live.ino !== identity?.ino) + throw new Error('Restore retry ownership changed'); + rmSync(journal); + journal = complete; + identity = lstatSync(complete); + syncParent(); + } }, }; } diff --git a/scripts/selfhost/restore-runtime.test.ts b/scripts/selfhost/restore-runtime.test.ts new file mode 100644 index 0000000000..dfbc450b59 --- /dev/null +++ b/scripts/selfhost/restore-runtime.test.ts @@ -0,0 +1,106 @@ +/** Discriminating store-only proof: no application, foreign config, image or mount may be admitted. */ +import { dirname, resolve } from 'node:path'; + +import { afterEach, beforeEach, expect, it, vi } from 'vitest'; + +import { type BoxContext, OBJECTSTORE_IMAGE } from './backup-lib'; +import { expectedComposeProjectFor } from './install-record'; +import { assertRestoreRuntime } from './restore-runtime'; +const COMPOSE = resolve(import.meta.dirname, '../../deploy/selfhost/docker-compose.yml'), + ID = 'a'.repeat(32), + container = 'c'.repeat(64); +let context: BoxContext, + project: string, + item: Record, + volume: Record; +beforeEach(() => { + for (const n of Object.keys(process.env)) + if (n === 'CI' || n === 'GITHUB_ACTIONS' || n.startsWith('RUNNER_')) vi.stubEnv(n, undefined); + context = { + box: { + SAM_DOMAIN: 'restore.example.com', + COMPOSE_PROFILES: 'local-store', + CELLD_BUCKET: 's3://restore/celld', + S3_ENDPOINT: 'http://127.0.0.1:9000', + }, + stateDir: resolve('.tmp/runtime-not-created/state'), + envFile: resolve('.tmp/runtime-not-created/env'), + composeFiles: [COMPOSE], + now: Date.now, + log: () => {}, + run: (_c, args) => ({ + status: 0, + stderr: '', + stdout: args[0] === 'ps' ? container : JSON.stringify(args[0] === 'volume' ? volume : item), + }), + }; + project = expectedComposeProjectFor(context.box, context.stateDir, ID); + context.box = { ...context.box, COMPOSE_PROJECT_NAME: project }; + item = { + id: container, + labels: { + 'com.docker.compose.project': project, + 'com.docker.compose.service': 'objectstore', + 'com.docker.compose.project.config_files': COMPOSE, + 'com.docker.compose.project.working_dir': dirname(COMPOSE), + }, + image: OBJECTSTORE_IMAGE, + command: [ + 'server', + '/data', + '--address', + '127.0.0.1:9000', + '--console-address', + '127.0.0.1:9001', + ], + network: 'host', + mounts: [ + { Type: 'volume', Destination: '/data', Name: `${project}_objectstore-data`, RW: true }, + ], + state: { Running: true, Health: { Status: 'healthy' } }, + }; + volume = { + name: `${project}_objectstore-data`, + labels: { + 'com.docker.compose.project': project, + 'com.docker.compose.volume': 'objectstore-data', + }, + }; +}); +afterEach(() => vi.unstubAllEnvs()); +it('permits only the verified pinned bundled store in its canonical target project', () => + expect(() => assertRestoreRuntime(context, ID)).not.toThrow()); +it.each([ + 'celld', + 'foreign-project', + 'foreign-config', + 'foreign-working-dir', + 'foreign-image', + 'foreign-network', + 'bind-data', + 'foreign-volume', + 'duplicate-mount', + 'unhealthy', + 'profile', + 'overlay', + 'foreign-volume-label', +] as const)('refuses %s', (defect) => { + const labels = item.labels as Record, + mounts = item.mounts as Array>; + if (defect === 'celld') labels['com.docker.compose.service'] = 'celld'; + else if (defect === 'foreign-project') labels['com.docker.compose.project'] = 'foreign'; + else if (defect === 'foreign-config') + labels['com.docker.compose.project.config_files'] = '/foreign/compose.yml'; + else if (defect === 'foreign-working-dir') + labels['com.docker.compose.project.working_dir'] = '/foreign'; + else if (defect === 'foreign-image') item.image = 'foreign:latest'; + else if (defect === 'foreign-network') item.network = 'bridge'; + else if (defect === 'bind-data') mounts[0] = { ...mounts[0], Type: 'bind' }; + else if (defect === 'foreign-volume') mounts[0] = { ...mounts[0], Name: 'foreign-data' }; + else if (defect === 'duplicate-mount') mounts.push({ ...mounts[0] }); + else if (defect === 'unhealthy') item.state = { Running: true, Health: { Status: 'starting' } }; + else if (defect === 'profile') context.box = { ...context.box, COMPOSE_PROFILES: 'tunnel' }; + else if (defect === 'overlay') context.composeFiles.push('/foreign/overlay.yml'); + else (volume.labels as Record)['com.docker.compose.project'] = 'foreign'; + expect(() => assertRestoreRuntime(context, ID)).toThrow(/already has containers/); +}); diff --git a/scripts/selfhost/restore-runtime.ts b/scripts/selfhost/restore-runtime.ts new file mode 100644 index 0000000000..ba43141e46 --- /dev/null +++ b/scripts/selfhost/restore-runtime.ts @@ -0,0 +1,161 @@ +/** Only the canonical install's bundled store may exist before a fresh restore. */ +import { dirname, resolve } from 'node:path'; + +import { type BoxContext, check, OBJECTSTORE_IMAGE } from './backup-lib'; +import { expectedComposeProjectFor, uninitializedComposeProjectFor } from './install-record'; +import { assertOperatorExecution } from './operator-only'; + +const COMPOSE = resolve(import.meta.dirname, '../../deploy/selfhost/docker-compose.yml'); +const fail = (): never => { + throw new Error( + 'Restore target already has containers or unverified store resources; use a fresh installation' + ); +}; +interface Metadata { + id?: string; + name?: string; + labels?: Record; + image?: string; + network?: string; + command?: string[]; + entrypoint?: string[]; + mounts?: Array<{ + Type?: string; + Destination?: string; + Name?: string; + RW?: boolean; + Source?: string; + }>; + state?: { Running?: boolean; Health?: { Status?: string }; Status?: string; ExitCode?: number }; +} +function metadata(ctx: BoxContext, args: string[]): Metadata { + try { + const value: unknown = JSON.parse( + check(ctx.run('docker', args), 'inspect restore store ownership').stdout + ); + if (!value || typeof value !== 'object' || Array.isArray(value)) return fail(); + return value as Metadata; + } catch { + return fail(); + } +} +function assertStore(ctx: BoxContext, project: string, ids: string[]): void { + if ( + !ctx.box.COMPOSE_PROFILES?.split(',').includes('local-store') || + ctx.composeFiles.length !== 1 || + resolve(ctx.composeFiles[0] ?? '') !== COMPOSE || + !ctx.box.CELLD_BUCKET?.startsWith('s3://') || + ctx.box.S3_ENDPOINT !== `http://127.0.0.1:${ctx.box.OBJECTSTORE_PORT || '9000'}` + ) + fail(); + const seen = new Set(); + for (const id of ids) { + const item = metadata(ctx, [ + 'container', + 'inspect', + '--format', + '{"id":{{json .Id}},"labels":{{json .Config.Labels}},"image":{{json .Config.Image}},"command":{{json .Config.Cmd}},"entrypoint":{{json .Config.Entrypoint}},"network":{{json .HostConfig.NetworkMode}},"mounts":{{json .Mounts}},"state":{"Running":{{json .State.Running}},"Status":{{json .State.Status}},"ExitCode":{{json .State.ExitCode}},"Health":{"Status":{{with index .State "Health"}}{{json .Status}}{{else}}null{{end}}}}}', + id, + ]); + const labels = item.labels, + role = labels?.['com.docker.compose.service']; + if ( + item.id !== id || + item.image !== OBJECTSTORE_IMAGE || + item.network !== 'host' || + !role || + !['objectstore', 'objectstore-init'].includes(role) || + seen.has(role) || + labels?.['com.docker.compose.project'] !== project || + labels?.['com.docker.compose.project.config_files'] !== COMPOSE || + labels?.['com.docker.compose.project.working_dir'] !== dirname(COMPOSE) || + !Array.isArray(item.mounts) || + item.mounts.length !== (role === 'objectstore' ? 1 : 2) + ) + fail(); + seen.add(role ?? ''); + const mount = item.mounts?.find( + (entry) => entry.Destination === (role === 'objectstore' ? '/data' : '/init/init.sh') + ); + if (!mount) return fail(); + if (role === 'objectstore') { + if ( + JSON.stringify(item.command) !== + JSON.stringify([ + 'server', + '/data', + '--address', + `127.0.0.1:${ctx.box.OBJECTSTORE_PORT || '9000'}`, + '--console-address', + `127.0.0.1:${ctx.box.OBJECTSTORE_CONSOLE_PORT || '9001'}`, + ]) || + !item.state?.Running || + item.state.Health?.Status !== 'healthy' || + mount.Type !== 'volume' || + mount.Destination !== '/data' || + mount.Name !== `${project}_objectstore-data` || + mount.RW !== true + ) + fail(); + const volume = metadata(ctx, [ + 'volume', + 'inspect', + '--format', + '{"name":{{json .Name}},"labels":{{json .Labels}}}', + mount.Name ?? '', + ]); + if ( + volume.name !== mount.Name || + volume.labels?.['com.docker.compose.project'] !== project || + volume.labels?.['com.docker.compose.volume'] !== 'objectstore-data' + ) + fail(); + } else if ( + JSON.stringify(item.entrypoint) !== JSON.stringify(['sh', '/init/init.sh']) || + !item.mounts?.some( + (entry) => + entry.Destination === '/data' && + entry.Type === 'volume' && + entry.RW === true && + /^[a-f0-9]{64}$/.test(entry.Name ?? '') + ) || + item.state?.Status !== 'exited' || + item.state.ExitCode !== 0 || + mount.Type !== 'bind' || + mount.Destination !== '/init/init.sh' || + mount.Source !== resolve(dirname(COMPOSE), 'objectstore/init.sh') || + mount.RW !== false + ) + fail(); + } + if (!seen.has('objectstore')) fail(); +} +export function assertRestoreRuntime(ctx: BoxContext, identity: string): void { + assertOperatorExecution(); + const final = expectedComposeProjectFor(ctx.box, ctx.stateDir, identity); + const projects = new Set([ + ctx.box.COMPOSE_PROJECT_NAME?.trim() || uninitializedComposeProjectFor(ctx.box, ctx.stateDir), + final, + ]); + for (const project of projects) { + const result = check( + ctx.run('docker', [ + 'ps', + '-aq', + '--no-trunc', + '--filter', + `label=com.docker.compose.project=${project}`, + ]), + 'check empty restore runtime' + ); + const ids = result.stdout.trim().split(/\s+/).filter(Boolean); + if (!ids.length) continue; + if ( + project !== final || + new Set(ids).size !== ids.length || + ids.some((id) => !/^[a-f0-9]{64}$/.test(id)) + ) + fail(); + assertStore(ctx, project, ids); + } +} diff --git a/scripts/selfhost/restore.ts b/scripts/selfhost/restore.ts index 4bb5d8b33b..5b3ab4c382 100644 --- a/scripts/selfhost/restore.ts +++ b/scripts/selfhost/restore.ts @@ -15,6 +15,7 @@ import { expectedComposeProjectFor } from './install-record'; const { values } = parseArgs({ options: { from: { type: 'string' }, + 'print-project': { type: 'boolean', default: false }, 'encryption-key-file': { type: 'string' }, 'box-env': { type: 'string' }, 'state-dir': { type: 'string' }, @@ -24,6 +25,10 @@ if (!values.from) throw new Error('--from is required'); const from = resolve(values.from); const envFile = resolve(values['box-env'] ?? join(SELFHOST_DIR, '.env')); const ctx = loadBox(envFile, values['state-dir'], values['encryption-key-file']); +if (values['print-project']) { + process.stdout.write(`${runRestore(ctx, from, 'project')}\n`); + process.exit(0); +} const manifest = runRestore(ctx, from); log(`restored backup of ${manifest.createdAt} (SAM ${manifest.samCommit ?? 'unknown commit'})`); log('Recover with the SAME SAM checkout the backup was taken with:'); diff --git a/scripts/selfhost/rollback-cache-transition.test.ts b/scripts/selfhost/rollback-cache-transition.test.ts new file mode 100644 index 0000000000..0ff8ad9fd4 --- /dev/null +++ b/scripts/selfhost/rollback-cache-transition.test.ts @@ -0,0 +1,155 @@ +/** Authorized creation intent never substitutes a name for live immutable ownership metadata. */ +import { dirname, resolve } from 'node:path'; + +import { afterEach, beforeEach, expect, it, type Mock, vi } from 'vitest'; + +import type { BoxContext } from './backup-lib'; +import { type CacheStartProof, recoverCacheStart } from './rollback-cache-transition'; + +vi.mock('./upgrade-preflight', () => ({ assertRollbackReady: vi.fn() })); +const original = 'a'.repeat(64); +const replacement = 'b'.repeat(64); +let proof: CacheStartProof; +let ctx: BoxContext; +let selected: string; +let volume: string; +let metadata: { Id: string; Created: string; Config: { Labels: Record } }; +let volumeCreated: string; +let inspectVolume: Mock<(ctx: BoxContext) => { name: string; createdAt: string }>; +let inspectCache: Mock<(ctx: BoxContext) => { name: string; createdAt: string; container: string }>; +beforeEach(() => { + for (const name of Object.keys(process.env)) { + if (name === 'CI' || name === 'GITHUB_ACTIONS' || name.startsWith('RUNNER_')) + vi.stubEnv(name, undefined); + } + const now = Date.now(); + proof = { + name: 'owned_celld-data', + createdAt: new Date(now - 60_000).toISOString(), + container: original, + startingAt: new Date(now - 1000).toISOString(), + }; + selected = replacement; + volume = proof.name; + volumeCreated = new Date(now - 500).toISOString(); + ctx = { + box: { COMPOSE_PROJECT_NAME: 'owned' }, + stateDir: '/fixture/state', + envFile: '/fixture/env', + composeFiles: [resolve('deploy/selfhost/docker-compose.yml')], + log: vi.fn(), + now: () => now, + run: (_command, args) => ({ + status: 0, + stderr: '', + stdout: args.includes('ps') + ? selected + : args.includes('ls') + ? volume + : JSON.stringify(metadata), + }), + }; + metadata = { + Id: replacement, + Created: volumeCreated, + Config: { + Labels: { + 'com.docker.compose.project': 'owned', + 'com.docker.compose.service': 'celld', + 'com.docker.compose.project.config_files': ctx.composeFiles.join(','), + 'com.docker.compose.project.working_dir': dirname(ctx.composeFiles[0]!), + }, + }, + }; + inspectVolume = vi.fn(() => ({ name: proof.name, createdAt: volumeCreated })); + inspectCache = vi.fn(() => ({ + name: proof.name, + createdAt: volumeCreated, + container: replacement, + })); +}); +afterEach(() => vi.unstubAllEnvs()); +const recover = (requireContainer = false) => + recoverCacheStart(ctx, proof, inspectVolume, inspectCache, requireContainer); + +it('binds a newly created canonical container and volume only after exact scope and mount proof', () => { + expect(recover()).toEqual({ name: proof.name, createdAt: volumeCreated, container: replacement }); + expect(inspectCache).toHaveBeenCalledOnce(); +}); +it.each([undefined, '', 'not-a-time', new Date(Date.now() + 60_000).toISOString()])( + 'refuses invalid creation intent %s before runner calls', + (startingAt) => { + proof.startingAt = startingAt; + const run = vi.fn(ctx.run); + ctx.run = run; + expect(recover).toThrow(/Missing authorized/); + expect(run).not.toHaveBeenCalled(); + } +); +it.each(['project', 'service', 'project.config_files', 'project.working_dir'])( + 'refuses a replacement with foreign Compose %s', + (field) => { + metadata.Config.Labels[`com.docker.compose.${field}`] = 'foreign'; + expect(recover).toThrow(/ownership proof/); + expect(inspectCache).not.toHaveBeenCalled(); + } +); +it.each([ + 'ambiguous', + 'old', + 'short', + 'wrong-volume', + 'no-volume', + 'old-container-time', + 'old-volume-time', + 'future-time', + 'wrong-inspect-id', + 'malformed', +])('refuses %s without adopting the replacement', (defect) => { + if (defect === 'ambiguous') selected += '\n' + 'd'.repeat(64); + if (defect === 'old') selected = original; + if (defect === 'short') selected = 'short'; + if (defect === 'wrong-volume') volume = 'foreign'; + if (defect === 'no-volume') volume = ''; + if (defect === 'old-container-time') metadata.Created = proof.createdAt; + if (defect === 'old-volume-time') volumeCreated = proof.createdAt; + if (defect === 'future-time') metadata.Created = new Date(Date.now() + 60_000).toISOString(); + if (defect === 'wrong-inspect-id') metadata.Id = original; + if (defect === 'malformed') ctx.run = () => ({ status: 0, stdout: 'not-json', stderr: '' }); + expect(recover).toThrow(); + expect(inspectCache).not.toHaveBeenCalled(); +}); +it('refuses ambiguous mount proof or a cache replaced during observation', () => { + inspectCache.mockImplementationOnce(() => { + throw new Error('ambiguous cache mount'); + }); + expect(recover).toThrow(/ambiguous cache mount/); + inspectCache.mockImplementationOnce(() => ({ + name: proof.name, + createdAt: proof.createdAt, + container: replacement, + })); + expect(recover).toThrow(/changed during/); +}); +it('can retry an intent interrupted before resource creation, but cannot declare startup successful', () => { + selected = ''; + volume = ''; + expect(recover()).toEqual({ name: proof.name, createdAt: proof.createdAt, container: original }); + expect(() => recover(true)).toThrow(/no celld container/); +}); +it('handles a volume-only partial creation using exact scope/time proof, without inventing a container', () => { + selected = ''; + expect(recover()).toEqual({ name: proof.name, createdAt: volumeCreated, container: original }); + expect(inspectCache).not.toHaveBeenCalled(); + expect(() => recover(true)).toThrow(/no celld container/); +}); +it.each(['CI', 'GITHUB_ACTIONS', 'RUNNER_TEMP'])( + 'refuses %s before inspecting anything', + (signal) => { + vi.stubEnv(signal, ''); + const run = vi.fn(ctx.run); + ctx.run = run; + expect(recover).toThrow(/forbidden in CI/); + expect(run).not.toHaveBeenCalled(); + } +); diff --git a/scripts/selfhost/rollback-cache-transition.ts b/scripts/selfhost/rollback-cache-transition.ts new file mode 100644 index 0000000000..4bc1337265 --- /dev/null +++ b/scripts/selfhost/rollback-cache-transition.ts @@ -0,0 +1,107 @@ +/** Adopt only resources created by an explicitly journaled recovery Compose start. */ +import { dirname, resolve } from 'node:path'; + +import { type BoxContext, check, composeArgs, composeRunEnv } from './backup-lib'; +import type { RollbackCacheProof } from './backup-recovery'; +import { composeProjectFor } from './install-record'; +import { assertOperatorExecution } from './operator-only'; +import { assertRollbackReady } from './upgrade-preflight'; + +export interface CacheStartProof extends RollbackCacheProof { + startingAt?: string; +} + +function createdAfter(value: unknown, start: string): void { + if ( + typeof value !== 'string' || + !Number.isFinite(Date.parse(value)) || + Date.parse(value) < Date.parse(start) || + Date.parse(value) > Date.now() + ) + throw new Error('Replacement cache predates its authorized recovery start'); +} + +/** Docker volume creation time has second precision; intent rounds down on that same clock. */ +export function cacheStartTime(): string { + return new Date(Math.floor(Date.now() / 1000) * 1000).toISOString(); +} + +function proveContainer(ctx: BoxContext, id: string, start: string): void { + let value; + try { + value = JSON.parse( + check( + ctx.run('docker', [ + 'inspect', + '--format', + '{"Id":{{json .Id}},"Created":{{json .Created}},"Config":{"Labels":{{json .Config.Labels}}}}', + id, + ]), + 'inspect replacement celld identity' + ).stdout + ); + } catch { + throw new Error('Cannot verify replacement celld identity'); + } + const labels = value?.Config?.Labels; + if ( + value?.Id !== id || + labels?.['com.docker.compose.project'] !== composeProjectFor(ctx.box, ctx.stateDir) || + labels?.['com.docker.compose.service'] !== 'celld' || + labels?.['com.docker.compose.project.config_files'] !== + ctx.composeFiles.map((p) => resolve(p)).join(',') || + labels?.['com.docker.compose.project.working_dir'] !== + dirname(resolve(ctx.composeFiles[0] ?? '')) + ) + throw new Error('Replacement celld has no exact Compose ownership proof'); + createdAfter(value.Created, start); +} + +export function recoverCacheStart( + ctx: BoxContext, + pending: CacheStartProof, + inspectVolume: (ctx: BoxContext) => { name: string; createdAt: string }, + inspectCache: (ctx: BoxContext) => RollbackCacheProof, + requireContainer = false +): RollbackCacheProof { + assertOperatorExecution(); + assertRollbackReady(ctx); + const start = pending.startingAt; + if (!start || !Number.isFinite(Date.parse(start)) || Date.parse(start) > Date.now()) + throw new Error('Missing authorized recovery start'); + const selected = check( + ctx.run( + 'docker', + composeArgs(ctx, ['ps', '--all', '--no-trunc', '-q', 'celld']), + composeRunEnv(ctx) + ), + 'inspect starting celld' + ).stdout.trim(); + const volumes = check( + ctx.run('docker', [ + 'volume', + 'ls', + '--filter', + `name=^${pending.name}$`, + '--format', + '{{.Name}}', + ]), + 'inspect starting cache' + ).stdout.trim(); + if (requireContainer && !selected) throw new Error('Recovery start has no celld container'); + if (!selected && !volumes) + return { name: pending.name, createdAt: pending.createdAt, container: pending.container }; + if ( + volumes !== pending.name || + (selected && (!/^[a-f0-9]{64}$/.test(selected) || selected === pending.container)) + ) + throw new Error('Ambiguous replacement cache identity'); + const volume = inspectVolume(ctx); + createdAfter(volume.createdAt, start); + if (!selected) return { ...volume, container: pending.container }; + proveContainer(ctx, selected, start); + const proof = inspectCache(ctx); + if (proof.container !== selected || proof.createdAt !== volume.createdAt) + throw new Error('Replacement cache changed during ownership proof'); + return proof; +} diff --git a/scripts/selfhost/teardown-box.ts b/scripts/selfhost/teardown-box.ts index e1036e59b6..0708b36c86 100644 --- a/scripts/selfhost/teardown-box.ts +++ b/scripts/selfhost/teardown-box.ts @@ -3,15 +3,17 @@ * the box is Docker Compose and files; the bucket goes through bucket-objects.ts, which already * speaks gs:// and s3://. Cloud resources are teardown-gcp.ts's (and any later adapter's). */ -import { existsSync, readdirSync, readFileSync, rmSync } from 'node:fs'; +import { existsSync, lstatSync, readdirSync, readFileSync, realpathSync, rmSync } from 'node:fs'; import { isAbsolute, join, resolve } from 'node:path'; import { type CreatedResource, readRecord } from '../../deploy/selfhost/created-resources.mjs'; import { type BoxContext, composeArgs, MANIFEST_NAME, parseBucketUrl } from './backup-lib'; import { assertBackupOwnership } from './backup-ownership'; -import { composeProjectFor, expectedComposeProjectFor, usesBundledStore } from './install-record'; +import { usesBundledStore } from './install-record'; import { readComposeInventory, removeContainers, stopContainers } from './teardown-compose'; +import { expectedTeardownProject, selectedTeardownProject } from './teardown-identity'; import { both, type Item, type Mode, STEPS } from './teardown-model'; +import { updateRemovalProof } from './teardown-record'; import { isProtectedDir, stateItems } from './teardown-state-dir'; export interface TeardownOptions { @@ -43,11 +45,9 @@ export function recorded(ctx: TeardownContext, kind: string, name?: string) { function composeItems(ctx: TeardownContext): { items: Item[]; owned: boolean } { const items: Item[] = []; - const projectName = composeProjectFor(ctx.box, ctx.stateDir); + const projectName = selectedTeardownProject(ctx); const project = recorded(ctx, 'compose-project', projectName); - const owned = - project?.action === 'created' && - projectName === expectedComposeProjectFor(ctx.box, ctx.stateDir); + const owned = project?.action === 'created' && projectName === expectedTeardownProject(ctx); const composeGone = project?.removedAt ?? (existsSync(ctx.envFile) ? undefined : 'no .env left'); const composeCmd = `docker ${composeArgs(ctx, []).join(' ')}`; const everything = ctx.mode === 'remove-everything'; @@ -174,14 +174,12 @@ export function boxItems(ctx: TeardownContext): Item[] { } /** A backup runBackup wrote: an absolute, unprotected directory with a version-1 manifest. */ -function isBackupDir(path: string, ctx: TeardownContext): boolean { - if (!isAbsolute(path) || isProtectedDir(path, ctx.selfhostDir)) return false; - if (resolve(path) === resolve(ctx.stateDir)) return false; - try { - return existsSync(join(path, '.sam-backup-manifest')); - } catch { - return false; - } +function safeBackupPath(path: string, ctx: TeardownContext): boolean { + return ( + isAbsolute(path) && + !isProtectedDir(path, ctx.selfhostDir) && + resolve(path) !== resolve(ctx.stateDir) + ); } function endpointHost(endpoint: string | undefined): string { @@ -208,18 +206,43 @@ function backupPaths(ctx: TeardownContext): Map r.cloud === 'box' && r.kind === 'backup' && r.name === path ); - if (!isBackupDir(path, ctx) || live?.attributes?.identity !== entry?.attributes?.identity) + if ( + !safeBackupPath(path, ctx) || + live?.attributes?.identity !== entry?.attributes?.identity + ) throw new Error('Refused: backup ownership changed after inventory'); - assertBackupOwnership(path, live); + assertBackupRemoval(path, live); + updateRemovalProof(ctx.recordFile, 'backup', path, { + removalAuthorized: live?.attributes?.identity ?? '', + }); + assertBackupRemoval( + path, + readRecord(ctx.recordFile).resources.find( + (r) => r.cloud === 'box' && r.kind === 'backup' && r.name === path + ) + ); rmSync(path, { recursive: true, force: true }); + if (lstatSync(path, { throwIfNoEntry: false })) + throw new Error('Backup removal incomplete'); }, record: { cloud: 'box', kind: 'backup', name: path, createdBy: 'backup' }, }); @@ -276,13 +313,8 @@ export function bucketItems(ctx: TeardownContext): Item[] { if (!url) return []; const entry = recorded(ctx, 'bucket', url); const contents = recorded(ctx, 'bucket-contents', url); - const project = recorded( - ctx, - 'compose-project', - expectedComposeProjectFor(ctx.box, ctx.stateDir) - ); - const owned = - project?.action === 'created' && composeProjectFor(ctx.box, ctx.stateDir) === project.name; + const project = recorded(ctx, 'compose-project', expectedTeardownProject(ctx)); + const owned = project?.action === 'created' && selectedTeardownProject(ctx) === project.name; if (usesBundledStore(ctx.box)) { return [ { diff --git a/scripts/selfhost/teardown-compose-progress.ts b/scripts/selfhost/teardown-compose-progress.ts new file mode 100644 index 0000000000..8ba249d633 --- /dev/null +++ b/scripts/selfhost/teardown-compose-progress.ts @@ -0,0 +1,86 @@ +/** Persist exact public resource identities before stopping a disposable installation. */ +import { readRecord } from '../../deploy/selfhost/created-resources.mjs'; +import type { TeardownContext } from './teardown-box'; +import type { ComposeInventory } from './teardown-compose'; +import { expectedTeardownProject } from './teardown-identity'; +import { updateRemovalProof } from './teardown-record'; + +function scope(ctx: TeardownContext) { + return { + installation: ctx.installationId, + domain: ctx.domain, + state: ctx.stateDir, + environment: ctx.envFile, + files: ctx.composeFiles, + }; +} +function identities(inventory: ComposeInventory) { + return { + containers: inventory.containers.map((c) => c.id), + volumes: inventory.volumes.map((v) => ({ name: v.name, createdAt: v.createdAt })), + }; +} +function progress( + ctx: TeardownContext +): { containers: string[]; volumes: { name: string; createdAt: string }[] } | null { + const project = expectedTeardownProject(ctx); + const record = readRecord(ctx.recordFile).resources.find( + (r) => r.cloud === 'box' && r.kind === 'compose-project' && r.name === project + ); + const text = record?.attributes?.teardownInventory; + if (!text) return null; + try { + const parsed = JSON.parse(text); + if ( + !parsed || + typeof parsed !== 'object' || + JSON.stringify(parsed.scope) !== JSON.stringify(scope(ctx)) || + !Array.isArray(parsed.containers) || + parsed.containers.some( + (id: unknown) => typeof id !== 'string' || !/^[a-f0-9]{64}$/.test(id) + ) || + new Set(parsed.containers).size !== parsed.containers.length || + !Array.isArray(parsed.volumes) || + parsed.volumes.some( + (v: { name?: unknown; createdAt?: unknown }) => + !v || + typeof v.name !== 'string' || + !v.name.startsWith(`${project}_`) || + typeof v.createdAt !== 'string' || + !v.createdAt + ) || + new Set(parsed.volumes.map((v: { name: string }) => v.name)).size !== parsed.volumes.length + ) + throw new Error('Invalid pending inventory'); + return parsed; + } catch { + throw new Error('Refused: unreadable or foreign pending Docker removal proof'); + } +} +export function assertPendingComposeInventory( + ctx: TeardownContext, + inventory: ComposeInventory +): void { + const pending = progress(ctx); + if (!pending) return; + const current = identities(inventory); + if ( + current.containers.some((id) => !pending.containers.includes(id)) || + current.volumes.some( + (v) => !pending.volumes.some((old) => old.name === v.name && old.createdAt === v.createdAt) + ) + ) + throw new Error('Refused: replacement Docker resource appeared during interrupted teardown'); +} +export function authorizeComposeRemoval(ctx: TeardownContext, inventory: ComposeInventory): void { + assertPendingComposeInventory(ctx, inventory); + if (progress(ctx)) return; + updateRemovalProof(ctx.recordFile, 'compose-project', expectedTeardownProject(ctx), { + teardownInventory: JSON.stringify({ scope: scope(ctx), ...identities(inventory) }), + }); +} +export function finishKeepDataRemoval(ctx: TeardownContext): void { + updateRemovalProof(ctx.recordFile, 'compose-project', expectedTeardownProject(ctx), { + teardownInventory: '', + }); +} diff --git a/scripts/selfhost/teardown-compose-retry.test.ts b/scripts/selfhost/teardown-compose-retry.test.ts new file mode 100644 index 0000000000..397ea64500 --- /dev/null +++ b/scripts/selfhost/teardown-compose-retry.test.ts @@ -0,0 +1,149 @@ +/** Real adapter retry boundaries keep the first exact Docker identities across invocations. */ +import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'; +import { dirname, join, resolve } from 'node:path'; + +import { afterEach, beforeEach, expect, it, vi } from 'vitest'; + +import { readRecord } from '../../deploy/selfhost/created-resources.mjs'; +import { expectedComposeProjectFor, recordInstall, recordPath } from './install-record'; +import { boxItems, type TeardownContext } from './teardown-box'; +import { execute } from './teardown-model'; +let root: string, ctx: TeardownContext, project: string; +let containers: string[], + volumes: { name: string; createdAt: string }[], + calls: string[][], + failure: string; +const id = 'd'.repeat(64), + second = 'e'.repeat(64); +beforeEach(() => { + for (const name of Object.keys(process.env)) + if (name === 'CI' || name === 'GITHUB_ACTIONS' || name.startsWith('RUNNER_')) + vi.stubEnv(name, undefined); + mkdirSync(resolve('.tmp'), { recursive: true }); + root = mkdtempSync(resolve('.tmp/teardown-compose-retry-')); + const state = join(root, 'state'); + mkdirSync(state); + const envFile = join(root, '.env'); + writeFileSync(envFile, '', { mode: 0o600 }); + writeFileSync( + join(state, 'platform-keys.json'), + JSON.stringify({ SAM_INSTALLATION_ID: 'a'.repeat(32) }), + { mode: 0o600 } + ); + const box = { SAM_DOMAIN: 'docker.example.com' }; + recordInstall(state, envFile, box, 'a'.repeat(32)); + project = expectedComposeProjectFor(box, state); + const composeFiles = [join(root, 'compose.yml')]; + containers = [id, second]; + volumes = [{ name: `${project}_cache`, createdAt: '2026-01-01T00:00:00Z' }]; + calls = []; + failure = ''; + ctx = { + box, + stateDir: state, + envFile, + composeFiles, + domain: box.SAM_DOMAIN, + installationId: 'a'.repeat(32), + now: Date.now, + log: () => undefined, + recordFile: recordPath(state), + record: readRecord(recordPath(state)).resources, + selfhostDir: join(root, 'repo/deploy/selfhost'), + mode: 'remove-everything', + options: { deleteBackups: false, destroyKey: false, adoptDiscovered: false, gcpProjects: [] }, + run: (_command, args) => { + calls.push(args); + const ok = (stdout = '') => ({ status: 0, stdout, stderr: '' }); + if (args[0] === 'container' && args[1] === 'ls') return ok(containers.join('\n')); + if (args[0] === 'volume' && args[1] === 'ls') + return ok(volumes.map((v) => v.name).join('\n')); + if (args[1] === 'inspect') { + if (args[0] === 'container') + return ok( + JSON.stringify({ + id: args.at(-1), + labels: { + 'com.docker.compose.project': project, + 'com.docker.compose.service': 'celld', + 'com.docker.compose.project.working_dir': dirname(composeFiles[0]!), + 'com.docker.compose.project.config_files': composeFiles.join(','), + }, + }) + ); + return ok( + JSON.stringify({ + ...volumes.find((v) => v.name === args.at(-1)), + labels: { + 'com.docker.compose.project': project, + 'com.docker.compose.volume': 'cache', + }, + }) + ); + } + if (args[0] === 'container' && args[1] === 'rm') { + containers = containers.filter((value) => value !== args[3]); + if (failure === 'container') { + failure = ''; + return { status: 1, stdout: '', stderr: 'injected partial removal' }; + } + containers = []; + } + if (args[0] === 'volume' && args[1] === 'rm') { + if (failure === 'volume') { + failure = ''; + return { status: 1, stdout: '', stderr: 'injected volume failure' }; + } + volumes = volumes.filter((v) => v.name !== args[2]); + } + return ok(); + }, + }; +}); +afterEach(() => { + vi.unstubAllEnvs(); + rmSync(root, { recursive: true, force: true }); +}); +function run(mode: 'keep-data' | 'remove-everything' = 'remove-everything') { + const fresh = { ...ctx, mode, record: readRecord(ctx.recordFile).resources }; + return execute( + boxItems(fresh).filter( + (item) => + ['box:stop', 'box:containers'].includes(item.id) || item.id.startsWith('box:volume:') + ), + mode, + ctx.recordFile + ); +} +it.each(['container', 'volume'])( + 'retries exact surviving resources after partial %s failure', + (fault) => { + failure = fault; + expect(run().some((o) => o.status === 'failed')).toBe(true); + expect(run().every((o) => ['removed', 'already removed'].includes(o.status))).toBe(true); + expect(containers).toEqual([]); + expect(volumes).toEqual([]); + } +); +it.each(['container', 'volume'])('refuses replacement %s on the next invocation', (resource) => { + failure = 'volume'; + expect(run().some((o) => o.status === 'failed')).toBe(true); + if (resource === 'container') containers = ['f'.repeat(64)]; + else volumes[0]!.createdAt = '2026-02-01T00:00:00Z'; + calls = []; + expect(run().some((o) => o.status === 'failed')).toBe(true); + expect(calls.some((args) => ['stop', 'rm'].includes(args[1] ?? ''))).toBe(false); +}); +it('allows disappeared resources to settle without selecting replacements', () => { + failure = 'volume'; + run(); + containers = []; + volumes = []; + expect(run().every((o) => ['removed', 'already removed'].includes(o.status))).toBe(true); +}); +it('clears completed keep-data intent so a legitimate restart can be stopped later', () => { + expect(run('keep-data').every((o) => ['removed', 'kept'].includes(o.status))).toBe(true); + containers = ['f'.repeat(64)]; + expect(run('keep-data').every((o) => ['removed', 'kept'].includes(o.status))).toBe(true); + expect(volumes).toHaveLength(1); +}); diff --git a/scripts/selfhost/teardown-compose.ts b/scripts/selfhost/teardown-compose.ts index d3fb2d38fa..ea71b50b17 100644 --- a/scripts/selfhost/teardown-compose.ts +++ b/scripts/selfhost/teardown-compose.ts @@ -3,8 +3,13 @@ import { dirname, resolve } from 'node:path'; import { readRecord } from '../../deploy/selfhost/created-resources.mjs'; import { check } from './backup-lib'; -import { composeProjectFor, expectedComposeProjectFor } from './install-record'; import type { TeardownContext } from './teardown-box'; +import { + assertPendingComposeInventory, + authorizeComposeRemoval, + finishKeepDataRemoval, +} from './teardown-compose-progress'; +import { expectedTeardownProject, selectedTeardownProject } from './teardown-identity'; interface Container { id: string; @@ -43,8 +48,8 @@ function parse(text: string): Record { } } function projectProof(ctx: TeardownContext): string { - const project = composeProjectFor(ctx.box, ctx.stateDir); - if (project !== expectedComposeProjectFor(ctx.box, ctx.stateDir) || !ctx.installationId) + const project = selectedTeardownProject(ctx); + if (project !== expectedTeardownProject(ctx) || !ctx.installationId) throw new Error('Refused: no exact installation Compose identity'); const record = readRecord(ctx.recordFile).resources; const installs = record.filter( @@ -146,13 +151,17 @@ export function readComposeInventory(ctx: TeardownContext): ComposeInventory { throw new Error('Refused: duplicate Docker volume inventory'); containers.sort((a, b) => a.id.localeCompare(b.id)); volumes.sort((a, b) => a.name.localeCompare(b.name)); - return { containers, volumes }; + const inventory = { containers, volumes }; + assertPendingComposeInventory(ctx, inventory); + return inventory; } export function assertComposeInventory(ctx: TeardownContext, expected: ComposeInventory): void { if (JSON.stringify(readComposeInventory(ctx)) !== JSON.stringify(expected)) throw new Error('Refused: Docker identities or ownership changed since inventory'); } export function stopContainers(ctx: TeardownContext, inventory: ComposeInventory): void { + assertComposeInventory(ctx, inventory); + authorizeComposeRemoval(ctx, inventory); assertComposeInventory(ctx, inventory); if (inventory.containers.length) check( @@ -165,6 +174,8 @@ export function removeContainers( inventory: ComposeInventory, volumes: boolean ): void { + assertComposeInventory(ctx, inventory); + authorizeComposeRemoval(ctx, inventory); assertComposeInventory(ctx, inventory); // Exact ids, individually re-fetched just above, cannot select a replacement container. if (inventory.containers.length) @@ -179,4 +190,5 @@ export function removeContainers( throw new Error('Refused: Docker volume identity changed before removal'); check(ctx.run('docker', ['volume', 'rm', volume.name]), 'remove owned volume'); } + else finishKeepDataRemoval(ctx); } diff --git a/scripts/selfhost/teardown-gcp-bootstrap.ts b/scripts/selfhost/teardown-gcp-bootstrap.ts index d683d0da6e..3f80b782d1 100644 --- a/scripts/selfhost/teardown-gcp-bootstrap.ts +++ b/scripts/selfhost/teardown-gcp-bootstrap.ts @@ -2,6 +2,7 @@ import type { CreatedResource } from '../../deploy/selfhost/created-resources.mjs'; import { check } from './backup-lib'; import type { TeardownContext } from './teardown-box'; +import { cloudMetadata, grantPresent } from './teardown-gcp-grants'; import { type Item, STEPS } from './teardown-model'; export const BOOTSTRAP = 'gcp-bootstrap'; @@ -75,8 +76,17 @@ export function bootstrapItems(ctx: TeardownContext, project: string): Item[] { if (!owned) throw new Error('refused: missing creation ownership'); const pool = attrs.pool; const { describe, remove, expected } = bootstrapOperation(entry, project, issuer); + if ( + entry.kind === 'iam-binding' && + !grantPresent(ctx, ['projects', 'get-iam-policy', project], attrs.role, attrs.member) + ) + return; const result = gcloud(ctx, [...describe, '--format=json']); - if (result.status !== 0 && gcloudNotFound(result.stderr)) return; + if (result.status !== 0 && gcloudNotFound(result.stderr)) { + if (entry.kind === 'iam-binding') + throw new Error('Refused: IAM grant account identity is unavailable'); + return; + } check(result, 'read recorded resource before deletion'); let current: Record; try { @@ -103,8 +113,11 @@ export function bootstrapItems(ctx: TeardownContext, project: string): Item[] { pool, entry.kind === 'service-account' ? entry.name : attrs.account ); - if (entry.kind === 'service-account-iam-binding') - assertServiceAccountGrant(ctx, project, entry); + if ( + entry.kind === 'service-account-iam-binding' && + !assertServiceAccountGrant(ctx, project, entry) + ) + return; check(gcloud(ctx, remove), 'delete recorded resource'); }, record: entry, @@ -131,7 +144,7 @@ function assertPoolProviders( '--format=json', ]); check(providers, 'check pool providers before deletion'); - const parsed: unknown = JSON.parse(providers.stdout); + const parsed: unknown = cloudMetadata(providers.stdout); const known = new Set( ctx.record .filter( @@ -171,7 +184,7 @@ function assertAccountExclusive( '--format=json', ]); check(policy, 'check account grants before deletion'); - const parsed: unknown = JSON.parse(policy.stdout); + const parsed: unknown = cloudMetadata(policy.stdout); if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) throw new Error('refused: unreadable account grants'); const bindings = (parsed as { bindings?: unknown }).bindings ?? []; @@ -201,7 +214,7 @@ function assertAccountExclusive( '--format=json', ]); check(keys, 'check account keys before deletion'); - const parsedKeys: unknown = JSON.parse(keys.stdout); + const parsedKeys: unknown = cloudMetadata(keys.stdout); if (!Array.isArray(parsedKeys) || parsedKeys.length) throw new Error('refused: account has user-managed keys'); } @@ -323,7 +336,7 @@ function assertServiceAccountGrant( ctx: TeardownContext, project: string, entry: CreatedResource -): void { +): boolean { const attrs = entry.attributes ?? {}; const pools = ctx.record.filter( (r) => @@ -344,35 +357,10 @@ function assertServiceAccountGrant( attrs.member !== `principalSet://iam.googleapis.com/${identity}/*` ) throw new Error('refused: service account grant pool identity changed'); - const policy = check( - gcloud(ctx, [ - 'iam', - 'service-accounts', - 'get-iam-policy', - attrs.account, - `--project=${project}`, - '--format=json', - ]), - 'read service account grant before deletion' + return grantPresent( + ctx, + ['iam', 'service-accounts', 'get-iam-policy', attrs.account, `--project=${project}`], + attrs.role, + attrs.member ); - try { - const value: unknown = JSON.parse(policy.stdout); - if (!value || typeof value !== 'object' || Array.isArray(value)) - throw new Error('Invalid policy'); - const bindings = (value as { bindings?: unknown }).bindings ?? []; - if ( - !Array.isArray(bindings) || - bindings.some( - (b) => - !b || - typeof b.role !== 'string' || - !Array.isArray(b.members) || - b.members.some((m: unknown) => typeof m !== 'string') || - (b.role === attrs.role && b.members.includes(attrs.member) && !!b.condition) - ) - ) - throw new Error('Invalid grant'); - } catch { - throw new Error('refused: unreadable or conditional service account grant'); - } } diff --git a/scripts/selfhost/teardown-gcp-grants.test.ts b/scripts/selfhost/teardown-gcp-grants.test.ts new file mode 100644 index 0000000000..1c1ed42fc1 --- /dev/null +++ b/scripts/selfhost/teardown-gcp-grants.test.ts @@ -0,0 +1,106 @@ +/** Lost IAM responses must settle exact absent grants, without deleting a reused identity. */ +import { mkdirSync, mkdtempSync, rmSync } from 'node:fs'; +import { join, resolve } from 'node:path'; + +import { afterEach, beforeEach, expect, it } from 'vitest'; + +import { addResource, readRecord } from '../../deploy/selfhost/created-resources.mjs'; +import type { TeardownContext } from './teardown-box'; +import { bootstrapItems } from './teardown-gcp-bootstrap'; +import { execute } from './teardown-model'; +let root: string; +beforeEach(() => { + mkdirSync(resolve('.tmp'), { recursive: true }); + root = mkdtempSync(resolve('.tmp/teardown-iam-retry-')); +}); +afterEach(() => rmSync(root, { recursive: true, force: true })); +it.each(['iam-binding', 'service-account-iam-binding'])( + 'settles %s after removal succeeded but its response was lost', + (kind) => { + const file = join(root, 'record.json'), + installation = 'a'.repeat(32), + domain = 'iam.example.com'; + const identity = 'projects/123/locations/global/workloadIdentityPools/pool'; + const attrs = { + installation, + environment: 'selfhost', + install: `https://api.${domain}`, + project: 'sam-test', + pool: 'pool', + }; + addResource(file, { + cloud: 'gcp', + kind: 'workload-identity-pool', + name: 'pool', + action: 'created', + createdBy: 'gcp-bootstrap', + attributes: { ...attrs, identity }, + }); + const role = + kind === 'iam-binding' ? 'roles/compute.securityAdmin' : 'roles/iam.workloadIdentityUser'; + const member = + kind === 'iam-binding' + ? 'serviceAccount:acct' + : `principalSet://iam.googleapis.com/${identity}/*`; + addResource(file, { + cloud: 'gcp', + kind, + name: 'grant', + action: 'created', + createdBy: 'gcp-bootstrap', + attributes: { ...attrs, identity: 'account-immutable-id', account: 'acct', role, member }, + }); + let present = true, + removals = 0; + const ctx: TeardownContext = { + box: {}, + envFile: join(root, 'env'), + stateDir: root, + composeFiles: [], + now: Date.now, + log: () => undefined, + selfhostDir: root, + recordFile: file, + record: readRecord(file).resources, + domain, + installationId: installation, + options: { deleteBackups: false, destroyKey: false, adoptDiscovered: false, gcpProjects: [] }, + run: (_command, args) => { + const cmd = args.join(' '), + ok = (value: unknown) => ({ status: 0, stdout: JSON.stringify(value), stderr: '' }); + if (args.includes('remove-iam-policy-binding')) { + present = false; + removals++; + return { status: 1, stdout: '', stderr: 'response lost' }; + } + if (args.includes('get-iam-policy')) { + const selected = + kind === 'iam-binding' + ? cmd.startsWith('projects') + : cmd.startsWith('iam service-accounts'); + return ok({ bindings: selected && present ? [{ role, members: [member] }] : [] }); + } + if (args.includes('describe')) + return ok({ + uniqueId: 'account-immutable-id', + description: `Creates and deletes SAM workspace VMs and their firewall rules for https://api.${domain}`, + }); + if (args.includes('list')) return ok([]); + throw Error('Unexpected destructive provider command'); + }, + }; + const items = () => + bootstrapItems({ ...ctx, record: readRecord(file).resources }, 'sam-test').filter( + (i) => i.id === `gcp:${kind}:grant` + ); + expect(execute(items(), 'keep-data', file)[0]?.status).toBe('kept'); + expect(removals).toBe(0); + expect(execute(items(), 'remove-everything', file)[0]?.status).toBe('failed'); + expect(readRecord(file).resources.find((r) => r.kind === kind)?.removedAt).toBeUndefined(); + expect(execute(items(), 'remove-everything', file)[0]?.status).toBe('removed'); + expect(removals).toBe(1); + expect( + readRecord(file).resources.find((r) => r.kind === 'workload-identity-pool')?.removedAt + ).toBeUndefined(); + } +); diff --git a/scripts/selfhost/teardown-gcp-grants.ts b/scripts/selfhost/teardown-gcp-grants.ts new file mode 100644 index 0000000000..d2fd3c482e --- /dev/null +++ b/scripts/selfhost/teardown-gcp-grants.ts @@ -0,0 +1,43 @@ +/** Policy observations are exact and sanitized; an already absent grant is retry completion. */ +import { check } from './backup-lib'; +import type { TeardownContext } from './teardown-box'; + +export function cloudMetadata(text: string): unknown { + try { + return JSON.parse(text); + } catch { + throw new Error('Refused: unreadable Google Cloud ownership metadata'); + } +} +export function grantPresent( + ctx: TeardownContext, + args: string[], + role: string, + member: string +): boolean { + let result; + try { + result = ctx.run('gcloud', [...args, '--format=json']); + } catch { + throw new Error('Cannot read recorded IAM grant policy'); + } + const value = cloudMetadata(check(result, 'read recorded IAM grant policy').stdout); + if (!value || typeof value !== 'object' || Array.isArray(value)) + throw new Error('Refused: unreadable IAM grant policy'); + const bindings = (value as { bindings?: unknown }).bindings ?? []; + if ( + !Array.isArray(bindings) || + bindings.some( + (b) => + !b || + typeof b.role !== 'string' || + !Array.isArray(b.members) || + b.members.some((m: unknown) => typeof m !== 'string') + ) + ) + throw new Error('Refused: unreadable IAM grant policy'); + const matching = bindings.filter((b) => b.role === role && b.members.includes(member)); + if (matching.some((b) => b.condition)) + throw new Error('Refused: recorded IAM grant is now conditional'); + return matching.length > 0; +} diff --git a/scripts/selfhost/teardown-identity.ts b/scripts/selfhost/teardown-identity.ts new file mode 100644 index 0000000000..1df178a284 --- /dev/null +++ b/scripts/selfhost/teardown-identity.ts @@ -0,0 +1,12 @@ +/** Keep cleanup identity stable after platform keys and finally installation state are removed. */ +import { composeProjectFor, expectedComposeProjectFor } from './install-record'; +import type { TeardownContext } from './teardown-box'; + +export function expectedTeardownProject(ctx: TeardownContext): string { + return expectedComposeProjectFor(ctx.box, ctx.stateDir, ctx.installationId ?? undefined); +} +export function selectedTeardownProject(ctx: TeardownContext): string { + return ctx.box.COMPOSE_PROJECT_NAME === undefined + ? expectedTeardownProject(ctx) + : composeProjectFor(ctx.box, ctx.stateDir); +} diff --git a/scripts/selfhost/teardown-interruption.test.ts b/scripts/selfhost/teardown-interruption.test.ts new file mode 100644 index 0000000000..9ea7b7f877 --- /dev/null +++ b/scripts/selfhost/teardown-interruption.test.ts @@ -0,0 +1,148 @@ +/** Operator entrypoint fault injection: interruption must retain ownership and allow exact retry. */ +import { + chmodSync, + existsSync, + mkdirSync, + mkdtempSync, + readFileSync, + renameSync, + rmSync, + writeFileSync, +} from 'node:fs'; +import { join, resolve } from 'node:path'; + +import { afterEach, beforeEach, expect, it, vi } from 'vitest'; + +import { readRecord } from '../../deploy/selfhost/created-resources.mjs'; +import { encryptBackupTree } from './backup-encryption'; +import { CHILD_TEST_TIMEOUT_MS, runTsx } from './deploy-harness'; +import { recordBackup, recordInstall, recordPath } from './install-record'; + +vi.setConfig({ testTimeout: CHILD_TEST_TIMEOUT_MS }); +let root: string, state: string, env: string, hook: string, bin: string; +const domain = 'interrupt.example.com'; +beforeEach(() => { + for (const name of Object.keys(process.env)) + if (name === 'CI' || name === 'GITHUB_ACTIONS' || name.startsWith('RUNNER_')) + vi.stubEnv(name, undefined); + mkdirSync(resolve('.tmp'), { recursive: true }); + root = mkdtempSync(resolve('.tmp/teardown-interrupt-')); + state = join(root, 'state'); + mkdirSync(state); + env = join(root, 'box.env'); + writeFileSync(env, `SAM_DOMAIN=${domain}\n`, { mode: 0o600 }); + writeFileSync( + join(state, 'platform-keys.json'), + JSON.stringify({ SAM_INSTALLATION_ID: 'c'.repeat(32) }), + { mode: 0o600 } + ); + recordInstall(state, env, { SAM_DOMAIN: domain }, 'c'.repeat(32)); + bin = join(root, 'bin'); + mkdirSync(bin); + writeFileSync(join(bin, 'docker'), '#!/usr/bin/env node\nprocess.exit(0);\n'); + chmodSync(join(bin, 'docker'), 0o755); + hook = join(root, 'fault.mjs'); + writeFileSync( + hook, + `import fs from 'node:fs'; import {syncBuiltinESMExports} from 'node:module'; +const rename=fs.renameSync, rm=fs.rmSync; +fs.renameSync=function(a,b){ + if(process.env.FAULT==='state-ledger'&&b===process.env.LEDGER&&!fs.existsSync(process.env.KEY)) throw Error('injected ledger failure'); + if(process.env.FAULT==='backup-ledger'&&b===process.env.LEDGER&&!fs.existsSync(process.env.BACKUP)) throw Error('injected ledger failure'); + return rename(a,b); +}; +fs.rmSync=function(p,o){ + if(process.env.FAULT==='backup-partial'&&p===process.env.BACKUP){ fs.unlinkSync(p+'/.sam-backup-manifest'); throw Error('injected partial removal'); } + if(process.env.FAULT==='env'&&p===process.env.ENVFILE) throw Error('injected env failure'); + return rm(p,o); +}; syncBuiltinESMExports();` + ); +}); +afterEach(() => { + vi.unstubAllEnvs(); + rmSync(root, { recursive: true, force: true }); +}); +function run(fault = '', extra: string[] = [], backup = '') { + return runTsx( + resolve(import.meta.dirname, 'teardown.ts'), + [ + '--box-env', + env, + '--state-dir', + state, + '--remove-everything', + '--destroy-key', + '--confirm', + domain, + ...extra, + ], + { + PATH: `${bin}:${process.env.PATH}`, + NODE_OPTIONS: `--import=${hook}`, + FAULT: fault, + KEY: join(state, 'platform-keys.json'), + LEDGER: recordPath(state), + ENVFILE: env, + BACKUP: backup, + } + ); +} +it.each(['state-ledger', 'env'])('retries after %s failure after keys are gone', async (fault) => { + const first = await run(fault); + expect(first.status, first.out).not.toBe(0); + expect(existsSync(join(state, 'platform-keys.json'))).toBe(false); + expect(existsSync(env)).toBe(true); + if (fault === 'state-ledger') { + const receipts = readRecord(recordPath(state)).resources.filter((r) => + ['state-dir', 'installation'].includes(r.kind) + ); + expect(receipts.every((r) => !r.removedAt)).toBe(true); + } + const retry = await run(); + expect(retry.status, retry.out).toBe(0); + expect(existsSync(env)).toBe(false); + expect( + readRecord(recordPath(state)) + .resources.filter((r) => ['state-dir', 'installation'].includes(r.kind)) + .every((r) => !!r.removedAt) + ).toBe(true); +}); +it.each(['backup-partial', 'backup-ledger', 'backup-replaced'])( + 'resumes %s with durable exact backup proof', + async (fault) => { + const source = join(root, 'source'); + mkdirSync(source); + writeFileSync(join(source, 'fixture'), 'fixture'); + const key = join(root, 'key'); + writeFileSync(key, Buffer.alloc(32, 11), { mode: 0o600 }); + const backup = join(root, 'backup'); + encryptBackupTree(source, backup, key); + recordBackup(state, backup); + const first = await run( + fault === 'backup-replaced' ? 'backup-partial' : fault, + ['--delete-backups'], + backup + ); + expect(first.status, first.out).not.toBe(0); + const receipt = readRecord(recordPath(state)).resources.find((r) => r.kind === 'backup'); + expect(receipt?.removedAt).toBeUndefined(); + expect(receipt?.attributes?.removalAuthorized).toBe(receipt?.attributes?.identity); + if (fault === 'backup-partial') expect(existsSync(backup)).toBe(true); + if (fault === 'backup-replaced') { + renameSync(backup, join(root, 'original-backup')); + mkdirSync(backup); + writeFileSync(join(backup, 'foreign'), 'foreign'); + const refused = await run('', ['--delete-backups'], backup); + expect(refused.status, refused.out).not.toBe(0); + expect(readFileSync(join(backup, 'foreign'), 'utf8')).toBe('foreign'); + return; + } + const retry = await run('', ['--delete-backups'], backup); + expect(retry.status, retry.out).toBe(0); + expect(existsSync(backup)).toBe(false); + expect( + readRecord(recordPath(state)).resources.find((r) => r.kind === 'backup')?.removedAt + ).toBeDefined(); + expect(readFileSync(key)).toEqual(Buffer.alloc(32, 11)); + } +); diff --git a/scripts/selfhost/teardown-model.test.ts b/scripts/selfhost/teardown-model.test.ts index d9ec363ea4..514b46a619 100644 --- a/scripts/selfhost/teardown-model.test.ts +++ b/scripts/selfhost/teardown-model.test.ts @@ -77,6 +77,10 @@ it('preserves provider, pool and account after a failed binding, then completes stdout: JSON.stringify(value), stderr: '', }); + if (cmd.startsWith('projects get-iam-policy')) + return ok({ + bindings: [{ role: 'roles/compute.securityAdmin', members: ['serviceAccount:acct'] }], + }); if (cmd.startsWith('projects remove-iam-policy-binding')) { if (failBinding) { failBinding = false; diff --git a/scripts/selfhost/teardown-model.ts b/scripts/selfhost/teardown-model.ts index e135627c9f..d907adcc8b 100644 --- a/scripts/selfhost/teardown-model.ts +++ b/scripts/selfhost/teardown-model.ts @@ -3,7 +3,7 @@ * mode decides about it, and the order and bookkeeping of a removal. Nothing here knows a cloud; * cloud specifics live in adapters (teardown-gcp.ts) that return items of this shape. */ -import { addResource, markRemoved, readRecord } from '../../deploy/selfhost/created-resources.mjs'; +import { completeRemoval } from './teardown-record'; export type Mode = 'keep-data' | 'remove-everything'; export const MODES: readonly Mode[] = ['keep-data', 'remove-everything']; @@ -161,33 +161,24 @@ function executeItem( const error = runAction(item, items, ran); if (error && !item.goneDespiteGroupFailure?.()) return { item, status: 'failed', why: error.message }; - const settled = item.settle?.() ?? { removed: true }; - if (!settled.removed) return { item, status: 'kept', why: settled.why }; - for (const ref of [item.record ?? []].flat()) markInRecord(recordFile, ref); - return { item, status: 'removed' }; + try { + const settled = item.settle?.() ?? { removed: true }; + if (!settled.removed) return { item, status: 'kept', why: settled.why }; + completeRemoval(recordFile, [item.record ?? []].flat()); + return { item, status: 'removed' }; + } catch { + return { + item, + status: 'failed', + why: 'cannot verify or persist removal completion; retry to finish bookkeeping', + }; + } } function statusOf(decision: Exclude): Outcome['status'] { return decision.act === 'keep' ? 'kept' : decision.act; } -function markInRecord(file: string, ref: RecordRef): void { - const known = readRecord(file).resources.some( - (r) => r.cloud === ref.cloud && r.kind === ref.kind && r.name === ref.name - ); - if (!known) { - addResource(file, { - cloud: ref.cloud, - kind: ref.kind, - name: ref.name, - action: 'created', - createdBy: ref.createdBy ?? 'discovered-by-teardown', - attributes: ref.attributes ?? {}, - }); - } - markRemoved(file, ref.cloud, ref.kind, ref.name); -} - /** Inventory: everything found, where it is, how it would go, and what each mode does with it. */ export function renderInventory(items: Item[]): string { const lines: string[] = []; diff --git a/scripts/selfhost/teardown-record.ts b/scripts/selfhost/teardown-record.ts new file mode 100644 index 0000000000..f44faa81ff --- /dev/null +++ b/scripts/selfhost/teardown-record.ts @@ -0,0 +1,46 @@ +/** Durable teardown bookkeeping; a failed save never authorizes a later destructive step. */ +import { addResource, readRecord } from '../../deploy/selfhost/created-resources.mjs'; +import { replacePrivateFile } from './secret-files'; +import type { RecordRef } from './teardown-model'; + +export function completeRemoval(file: string, refs: RecordRef[]): void { + if (!refs.length) return; + for (const ref of refs) { + if ( + !readRecord(file).resources.some( + (r) => r.cloud === ref.cloud && r.kind === ref.kind && r.name === ref.name + ) + ) + addResource(file, { + ...ref, + action: 'created', + createdBy: ref.createdBy ?? 'discovered-by-teardown', + }); + } + const record = readRecord(file); + const removedAt = new Date().toISOString(); + for (const ref of refs) { + const entry = record.resources.find( + (r) => r.cloud === ref.cloud && r.kind === ref.kind && r.name === ref.name + ); + if (!entry) throw new Error('Removal receipt disappeared'); + entry.removedAt = removedAt; + } + if (refs.length) replacePrivateFile(file, `${JSON.stringify(record, null, 2)}\n`); +} + +export function updateRemovalProof( + file: string, + kind: string, + name: string, + attributes: Record +): void { + const record = readRecord(file); + const entry = record.resources.find( + (r) => r.cloud === 'box' && r.kind === kind && r.name === name + ); + if (!entry || entry.action !== 'created' || entry.removedAt) + throw new Error('No active resource creation receipt for removal'); + entry.attributes = { ...entry.attributes, ...attributes }; + replacePrivateFile(file, `${JSON.stringify(record, null, 2)}\n`); +} diff --git a/scripts/selfhost/teardown-state-dir.ts b/scripts/selfhost/teardown-state-dir.ts index 77fd000201..879de63465 100644 --- a/scripts/selfhost/teardown-state-dir.ts +++ b/scripts/selfhost/teardown-state-dir.ts @@ -21,6 +21,7 @@ import { STATE_CACHE_EXCLUDES } from './backup-lib'; import { RECORD_FILE } from './install-record'; import type { TeardownContext } from './teardown-box'; import { both, type Item, STEPS } from './teardown-model'; +import { updateRemovalProof } from './teardown-record'; const KEY_FILE = join('key-agent', 'kek'); const LEGACY_KEYS = 'platform-keys.json'; @@ -131,6 +132,10 @@ function isGone(path: string): boolean { /** Everything in .state except the record, and the keys when they are kept. */ function clearState(ctx: TeardownContext, keepKey: boolean): void { assertStateDir(ctx); + if (!keepKey) + updateRemovalProof(ctx.recordFile, 'state-dir', ctx.stateDir, { + destroyKeysAuthorized: ctx.installationId ?? '', + }); const left = clearStateEntries(ctx.stateDir, keepKey, ctx.removeTree); if (left.length > 0) throw new Error(describeLeftovers(ctx.stateDir, left)); } @@ -283,6 +288,7 @@ function assertStateDir(ctx: TeardownContext): void { if (identity !== ctx.installationId) throw new Error('Refused: platform identity disagrees with installation receipt'); } else if ( + states[0]?.attributes?.destroyKeysAuthorized !== ctx.installationId && !record.some( (r) => r.cloud === 'box' && diff --git a/scripts/selfhost/upgrade-lib.ts b/scripts/selfhost/upgrade-lib.ts index 221487128b..5b37a7175f 100644 --- a/scripts/selfhost/upgrade-lib.ts +++ b/scripts/selfhost/upgrade-lib.ts @@ -10,6 +10,7 @@ import { dirname, join, resolve } from 'node:path'; import { assertRollbackCacheReady, + beginRollbackCacheStart, type BoxContext as BackupContext, composeArgs, composeRunEnv, @@ -206,8 +207,8 @@ export async function recoverUpgrade( finishRollbackCache(backupContext(ctx)); } -/** A partial start may have replaced the cache; retain its exact identity for another retry. */ function startRecoveredStack(ctx: BoxContext, backupDir: string, env?: NodeJS.ProcessEnv): void { + beginRollbackCacheStart(backupContext(ctx), backupDir); try { check(ctx.run('docker', composeArgs(ctx, ['up', '-d']), env), 'restore previous stack'); } catch (error) { diff --git a/scripts/selfhost/upgrade-rollback-cli.test.ts b/scripts/selfhost/upgrade-rollback-cli.test.ts index f9fc43d5c1..7d14e70207 100644 --- a/scripts/selfhost/upgrade-rollback-cli.test.ts +++ b/scripts/selfhost/upgrade-rollback-cli.test.ts @@ -74,16 +74,24 @@ const fs = require('node:fs'); const cp = require('node:child_process'); const { syncBuiltinESMExports } = require('node:module'); const original = cp.spawnSync; +let container = 'c'.repeat(64); +let volume = true; +let created = '2026-11-19T00:00:00Z'; cp.spawnSync = (command, args, options) => { if (!['git', 'pnpm', 'docker', 'gcloud'].includes(command)) return original(command,args,options); fs.appendFileSync(${JSON.stringify(join(root, 'calls'))}, command+' '+args.join(' ')+'\\n'); let stdout = ''; if(command === 'git' && args[0] === 'rev-parse') stdout = 'b'.repeat(40); if (command === 'docker') { - if(args.includes('ps')) stdout = 'c'.repeat(64); - if(args[0]==='inspect') stdout = JSON.stringify([{Destination:'/var/lib/celld', Type:'volume', Name:${JSON.stringify(`${project}_celld-data`)}}]); - if(args[0]==='volume' && args[1]==='ls') stdout = ${JSON.stringify(`${project}_celld-data`)}; - if(args[0]==='volume' && args[1]==='inspect') stdout = JSON.stringify([{Name:${JSON.stringify(`${project}_celld-data`)},CreatedAt:'2026-11-19T00:00:00Z',Labels:{'com.docker.compose.project':${JSON.stringify(project)},'com.docker.compose.volume':'celld-data'}}]); + if(args[0]==='container' && args[1]==='rm') container=''; + if(args[0]==='volume' && args[1]==='rm') volume=false; + if(args.includes('up')) { container='d'.repeat(64); volume=true; created=new Date().toISOString(); } + if(args.includes('ps')) stdout = container; + if(args[0]==='inspect') stdout = args[2]?.includes('{{json .Id}}') + ? JSON.stringify({Id:container,Created:created,Config:{Labels:{'com.docker.compose.project':${JSON.stringify(project)},'com.docker.compose.service':'celld','com.docker.compose.project.config_files':${JSON.stringify(resolve('deploy/selfhost/docker-compose.yml'))},'com.docker.compose.project.working_dir':${JSON.stringify(resolve('deploy/selfhost'))}}}}) + : JSON.stringify([{Destination:'/var/lib/celld', Type:'volume', Name:${JSON.stringify(`${project}_celld-data`)}}]); + if(args[0]==='volume' && args[1]==='ls') stdout = volume ? ${JSON.stringify(`${project}_celld-data`)} : ''; + if(args[0]==='volume' && args[1]==='inspect') stdout = JSON.stringify([{Name:${JSON.stringify(`${project}_celld-data`)},CreatedAt:created,Labels:{'com.docker.compose.project':${JSON.stringify(project)},'com.docker.compose.volume':'celld-data'}}]); if(args.includes('config')) stdout='celld\\ncaddy'; } if(command === 'gcloud') { diff --git a/scripts/selfhost/upgrade-rollback.test.ts b/scripts/selfhost/upgrade-rollback.test.ts index 03696d41de..9cee8de96a 100644 --- a/scripts/selfhost/upgrade-rollback.test.ts +++ b/scripts/selfhost/upgrade-rollback.test.ts @@ -4,7 +4,12 @@ import { join, resolve } from 'node:path'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; -import { finishRollbackCache, refreshRollbackCacheReceipt, runRollback } from './backup-lib.js'; +import { + beginRollbackCacheStart, + finishRollbackCache, + refreshRollbackCacheReceipt, + runRollback, +} from './backup-lib.js'; import { rollbackSteps } from './upgrade-instructions.js'; import { type BoxContext, UPGRADE_PENDING_FILE } from './upgrade-lib.js'; import { runManualRollback } from './upgrade-rollback.js'; @@ -12,6 +17,7 @@ import { runManualRollback } from './upgrade-rollback.js'; vi.mock('./backup-lib.js', async (original) => ({ ...(await original()), runRollback: vi.fn(), + beginRollbackCacheStart: vi.fn(), refreshRollbackCacheReceipt: vi.fn(), finishRollbackCache: vi.fn(), })); @@ -41,6 +47,7 @@ beforeEach(() => { stateEnvs = []; dirty = false; vi.mocked(refreshRollbackCacheReceipt).mockReset(); + vi.mocked(beginRollbackCacheStart).mockReset(); vi.mocked(finishRollbackCache).mockReset(); ctx = { box: { COMPOSE_PROJECT_NAME: 'owned-manual' }, @@ -77,6 +84,62 @@ const rollback = (checkHealth = async () => true) => }); describe('manual owned rollback', () => { + it.each([ + 'checkout', + 'dependencies', + 'services', + 'build', + 'intent', + 'up-status', + 'up-throw', + 'refresh', + 'health', + 'finish', + ])( + 'retries a recovery interrupted at the %s boundary without skipping snapshot restoration', + async (phase) => { + const runner = ctx.run; + let failed = false; + ctx.run = (command, args, env) => { + const matches = + (phase === 'checkout' && command === 'git' && args[0] === 'checkout') || + (phase === 'dependencies' && command === 'pnpm' && args[0] === 'install') || + (phase === 'services' && args.includes('config')) || + (phase === 'build' && args.includes('build')) || + (phase.startsWith('up-') && args.includes('up')); + if (matches && !failed) { + failed = true; + if (phase === 'up-throw') throw new Error('transport unavailable'); + return { status: 1, stdout: '', stderr: 'withheld' }; + } + return runner(command, args, env); + }; + if (phase === 'intent') + vi.mocked(beginRollbackCacheStart).mockImplementationOnce(() => { + throw new Error('cannot persist intent'); + }); + if (phase === 'refresh') + vi.mocked(refreshRollbackCacheReceipt).mockImplementationOnce(() => { + throw new Error('cannot inspect replacement'); + }); + if (phase === 'finish') + vi.mocked(finishRollbackCache).mockImplementationOnce(() => { + throw new Error('cannot clear progress'); + }); + const health = vi + .fn() + .mockResolvedValueOnce(phase !== 'health') + .mockResolvedValue(true); + await expect(rollback(health)).rejects.toThrow(/Manual rollback did not complete/); + expect(existsSync(join(ctx.stateDir, UPGRADE_PENDING_FILE))).toBe(true); + if (phase !== 'finish') expect(finishRollbackCache).not.toHaveBeenCalled(); + await rollback(health); + expect(runRollback).toHaveBeenCalledTimes(2); + expect(existsSync(join(ctx.stateDir, UPGRADE_PENDING_FILE))).toBe(false); + expect(steps.filter((step) => step === 'OWNED_SNAPSHOT_RESTORE')).toHaveLength(2); + } + ); + it('retries after dependency failure with the removed cache receipt still retained', async () => { const receipt = join(ctx.stateDir, 'rollback-cache-pending.json'); let removed = false; diff --git a/scripts/selfhost/upgrade-safeguards.test.ts b/scripts/selfhost/upgrade-safeguards.test.ts index 38ee0bf094..e261f321b4 100644 --- a/scripts/selfhost/upgrade-safeguards.test.ts +++ b/scripts/selfhost/upgrade-safeguards.test.ts @@ -11,6 +11,7 @@ vi.mock('./backup-lib', async (importOriginal) => ({ ...(await importOriginal()), runBackup: vi.fn(), runRollback: vi.fn(), + beginRollbackCacheStart: vi.fn(), refreshRollbackCacheReceipt: vi.fn(), finishRollbackCache: vi.fn(), })); diff --git a/scripts/selfhost/upgrade.test.ts b/scripts/selfhost/upgrade.test.ts index 913255a4b3..7bb0f64b38 100644 --- a/scripts/selfhost/upgrade.test.ts +++ b/scripts/selfhost/upgrade.test.ts @@ -28,6 +28,7 @@ vi.mock('./backup-lib.js', async (original) => ({ runBackup: vi.fn(), assertRollbackCacheReady: vi.fn(), runRollback: vi.fn(), + beginRollbackCacheStart: vi.fn(), refreshRollbackCacheReceipt: vi.fn(), finishRollbackCache: vi.fn(), })); diff --git a/tasks/archive/2026-11-19-l24-selfhost-operations.md b/tasks/archive/2026-11-19-l24-selfhost-operations.md index 74b85d92c4..60c1c0912b 100644 --- a/tasks/archive/2026-11-19-l24-selfhost-operations.md +++ b/tasks/archive/2026-11-19-l24-selfhost-operations.md @@ -26,17 +26,17 @@ The historical backup failed on the actual BOX during a stopped gcloud copy. Ret - [x] Keep-data retains storage, keys and WIF/service-account access; same-step failure blocks new destructive actions immediately. - [x] Retained keys keep active ownership receipts for a later env-absent destroy-key retry. Backup deletion requires active exact directory/inventory inode/hash proof, rechecked at deletion. - [x] Documentation matches actual key separation, restore identity, retry, migration, rollback and teardown behavior. -- [x] Independent security, documentation and implementation-completion review passed on tested source39f3fa951c104e410d1feb43123c8166580da727. +- [x] Independent security, documentation and implementation-completion review passed on the combined operations tree, including the comprehensive interruption/retry audit; exact release head is recorded in PR2918. - [x] Required real BOX backup, fresh restore/data verification, valid/refused upgrade and automatic rollback passed. - [x] Disposable keep-data/restart and two-step full teardown passed; all created resources cleaned; shared BOX healthy and BOX FREE posted. ## Automated validation -Full self-host suite648PASS/1conditional skip across36files. The root-only foreign-owner setup skips for an unprivileged runner; the actual foreign-owned `/tmp` preservation control passes. The entire suite also passed with `packages/providers/dist` physically absent, proving clean-checkout CLI/Vitest resolution through the explicit self-host source configuration. Typecheck, focused lint, formatting and diff checks pass. Secret scanner reports zero findings;187 scanner/exception controls passed. Real MinIO backup/restore and injected partial upload/resume tests passed and cleaned their resources. Projection, guard removal, cache retry and read-only cleanup fault controls fail when their respective protections are removed. +Final combined self-host suite730PASS/1conditional skip across43files. The root-only foreign-owner setup skips for an unprivileged runner; the actual foreign-owned `/tmp` preservation control passes. The entire suite also passed with `packages/providers/dist` physically absent, proving clean-checkout CLI/Vitest resolution through the explicit self-host source configuration. Typecheck, focused lint, formatting and diff checks pass. Secret scanner reports zero findings;187 scanner/exception controls passed. Real MinIO backup/restore and injected partial upload/resume tests passed and cleaned their resources. Projection, guard removal, cache retry and read-only cleanup fault controls fail when their respective protections are removed. Repository lint23packages, typecheck38packages and build19packages passed. Root tests40/41tasks passed, with API17902passed and one timeout in an unchanged test; that entire file passed12/12 on retry. Type-boundary ratchet has zero blocking findings. Current-head CI is tracked separately before merge. -All11 Codex findings were fixed with focused regressions and replies; their threads were resolved. CodeRabbit was requested through the trusted label workflow at ready23:03UTC Nov19 and returned a review-limit/rate-limit response; the wait ended on that response, with no CodeRabbit finding or waiver. +All11 earlier Codex findings were fixed with focused regressions and resolved threads. Three additional findings (interrupted Compose replacement, bundled-store restore bootstrap and completion-journal durability) are fixed with discriminating retries; final review reconciliation is recorded in PR2918. CodeRabbit was requested through the trusted label workflow at ready23:03UTC Nov19 and returned a review-limit/rate-limit response; the wait ended on that response, with no CodeRabbit finding or waiver. ## BOX evidence and cleanup @@ -53,7 +53,17 @@ Final tested operations source39f3fa951c104e410d1feb43123c8166580da727: All18547 objects under the uniquely owned task prefix were deleted with generation conditions; existing shared bucket and `/celld` data were preserved. Removed the owned worktree, scratch tree, decrypted plaintext, backups, key,14 uploaded files, exact metadata SSH key and immutable-id-verified SSH firewall. Verified metadata-key absence and firewall404, then deleted local token/private key. Final shared checkout and four original services were unchanged, APIHTTP200. BOX FREE sequence422/eventef041954-cde5-4ebb-951f-4bbd9d95adeb; coordinator and next H2 task notified. -Latest main20675016f (Claude action dependency bump only) was merged before release. Self-host source after synchronization is byte-identical to the tested39f source; final evidence/archive changes are documentation only. Current-head specialist/CI evidence and merge/deploy receipts live in PR2918 and `.do-state.md`. +Latest main20675016f (Claude action dependency bump only) was merged before release. Subsequent changes cover failure/retry bookkeeping and the formerly blocked bundled-store restore path. The existing GCS happy-path projection/data and migration algorithms are unchanged. Under the coordinator’s explicit exception, those failure-only changes are covered by real-filesystem/store tests and the canonical local-store path by real MinIO, without reacquiring BOX. Current-head specialist/CI evidence and merge/deploy receipts live in PR2918 and `.do-state.md`. + +## Comprehensive interruption and retry audit + +The final audit traced backup, restore, upgrade/rollback and keep/full teardown through interruption and retry, rather than addressing only review examples. Backup restarts its exact writer even when stop returns failure after taking effect; copied read-only plaintext scratch is removed without following symlinks or changing foreign directories. Surgical controls confirm both protections are necessary. A killed process still requires documented operator inspection/restart and a fresh destination. + +Restore durably records ownership before target writes, re-syncs a surviving journal on retry, and retains a durable completion receipt before unlinking progress. Real filesystem fault tests cover initial write/file-sync/directory-sync, completion link/unlink/sync and torn state copies. Only exact authenticated state prefixes may resume; bucket objects require complete equality. Read-only `--print-project` authenticates first and allows the canonical bundled store to bootstrap under the final projected identity; strict runtime inspection refuses app/foreign containers and mismatched mounts, labels, config or images. Three real MinIO tests cover canonical Compose with custom ports, restore, real deployment init, retained volume/data and actual app-container refusal. The pinned store healthcheck now uses its configured IPv4 port. All containers and named/anonymous fixture volumes were removed with exact ownership proof. + +Upgrade persists a snapshot-bound cache recreation intent before Compose. Partial container/volume creation, failed command response and failed inspection can recover only with exact project, service, paths, mount and creation-time proof. Ten boundary faults, three encrypted repeated-attempt scenarios and changed-target A→B→C controls pass; no replacement cache is adopted without its durable intent. + +Teardown durably records original Docker inventories, key-removal authorization and backup inode proof before mutation. Partial deletes and lost receipt saves resume only remaining original resources, while replacements refuse. Atomic grouped tombstones halt later destructive steps on save failure; identity survives key/env cleanup, and exact absent IAM grants settle lost-success responses. Eight teardown files/81 tests include actual CLI filesystem faults and Docker/IAM adapters. The audit matrix is retained locally with PR evidence; no new BOX/cloud resources were used. ## Post-mortem From a2a45b8b9fe8efacac66f5eaba45d25cd8313c51 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rapha=C3=ABl=20Titsworth-Morin?= Date: Fri, 20 Nov 2026 01:41:25 +0000 Subject: [PATCH 12/17] fix(selfhost): print the restored target health URL --- scripts/selfhost/backup-entrypoint.test.ts | 9 ++++++++- scripts/selfhost/restore.ts | 7 ++++++- tasks/archive/2026-11-19-l24-selfhost-operations.md | 4 +++- 3 files changed, 17 insertions(+), 3 deletions(-) diff --git a/scripts/selfhost/backup-entrypoint.test.ts b/scripts/selfhost/backup-entrypoint.test.ts index 3970c399ac..18e966135e 100644 --- a/scripts/selfhost/backup-entrypoint.test.ts +++ b/scripts/selfhost/backup-entrypoint.test.ts @@ -319,7 +319,12 @@ describe('selfhost:backup and selfhost:restore (real entry points, fake gcloud)' expect(operations[3]).toMatch(/start celld$/); // Restore into an empty install: new bucket, no platform keys yet. - writeFileSync(join(root, 'new.env'), 'CELLD_BUCKET=gs://fresh/celld\n', { mode: 0o600 }); + writeFileSync( + join(root, 'new.env'), + 'CELLD_BUCKET=gs://fresh/celld\nSAM_DOMAIN=restore.example.org\n', + { mode: 0o600 } + ); + delete env.SAM_DOMAIN; // The target domain exists only in its private .env. const restore = run('restore.ts', [ '--from', dest, @@ -332,6 +337,8 @@ describe('selfhost:backup and selfhost:restore (real entry points, fake gcloud)' ]); expect(restore.stderr).toBe(''); expect(restore.status).toBe(0); + expect(restore.stdout).toContain("curl -fsS 'https://api.restore.example.org/health'"); + expect(restore.stdout).not.toContain('$SAM_DOMAIN'); expect(tree(join(root, 'gcs/fresh/celld'))).toEqual(afterStop); const restoredKeys = JSON.parse(tree(join(root, 'new-state'))['platform-keys.json']!); expect(restoredKeys).toEqual({ diff --git a/scripts/selfhost/restore.ts b/scripts/selfhost/restore.ts index 31b1b7a60a..d29fcd7899 100644 --- a/scripts/selfhost/restore.ts +++ b/scripts/selfhost/restore.ts @@ -53,4 +53,9 @@ log( log( ` pnpm selfhost:deploy --env-file '${envFile.replaceAll("'", "'\"'\"'")}' --state-dir '${ctx.stateDir.replaceAll("'", "'\"'\"'")}'` ); -log(` curl -fsS https://api.$SAM_DOMAIN/health`); +if (ctx.box.SAM_DOMAIN) { + const health = `https://api.${ctx.box.SAM_DOMAIN}/health`; + log(` curl -fsS '${health.replaceAll("'", "'\"'\"'")}'`); +} else { + log('Set SAM_DOMAIN in the target .env before checking the restored API health'); +} diff --git a/tasks/archive/2026-11-19-l24-selfhost-operations.md b/tasks/archive/2026-11-19-l24-selfhost-operations.md index 48126698a1..b559e18efa 100644 --- a/tasks/archive/2026-11-19-l24-selfhost-operations.md +++ b/tasks/archive/2026-11-19-l24-selfhost-operations.md @@ -36,7 +36,7 @@ Final main-integrated self-host suite973PASS/4conditional skips across55files. T Repository lint23packages, typecheck38packages and build19packages passed. Root tests40/41tasks passed, with API17902passed and one timeout in an unchanged test; that entire file passed12/12 on retry. Type-boundary ratchet has zero blocking findings. Current-head CI is tracked separately before merge. -All11 earlier Codex findings were fixed with focused regressions and resolved threads. Four additional findings (interrupted Compose replacement, bundled-store restore bootstrap, completion-journal durability and conditional IAM ownership) are fixed with discriminating retries; final review reconciliation is recorded in PR2918. No further Codex request is required by the coordinator. CodeRabbit was requested through the trusted label workflow at ready23:03UTC Nov19 and returned a review-limit/rate-limit response; the wait ended on that response, with no CodeRabbit finding or waiver. +All11 earlier Codex findings were fixed with focused regressions and resolved threads. Five additional findings (interrupted Compose replacement, bundled-store restore bootstrap, completion-journal durability, conditional IAM ownership and the target health-command domain) are fixed with discriminating retries; final review reconciliation is recorded in PR2918. No further Codex request is required by the coordinator. CodeRabbit was requested through the trusted label workflow at ready23:03UTC Nov19 and returned a review-limit/rate-limit response; the wait ended on that response, with no CodeRabbit finding or waiver. ## BOX evidence and cleanup @@ -73,6 +73,8 @@ Main L23 `860718dc3878095322772c43cc7d385ba35aeb16` was integrated before final The coordinator explicitly accepted that the combined L23+L24 upgrade has not been proven live before merge: this self-host-only integration has no Cloudflare impact. H2’s post-merge BOX smoke on the resulting main supplies the combined live upgrade proof; any upgrade/rollback failure remains this slice owner’s follow-up responsibility. This is an accepted validation gap, not a claim that the combined source is byte-identical to BOX39. +An incremental review also corrected the printed health check to use the shell-quoted target domain read from its private .env, instead of an unexported shell variable. The actual CLI regression clears the shell variable and verifies the emitted target URL; five CLI tests, typecheck and lint pass. Independent security/completion/docs delta review passed; operation and data algorithms are unchanged. + ## Post-mortem Plaintext backups, missing rollback/history validation and name-based lifecycle assumptions were unsafe. Real SDK failure evidence replaced the unconfirmed tracker hypothesis. Real disposable execution exposed read-only cache cleanup and executable-mode loss; both have discriminating regressions. Review added clone identity isolation, inactive restore deployment, durable retries, exact backup deletion proof and retained-key retry ownership. Clean CI exposed an unbuilt workspace-package dependency that locally built output had hidden; the full suite now proves source resolution with that output absent. From 28953218671e7306bcbab17b0ff53f3c3ad27f33 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rapha=C3=ABl=20Titsworth-Morin?= Date: Fri, 20 Nov 2026 02:05:18 +0000 Subject: [PATCH 13/17] fix(selfhost): persist IAM grant ownership before cloud mutation --- deploy/selfhost/README.md | 24 ++ deploy/selfhost/created-resources.d.mts | 5 + deploy/selfhost/created-resources.mjs | 92 +++++- deploy/selfhost/gcp-bootstrap.sh | 12 +- scripts/selfhost/gcp-bootstrap-intent.test.ts | 299 ++++++++++++++++++ scripts/selfhost/teardown-gcp-bootstrap.ts | 6 + scripts/selfhost/testdata/fake-gcloud-iam.mjs | 13 +- .../2026-11-19-l24-selfhost-operations.md | 10 +- 8 files changed, 450 insertions(+), 11 deletions(-) create mode 100644 scripts/selfhost/gcp-bootstrap-intent.test.ts diff --git a/deploy/selfhost/README.md b/deploy/selfhost/README.md index d6655136e3..df41f0b563 100644 --- a/deploy/selfhost/README.md +++ b/deploy/selfhost/README.md @@ -306,6 +306,30 @@ other VM users; it preserves shared or legacy rules (`deploy/selfhost/gcp-bootst `scripts/selfhost/teardown-gcp.ts:firewallItems`). Keep `.state/created-resources.json` after a partial teardown: it is the receipt used to resume cleanup. +Keep that receipt after interrupted bootstrap too: project and service-account IAM grants have +an exact, durable intent before mutation, so retrying can preserve their creation proof +(`deploy/selfhost/created-resources.mjs:grantIntent`, `gcp-bootstrap.sh:record_resource`). +Pool, provider, service-account and optional firewall creation still have a post-create receipt +window: interruption before the receipt is saved can leave an unrecorded resource that retry +preserves as reused. Teardown will not adopt it. Inspect these public inventories in the node +project before manual cleanup: + +```sh +gcloud iam workload-identity-pools list --project --location global --show-deleted +gcloud iam workload-identity-pools providers list --project --location global --workload-identity-pool --show-deleted +gcloud iam service-accounts list --project +gcloud compute firewall-rules list --project +``` + +Cross-check immutable IDs, issuer/description, creation time and the creator in Cloud Audit Logs +against your setup; a familiar name is insufficient. Inspect pool providers, account grants/keys +and firewall users before deleting anything. Remove only resources you can prove this install +created and exclusively uses; retain ambiguous/shared resources for inspection. A leftover +bootstrap firewall retains its original target tags, source ranges and TCP ports: agent ingress +8080/8443 from the selected ranges, or public app ingress 80/443. It does not widen them, but it +continues admitting matching traffic until you remove the proven-owned rule. These limitations +follow the create/describe/record sequence in `deploy/selfhost/gcp-bootstrap.sh`. + ## Image builds `caddy` and `sam-mx` are built on the box; every other image is pulled by digest. Builds are diff --git a/deploy/selfhost/created-resources.d.mts b/deploy/selfhost/created-resources.d.mts index aefeb54221..96dad75288 100644 --- a/deploy/selfhost/created-resources.d.mts +++ b/deploy/selfhost/created-resources.d.mts @@ -30,3 +30,8 @@ export function markRemoved( name: string, now?: Date ): void; + +export function grantIntent( + file: string, + entry: Omit +): void; diff --git a/deploy/selfhost/created-resources.mjs b/deploy/selfhost/created-resources.mjs index 0d9091971e..0eb6291b79 100644 --- a/deploy/selfhost/created-resources.mjs +++ b/deploy/selfhost/created-resources.mjs @@ -21,7 +21,18 @@ // created-resources.mjs add [k=v ...] // created-resources.mjs list -> kindnameactionremovedAt // created-resources.mjs removed -import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs'; +import { randomUUID } from 'node:crypto'; +import { + closeSync, + existsSync, + fsyncSync, + mkdirSync, + openSync, + readFileSync, + renameSync, + rmSync, + writeSync, +} from 'node:fs'; import { dirname } from 'node:path'; export const FORMAT = 'sam-created-resources/1'; @@ -62,9 +73,78 @@ export function readRecord(file) { function writeRecord(file, record) { mkdirSync(dirname(file), { recursive: true, mode: 0o700 }); - const tmp = `${file}.tmp-${process.pid}`; - writeFileSync(tmp, `${JSON.stringify(record, null, 2)}\n`, { mode: 0o600 }); + const tmp = `${file}.tmp-${process.pid}-${randomUUID()}`; + const fd = openSync(tmp, 'wx', 0o600); + try { + const data = Buffer.from(`${JSON.stringify(record, null, 2)}\n`); + let offset = 0; + while (offset < data.length) { + const count = writeSync(fd, data, offset, data.length - offset); + if (!count) throw new Error('Cannot persist resource receipt'); + offset += count; + } + fsyncSync(fd); + } catch (error) { + rmSync(tmp, { force: true }); + throw error; + } finally { + closeSync(fd); + } renameSync(tmp, file); + const parent = openSync(dirname(file), 'r'); + try { + fsyncSync(parent); + } finally { + closeSync(parent); + } +} + +/** Absence was checked before an exact unconditional IAM mutation; retain that intent on retry. */ +export function grantIntent(file, entry) { + const attrs = entry.attributes ?? {}; + const required = [ + 'project', + 'install', + 'identity', + 'pool', + 'environment', + 'installation', + 'account', + 'member', + 'role', + 'condition', + ]; + if ( + entry.cloud !== 'gcp' || + entry.createdBy !== 'gcp-bootstrap' || + !['created', 'reused'].includes(entry.action) || + !['iam-binding', 'service-account-iam-binding'].includes(entry.kind) || + required.some((key) => typeof attrs[key] !== 'string' || !attrs[key]) || + attrs.condition !== 'None' + ) + throw new Error('Incomplete unconditional IAM grant intent'); + const prior = readRecord(file).resources.find( + (r) => r.cloud === entry.cloud && r.kind === entry.kind && r.name === entry.name + ); + if (prior && !prior.removedAt) { + if ( + (prior.attributes?.grantPending && + prior.attributes.grantPending !== 'unconditional-grant/1') || + prior.createdBy !== entry.createdBy || + required.some( + (key) => + (prior.attributes?.[key] ?? (key === 'condition' ? 'None' : undefined)) !== attrs[key] + ) + ) + throw new Error('IAM grant identity or ownership scope changed; refusing intent adoption'); + // A present preexisting grant stays reused. An observed absent grant is a new creation. + if (prior.action === 'created') entry.action = 'created'; + } + entry.attributes = { + ...attrs, + grantPending: entry.action === 'created' ? 'unconditional-grant/1' : '', + }; + addResource(file, entry); } /** @@ -125,7 +205,7 @@ export function markRemoved(file, cloud, kind, name, now = new Date()) { if (import.meta.url === `file://${process.argv[1]}`) { const [command, file, ...rest] = process.argv.slice(2); try { - if (command === 'add') { + if (command === 'add' || command === 'grant-intent') { const [cloud, kind, name, action, createdBy, ...pairs] = rest; if (!cloud || !kind || !name || !['created', 'reused'].includes(action) || !createdBy) { throw new Error( @@ -135,7 +215,9 @@ if (import.meta.url === `file://${process.argv[1]}`) { const attributes = Object.fromEntries( pairs.map((pair) => [pair.slice(0, pair.indexOf('=')), pair.slice(pair.indexOf('=') + 1)]) ); - addResource(file, { cloud, kind, name, attributes, createdBy, action }); + const entry = { cloud, kind, name, attributes, createdBy, action }; + if (command === 'grant-intent') grantIntent(file, entry); + else addResource(file, entry); } else if (command === 'list') { const [cloud, createdBy] = rest; for (const r of readRecord(file).resources) { diff --git a/deploy/selfhost/gcp-bootstrap.sh b/deploy/selfhost/gcp-bootstrap.sh index caebc0a829..b555f191d8 100755 --- a/deploy/selfhost/gcp-bootstrap.sh +++ b/deploy/selfhost/gcp-bootstrap.sh @@ -157,10 +157,14 @@ command -v gcloud >/dev/null 2>&1 || die "gcloud is not installed or not on PATH # creation proof; teardown will preserve resources that existed before this install. record_resource() { local resource_kind="$1" resource_name="$2" resource_action="$3" resource_identity="$4" - local resource_member="${5:-}" resource_role="${6:-}" + local resource_member="${5:-}" resource_role="${6:-}" resource_operation="${7:-add}" + local grant_attributes=() + if [[ "$resource_kind" == iam-binding || "$resource_kind" == service-account-iam-binding ]]; then + grant_attributes=("condition=None" "grantPending=") + fi [[ "$DRY_RUN" -eq 0 && -n "$INSTALLATION_ID" ]] || return 0 - node "$SCRIPT_DIR/created-resources.mjs" add "$STATE_DIR/created-resources.json" gcp "$resource_kind" "$resource_name" "$resource_action" gcp-bootstrap \ - "project=$PROJECT" "install=$ISSUER" "identity=$resource_identity" "pool=$POOL_ID" "environment=selfhost" "installation=$INSTALLATION_ID" "account=$SA_EMAIL" "member=$resource_member" "role=$resource_role" + node "$SCRIPT_DIR/created-resources.mjs" "$resource_operation" "$STATE_DIR/created-resources.json" gcp "$resource_kind" "$resource_name" "$resource_action" gcp-bootstrap \ + "project=$PROJECT" "install=$ISSUER" "identity=$resource_identity" "pool=$POOL_ID" "environment=selfhost" "installation=$INSTALLATION_ID" "account=$SA_EMAIL" "member=$resource_member" "role=$resource_role" "${grant_attributes[@]}" } # The OIDC provider trusts the issuer the install advertises: check it before trusting it. @@ -396,6 +400,7 @@ for role in "${NODE_ROLES[@]}"; do *) die "cannot parse project IAM policy" ;; esac fi + record_resource iam-binding "projects/$PROJECT#$role#serviceAccount:$SA_EMAIL" "$grant_action" "${sa_identity:-}" "serviceAccount:$SA_EMAIL" "$role" grant-intent change_retry projects add-iam-policy-binding "$PROJECT" --member="serviceAccount:${SA_EMAIL}" \ --role="$role" --condition=None --quiet --format=none if [[ "$DRY_RUN" -eq 0 && -n "$INSTALLATION_ID" ]]; then @@ -424,6 +429,7 @@ if [[ "$DRY_RUN" -eq 0 && -n "$INSTALLATION_ID" && "$sa_existed" -eq 1 ]]; then *) die "cannot parse service account IAM policy" ;; esac fi +record_resource service-account-iam-binding "$SA_EMAIL#roles/iam.workloadIdentityUser#$POOL_PRINCIPAL" "$sa_grant_action" "${sa_identity:-}" "$POOL_PRINCIPAL" roles/iam.workloadIdentityUser grant-intent change_retry iam service-accounts add-iam-policy-binding "$SA_EMAIL" --project="$PROJECT" \ --role=roles/iam.workloadIdentityUser --member="$POOL_PRINCIPAL" \ --condition=None --quiet --format=none diff --git a/scripts/selfhost/gcp-bootstrap-intent.test.ts b/scripts/selfhost/gcp-bootstrap-intent.test.ts new file mode 100644 index 0000000000..fcce66c31e --- /dev/null +++ b/scripts/selfhost/gcp-bootstrap-intent.test.ts @@ -0,0 +1,299 @@ +/** Actual bash interruption after IAM side effects must retain pre-mutation creation proof. */ +import { spawnSync } from 'node:child_process'; +import { + chmodSync, + existsSync, + mkdirSync, + mkdtempSync, + readFileSync, + rmSync, + writeFileSync, +} from 'node:fs'; +import { join, resolve } from 'node:path'; + +import { afterEach, beforeEach, expect, it, vi } from 'vitest'; + +import { grantIntent, readRecord } from '../../deploy/selfhost/created-resources.mjs'; +import type { TeardownContext } from './teardown-box'; +import { bootstrapItems } from './teardown-gcp-bootstrap'; +import { execute } from './teardown-model'; +const script = resolve(import.meta.dirname, '../../deploy/selfhost/gcp-bootstrap.sh'); +const fake = resolve(import.meta.dirname, 'testdata/fake-gcloud-iam.mjs'); +const issuer = 'https://api.intent.example.com', + project = 'sam-vm-test'; +const account = `sam-nodes@${project}.iam.gserviceaccount.com`; +let root: string, bin: string, ledger: string, hook: string; +vi.setConfig({ testTimeout: 60_000 }); +beforeEach(() => { + mkdirSync(resolve('.tmp'), { recursive: true }); + root = mkdtempSync(resolve('.tmp/bootstrap-intent-')); + bin = join(root, 'bin'); + mkdirSync(bin); + ledger = join(root, 'receipts'); + hook = join(root, 'fault.mjs'); + writeFileSync(join(bin, 'gcloud'), `#!/usr/bin/env bash\nexec node '${fake}' "$@"\n`); + writeFileSync( + join(bin, 'curl'), + `#!/usr/bin/env bash\nprintf '%s' '{"issuer":"${issuer}","jwks_uri":"${issuer}/.well-known/jwks.json"}'\n` + ); + chmodSync(join(bin, 'gcloud'), 0o755); + chmodSync(join(bin, 'curl'), 0o755); + writeFileSync( + hook, + `import fs from 'node:fs'; import {syncBuiltinESMExports} from 'node:module'; +const rename=fs.renameSync,sync=fs.fsyncSync; +fs.renameSync=function(a,b){if(process.argv[2]==='add'&&process.argv[5]===process.env.FAULT_KIND&&process.env.FAULT==='receipt')throw Error('Injected final receipt failure');return rename(a,b)}; +fs.fsyncSync=function(fd){if(process.argv[2]==='grant-intent'&&process.argv[5]===process.env.FAULT_KIND&&((process.env.FAULT==='file-sync'&&fs.fstatSync(fd).isFile())||(process.env.FAULT==='parent-sync'&&fs.fstatSync(fd).isDirectory())))throw Error('Injected intent sync failure');return sync(fd)}; +syncBuiltinESMExports();` + ); +}); +afterEach(() => rmSync(root, { recursive: true, force: true })); +function run(extra: NodeJS.ProcessEnv = {}, receipts = true) { + return spawnSync( + 'bash', + [ + script, + '--project', + project, + '--api-url', + issuer, + ...(receipts ? ['--installation-id', 'a'.repeat(32), '--state-dir', ledger] : []), + ], + { + encoding: 'utf8', + env: { + ...process.env, + PATH: `${bin}:${process.env.PATH}`, + STATE: root, + GCP_BOOTSTRAP_RETRY_SECONDS: '0', + ...extra, + }, + } + ); +} +function seed(kind: string, absent = true) { + expect(run({}, false).status).toBe(0); + const db = JSON.parse(readFileSync(join(root, 'gcp.json'), 'utf8')); + if (absent) { + if (kind === 'iam-binding') db.bindings = []; + else db.saBindings = {}; + } + writeFileSync(join(root, 'gcp.json'), JSON.stringify(db)); +} +function grant(kind: string) { + return readRecord(join(ledger, 'created-resources.json')).resources.find((r) => r.kind === kind); +} +function prefix(kind: string) { + return kind === 'iam-binding' + ? 'projects add-iam-policy-binding' + : 'iam service-accounts add-iam-policy-binding'; +} +it.each(['iam-binding', 'service-account-iam-binding'])( + 'retains %s after killed grant or failed final receipt and reconciles retries', + (kind) => { + for (const fault of ['kill', 'receipt']) { + if (existsSync(join(root, 'gcp.json'))) { + rmSync(join(root, 'gcp.json')); + rmSync(ledger, { recursive: true, force: true }); + rmSync(join(root, 'grant-effect'), { force: true }); + } + seed(kind); + const first = run( + fault === 'kill' + ? { FAKE_GCLOUD_AFTER_GRANT: prefix(kind), FAKE_GCLOUD_GRANT_FAILURE: 'kill' } + : { NODE_OPTIONS: `--import=${hook}`, FAULT: fault, FAULT_KIND: kind } + ); + expect(first.status, first.stderr).not.toBe(0); + expect(grant(kind)?.action).toBe('created'); + expect(grant(kind)?.attributes?.grantPending).toBe('unconditional-grant/1'); + const retried = run(); + expect(retried.status, retried.stderr).toBe(0); + expect(grant(kind)?.action).toBe('created'); + expect(grant(kind)?.attributes?.grantPending).toBe(''); + } + } +); +it.each(['iam-binding', 'service-account-iam-binding'])( + 'persists %s intent before mutation and refuses invalid retry scope', + (kind) => { + seed(kind); + const first = run({ FAKE_GCLOUD_AFTER_GRANT: prefix(kind), FAKE_GCLOUD_GRANT_FAILURE: 'kill' }); + expect(first.status).not.toBe(0); + const file = join(ledger, 'created-resources.json'), + original = readFileSync(file, 'utf8'); + for (const field of [ + 'identity', + 'installation', + 'project', + 'member', + 'role', + 'condition', + 'grantPending', + ]) { + const record = JSON.parse(original); + record.resources.find((r: { kind: string }) => r.kind === kind).attributes[field] = 'foreign'; + writeFileSync(file, JSON.stringify(record)); + const before = readFileSync(join(root, 'calls'), 'utf8').length; + const rejected = run(); + expect(rejected.status, rejected.stderr).not.toBe(0); + expect(readFileSync(join(root, 'calls'), 'utf8').slice(before)).not.toContain(prefix(kind)); + } + writeFileSync(file, original); + const db = JSON.parse(readFileSync(join(root, 'gcp.json'), 'utf8')); + db.accounts[account].uniqueId = 'replacement'; + writeFileSync(join(root, 'gcp.json'), JSON.stringify(db)); + expect(run().status).not.toBe(0); + } +); +it.each(['file-sync', 'parent-sync'])( + 'failed %s prevents the project mutation; exact retry succeeds', + (fault) => { + seed('iam-binding'); + const before = readFileSync(join(root, 'calls'), 'utf8').length; + const failed = run({ + NODE_OPTIONS: `--import=${hook}`, + FAULT: fault, + FAULT_KIND: 'iam-binding', + }); + expect(failed.status).not.toBe(0); + expect(readFileSync(join(root, 'calls'), 'utf8').slice(before)).not.toContain( + prefix('iam-binding') + ); + expect(run().status).toBe(0); + expect(grant('iam-binding')?.action).toBe('created'); + } +); +it.each(['iam-binding', 'service-account-iam-binding'])( + 'never adopts a preexisting %s and tolerates a lost success response', + (kind) => { + seed(kind, false); + const result = run({ FAKE_GCLOUD_AFTER_GRANT: prefix(kind) }); + expect(result.status, result.stderr).toBe(0); + expect(grant(kind)?.action).toBe('reused'); + expect(run().status).toBe(0); + expect(grant(kind)?.action).toBe('reused'); + const db = JSON.parse(readFileSync(join(root, 'gcp.json'), 'utf8')); + if (kind === 'iam-binding') db.bindings = []; + else db.saBindings = {}; + writeFileSync(join(root, 'gcp.json'), JSON.stringify(db)); + expect(run().status).toBe(0); + expect(grant(kind)?.action).toBe('created'); // A later observed absence permits a fresh owned creation. + } +); + +it('rejects unsupported direct grant actions before persisting an intent', () => { + const entry = { + cloud: 'gcp', + kind: 'iam-binding', + name: 'grant', + action: 'invalid', + createdBy: 'gcp-bootstrap', + attributes: { + project, + install: issuer, + identity: '123456789', + pool: 'pool', + environment: 'selfhost', + installation: 'a'.repeat(32), + account, + member: `serviceAccount:${account}`, + role: 'roles/compute.securityAdmin', + condition: 'None', + }, + }; + expect(() => + Reflect.apply(grantIntent, undefined, [join(ledger, 'created-resources.json'), entry]) + ).toThrow(/Incomplete/); + expect(existsSync(join(ledger, 'created-resources.json'))).toBe(false); +}); +it.each(['iam-binding', 'service-account-iam-binding'])( + 'refuses an explicit conditional %s receipt before provider access', + (kind) => { + seed(kind); + expect(run().status).toBe(0); + const file = join(ledger, 'created-resources.json'); + const record = readRecord(file); + const receipt = record.resources.find((r) => r.kind === kind)!; + receipt.attributes = { ...receipt.attributes, condition: 'request.time < timestamp(...)' }; + const provider = vi.fn(() => ({ status: 0, stdout: '', stderr: '' })); + const ctx: TeardownContext = { + box: {}, + stateDir: ledger, + envFile: join(root, 'env'), + composeFiles: [], + recordFile: file, + record: record.resources, + selfhostDir: root, + domain: 'intent.example.com', + installationId: 'a'.repeat(32), + now: Date.now, + log: () => undefined, + options: { destroyKey: false, deleteBackups: false, adoptDiscovered: false, gcpProjects: [] }, + run: provider, + }; + const items = bootstrapItems(ctx, project).filter( + (item) => item.id === `gcp:${kind}:${receipt.name}` + ); + expect(execute(items, 'remove-everything', file)[0]?.status).toBe('failed'); + expect(provider).not.toHaveBeenCalled(); + } +); + +it.each(['iam-binding', 'service-account-iam-binding'])( + 'teardown settles a durable but absent %s intent without deleting its conditional sibling', + (kind) => { + seed(kind); + const interrupted = run({ + NODE_OPTIONS: `--import=${hook}`, + FAULT: 'parent-sync', + FAULT_KIND: kind, + }); + expect(interrupted.status).not.toBe(0); + const file = join(ledger, 'created-resources.json'); + const record = readRecord(file), + receipt = record.resources.find((r) => r.kind === kind)!; + expect(receipt.attributes?.grantPending).toBe('unconditional-grant/1'); + const provider = vi.fn((_command: string, args: string[]) => ({ + status: 0, + stderr: '', + stdout: JSON.stringify( + args.includes('describe') + ? { uniqueId: receipt.attributes?.identity } + : { + bindings: [ + { + role: receipt.attributes?.role, + members: [receipt.attributes?.member], + condition: { expression: 'true' }, + }, + ], + } + ), + })); + const ctx: TeardownContext = { + box: {}, + stateDir: ledger, + envFile: join(root, 'env'), + composeFiles: [], + recordFile: file, + record: record.resources, + selfhostDir: root, + domain: 'intent.example.com', + installationId: 'a'.repeat(32), + now: Date.now, + log: () => undefined, + options: { destroyKey: false, deleteBackups: false, adoptDiscovered: false, gcpProjects: [] }, + run: provider, + }; + const items = bootstrapItems(ctx, project).filter( + (item) => item.id === `gcp:${kind}:${receipt.name}` + ); + expect(execute(items, 'remove-everything', file)[0]?.status).toBe('removed'); + expect(provider.mock.calls.some(([, args]) => args.includes('remove-iam-policy-binding'))).toBe( + false + ); + expect( + readRecord(file).resources.find((r) => r.name === receipt.name)?.removedAt + ).toBeDefined(); + } +); diff --git a/scripts/selfhost/teardown-gcp-bootstrap.ts b/scripts/selfhost/teardown-gcp-bootstrap.ts index 3f80b782d1..7a0e60b45e 100644 --- a/scripts/selfhost/teardown-gcp-bootstrap.ts +++ b/scripts/selfhost/teardown-gcp-bootstrap.ts @@ -221,6 +221,12 @@ function assertAccountExclusive( function bootstrapOperation(entry: CreatedResource, project: string, issuer: string) { const attrs = entry.attributes ?? {}; + if ( + ['iam-binding', 'service-account-iam-binding'].includes(entry.kind) && + attrs.condition !== undefined && + attrs.condition !== 'None' + ) + throw new Error('Refused: grant receipt does not prove an unconditional binding'); const pool = attrs.pool; const where = [`--project=${project}`]; let describe: string[]; diff --git a/scripts/selfhost/testdata/fake-gcloud-iam.mjs b/scripts/selfhost/testdata/fake-gcloud-iam.mjs index 59282c741b..0b1dc6b5c9 100644 --- a/scripts/selfhost/testdata/fake-gcloud-iam.mjs +++ b/scripts/selfhost/testdata/fake-gcloud-iam.mjs @@ -12,7 +12,18 @@ const file = join(STATE, 'gcp.json'); const db = existsSync(file) ? JSON.parse(readFileSync(file, 'utf8')) : { pools: {}, providers: {}, accounts: {}, bindings: [] }; -const save = () => writeFileSync(file, JSON.stringify(db, null, 2)); +const save = () => { + writeFileSync(file, JSON.stringify(db, null, 2)); + if ( + process.env.FAKE_GCLOUD_AFTER_GRANT && + cmd.startsWith(process.env.FAKE_GCLOUD_AFTER_GRANT) && + !existsSync(join(STATE, 'grant-effect')) + ) { + writeFileSync(join(STATE, 'grant-effect'), cmd); + if (process.env.FAKE_GCLOUD_GRANT_FAILURE === 'kill') process.kill(process.ppid, 'SIGKILL'); + else process.exit(1); + } +}; const flag = (name) => { const hit = args.find((a) => a.startsWith(`--${name}=`)); if (hit) return hit.slice(name.length + 3); diff --git a/tasks/archive/2026-11-19-l24-selfhost-operations.md b/tasks/archive/2026-11-19-l24-selfhost-operations.md index b559e18efa..c7c8175c12 100644 --- a/tasks/archive/2026-11-19-l24-selfhost-operations.md +++ b/tasks/archive/2026-11-19-l24-selfhost-operations.md @@ -69,12 +69,18 @@ Teardown durably records original Docker inventories, key-removal authorization Final Codex review identified a conditional project IAM binding misclassified as reused before `--condition=None` adds an unconditional grant. Bootstrap now validates binding/condition shapes and marks only an existing unconditional grant as reused. Teardown removes only the receipted unconditional member/role, leaving conditional siblings unchanged; lost-success retries recognize that exact unconditional grant as absent. Nine actual bash controls cover conditional-only, unconditional and malformed/unparsable policy cases, with independent security delta PASS. The existing bootstrap test fixture now uses exact cleaned `.tmp` roots. -Main L23 `860718dc3878095322772c43cc7d385ba35aeb16` was integrated before final CI, preserving fence fingerprint/force recreation and filtering image rebuilds against old active services. Integration exposed its exited data-owner helper retaining Docker’s cache-volume reference; recovery requires exact owned-helper cleanup before deleting that cache. Real Docker helper recovery (one test) and canonical local MinIO (three tests) pass with owned resources cleaned. The final combined suite passes973tests across55files, with four conditional skips; TypeScript, lint, formatting and secret scanner pass. The test fixtures model the new helper metadata boundary and follow canonical-project setup before repeated init. +Main L23 `860718dc3878095322772c43cc7d385ba35aeb16` was integrated before final CI, preserving fence fingerprint/force recreation and filtering image rebuilds against old active services. Integration exposed its exited data-owner helper retaining Docker’s cache-volume reference; recovery requires exact owned-helper cleanup before deleting that cache. Real Docker helper recovery (one test) and canonical local MinIO (three tests) pass with owned resources cleaned. The final combined suite passes986tests across56files, with four conditional skips; TypeScript, lint, formatting and secret scanner pass. The test fixtures model the new helper metadata boundary and follow canonical-project setup before repeated init. -The coordinator explicitly accepted that the combined L23+L24 upgrade has not been proven live before merge: this self-host-only integration has no Cloudflare impact. H2’s post-merge BOX smoke on the resulting main supplies the combined live upgrade proof; any upgrade/rollback failure remains this slice owner’s follow-up responsibility. This is an accepted validation gap, not a claim that the combined source is byte-identical to BOX39. +The coordinator explicitly accepted that the combined L23+L24 upgrade has not been proven live before merge: this self-host-only integration has no Cloudflare impact. **Owed: coordinator post-merge combined smoke**, tracked on landing idea01M72M9AEB933ZY8269D376DKC: after both H2 #2907 and L24 #2918 are on main, upgrade from the then-current BOX state to main, recreate the fence, verify health and trigger one rollback. Real Docker and MinIO remain the pre-merge proof; any upgrade/rollback failure remains this slice owner’s follow-up responsibility. This is an accepted validation gap, not a claim that the combined source is byte-identical to BOX39. An incremental review also corrected the printed health check to use the shell-quoted target domain read from its private .env, instead of an unexported shell variable. The actual CLI regression clears the shell variable and verifies the emitted target URL; five CLI tests, typecheck and lint pass. Independent security/completion/docs delta review passed; operation and data algorithms are unchanged. +## Durable grant intent review delta + +Project and service-account IAM mutations now persist exact unconditional grant intent before cloud mutation using the existing ownership ledger. File sync, atomic rename and parent sync complete first. Interrupted or lost-success retries preserve created ownership; preexisting grants remain reused. Changed scope/account identity, malformed pending intent and explicit conditional teardown receipts refuse. Thirteen new controls cover actual bash termination after side effects, final receipt failure, sync failures before cloud mutation, safe retry/recreation and conditional sibling preservation. Full self-host validation: 986 passed, four conditional skips, 56 files; TypeScript, lint, format and secret scanner pass. Independent security review found no blocker. + +The coordinator explicitly deferred the pre-existing pool/provider/service-account/firewall post-create receipt windows to backlog idea 01M7VB4538WSGP3QBP8EBDVTZA. README teardown now lists manual inventories and requires immutable identity, audit-log and exclusive-use proof. Such resources are preserved rather than destructively adopted. A leaked firewall retains precisely the configured source ranges, target tags and ports; interruption cannot broaden them, though their original exposure persists until proven-owned cleanup. + ## Post-mortem Plaintext backups, missing rollback/history validation and name-based lifecycle assumptions were unsafe. Real SDK failure evidence replaced the unconfirmed tracker hypothesis. Real disposable execution exposed read-only cache cleanup and executable-mode loss; both have discriminating regressions. Review added clone identity isolation, inactive restore deployment, durable retries, exact backup deletion proof and retained-key retry ownership. Clean CI exposed an unbuilt workspace-package dependency that locally built output had hidden; the full suite now proves source resolution with that output absent. From 53ca7780daa869d63f1121137cab305599c49f56 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rapha=C3=ABl=20Titsworth-Morin?= Date: Fri, 20 Nov 2026 03:07:47 +0000 Subject: [PATCH 14/17] test(selfhost): handle restore overloads in scanner controls --- scripts/quality/operator-backup-exceptions.test.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/scripts/quality/operator-backup-exceptions.test.ts b/scripts/quality/operator-backup-exceptions.test.ts index d953d4ea2d..ec02282815 100644 --- a/scripts/quality/operator-backup-exceptions.test.ts +++ b/scripts/quality/operator-backup-exceptions.test.ts @@ -17,7 +17,7 @@ const scan = (file: string, text: string) => scanText(file, text, () => false).f function removeGuard(text: string, name: string): string { const source = ts.createSourceFile('operator.ts', text, ts.ScriptTarget.Latest, true); const fn = source.statements.find( - (s) => ts.isFunctionDeclaration(s) && s.name?.text === name + (s) => ts.isFunctionDeclaration(s) && s.name?.text === name && s.body !== undefined ) as ts.FunctionDeclaration; const guard = fn.body!.statements[0]; expect(guard.getText(source)).toBe('assertOperatorExecution();'); @@ -78,7 +78,7 @@ describe('L24 operator-only backup scanner exception (policy 795e72a6)', () => { expect(scan(file, attached).some((f) => f.rule === 'decryption')).toBe(true); expect( - scan(file, text.replace(`function ${fn}(`, 'function differentFunction(')).some( + scan(file, text.replaceAll(`function ${fn}(`, 'function differentFunction(')).some( (f) => f.rule === 'decryption' ) ).toBe(true); From 0755f69d63173b89364a52e55e4f353bb107adf0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rapha=C3=ABl=20Titsworth-Morin?= Date: Fri, 20 Nov 2026 04:01:39 +0000 Subject: [PATCH 15/17] fix(selfhost): resume interrupted rollback state swaps --- deploy/selfhost/README.md | 5 + scripts/selfhost/backup-recovery.ts | 27 +- scripts/selfhost/rollback-state.ts | 266 +++++++++++++++ scripts/selfhost/upgrade-lib.ts | 3 + scripts/selfhost/upgrade-rollback-cli.test.ts | 314 ++++++++++++++---- scripts/selfhost/upgrade-rollback.ts | 2 + .../2026-11-19-l24-selfhost-operations.md | 8 + 7 files changed, 532 insertions(+), 93 deletions(-) create mode 100644 scripts/selfhost/rollback-state.ts diff --git a/deploy/selfhost/README.md b/deploy/selfhost/README.md index cc2cd8ce23..fbe9869df2 100644 --- a/deploy/selfhost/README.md +++ b/deploy/selfhost/README.md @@ -237,6 +237,11 @@ snapshot and key, and retry the same resolved target to recover the original ins `--to`, a moved branch/tag, or an older journal without a target requires the explicit rollback command before choosing another target. Do not delete the pending record to bypass a failed recovery. +Rollback also keeps a private sibling `..rollback-state.json` receipt +while replacing local state. Retry reconciles an interrupted directory swap before reading +installation metadata, and refuses changed directory identities. Keep that receipt and its +recorded `.rollback-state-*` directory together until recovery finishes; do not remove them +manually. After a successful upgrade, its printed rollback command restores the populated installation in place. Run it from the upgraded checkout, keeping the original full commit SHA, snapshot, diff --git a/scripts/selfhost/backup-recovery.ts b/scripts/selfhost/backup-recovery.ts index 79e762d0bc..b35b47a557 100644 --- a/scripts/selfhost/backup-recovery.ts +++ b/scripts/selfhost/backup-recovery.ts @@ -1,13 +1,5 @@ /** Restore an upgrade's authenticated snapshot to the same owned installation. */ -import { - cpSync, - existsSync, - lstatSync, - mkdtempSync, - readFileSync, - renameSync, - rmSync, -} from 'node:fs'; +import { cpSync, existsSync, lstatSync, mkdtempSync, readFileSync, rmSync } from 'node:fs'; import { dirname, join, resolve } from 'node:path'; import { readRecord } from '../../deploy/selfhost/created-resources.mjs'; @@ -29,7 +21,7 @@ import { readManifest, STATE_DIR, } from './backup-lib'; -import { composeProjectFor, recordInstall, SELFHOST_ENVIRONMENT } from './install-record'; +import { composeProjectFor, SELFHOST_ENVIRONMENT } from './install-record'; import { assertOperatorExecution } from './operator-only'; import { removePrivateTree } from './private-tree'; import { @@ -44,6 +36,7 @@ import { cacheStartTime, recoverCacheStart, } from './rollback-cache-transition'; +import { publishRollbackState, recoverRollbackState, rollbackStatePending } from './rollback-state'; import { assertPrivateFile, replacePrivateFile } from './secret-files'; import { assertRollbackReady } from './upgrade-preflight'; function compose(ctx: BoxContext, args: string[]): void { @@ -342,7 +335,6 @@ function restoreState( ): void { const stage = mkdtempSync(join(dirname(ctx.stateDir), '.rollback-state-')); const staged = join(stage, 'restored'); - const previous = join(stage, 'previous'); try { cpSync(source, staged, { recursive: true }); // Keep the original upgrade's recovery pointer until recoverUpgrade verifies health. @@ -360,17 +352,9 @@ function restoreState( JSON.stringify({ ...pending, snapshot: resolve(from) }) ); replacePrivateFile(join(staged, 'created-resources.json'), currentLedger(ctx, id)); - renameSync(ctx.stateDir, previous); - try { - renameSync(staged, ctx.stateDir); - recordInstall(ctx.stateDir, ctx.envFile, ctx.box, id); - } catch (error) { - rmSync(ctx.stateDir, { recursive: true, force: true }); - renameSync(previous, ctx.stateDir); - throw error; - } + publishRollbackState(ctx, stage, id); } finally { - removePrivateTree(stage); + if (!rollbackStatePending(ctx)) removePrivateTree(stage); } } @@ -380,6 +364,7 @@ function restoreState( */ export function runRollback(ctx: BoxContext, from: string, expectedSamCommit?: string): void { assertOperatorExecution(); + recoverRollbackState(ctx); const key = backupKey(ctx); assertBackupOutside(ctx, from); const temp = backupScratch(); diff --git a/scripts/selfhost/rollback-state.ts b/scripts/selfhost/rollback-state.ts new file mode 100644 index 0000000000..4f1b4169ef --- /dev/null +++ b/scripts/selfhost/rollback-state.ts @@ -0,0 +1,266 @@ +/** Durable ownership proof for the two renames that publish restored installation state. */ +import { + closeSync, + constants, + fstatSync, + fsyncSync, + lstatSync, + openSync, + readFileSync, + realpathSync, + renameSync, + rmSync, +} from 'node:fs'; +import { basename, dirname, join, resolve } from 'node:path'; + +import { readRecord } from '../../deploy/selfhost/created-resources.mjs'; +import type { BoxContext } from './backup-lib'; +import { expectedComposeProjectFor, SELFHOST_ENVIRONMENT } from './install-record'; +import { assertOperatorExecution } from './operator-only'; +import { removePrivateTree } from './private-tree'; +import { replacePrivateFile } from './secret-files'; + +type Context = Pick; +interface Identity { + device: string; + inode: string; +} +interface Swap { + version: 1; + scope: string; + installation: string; + stage: string; + stageIdentity: Identity; + original: Identity; + replacement: Identity; +} +function receipt(ctx: Context): string { + return join(dirname(resolve(ctx.stateDir)), `.${basename(ctx.stateDir)}.rollback-state.json`); +} +function scope(ctx: Context): string { + return JSON.stringify([ + resolve(ctx.stateDir), + resolve(ctx.envFile), + ctx.box.SAM_DOMAIN ?? '', + ctx.box.CELLD_BUCKET ?? '', + ]); +} +function identity(path: string): Identity | null { + const info = lstatSync(path, { throwIfNoEntry: false }); + if (!info) return null; + if ( + !info.isDirectory() || + info.isSymbolicLink() || + (process.getuid && info.uid !== process.getuid()) + ) + throw new Error('Rollback state swap refuses a replaced directory'); + return { device: String(info.dev), inode: String(info.ino) }; +} +function same(left: Identity | null, right: Identity): boolean { + return left?.device === right.device && left.inode === right.inode; +} +function isIdentity(value: unknown): value is Identity { + if (!value || typeof value !== 'object') return false; + const v = value as Partial; + return ( + typeof v.device === 'string' && + /^\d+$/.test(v.device) && + typeof v.inode === 'string' && + /^\d+$/.test(v.inode) + ); +} +function syncDirectory(path: string): void { + const fd = openSync(path, 'r'); + try { + fsyncSync(fd); + } finally { + closeSync(fd); + } +} +function assertParent(ctx: Context): void { + const parent = dirname(resolve(ctx.stateDir)); + if (realpathSync(parent) !== parent) + throw new Error('Rollback state swap refuses symlink parents'); +} +function assertLedger(ctx: Context, path: string, id: string, expected: Identity): void { + const record = readRecord(join(path, 'created-resources.json')); + const active = record.resources.filter( + (r) => r.cloud === 'box' && r.action === 'created' && !r.removedAt + ); + const state = active.filter((r) => r.kind === 'state-dir'); + const install = active.filter((r) => r.kind === 'installation'); + if ( + state.length !== 1 || + state[0]?.name !== ctx.stateDir || + state[0]?.attributes?.installation !== id || + state[0]?.attributes?.device !== expected.device || + state[0]?.attributes?.inode !== expected.inode || + install.length !== 1 || + install[0]?.name !== id || + install[0]?.attributes?.domain !== (ctx.box.SAM_DOMAIN ?? '') || + install[0]?.attributes?.environment !== SELFHOST_ENVIRONMENT || + install[0]?.attributes?.composeProject !== expectedComposeProjectFor(ctx.box, ctx.stateDir, id) + ) + throw new Error('Rollback state swap ownership or scope changed'); + let keys: unknown; + try { + keys = JSON.parse(readFileSync(join(path, 'platform-keys.json'), 'utf8')); + } catch { + throw new Error('Cannot verify rollback state swap installation'); + } + if ( + !keys || + typeof keys !== 'object' || + !('SAM_INSTALLATION_ID' in keys) || + keys.SAM_INSTALLATION_ID !== id + ) + throw new Error('Rollback state swap installation changed'); +} + +/** Run before any preflight reads state, including direct recovery/manual rollback calls. */ +export function recoverRollbackState(ctx: Context): void { + assertOperatorExecution(); + const path = receipt(ctx); + const info = lstatSync(path, { throwIfNoEntry: false }); + if (!info) return; + assertParent(ctx); + if ( + !info.isFile() || + info.nlink !== 1 || + info.mode & 0o077 || + (process.getuid && info.uid !== process.getuid()) + ) + throw new Error('Invalid rollback state swap receipt'); + const fd = openSync(path, constants.O_RDONLY | constants.O_NOFOLLOW); + let raw: unknown; + try { + const stat = fstatSync(fd); + if ( + !stat.isFile() || + stat.nlink !== 1 || + stat.mode & 0o077 || + stat.dev !== info.dev || + stat.ino !== info.ino || + (process.getuid && stat.uid !== process.getuid()) + ) + throw new Error('Invalid rollback state swap receipt'); + raw = JSON.parse(readFileSync(fd, 'utf8')); + } finally { + closeSync(fd); + } + if (!raw || typeof raw !== 'object' || Array.isArray(raw)) + throw new Error('Invalid rollback state swap receipt'); + const swap = raw as Partial; + if ( + swap.version !== 1 || + swap.scope !== scope(ctx) || + typeof swap.installation !== 'string' || + !/^[a-f0-9]{32}$/.test(swap.installation) || + typeof swap.stage !== 'string' || + dirname(swap.stage) !== dirname(resolve(ctx.stateDir)) || + !/^\.rollback-state-[a-zA-Z0-9]+$/.test(basename(swap.stage)) || + !isIdentity(swap.stageIdentity) || + !isIdentity(swap.original) || + !isIdentity(swap.replacement) + ) + throw new Error('Invalid rollback state swap scope'); + const staged = join(swap.stage, 'restored'); + const previous = join(swap.stage, 'previous'); + const stage = identity(swap.stage); + if (stage && !same(stage, swap.stageIdentity)) + throw new Error('Rollback state staging directory changed'); + let live = identity(ctx.stateDir); + if (!live) { + if ( + !stage || + !same(identity(previous), swap.original) || + !same(identity(staged), swap.replacement) + ) + throw new Error('Cannot prove interrupted rollback state directories'); + assertLedger(ctx, previous, swap.installation, swap.original); + renameSync(previous, ctx.stateDir); + syncDirectory(swap.stage); + syncDirectory(dirname(ctx.stateDir)); + live = identity(ctx.stateDir); + } + if (!same(live, swap.original) && !same(live, swap.replacement)) + throw new Error('Rollback state directory identity changed'); + assertLedger(ctx, ctx.stateDir, swap.installation, live as Identity); + if (stage) { + const old = identity(previous), + next = identity(staged); + if ((old && !same(old, swap.original)) || (next && !same(next, swap.replacement))) + throw new Error('Rollback state staging contents changed'); + // Cleanup may itself be interrupted. Keep the receipt until cleanup and directory sync finish. + removePrivateTree(swap.stage); + syncDirectory(dirname(ctx.stateDir)); + } + const current = lstatSync(path); + if (current.dev !== info.dev || current.ino !== info.ino || !current.isFile()) + throw new Error('Rollback state swap receipt changed'); + rmSync(path); + syncDirectory(dirname(path)); +} + +/** The caller already authenticated the snapshot and copied live ownership history into staged. */ +export function publishRollbackState(ctx: Context, stage: string, id: string): void { + assertOperatorExecution(); + assertParent(ctx); + const staged = join(stage, 'restored'); + const original = identity(ctx.stateDir), + replacement = identity(staged), + stageIdentity = identity(stage); + if (!original || !replacement || !stageIdentity) + throw new Error('Missing rollback state directory'); + assertLedger(ctx, ctx.stateDir, id, original); + const ledger = readRecord(join(staged, 'created-resources.json')); + const state = ledger.resources.find( + (r) => r.cloud === 'box' && r.kind === 'state-dir' && !r.removedAt + ); + if (!state?.attributes) throw new Error('Missing rollback state ownership'); + state.attributes.device = replacement.device; + state.attributes.inode = replacement.inode; + replacePrivateFile( + join(staged, 'created-resources.json'), + `${JSON.stringify(ledger, null, 2)}\n` + ); + assertLedger(ctx, staged, id, replacement); + syncDirectory(stage); + if (lstatSync(receipt(ctx), { throwIfNoEntry: false })) + throw new Error('Rollback state swap already pending'); + const swap: Swap = { + version: 1, + scope: scope(ctx), + installation: id, + stage, + stageIdentity, + original, + replacement, + }; + replacePrivateFile(receipt(ctx), JSON.stringify(swap)); + if ( + !same(identity(ctx.stateDir), original) || + !same(identity(stage), stageIdentity) || + !same(identity(staged), replacement) + ) + throw new Error('Rollback state swap directory identity changed before publication'); + renameSync(ctx.stateDir, join(stage, 'previous')); + syncDirectory(stage); + syncDirectory(dirname(ctx.stateDir)); + if ( + identity(ctx.stateDir) || + !same(identity(stage), stageIdentity) || + !same(identity(staged), replacement) || + !same(identity(join(stage, 'previous')), original) + ) + throw new Error('Rollback state swap directory identity changed during publication'); + renameSync(staged, ctx.stateDir); + syncDirectory(stage); + syncDirectory(dirname(ctx.stateDir)); + recoverRollbackState(ctx); +} + +/** A published intent owns cleanup; never delete the sole surviving original in a finally block. */ +export function rollbackStatePending(ctx: Context): boolean { + return Boolean(lstatSync(receipt(ctx), { throwIfNoEntry: false })); +} diff --git a/scripts/selfhost/upgrade-lib.ts b/scripts/selfhost/upgrade-lib.ts index 005dd2e559..4d617b93f2 100644 --- a/scripts/selfhost/upgrade-lib.ts +++ b/scripts/selfhost/upgrade-lib.ts @@ -24,6 +24,7 @@ import { composeFilesFor } from './compose-env.js'; import { log, REPO_ROOT, SELFHOST_DIR } from './deploy-steps.js'; import { COMPOSE_PATH, imageRebuilds } from './image-rebuilds.js'; import { assertOperatorExecution } from './operator-only.js'; +import { recoverRollbackState } from './rollback-state.js'; import { assertPrivateFile, replacePrivateFile } from './secret-files.js'; import { composeInputsChanged, @@ -170,6 +171,7 @@ export async function recoverUpgrade( opts: UpgradeOptions ): Promise { assertOperatorExecution(); + recoverRollbackState(ctx); const pendingPath = join(ctx.stateDir, UPGRADE_PENDING_FILE); const to = existsSync(pendingPath) ? pendingUpgradeTarget(JSON.parse(readFileSync(pendingPath, 'utf8'))) @@ -383,6 +385,7 @@ async function rollbackFailedUpgrade( export async function runUpgrade(ctx: BoxContext, opts: UpgradeOptions): Promise { assertOperatorExecution(); + recoverRollbackState(ctx); assertRollbackReady(ctx); const git: Git = (args, what = `git ${args.join(' ')}`) => check(ctx.run('git', args), what); diff --git a/scripts/selfhost/upgrade-rollback-cli.test.ts b/scripts/selfhost/upgrade-rollback-cli.test.ts index eed914feb1..c90be0902f 100644 --- a/scripts/selfhost/upgrade-rollback-cli.test.ts +++ b/scripts/selfhost/upgrade-rollback-cli.test.ts @@ -1,13 +1,25 @@ /** Execute the printed command through the real CLI and authenticated in-place recovery. */ import { spawnSync } from 'node:child_process'; import { randomBytes } from 'node:crypto'; -import { cpSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'; +import { + cpSync, + existsSync, + lstatSync, + mkdirSync, + mkdtempSync, + readdirSync, + readFileSync, + renameSync, + rmSync, + symlinkSync, + writeFileSync, +} from 'node:fs'; import { join, resolve } from 'node:path'; import { afterEach, beforeEach, expect, it, vi } from 'vitest'; import { encryptBackupTree } from './backup-encryption'; -import { expectedComposeProjectFor, recordInstall } from './install-record'; +import { expectedComposeProjectFor, readInstallRecord, recordInstall } from './install-record'; import { rollbackSteps } from './upgrade-instructions'; const FROM = 'a'.repeat(40); @@ -22,58 +34,130 @@ beforeEach(() => { }); afterEach(() => { vi.unstubAllEnvs(); + const scratchLog = join(root, 'scratch-paths.jsonl'); + if (existsSync(scratchLog)) { + for (const line of readFileSync(scratchLog, 'utf8').trim().split('\n')) { + const path = JSON.parse(line) as string; + // Only exact paths returned by this child's real mkdtemp are eligible for cleanup. + rmSync(path, { recursive: true, force: true }); + } + } rmSync(root, { recursive: true, force: true }); }); -it('executes the emitted populated-target rollback with real decryption, state restore and old checkout', () => { - const stateDir = join(root, 'custom state'); - const envFile = join(root, 'box.env'); - const key = join(root, 'backup-key'); - const snapshot = join(root, 'snapshot'); - const plain = join(root, 'plain'); - const bucket = join(root, 'bucket'); - mkdirSync(stateDir); - mkdirSync(bucket); - const box = { CELLD_BUCKET: 'gs://test/owned', SAM_DOMAIN: 'rollback.test' }; - writeFileSync(envFile, 'CELLD_BUCKET=gs://test/owned\nSAM_DOMAIN=rollback.test\n', { - mode: 0o600, - }); - writeFileSync(key, randomBytes(32), { mode: 0o600 }); - const id = 'b'.repeat(32); - writeFileSync(join(stateDir, 'platform-keys.json'), JSON.stringify({ SAM_INSTALLATION_ID: id })); - writeFileSync(join(stateDir, 'data'), 'old-state'); - recordInstall(stateDir, envFile, box, id); - mkdirSync(plain); - cpSync(stateDir, join(plain, 'state'), { recursive: true }); - cpSync(envFile, join(plain, 'env')); - mkdirSync(join(plain, 'bucket')); - writeFileSync(join(plain, 'bucket/data'), 'old-rows'); - writeFileSync( - join(plain, 'backup-manifest.json'), - JSON.stringify({ - version: 1, - createdAt: new Date().toISOString(), - bucket: box.CELLD_BUCKET, - samCommit: FROM, - precopyMs: 0, - downtimeMs: 0, - deltaCopyMs: 0, - objectCount: 1, - }) - ); - encryptBackupTree(plain, snapshot, key); - writeFileSync(join(stateDir, 'data'), 'new-state'); - writeFileSync(join(bucket, 'data'), 'new-rows'); - writeFileSync(join(bucket, 'new-only'), 'must disappear'); - const project = expectedComposeProjectFor(box, stateDir); - const preload = join(root, 'boundary.cjs'); - writeFileSync( - preload, - ` +it.each([ + { name: 'uninterrupted', boundary: '', foreign: '' }, + { name: 'SIGKILL after live state moves to previous', boundary: 'previous', foreign: '' }, + { name: 'SIGKILL after restored state becomes live', boundary: 'restored', foreign: '' }, + { name: 'SIGKILL after receipt publication', boundary: 'receipt', foreign: '' }, + { name: 'SIGKILL after stage cleanup', boundary: 'cleanup', foreign: '' }, + { name: 'foreign staging inode after SIGKILL', boundary: 'receipt', foreign: 'stage' }, + { name: 'foreign staged inode after SIGKILL', boundary: 'receipt', foreign: 'staged' }, + { name: 'symlink receipt after SIGKILL', boundary: 'receipt', foreign: 'receipt' }, + { name: 'foreign previous inode after SIGKILL', boundary: 'previous', foreign: 'previous' }, + { name: 'foreign live inode after SIGKILL', boundary: 'restored', foreign: 'live' }, +])( + 'executes the emitted populated-target rollback: $name', + ({ boundary, foreign }) => { + const stateDir = join(root, 'custom state'); + const envFile = join(root, 'box.env'); + const key = join(root, 'backup-key'); + const snapshot = join(root, 'snapshot'); + const plain = join(root, 'plain'); + const bucket = join(root, 'bucket'); + mkdirSync(stateDir); + mkdirSync(bucket); + const box = { CELLD_BUCKET: 'gs://test/owned', SAM_DOMAIN: 'rollback.test' }; + writeFileSync(envFile, 'CELLD_BUCKET=gs://test/owned\nSAM_DOMAIN=rollback.test\n', { + mode: 0o600, + }); + writeFileSync(key, randomBytes(32), { mode: 0o600 }); + const id = 'b'.repeat(32); + writeFileSync( + join(stateDir, 'platform-keys.json'), + JSON.stringify({ SAM_INSTALLATION_ID: id }) + ); + writeFileSync(join(stateDir, 'data'), 'old-state'); + recordInstall(stateDir, envFile, box, id); + mkdirSync(plain); + cpSync(stateDir, join(plain, 'state'), { recursive: true }); + cpSync(envFile, join(plain, 'env')); + mkdirSync(join(plain, 'bucket')); + writeFileSync(join(plain, 'bucket/data'), 'old-rows'); + writeFileSync( + join(plain, 'backup-manifest.json'), + JSON.stringify({ + version: 1, + createdAt: new Date().toISOString(), + bucket: box.CELLD_BUCKET, + samCommit: FROM, + precopyMs: 0, + downtimeMs: 0, + deltaCopyMs: 0, + objectCount: 1, + }) + ); + encryptBackupTree(plain, snapshot, key); + writeFileSync(join(stateDir, 'data'), 'new-state'); + writeFileSync(join(bucket, 'data'), 'new-rows'); + writeFileSync(join(bucket, 'new-only'), 'must disappear'); + // These receipts postdate the snapshot and must survive replacement until health succeeds. + const upgradePending = { from: FROM, to: 'b'.repeat(40), backupDir: snapshot }; + const project = expectedComposeProjectFor(box, stateDir); + const cachePending = { + snapshot, + name: `${project}_celld-data`, + createdAt: '2026-11-19T00:00:00Z', + container: 'c'.repeat(64), + helpers: [], + }; + writeFileSync(join(stateDir, 'upgrade-pending.json'), JSON.stringify(upgradePending), { + mode: 0o600, + }); + writeFileSync(join(stateDir, 'rollback-cache-pending.json'), JSON.stringify(cachePending), { + mode: 0o600, + }); + const killed = join(root, 'killed.json'); + const swapReceipt = join(root, '.custom state.rollback-state.json'); + const preload = join(root, 'boundary.cjs'); + writeFileSync( + preload, + ` const fs = require('node:fs'); const cp = require('node:child_process'); const { syncBuiltinESMExports } = require('node:module'); const original = cp.spawnSync; +const originalMkdtemp = fs.mkdtempSync; +fs.mkdtempSync = (prefix, options) => { + const path = originalMkdtemp(prefix, options); + if (prefix === ${JSON.stringify(resolve('.tmp/selfhost-backups/operation-'))}) + fs.appendFileSync(${JSON.stringify(join(root, 'scratch-paths.jsonl'))}, JSON.stringify(path)+'\\n'); + return path; +}; +const boundary = ${JSON.stringify(boundary)}; +const markKilled = (source, destination) => { + if (fs.existsSync(${JSON.stringify(killed)})) return; + const swap = JSON.parse(fs.readFileSync(${JSON.stringify(swapReceipt)}, 'utf8')); + fs.writeFileSync(${JSON.stringify(killed)}, JSON.stringify({source, destination, stage:swap.stage}), {mode:0o600}); + process.kill(process.pid, 'SIGKILL'); +}; +const originalRename = fs.renameSync; +fs.renameSync = (source, destination) => { + originalRename(source, destination); + if ( + (boundary === 'previous' && source === ${JSON.stringify(stateDir)} && require('node:path').basename(destination) === 'previous') || + (boundary === 'restored' && destination === ${JSON.stringify(stateDir)} && require('node:path').basename(source) === 'restored') || + (boundary === 'receipt' && destination === ${JSON.stringify(swapReceipt)}) + ) markKilled(source, destination); +}; +const originalRm = fs.rmSync; +fs.rmSync = (path, options) => { + originalRm(path, options); + if (boundary === 'cleanup' && fs.existsSync(${JSON.stringify(swapReceipt)})) { + const swap = JSON.parse(fs.readFileSync(${JSON.stringify(swapReceipt)}, 'utf8')); + if (path === swap.stage) markKilled(path, ${JSON.stringify(stateDir)}); + } +}; let container = 'c'.repeat(64); let volume = true; let created = '2026-11-19T00:00:00Z'; @@ -103,29 +187,115 @@ cp.spawnSync = (command, args, options) => { syncBuiltinESMExports(); globalThis.fetch = async () => new Response('healthy', {status:200}); ` - ); - const ctx = { box, stateDir, envFile, encryptionKeyFile: key }; - const command = rollbackSteps(ctx, FROM, snapshot, ['caddy'])[0]; - const tsx = resolve('node_modules/.bin/tsx'); - const cli = resolve('scripts/selfhost/upgrade.ts'); - const result = spawnSync( - 'bash', - ['-c', `pnpm() { shift; '${tsx}' '${cli}' "$@"; }; ${command}`], - { - encoding: 'utf8', - env: { ...process.env, NODE_OPTIONS: `--require=${preload}` }, + ); + const ctx = { box, stateDir, envFile, encryptionKeyFile: key }; + const command = rollbackSteps(ctx, FROM, snapshot, ['caddy'])[0]; + const tsx = resolve('node_modules/.bin/tsx'); + const cli = resolve('scripts/selfhost/upgrade.ts'); + const run = () => + spawnSync('bash', ['-c', `pnpm() { shift; '${tsx}' '${cli}' "$@"; }; ${command}`], { + encoding: 'utf8', + env: { ...process.env, NODE_OPTIONS: `--require=${preload}` }, + }); + let result = run(); + if (boundary) { + expect(result.status).not.toBe(0); + expect(existsSync(killed)).toBe(true); + const interrupted = JSON.parse(readFileSync(killed, 'utf8')) as { + source: string; + destination: string; + stage: string; + }; + // The marker is written only after the real filesystem operation, never by a fake restore. + expect(existsSync(interrupted.source)).toBe(false); + expect(existsSync(interrupted.destination)).toBe(true); + const restored = ['previous', 'receipt'].includes(boundary) + ? join(interrupted.stage, 'restored') + : stateDir; + expect(existsSync(swapReceipt)).toBe(true); + expect(existsSync(interrupted.stage)).toBe(boundary !== 'cleanup'); + expect(readFileSync(join(restored, 'data'), 'utf8')).toBe('old-state'); + const stagedState = lstatSync(restored); + const stagedLedger = readInstallRecord(restored).find( + (entry) => entry.kind === 'state-dir' && !entry.removedAt + ); + expect(stagedLedger?.attributes).toMatchObject({ + device: String(stagedState.dev), + inode: String(stagedState.ino), + }); + expect(JSON.parse(readFileSync(join(restored, 'upgrade-pending.json'), 'utf8'))).toEqual( + upgradePending + ); + expect( + JSON.parse(readFileSync(join(restored, 'rollback-cache-pending.json'), 'utf8')) + ).toEqual(cachePending); + const beforeRetry = readFileSync(join(root, 'calls'), 'utf8'); + expect(beforeRetry).toContain('gcloud storage rsync'); + expect(beforeRetry).not.toContain('container rm'); + expect(beforeRetry).not.toContain('volume rm'); + if (foreign) { + // Same data/installation but a different inode must never inherit swap authorization. + const target = + foreign === 'stage' + ? interrupted.stage + : foreign === 'staged' + ? join(interrupted.stage, 'restored') + : foreign === 'receipt' + ? swapReceipt + : interrupted.destination; + const retained = join(root, 'retained original'); + const originalInode = lstatSync(target).ino; + renameSync(target, retained); + if (foreign === 'receipt') symlinkSync(retained, target); + else cpSync(retained, target, { recursive: true }); + expect(lstatSync(target).ino).not.toBe(originalInode); + if (foreign !== 'receipt') + writeFileSync(join(target, 'foreign-marker'), 'preserve foreign directory'); + result = run(); + expect(result.status).not.toBe(0); + if (foreign === 'receipt') { + expect(lstatSync(target).isSymbolicLink()).toBe(true); + expect(readFileSync(target, 'utf8')).toBe(readFileSync(retained, 'utf8')); + } else + expect(readFileSync(join(target, 'foreign-marker'), 'utf8')).toBe( + 'preserve foreign directory' + ); + expect(existsSync(retained)).toBe(true); + const retryCalls = readFileSync(join(root, 'calls'), 'utf8').slice(beforeRetry.length); + expect(retryCalls).not.toContain('gcloud storage rsync'); + expect(retryCalls).not.toContain('container rm'); + expect(retryCalls).not.toContain('volume rm'); + return; + } + // Reuse precisely the operator's emitted command, including its state path with spaces. + result = run(); } - ); - expect(result.stderr).toBe(''); - expect(result.status).toBe(0); - expect(result.stdout).toContain('manual rollback completed'); - expect(readFileSync(join(stateDir, 'data'), 'utf8')).toBe('old-state'); - expect(readFileSync(join(bucket, 'data'), 'utf8')).toBe('old-rows'); - const calls = readFileSync(join(root, 'calls'), 'utf8'); - expect(calls.indexOf('gcloud storage rsync')).toBeLessThan( - calls.indexOf(`git checkout --detach ${FROM}`) - ); - expect(calls).toContain(`--project-name ${project}`); - expect(calls).toContain(' build caddy'); - expect(calls).toContain('container rm --force ' + 'c'.repeat(64)); -}, 60_000); + expect(result.stderr).toBe(''); + expect(result.status).toBe(0); + expect(result.stdout).toContain('manual rollback completed'); + expect(readFileSync(join(stateDir, 'data'), 'utf8')).toBe('old-state'); + expect(readFileSync(join(bucket, 'data'), 'utf8')).toBe('old-rows'); + expect(existsSync(join(bucket, 'new-only'))).toBe(false); + const state = lstatSync(stateDir); + const receipt = readInstallRecord(stateDir).filter( + (entry) => entry.kind === 'state-dir' && !entry.removedAt + ); + expect(receipt).toHaveLength(1); + expect(receipt[0]?.attributes).toMatchObject({ + device: String(state.dev), + inode: String(state.ino), + }); + expect(existsSync(join(stateDir, 'upgrade-pending.json'))).toBe(false); + expect(existsSync(join(stateDir, 'rollback-cache-pending.json'))).toBe(false); + expect(existsSync(swapReceipt)).toBe(false); + expect(readdirSync(root).filter((entry) => entry.startsWith('.rollback-state-'))).toEqual([]); + const calls = readFileSync(join(root, 'calls'), 'utf8'); + expect(calls.indexOf('gcloud storage rsync')).toBeLessThan( + calls.indexOf(`git checkout --detach ${FROM}`) + ); + expect(calls).toContain(`--project-name ${project}`); + expect(calls).toContain(' build caddy'); + expect(calls).toContain('container rm --force ' + 'c'.repeat(64)); + }, + 60_000 +); diff --git a/scripts/selfhost/upgrade-rollback.ts b/scripts/selfhost/upgrade-rollback.ts index 1fc1eaa629..dde5485f60 100644 --- a/scripts/selfhost/upgrade-rollback.ts +++ b/scripts/selfhost/upgrade-rollback.ts @@ -4,6 +4,7 @@ import { join } from 'node:path'; import { composeArgs, composeRunEnv } from './backup-lib.js'; import { assertOperatorExecution } from './operator-only.js'; +import { recoverRollbackState } from './rollback-state.js'; import { type BoxContext, recoverUpgrade, UPGRADE_PENDING_FILE } from './upgrade-lib.js'; import { assertRollbackReady } from './upgrade-preflight.js'; @@ -19,6 +20,7 @@ export async function runManualRollback( opts: ManualRollbackOptions ): Promise { assertOperatorExecution(); + recoverRollbackState(ctx); if ( !/^[a-f0-9]{40}$/.test(opts.from) || opts.rebuilds.some((name) => !/^[a-zA-Z0-9][a-zA-Z0-9_.-]*$/.test(name)) diff --git a/tasks/archive/2026-11-19-l24-selfhost-operations.md b/tasks/archive/2026-11-19-l24-selfhost-operations.md index c7c8175c12..5dcd52234d 100644 --- a/tasks/archive/2026-11-19-l24-selfhost-operations.md +++ b/tasks/archive/2026-11-19-l24-selfhost-operations.md @@ -85,6 +85,14 @@ The coordinator explicitly deferred the pre-existing pool/provider/service-accou Plaintext backups, missing rollback/history validation and name-based lifecycle assumptions were unsafe. Real SDK failure evidence replaced the unconfirmed tracker hypothesis. Real disposable execution exposed read-only cache cleanup and executable-mode loss; both have discriminating regressions. Review added clone identity isolation, inactive restore deployment, durable retries, exact backup deletion proof and retained-key retry ownership. Clean CI exposed an unbuilt workspace-package dependency that locally built output had hidden; the full suite now proves source resolution with that output absent. +## Rollback state-swap interruption delta + +Automatic review 4638273658 exposed a process-kill gap between moving live state aside and recording the replacement inode. The same emitted rollback command reproduced both missing-state and stale-ledger failures. The replacement ledger now binds its new inode before publication; a private sibling swap receipt durably binds installation scope and original/staged directory identities before either rename. Automatic, explicit and direct recovery reconcile that receipt before reading installation metadata. An interrupted cleanup retains the proof; replaced or symlinked directories and receipts refuse before destructive work. + +Ten real-CLI scenarios cover uninterrupted recovery, SIGKILL after receipt publication, each directory rename and stage removal, plus foreign previous/live/stage/restored inodes and a symlink receipt. Every retry uses the same printed command and state path with spaces. Tests assert preserved upgrade/cache pointers, restored bucket/state, the new ledger inode, exact scratch cleanup and refusal before cloud/cache mutation. The two rename controls failed on the original implementation and pass with the fix. Existing BOX evidence and the coordinator-owned post-merge combined smoke remain as recorded above. + +Final delta validation: full self-host suite 995 passed, four conditional skips, 56 files; TypeScript, focused lint, formatting, diff and secret-readback scanner pass. Independent security and completion/documentation/constitution delta reviews pass with no unresolved finding. FIFO receipts refuse before opening and malformed key diagnostics withhold source contents. + ## References PR https://github.com/raphaeltm/simple-agent-manager/pull/2918; idea01M72M9AEB933ZY8269D376DKC LANDING PLAN part6; SAM task01M7TTKAS78AMJ3853S5N4BYAK; coordinator01M7JMXS2JRW6QQMB1356ENPM3; policy795e72a6; rule56; `/do`. From d436de56b122f4ce47c1477eb81afeb7614e1695 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rapha=C3=ABl=20Titsworth-Morin?= Date: Fri, 20 Nov 2026 04:54:18 +0000 Subject: [PATCH 16/17] fix(selfhost): reserve independent clone identities and protect project receipts --- deploy/selfhost/README.md | 29 ++- deploy/selfhost/created-resources.mjs | 16 +- deploy/selfhost/gcp-bootstrap.sh | 4 + scripts/selfhost/backup-entrypoint.test.ts | 20 +- scripts/selfhost/backup-lib.ts | 11 +- scripts/selfhost/backup-restore.ts | 10 +- scripts/selfhost/backup.test.ts | 111 ++++++++- scripts/selfhost/gcp-bootstrap.test.ts | 98 ++++++++ scripts/selfhost/restore-completion.test.ts | 39 ++- scripts/selfhost/restore-identity.ts | 38 +-- scripts/selfhost/restore-progress.ts | 230 +++++++++++++----- .../2026-11-19-l24-selfhost-operations.md | 10 + 12 files changed, 503 insertions(+), 113 deletions(-) diff --git a/deploy/selfhost/README.md b/deploy/selfhost/README.md index fbe9869df2..d6ccba7b85 100644 --- a/deploy/selfhost/README.md +++ b/deploy/selfhost/README.md @@ -140,7 +140,7 @@ pnpm --silent selfhost:restore --from /absolute/path/to/backup --print-project \ --encryption-key-file "$HOME/.config/sam/backup.key" ``` -This prints only the public project name; it makes no target, runtime or store changes. Put that +This prints only the public project name; it writes a private sibling identity reservation but makes no target state, runtime or store changes. Put that name in the target `.env` as `COMPOSE_PROJECT_NAME`, keep `COMPOSE_PROFILES=local-store` (plus any other desired profiles), and start only the bundled store and its initializer: @@ -164,7 +164,8 @@ pnpm selfhost:restore --from /absolute/path/to/backup \ Restore authenticates the complete encrypted inventory and every file before touching the target. If a copy fails, retain `.restore-progress.json` and retry the exact same command and -backup. This private journal binds the original empty target and authenticated snapshot. A retry +backup. This private journal binds the target and authenticated snapshot; its started phase records that +the target passed the empty-state and empty-bucket checks. A retry refuses changed, additional, linked or foreign-owned partial files before copying again; do not start the target or remove its journal to bypass a refusal. State files interrupted mid-copy may be retried only when their bytes are an exact prefix of the authenticated source; bucket objects @@ -176,7 +177,8 @@ match if present. A completed retry still refuses changed data or an application verification, remove these exact operator-owned metadata files manually; teardown retains them. It permits only the verified bundled-store bootstrap described above, copies state and bucket data, keeps the target `.env`, strips the source installation's creation receipts, and does not start celld. -A fresh restore assigns a distinct `SAM_INSTALLATION_ID`, stable for retries of the same target, +A fresh restore reserves a random `SAM_INSTALLATION_ID` in private target-local metadata, +distinct even for independent hosts using identical paths and bucket names and stable for retries, while preserving all cryptographic keys needed to read the restored data. The generated local config receives that new ID. Restore omits the source bucket's active `deploy/current.json` pointer but retains immutable deployment objects and application data, so starting celld cannot @@ -187,7 +189,12 @@ labels are retained: the replacement must provision its own nodes, and its teard delete the source fleet. This also applies to disaster recovery; retire surviving source resources separately using their original installation records. For every store type, set the target `.env`'s `COMPOSE_PROJECT_NAME` to the canonical name restore prints **before** running `selfhost:deploy --init`. -You can also derive it beforehand with the authenticated, read-only `--print-project` command. +You can also reserve it beforehand with the authenticated `--print-project` command. That command +creates only the private sibling identity reservation; it does not write target state or bucket data +or start a runtime. A reservation alone never permits restoring into occupied state or a bucket. +Keep the reservation on the target host and reuse the exact command and backup. Older v1 journals +are refused because they cannot prove an independent clone identity; preserve their target and +receipts for inspection instead of deleting metadata to bypass the check. The name incorporates the restored installation ID, domain and state directory. On the original SAM ref, run init with that setting to retain the keys and establish target ownership receipts, then start that target's Compose stack, deploy and verify its data (`scripts/selfhost/backup-lib.ts:runRestore`, @@ -199,10 +206,11 @@ inspect the exact installation's containers and restart only that installation's then use a fresh backup destination. Normal backup refuses a missing or stopped writer; it never guesses which other installation to start. A partial ciphertext directory is not reusable, and a fully encrypted backup whose receipt write failed is retained for operator inspection and restore; -it is not automatically adopted for destructive cleanup. An interrupted initial journal write -before target writes can leave an invalid progress receipt: restore refuses to adopt it. Verify -that both target state and bucket are still empty before manually removing that exact receipt and -retrying. Preserve populated or unverified targets for inspection instead of bypassing ownership. +it is not automatically adopted for destructive cleanup. Restore writes and syncs the complete +private journal before atomically publishing it, so an interrupted initial write can be retried +without adopting partial metadata. A published journal is revalidated and synced before any +target write. Invalid or legacy metadata still causes refusal: preserve the target and receipts +for inspection instead of bypassing ownership. ## Upgrade @@ -554,3 +562,8 @@ addresses and protected local listeners remain forbidden for relays. The broker port must also differ from every other managed box listener, including disabled optional services. Deploy, fence planning and Caddy startup all check this reservation. + +GCP bootstrap requires a dedicated `--state-dir` receipt path for each GCP project. It refuses +active GCP receipts for a different or unrecorded project before making issuer or cloud calls, +including in dry-run mode. Preserve existing receipts; use a separate state directory for another +project. Removed resource receipts do not block reuse. diff --git a/deploy/selfhost/created-resources.mjs b/deploy/selfhost/created-resources.mjs index 0eb6291b79..23653855c3 100644 --- a/deploy/selfhost/created-resources.mjs +++ b/deploy/selfhost/created-resources.mjs @@ -71,6 +71,16 @@ export function readRecord(file) { return parsed; } +/** Bare GCP resource names may repeat across projects; never replace another project's proof. */ +export function assertProject(file, project) { + for (const resource of readRecord(file).resources) { + if (resource.cloud === 'gcp' && !resource.removedAt && resource.attributes?.project !== project) + throw new Error( + 'GCP receipt belongs to a different or unrecorded project; use a separate --state-dir and preserve the existing receipts' + ); + } +} + function writeRecord(file, record) { mkdirSync(dirname(file), { recursive: true, mode: 0o700 }); const tmp = `${file}.tmp-${process.pid}-${randomUUID()}`; @@ -205,7 +215,11 @@ export function markRemoved(file, cloud, kind, name, now = new Date()) { if (import.meta.url === `file://${process.argv[1]}`) { const [command, file, ...rest] = process.argv.slice(2); try { - if (command === 'add' || command === 'grant-intent') { + if (command === 'assert-project') { + const [project] = rest; + if (!project) throw new Error('assert-project requires a GCP project'); + assertProject(file, project); + } else if (command === 'add' || command === 'grant-intent') { const [cloud, kind, name, action, createdBy, ...pairs] = rest; if (!cloud || !kind || !name || !['created', 'reused'].includes(action) || !createdBy) { throw new Error( diff --git a/deploy/selfhost/gcp-bootstrap.sh b/deploy/selfhost/gcp-bootstrap.sh index b555f191d8..c777b4383a 100755 --- a/deploy/selfhost/gcp-bootstrap.sh +++ b/deploy/selfhost/gcp-bootstrap.sh @@ -151,6 +151,10 @@ change_retry() { return 1 } +# Validate the existing ledger before any issuer/cloud call, including dry-run and no-ID modes. +node "$SCRIPT_DIR/created-resources.mjs" assert-project "$STATE_DIR/created-resources.json" "$PROJECT" \ + || die "cannot use this receipt path for the requested GCP project" + command -v gcloud >/dev/null 2>&1 || die "gcloud is not installed or not on PATH" # Receipts contain public resource identifiers only, never credentials. Reuse never becomes diff --git a/scripts/selfhost/backup-entrypoint.test.ts b/scripts/selfhost/backup-entrypoint.test.ts index 18e966135e..09d414e1ec 100644 --- a/scripts/selfhost/backup-entrypoint.test.ts +++ b/scripts/selfhost/backup-entrypoint.test.ts @@ -11,6 +11,7 @@ import { chmodSync, copyFileSync, existsSync, + lstatSync, mkdirSync, mkdtempSync, readdirSync, @@ -125,7 +126,7 @@ afterEach(() => { }); describe('selfhost:backup and selfhost:restore (real entry points, fake gcloud)', () => { - it('prints only the authenticated final project without target writes or runtime/store calls', () => { + it('reserves the authenticated final project without target state, bucket or runtime writes', () => { const dest = join(root, 'project-backup'); expect( run('backup.ts', [ @@ -141,7 +142,7 @@ describe('selfhost:backup and selfhost:restore (real entry points, fake gcloud)' ).toBe(0); writeFileSync(join(root, 'fresh.env'), 'CELLD_BUCKET=gs://fresh/celld\n', { mode: 0o600 }); writeFileSync(join(root, 'fake/calls.log'), ''); - const output = run('restore.ts', [ + const args = [ '--from', dest, '--print-project', @@ -151,14 +152,25 @@ describe('selfhost:backup and selfhost:restore (real entry points, fake gcloud)' join(root, 'fresh-state'), '--encryption-key-file', join(root, 'backup-key'), - ]); + ]; + const output = run('restore.ts', args); expect(output.status).toBe(0); expect(output.stderr).toBe(''); expect(output.stdout).toMatch(/^sam-selfhost-[a-f0-9]{12}\n$/); expect(readFileSync(join(root, 'fake/calls.log'), 'utf8')).toBe(''); expect(existsSync(join(root, 'fresh-state'))).toBe(false); expect(existsSync(join(root, 'gcs/fresh'))).toBe(false); - expect(existsSync(join(root, 'fresh-state.restore-progress.json'))).toBe(false); + const receipt = join(root, 'fresh-state.restore-progress.json'); + expect(existsSync(receipt)).toBe(true); + expect(lstatSync(receipt).mode & 0o777).toBe(0o600); + const reserved = readFileSync(receipt, 'utf8'); + const repeated = run('restore.ts', args); + expect(repeated.status).toBe(0); + expect(repeated.stdout).toBe(output.stdout); + expect(readFileSync(receipt, 'utf8')).toBe(reserved); + expect(readFileSync(join(root, 'fake/calls.log'), 'utf8')).toBe(''); + expect(existsSync(join(root, 'fresh-state'))).toBe(false); + expect(existsSync(join(root, 'gcs/fresh'))).toBe(false); }); it('uses a clean full copy after the stopped pass hits the confirmed POSIX stat of a missing finalized file', () => { writeFileSync( diff --git a/scripts/selfhost/backup-lib.ts b/scripts/selfhost/backup-lib.ts index 619dcb177e..48dcb22083 100644 --- a/scripts/selfhost/backup-lib.ts +++ b/scripts/selfhost/backup-lib.ts @@ -22,7 +22,8 @@ import { requireRunningCelld } from './backup-runtime'; import { composeProjectFor, expectedComposeProjectFor, recordBackup } from './install-record'; import { assertOperatorExecution } from './operator-only'; import { removePrivateTree } from './private-tree'; -import { projectRestoreIdentity } from './restore-identity'; +import { projectRestoreIdentity, restoreSourceInstallationId } from './restore-identity'; +import { restoreProgress } from './restore-progress'; import { ensurePrivateDir } from './secret-files'; /** @@ -452,7 +453,13 @@ export function runRestore( decryptBackupTree(from, plain, key); if (mode === 'project') { readManifest(plain); - const identity = projectRestoreIdentity(ctx, join(plain, STATE_DIR)); + const progress = restoreProgress( + ctx, + from, + restoreSourceInstallationId(ctx, join(plain, STATE_DIR)) + ); + progress.reserve(); + const identity = projectRestoreIdentity(ctx, join(plain, STATE_DIR), progress.installationId); return expectedComposeProjectFor(ctx.box, ctx.stateDir, identity); } return restoreBackup(ctx, plain, from); diff --git a/scripts/selfhost/backup-restore.ts b/scripts/selfhost/backup-restore.ts index e607d5fc58..bf4f5715b1 100644 --- a/scripts/selfhost/backup-restore.ts +++ b/scripts/selfhost/backup-restore.ts @@ -13,7 +13,7 @@ import { STATE_DIR, } from './backup-lib'; import { assertOperatorExecution } from './operator-only'; -import { projectRestoreIdentity } from './restore-identity'; +import { projectRestoreIdentity, restoreSourceInstallationId } from './restore-identity'; import { assertRestoreSubset, restoreProgress } from './restore-progress'; import { assertRestoreRuntime } from './restore-runtime'; import { ensurePrivateDir } from './secret-files'; @@ -21,10 +21,14 @@ import { ensurePrivateDir } from './secret-files'; export function restoreBackup(ctx: BoxContext, plain: string, encrypted: string): BackupManifest { assertOperatorExecution(); const manifest = readManifest(plain); - const identity = projectRestoreIdentity(ctx, join(plain, STATE_DIR)); + const progress = restoreProgress( + ctx, + encrypted, + restoreSourceInstallationId(ctx, join(plain, STATE_DIR)) + ); + const identity = projectRestoreIdentity(ctx, join(plain, STATE_DIR), progress.installationId); // No source Worker (including its Durable Object alarms) may run before a fresh target deploy. rmSync(join(plain, BUCKET_DIR, 'deploy', 'current.json'), { force: true }); - const progress = restoreProgress(ctx, encrypted); const state = lstatSync(ctx.stateDir, { throwIfNoEntry: false }); if (state && process.getuid !== undefined && state.uid !== process.getuid()) throw new Error('Restore target state is owned by another user'); diff --git a/scripts/selfhost/backup.test.ts b/scripts/selfhost/backup.test.ts index 3d04323632..f20f635da3 100644 --- a/scripts/selfhost/backup.test.ts +++ b/scripts/selfhost/backup.test.ts @@ -4,7 +4,7 @@ * and executed against a directory standing in for the bucket. The real-store version of the * round trip is live/backup-restore.live.test.ts (pinned MinIO image, Docker). */ -import { randomBytes } from 'node:crypto'; +import { createHash, randomBytes } from 'node:crypto'; import * as fs from 'node:fs'; import { chmodSync, @@ -46,6 +46,7 @@ import { prepareCelldProject, writeCelldConfig } from './celld-project'; import { runDeploy, runTsx, writeBox } from './deploy-harness'; import { composeProjectFor, expectedComposeProjectFor, recordInstall } from './install-record'; import { restoredInstallationId } from './restore-identity'; +import { ownershipRefusal } from './teardown-gcp'; import { recoverUpgrade } from './upgrade-lib'; vi.mock('node:fs', async (importOriginal) => ({ @@ -549,6 +550,108 @@ describe('runBackup', () => { }); describe('runRestore', () => { + it('reserves different fleet identities on independent hosts with identical source, path and bucket', () => { + const snapshot = join(root, 'same-input-snapshot'); + runBackup(ctx('s3://fleet/celld', join(root, 'state')), snapshot); + const target = ctx('s3://fresh/celld', join(root, 'new-state')); + const journal = `${target.stateDir}.restore-progress.json`; + const firstProject = runRestore(target, snapshot, 'project'); + const firstId = restoredInstallationId(target, 'a'.repeat(32)); + // Host-local receipts are the only difference: both hosts use the same conventional paths. + // Retain host one's local filesystem while exposing an empty local filesystem for host two. + if (existsSync(journal)) renameSync(journal, join(root, 'host-one-journal')); + const secondProject = runRestore(target, snapshot, 'project'); + const secondId = restoredInstallationId(target, 'a'.repeat(32)); + expect(secondId).not.toBe(firstId); + expect(secondProject).not.toBe(firstProject); + expect(firstId).toMatch(/^[a-f0-9]{32}$/); + expect(secondId).toMatch(/^[a-f0-9]{32}$/); + expect(firstId).not.toBe('a'.repeat(32)); + expect(secondId).not.toBe('a'.repeat(32)); + expect(runRestore(target, snapshot, 'project')).toBe(secondProject); + const vm = { + id: '12345', + name: 'sam-host-one', + zone: 'europe-west1-b', + disks: [], + tags: [], + networks: [], + labels: { + managed: 'simple-agent-manager', + installation: firstId, + env: 'selfhost', + node: 'node-one', + }, + }; + expect(ownershipRefusal(vm, firstId)).toBeNull(); + expect(ownershipRefusal(vm, secondId)).toContain('another install'); + renameSync(journal, join(root, 'host-two-journal')); + renameSync(join(root, 'host-one-journal'), journal); + expect(runRestore(target, snapshot, 'project')).toBe(firstProject); + expect(restoredInstallationId(target, 'a'.repeat(32))).toBe(firstId); + runRestore(target, snapshot); + expect( + JSON.parse(readFileSync(join(target.stateDir, 'platform-keys.json'), 'utf8')) + .SAM_INSTALLATION_ID + ).toBe(firstId); + expect(runRestore(target, snapshot, 'project')).toBe(firstProject); + runRestore(target, snapshot); + expect( + JSON.parse(readFileSync(join(target.stateDir, 'platform-keys.json'), 'utf8')) + .SAM_INSTALLATION_ID + ).toBe(firstId); + }); + + it.each(['state', 'bucket'] as const)( + 'a print-project reservation cannot authorize overwriting populated %s', + (occupied) => { + const snapshot = join(root, 'reserved-snapshot'); + runBackup(ctx('s3://fleet/celld', join(root, 'state')), snapshot); + const target = ctx('s3://fresh/celld', join(root, 'new-state')); + const project = runRestore(target, snapshot, 'project'); + expect(project).toMatch(/^sam-selfhost-[a-f0-9]{12}$/); + const path = occupied === 'state' ? target.stateDir : join(root, 'store/fresh/celld'); + mkdirSync(path, { recursive: true }); + // A valid snapshot subset would be accepted by the started-resume path. A mere + // print reservation must still require emptiness, even when those bytes match. + const marker = join(path, occupied === 'state' ? 'platform-keys.json' : 'current.json'); + const retained = + occupied === 'state' + ? JSON.stringify({ SAM_INSTALLATION_ID: restoredInstallationId(target, 'a'.repeat(32)) }) + : '{"v":3}'; + writeFileSync(marker, retained, { mode: 0o600 }); + calls = []; + expect(() => runRestore(target, snapshot)).toThrow(/not empty|empty install/); + expect(readFileSync(marker, 'utf8')).toBe(retained); + expect(calls.some((call) => call.args.includes('mirror'))).toBe(false); + expect(existsSync(`${target.stateDir}.restore-progress.json`)).toBe(true); + } + ); + + it('refuses a legacy deterministic-identity journal before any target runner call', () => { + const snapshot = join(root, 'legacy-journal-snapshot'); + runBackup(ctx('s3://fleet/celld', join(root, 'state')), snapshot); + const target = ctx('s3://fresh/celld', join(root, 'new-state')); + const journal = `${target.stateDir}.restore-progress.json`; + const legacy = JSON.stringify({ + format: 'sam-restore-progress/1', + bucket: target.box.CELLD_BUCKET, + state: resolve(target.stateDir), + backup: resolve(snapshot), + snapshot: createHash('sha256') + .update(readFileSync(join(snapshot, '.sam-backup-manifest'))) + .digest('hex'), + }); + mkdirSync(join(root, 'store/fresh/celld'), { recursive: true }); + writeFileSync(journal, legacy, { mode: 0o600 }); + calls = []; + expect(() => runRestore(target, snapshot)).toThrow(/ownership|legacy|identity|journal/); + expect(calls).toHaveLength(0); + expect(readFileSync(journal, 'utf8')).toBe(legacy); + expect(existsSync(target.stateDir)).toBe(false); + expect(tree(join(root, 'store/fresh/celld'))).toEqual({}); + }); + it('refuses a hard-linked partial state file before copying over an external inode', () => { const snapshot = join(root, 'retry-hardlink-snapshot'); runBackup(ctx('s3://fleet/celld', join(root, 'state')), snapshot); @@ -655,11 +758,7 @@ describe('runRestore', () => { runBackup(ctx('s3://fleet/celld', join(root, 'state')), snapshot); const target = ctx('s3://fresh/celld', join(root, 'new-state')); const preKey = composeProjectFor(target.box, target.stateDir); - const finalProject = expectedComposeProjectFor( - target.box, - target.stateDir, - restoredInstallationId(target, 'a'.repeat(32)) - ); + const finalProject = runRestore(target, snapshot, 'project'); expect(finalProject).not.toBe(preKey); occupiedProject = finalProject; targetContainers = 'fixture-final-project-container\n'; diff --git a/scripts/selfhost/gcp-bootstrap.test.ts b/scripts/selfhost/gcp-bootstrap.test.ts index 64d24f6521..644367af0f 100644 --- a/scripts/selfhost/gcp-bootstrap.test.ts +++ b/scripts/selfhost/gcp-bootstrap.test.ts @@ -24,6 +24,7 @@ const FAKE_GCLOUD = `#!/usr/bin/env bash exec node ${JSON.stringify(resolve(import.meta.dirname, 'testdata/fake-gcloud-iam.mjs'))} "$@" `; const FAKE_CURL = `#!/usr/bin/env bash +printf 'issuer check\\n' >> "$STATE/issuer-calls" printf '{"issuer":"%s","jwks_uri":"%s/.well-known/jwks.json"}' "$FAKE_ISSUER" "$FAKE_ISSUER" `; @@ -100,6 +101,103 @@ function calls(): string[] { const MUTATING = /^(services enable|iam workload-identity-pools( providers)? (create|update)|iam service-accounts create|projects add-iam-policy-binding|iam service-accounts add-iam-policy-binding)/; +describe('bootstrap project scope at the same state directory', () => { + const args = (project: string, installation = true) => [ + '--project', + project, + '--api-url', + ISSUER, + '--state-dir', + state, + ...(installation ? ['--installation-id', 'a'.repeat(32)] : []), + ]; + const receiptFile = () => join(state, 'created-resources.json'); + function seed() { + const first = run(args('sam-vm-test')); + expect(first.status, first.stderr).toBe(0); + expect(first.calls.some((call) => MUTATING.test(call))).toBe(true); + const record = JSON.parse(readFileSync(receiptFile(), 'utf8')); + expect( + record.resources.some( + (r: { attributes?: { project?: string } }) => r.attributes?.project === 'sam-vm-test' + ) + ).toBe(true); + return record; + } + it.each([ + { name: 'default-name collisions in another project', installation: true, dryRun: false }, + { name: 'omitted installation ID', installation: false, dryRun: false }, + { name: 'dry run', installation: true, dryRun: true }, + ])( + 'refuses $name before issuer or cloud access and preserves original receipts', + ({ installation, dryRun }) => { + seed(); + const original = readFileSync(receiptFile(), 'utf8'); + const cloud = readFileSync(join(state, 'gcp.json'), 'utf8'); + const before = calls(); + const issuerCalls = readFileSync(join(state, 'issuer-calls'), 'utf8'); + const result = run([ + ...args('second-project', installation), + ...(dryRun ? ['--dry-run'] : []), + ]); + expect(result.status, result.stderr).not.toBe(0); + expect(result.stderr).toMatch(/project|scope/i); + expect(readFileSync(receiptFile(), 'utf8')).toBe(original); + expect(readFileSync(join(state, 'gcp.json'), 'utf8')).toBe(cloud); + expect(calls()).toEqual(before); + expect(readFileSync(join(state, 'issuer-calls'), 'utf8')).toBe(issuerCalls); + } + ); + it.each(['missing', 'malformed'])( + 'refuses an active receipt with %s project scope before external access', + (scope) => { + const record = seed(); + const active = record.resources.find( + (r: { cloud: string; removedAt?: string }) => r.cloud === 'gcp' && !r.removedAt + ); + if (scope === 'missing') delete active.attributes.project; + else active.attributes.project = { invalid: true }; + writeFileSync(receiptFile(), JSON.stringify(record)); + const original = readFileSync(receiptFile(), 'utf8'); + const cloud = readFileSync(join(state, 'gcp.json'), 'utf8'); + const before = calls(); + const issuerCalls = readFileSync(join(state, 'issuer-calls'), 'utf8'); + const result = run(args('sam-vm-test')); + expect(result.status).not.toBe(0); + expect(readFileSync(receiptFile(), 'utf8')).toBe(original); + expect(readFileSync(join(state, 'gcp.json'), 'utf8')).toBe(cloud); + expect(calls()).toEqual(before); + expect(readFileSync(join(state, 'issuer-calls'), 'utf8')).toBe(issuerCalls); + } + ); + it('allows an exact same-project retry and preserves created ownership', () => { + seed(); + const before = calls().length; + const result = run(args('sam-vm-test')); + expect(result.status, result.stderr).toBe(0); + expect(result.calls.length).toBeGreaterThan(before); + expect(result.calls.slice(before).filter((call) => / (create|update)/.test(call))).toEqual([]); + const record = JSON.parse(readFileSync(receiptFile(), 'utf8')); + expect( + record.resources.every( + (r: { action: string; attributes: { project: string } }) => + r.action === 'created' && r.attributes.project === 'sam-vm-test' + ) + ).toBe(true); + }); + it('allows project reuse when every old GCP receipt is removed', () => { + const record = seed(); + for (const resource of record.resources) resource.removedAt = new Date().toISOString(); + writeFileSync(receiptFile(), JSON.stringify(record)); + const before = calls().length; + const result = run(args('second-project')); + expect(result.status, result.stderr).toBe(0); + expect( + result.calls.slice(before).some((call) => call.includes('--project=second-project')) + ).toBe(true); + }); +}); + describe('pnpm selfhost:gcp-bootstrap', () => { it('creates the pool, issuer-scoped provider, service account and bindings, and prints the five form values', () => { const result = run(['--project', 'sam-vm-test', '--api-url', `${ISSUER}/`]); diff --git a/scripts/selfhost/restore-completion.test.ts b/scripts/selfhost/restore-completion.test.ts index 86c47de75a..b4441fdd24 100644 --- a/scripts/selfhost/restore-completion.test.ts +++ b/scripts/selfhost/restore-completion.test.ts @@ -2,7 +2,7 @@ import { spawnSync } from 'node:child_process'; import { randomBytes } from 'node:crypto'; import * as fs from 'node:fs'; -import { join, resolve } from 'node:path'; +import { basename, dirname, join, resolve } from 'node:path'; import { afterEach, beforeEach, expect, it, vi } from 'vitest'; @@ -81,8 +81,31 @@ it.each(['write', 'file-sync', 'parent-sync'] as const)( let failed = false; const originalWrite = fs.writeSync, originalSync = fs.fsyncSync; + const trackJournalDescriptors = () => { + const descriptors = new Set(); + const originalOpen = fs.openSync, + originalClose = fs.closeSync; + vi.spyOn(fs, 'openSync').mockImplementation((...args: Parameters) => { + const fd = Reflect.apply(originalOpen, fs, args); + const path = String(args[0]); + if ( + path === progress || + (dirname(path) === dirname(progress) && + basename(path).startsWith(`.${basename(progress)}.`) && + path.endsWith('.tmp')) + ) + descriptors.add(fd); + return fd; + }); + vi.spyOn(fs, 'closeSync').mockImplementation((fd) => { + descriptors.delete(fd); + return originalClose(fd); + }); + return descriptors; + }; + let journalDescriptors = trackJournalDescriptors(); vi.spyOn(fs, 'writeSync').mockImplementation((...args: Parameters) => { - if (!failed && boundary === 'write' && fs.existsSync(progress)) { + if (!failed && boundary === 'write' && journalDescriptors.has(args[0])) { failed = true; originalWrite(args[0], Buffer.from('partial')); throw Error('Injected initial journal write'); @@ -92,8 +115,9 @@ it.each(['write', 'file-sync', 'parent-sync'] as const)( vi.spyOn(fs, 'fsyncSync').mockImplementation((fd) => { if ( !failed && - fs.existsSync(progress) && - (fs.fstatSync(fd).isDirectory() ? boundary === 'parent-sync' : boundary === 'file-sync') + (fs.fstatSync(fd).isDirectory() + ? boundary === 'parent-sync' && fs.existsSync(progress) + : boundary === 'file-sync' && journalDescriptors.has(fd)) ) { failed = true; throw Error('Injected initial journal sync'); @@ -105,13 +129,12 @@ it.each(['write', 'file-sync', 'parent-sync'] as const)( expect(fs.existsSync(context.stateDir)).toBe(false); expect(fs.existsSync(join(root, 'store/fresh/celld/data/value'))).toBe(false); vi.restoreAllMocks(); + journalDescriptors = trackJournalDescriptors(); let fileSynced = false, parentSynced = false; vi.spyOn(fs, 'fsyncSync').mockImplementation((fd) => { - if (fs.existsSync(progress)) { - if (fs.fstatSync(fd).isDirectory()) parentSynced = true; - else fileSynced = true; - } + if (fs.fstatSync(fd).isDirectory() && fs.existsSync(progress)) parentSynced = true; + else if (journalDescriptors.has(fd)) fileSynced = true; return originalSync(fd); }); const originalRun = context.run; diff --git a/scripts/selfhost/restore-identity.ts b/scripts/selfhost/restore-identity.ts index d0ee92bafd..9171e22f6a 100644 --- a/scripts/selfhost/restore-identity.ts +++ b/scripts/selfhost/restore-identity.ts @@ -1,33 +1,20 @@ /** A restored fleet gets its own ownership identity while retaining its data encryption keys. */ -import { createHash } from 'node:crypto'; import { existsSync, readFileSync } from 'node:fs'; -import { join, resolve } from 'node:path'; +import { join } from 'node:path'; import type { BoxContext } from './backup-lib'; import { assertOperatorExecution } from './operator-only'; +import { readRestoredInstallationId } from './restore-progress'; import { readPrivateJson, readSecretsFile, writePrivateFile } from './secret-files'; /** Stable for a retry of this target; never adopts the source fleet's VM ownership labels. */ export function restoredInstallationId(ctx: BoxContext, source: string): string { assertOperatorExecution(); if (!/^[a-f0-9]{32}$/.test(source)) throw new Error('Invalid backup installation identity'); - const identity = createHash('sha256') - .update( - JSON.stringify([ - 'sam-restored-installation/1', - source, - resolve(ctx.stateDir), - ctx.box.CELLD_BUCKET, - ]) - ) - .digest('hex') - .slice(0, 32); - if (identity === source) throw new Error('Restore installation identity collision'); - return identity; + return readRestoredInstallationId(ctx, source); } -/** Mutates only private decrypted scratch. Target output remains journal-owned and retryable. */ -export function projectRestoreIdentity(ctx: BoxContext, state: string): string { +function sourceKeys(ctx: BoxContext, state: string): Record { assertOperatorExecution(); if (ctx.box.SAM_INSTALLATION_ID !== undefined || process.env.SAM_INSTALLATION_ID !== undefined) throw new Error('Restore refuses an explicit installation identity override'); @@ -41,7 +28,22 @@ export function projectRestoreIdentity(ctx: BoxContext, state: string): string { throw new Error('Restore refuses an explicit installation identity override'); const path = join(state, 'platform-keys.json'); const keys = readPrivateJson(path); - const identity = restoredInstallationId(ctx, keys.SAM_INSTALLATION_ID ?? ''); + if (!/^[a-f0-9]{32}$/.test(keys.SAM_INSTALLATION_ID ?? '')) + throw new Error('Invalid backup installation identity'); + return keys; +} + +export function restoreSourceInstallationId(ctx: BoxContext, state: string): string { + return sourceKeys(ctx, state).SAM_INSTALLATION_ID as string; +} + +/** Mutates only private decrypted scratch using the target's durable random reservation. */ +export function projectRestoreIdentity(ctx: BoxContext, state: string, target?: string): string { + const keys = sourceKeys(ctx, state); + const identity = target ?? restoredInstallationId(ctx, keys.SAM_INSTALLATION_ID as string); + if (!/^[a-f0-9]{32}$/.test(identity) || identity === keys.SAM_INSTALLATION_ID) + throw new Error('Invalid restore target installation identity'); + const path = join(state, 'platform-keys.json'); writePrivateFile(path, JSON.stringify({ ...keys, SAM_INSTALLATION_ID: identity })); const configPath = join(state, 'project', 'wrangler.json'); if (existsSync(configPath)) { diff --git a/scripts/selfhost/restore-progress.ts b/scripts/selfhost/restore-progress.ts index c85ef0ce29..acc33e3670 100644 --- a/scripts/selfhost/restore-progress.ts +++ b/scripts/selfhost/restore-progress.ts @@ -1,5 +1,5 @@ /** Private retry ownership for a restore that started from an empty bucket and state directory. */ -import { createHash } from 'node:crypto'; +import { createHash, randomBytes } from 'node:crypto'; import { closeSync, constants, @@ -15,12 +15,12 @@ import { type Stats, writeSync, } from 'node:fs'; -import { dirname, join, resolve } from 'node:path'; +import { basename, dirname, join, resolve } from 'node:path'; import { prepareBackupParent } from './backup-destination'; import { assertBackupOutside, type BoxContext } from './backup-lib'; import { assertOperatorExecution } from './operator-only'; -import { assertPrivateFile } from './secret-files'; +import { assertPrivateFile, replacePrivateFile } from './secret-files'; function digest(path: string): string { const input = openSync(path, constants.O_RDONLY | constants.O_NOFOLLOW); @@ -99,15 +99,88 @@ export function assertRestoreSubset(current: string, expected: string, partialSt } } +interface TargetRecord { + format: 'sam-restore-progress/2'; + source: string; + bucket: string | undefined; + state: string; + environment: string; + domain: string; + endpoint: string; + backup: string; + snapshot: string; + targetInstallation: string; + phase: 'reserved' | 'started'; +} +function targetScope(ctx: BoxContext, source: string) { + return { + format: 'sam-restore-progress/2' as const, + source, + bucket: ctx.box.CELLD_BUCKET, + state: resolve(ctx.stateDir), + environment: resolve(ctx.envFile), + domain: ctx.box.SAM_DOMAIN ?? '', + endpoint: ctx.box.S3_ENDPOINT ?? '', + }; +} +function journalPaths(ctx: BoxContext): { progress: string; complete: string } { + return { + progress: `${resolve(ctx.stateDir)}.restore-progress.json`, + complete: `${resolve(ctx.stateDir)}.restore-complete.json`, + }; +} +function readTarget(ctx: BoxContext, source: string, path: string): TargetRecord { + try { + const stat = lstatSync(path); + if (!stat.isFile() || stat.isSymbolicLink()) throw new Error('Invalid journal'); + assertPrivateFile(path); + const raw: unknown = JSON.parse(readFileSync(path, 'utf8')); + if (!raw || typeof raw !== 'object' || Array.isArray(raw)) throw new Error('Invalid journal'); + const value = raw as Partial; + const scope = targetScope(ctx, source); + if ( + Object.entries(scope).some( + ([key, expected]) => value[key as keyof TargetRecord] !== expected + ) || + typeof value.backup !== 'string' || + resolve(value.backup) !== value.backup || + typeof value.snapshot !== 'string' || + !/^[a-f0-9]{64}$/.test(value.snapshot) || + typeof value.targetInstallation !== 'string' || + !/^[a-f0-9]{32}$/.test(value.targetInstallation) || + value.targetInstallation === source || + !['reserved', 'started'].includes(value.phase ?? '') + ) + throw new Error('Invalid journal'); + return value as TargetRecord; + } catch { + throw new Error( + 'Cannot verify restore retry ownership or target identity; preserve the target and its receipts for inspection' + ); + } +} +/** Read a reservation already made by authenticated print-project/restore, never derive a clone ID. */ +export function readRestoredInstallationId(ctx: BoxContext, source: string): string { + assertOperatorExecution(); + const paths = journalPaths(ctx); + const path = lstatSync(paths.progress, { throwIfNoEntry: false }) + ? paths.progress + : paths.complete; + return readTarget(ctx, source, path).targetInstallation; +} export interface RestoreProgress { - resume: boolean; + readonly resume: boolean; + readonly installationId: string; + reserve(): void; begin(): void; finish(): void; } -export function restoreProgress(ctx: BoxContext, backup: string): RestoreProgress { +export function restoreProgress(ctx: BoxContext, backup: string, source = ''): RestoreProgress { assertOperatorExecution(); - const progressPath = `${resolve(ctx.stateDir)}.restore-progress.json`; - const complete = `${resolve(ctx.stateDir)}.restore-complete.json`; + if (!/^[a-f0-9]{32}$/.test(source)) throw new Error('Invalid backup installation identity'); + const paths = journalPaths(ctx); + const progressPath = paths.progress, + complete = paths.complete; let journal = lstatSync(progressPath, { throwIfNoEntry: false }) || !lstatSync(complete, { throwIfNoEntry: false }) @@ -115,28 +188,35 @@ export function restoreProgress(ctx: BoxContext, backup: string): RestoreProgres : complete; assertBackupOutside(ctx, progressPath); assertBackupOutside(ctx, complete); - const expected = JSON.stringify({ - format: 'sam-restore-progress/1', - bucket: ctx.box.CELLD_BUCKET, - state: resolve(ctx.stateDir), + let identity = lstatSync(journal, { throwIfNoEntry: false }); + const expectedScope = { + ...targetScope(ctx, source), backup: resolve(backup), snapshot: digest(join(backup, '.sam-backup-manifest')), - }); - const existing = lstatSync(journal, { throwIfNoEntry: false }); + }; + let record: TargetRecord = identity + ? readTarget(ctx, source, journal) + : { ...expectedScope, targetInstallation: randomBytes(16).toString('hex'), phase: 'reserved' }; + if (record.targetInstallation === source) + throw new Error('Restore installation identity collision'); const validate = (path = journal): void => { - try { - if (lstatSync(path).isSymbolicLink()) throw new Error('Invalid journal'); - assertPrivateFile(path); - if (readFileSync(path, 'utf8') !== expected) throw new Error('Different restore'); - } catch { + const current = readTarget(ctx, source, path); + if ( + JSON.stringify(current) !== JSON.stringify(record) || + Object.entries(expectedScope).some( + ([key, value]) => current[key as keyof TargetRecord] !== value + ) + ) throw new Error( 'Cannot verify restore retry ownership; preserve the partial target for inspection' ); - } }; - if (existing) validate(); - if (lstatSync(complete, { throwIfNoEntry: false })) validate(complete); - let identity = existing; + if (identity) validate(); + if (lstatSync(complete, { throwIfNoEntry: false })) { + validate(complete); + if (record.phase !== 'started') + throw new Error('Invalid completed restore identity reservation'); + } const syncParent = (): void => { const fd = openSync(dirname(journal), 'r'); try { @@ -145,68 +225,92 @@ export function restoreProgress(ctx: BoxContext, backup: string): RestoreProgres closeSync(fd); } }; - const persist = (path: string): void => { - prepareBackupParent(path); - const fd = openSync(path, 'wx', 0o600); - const created = fstatSync(fd); + const verifyIdentity = (): void => { + validate(); + const current = lstatSync(journal); + if (current.dev !== identity?.dev || current.ino !== identity?.ino) + throw new Error('Restore retry ownership changed'); + const fd = openSync(journal, constants.O_RDONLY | constants.O_NOFOLLOW); try { - const data = Buffer.from(expected); + const opened = fstatSync(fd); + if (opened.dev !== identity?.dev || opened.ino !== identity?.ino) + throw new Error('Restore retry ownership changed'); + fsyncSync(fd); + } finally { + closeSync(fd); + } + syncParent(); + validate(); + }; + const persist = (): void => { + prepareBackupParent(journal); + const temp = join( + dirname(journal), + `.${basename(journal)}.${randomBytes(16).toString('hex')}.tmp` + ); + const fd = openSync(temp, 'wx', 0o600); + try { + const data = Buffer.from(JSON.stringify(record)); let offset = 0; while (offset < data.length) { const written = writeSync(fd, data, offset, data.length - offset); - if (written === 0) throw new Error('Cannot persist restore retry ownership'); + if (!written) throw new Error('Cannot persist restore retry ownership'); offset += written; } fsyncSync(fd); - } catch (error) { - // No target writes precede this initial receipt. Remove only this attempt's fresh inode. - const current = lstatSync(path, { throwIfNoEntry: false }); - if (current?.dev === created.dev && current.ino === created.ino) rmSync(path); - throw error; + // No replace: concurrent reservations cannot overwrite the winning random identity. + linkSync(temp, journal); } finally { closeSync(fd); + rmSync(temp, { force: true }); } + identity = lstatSync(journal); + syncParent(); + validate(); }; return { - resume: Boolean(existing), - begin() { - if (existing) { - validate(); - const current = lstatSync(journal); - if (current.dev !== identity?.dev || current.ino !== identity?.ino) - throw new Error('Restore retry ownership changed'); - const fd = openSync(journal, constants.O_RDONLY | constants.O_NOFOLLOW); + get resume() { + return Boolean(identity && record.phase === 'started'); + }, + get installationId() { + return record.targetInstallation; + }, + reserve() { + if (identity) verifyIdentity(); + else { try { - const opened = fstatSync(fd); - if (opened.dev !== identity?.dev || opened.ino !== identity?.ino) - throw new Error('Restore retry ownership changed'); - fsyncSync(fd); - } finally { - closeSync(fd); + persist(); + } catch (error) { + if ((error as NodeJS.ErrnoException).code !== 'EEXIST') throw error; + // Read and durably reuse the winner rather than replacing its nonce. + record = readTarget(ctx, source, journal); + identity = lstatSync(journal); + verifyIdentity(); } - syncParent(); - validate(); - return; } - persist(journal); - identity = lstatSync(journal); - syncParent(); - validate(); + }, + begin() { + if (identity) { + verifyIdentity(); + if (record.phase === 'reserved') { + record = { ...record, phase: 'started' }; + replacePrivateFile(journal, JSON.stringify(record)); + identity = lstatSync(journal); + validate(); + } + } else { + record = { ...record, phase: 'started' }; + persist(); + } }, finish() { - validate(); - const current = lstatSync(journal); - if (current.dev !== identity?.dev || current.ino !== identity?.ino) - throw new Error('Restore retry ownership changed'); + if (record.phase !== 'started') throw new Error('Restore has not started'); + verifyIdentity(); if (!lstatSync(complete, { throwIfNoEntry: false })) linkSync(journal, complete); validate(complete); - // Make completion durable before unlinking progress: every error leaves a retry receipt. syncParent(); if (journal === progressPath) { - validate(); - const live = lstatSync(journal); - if (live.dev !== identity?.dev || live.ino !== identity?.ino) - throw new Error('Restore retry ownership changed'); + verifyIdentity(); rmSync(journal); journal = complete; identity = lstatSync(complete); diff --git a/tasks/archive/2026-11-19-l24-selfhost-operations.md b/tasks/archive/2026-11-19-l24-selfhost-operations.md index 5dcd52234d..ff55ce4007 100644 --- a/tasks/archive/2026-11-19-l24-selfhost-operations.md +++ b/tasks/archive/2026-11-19-l24-selfhost-operations.md @@ -93,6 +93,16 @@ Ten real-CLI scenarios cover uninterrupted recovery, SIGKILL after receipt publi Final delta validation: full self-host suite 995 passed, four conditional skips, 56 files; TypeScript, focused lint, formatting, diff and secret-readback scanner pass. Independent security and completion/documentation/constitution delta reviews pass with no unresolved finding. FIFO receipts refuse before opening and malformed key diagnostics withhold source contents. +## Independent clone and GCP receipt scope review delta + +Review 4638509411 found that deterministic IDs could collide across independent hosts with identical target paths and bucket names. Restore now persists a random 128-bit target identity in the existing private v2 journal. Authenticated print-project reserves that identity without writing state or bucket data; reserved phase still requires empty state and bucket checks. Started phase is durable before target writes. Atomic no-replace publication preserves a concurrent reservation winner; actual restore safely refuses a competing publication rather than changing an already projected identity. Retries bind the snapshot and target scope and preserve the ID. Legacy v1 journals fail closed and remain available for inspection. + +Identity tests failed five cases on the old implementation, then passed with the fix: identical-path independent hosts, stable print/restore/retry, cross-clone VM deletion refusal with own-clone liveness, occupied state and bucket after reservation, and legacy-journal refusal. The emitted CLI asserts that print-project creates only private sibling metadata. Initial-journal write/sync fault injection follows the actual temporary descriptor and verifies no target writes before durable publication and retry sync. + +Review 4638509415 found shared receipt keys could replace another GCP project's pool/provider/firewall proof. Bootstrap now refuses all active GCP receipts for different or unrecorded projects before issuer or cloud calls, even without installation ID and in dry-run mode. Five refusal controls failed on old code; all 54 bootstrap tests pass, including same-project and removed-record controls. Refusal preserves exact receipt bytes and cloud state. Per-project receipt namespacing is deferred to idea 01M7VMRP6RY7EHCHDCN49VT0FT alongside earlier crash-window follow-up 01M7VB4538WSGP3QBP8EBDVTZA; operators use separate state directories now. + +Full self-host suite: 1006 passed, four conditional skips, 56 files. TypeScript, focused lint, formatting, diff check and secret-readback scan pass. Independent security, task completion, doc-sync and constitution delta reviews pass. Original BOX evidence remains valid; the accepted coordinator-owned combined H2/L24 post-merge upgrade/rollback smoke remains owed. + ## References PR https://github.com/raphaeltm/simple-agent-manager/pull/2918; idea01M72M9AEB933ZY8269D376DKC LANDING PLAN part6; SAM task01M7TTKAS78AMJ3853S5N4BYAK; coordinator01M7JMXS2JRW6QQMB1356ENPM3; policy795e72a6; rule56; `/do`. From be24db7669ccdc313efc943dfdbd5bd579a64585 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rapha=C3=ABl=20Titsworth-Morin?= Date: Fri, 20 Nov 2026 05:17:48 +0000 Subject: [PATCH 17/17] fix(selfhost): commit healthy upgrade and recovery before cleanup --- deploy/selfhost/README.md | 15 +- scripts/selfhost/upgrade-journal.ts | 74 ++++++++ scripts/selfhost/upgrade-lib.ts | 51 +++--- scripts/selfhost/upgrade-rollback.test.ts | 2 +- scripts/selfhost/upgrade.test.ts | 170 ++++++++++++++++++ .../2026-11-19-l24-selfhost-operations.md | 8 + 6 files changed, 290 insertions(+), 30 deletions(-) create mode 100644 scripts/selfhost/upgrade-journal.ts diff --git a/deploy/selfhost/README.md b/deploy/selfhost/README.md index d6ccba7b85..73c3d7fb1c 100644 --- a/deploy/selfhost/README.md +++ b/deploy/selfhost/README.md @@ -214,6 +214,17 @@ for inspection instead of bypassing ownership. ## Upgrade +After target deployment or restoration of the previous version, upgrade durably records that +health verification is in progress. If +verification is interrupted, a retry refuses automatic snapshot recovery: preserve live data and +inspect the stack before choosing an explicit rollback. A returned health failure still triggers +automatic rollback. Once health succeeds, both a successful upgrade and recovery of the previous version durably +commit completion before removing their recovery marker and syncing the state directory. A stale completed marker permits cleanup only, +never restoration of the pre-upgrade snapshot. An invalid phase or different checkout refuses. +If deployment is interrupted before health verification begins, retry still recovers the original +snapshot. **Writes accepted during that unverified upgrade window are discarded on rollback.** +Holding traffic until verification is tracked separately; schedule upgrades accordingly. + ```sh pnpm selfhost:upgrade --to --encryption-key-file "$HOME/.config/sam/backup.key" ``` @@ -241,7 +252,9 @@ migration. An unfinished operation retains `.state/upgrade-pending.json` with the previous ref and encrypted snapshot path and resolved target SHA. Keep celld stopped if automatic recovery fails; retain the -snapshot and key, and retry the same resolved target to recover the original install. A changed +snapshot and key. A pre-verification pending record permits retrying the same resolved target +to recover the original install. An interrupted verification or uncertain completion instead +requires inspection as described above; a valid completed marker permits cleanup only. A changed `--to`, a moved branch/tag, or an older journal without a target requires the explicit rollback command before choosing another target. Do not delete the pending record to bypass a failed recovery. diff --git a/scripts/selfhost/upgrade-journal.ts b/scripts/selfhost/upgrade-journal.ts new file mode 100644 index 0000000000..fefd6669b9 --- /dev/null +++ b/scripts/selfhost/upgrade-journal.ts @@ -0,0 +1,74 @@ +/** Upgrade completion is committed before recovery metadata is removed. */ +import { + closeSync, + existsSync, + fsyncSync, + lstatSync, + openSync, + readFileSync, + rmSync, +} from 'node:fs'; +import { isAbsolute, join } from 'node:path'; + +import { assertPrivateFile, replacePrivateFile } from './secret-files.js'; + +export const UPGRADE_PENDING_FILE = 'upgrade-pending.json'; +function sync(path: string): void { + const fd = openSync(path, 'r'); + try { + fsyncSync(fd); + } finally { + closeSync(fd); + } +} +export function clearUpgradeJournal(stateDir: string): void { + rmSync(join(stateDir, UPGRADE_PENDING_FILE), { force: true }); + sync(stateDir); +} +export function completeUpgradeJournal( + stateDir: string, + record: { from: string; to: string; backupDir: string } +): void { + replacePrivateFile( + join(stateDir, UPGRADE_PENDING_FILE), + JSON.stringify({ ...record, phase: 'completed' }) + ); + clearUpgradeJournal(stateDir); +} +/** A terminal marker authorizes cleanup, never restoration of its old snapshot. */ +export function readPendingFrom(stateDir: string, head: string): string | null { + const path = join(stateDir, UPGRADE_PENDING_FILE); + if (!existsSync(path)) return null; + let record: Record; + try { + const stat = lstatSync(path); + if (!stat.isFile() || stat.isSymbolicLink()) throw new Error('Invalid record'); + const raw: unknown = JSON.parse(readFileSync(path, 'utf8')); + if (!raw || typeof raw !== 'object' || Array.isArray(raw)) throw new Error('Invalid record'); + record = raw as Record; + if (typeof record.from !== 'string' || !/^[0-9a-f]{40}$/.test(record.from)) + throw new Error('Invalid ref'); + } catch { + throw new Error( + `${path} is not a record this upgrade wrote; preserve the target and recovery metadata for inspection` + ); + } + if (record.phase === undefined) return record.from as string; + if ( + record.phase !== 'completed' || + typeof record.to !== 'string' || + !/^[0-9a-f]{40}$/.test(record.to) || + record.to !== head || + typeof record.backupDir !== 'string' || + !isAbsolute(record.backupDir) + ) + throw new Error( + 'Upgrade verification or completion is uncertain; preserve live data and use explicit rollback only after inspection' + ); + assertPrivateFile(path); + // Reestablish durability if the completed rename was observed before a failed directory sync. + sync(path); + sync(stateDir); + clearUpgradeJournal(stateDir); + return null; +} diff --git a/scripts/selfhost/upgrade-lib.ts b/scripts/selfhost/upgrade-lib.ts index 4d617b93f2..3c12d5401f 100644 --- a/scripts/selfhost/upgrade-lib.ts +++ b/scripts/selfhost/upgrade-lib.ts @@ -5,7 +5,7 @@ * record; retry recovers the old installation first, then starts a fresh upgrade. */ import { spawnSync } from 'node:child_process'; -import { existsSync, mkdirSync, readFileSync, rmSync } from 'node:fs'; +import { existsSync, mkdirSync, readFileSync } from 'node:fs'; import { dirname, join, resolve } from 'node:path'; import { @@ -36,6 +36,12 @@ import { stateFingerprint, } from './upgrade-compose.js'; import { rollbackSteps } from './upgrade-instructions.js'; +import { + clearUpgradeJournal, + completeUpgradeJournal, + readPendingFrom, + UPGRADE_PENDING_FILE, +} from './upgrade-journal.js'; import { assertMigrationProgression, type DoMigration, @@ -53,7 +59,7 @@ import { const MIGRATIONS_DIR = 'apps/api/src/db/migrations/'; /** Pending original source/target SHAs and encrypted snapshot path, retained through recovery. */ -export const UPGRADE_PENDING_FILE = 'upgrade-pending.json'; +export { UPGRADE_PENDING_FILE } from './upgrade-journal.js'; export interface RunResult { status: number; @@ -200,8 +206,13 @@ export async function recoverUpgrade( ); } startRecoveredStack(ctx, backupDir, env); + replacePrivateFile( + pendingPath, + JSON.stringify({ from, ...(to ? { to } : {}), backupDir, phase: 'verifying' }) + ); if (!(await opts.checkHealth())) throw new Error('previous version health check failed'); finishRollbackCache(backupContext(ctx)); + completeUpgradeJournal(ctx.stateDir, { from, to: from, backupDir }); } function startRecoveredStack(ctx: BoxContext, backupDir: string, env?: NodeJS.ProcessEnv): void { @@ -222,26 +233,6 @@ function startRecoveredStack(ctx: BoxContext, backupDir: string, env?: NodeJS.Pr refreshRollbackCacheReceipt(backupContext(ctx), backupDir); } -/** The ref an unfinished upgrade started from (`UPGRADE_PENDING_FILE`), or null. */ -function readPendingFrom(stateDir: string): string | null { - const path = join(stateDir, UPGRADE_PENDING_FILE); - if (!existsSync(path)) return null; - let from: unknown; - try { - const record = JSON.parse(readFileSync(path, 'utf8')) as unknown; - if (typeof record === 'object' && record !== null && 'from' in record) from = record.from; - } catch { - from = undefined; - } - if (typeof from !== 'string' || !/^[0-9a-f]{40}$/.test(from)) { - throw new Error( - `${path} is not a record this upgrade wrote; check which ref the box last deployed ` + - 'successfully, check it out, and delete the file' - ); - } - return from; -} - type Git = (args: string[], what?: string) => string; /** `origin/` after the fetch, else `` as given (a tag or a commit). */ @@ -323,6 +314,10 @@ async function applyUpgrade( ctx.log('compose inputs unchanged; the stack keeps running'); } pnpm(['selfhost:deploy', ...plan.boxArgs]); + // A killed health check may already have admitted writes: never infer rollback is safe. + const pendingPath = join(ctx.stateDir, UPGRADE_PENDING_FILE); + const pending = JSON.parse(readFileSync(pendingPath, 'utf8')); + replacePrivateFile(pendingPath, JSON.stringify({ ...pending, phase: 'verifying' })); if (!(await opts.checkHealth())) throw new Error('the API is not healthy after the upgrade'); return composeRestarted; } @@ -342,10 +337,9 @@ async function recoverPendingUpgrade( } catch { stopCelldAfterFailure(ctx); throw new Error( - 'unfinished upgrade recovery failed; keep celld stopped and retry using the recorded encrypted snapshot' + 'unfinished upgrade recovery failed; keep celld stopped, inspect the journal and live data before explicit recovery' ); } - rmSync(pendingPath, { force: true }); } function stopCelldAfterFailure(ctx: BoxContext): void { @@ -372,13 +366,13 @@ async function rollbackFailedUpgrade( } else { git(['checkout', '--detach', from]); check(ctx.run('pnpm', ['install', '--frozen-lockfile']), 'restore previous dependencies'); + clearUpgradeJournal(ctx.stateDir); } - rmSync(join(ctx.stateDir, UPGRADE_PENDING_FILE), { force: true }); ctx.log('automatic rollback completed'); } catch { if (progress.deploymentStarted) stopCelldAfterFailure(ctx); throw new Error( - 'upgrade failed and automatic rollback did not complete; keep celld stopped and retry using the recorded encrypted snapshot' + 'upgrade failed and automatic rollback did not complete; keep celld stopped, inspect the journal and live data before explicit recovery' ); } } @@ -396,7 +390,7 @@ export async function runUpgrade(ctx: BoxContext, opts: UpgradeOptions): Promise } git(['fetch', '--tags', 'origin']); const head = git(['rev-parse', 'HEAD']); - const pendingFrom = readPendingFrom(ctx.stateDir); + const pendingFrom = readPendingFrom(ctx.stateDir, head); // A pending record means the checkout may be ahead of what is deployed: start from the record. const from = pendingFrom ?? head; const to = resolveUpgradeTarget(git, opts.to); @@ -488,7 +482,8 @@ export async function runUpgrade(ctx: BoxContext, opts: UpgradeOptions): Promise throw error; } - rmSync(pendingPath, { force: true }); + // Completion/cleanup failure must never enter automatic rollback after health succeeded. + completeUpgradeJournal(ctx.stateDir, { from, to, backupDir }); const { imagesRebuilt } = progress; const rollback = rollbackSteps(ctx, from, backupDir, imagesRebuilt); diff --git a/scripts/selfhost/upgrade-rollback.test.ts b/scripts/selfhost/upgrade-rollback.test.ts index 9cee8de96a..b7c9e4f213 100644 --- a/scripts/selfhost/upgrade-rollback.test.ts +++ b/scripts/selfhost/upgrade-rollback.test.ts @@ -236,7 +236,7 @@ describe('manual owned rollback', () => { const pending = JSON.parse( readFileSync(join(ctx.stateDir, UPGRADE_PENDING_FILE), 'utf8') ) as unknown; - expect(pending).toEqual({ from: FROM, backupDir: join(root, 'snapshot') }); + expect(pending).toEqual({ from: FROM, backupDir: join(root, 'snapshot'), phase: 'verifying' }); expect(steps.at(-3)).toMatch(/ stop celld$/); expect(steps.slice(-2)).toEqual([ `git checkout --detach ${OPERATOR_REF}`, diff --git a/scripts/selfhost/upgrade.test.ts b/scripts/selfhost/upgrade.test.ts index a80a916856..9226175dff 100644 --- a/scripts/selfhost/upgrade.test.ts +++ b/scripts/selfhost/upgrade.test.ts @@ -6,6 +6,7 @@ * whose build inputs changed (never `up --build`), that interrupted recovery retains its original snapshot for retry, and that * the printed rollback selects the same box and matches whether the upgrade carried a D1 migration. */ +import * as fs from 'node:fs'; import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'; import { join, resolve } from 'node:path'; @@ -24,6 +25,8 @@ import { UPGRADE_PENDING_FILE, } from './upgrade-lib.js'; +vi.mock('node:fs', async (original) => ({ ...(await original()) })); + vi.mock('./backup-lib.js', async (original) => ({ ...(await original()), runBackup: vi.fn(), @@ -175,6 +178,7 @@ beforeEach(() => { }); afterEach(() => { + vi.restoreAllMocks(); vi.unstubAllEnvs(); rmSync(root, { recursive: true, force: true }); }); @@ -374,6 +378,172 @@ describe('runUpgrade', () => { expect(steps).toEqual(['git fetch --tags origin']); }); + it.each([ + 'unlink-before', + 'unlink-lost', + 'completion-file-sync', + 'completion-parent-sync', + 'unlink-parent-sync', + ] as const)( + 'preserves accepted live writes after successful health and interrupted %s', + async (boundary) => { + const pending = join(root, 'state', UPGRADE_PENDING_FILE); + const data = join(root, 'state/accepted-data'); + let healthy = false, + injected = false, + completionWritten = false; + const originalRm = fs.rmSync, + originalSync = fs.fsyncSync, + originalWrite = fs.writeSync; + vi.spyOn(fs, 'writeSync').mockImplementation((...args: Parameters) => { + const result = Reflect.apply(originalWrite, fs, args); + if (healthy && /"phase"\s*:\s*"completed"/.test(String(args[1]))) completionWritten = true; + return result; + }); + vi.spyOn(fs, 'rmSync').mockImplementation((path, options) => { + if ( + !injected && + healthy && + String(path) === pending && + ['unlink-before', 'unlink-lost'].includes(boundary) + ) { + injected = true; + if (boundary === 'unlink-before') throw new Error('Injected pending unlink failure'); + const retained = readFileSync(pending, 'utf8'); + originalRm(path, options); + // Model the directory entry reappearing after a power loss without parent fsync. + writeFileSync(pending, retained, { mode: 0o600 }); + return; + } + return originalRm(path, options); + }); + vi.spyOn(fs, 'fsyncSync').mockImplementation((fd) => { + originalSync(fd); + if (injected || !healthy) return; + const directory = fs.fstatSync(fd).isDirectory(); + const completed = + existsSync(pending) && /"phase"\s*:\s*"completed"/.test(readFileSync(pending, 'utf8')); + if ( + (boundary === 'completion-file-sync' && !directory && completionWritten) || + (boundary === 'completion-parent-sync' && directory && completed) || + (boundary === 'unlink-parent-sync' && + directory && + completionWritten && + !existsSync(pending)) + ) { + injected = true; + throw new Error('Injected completion durability failure'); + } + }); + vi.mocked(runRollback).mockImplementation(() => writeFileSync(data, 'old snapshot rows')); + const health = vi.fn(async () => { + healthy = true; + writeFileSync(data, 'accepted live writes'); + return true; + }); + try { + await runUpgrade(ctx(), { to: 'v2026.11.12', checkHealth: health }); + } catch { + /* A completion durability failure must remain safe to retry. */ + } + expect(health).toHaveBeenCalledOnce(); + expect(injected).toBe(true); + expect(head).toBe(TO); + expect(readFileSync(data, 'utf8')).toBe('accepted live writes'); + expect(runRollback).not.toHaveBeenCalled(); + vi.restoreAllMocks(); + vi.mocked(runBackup).mockClear(); + vi.mocked(runRollback).mockClear(); + steps = []; + const retryHealth = vi.fn(async () => true); + let retryError: unknown; + try { + await runUpgrade(ctx(), { to: 'v2026.11.12', checkHealth: retryHealth }); + } catch (error) { + retryError = error; + } + if (boundary === 'completion-file-sync') { + if (retryError) expect(String(retryError)).toMatch(/verification|completion/); + } else expect(retryError).toBeUndefined(); + expect(readFileSync(data, 'utf8')).toBe('accepted live writes'); + expect(head).toBe(TO); + expect(runRollback).not.toHaveBeenCalled(); + expect(runBackup).not.toHaveBeenCalled(); + expect(retryHealth).not.toHaveBeenCalled(); + expect(steps.some((step) => /selfhost:deploy|checkout|docker/.test(step))).toBe(false); + if (boundary !== 'completion-file-sync') expect(existsSync(pending)).toBe(false); + } + ); + + it.each(['before-unlink', 'lost-unlink'] as const)( + 'never replays the snapshot after healthy automatic recovery and %s interruption', + async (boundary) => { + const pending = join(root, 'state', UPGRADE_PENDING_FILE); + const data = join(root, 'state/recovered-live-data'); + let healthCalls = 0, + injected = false; + const originalRm = fs.rmSync; + vi.mocked(runRollback).mockImplementation(() => writeFileSync(data, 'old snapshot rows')); + vi.spyOn(fs, 'rmSync').mockImplementation((path, options) => { + if (!injected && healthCalls === 2 && String(path) === pending) { + injected = true; + if (boundary === 'before-unlink') + throw new Error('Injected recovered cleanup interruption'); + const retained = readFileSync(pending, 'utf8'); + originalRm(path, options); + writeFileSync(pending, retained, { mode: 0o600 }); + return; + } + return originalRm(path, options); + }); + const health = vi.fn(async () => { + healthCalls += 1; + if (healthCalls === 1) return false; + writeFileSync(data, 'accepted recovery writes'); + return true; + }); + await expect(runUpgrade(ctx(), { to: 'v2026.11.12', checkHealth: health })).rejects.toThrow(); + expect(health).toHaveBeenCalledTimes(2); + expect(injected).toBe(true); + expect(head).toBe(FROM); + expect(readFileSync(data, 'utf8')).toBe('accepted recovery writes'); + expect(runRollback).toHaveBeenCalledOnce(); + expect(existsSync(pending)).toBe(true); + vi.restoreAllMocks(); + vi.mocked(runRollback).mockClear(); + await runUpgrade(ctx(), { to: 'v2026.11.12', checkHealth: async () => true }); + expect(readFileSync(data, 'utf8')).toBe('accepted recovery writes'); + expect(runRollback).not.toHaveBeenCalled(); + expect(head).toBe(TO); + expect(existsSync(pending)).toBe(false); + } + ); + + it.each(['source', 'target', 'snapshot', 'phase', 'head', 'public-file'] as const)( + 'refuses a completed marker with invalid %s without restoring or deploying', + async (defect) => { + head = defect === 'head' ? FROM : TO; + const originalHead = head; + const pending = join(root, 'state', UPGRADE_PENDING_FILE); + const marker = { + from: defect === 'source' ? 'HEAD~1' : FROM, + to: defect === 'target' ? 'c'.repeat(40) : TO, + backupDir: defect === 'snapshot' ? 'relative/path' : join(root, 'snapshot'), + phase: defect === 'phase' ? 'unrecognized' : 'completed', + }; + const bytes = JSON.stringify(marker); + writeFileSync(pending, bytes, { mode: defect === 'public-file' ? 0o644 : 0o600 }); + const health = vi.fn(async () => true); + await expect(runUpgrade(ctx(), { to: 'v2026.11.12', checkHealth: health })).rejects.toThrow(); + expect(readFileSync(pending, 'utf8')).toBe(bytes); + expect(head).toBe(originalHead); + expect(runRollback).not.toHaveBeenCalled(); + expect(runBackup).not.toHaveBeenCalled(); + expect(health).not.toHaveBeenCalled(); + expect(steps.some((step) => /selfhost:deploy|checkout|docker/.test(step))).toBe(false); + } + ); + it('control: a completed upgrade leaves no pending record and is not repeated', async () => { await upgrade(); expect(existsSync(join(root, 'state', UPGRADE_PENDING_FILE))).toBe(false); diff --git a/tasks/archive/2026-11-19-l24-selfhost-operations.md b/tasks/archive/2026-11-19-l24-selfhost-operations.md index ff55ce4007..cd88769e31 100644 --- a/tasks/archive/2026-11-19-l24-selfhost-operations.md +++ b/tasks/archive/2026-11-19-l24-selfhost-operations.md @@ -103,6 +103,14 @@ Review 4638509415 found shared receipt keys could replace another GCP project's Full self-host suite: 1006 passed, four conditional skips, 56 files. TypeScript, focused lint, formatting, diff check and secret-readback scan pass. Independent security, task completion, doc-sync and constitution delta reviews pass. Original BOX evidence remains valid; the accepted coordinator-owned combined H2/L24 post-merge upgrade/rollback smoke remains owed. +## Healthy upgrade and recovery completion delta + +Review 4638641086 exposed stale pending metadata after healthy upgrade cleanup. A retry could restore the original snapshot and discard accepted live writes. Upgrade now durably records verification before health; interruption or unknown phases refuse automatic recovery. A successful new version or recovered old version commits a private completed phase before cleanup, followed by state-directory sync. Completed retry validates full source/target refs, snapshot path, private ownership and actual checkout before cleanup only; it never replays the old snapshot. Recovery owns terminal cleanup once, with no outer duplicate deletion. Completion failure after health cannot enter automatic rollback. A returned unhealthy result still follows the normal rollback path. + +Thirteen new controls include real unlink, file/parent sync faults, invalid completion scope/private modes and two recovered-version cleanup interruptions. Six completion controls failed on old code, including two direct accepted-write sentinel losses; both adjacent recovery controls independently reproduced accepted recovery writes overwritten by snapshot rows. All 69 upgrade tests and 24 manual rollback tests pass after both fixes. Final full suite: 1019 passed, four conditional skips, 56 files (two workers). TypeScript, focused lint, formatting, diff and secret-readback checks pass. Security, task completion, doc-sync and constitution delta reviews pass. + +The coordinator explicitly retains the earlier unverified deployment recovery policy: writes accepted before verification can be discarded on snapshot rollback. README states this plainly; traffic fencing is tracked in idea 01M7VNSGPNHEZHKD9P021128YR. Security review did not classify this intentional existing operational tradeoff HIGH/CRITICAL. The adjacent recovered-version completion issue from idea 01M7VNSH879F53JTQA5AQ5YWJ0 is fixed in this delta. + ## References PR https://github.com/raphaeltm/simple-agent-manager/pull/2918; idea01M72M9AEB933ZY8269D376DKC LANDING PLAN part6; SAM task01M7TTKAS78AMJ3853S5N4BYAK; coordinator01M7JMXS2JRW6QQMB1356ENPM3; policy795e72a6; rule56; `/do`.