From cbbf2edd1ed3ff30a3e6381783d45cbb18cfde1f Mon Sep 17 00:00:00 2001 From: "congvc-bot[bot]" <3634010+congvc-bot[bot]@users.noreply.github.com> Date: Fri, 20 Nov 2026 22:28:28 +0700 Subject: [PATCH 1/2] =?UTF-8?q?ci(doop):=20train=20S3b=20=E2=80=94=20audit?= =?UTF-8?q?ed=20lift=20workflow=20(CHE-5551)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Add cd-lift.yml, the only way from armed/suspended back to clear (plan CHE-5474 C-10.6, C-10.7). Dispatch only, one input (decision_id), allowlisted dispatcher, C00 runner under the host deploy lock. scripts/deploy-lift.mjs refuses unless the Multica decision is an approved doop.deploy_lift by the configured approver, not withdrawn/revoked/expired, its marker_value equals the standing marker and repo matches, quiescence and /healthz are proven, and the decision and marker still hold when re-read right before the write. It then writes clear::, reads it back and records lift-evidence.json. A refusal leaves the marker unchanged. c00.sh gains a `lift` command (guard, lock, quiescence, digest, revision label, container health). deploy-marker.mjs gains lift() and exports readMarker(). The train switch DOOP_DEPLOY_TRAIN is not touched. --- .context/RELEASE.md | 4 + .context/TECHSTACK.md | 5 + .github/workflows/cd-deploy.yml | 4 +- .github/workflows/cd-lift.yml | 99 +++++ deploy/cd/README.md | 44 +- deploy/cd/c00.sh | 27 +- eslint.config.js | 2 +- scripts/deploy-lift.mjs | 311 +++++++++++++ scripts/deploy-marker.mjs | 20 +- tests/c00Lift.test.ts | 170 +++++++ tests/deployLift.test.ts | 740 +++++++++++++++++++++++++++++++ tests/deployLiftWorkflow.test.ts | 160 +++++++ tests/deployMarker.test.ts | 49 +- 13 files changed, 1618 insertions(+), 17 deletions(-) create mode 100644 .github/workflows/cd-lift.yml create mode 100644 scripts/deploy-lift.mjs create mode 100644 tests/c00Lift.test.ts create mode 100644 tests/deployLift.test.ts create mode 100644 tests/deployLiftWorkflow.test.ts diff --git a/.context/RELEASE.md b/.context/RELEASE.md index 29b06c0f2..bbdaf0da8 100644 --- a/.context/RELEASE.md +++ b/.context/RELEASE.md @@ -53,6 +53,10 @@ confirm, and written `suspended:*` (never clear) by recovery, drill and rollback and a GitHub App token from environment `doop-deploy-marker`. Setup and rules: [`deploy/cd/README.md`](../deploy/cd/README.md). +Lifting a suspension is `cd-lift.yml` (S3b): dispatch with the id of an approved Multica decision; it checks the +decision against the standing marker, proves quiescence and health on C00, and writes `clear:*` with evidence. +It never turns the train on. + ## Desktop app (Tauri: macOS DMG + Windows NSIS installer + Linux AppImage/.deb/.rpm) Driven by `.github/workflows/desktop-release.yml`; every desktop job shares the toolchain setup diff --git a/.context/TECHSTACK.md b/.context/TECHSTACK.md index 8129b3225..49a5ca357 100644 --- a/.context/TECHSTACK.md +++ b/.context/TECHSTACK.md @@ -1125,6 +1125,11 @@ data-doop-webfonts>` for the roster families the frame names and does not load i - `.github/workflows/cd-deploy.yml` - D2, the only workflow that deploys to C00: schedule (3 a day) and dispatch, off unless repo variable `DOOP_DEPLOY_TRAIN` is `on`; the `DOOP_DEPLOY_SUSPENDED` marker is written only by `scripts/deploy-marker.mjs`. See `deploy/cd/README.md`. + - `.github/workflows/cd-lift.yml` - S3b, the audited lift: dispatch only (`decision_id`), allowlisted dispatcher, + C00 runner under the deploy lock. Writes `clear:*` only for an approved `doop.deploy_lift` Multica decision whose + `marker_value` equals the standing marker, with quiescence and `/healthz` proven and the decision and marker + re-read before the write; evidence in `lift-evidence.json`. Logic in `scripts/deploy-lift.mjs` + (`c00.sh lift` supplies the C00 facts). Never touches `DOOP_DEPLOY_TRAIN`. - `.github/workflows/cd-freshness-watch.yml` and `cd-live-revision.yml` - the two D2 watchers (every 15 min): a backup `schedule_backup` dispatch when D2 is 45 min late (alarm at 90 min), and a check that C00's `/healthz` `revision` is not behind the last successful D2 SHA. Both idle while `DOOP_DEPLOY_TRAIN` is not `on`. diff --git a/.github/workflows/cd-deploy.yml b/.github/workflows/cd-deploy.yml index d55ef45f0..78a2901ab 100644 --- a/.github/workflows/cd-deploy.yml +++ b/.github/workflows/cd-deploy.yml @@ -20,7 +20,7 @@ name: CD deploy # The suspension marker (repo variable DOOP_DEPLOY_SUSPENDED, CHE-5545, plan C-10) is written only by the three # C00 jobs, with scripts/deploy-marker.mjs: a train run arms it before its first change and only a passing # confirm of that same run restores it; recovery and drill runs, and a rollback, write `suspended:*` and never -# `clear:*`. Every failure leaves it armed or suspended, which stops the train. Lifting is S3b. +# `clear:*`. Every failure leaves it armed or suspended, which stops the train. Lifting is cd-lift.yml. # The train ships OFF: the repository variable DOOP_DEPLOY_TRAIN is absent or not 'on', so a scheduled run # ends at `resolve` as a clean skip. # Schedule: 23:17, 07:17 and 15:17 UTC = 06:17, 14:17 and 22:17 ICT. @@ -392,7 +392,7 @@ jobs: repositories: doop permission-variables: write # Whatever the rollback did, even if it failed: this run's armed value becomes suspended (C-10.3). Only a - # lift (S3b) clears it. Not after a refused check, where the marker is no longer this run's own. + # lift (cd-lift.yml) clears it. Not after a refused check, where the marker is no longer this run's own. - name: Suspend the marker if: ${{ !cancelled() && steps.rollback.outputs.go == 'true' }} env: diff --git a/.github/workflows/cd-lift.yml b/.github/workflows/cd-lift.yml new file mode 100644 index 000000000..d09821051 --- /dev/null +++ b/.github/workflows/cd-lift.yml @@ -0,0 +1,99 @@ +# ci-policy: class=deploy +name: CD lift + +# S3b of the deploy train (CHE-5551, plan CHE-5474 C-10.6 and C-10.7): the audited lift. It is the only way from +# `armed:*` or `suspended:*` back to `clear:*`, and nothing but this workflow writes a lift. +# +# Dispatch only, one input: the id of a Multica decision. The dispatcher (and the login that triggered the run) +# must be in vars.DOOP_LIFT_DISPATCHERS. On the C00 runner, under the host lock, scripts/deploy-lift.mjs refuses +# unless ALL hold: +# - the decision is action type doop.deploy_lift (v1), state approved, approved by vars.DOOP_LIFT_APPROVER_ID +# (Cheese), and not withdrawn, rejected, revoked or expired; +# - its marker_value param equals the marker that stands now, byte for byte, and its repo param is this repository; +# - migration quiescence is proven (C-8.8), /healthz answers 200, and the running digest and revision label read; +# - right before the write, still under the lock, the decision and the marker are read again and still hold. +# Then it writes `clear::`, reads it back, and records the lifter, decision, approver, health, +# digest, revision and ICT times in the run summary and lift-evidence.json. A refusal leaves the marker unchanged and +# fails the run. No step is a human-typed command. +# +# The decision is read from the Multica server over the tailnet with a scoped read-only token (environment +# doop-lift), so the C00 runner must reach that server. The marker is a repository variable that only the GitHub +# App can write, so environment doop-lift also holds the App's id and key (DOOP_MARKER_APP_ID, DOOP_MARKER_APP_KEY). +# A dispatch from any branch but the default one is skipped: a branch must not run its own lift script. +# The train ships OFF and this workflow does not touch the switch (DOOP_DEPLOY_TRAIN). +on: + workflow_dispatch: + inputs: + decision_id: + description: Id of the approved Multica decision (action doop.deploy_lift) that names the marker to lift + type: string + required: true + +permissions: + contents: read + +jobs: + lift: + if: ${{ github.repository == 'cheese-work/doop' && github.ref == 'refs/heads/cheese/main' }} + runs-on: [self-hosted, cheese-c00-deploy] + timeout-minutes: 20 + environment: doop-lift + permissions: + contents: read + # One C00 job at a time, shared with deploy, readback-confirm and rollback; a started lift is never cancelled. + concurrency: + group: c00-deploy-doop + cancel-in-progress: false + env: + C00_COMPOSE_DIR: ${{ vars.C00_DOOP_COMPOSE_DIR || '/home/congvc/.local/share/doop' }} + # Empty: c00.sh finds the compose project's `db` service. Set it to name the live Postgres container. + C00_PG_CONTAINER: ${{ vars.C00_DOOP_PG_CONTAINER }} + steps: + - uses: actions/checkout@v4 + with: + persist-credentials: false + - uses: actions/setup-node@v4 + with: + node-version: 22 + # First, before any secret is read or minted: a login outside the allowlist ends the run here. + - name: Admit the dispatcher + env: + ACTOR: ${{ github.actor }} + TRIGGER: ${{ github.triggering_actor }} + DISPATCHERS: ${{ vars.DOOP_LIFT_DISPATCHERS }} + run: node scripts/deploy-lift.mjs admit + # The marker is a repository variable; `github.token` cannot write one, so a GitHub App token does. + - name: Mint the marker token + id: app + uses: actions/create-github-app-token@64ab729a6294000f5aa4a4bc0b73d1f32bc45510 # v3.3.0 + with: + app-id: ${{ vars.DOOP_MARKER_APP_ID }} + private-key: ${{ secrets.DOOP_MARKER_APP_KEY }} + repositories: doop + permission-variables: write + # C-5: every C00 job removes the compat sandboxes first. A failed sweep fails the run before the lift. + - name: Sweep the compat sandboxes + run: bash deploy/cd/c00.sh sweep + # One step, all under the C00 flock: quiescence, then digest, revision label and health, then the decision and + # the marker read, decided, read again, and written. Anything missing refuses and leaves the marker as it was. + - name: Lift on C00 + env: + GH_TOKEN: ${{ steps.app.outputs.token }} + REPO: ${{ github.repository }} + RUN_ID: ${{ github.run_id }} + LIFTER: ${{ github.triggering_actor }} + DECISION_ID: ${{ inputs.decision_id }} + APPROVER_ID: ${{ vars.DOOP_LIFT_APPROVER_ID }} + MULTICA_SERVER_URL: ${{ secrets.DOOP_LIFT_MULTICA_SERVER_URL }} + MULTICA_WORKSPACE_ID: ${{ secrets.DOOP_LIFT_MULTICA_WORKSPACE_ID }} + DECISION_READ_TOKEN: ${{ secrets.DOOP_LIFT_DECISION_READ_TOKEN }} + # What the app answers on C00 itself; set the variable when the published port is not 4400. + HEALTHZ_URL: ${{ vars.C00_DOOP_HEALTHZ_URL || 'http://127.0.0.1:4400/healthz' }} + run: bash deploy/cd/c00.sh lift + - name: Upload the lift evidence + if: ${{ always() }} + uses: actions/upload-artifact@4cec3d8aa04e39d1a68397de0c4cd6fb9dce8ec1 # v4.6.1 + with: + name: lift-evidence + path: lift-evidence.json + if-no-files-found: warn diff --git a/deploy/cd/README.md b/deploy/cd/README.md index e91f36082..0e6023f06 100644 --- a/deploy/cd/README.md +++ b/deploy/cd/README.md @@ -25,11 +25,11 @@ a skip too. This slice approves no deploy: nothing sets the switch to `on`, and Repo variable `DOOP_DEPLOY_SUSPENDED` is the one thing that lets a train run. Its value is one of: -| Value | Meaning | -| ------------------------------------------- | --------------------------------------------- | -| `clear::` | the train may run | -| `armed:::` | a train run is changing C00 | -| `suspended::::` | stopped until a lift (slice S3b) writes clear | +| Value | Meaning | +| ------------------------------------------- | ----------------------------------------------------------- | +| `clear::` | the train may run | +| `armed:::` | a train run is changing C00 | +| `suspended::::` | stopped until the audited lift (`cd-lift.yml`) writes clear | The nonce is 128 random bits. Absent, unreadable or any other shape reads as suspended; a prefix match is not enough. `scripts/deploy-marker.mjs` is the only writer. Every write reads the variable, checks it is the @@ -46,7 +46,39 @@ value the writer expects, writes, and reads it back; a write it cannot prove fai over its own `armed:*`, whatever the rollback itself did. - **Reading is read only.** `decide` and every check read the marker and never write it. -Every failure leaves the marker `armed` or `suspended`, so the train stops until a lift. Lifting is S3b. +Every failure leaves the marker `armed` or `suspended`, so the train stops until a lift. Lifting is `cd-lift.yml` (below). + +### The audited lift (`cd-lift.yml`, S3b, C-10.6 and C-10.7) + +The only way from `armed:*` or `suspended:*` back to `clear:*`. Dispatch only, one input: `decision_id`, the id of +a Multica decision. No step is a human-typed command. + +1. The dispatcher and the triggering login must both be in repo variable `DOOP_LIFT_DISPATCHERS` (checked first, + before any secret is read). The job runs only on `cheese/main`, in environment `doop-lift`, on the C00 runner, + in concurrency group `c00-deploy-doop`, and `c00.sh lift` takes the host lock. +2. Under the lock it refuses unless **all** hold, and a refusal leaves the marker as it was: + - the decision is action `doop.deploy_lift` v1, `approved`, by `vars.DOOP_LIFT_APPROVER_ID` (Cheese), not + withdrawn, rejected, revoked or expired; unreadable or unknown is a refusal; + - its `marker_value` equals the marker that stands now, byte for byte, and its `repo` is `cheese-work/doop`; + - migration quiescence is proven (C-8.8), `/healthz` answers 200, and the running digest and revision label read; + - the decision and the marker are read again immediately before the write and still hold (a marker that + changed, or a decision revoked, during the lift refuses). +3. It writes `clear::`, reads it back, and records lifter, decision id, approver, health, digest, + revision and ICT times in the run summary and the `lift-evidence` artifact (`lift-evidence.json`, outcome + `lifted`, `refused` or `failed`; `failed` means the write could not be read back, so check the marker by hand). + Two lifts at once serialize on the lock; the second finds the marker changed and is refused. + +The lift never reads or writes `DOOP_DEPLOY_TRAIN`: the train stays off until Cheese turns it on. + +| Where | Name | Value | +| -------------- | -------------------------------------------------- | ---------------------------------------------------------------------------------------- | +| Environment | `doop-lift` | holds the secrets below; restrict deployment branches to `cheese/main` | +| Env secret | `DOOP_LIFT_DECISION_READ_TOKEN` | read-only token for `GET /api/decisions/{id}/state` | +| Env secret | `DOOP_LIFT_MULTICA_SERVER_URL`, `..._WORKSPACE_ID` | the Multica server (tailnet only, so the C00 runner must reach it) and its workspace | +| Env var/secret | `DOOP_MARKER_APP_ID`, `DOOP_MARKER_APP_KEY` | the same marker App as D2: copy both into `doop-lift`, since a job takes one environment | +| Repo variable | `DOOP_LIFT_DISPATCHERS` | logins that may dispatch a lift | +| Repo variable | `DOOP_LIFT_APPROVER_ID` | Cheese's Multica member id; the decision's approver must equal it | +| Repo variable | `C00_DOOP_HEALTHZ_URL` | optional; default `http://127.0.0.1:4400/healthz` (what the app answers on C00 itself) | ### Adoption of the 11 Nov failure (one write, by an admin) diff --git a/deploy/cd/c00.sh b/deploy/cd/c00.sh index 0f1fcf8e9..b6c656e0f 100755 --- a/deploy/cd/c00.sh +++ b/deploy/cd/c00.sh @@ -22,6 +22,11 @@ # c00.sh guard refuse (exit 1) while an earlier compat migration's quiescence is unproven; re-proves the three # facts and clears the guard when they hold. apply, rollback and sweep run it first; the lift # job calls it. `guard-set run mig db user dbname app` writes it (compat-sandbox.mjs does). +# c00.sh lift the C00 half of cd-lift.yml (CHE-5551, C-10.7): refuse while a compat guard holds, take the host +# lock, prove migration quiescence, read the running digest, revision label and container +# health, and run scripts/deploy-lift.mjs lift under the same lock with those facts. That script +# decides, re-reads the decision and the marker right before the write, and writes `clear:*`. +# Unproven quiescence does not stop here: the script is told and records the refusal. # c00.sh sweep remove every doop.compat.run resource (containers, networks, volumes), read back # zero, print df before and after. Needs no compose dir and no deploy ref (CHE-5474 C-8.5d). # @@ -422,6 +427,26 @@ case $cmd in fi ;; + lift) + guard_check + take_lock + # Under the lock: the three C-8.8 facts (in a subshell, so a refusal is handed on rather than exiting), then what + # C00 runs. A read that fails leaves its fact empty, which the lift script refuses. + if ( require_quiescent ) >&2; then LIFT_QUIESCENT=true; else LIFT_QUIESCENT=false; fi + img=$(docker inspect --format '{{.Image}}' "$container" 2>/dev/null) || img= + LIFT_DIGEST= + LIFT_REVISION= + if [ -n "$img" ]; then + LIFT_DIGEST=$(docker image inspect --format '{{range .RepoDigests}}{{println .}}{{end}}' "$img" 2>/dev/null | + sed -n 's/.*@\(sha256:[0-9a-f]\{64\}\)$/\1/p' | head -n 1) || LIFT_DIGEST= + LIFT_REVISION=$(docker image inspect --format '{{index .Config.Labels "org.opencontainers.image.revision"}}' "$img" 2>/dev/null) || LIFT_REVISION= + fi + LIFT_CONTAINER_HEALTH=$(docker inspect --format '{{if .State.Health}}{{.State.Health.Status}}{{else}}none{{end}}' "$container" 2>/dev/null) || LIFT_CONTAINER_HEALTH= + export LIFT_QUIESCENT LIFT_DIGEST LIFT_REVISION LIFT_CONTAINER_HEALTH + echo "lift facts: quiescent=$LIFT_QUIESCENT digest=${LIFT_DIGEST:-unknown} revision=${LIFT_REVISION:-unknown} container=${LIFT_CONTAINER_HEALTH:-unknown}" + node "$here/../../scripts/deploy-lift.mjs" lift + ;; + quiescence) require_quiescent echo "quiescent: no migrate container running, no migrate session, advisory key free" @@ -449,5 +474,5 @@ case $cmd in echo "sweep ok: containers=0 networks=0 volumes=0" ;; - *) die "usage: c00.sh apply|readback|confirm|rollback|quiescence|sweep|guard|guard-set" ;; + *) die "usage: c00.sh apply|readback|confirm|rollback|quiescence|lift|sweep|guard|guard-set" ;; esac diff --git a/eslint.config.js b/eslint.config.js index 6052b67f3..a0d0a76ea 100644 --- a/eslint.config.js +++ b/eslint.config.js @@ -163,7 +163,7 @@ export default tseslint.config( ], languageOptions: { globals: Object.fromEntries( - 'process console Buffer URL fetch setTimeout clearTimeout setInterval clearInterval' + 'process console Buffer URL AbortSignal fetch setTimeout clearTimeout setInterval clearInterval' .split(' ') .map((g) => [g, 'readonly']), ), diff --git a/scripts/deploy-lift.mjs b/scripts/deploy-lift.mjs new file mode 100644 index 000000000..cbb362760 --- /dev/null +++ b/scripts/deploy-lift.mjs @@ -0,0 +1,311 @@ +// The audited lift (CHE-5551, train S3b, plan CHE-5474 C-10.6 and C-10.7): the only way from `suspended:*` or +// `armed:*` back to `clear:*`. It runs in `cd-lift.yml` on the C00 runner, under the host lock, and refuses unless +// ONE approved Multica decision of action type doop.deploy_lift, answered by the configured approver (Cheese), names +// the exact marker that stands now, and C00 is quiescent and healthy. Nothing is parsed from free text. +// +// admit the dispatcher (and the login that triggered the run) is in the allowlist +// lift decide on the decision, the marker and the C00 facts; read the decision and the marker again right +// before the write; write `clear::`, read it back; record the evidence +// +// The decision read is `GET {server}/api/decisions/{id}/state` (scoped read-only token, X-Workspace-ID header): +// decision_id, action_id, action_type, action_version, state, approver_id, answered_at, withdrawn_at, revoked_at, +// expires_at, params { marker_value, repo }. A missing or malformed field is a refusal, never a pass. +// A refusal leaves the marker unchanged. The evidence (`lift-evidence.json`, the run summary) is written for a +// refusal too: outcome `lifted`, `refused` (nothing written) or `failed` (a write that could not be read back; the +// marker must be checked by hand). +// +// CLI: node scripts/deploy-lift.mjs admit | lift +// Env (admit): ACTOR, TRIGGER, DISPATCHERS +// Env (lift): GH_TOKEN (marker GitHub App token), REPO, RUN_ID, LIFTER, DECISION_ID, APPROVER_ID, MULTICA_SERVER_URL, +// MULTICA_WORKSPACE_ID, DECISION_READ_TOKEN, HEALTHZ_URL, and the C00 facts c00.sh lift proved under the +// lock: LIFT_QUIESCENT (true), LIFT_DIGEST, LIFT_REVISION, LIFT_CONTAINER_HEALTH. +import { appendFileSync, writeFileSync } from 'node:fs' +import { pathToFileURL } from 'node:url' +import { kindOf, lift as writeLift, readMarker } from './deploy-marker.mjs' + +const ACTION_TYPE = 'doop.deploy_lift' +const ACTION_VERSION = 1 +const ID = /^[A-Za-z0-9][A-Za-z0-9-]{5,63}$/ +const DIGEST = /^sha256:[0-9a-f]{64}$/ +const SHA40 = /^[0-9a-f]{40}$/ +const READ_MS = 15_000 + +class Refusal extends Error {} +const refuse = (why) => new Refusal(why) + +export const parseList = (text) => + String(text ?? '') + .split(/[\s,]+/) + .filter(Boolean) + +/** Both the actor and the login that triggered this attempt must be allowlisted (a rerun keeps the original actor). */ +export function admitDispatcher({ actor, triggering, allowed }) { + const list = parseList(allowed).map((x) => x.toLowerCase()) + for (const login of [actor, triggering]) { + if (!login || !list.includes(String(login).toLowerCase())) + throw new Error(`refused: dispatcher '${login ?? ''}' is not in DOOP_LIFT_DISPATCHERS`) + } +} + +const pad = (n) => String(n).padStart(2, '0') +/** `YYYY-MM-DD HH:MM:SS ICT` (UTC+7, no daylight saving). */ +export function ictTime(date) { + const d = new Date(date.getTime() + 7 * 3600_000) + return ( + `${d.getUTCFullYear()}-${pad(d.getUTCMonth() + 1)}-${pad(d.getUTCDate())} ` + + `${pad(d.getUTCHours())}:${pad(d.getUTCMinutes())}:${pad(d.getUTCSeconds())} ICT` + ) +} + +/** The decision, as the API answers it. Refuses (throws) when it is missing or cannot be read; no token in any error. */ +export async function readDecision({ fetchImpl = fetch, server, workspace, token, id }) { + if (!/^https?:\/\/[^\s/]+/.test(server ?? '')) + throw refuse('unreadable decision: the Multica server URL is not http(s)') + if (!token) throw refuse('unreadable decision: no read token') + if (!workspace) throw refuse('unreadable decision: no workspace id') + if (!ID.test(id ?? '')) throw refuse('unreadable decision: the decision id is not a plain id') + let res + try { + res = await fetchImpl(`${server.replace(/\/+$/, '')}/api/decisions/${id}/state`, { + headers: { Authorization: `Bearer ${token}`, 'X-Workspace-ID': workspace, Accept: 'application/json' }, + signal: AbortSignal.timeout(READ_MS), + }) + } catch (err) { + throw refuse(`unreadable decision: the Multica API did not answer (${String(err?.message ?? err).split('\n')[0]})`) + } + if (res.status === 404) throw refuse('no such decision (404)') + if (!res.ok) throw refuse(`unreadable decision: the Multica API answered ${res.status}`) + let body + try { + body = JSON.parse(await res.text()) + } catch { + throw refuse('unreadable decision: the answer is not JSON') + } + if (!body || typeof body !== 'object' || Array.isArray(body)) throw refuse('unreadable decision: not an object') + return body +} + +const str = (v) => typeof v === 'string' && v !== '' +const instant = (v) => (str(v) && !Number.isNaN(Date.parse(v)) ? Date.parse(v) : null) + +/** + * Why this decision does not lift this marker, or null when it does. Pure: no I/O. Every field is checked; + * anything missing or of the wrong shape is a refusal. + */ +export function refusalFor(d, { marker, repo, approverId, now, id }) { + if (!d || typeof d !== 'object') return 'unreadable decision' + if (id !== undefined && d.decision_id !== id) return 'unreadable decision: it answers for another decision id' + if (d.action_type !== ACTION_TYPE) return `wrong action type '${d.action_type}', need ${ACTION_TYPE}` + for (const f of ['state', 'approver_id']) if (!str(d[f])) return `unreadable decision: no ${f}` + if (!str(d.params?.marker_value) || !str(d.params?.repo)) + return 'unreadable decision: params lack marker_value or repo' + if (d.answered_at == null || instant(d.answered_at) === null) return 'unreadable decision: no answered_at' + if (d.expires_at != null && instant(d.expires_at) === null) return 'unreadable decision: expires_at is not a time' + if (Number(d.action_version) !== ACTION_VERSION) + return `wrong action version '${d.action_version}', need ${ACTION_VERSION}` + if (d.state !== 'approved') return `the decision is not approved (state ${d.state})` + if (d.withdrawn_at != null) return 'the decision was withdrawn' + if (d.revoked_at != null) return 'the decision was revoked' + if (d.expires_at != null && instant(d.expires_at) <= now.getTime()) return 'the decision has expired' + if (!approverId) return 'no approver id is configured (DOOP_LIFT_APPROVER_ID)' + if (d.approver_id !== approverId) return 'the approver is not the configured approver' + if (d.params.repo !== repo) return `the repo param '${d.params.repo}' is not ${repo}` + if (d.params.marker_value !== marker) return 'the marker_value param is not the marker that stands now' + return null +} + +/** The marker that stands, as something a lift may replace; refuses for absent, unreadable, clear or unknown. */ +async function standingMarker(ghApi, repo) { + let marker + try { + marker = await readMarker(ghApi, repo) + } catch (err) { + throw refuse(`the marker cannot be read (${String(err?.message ?? err).split('\n')[0]})`) + } + if (marker === null) throw refuse('the marker is absent; there is nothing to lift') + const kind = kindOf(marker) + if (kind === 'clear') throw refuse('the marker is already clear; there is nothing to lift') + if (kind === null) throw refuse('the marker is not a marker value; it is not lifted') + return marker +} + +async function checkHealth({ fetchImpl, healthzUrl, containerHealth }) { + if (containerHealth !== 'healthy') throw refuse(`C00 health: the container is ${containerHealth || 'unknown'}`) + let res + try { + res = await fetchImpl(healthzUrl, { redirect: 'manual', signal: AbortSignal.timeout(READ_MS) }) + } catch (err) { + throw refuse(`C00 health: ${healthzUrl} did not answer (${String(err?.message ?? err).split('\n')[0]})`) + } + if (res.status !== 200) throw refuse(`C00 health: ${healthzUrl} answered ${res.status}, not 200`) + return { status: 200, url: healthzUrl } +} + +/** + * Run the lift. Always returns the evidence; `outcome` is `lifted`, `refused` (nothing was written) or `failed`. + * The caller holds the C00 lock; `facts` are what it proved under that lock. + */ +export async function lift(o) { + const clock = o.now ?? (() => new Date()) + const started = clock() + const ev = { + outcome: 'refused', + reason: '', + lifter: o.lifter ?? '', + decision_id: o.decisionId ?? '', + approver_id: '', + decision_answered_at: '', + lift_run_id: String(o.runId ?? ''), + repo: o.repo ?? '', + marker_before: null, + marker_after: null, + health: null, + quiescence: o.facts?.quiescent === true ? 'proven' : 'not proven', + digest: o.facts?.digest ?? '', + revision: o.facts?.revision ?? '', + started_ict: ictTime(started), + finished_ict: '', + } + try { + if (!/^\d+$/.test(ev.lift_run_id)) throw refuse('the lift run id is not a number') + if (!str(ev.lifter)) throw refuse('no lifter login') + const read = () => + readDecision({ + fetchImpl: o.fetchImpl, + server: o.server, + workspace: o.workspace, + token: o.token, + id: o.decisionId, + }) + const judge = (d, marker) => + refusalFor(d, { marker, repo: o.repo, approverId: o.approverId, now: clock(), id: o.decisionId }) + + // 1. Decide on the decision, the marker and C00. + const decision = await read() + ev.approver_id = str(decision.approver_id) ? decision.approver_id : '' + ev.decision_answered_at = str(decision.answered_at) ? decision.answered_at : '' + const marker = await standingMarker(o.ghApi, o.repo) + ev.marker_before = marker + const why = judge(decision, marker) + if (why) throw refuse(why) + if (o.facts?.quiescent !== true) throw refuse('migration quiescence is not proven (C-8.8)') + if (!DIGEST.test(o.facts?.digest ?? '')) throw refuse('no readable running digest') + if (!SHA40.test(o.facts?.revision ?? '')) throw refuse('no readable revision label') + ev.health = await checkHealth({ + fetchImpl: o.fetchImpl, + healthzUrl: o.healthzUrl, + containerHealth: o.facts.containerHealth, + }) + + // 2. Immediately before the write: the decision again, then the marker again, and still equal. + const again = await read() + const whyAgain = judge(again, await standingMarker(o.ghApi, o.repo)) + if (whyAgain) throw refuse(`changed during the lift: ${whyAgain}`) + + // 3. writeMarker reads the marker once more, writes, and reads it back. + try { + ev.marker_after = await writeLift({ ghApi: o.ghApi, repo: o.repo, runId: ev.lift_run_id, expected: marker }) + } catch (err) { + const msg = String(err?.message ?? err) + if (/nothing was written/.test(msg)) throw refuse(`the marker changed during the lift: ${msg}`) + ev.outcome = 'failed' + ev.reason = `the marker write failed: ${msg}; check ${o.repo} variable DOOP_DEPLOY_SUSPENDED by hand` + return finish(ev, clock) + } + ev.outcome = 'lifted' + ev.reason = '' + } catch (err) { + if (!(err instanceof Refusal)) ev.reason = `refused (unexpected): ${String(err?.message ?? err).split('\n')[0]}` + else ev.reason = err.message + ev.outcome = 'refused' + } + return finish(ev, clock) +} + +const finish = (ev, clock) => ({ ...ev, finished_ict: ictTime(clock()) }) + +function summary(ev) { + const rows = [ + ['Outcome', ev.outcome === 'lifted' ? 'lifted (marker is clear)' : `${ev.outcome}: ${ev.reason}`], + ['Lifter', ev.lifter], + ['Decision', ev.decision_id], + ['Approver', ev.approver_id], + ['Decision answered', ev.decision_answered_at], + ['Lift run', ev.lift_run_id], + ['Marker before', `\`${ev.marker_before ?? ''}\``], + ['Marker after', `\`${ev.marker_after ?? ''}\``], + ['Health', ev.health ? `${ev.health.status} from ${ev.health.url}` : 'not checked'], + ['Migration quiescence', ev.quiescence], + ['Running digest', ev.digest], + ['Revision label', ev.revision], + ['Started', ev.started_ict], + ['Finished', ev.finished_ict], + ] + return `## Deploy lift\n\n| | |\n| --- | --- |\n${rows.map(([k, v]) => `| ${k} | ${String(v).replace(/\|/g, '\\|')} |`).join('\n')}\n` +} + +function record(ev, env) { + writeFileSync('lift-evidence.json', `${JSON.stringify(ev, null, 2)}\n`) + if (env.GITHUB_STEP_SUMMARY) appendFileSync(env.GITHUB_STEP_SUMMARY, summary(ev)) + console.log(`deploy lift: ${ev.outcome}${ev.reason ? ` (${ev.reason})` : ''}`) +} + +// --------------------------------------------------------------------------------------------- +const api = + (token) => + async (path, init = {}) => { + const res = await fetch(`${process.env.GITHUB_API_URL || 'https://api.github.com'}/${path}`, { + method: init.method ?? 'GET', + headers: { + Authorization: `Bearer ${token}`, + Accept: 'application/vnd.github+json', + 'Content-Type': 'application/json', + }, + body: init.body ? JSON.stringify(init.body) : undefined, + }) + if (!res.ok) + throw Object.assign(new Error(`GitHub ${res.status} for ${init.method ?? 'GET'} ${path}`), { status: res.status }) + const text = await res.text() + return text ? JSON.parse(text) : {} + } + +async function cli(argv, env) { + const [command] = argv + if (command === 'admit') { + admitDispatcher({ actor: env.ACTOR, triggering: env.TRIGGER, allowed: env.DISPATCHERS }) + console.log(`deploy lift: dispatcher ${env.ACTOR} admitted`) + return 0 + } + if (command !== 'lift') throw new Error(`unknown command '${command}'`) + const ev = await lift({ + ghApi: api(env.GH_TOKEN ?? ''), + fetchImpl: fetch, + repo: env.REPO ?? '', + runId: env.RUN_ID, + lifter: env.LIFTER, + decisionId: env.DECISION_ID, + approverId: env.APPROVER_ID, + server: env.MULTICA_SERVER_URL, + workspace: env.MULTICA_WORKSPACE_ID, + token: env.DECISION_READ_TOKEN, + healthzUrl: env.HEALTHZ_URL, + facts: { + quiescent: env.LIFT_QUIESCENT === 'true', + digest: env.LIFT_DIGEST, + revision: env.LIFT_REVISION, + containerHealth: env.LIFT_CONTAINER_HEALTH, + }, + }) + record(ev, env) + return ev.outcome === 'lifted' ? 0 : 1 +} + +if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) { + cli(process.argv.slice(2), process.env).then( + (code) => process.exit(code), + (err) => { + console.error(`deploy lift failed closed: ${err.message}`) + process.exit(1) + }, + ) +} diff --git a/scripts/deploy-marker.mjs b/scripts/deploy-marker.mjs index 6bddb2a38..8ee3b4411 100644 --- a/scripts/deploy-marker.mjs +++ b/scripts/deploy-marker.mjs @@ -2,7 +2,7 @@ // It is the one switch that lets the train run, so every write is: read it, check it is the value this // writer expects, write, read it back. A write that cannot be proven throws and fails the job. // -// clear:: the train may run +// clear:: the train may run (a lift is written by scripts/deploy-lift.mjs) // armed::: a train run is changing C00 // suspended:::: nobody runs until a lift (S3b) writes clear // @@ -36,7 +36,7 @@ export const kindOf = (value) => const nonce = () => randomBytes(16).toString('hex') // The variable's value, or null when it does not exist. Anything else that goes wrong throws. -async function read(ghApi, repo) { +export async function readMarker(ghApi, repo) { try { return String((await ghApi(`repos/${repo}/actions/variables/${NAME}`)).value ?? '') } catch (err) { @@ -48,19 +48,19 @@ async function read(ghApi, repo) { /** Read, check, write, read back. `expected` is the exact value that must stand now (null: absent). */ export async function writeMarker({ ghApi, repo, expected, next }) { if (!kindOf(next)) throw new Error('refusing to write a value that is not a marker value') - const now = await read(ghApi, repo) + const now = await readMarker(ghApi, repo) if (now !== expected) throw new Error('the suspension marker changed since it was read; nothing was written') if (now === null) await ghApi(`repos/${repo}/actions/variables`, { method: 'POST', body: { name: NAME, value: next } }) else await ghApi(`repos/${repo}/actions/variables/${NAME}`, { method: 'PATCH', body: { name: NAME, value: next } }) - if ((await read(ghApi, repo)) !== next) throw new Error('the suspension marker write could not be read back') + if ((await readMarker(ghApi, repo)) !== next) throw new Error('the suspension marker write could not be read back') return next } /** A train run, before its first change: clear -> this run's armed value. Anything but clear refuses. */ export async function arm({ ghApi, repo, runId, sha }) { if (!/^\d+$/.test(String(runId)) || !SHA40.test(sha ?? '')) throw new Error('arm needs a run id and a full SHA') - const now = await read(ghApi, repo) + const now = await readMarker(ghApi, repo) if (kindOf(now) !== 'clear') throw new Error(`cannot arm: the marker is ${now === null ? 'absent' : 'not clear'}`) return writeMarker({ ghApi, repo, expected: now, next: `armed:${nonce()}:${runId}:${sha}` }) } @@ -71,12 +71,20 @@ export async function restore({ ghApi, repo, expected }) { return writeMarker({ ghApi, repo, expected, next: `clear:${nonce()}:restore` }) } +/** An approved lift (CHE-5551, C-10.7): exactly the stated armed or suspended value -> a new clear. Nothing else lifts. */ +export async function lift({ ghApi, repo, runId, expected }) { + if (!/^\d+$/.test(String(runId ?? ''))) throw new Error('lift needs the lift run id') + if (!['armed', 'suspended'].includes(kindOf(expected) ?? '')) + throw new Error('lift needs the armed or suspended value it lifts') + return writeMarker({ ghApi, repo, expected, next: `clear:${nonce()}:${runId}` }) +} + /** -> suspended, over this run's own armed value (`expected`) or, with `any`, over whatever stands. */ export async function suspend({ ghApi, repo, runId, sha, reason, expected, any = false }) { if (!/^\d+$/.test(String(runId)) || !SHA40.test(sha ?? '')) throw new Error('suspend needs a run id and a full SHA') if (!WORD.test(reason ?? '')) throw new Error('the suspension reason must be one word of letters, digits, _ or -') let over = expected - if (any) over = await read(ghApi, repo) + if (any) over = await readMarker(ghApi, repo) else if (!['armed', 'suspended'].includes(kindOf(expected) ?? '')) throw new Error('suspend needs this run’s own armed or suspended value, or any') return writeMarker({ ghApi, repo, expected: over, next: `suspended:${nonce()}:${runId}:${sha}:${reason}` }) diff --git a/tests/c00Lift.test.ts b/tests/c00Lift.test.ts new file mode 100644 index 000000000..1e80d8358 --- /dev/null +++ b/tests/c00Lift.test.ts @@ -0,0 +1,170 @@ +import { spawn, spawnSync } from 'node:child_process' +import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join, resolve } from 'node:path' +import { afterEach, beforeEach, describe, expect, it } from 'vitest' + +/* `c00.sh lift` (CHE-5551, train S3b, plan CHE-5474 C-10.7) against a stub `docker` and a stub `node`. It takes the + host lock, proves migration quiescence, reads what C00 runs (digest, revision label, container health), and + only then runs the lift script, under the same lock, with those facts. The stubs answer from files in a scratch + dir; the lift decision itself is tested in deployLift.test.ts. */ +const SCRIPT = resolve('deploy/cd/c00.sh') +const DIGEST = 'sha256:' + 'a'.repeat(64) +const SHA = 'c'.repeat(40) + +const DOCKER = `#!/usr/bin/env bash +echo "docker $*" >> "$STUB_DIR/log" +case "$*" in *" ps -q "*) echo "doop-db"; exit 0 ;; esac +say() { [ -f "$STUB_DIR/$1" ] && cat "$STUB_DIR/$1" || exit 1; } +case "$*" in + *pg_locks*) cat "$STUB_DIR/locks" 2>/dev/null || echo 0 ;; + *pg_stat_activity*) cat "$STUB_DIR/sessions" 2>/dev/null || true ;; + "ps "*) cat "$STUB_DIR/migrate_ps" 2>/dev/null || true ;; + *State.Health*) say health ;; + *RepoDigests*) say repodigests ;; + *Labels*) say label ;; + *"{{.Image}}"*) say container_image ;; + *) exit 0 ;; +esac +` + +/* Records what it was given, and how long it ran (for the lock test). It writes lift-evidence.json like the real one. */ +const NODE = `#!/usr/bin/env bash +{ + echo "start $(date +%s.%N) $*" + echo "env LIFT_QUIESCENT=$LIFT_QUIESCENT LIFT_DIGEST=$LIFT_DIGEST LIFT_REVISION=$LIFT_REVISION LIFT_CONTAINER_HEALTH=$LIFT_CONTAINER_HEALTH" +} >> "$STUB_DIR/nodelog" +[ ! -f "$STUB_DIR/node_sleep" ] || sleep "$(cat "$STUB_DIR/node_sleep")" +echo "end $(date +%s.%N)" >> "$STUB_DIR/nodelog" +[ ! -f "$STUB_DIR/node_fail" ] || exit 1 +exit 0 +` + +let dir: string +beforeEach(() => { + dir = mkdtempSync(join(tmpdir(), 'c00lift-')) + mkdirSync(join(dir, 'bin')) + for (const [name, text] of [ + ['docker', DOCKER], + ['node', NODE], + ] as const) { + writeFileSync(join(dir, 'bin', name), text) + chmodSync(join(dir, 'bin', name), 0o755) + } + put('log', '') + put('health', 'healthy\n') + put('container_image', 'sha256:runningid\n') + put('repodigests', `ghcr.io/cheese-work/doop@${DIGEST}\n`) + put('label', SHA + '\n') +}) +afterEach(() => rmSync(dir, { recursive: true, force: true })) + +const put = (name: string, text: string) => writeFileSync(join(dir, name), text) +const log = () => readFileSync(join(dir, 'log'), 'utf8') +const nodelog = () => (existsSync(join(dir, 'nodelog')) ? readFileSync(join(dir, 'nodelog'), 'utf8') : '') + +const envOf = (extra: Record = {}) => ({ + PATH: `${join(dir, 'bin')}:${process.env.PATH}`, + STUB_DIR: dir, + C00_PG_CONTAINER: 'doop-db', + C00_LOCK_FILE: join(dir, 'lock'), + C00_LOCK_WAIT: '5', + C00_STATE_DIR: join(dir, 'state'), + GITHUB_OUTPUT: join(dir, 'out'), + ...extra, +}) +const c00 = (cmd: string, extra: Record = {}) => + spawnSync('bash', [SCRIPT, cmd], { encoding: 'utf8', env: envOf(extra) }) + +describe('c00.sh lift', () => { + it('proves quiescence, reads digest, revision label and health, then runs the lift script with them', () => { + const r = c00('lift') + expect(r.status, r.stderr).toBe(0) + expect(nodelog()).toMatch(/start \S+ .*scripts\/deploy-lift\.mjs lift/) + expect(nodelog()).toContain( + `env LIFT_QUIESCENT=true LIFT_DIGEST=${DIGEST} LIFT_REVISION=${SHA} LIFT_CONTAINER_HEALTH=healthy`, + ) + // The three C-8.8 facts were read before the lift script ran. + expect(log()).toContain('pg_stat_activity') + expect(log()).toContain('pg_locks') + expect(log()).toMatch(/docker ps -a .*doop\.migrate\.run/) + }) + + it('never changes C00: no pull, tag, compose, rm, kill or restart', () => { + c00('lift') + expect(log()).not.toMatch( + /docker (pull|tag|rm|rmi|kill|stop|restart|compose|run|exec .*(insert|update|delete|alter|drop))/i, + ) + }) + + it('passes the lift script’s refusal on: exit 1, nothing else claims success', () => { + put('node_fail', '1') + expect(c00('lift').status).toBe(1) + }) + + it.each([ + ['a live migrate session', () => put('sessions', '4242|2026-11-20 09:00:00\n')], + ['the advisory key held', () => put('locks', '1\n')], + ['a migrate container not exited', () => put('migrate_ps', 'doop-migrate-9 running\n')], + ])('unproven quiescence (%s): outcome needs_operator, and the lift script is told so', (_n, arrange) => { + arrange() + const r = c00('lift') + expect(readFileSync(join(dir, 'out'), 'utf8')).toContain('outcome=needs_operator') + expect(nodelog()).toContain('LIFT_QUIESCENT=false') + expect(r.status).toBe(0) // the stub node would refuse; here only the facts handed over matter + }) + + it('an unhealthy container is handed over as such', () => { + put('health', 'unhealthy\n') + c00('lift') + expect(nodelog()).toContain('LIFT_CONTAINER_HEALTH=unhealthy') + }) + + it('a missing running container hands over empty facts, never a guess', () => { + rmSync(join(dir, 'container_image')) + c00('lift') + expect(nodelog()).toContain('LIFT_DIGEST= LIFT_REVISION=') + }) + + it('an unresolved compat guard refuses before the lock and before the lift script', () => { + mkdirSync(join(dir, 'state')) + writeFileSync(join(dir, 'state', 'compat-unresolved.env'), 'junk\n') + const r = c00('lift') + expect(r.status).toBe(1) + expect(r.stderr).toMatch(/unreadable|unresolved/) + expect(nodelog()).toBe('') + }) +}) + +describe('c00.sh lift under the lock (two concurrent lifts serialize)', () => { + const start = (extra: Record = {}) => + new Promise<{ code: number | null; stderr: string }>((done) => { + const child = spawn('bash', [SCRIPT, 'lift'], { env: envOf(extra) }) + let stderr = '' + child.stderr.on('data', (d) => (stderr += d)) + child.on('close', (code) => done({ code, stderr })) + }) + + it('the second waits until the first has finished: the lift script runs twice, never at the same time', async () => { + put('node_sleep', '1') + const both = await Promise.all([start(), start()]) + expect(both.map((r) => r.code)).toEqual([0, 0]) + const lines = nodelog().trim().split('\n') + const stamps = lines + .filter((l) => /^(start|end) /.test(l)) + .map((l) => [l.split(' ')[0], Number(l.split(' ')[1])] as [string, number]) + expect(stamps.map(([k]) => k)).toEqual(['start', 'end', 'start', 'end']) + expect((stamps[2] ?? [0, 0])[1]).toBeGreaterThanOrEqual((stamps[1] ?? [0, 0])[1]) + }, 30_000) + + it('a lift that cannot get the lock in time fails and never runs the lift script', async () => { + put('node_sleep', '3') + const first = start() + await new Promise((r) => setTimeout(r, 700)) + const second = await start({ C00_LOCK_WAIT: '1' }) + expect(second.code).toBe(1) + expect(second.stderr).toMatch(/could not take the deploy lock/) + await first + expect(nodelog().match(/^start /gm)).toHaveLength(1) + }, 30_000) +}) diff --git a/tests/deployLift.test.ts b/tests/deployLift.test.ts new file mode 100644 index 000000000..33ffa91d1 --- /dev/null +++ b/tests/deployLift.test.ts @@ -0,0 +1,740 @@ +import { spawn } from 'node:child_process' +import { mkdtempSync, readFileSync, rmSync } from 'node:fs' +import { createServer } from 'node:http' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { describe, expect, it } from 'vitest' +// @ts-expect-error plain .mjs script, no type declarations +import { admitDispatcher, ictTime, lift, parseList, readDecision, refusalFor } from '../scripts/deploy-lift.mjs' +// @ts-expect-error plain .mjs script, no type declarations +import { kindOf } from '../scripts/deploy-marker.mjs' + +/* CHE-5551 (train S3b, plan CHE-5474 C-10.6 and C-10.7). The lift is the only way back from a suspension. It + writes `clear:*` only when one approved Multica decision of type doop.deploy_lift, answered by Cheese, names the + exact marker that stands now, and C00 is quiescent and healthy. The decision and the marker are read again + right before the write. A refused lift leaves the marker exactly as it was. A fake GitHub holds the variable and + a fake Multica serves the decision; both record every call. */ +const REPO = 'cheese-work/doop' +const SHA = 'c'.repeat(40) +const SUSPENDED = 'suspended:' + '2'.repeat(32) + ':9:' + SHA + ':migrated' +const ARMED = 'armed:' + '1'.repeat(32) + ':8:' + SHA +const CLEAR = 'clear:' + '0'.repeat(32) + ':restore' +const DECISION_ID = '7a1f0f3e-5d2e-4b6a-9c11-0b0f7d3a2c10' +const CHEESE = 'user-cheese-0001' +const SERVER = 'https://multica.tailnet.example' +const WORKSPACE = 'ws-0001' +const TOKEN = 'mdt_secret_read_token' +const HEALTHZ = 'http://127.0.0.1:4400/healthz' +const DIGEST = 'sha256:' + 'a'.repeat(64) +const RUN_ID = '4242' +const NOW = new Date('2026-11-20T03:00:00Z') // 10:00:00 ICT +const VAR_URL = `repos/${REPO}/actions/variables/DOOP_DEPLOY_SUSPENDED` + +const httpError = (status: number) => Object.assign(new Error(`GitHub ${status}`), { status }) + +type Decision = Record +const decisionOf = (over: Decision = {}): Decision => ({ + decision_id: DECISION_ID, + action_id: 'act-1', + action_type: 'doop.deploy_lift', + action_version: 1, + state: 'approved', + approver_id: CHEESE, + answered_at: '2026-11-20T02:00:00Z', + withdrawn_at: null, + revoked_at: null, + expires_at: '2026-11-21T02:00:00Z', + params: { marker_value: SUSPENDED, repo: REPO }, + ...over, +}) + +type World = { + marker: string | null + /** What the decision API answers on read n (1-based); a function may change the world first. */ + decision?: (n: number) => { status: number; body?: unknown; text?: string } | 'throw' + health?: number | 'throw' + unreadableMarker?: boolean + /** Runs after the n-th marker read; used to change the marker mid-lift. */ + afterMarkerRead?: (n: number, w: World) => void +} + +function world(w: World) { + const calls = { decision: 0, marker: 0, health: 0, headers: [] as Record[], writes: [] as string[] } + const ghApi = async (path: string, init: { method?: string; body?: { value: string } } = {}) => { + const method = init.method ?? 'GET' + if (method === 'GET') { + if (path !== VAR_URL) throw new Error(`unexpected read ${path}`) + calls.marker++ + if (w.unreadableMarker) throw httpError(500) + const n = calls.marker + const value = w.marker + w.afterMarkerRead?.(n, w) + if (value === null) throw httpError(404) + return { value } + } + if (method !== 'PATCH' || path !== VAR_URL) throw new Error(`unexpected write ${method} ${path}`) + calls.writes.push(init.body?.value ?? '') + w.marker = init.body?.value ?? '' + return {} + } + const fetchImpl = async (url: string, init: { headers?: Record } = {}) => { + if (url === HEALTHZ) { + calls.health++ + if (w.health === 'throw') throw new Error('connect ECONNREFUSED') + return { ok: (w.health ?? 200) === 200, status: w.health ?? 200, text: async () => '{"ok":true}' } + } + if (url !== `${SERVER}/api/decisions/${DECISION_ID}/state`) throw new Error(`unexpected fetch ${url}`) + calls.decision++ + calls.headers.push(init.headers ?? {}) + const r = ( + w.decision ?? ((): { status: number; body?: unknown; text?: string } => ({ status: 200, body: decisionOf() })) + )(calls.decision) + if (r === 'throw') throw new Error('getaddrinfo ENOTFOUND multica.tailnet.example') + return { + ok: r.status >= 200 && r.status < 300, + status: r.status, + text: async () => r.text ?? JSON.stringify(r.body ?? {}), + } + } + return { w, calls, ghApi, fetchImpl } +} + +const goodFacts = { quiescent: true, digest: DIGEST, revision: SHA, containerHealth: 'healthy' } + +function run( + env: ReturnType, + over: { facts?: Record; approverId?: string; lifter?: string } = {}, +) { + return lift({ + ghApi: env.ghApi, + fetchImpl: env.fetchImpl, + repo: REPO, + runId: RUN_ID, + lifter: over.lifter ?? 'congvc-dev', + decisionId: DECISION_ID, + approverId: over.approverId ?? CHEESE, + server: SERVER, + workspace: WORKSPACE, + token: TOKEN, + healthzUrl: HEALTHZ, + facts: over.facts ?? goodFacts, + now: () => NOW, + }) +} + +describe('the accepted lift (C-10.7)', () => { + it('writes a new clear::, reads it back, and records the evidence', async () => { + const env = world({ marker: SUSPENDED }) + const ev = await run(env) + expect(ev.outcome).toBe('lifted') + expect(env.calls.writes).toHaveLength(1) + const written = env.calls.writes[0] ?? '' + expect(written).toMatch(new RegExp(`^clear:[0-9a-f]{32}:${RUN_ID}$`)) + expect(kindOf(written)).toBe('clear') + expect(env.w.marker).toBe(written) + expect(ev).toMatchObject({ + outcome: 'lifted', + lifter: 'congvc-dev', + decision_id: DECISION_ID, + approver_id: CHEESE, + lift_run_id: RUN_ID, + marker_before: SUSPENDED, + marker_after: written, + health: { status: 200, url: HEALTHZ }, + quiescence: 'proven', + digest: DIGEST, + revision: SHA, + }) + expect(ev.started_ict).toBe('2026-11-20 10:00:00 ICT') + expect(ev.finished_ict).toBe('2026-11-20 10:00:00 ICT') + }) + + it('lifts an armed marker too (a train run that died leaves one)', async () => { + const env = world({ + marker: ARMED, + decision: () => ({ status: 200, body: decisionOf({ params: { marker_value: ARMED, repo: REPO } }) }), + }) + expect((await run(env)).outcome).toBe('lifted') + }) + + it('reads the decision with the scoped token and the workspace header, twice, and never writes the token down', async () => { + const env = world({ marker: SUSPENDED }) + const ev = await run(env) + expect(env.calls.decision).toBe(2) + for (const h of env.calls.headers) { + expect(h.Authorization).toBe(`Bearer ${TOKEN}`) + expect(h['X-Workspace-ID']).toBe(WORKSPACE) + } + expect(JSON.stringify(ev)).not.toContain(TOKEN) + }) + + it('reads the decision again, then the marker again, right before the write', async () => { + const order: string[] = [] + const env = world({ + marker: SUSPENDED, + decision: (n) => { + order.push(`decision${n}`) + return { status: 200, body: decisionOf() } + }, + afterMarkerRead: (n) => order.push(`marker${n}`), + }) + const base = env.ghApi + env.ghApi = async (path: string, init?: { method?: string; body?: { value: string } }) => { + if (init?.method === 'PATCH') order.push('write') + return base(path, init) + } + await run(env) + // decision 1 and marker 1 decide; decision 2 and marker 2 are the re-read; marker 3 is writeMarker's own check. + expect(order.slice(0, 2).sort()).toEqual(['decision1', 'marker1']) + expect(order.indexOf('decision2')).toBeLessThan(order.indexOf('write')) + expect(order.indexOf('marker2')).toBeLessThan(order.indexOf('write')) + expect(order.indexOf('decision2')).toBeLessThan(order.indexOf('marker2')) + expect(order.filter((x) => x === 'write')).toHaveLength(1) + }) +}) + +/* Every refusal: nothing was written, and the marker is exactly as it was (or as another run left it). */ +async function refused( + env: ReturnType, + over?: Parameters[1], + reason?: RegExp, + /** The marker that stands after: the one it was, unless another run changed it meanwhile. */ + standing?: string, +) { + const before = standing ?? env.w.marker + const ev = await run(env, over) + expect(ev.outcome).toBe('refused') + if (reason) expect(ev.reason).toMatch(reason) + expect(env.calls.writes).toEqual([]) + expect(env.w.marker).toBe(before) + return ev +} + +describe('refused: the decision (C-10.6, C-10.7)', () => { + it('no decision (404)', async () => { + await refused(world({ marker: SUSPENDED, decision: () => ({ status: 404 }) }), undefined, /no such decision/) + }) + + it.each([ + ['server error', () => ({ status: 500, text: 'boom' })], + ['forbidden (bad scope or not the owner)', () => ({ status: 403 })], + ['unauthorized', () => ({ status: 401 })], + ['not JSON', () => ({ status: 200, text: '' })], + ['a JSON array', () => ({ status: 200, body: [] })], + ['the network fails', () => 'throw' as const], + ['no state', () => ({ status: 200, body: { ...decisionOf(), state: undefined } })], + ['no approver', () => ({ status: 200, body: { ...decisionOf(), approver_id: undefined } })], + ['no params', () => ({ status: 200, body: { ...decisionOf(), params: undefined } })], + ['no marker_value', () => ({ status: 200, body: decisionOf({ params: { repo: REPO } }) })], + ['no repo', () => ({ status: 200, body: decisionOf({ params: { marker_value: SUSPENDED } }) })], + ['no answered_at', () => ({ status: 200, body: decisionOf({ answered_at: null }) })], + ['another decision id', () => ({ status: 200, body: decisionOf({ decision_id: 'someone-else' }) })], + ['an unparsable deadline', () => ({ status: 200, body: decisionOf({ expires_at: 'soon' }) })], + ])('unreadable decision: %s', async (_name, decision) => { + await refused(world({ marker: SUSPENDED, decision }), undefined, /unreadable|no such decision/) + }) + + it.each(['doop.deploy', 'doop.deploy_lift2', '', 'multica.issue.close'])('wrong action type %j', async (type) => { + await refused( + world({ marker: SUSPENDED, decision: () => ({ status: 200, body: decisionOf({ action_type: type }) }) }), + undefined, + /action type/, + ) + }) + + it('wrong action version', async () => { + await refused( + world({ marker: SUSPENDED, decision: () => ({ status: 200, body: decisionOf({ action_version: 2 }) }) }), + undefined, + /action version/, + ) + }) + + it.each(['pending', 'rejected', 'withdrawn', 'revoked', 'expired', 'cancelled', 'failed', 'APPROVED', ''])( + 'state %j is not approved', + async (state) => { + await refused( + world({ marker: SUSPENDED, decision: () => ({ status: 200, body: decisionOf({ state }) }) }), + undefined, + /not approved|unreadable/, + ) + }, + ) + + it.each([ + ['withdrawn_at', '2026-11-20T02:30:00Z'], + ['revoked_at', '2026-11-20T02:30:00Z'], + ])('approved but %s is set', async (field, at) => { + await refused( + world({ marker: SUSPENDED, decision: () => ({ status: 200, body: decisionOf({ [field]: at }) }) }), + undefined, + /withdrawn|revoked/, + ) + }) + + it('approved but past its deadline', async () => { + await refused( + world({ + marker: SUSPENDED, + decision: () => ({ status: 200, body: decisionOf({ expires_at: '2026-11-20T02:59:59Z' }) }), + }), + undefined, + /expired/, + ) + }) + + it('approver is not Cheese', async () => { + await refused( + world({ + marker: SUSPENDED, + decision: () => ({ status: 200, body: decisionOf({ approver_id: 'user-agent-1' }) }), + }), + undefined, + /approver/, + ) + }) + + it('no configured approver id refuses everything', async () => { + await refused(world({ marker: SUSPENDED }), { approverId: '' }, /approver/) + }) +}) + +describe('refused: the marker (C-10.7)', () => { + it('marker_value is not the marker that stands now', async () => { + const other = 'suspended:' + '3'.repeat(32) + ':9:' + SHA + ':migrated' + await refused( + world({ + marker: SUSPENDED, + decision: () => ({ status: 200, body: decisionOf({ params: { marker_value: other, repo: REPO } }) }), + }), + undefined, + /marker_value/, + ) + }) + + it('marker_value differs by one byte (no prefix or case folding)', async () => { + await refused( + world({ + marker: SUSPENDED, + decision: () => ({ + status: 200, + body: decisionOf({ params: { marker_value: SUSPENDED + ' ', repo: REPO } }), + }), + }), + undefined, + /marker_value/, + ) + }) + + it('repo param is another repository', async () => { + await refused( + world({ + marker: SUSPENDED, + decision: () => ({ + status: 200, + body: decisionOf({ params: { marker_value: SUSPENDED, repo: 'other/doop' } }), + }), + }), + undefined, + /repo/, + ) + }) + + it('the marker is already clear: nothing to lift', async () => { + await refused( + world({ + marker: CLEAR, + decision: () => ({ status: 200, body: decisionOf({ params: { marker_value: CLEAR, repo: REPO } }) }), + }), + undefined, + /clear/, + ) + }) + + it('the marker is absent', async () => { + await refused(world({ marker: null }), undefined, /absent/) + }) + + it('the marker is unreadable', async () => { + await refused(world({ marker: SUSPENDED, unreadableMarker: true }), undefined, /marker/) + }) + + it('the marker is not a marker value', async () => { + await refused( + world({ + marker: 'whatever', + decision: () => ({ status: 200, body: decisionOf({ params: { marker_value: 'whatever', repo: REPO } }) }), + }), + undefined, + /marker/, + ) + }) +}) + +describe('refused: a change during the lift (C-10.7, the re-read under the lock)', () => { + it('the marker changes after the decision was read: refused, and the new marker stands', async () => { + const other = 'suspended:' + '3'.repeat(32) + ':10:' + SHA + ':readback' + const env = world({ + marker: SUSPENDED, + decision: (n) => { + if (n === 2) env.w.marker = other // a recovery run suspends again while the lift runs + return { status: 200, body: decisionOf() } + }, + }) + const ev = await refused(env, undefined, /marker/, other) + expect(ev.reason).toMatch(/changed|marker_value/) + }) + + it('the marker changes between the re-read and the write: writeMarker still refuses', async () => { + const other = 'suspended:' + '3'.repeat(32) + ':10:' + SHA + ':readback' + const env = world({ + marker: SUSPENDED, + afterMarkerRead: (n, w) => { + if (n === 2) w.marker = other // the second marker read passes; the next one sees the change + }, + }) + const ev = await refused(env, undefined, /changed/, other) + expect(ev.outcome).toBe('refused') + }) + + it.each(['revoked', 'withdrawn', 'expired', 'rejected'])('the decision becomes %s during the lift', async (state) => { + const env = world({ + marker: SUSPENDED, + decision: (n) => ({ status: 200, body: decisionOf(n === 1 ? {} : { state }) }), + }) + await refused(env, undefined, /not approved/) + expect(env.calls.decision).toBe(2) + }) + + it('revoked_at appears during the lift', async () => { + const env = world({ + marker: SUSPENDED, + decision: (n) => ({ status: 200, body: decisionOf(n === 1 ? {} : { revoked_at: '2026-11-20T02:59:00Z' }) }), + }) + await refused(env, undefined, /revoked/) + }) + + it('the decision cannot be read the second time', async () => { + const env = world({ + marker: SUSPENDED, + decision: (n) => (n === 1 ? { status: 200, body: decisionOf() } : { status: 503 }), + }) + await refused(env, undefined, /unreadable/) + }) + + it('a write that cannot be read back is a failure, not a refusal, and says so', async () => { + const env = world({ marker: SUSPENDED }) + const base = env.ghApi + env.ghApi = async (path: string, init?: { method?: string; body?: { value: string } }) => { + if (init?.method === 'PATCH') { + env.calls.writes.push(init.body?.value ?? '') + return {} // lost update: GitHub says ok, a read still returns the old value + } + return base(path, init) + } + const ev = await run(env) + expect(ev.outcome).toBe('failed') + expect(ev.reason).toMatch(/read back/) + }) +}) + +describe('refused: C00 (C-10.7)', () => { + it.each([404, 500, 503, 302])('/healthz answers %i', async (status) => { + await refused(world({ marker: SUSPENDED, health: status }), undefined, /health/) + }) + + it('/healthz does not answer', async () => { + await refused(world({ marker: SUSPENDED, health: 'throw' }), undefined, /health/) + }) + + it('unproven migration quiescence', async () => { + await refused(world({ marker: SUSPENDED }), { facts: { ...goodFacts, quiescent: false } }, /quiescence/) + }) + + it.each([undefined, 'true', 1])('quiescence must be the boolean true, not %j', async (quiescent) => { + await refused(world({ marker: SUSPENDED }), { facts: { ...goodFacts, quiescent } }, /quiescence/) + }) + + it('the container itself is not healthy', async () => { + await refused(world({ marker: SUSPENDED }), { facts: { ...goodFacts, containerHealth: 'unhealthy' } }, /health/) + }) + + it.each([ + ['digest', 'latest'], + ['digest', ''], + ['revision', 'abc'], + ['revision', ''], + ])('no readable %s (%j)', async (field, value) => { + await refused(world({ marker: SUSPENDED }), { facts: { ...goodFacts, [field]: value } }, new RegExp(field)) + }) + + it('a refusal never reaches the marker API at all for a bad run id', async () => { + const env = world({ marker: SUSPENDED }) + const ev = await lift({ + ghApi: env.ghApi, + fetchImpl: env.fetchImpl, + repo: REPO, + runId: 'x; rm -rf', + lifter: 'congvc-dev', + decisionId: DECISION_ID, + approverId: CHEESE, + server: SERVER, + workspace: WORKSPACE, + token: TOKEN, + healthzUrl: HEALTHZ, + facts: goodFacts, + now: () => NOW, + }) + expect(ev.outcome).toBe('refused') + expect(env.calls.writes).toEqual([]) + }) +}) + +describe('two lifts of the same decision serialize, and the second is refused (marker changed)', () => { + it('the second sees the first one’s clear and refuses', async () => { + const env = world({ marker: SUSPENDED }) + const first = await run(env) + expect(first.outcome).toBe('lifted') + const afterFirst = env.w.marker + const second = await run(env) + expect(second.outcome).toBe('refused') + expect(second.reason).toMatch(/marker/) + expect(env.calls.writes).toHaveLength(1) + expect(env.w.marker).toBe(afterFirst) + }) +}) + +describe('the decision read', () => { + const base = { server: SERVER, workspace: WORKSPACE, token: TOKEN, id: DECISION_ID } + + it('refuses a decision id that is not a plain token, before any request', async () => { + const env = world({ marker: SUSPENDED }) + await expect(readDecision({ ...base, id: '../x?y', fetchImpl: env.fetchImpl })).rejects.toThrow(/decision id/) + expect(env.calls.decision).toBe(0) + }) + + it.each(['', 'ftp://x', 'multica.tailnet.example'])( + 'refuses a server URL that is not http(s): %j', + async (server) => { + const env = world({ marker: SUSPENDED }) + await expect(readDecision({ ...base, server, fetchImpl: env.fetchImpl })).rejects.toThrow(/server/) + }, + ) + + it('refuses a missing token or workspace', async () => { + const env = world({ marker: SUSPENDED }) + await expect(readDecision({ ...base, token: '', fetchImpl: env.fetchImpl })).rejects.toThrow(/token/) + await expect(readDecision({ ...base, workspace: '', fetchImpl: env.fetchImpl })).rejects.toThrow(/workspace/) + }) + + it('does not put the token in an error', async () => { + const env = world({ marker: SUSPENDED, decision: () => ({ status: 500, text: TOKEN }) }) + const err = await readDecision({ ...base, fetchImpl: env.fetchImpl }).catch((e: Error) => e) + expect(String((err as Error).message)).not.toContain(TOKEN) + }) +}) + +describe('refusalFor (pure)', () => { + const ctx = { marker: SUSPENDED, repo: REPO, approverId: CHEESE, now: NOW } + it('is null for the good decision and names the reason otherwise', () => { + expect(refusalFor(decisionOf(), ctx)).toBeNull() + expect(refusalFor(decisionOf({ state: 'revoked' }), ctx)).toMatch(/not approved/) + expect(refusalFor(decisionOf({ approver_id: 'x' }), ctx)).toMatch(/approver/) + }) +}) + +describe('the dispatcher allowlist (C-10.7)', () => { + it('parses a comma or space separated list', () => { + expect(parseList('congvc-dev, congvc-bot-x99\ncheese')).toEqual(['congvc-dev', 'congvc-bot-x99', 'cheese']) + expect(parseList(undefined)).toEqual([]) + expect(parseList('')).toEqual([]) + }) + + it('admits a dispatcher on the list, whose own login also triggered the run', () => { + expect(() => + admitDispatcher({ actor: 'congvc-dev', triggering: 'congvc-dev', allowed: 'congvc-dev,congvc-bot-x99' }), + ).not.toThrow() + }) + + it.each([ + ['not on the list', 'mallory', 'mallory'], + ['actor on the list but the rerun was triggered by another login', 'congvc-dev', 'mallory'], + ['triggering login on the list but the actor is not', 'mallory', 'congvc-dev'], + ['empty actor', '', ''], + ])('refuses: %s', (_n, actor, triggering) => { + expect(() => admitDispatcher({ actor, triggering, allowed: 'congvc-dev,congvc-bot-x99' })).toThrow(/dispatcher/) + }) + + it('refuses everyone when the list is unset or empty', () => { + expect(() => admitDispatcher({ actor: 'congvc-dev', triggering: 'congvc-dev', allowed: '' })).toThrow(/dispatcher/) + expect(() => admitDispatcher({ actor: 'congvc-dev', triggering: 'congvc-dev', allowed: undefined })).toThrow( + /dispatcher/, + ) + }) + + it('matches whole logins, case-insensitively, never a prefix', () => { + expect(() => admitDispatcher({ actor: 'congvc', triggering: 'congvc', allowed: 'congvc-dev' })).toThrow() + expect(() => + admitDispatcher({ actor: 'CongVC-Dev', triggering: 'CONGVC-DEV', allowed: 'congvc-dev' }), + ).not.toThrow() + }) +}) + +describe('time in ICT', () => { + it('writes UTC+7 with the ICT suffix', () => { + expect(ictTime(new Date('2026-11-20T17:30:05Z'))).toBe('2026-11-21 00:30:05 ICT') + }) +}) + +describe('the CLI', () => { + const dir = () => mkdtempSync(join(tmpdir(), 'lift-')) + + it('refuses when the inputs are missing, writes lift-evidence.json, exits 1', async () => { + const { spawnSync } = await import('node:child_process') + const d = dir() + try { + const r = spawnSync('node', [join(process.cwd(), 'scripts/deploy-lift.mjs'), 'lift'], { + cwd: d, + encoding: 'utf8', + env: { PATH: process.env.PATH ?? '', GITHUB_STEP_SUMMARY: join(d, 'summary.md') }, + }) + expect(r.status).toBe(1) + const ev = JSON.parse(readFileSync(join(d, 'lift-evidence.json'), 'utf8')) + expect(ev.outcome).toBe('refused') + expect(readFileSync(join(d, 'summary.md'), 'utf8')).toContain('refused') + } finally { + rmSync(d, { recursive: true, force: true }) + } + }) + + it('admit exits 1 for a login that is not allowlisted', async () => { + const { spawnSync } = await import('node:child_process') + const r = spawnSync('node', [join(process.cwd(), 'scripts/deploy-lift.mjs'), 'admit'], { + encoding: 'utf8', + env: { PATH: process.env.PATH ?? '', ACTOR: 'mallory', TRIGGER: 'mallory', DISPATCHERS: 'congvc-dev' }, + }) + expect(r.status).toBe(1) + expect(r.stderr).toMatch(/dispatcher/) + }) + + it('admit exits 0 for an allowlisted login', async () => { + const { spawnSync } = await import('node:child_process') + const r = spawnSync('node', [join(process.cwd(), 'scripts/deploy-lift.mjs'), 'admit'], { + encoding: 'utf8', + env: { PATH: process.env.PATH ?? '', ACTOR: 'congvc-dev', TRIGGER: 'congvc-dev', DISPATCHERS: 'congvc-dev' }, + }) + expect(r.status).toBe(0) + }) +}) + +/* The real script, as the workflow runs it, against one local HTTP server standing in for GitHub, Multica and the app. */ +describe('the CLI end to end (a real process, real HTTP)', () => { + async function cli(over: { decision?: Decision; marker?: string; health?: number }) { + let marker = over.marker ?? SUSPENDED + const seen: string[] = [] + const server = createServer((req, res) => { + const url = req.url ?? '' + seen.push(`${req.method} ${url}`) + let body = '' + req.on('data', (c) => (body += c)) + req.on('end', () => { + const send = (status: number, json: unknown) => { + res.writeHead(status, { 'Content-Type': 'application/json' }) + res.end(JSON.stringify(json)) + } + if (url === `/api/decisions/${DECISION_ID}/state`) { + if (req.headers.authorization !== `Bearer ${TOKEN}` || req.headers['x-workspace-id'] !== WORKSPACE) + return send(403, {}) + return send(200, over.decision ?? decisionOf()) + } + if (url === '/healthz') return send(over.health ?? 200, { ok: true }) + if (url === `/${VAR_URL}`) { + if (req.method === 'PATCH') marker = (JSON.parse(body) as { value: string }).value + return send(200, { name: 'DOOP_DEPLOY_SUSPENDED', value: marker }) + } + send(404, {}) + }) + }) + await new Promise((r) => server.listen(0, '127.0.0.1', r)) + const port = (server.address() as { port: number }).port + const base = `http://127.0.0.1:${port}` + const d = mkdtempSync(join(tmpdir(), 'lift-e2e-')) + try { + const child = spawn('node', [join(process.cwd(), 'scripts/deploy-lift.mjs'), 'lift'], { + cwd: d, + env: { + PATH: process.env.PATH ?? '', + GITHUB_API_URL: base, + GITHUB_STEP_SUMMARY: join(d, 'summary.md'), + GH_TOKEN: 'app-token', + REPO, + RUN_ID, + LIFTER: 'congvc-dev', + DECISION_ID, + APPROVER_ID: CHEESE, + MULTICA_SERVER_URL: base, + MULTICA_WORKSPACE_ID: WORKSPACE, + DECISION_READ_TOKEN: TOKEN, + HEALTHZ_URL: `${base}/healthz`, + LIFT_QUIESCENT: 'true', + LIFT_DIGEST: DIGEST, + LIFT_REVISION: SHA, + LIFT_CONTAINER_HEALTH: 'healthy', + }, + }) + let out = '' + child.stdout.on('data', (c) => (out += c)) + child.stderr.on('data', (c) => (out += c)) + const code = await new Promise((r) => child.on('close', r)) + return { + code, + out, + marker, + seen, + evidence: JSON.parse(readFileSync(join(d, 'lift-evidence.json'), 'utf8')), + summary: readFileSync(join(d, 'summary.md'), 'utf8'), + } + } finally { + server.close() + rmSync(d, { recursive: true, force: true }) + } + } + + it('accepted: exit 0, the marker is a new clear, lift-evidence.json and the run summary say who, what and when', async () => { + const r = await cli({}) + expect(r.code, r.out).toBe(0) + expect(r.marker).toMatch(new RegExp(`^clear:[0-9a-f]{32}:${RUN_ID}$`)) + expect(r.evidence).toMatchObject({ + outcome: 'lifted', + lifter: 'congvc-dev', + decision_id: DECISION_ID, + approver_id: CHEESE, + digest: DIGEST, + revision: SHA, + marker_before: SUSPENDED, + marker_after: r.marker, + health: { status: 200 }, + }) + expect(r.evidence.started_ict).toMatch(/ ICT$/) + expect(r.evidence.finished_ict).toMatch(/ ICT$/) + for (const word of ['congvc-dev', DECISION_ID, CHEESE, DIGEST, SHA, 'ICT']) expect(r.summary).toContain(word) + expect(r.out).not.toContain(TOKEN) + expect(r.summary).not.toContain(TOKEN) + }) + + it('refused (decision rejected): exit 1, the marker is untouched, no write was sent, the evidence says why', async () => { + const r = await cli({ decision: decisionOf({ state: 'rejected' }) }) + expect(r.code).toBe(1) + expect(r.marker).toBe(SUSPENDED) + expect(r.seen.filter((s) => s.startsWith('PATCH'))).toEqual([]) + expect(r.evidence).toMatchObject({ outcome: 'refused', marker_before: SUSPENDED, marker_after: null }) + expect(r.evidence.reason).toMatch(/not approved/) + }) + + it('refused (/healthz 503): exit 1, the marker is untouched', async () => { + const r = await cli({ health: 503 }) + expect(r.code).toBe(1) + expect(r.marker).toBe(SUSPENDED) + expect(r.evidence.reason).toMatch(/health/) + }) +}) diff --git a/tests/deployLiftWorkflow.test.ts b/tests/deployLiftWorkflow.test.ts new file mode 100644 index 000000000..490ce954d --- /dev/null +++ b/tests/deployLiftWorkflow.test.ts @@ -0,0 +1,160 @@ +import { readFileSync } from 'node:fs' +import { describe, expect, it } from 'vitest' + +/* Text assertions on `cd-lift.yml` (CHE-5551, train S3b, plan CHE-5474 C-10.7): dispatch only, an allowlisted + dispatcher, one C00 job under the deploy lock, no human-typed command, no value inlined into a script. */ +const lift = readFileSync('.github/workflows/cd-lift.yml', 'utf8') +const deploy = readFileSync('.github/workflows/cd-deploy.yml', 'utf8') + +/* The text of one step, by its `name:`, up to the next step. */ +function step(name: string): string { + const parts = lift.split(/^ {6}- /m) + const hit = parts.find((p) => p.startsWith(`name: ${name}\n`) || p.includes(`\n name: ${name}\n`)) + if (!hit) throw new Error(`no step ${name}`) + return hit +} +const stepNames = [...lift.matchAll(/^ {6}- name: (.+)$/gm)].map((m) => m[1] ?? '') + +describe('cd-lift.yml: triggers', () => { + it('is classed deploy, and runs on manual dispatch only', () => { + expect(lift).toMatch(/^# ci-policy: class=deploy$/m) + const on = /^on:\n([\s\S]*?)(?=^\S)/m.exec(lift)?.[1] ?? '' + expect(on).toMatch(/^ {2}workflow_dispatch:/m) + expect(on).not.toMatch(/schedule|push|pull_request|workflow_call|workflow_run|repository_dispatch/) + }) + + it('takes one required input, decision_id, and nothing else', () => { + const on = /^on:\n([\s\S]*?)(?=^\S)/m.exec(lift)?.[1] ?? '' + const inputs = [...on.matchAll(/^ {6}([a-z_]+):\n/gm)].map((m) => m[1]) + expect(inputs).toEqual(['decision_id']) + expect(on).toMatch(/decision_id:[\s\S]*?required: true/) + expect(on).toMatch(/decision_id:[\s\S]*?type: string/) + }) + + it('reads contents only at workflow level', () => { + expect(lift).toMatch(/^permissions:\n {2}contents: read\n/m) + }) +}) + +describe('cd-lift.yml: the one job', () => { + it('runs on the C00 deploy runner, in the deploy lock group that is never cancelled', () => { + expect(lift).toContain('runs-on: [self-hosted, cheese-c00-deploy]') + expect(lift).toMatch(/concurrency:\n {6}group: c00-deploy-doop\n {6}cancel-in-progress: false/) + expect(lift).toContain(deploy.match(/group: c00-deploy-doop/)?.[0] ?? 'missing') + }) + + it('has exactly one job, and it runs only in this repository, from the default branch', () => { + const jobs = [...lift.matchAll(/^ {2}([a-z][a-z0-9-]*):\n/gm)].map((m) => m[1]) + expect(jobs).toEqual(['lift']) + expect(lift).toContain("github.repository == 'cheese-work/doop'") + // A dispatch from a branch would run that branch's lift script: only the default branch lifts. + expect(lift).toContain("github.ref == 'refs/heads/cheese/main'") + }) + + it('uses the doop-lift environment, which holds the decision read secrets', () => { + expect(lift).toMatch(/^ {4}environment: doop-lift$/m) + for (const s of ['DOOP_LIFT_DECISION_READ_TOKEN', 'DOOP_LIFT_MULTICA_SERVER_URL', 'DOOP_LIFT_MULTICA_WORKSPACE_ID']) + expect(lift).toContain(`secrets.${s}`) + }) + + it('names the approver and the dispatchers as repository variables', () => { + expect(lift).toContain('vars.DOOP_LIFT_APPROVER_ID') + expect(lift).toContain('vars.DOOP_LIFT_DISPATCHERS') + }) + + it('never inlines an input, a variable or a secret into a script: values go through env', () => { + for (const line of lift.split('\n').filter((l) => /^\s+run:/.test(l))) expect(line).not.toContain('${{') + // A multi-line run block is checked as a whole. + for (const m of lift.matchAll(/^\s+run: \|\n((?:\s{10,}.*\n?)+)/gm)) expect(m[1]).not.toContain('${{') + }) + + it('passes the decision id through env only, never into a command line', () => { + expect(lift).toMatch(/DECISION_ID: \$\{\{ inputs\.decision_id \}\}/) + expect(lift.match(/inputs\.decision_id/g)).toHaveLength(1) + }) + + it('has no human-typed command: every action is a script in this repository', () => { + const runs = [...lift.matchAll(/^\s+run: (.+)$/gm)].map((m) => m[1] ?? '') + for (const r of runs) expect(r).toMatch(/^(node scripts\/deploy-lift\.mjs |bash deploy\/cd\/c00\.sh |\|)/) + }) + + it('does not build, pull or start anything', () => { + expect(lift).not.toMatch(/docker (build|pull|run|compose)|npm (ci|install)|bun /) + }) +}) + +describe('cd-lift.yml: step order', () => { + it('admits the dispatcher first; the marker token is minted only after, and the lift runs last of the C00 steps', () => { + const at = (n: string) => stepNames.indexOf(n) + expect(at('Admit the dispatcher')).toBeGreaterThanOrEqual(0) + expect(at('Admit the dispatcher')).toBeLessThan(at('Mint the marker token')) + expect(at('Mint the marker token')).toBeLessThan(at('Sweep the compat sandboxes')) + expect(at('Sweep the compat sandboxes')).toBeLessThan(at('Lift on C00')) + expect(at('Lift on C00')).toBeLessThan(at('Upload the lift evidence')) + }) + + it('checks out the default branch’s code without keeping the token, before anything runs', () => { + expect(lift).toMatch(/uses: actions\/checkout@v4\n\s+with:\n\s+persist-credentials: false/) + expect(stepNames.indexOf('Admit the dispatcher')).toBeGreaterThan(-1) + expect(lift.indexOf('actions/checkout@v4')).toBeLessThan(lift.indexOf('Admit the dispatcher')) + }) + + it('admits by the actor and the triggering login against the allowlist, before any secret is read', () => { + const s = step('Admit the dispatcher') + expect(s).toContain('ACTOR: ${{ github.actor }}') + expect(s).toContain('TRIGGER: ${{ github.triggering_actor }}') + expect(s).toContain('DISPATCHERS: ${{ vars.DOOP_LIFT_DISPATCHERS }}') + expect(s).toContain('run: node scripts/deploy-lift.mjs admit') + expect(s).not.toContain('secrets.') + }) + + it('mints the marker token for variables only, pinned like D2', () => { + const s = step('Mint the marker token') + expect(s).toContain('actions/create-github-app-token@64ab729a6294000f5aa4a4bc0b73d1f32bc45510 # v3.3.0') + expect(s).toContain('permission-variables: write') + expect(s).toContain('repositories: doop') + expect(s).toContain('DOOP_MARKER_APP_KEY') + }) + + it('sweeps first (C-5, C-8.5d), then lifts under the host lock with c00.sh', () => { + expect(step('Sweep the compat sandboxes')).toContain('run: bash deploy/cd/c00.sh sweep') + expect(step('Lift on C00')).toContain('run: bash deploy/cd/c00.sh lift') + }) + + it('gives the lift the marker token, the read token and every id it checks, and nothing broader', () => { + const s = step('Lift on C00') + for (const v of [ + 'GH_TOKEN: ${{ steps.app.outputs.token }}', + 'REPO: ${{ github.repository }}', + 'RUN_ID: ${{ github.run_id }}', + 'LIFTER: ${{ github.triggering_actor }}', + 'DECISION_ID: ${{ inputs.decision_id }}', + 'APPROVER_ID: ${{ vars.DOOP_LIFT_APPROVER_ID }}', + 'MULTICA_SERVER_URL: ${{ secrets.DOOP_LIFT_MULTICA_SERVER_URL }}', + 'MULTICA_WORKSPACE_ID: ${{ secrets.DOOP_LIFT_MULTICA_WORKSPACE_ID }}', + 'DECISION_READ_TOKEN: ${{ secrets.DOOP_LIFT_DECISION_READ_TOKEN }}', + 'HEALTHZ_URL:', + ]) + expect(s).toContain(v) + expect(s).not.toContain('github.token') + }) + + it('uploads lift-evidence.json whatever happened, and never the token', () => { + const s = step('Upload the lift evidence') + expect(s).toContain('if: ${{ always() }}') + expect(s).toContain('uses: actions/upload-artifact@') + expect(s).toContain('lift-evidence.json') + expect(s).not.toMatch(/secrets\.|token/i) + }) +}) + +describe('cd-lift.yml: the train switch stays off', () => { + it('does not read or write DOOP_DEPLOY_TRAIN, and writes no marker but the lift’s own', () => { + const code = lift + .split('\n') + .filter((l) => !/^\s*#/.test(l)) + .join('\n') + expect(code).not.toContain('DOOP_DEPLOY_TRAIN') + expect(code).not.toMatch(/deploy-marker\.mjs/) + }) +}) diff --git a/tests/deployMarker.test.ts b/tests/deployMarker.test.ts index e5b5d8b60..1203029cc 100644 --- a/tests/deployMarker.test.ts +++ b/tests/deployMarker.test.ts @@ -1,7 +1,7 @@ import { spawnSync } from 'node:child_process' import { describe, expect, it } from 'vitest' // @ts-expect-error plain .mjs script, no type declarations -import { arm, kindOf, restore, suspend, writeMarker } from '../scripts/deploy-marker.mjs' +import { arm, kindOf, lift, readMarker, restore, suspend, writeMarker } from '../scripts/deploy-marker.mjs' /* CHE-5545 (train S3a, plan CHE-5474 C-10.1 to C-10.5). One repo variable, DOOP_DEPLOY_SUSPENDED, is the only thing that lets the train run. Every write is read, check, write, read back; a write that cannot be proven @@ -269,3 +269,50 @@ describe('deploy-marker CLI', () => { expect(run(['arm'], { RUN_ID: '1', SHA }).status).not.toBe(0) }) }) + +describe('lift (CHE-5551, C-10.7)', () => { + it('writes clear:: over exactly the expected suspended value, and reads it back', async () => { + const { state, ghApi } = fake(SUSPENDED) + const value = await lift({ ghApi, repo: REPO, runId: '777', expected: SUSPENDED }) + expect(value).toMatch(/^clear:[0-9a-f]{32}:777$/) + expect(kindOf(value)).toBe('clear') + expect(state.value).toBe(value) + expect(state.writes).toHaveLength(1) + }) + + it('lifts an armed value (a train run that died leaves one)', async () => { + const { state, ghApi } = fake(OTHER_ARMED) + await lift({ ghApi, repo: REPO, runId: '777', expected: OTHER_ARMED }) + expect(kindOf(state.value)).toBe('clear') + }) + + it('refuses when the marker is not the expected value: nothing is written', async () => { + const { state, ghApi } = fake(OTHER_ARMED) + await expect(lift({ ghApi, repo: REPO, runId: '777', expected: SUSPENDED })).rejects.toThrow(/changed/) + expect(state.writes).toEqual([]) + expect(state.value).toBe(OTHER_ARMED) + }) + + it.each([CLEAR, null, 'junk'])('refuses to lift %j (nothing to lift)', async (expected) => { + const { state, ghApi } = fake(expected) + await expect(lift({ ghApi, repo: REPO, runId: '777', expected })).rejects.toThrow(/lift needs/) + expect(state.writes).toEqual([]) + }) + + it.each(['', 'x y', '1;2', undefined])('refuses a lift run id of %j', async (runId) => { + const { state, ghApi } = fake(SUSPENDED) + await expect(lift({ ghApi, repo: REPO, runId, expected: SUSPENDED })).rejects.toThrow(/run id/) + expect(state.writes).toEqual([]) + }) + + it('fails when the write cannot be read back', async () => { + const { ghApi } = fake(SUSPENDED, { stale: true }) + await expect(lift({ ghApi, repo: REPO, runId: '777', expected: SUSPENDED })).rejects.toThrow(/read back/) + }) + + it('readMarker returns the value, null when absent, and throws on anything else', async () => { + expect(await readMarker(fake(SUSPENDED).ghApi, REPO)).toBe(SUSPENDED) + expect(await readMarker(fake(null).ghApi, REPO)).toBeNull() + await expect(readMarker(fake(SUSPENDED, { unreadable: true }).ghApi, REPO)).rejects.toThrow() + }) +}) From 40c8ba73f3bcf321e4fce709fc59c32161608f69 Mon Sep 17 00:00:00 2001 From: "congvc-bot[bot]" <3634010+congvc-bot[bot]@users.noreply.github.com> Date: Sat, 21 Nov 2026 01:21:29 +0700 Subject: [PATCH 2/2] fix(ci): lift refuses a decision answer that omits withdrawn_at, revoked_at or expires_at (CHE-5551) --- scripts/deploy-lift.mjs | 3 +++ tests/deployLift.test.ts | 9 +++++++++ 2 files changed, 12 insertions(+) diff --git a/scripts/deploy-lift.mjs b/scripts/deploy-lift.mjs index cbb362760..519b2408d 100644 --- a/scripts/deploy-lift.mjs +++ b/scripts/deploy-lift.mjs @@ -100,6 +100,9 @@ export function refusalFor(d, { marker, repo, approverId, now, id }) { if (!str(d.params?.marker_value) || !str(d.params?.repo)) return 'unreadable decision: params lack marker_value or repo' if (d.answered_at == null || instant(d.answered_at) === null) return 'unreadable decision: no answered_at' + // The API always sends these three, null when unset. An absent key is a malformed answer, not "unset". + for (const f of ['withdrawn_at', 'revoked_at', 'expires_at']) + if (!(f in d)) return `unreadable decision: no ${f} field` if (d.expires_at != null && instant(d.expires_at) === null) return 'unreadable decision: expires_at is not a time' if (Number(d.action_version) !== ACTION_VERSION) return `wrong action version '${d.action_version}', need ${ACTION_VERSION}` diff --git a/tests/deployLift.test.ts b/tests/deployLift.test.ts index 33ffa91d1..caab1e1ea 100644 --- a/tests/deployLift.test.ts +++ b/tests/deployLift.test.ts @@ -48,6 +48,12 @@ const decisionOf = (over: Decision = {}): Decision => ({ ...over, }) +/** A well-formed decision with one API field left out of the body (not null: absent). */ +const withoutField = (field: string): Decision => { + const { [field]: _omitted, ...rest } = decisionOf() + return rest +} + type World = { marker: string | null /** What the decision API answers on read n (1-based); a function may change the world first. */ @@ -230,6 +236,9 @@ describe('refused: the decision (C-10.6, C-10.7)', () => { ['no answered_at', () => ({ status: 200, body: decisionOf({ answered_at: null }) })], ['another decision id', () => ({ status: 200, body: decisionOf({ decision_id: 'someone-else' }) })], ['an unparsable deadline', () => ({ status: 200, body: decisionOf({ expires_at: 'soon' }) })], + ['no withdrawn_at field', () => ({ status: 200, body: withoutField('withdrawn_at') })], + ['no revoked_at field', () => ({ status: 200, body: withoutField('revoked_at') })], + ['no expires_at field', () => ({ status: 200, body: withoutField('expires_at') })], ])('unreadable decision: %s', async (_name, decision) => { await refused(world({ marker: SUSPENDED, decision }), undefined, /unreadable|no such decision/) })