diff --git a/.github/workflows/release-candidate.yml b/.github/workflows/release-candidate.yml index ab00d06e69..43c983a8da 100644 --- a/.github/workflows/release-candidate.yml +++ b/.github/workflows/release-candidate.yml @@ -53,6 +53,7 @@ jobs: exclude_discovery: ${{ steps.request.outputs.exclude_discovery }} manifest: ${{ steps.request.outputs.manifest }} image_names: ${{ steps.request.outputs.image_names }} + reference_host_profiles: ${{ steps.request.outputs.reference_host_profiles }} steps: - name: Checkout protected workflow revision uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 @@ -77,6 +78,7 @@ jobs: REQUEST_RELEASE_ID: ${{ github.event.client_payload.release_id }} REQUEST_SOURCE_SHA: ${{ github.event.client_payload.source_sha }} REQUEST_ID: ${{ github.event.client_payload.request_id }} + REFERENCE_HOST_COORDINATOR: ${{ toJSON(github.event.client_payload.coordinator_reference_host) }} shell: bash run: | set -euo pipefail @@ -120,6 +122,23 @@ jobs: release_image_names="${selected_images% }" fi fi + reference_host_profiles='["breg","casework"]' + case "${REFERENCE_HOST_COORDINATOR}" in + null | false) ;; + true) + if [[ "${REQUEST_UNIT}" != stack || + " ${release_image_names} " != *" registry-session "* || + " ${release_image_names} " != *" coordinator "* ]]; then + echo "Coordinator reference host requires a Stack candidate with Session and Coordinator images" >&2 + exit 1 + fi + reference_host_profiles='["breg","casework","coordinator"]' + ;; + *) + echo "Coordinator reference host opt-in must be a JSON boolean" >&2 + exit 1 + ;; + esac if [[ ! "${REQUEST_RELEASE_ID}" =~ ^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$ ]]; then echo "release_id is invalid" >&2 exit 1 @@ -252,6 +271,7 @@ jobs: echo "tag=${tag}" echo "manifest=${manifest}" echo "image_names=${release_image_names}" + echo "reference_host_profiles=${reference_host_profiles}" } >> "${GITHUB_OUTPUT}" - name: Validate manifests, pins, recipes, and scanner policy fixtures @@ -2728,7 +2748,7 @@ jobs: strategy: fail-fast: false matrix: - profile: [breg, casework] + profile: ${{ fromJSON(needs.validate.outputs.reference_host_profiles) }} permissions: actions: read attestations: read @@ -2797,8 +2817,26 @@ jobs: run: | set -euo pipefail stage="${RUNNER_TEMP}/reference-host-inputs" + profile="$(jq -er '.profile' "${stage}/inputs.json")" + if [[ "${profile}" == coordinator ]]; then + input_sha256="$(sha256sum "${stage}/inputs.json")" + version="$(jq -er '.release.version' "${stage}/inputs.json")" + tool_sha256="$(jq -er '.assets.coordinatorctl.sha256 | select(test("^[a-f0-9]{64}$"))' "${stage}/inputs.json")" + printf '%s %s\n' "${tool_sha256}" "${stage}/coordinatorctl" | sha256sum --check --strict --quiet + if ! tool_version="$(timeout --kill-after=1s 5s "${stage}/coordinatorctl" --version)" || + [[ "${tool_version}" != "coordinatorctl ${version}" ]]; then + echo "Candidate coordinatorctl must report the sealed release version" >&2 + exit 1 + fi + node --test "${stage}/source/deploy/examples/business-registration/tests/coordinator.test.mjs" + fi bash "${stage}/source/release/scripts/candidate-host-smoke.sh" \ "${stage}" "${RUNNER_TEMP}/candidate-host-receipt.json" --with-deps + if [[ "${profile}" == coordinator ]]; then + sha256sum --check --strict --quiet <<<"${input_sha256}" + python3 release/scripts/candidate_host_inputs.py verify-coordinator-receipt \ + --stage "${stage}" --receipt "${RUNNER_TEMP}/candidate-host-receipt.json" + fi - name: Retain the checked reference host receipt uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 diff --git a/deploy/examples/business-registration/README.md b/deploy/examples/business-registration/README.md index 578e08596d..456e59976c 100644 --- a/deploy/examples/business-registration/README.md +++ b/deploy/examples/business-registration/README.md @@ -457,6 +457,72 @@ is refused, the protected page asks for sign-in again, and the second registrar can still read its Record. It checks application requests for browser-sent Authorization headers throughout. +## Add the Coordinator proof + +The [Coordinator overlay](coordinator/compose.yaml) adds an independent, +synthetic workflow. It reads ThunderID's public discovery document over +verified HTTPS and returns the issuer identifier. A separate, short-lived +fixture bearer can start and read this one workflow. The proof discovers the +active revision, starts a run once, checks that a read without a bearer +returns 401, and reads back the same run and revision until the expected +output is finished. Business submissions still use the BReg Action. This +fixture has no business trigger, registry access or Casework authority. + +Use the release source and a verified release manifest that contains both the +`registry-session` and `coordinator` image records. Stage the signed +`coordinatorctl` executable for Linux amd64 with the same-version tools in +`REFERENCE_ARTIFACTS` and verify it against that manifest. Complete the BReg +manual startup above before adding the overlay. Use the same Compose project +and environment file. + +```bash +reference_image_digest() { + jq -er --arg name "$1" ' + [.images[] | select(.name == $name) | .digest] + | select(length == 1) | .[0] + | select(test("^sha256:[0-9a-f]{64}$") and . != ("sha256:" + ("0" * 64)))' \ + "$RELEASE_MANIFEST" +} +REFERENCE_SESSION_DIGEST=$(reference_image_digest registry-session) +REFERENCE_COORDINATOR_DIGEST=$(reference_image_digest coordinator) +export REFERENCE_SESSION_DIGEST REFERENCE_COORDINATOR_DIGEST + +umask 077 +mkdir -p "$REFERENCE_CONFIG/coordinator" +"$REFERENCE_ARTIFACTS/coordinatorctl" --format json package \ + --project "$RECIPE/coordinator/workflow" \ + --output "$REFERENCE_CONFIG/coordinator/package" \ + > "$REFERENCE_CONFIG/coordinator/package-report.json" +coordinator_digest=$(jq -er '.packageDigest' "$REFERENCE_CONFIG/coordinator/package-report.json") +node "$RECIPE/coordinator/prepare.mjs" "$REFERENCE_CONFIG" "$coordinator_digest" + +compose+=(--file "$RECIPE/coordinator/compose.yaml") +"${compose[@]}" pull session coordinator +coordinator_admin=("${compose[@]}" run -T --rm coordinator-admin \ + --runtime-config /run/coordinator/runtime.yaml --posture production) +"${coordinator_admin[@]}" check --deny-warnings +"${coordinator_admin[@]}" provision --admin-url-file /run/coordinator/secrets/admin-database-url +"${coordinator_admin[@]}" apply +"${coordinator_admin[@]}" deployment-status +"${compose[@]}" up --wait --wait-timeout 60 --no-build session coordinator +timeout --kill-after=5s 90s "${compose[@]}" run -T --rm --no-deps coordinator-proof +``` + +The setup uses the existing private PostgreSQL server and creates a separate +`reference_coordinator` database with distinct migration and runtime roles +and verified TLS. The administrator and migration URLs are mounted only for +setup. The proof's signing key is mounted only for the one-shot proof. The +Coordinator listener binds loopback inside the private upstream namespace, +with no edge route or host port. Use the extended Compose command for teardown. + +For a source-checkout run, build `registry-coordinator` with the same build +command as the other reference binaries, and pass `coordinator` in place of +`casework` to `tests/run-reference.sh`. This selects the existing local +overlay plus the [Coordinator local overlay](coordinator/compose.local.yaml), +using the local `coordinator` and `coordinatorctl` executables. The runner +checks the BReg browser journey and includes the Coordinator run ID, workflow +ID, revision and finished state in its receipt. + ## Remove the instance Stop the containers and remove the project's volumes, networks and the @@ -474,8 +540,8 @@ Keep the audit files if you need them, then delete `REFERENCE_CONFIG` with root, because some files belong to UIDs 999 and 10001. Also delete `REFERENCE_CA`, `BUSINESS_BUNDLE` and the identity work directory. -To replay the BReg or Casework proof with an attested candidate, follow the -[candidate reference-host replay](../../../release/OPERATIONS.md#replay-the-candidate-reference-host-locally). +To replay the BReg, Casework, or Coordinator proof with an attested candidate, +follow the [candidate reference-host replay](../../../release/OPERATIONS.md#replay-the-candidate-reference-host-locally). ## Check browser route parity diff --git a/deploy/examples/business-registration/coordinator/compose.local.yaml b/deploy/examples/business-registration/coordinator/compose.local.yaml new file mode 100644 index 0000000000..5a3a5fc14b --- /dev/null +++ b/deploy/examples/business-registration/coordinator/compose.local.yaml @@ -0,0 +1,12 @@ +# Add after compose.yaml and coordinator/compose.yaml for local development. +services: + coordinator: + image: ubuntu:24.04@sha256:73b999393d07f2bf65a40373778a44dc9a6d54ad7718d29247d8ff9413c4d6a8 + entrypoint: [/opt/native/coordinator] + volumes: + - ${REFERENCE_ARTIFACTS}/coordinator:/opt/native/coordinator:ro + coordinator-admin: + image: ubuntu:24.04@sha256:73b999393d07f2bf65a40373778a44dc9a6d54ad7718d29247d8ff9413c4d6a8 + entrypoint: [/opt/native/coordinatorctl] + volumes: + - ${REFERENCE_ARTIFACTS}/coordinatorctl:/opt/native/coordinatorctl:ro diff --git a/deploy/examples/business-registration/coordinator/compose.yaml b/deploy/examples/business-registration/coordinator/compose.yaml new file mode 100644 index 0000000000..10397a7a37 --- /dev/null +++ b/deploy/examples/business-registration/coordinator/compose.yaml @@ -0,0 +1,47 @@ +x-coordinator: &coordinator + image: ${REFERENCE_COORDINATOR_REPOSITORY:-ghcr.io/registrystack/coordinator}@${REFERENCE_COORDINATOR_DIGEST:?Set REFERENCE_COORDINATOR_DIGEST to the verified Coordinator image digest} + user: "${REFERENCE_UID:-1000}:${REFERENCE_GID:-1000}" + read_only: true + cap_drop: [ALL] + security_opt: [no-new-privileges:true] + +services: + coordinator: + <<: *coordinator + network_mode: service:upstreams + command: [--runtime-config, /run/coordinator/runtime.yaml, --posture, production] + environment: + SSL_CERT_FILE: /run/trust/https-ca.pem + volumes: + - ${REFERENCE_CONFIG}/coordinator/runtime:/run/coordinator:ro + - ${REFERENCE_CONFIG}/coordinator/package:/run/coordinator-package:ro + - ${REFERENCE_CONFIG}/coordinator/audit:/var/lib/registry-coordinator + - ${REFERENCE_CONFIG}/trust:/run/trust:ro + depends_on: + postgres: {condition: service_healthy} + issuer-ready: {condition: service_completed_successfully} + + coordinator-admin: + <<: *coordinator + profiles: [setup] + networks: [database] + entrypoint: [/usr/local/bin/coordinatorctl] + volumes: + - ${REFERENCE_CONFIG}/coordinator/admin:/run/coordinator:ro + - ${REFERENCE_CONFIG}/coordinator/package:/run/coordinator-package:ro + - ${REFERENCE_CONFIG}/coordinator/audit:/var/lib/registry-coordinator + depends_on: + postgres: {condition: service_healthy} + + coordinator-proof: + image: node:24.22.3@sha256:dc26ae92c9fb15cf6b1d63e20f0944b2efe0f115b20e00be48fb23fceb061c54 + user: "${REFERENCE_UID:-1000}:${REFERENCE_GID:-1000}" + network_mode: service:upstreams + read_only: true + cap_drop: [ALL] + security_opt: [no-new-privileges:true] + profiles: [setup] + entrypoint: [node, /run/reference/prove.mjs, /run/proof/signing-key.pem] + volumes: + - ./coordinator/prove.mjs:/run/reference/prove.mjs:ro + - ${REFERENCE_CONFIG}/coordinator/proof:/run/proof:ro diff --git a/deploy/examples/business-registration/coordinator/prepare.mjs b/deploy/examples/business-registration/coordinator/prepare.mjs new file mode 100644 index 0000000000..59c845a857 --- /dev/null +++ b/deploy/examples/business-registration/coordinator/prepare.mjs @@ -0,0 +1,39 @@ +import { generateKeyPairSync, randomBytes } from 'node:crypto' +import { mkdir, readFile, writeFile } from 'node:fs/promises' +import { isAbsolute, join } from 'node:path' + +const [root, digest, ...extra] = process.argv.slice(2) +const digestSlot = 'sha256:' + '0'.repeat(64) +if (!root || !isAbsolute(root) || !/^sha256:[a-f0-9]{64}$/u.test(digest) || digest === digestSlot || extra.length) { + throw new Error('Pass the absolute reference config directory and the sealed Coordinator package digest.') +} + +const template = await readFile(new URL('runtime.yaml', import.meta.url), 'utf8') +if (template.split(digestSlot).length !== 2) throw new Error('Expected one Coordinator package digest slot.') +const runtime = template.replace(digestSlot, digest) +const adminUrl = await readFile(join(root, 'breg/admin/secrets/admin-database-url')) +const databaseCa = await readFile(join(root, 'trust/postgres-ca.pem')) +const databaseUrl = role => `postgresql://reference_coordinator_${role}:${randomBytes(32).toString('hex')}@postgres:5432/reference_coordinator?sslmode=verify-full` +const { privateKey, publicKey } = generateKeyPairSync('rsa', { modulusLength: 2048 }) +const jwk = { ...publicKey.export({ format: 'jwk' }), alg: 'RS256', use: 'sig', kid: 'reference-coordinator' } +const serving = { + 'runtime-database-url': databaseUrl('runtime'), + 'database-ca': databaseCa, + 'audit-key': randomBytes(32), + 'admission-key': randomBytes(32), + 'state-key': randomBytes(32), + 'oidc-jwks': JSON.stringify({ keys: [jwk] }), +} + +const path = (...parts) => join(root, 'coordinator', ...parts) +const write = (value, ...parts) => writeFile(path(...parts), value, { flag: 'wx', mode: 0o600 }) +for (const [area, secrets] of Object.entries({ + admin: { ...serving, 'admin-database-url': adminUrl, 'migration-database-url': databaseUrl('migration') }, + runtime: serving, +})) { + await mkdir(path(area, 'secrets'), { recursive: true, mode: 0o700 }) + await write(runtime, area, 'runtime.yaml') + for (const [name, value] of Object.entries(secrets)) await write(value, area, 'secrets', name) +} +for (const area of ['audit', 'proof']) await mkdir(path(area), { mode: 0o700 }) +await write(privateKey.export({ type: 'pkcs8', format: 'pem' }), 'proof', 'signing-key.pem') diff --git a/deploy/examples/business-registration/coordinator/prove.mjs b/deploy/examples/business-registration/coordinator/prove.mjs new file mode 100644 index 0000000000..4a23e07337 --- /dev/null +++ b/deploy/examples/business-registration/coordinator/prove.mjs @@ -0,0 +1,127 @@ +import { createPrivateKey, randomUUID, sign } from 'node:crypto' +import { readFile } from 'node:fs/promises' +import { resolve } from 'node:path' +import { setTimeout as sleep } from 'node:timers/promises' +import { pathToFileURL } from 'node:url' + +const workflow = 'reference-coordinator' +const outcome = 'issuer-checked' +const issuer = 'https://identity.reference.test:9443' +const service = 'http://127.0.0.1:8108' + +function fixtureToken(key) { + const now = Math.floor(Date.now() / 1000) + const client = 'reference-coordinator-producer' + const encode = value => Buffer.from(JSON.stringify(value)).toString('base64url') + const header = encode({ alg: 'RS256', kid: workflow, typ: 'at+jwt' }) + const claims = encode({ + iss: 'https://coordinator-fixture.reference.test', aud: 'urn:example:reference-coordinator', + sub: client, client_id: client, scope: 'coordinator:reference', iat: now, exp: now + 120, + jti: randomUUID(), + }) + const unsigned = header + '.' + claims + return unsigned + '.' + sign('sha256', Buffer.from(unsigned), key).toString('base64url') +} + +async function json(response, expected, phase) { + if (response.status !== expected) { + await response.body?.cancel() + throw new Error(`Coordinator ${phase} returned HTTP ${response.status}.`) + } + const chunks = [] + let bytes = 0 + for await (const chunk of response.body) { + bytes += chunk.length + if (bytes > 64 * 1024) throw new Error(`Coordinator ${phase} exceeded 64 KiB.`) + chunks.push(chunk) + } + try { + return JSON.parse(Buffer.concat(chunks).toString('utf8')) + } catch { + throw new Error(`Coordinator ${phase} returned invalid JSON.`) + } +} + +export async function proveCoordinator(key, { fetch = globalThis.fetch, pause = sleep } = {}) { + const request = (path, method, headers = {}, body) => fetch(new URL(path, service), { + method, headers, body, redirect: 'error', signal: AbortSignal.timeout(2000), + }) + let ready + for (let attempt = 0; attempt < 15; attempt++) { + const probe = await request('/ready', 'GET').catch(error => { + if (error instanceof TypeError || error.name === 'TimeoutError') return undefined + throw error + }) + if (probe && probe.status !== 503) { + ready = await json(probe, 200, 'readiness') + break + } + await probe?.body?.cancel() + await pause(500) + } + if (ready?.ready !== true || ready.posture !== 'production' + || !Array.isArray(ready.developmentSettings) || ready.developmentSettings.length !== 0) { + throw new Error('Coordinator did not become ready in production posture.') + } + const auth = { Authorization: 'Bearer ' + fixtureToken(key) } + const contract = await json(await request('/v1/workflows/' + workflow, 'GET', auth), 200, 'workflow discovery') + const { workflowRevision } = contract + if (contract.workflow !== workflow || !/^sha256:[a-f0-9]{64}$/u.test(workflowRevision)) { + throw new Error('Coordinator did not discover the expected workflow revision.') + } + const start = await json(await request('/v1/runs', 'POST', { + ...auth, 'Content-Type': 'application/json', 'Idempotency-Key': randomUUID(), + }, JSON.stringify({ workflow, workflowRevision, input: {} })), 200, 'admission') + const { runId } = start + if (start.workflow !== workflow || start.workflowRevision !== workflowRevision + || !/^[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/u.test(runId)) { + throw new Error('Coordinator admitted a different run.') + } + const path = '/v1/runs/' + runId + const refusal = await request(path, 'GET') + await refusal.body?.cancel() + if (refusal.status !== 401) throw new Error('Coordinator did not refuse the unauthenticated run read.') + + const deadline = performance.now() + 35_000 + for (let attempt = 0; attempt < 40 && performance.now() < deadline; attempt++) { + const readback = await json(await request(path, 'GET', auth), 200, 'run read') + if (readback.runId !== runId || readback.workflow !== workflow || readback.workflowRevision !== workflowRevision) { + throw new Error('Coordinator returned a different run.') + } + if (readback.state === 'finished') { + if (readback.outcome !== outcome || readback.output?.issuer !== issuer + || Object.keys(readback.output).length !== 1 || readback.uncertain !== false + || readback.restoreReviewRequired !== false) { + throw new Error('Coordinator did not return the expected completion.') + } + return { + workflow: readback.workflow, + workflowRevision: readback.workflowRevision, + runId: readback.runId, + state: readback.state, + outcome: readback.outcome, + output: readback.output, + uncertain: readback.uncertain, + restoreReviewRequired: readback.restoreReviewRequired, + } + } + if (readback.state !== 'running') { + const state = ['failed', 'cancelled', 'expired', 'attention', 'cancel-requested', 'cancelled-after-effect'] + .includes(readback.state) ? readback.state : 'unknown' + throw new Error(`Coordinator run reached state ${state}.`) + } + await pause(1000) + } + throw new Error('Coordinator did not finish within the completion deadline.') +} + +if (process.argv[1] && import.meta.url === pathToFileURL(resolve(process.argv[1])).href) { + try { + const key = createPrivateKey(await readFile(process.argv[2])) + console.log(JSON.stringify(await proveCoordinator(key))) + } catch (error) { + const diagnostic = error.message.startsWith('Coordinator ') ? error.message : 'Coordinator proof exchange failed.' + console.error(diagnostic) + process.exitCode = 1 + } +} diff --git a/deploy/examples/business-registration/coordinator/runtime.yaml b/deploy/examples/business-registration/coordinator/runtime.yaml new file mode 100644 index 0000000000..d0c7b084bd --- /dev/null +++ b/deploy/examples/business-registration/coordinator/runtime.yaml @@ -0,0 +1,59 @@ +# yaml-language-server: $schema=https://id.registrystack.org/schemas/coordinator/runtime/runtime.v1alpha1.schema.json +apiVersion: id.registrystack.org/formats/coordinator/runtime/v1alpha1 +kind: CoordinatorRuntimeConfig +secretProviders: + file: + root: /run/coordinator/secrets +database: + transport: verified-tls + runtimeUrlRef: secret:file/runtime-database-url + migrationUrlRef: secret:file/migration-database-url + caBundleRef: secret:file/database-ca +namespace: coordinator_reference +connections: + identity-metadata: + type: external-http + baseUrl: https://identity.reference.test:9443/ + paths: [.well-known/openid-configuration] + responseSchema: + type: object + required: [status, body] + properties: + status: {const: 200} + body: + type: object + required: [issuer] + properties: + issuer: {const: 'https://identity.reference.test:9443'} +deployment: + databaseId: reference-coordinator + runtimeRole: reference_coordinator_runtime + packages: + - root: /run/coordinator-package + expectedDigest: sha256:0000000000000000000000000000000000000000000000000000000000000000 + listener: + bind: 127.0.0.1:8108 + tlsTermination: loopback-plaintext + authentication: + issuers: + fixture: + issuer: https://coordinator-fixture.reference.test + audience: urn:example:reference-coordinator + jwksSource: + type: static + documentRef: secret:file/oidc-jwks + allowedClients: from-access-profiles + accessProfiles: + fixture-producer: + requesterClients: [reference-coordinator-producer] + subjects: [reference-coordinator-producer] + requiredScopes: [coordinator:reference] + workflows: [reference-coordinator] + actions: [start, status] + auditFile: /var/lib/registry-coordinator/audit.jsonl + auditKeyRef: secret:file/audit-key + activeStateKey: 1 + stateKeys: + "1": + keyRef: secret:file/state-key + admissionKeyRef: secret:file/admission-key diff --git a/deploy/examples/business-registration/coordinator/workflow/fixtures/issuer-read.yaml b/deploy/examples/business-registration/coordinator/workflow/fixtures/issuer-read.yaml new file mode 100644 index 0000000000..8af2110d83 --- /dev/null +++ b/deploy/examples/business-registration/coordinator/workflow/fixtures/issuer-read.yaml @@ -0,0 +1,17 @@ +# yaml-language-server: $schema=https://id.registrystack.org/schemas/coordinator/fixture/fixture.v1alpha1.schema.json +apiVersion: id.registrystack.org/formats/coordinator/fixture/v1alpha1 +kind: CoordinatorFixture +id: issuer-read +admittedAt: '2026-10-10T09:00:00Z' +input: {} +replies: + read: + - type: success + value: + status: 200 + body: {issuer: 'https://identity.reference.test:9443'} +expect: + path: [read, checked] + state: completed + outcome: {type: named, value: issuer-checked} + output: {issuer: 'https://identity.reference.test:9443'} diff --git a/deploy/examples/business-registration/coordinator/workflow/workflow.yaml b/deploy/examples/business-registration/coordinator/workflow/workflow.yaml new file mode 100644 index 0000000000..f8a344f299 --- /dev/null +++ b/deploy/examples/business-registration/coordinator/workflow/workflow.yaml @@ -0,0 +1,40 @@ +# yaml-language-server: $schema=https://id.registrystack.org/schemas/coordinator/project/project.v1alpha1.schema.json +apiVersion: id.registrystack.org/formats/coordinator/project/v1alpha1 +kind: CoordinatorProject +project: + id: reference-coordinator + version: '1' +operations: + read-issuer: + uses: external.get/v1 + connection: identity-metadata +workflow: + input: + type: object + additionalProperties: false + properties: {} + deadlineSeconds: 30 + start: read + steps: + read: + type: call + operation: read-issuer + input: + type: fields + fields: + path: {type: literal, value: .well-known/openid-configuration} + next: checked + checked: + type: finish + outcome: issuer-checked + output: + type: fields + fields: + issuer: {type: step, step: read, path: /body/issuer} + outcomes: + issuer-checked: + type: object + additionalProperties: false + required: [issuer] + properties: + issuer: {type: string} diff --git a/deploy/examples/business-registration/tests/coordinator.test.mjs b/deploy/examples/business-registration/tests/coordinator.test.mjs new file mode 100644 index 0000000000..c517ffa35c --- /dev/null +++ b/deploy/examples/business-registration/tests/coordinator.test.mjs @@ -0,0 +1,82 @@ +import assert from 'node:assert/strict' +import { generateKeyPairSync, verify } from 'node:crypto' +import { test } from 'node:test' +import { proveCoordinator } from '../coordinator/prove.mjs' + +const workflow = 'reference-coordinator' +const workflowRevision = 'sha256:' + '1'.repeat(64) +const runId = '74289567-e3f1-4746-abc9-56655cd1dc04' +const issuer = 'https://identity.reference.test:9443' +const identity = { workflow, workflowRevision, runId } +const finished = { + ...identity, state: 'finished', outcome: 'issuer-checked', output: { issuer }, + uncertain: false, restoreReviewRequired: false, +} +const { privateKey, publicKey } = generateKeyPairSync('rsa', { modulusLength: 2048 }) + +function fixture(statuses = [{ ...identity, state: 'running' }, finished], refusal = 401) { + const calls = [] + async function fetch(url, options) { + assert.equal(url.origin, 'http://127.0.0.1:8108') + assert.equal(options.redirect, 'error') + assert.ok(options.signal instanceof AbortSignal) + calls.push([options.method, url.pathname, Boolean(options.headers.Authorization)]) + if (url.pathname === '/ready') { + return Response.json({ ready: true, posture: 'production', developmentSettings: [] }) + } + if (!options.headers.Authorization) return Response.json({}, { status: refusal }) + const [header, claims, signature] = options.headers.Authorization.slice('Bearer '.length).split('.') + assert.ok(verify('sha256', Buffer.from(header + '.' + claims), publicKey, Buffer.from(signature, 'base64url'))) + const { iss, aud, sub, client_id, scope, iat, exp } = JSON.parse(Buffer.from(claims, 'base64url')) + assert.equal(iss, 'https://coordinator-fixture.reference.test') + assert.equal(aud, 'urn:example:reference-coordinator') + assert.equal(sub, 'reference-coordinator-producer') + assert.equal(client_id, sub) + assert.equal(scope, 'coordinator:reference') + assert.equal(exp - iat, 120) + if (url.pathname === '/v1/workflows/' + workflow) return Response.json({ workflow, workflowRevision }) + if (url.pathname === '/v1/runs') { + assert.equal(options.method, 'POST') + assert.match(options.headers['Idempotency-Key'], /^[a-f0-9-]{36}$/u) + assert.deepEqual(JSON.parse(options.body), { workflow, workflowRevision, input: {} }) + return Response.json({ ...identity, state: 'running' }) + } + assert.equal(url.pathname, '/v1/runs/' + runId) + assert.equal(options.method, 'GET') + return Response.json(statuses.length > 1 ? statuses.shift() : statuses[0]) + } + return { calls, run: () => proveCoordinator(privateKey, { fetch, pause: async () => {} }) } +} + +test('requires a separate authenticated read of the exact completed run', async () => { + const { calls, run } = fixture() + assert.deepEqual(await run(), finished) + assert.deepEqual(calls, [ + ['GET', '/ready', false], + ['GET', '/v1/workflows/' + workflow, true], + ['POST', '/v1/runs', true], + ['GET', '/v1/runs/' + runId, false], + ['GET', '/v1/runs/' + runId, true], + ['GET', '/v1/runs/' + runId, true], + ]) +}) + +test('refuses mismatched, unauthenticated, ambiguous or nonterminal evidence', async () => { + await assert.rejects(fixture([finished], 200).run, /unauthenticated run read/u) + for (const change of [ + { runId: '51289567-e3f1-4746-abc9-56655cd1dc04' }, { workflow: 'other' }, + { workflowRevision: 'sha256:' + '2'.repeat(64) }, + ]) { + await assert.rejects(fixture([{ ...finished, ...change }]).run, /different run/u) + } + for (const change of [{ outcome: 'other' }, { output: {} }, { output: { issuer, extra: true } }, + { uncertain: true }, { restoreReviewRequired: true }]) { + await assert.rejects(fixture([{ ...finished, ...change }]).run, /expected completion/u) + } + assert.deepEqual(await fixture([{ ...finished, extraRuntimeData: 'excluded' }]).run(), finished) + await assert.rejects(fixture([{ ...finished, state: 'failed' }]).run, /state failed/u) + const { calls, run } = fixture([{ ...identity, state: 'running' }]) + await assert.rejects(run, /completion deadline/u) + assert.equal(calls.filter(([method]) => method === 'POST').length, 1) + assert.ok(calls.length < 50) +}) diff --git a/deploy/examples/business-registration/tests/receipt.mjs b/deploy/examples/business-registration/tests/receipt.mjs index 8a44ed6d30..9a6d59d50b 100644 --- a/deploy/examples/business-registration/tests/receipt.mjs +++ b/deploy/examples/business-registration/tests/receipt.mjs @@ -23,7 +23,7 @@ export function assertReceipt(profile, receipt) { assert.deepEqual(receipt.citizenCaseworkRefusal, refusal) return } - assert.equal(profile, 'breg') + assert.ok(profile === 'breg' || profile === 'coordinator') assert.equal(receipt.distinctSubjects, true) assert.equal(receipt.separateContexts, true) for (const asset of ['index.html', 'app.js', 'service.css']) { diff --git a/deploy/examples/business-registration/tests/receipt.test.mjs b/deploy/examples/business-registration/tests/receipt.test.mjs index 1cf7815a13..93fd9fedde 100644 --- a/deploy/examples/business-registration/tests/receipt.test.mjs +++ b/deploy/examples/business-registration/tests/receipt.test.mjs @@ -42,6 +42,7 @@ const casework = { test('baseline receipt pins the two registrar sessions and logout', () => { assertReceipt('breg', baseline) + assertReceipt('coordinator', baseline) assert.throws(() => assertReceipt('unknown', baseline)) for (const [key, value] of Object.entries({ distinctSubjects: false, diff --git a/deploy/examples/business-registration/tests/run-reference.sh b/deploy/examples/business-registration/tests/run-reference.sh index 08c0623260..f39b3b6b39 100644 --- a/deploy/examples/business-registration/tests/run-reference.sh +++ b/deploy/examples/business-registration/tests/run-reference.sh @@ -29,7 +29,7 @@ if [[ ${1:-} == --candidate ]]; then unset REFERENCE_TEST_CHROMIUM unset GH_TOKEN GITHUB_TOKEN GH_ENTERPRISE_TOKEN GITHUB_ENTERPRISE_TOKEN else - profile=${1:?Pass breg or casework} + profile=${1:?Pass breg, casework or coordinator} export REFERENCE_ARTIFACTS=${2:?Pass the absolute directory containing the CI-profile or release-profile binaries} playwright=${3:?Pass the absolute Playwright module path} yaml=${4:?Pass the absolute YAML module path} @@ -37,14 +37,18 @@ else [[ "$playwright" == /* && "$yaml" == /* ]] || refuse 'Pass absolute module paths.' fi case "$profile" in - breg | casework) ;; - *) refuse 'Choose breg or casework.' ;; + breg | casework | coordinator) ;; + *) refuse 'Choose breg, casework or coordinator.' ;; esac [[ "$REFERENCE_ARTIFACTS" == /* && "$receipt" == /* && ! -e "$receipt" && ! -L "$receipt" ]] || refuse 'Use an absolute input directory and a new absolute receipt path.' binaries=(rstack breg bregctl registry-session) if [[ "$profile" == casework ]]; then binaries+=(casework caseworkctl); fi +if [[ "$profile" == coordinator ]]; then + binaries+=(coordinatorctl) + if ! "$candidate"; then binaries+=(coordinator); fi +fi for bin in "${binaries[@]}"; do [[ -x "$REFERENCE_ARTIFACTS/$bin" ]] || refuse "Missing executable $bin." done @@ -74,6 +78,7 @@ image_id() { } declare -A verified_images=() +candidate_coordinator_image= export REFERENCE_SESSION_DIGEST if "$candidate"; then version=$(jq -er '.release.version' "$binding") @@ -84,6 +89,7 @@ if "$candidate"; then done image_names=(breg registry-session) if [[ "$profile" == casework ]]; then image_names+=(casework); fi + if [[ "$profile" == coordinator ]]; then image_names+=(coordinator); fi for name in "${image_names[@]}"; do ref=$(jq -er --arg name "$name" '.images[$name]' "$binding") verified_images[$name]=$(image_id "$name" "$ref") || @@ -92,12 +98,20 @@ if "$candidate"; then breg) export CANDIDATE_BREG_IMAGE="$ref" ;; registry-session) export CANDIDATE_SESSION_IMAGE="$ref" ;; casework) export CANDIDATE_CASEWORK_IMAGE="$ref" ;; + coordinator) + candidate_coordinator_image=$ref + export REFERENCE_COORDINATOR_REPOSITORY="${ref%@*}" + export REFERENCE_COORDINATOR_DIGEST="${ref##*@}" + ;; esac done REFERENCE_SESSION_DIGEST=${CANDIDATE_SESSION_IMAGE##*@} else # The local overlay runs the same shared CI-profile Session executable. REFERENCE_SESSION_DIGEST="sha256:$(printf '%064d' 0)" + if [[ "$profile" == coordinator ]]; then + export REFERENCE_COORDINATOR_DIGEST="$REFERENCE_SESSION_DIGEST" + fi fi scratch=$(realpath -- "$(mktemp -d)") @@ -115,6 +129,10 @@ rstack="$REFERENCE_ARTIFACTS/rstack" compose_files=("$recipe/compose.yaml") if ! "$candidate"; then compose_files+=("$recipe/compose.local.yaml"); fi if [[ "$profile" == casework ]]; then compose_files+=("$recipe/casework/compose.yaml"); fi +if [[ "$profile" == coordinator ]]; then + compose_files+=("$recipe/coordinator/compose.yaml") + if ! "$candidate"; then compose_files+=("$recipe/coordinator/compose.local.yaml"); fi +fi if "$candidate"; then export REFERENCE_HOST="$REFERENCE_HOST_CLIENT" export CANDIDATE_BREG_ADMIN_DIR="$REFERENCE_CONFIG/breg/admin" @@ -201,18 +219,22 @@ if "$candidate"; then # model may add only public, digest-pinned support images. model=$("${compose[@]}" --profile setup config --format json) jq -e --arg breg "$CANDIDATE_BREG_IMAGE" --arg session "$CANDIDATE_SESSION_IMAGE" \ - --arg profile "$profile" --arg casework "${CANDIDATE_CASEWORK_IMAGE:-}" ' + --arg profile "$profile" --arg casework "${CANDIDATE_CASEWORK_IMAGE:-}" \ + --arg coordinator "$candidate_coordinator_image" ' .services.breg.image == $breg and .services["breg-admin"].image == $breg and .services.session.image == $session and (if $profile == "casework" then .services.casework.image == $casework and .services["casework-admin"].image == $casework else (.services | has("casework") | not) end) and + (if $profile == "coordinator" then + .services.coordinator.image == $coordinator and .services["coordinator-admin"].image == $coordinator + else (.services | has("coordinator") | not) end) and ([.services[] | has("build") | not] | all) and ([.services[].image | test("@sha256:[a-f0-9]{64}$")] | all)' <<<"$model" >/dev/null image_refs=$(jq -er '.services[].image' <<<"$model" | sort -u) while IFS= read -r image; do if [[ "$image" != "$CANDIDATE_BREG_IMAGE" && "$image" != "$CANDIDATE_SESSION_IMAGE" && - "$image" != "${CANDIDATE_CASEWORK_IMAGE:-}" ]]; then + "$image" != "${CANDIDATE_CASEWORK_IMAGE:-}" && "$image" != "$candidate_coordinator_image" ]]; then docker pull --platform linux/amd64 "$image" fi done <<<"$image_refs" @@ -391,6 +413,19 @@ stage_runtime() { } stage_runtime breg if [[ "$profile" == casework ]]; then stage_runtime casework; fi +if [[ "$profile" == coordinator ]]; then + phase 'package and activate the synthetic Coordinator workflow' + install -d "$REFERENCE_CONFIG/coordinator" + "$REFERENCE_ARTIFACTS/coordinatorctl" --format json package \ + --project "$recipe/coordinator/workflow" --output "$REFERENCE_CONFIG/coordinator/package" >"$scratch/coordinator-package.json" + coordinator_digest=$(jq -er '.packageDigest | select(test("^sha256:[a-f0-9]{64}$"))' "$scratch/coordinator-package.json") + node "$recipe/coordinator/prepare.mjs" "$REFERENCE_CONFIG" "$coordinator_digest" + coordinator_admin=("${run[@]}" coordinator-admin --runtime-config /run/coordinator/runtime.yaml --posture production) + "${coordinator_admin[@]}" check --deny-warnings + "${coordinator_admin[@]}" provision --admin-url-file /run/coordinator/secrets/admin-database-url + "${coordinator_admin[@]}" apply + "${coordinator_admin[@]}" deployment-status +fi if ! "${up[@]}"; then "${compose[@]}" ps --all "${compose[@]}" logs --no-log-prefix issuer-ready gateway-check @@ -407,6 +442,16 @@ if "$candidate"; then done fi cmp "$REFERENCE_CONFIG/gateway/envoy.json" "$REFERENCE_CONFIG/gateway-checked/envoy.json" +if [[ "$profile" == coordinator ]]; then + phase 'read back an authenticated Coordinator completion' + timeout --kill-after=5s 90s "${run[@]}" --no-deps coordinator-proof >"$scratch/coordinator-runtime.json" + jq -es 'select(length == 1) | .[0] | + select(.workflow == "reference-coordinator" and .state == "finished" + and (.runId | test("^[0-9a-f]{8}(-[0-9a-f]{4}){3}-[0-9a-f]{12}$")) + and (.workflowRevision | test("^sha256:[0-9a-f]{64}$"))) | + {workflow_id:.workflow, workflow_revision:.workflowRevision, run_id:.runId, state}' \ + "$scratch/coordinator-runtime.json" >"$scratch/coordinator-receipt.json" +fi app_mapping=$("${compose[@]}" port edge 8080) || refuse 'Missing app edge mapping.' issuer_mapping=$("${compose[@]}" port edge 9443) || refuse 'Missing issuer edge mapping.' @@ -474,7 +519,7 @@ JS phase 'run browser proof' browser_command=(node "$recipe/tests/browser.mjs" "$playwright" "$REFERENCE_CONFIG" "$REFERENCE_CONFIG/browser-passwords" "$BUSINESS_BUNDLE" "$profile" "${compose[@]:1}") -if [[ "$profile" == breg ]] && ! "$candidate"; then +if [[ "$profile" != casework ]] && ! "$candidate"; then # Bound the browser phase within the reference-host step's 15-minute budget. browser_command=(timeout --kill-after=10s 180s "${browser_command[@]}") fi @@ -488,14 +533,27 @@ fi stop_browser_edge || refuse 'The browser edge did not finish cleanly.' node "$recipe/tests/receipt.mjs" "$profile" "$scratch/browser-receipt.json" "$REFERENCE_CONFIG/browser-authorization.jsonl" phase 'browser receipt validated' +coordinator_receipt=() +if [[ "$profile" == coordinator ]]; then + coordinator_receipt=(--slurpfile coordinator "$scratch/coordinator-receipt.json") +fi if "$candidate"; then + if [[ "$profile" == coordinator ]]; then + coordinator_receipt+=(--slurpfile coordinator_runtime "$scratch/coordinator-runtime.json") + fi phase 'assemble candidate receipt' gateway=$(sha256sum "$REFERENCE_CONFIG/gateway-checked/envoy.json" | cut -d' ' -f1) schema_receipt=$(sha256sum "$scratch/rehearsal/receipt.json" | cut -d' ' -f1) proof_path="$scratch/proof.json" jq --arg digest "$digest" --arg schema_receipt "$schema_receipt" --arg gateway "$gateway" \ - --arg bundle "$BUSINESS_BUNDLE_SHA256" --slurpfile browser "$scratch/browser-receipt.json" ' + --arg bundle "$BUSINESS_BUNDLE_SHA256" --slurpfile browser "$scratch/browser-receipt.json" "${coordinator_receipt[@]}" ' . + {package_digest:$digest, schema_test_receipt_sha256:$schema_receipt, - gateway_sha256:$gateway, preview_bundle_sha256:$bundle, browser:$browser[0]}' \ + gateway_sha256:$gateway, preview_bundle_sha256:$bundle, browser:$browser[0]} + | if .profile == "coordinator" then + . + {coordinator:$ARGS.named.coordinator[0], coordinator_runtime:$ARGS.named.coordinator_runtime[0]} + else . end' \ "$binding" >"$proof_path" +elif [[ "$profile" == coordinator ]]; then + proof_path="$scratch/proof.json" + jq "${coordinator_receipt[@]}" '. + {coordinator:$coordinator[0]}' "$scratch/browser-receipt.json" >"$proof_path" fi diff --git a/release/OPERATIONS.md b/release/OPERATIONS.md index 55ac944ceb..f4dfab7ebb 100644 --- a/release/OPERATIONS.md +++ b/release/OPERATIONS.md @@ -1143,6 +1143,13 @@ deployments** in that run. Add `--verbose-wait` to retain the raw `gh run watch` display when detailed live job output is useful. Omit either flag when another operator or monitor owns the corresponding wait. +Add `--coordinator-reference-host` to request the Coordinator proof alongside +the BReg and Casework reference host jobs. This option requires a Stack +candidate that ships both the Session and Coordinator images. The request sends +a JSON boolean and follows the same protected source, request ID, and run +correlation as an ordinary candidate. Use `--print-request` to inspect the +resolved dispatch command before submitting it. + The request is accepted only when `source_sha` is the exact protected-main workflow revision. Before dispatch, the CLI also requires that exact commit to have a conventional subject and a Git-parseable `Signed-off-by` trailer matching @@ -1201,8 +1208,12 @@ workflow then: package sealed from a separate production-posture schema test. The Casework browser checks that the same reviewer reads both products with one Session sign-in, verifies the two role refusals, and checks for browser Authorization - headers. Each job retains its checked receipt for two days. Promotion - requires a successful candidate workflow run. + headers. When requested, the Coordinator profile runs `coordinator.test.mjs` + from the exact staged source and uses the same attempt's sealed + `coordinatorctl` and private Coordinator image. It runs the BReg browser + journey and reads a synthetic Coordinator completion from the private + runtime with a fixture producer token. Each job retains its checked receipt + for two days. Promotion requires a successful candidate workflow run. ### Replay the candidate reference host locally @@ -1211,8 +1222,9 @@ from the exact successful run attempt, and an authenticated GitHub CLI with read access to its attestations. On a disposable Linux amd64 Docker host with Node.js 24 and noninteractive sudo, choose a new absolute staging directory. The host needs the Compose v2 plugin, Chromium's system libraries and unused -loopback ports 8443 and 9443. Set `PROFILE` to `breg` or `casework`. To replay -both, run one profile at a time with a fresh stage and receipt path for each. +loopback ports 8443 and 9443. Set `PROFILE` to `breg`, `casework`, or +`coordinator`. Run one profile at a time with a fresh stage and receipt path +for each. ```sh python3 release/scripts/candidate_host_inputs.py verify \ @@ -1228,7 +1240,11 @@ python3 release/scripts/candidate_host_inputs.py verify \ With read access to the private candidate packages, pull the exact references from `jq -er '.images[]' "$STAGE/inputs.json"` for `linux/amd64`. Then run the staged driver with no GitHub credentials in its -environment. +environment. For `coordinator`, first run the staged fixture test. + +```sh +node --test "$STAGE/source/deploy/examples/business-registration/tests/coordinator.test.mjs" +``` ```sh bash "$STAGE/source/release/scripts/candidate-host-smoke.sh" \ @@ -1243,6 +1259,25 @@ BReg package and gateway configuration to the selected profile's browser result. The Casework receipt also binds the Casework image and both Casework executables to the same manifest and candidate attempt. +For `coordinator`, verify the completed receipt against the authenticated stage. + +```sh +python3 release/scripts/candidate_host_inputs.py verify-coordinator-receipt \ + --stage "$STAGE" --receipt "$RECEIPT" +``` + +The verifier checks the staged `coordinatorctl` hash and uses its offline +`check --project` report to derive the workflow ID and semantic revision from +the staged source. The receipt's `coordinator` object records `workflow_id`, +`workflow_revision`, `run_id`, and `state`. They must agree with the +authenticated GET projection in `coordinator_runtime`, which records +`workflow`, `workflowRevision`, `runId`, `state`, `outcome`, `output`, +`uncertain`, and `restoreReviewRequired`. The expected completion is `finished` +with outcome `issuer-checked`, the fixture issuer as the only output field, +and both flags false. The top-level `package_digest` continues to identify the +BReg browser package. The receipt records the protected job's checks against +the attested candidate inputs. + ### Renew an image advisory fingerprint Treat a fingerprint failure as a stopped candidate, not as a mechanical digest diff --git a/release/scripts/candidate_host_inputs.py b/release/scripts/candidate_host_inputs.py index f12f5179c8..546f838d8e 100644 --- a/release/scripts/candidate_host_inputs.py +++ b/release/scripts/candidate_host_inputs.py @@ -5,6 +5,7 @@ import json import os from pathlib import Path +import re import shutil import subprocess import sys @@ -31,7 +32,9 @@ RECIPE = "deploy/examples/business-registration" PREVIEW = "products/platform/examples/service-previews/business-registration" LOCK_HELPER = "products/platform/scripts/prepare-service-preview-locks.mjs" -PROFILES = ("breg", "casework") +PROFILES = ("breg", "casework", "coordinator") +MAX_COORDINATOR_RECEIPT_BYTES = 256 * 1024 +RECEIPT_SHA256_FIELDS = {"schema_test_receipt_sha256", "gateway_sha256", "preview_bundle_sha256"} SOURCE_PATHS = ( RECIPE, PREVIEW, @@ -57,6 +60,9 @@ def host_inputs(manifest, profile): if profile == "casework": binaries += ("casework", "caseworkctl") image_names += ("casework",) + if profile == "coordinator": + binaries += ("coordinatorctl",) + image_names += ("coordinator",) paths = {binary: f"{binary}-v{version}-linux-amd64" for binary in binaries} paths["client.tgz"] = web_client images = {image["name"]: image for image in manifest["images"]} @@ -79,6 +85,113 @@ def require_digest_match(path, expected): raise CandidateError(f"candidate host input sha256 mismatch: {path.name}") +def check_coordinator_tool_abi(path): + with path.open("rb") as binary: + header = binary.read(20) + # ELF64, little-endian, current ELF version, and EM_X86_64. + if header[:7] != b"\x7fELF\x02\x01\x01" or header[18:20] != b"\x3e\x00": + raise CandidateError("candidate host requires a Linux amd64 coordinatorctl executable") + subprocess.run( + [str(ROOT / "release/scripts/check-glibc-floor.sh"), str(path)], + check=True, timeout=30, + ) + + +def receipt_object(pairs): + result = dict(pairs) + if len(result) != len(pairs): + raise CandidateError("candidate Coordinator receipt has duplicate fields") + return result + + +def expected_coordinator_workflow(stage, binding): + tool = stage / "coordinatorctl" + tool_digest = binding.get("assets", {}).get("coordinatorctl", {}).get("sha256") + require_digest_match(tool, tool_digest) + # The stage comes from git archive at the authenticated candidate source. + # Coordinator uses the same checked definition at authoring and at runtime. + project = stage / "source" / RECIPE / "coordinator/workflow" + report = json.loads(subprocess.check_output([ + str(tool), "--format", "json", "check", "--project", str(project), "--deny-warnings", + ], text=True, timeout=30, env={"LC_ALL": "C"}), object_pairs_hook=receipt_object) + if ( + not isinstance(report, dict) + or report.get("ok") is not True + or report.get("command") != "check" + or report.get("status") != "valid" + or not isinstance(report.get("workflow"), str) + or not re.fullmatch(r"[a-z][a-z0-9_-]{0,63}", report["workflow"]) + ): + raise CandidateError("sealed coordinatorctl did not report a valid reference workflow") + revision = require_digest(report.get("workflowRevision"), "expected Coordinator workflow revision") + return report["workflow"], revision + + +def verify_coordinator_receipt(stage, receipt): + """Check the bounded, recipe-validated proof before retaining it.""" + binding = read_json(stage / "inputs.json") + if not isinstance(binding, dict) or binding.get("profile") != "coordinator": + raise CandidateError("candidate Coordinator receipt requires a verified Coordinator stage") + if receipt.is_symlink() or not receipt.is_file(): + raise CandidateError("candidate Coordinator receipt must be a regular file") + with receipt.open("rb") as file: + data = file.read(MAX_COORDINATOR_RECEIPT_BYTES + 1) + if not data or len(data) > MAX_COORDINATOR_RECEIPT_BYTES: + raise CandidateError("candidate Coordinator receipt is empty or exceeds its size bound") + try: + proof = json.loads(data, object_pairs_hook=receipt_object) + except (ValueError, RecursionError) as exc: + raise CandidateError("candidate Coordinator receipt is invalid JSON") from exc + + fields = binding.keys() | RECEIPT_SHA256_FIELDS | { + "package_digest", "browser", "coordinator", "coordinator_runtime", + } + if not isinstance(proof, dict) or proof.keys() != fields: + raise CandidateError("candidate Coordinator receipt has unexpected fields") + # Keep JSON types exact, including the numeric run ID and attempt. + reported_binding = {key: proof[key] for key in binding} + if json.dumps(reported_binding, sort_keys=True) != json.dumps(binding, sort_keys=True): + raise CandidateError("candidate Coordinator receipt differs from the verified stage") + for field in sorted(RECEIPT_SHA256_FIELDS): + require_sha256(proof[field], field) + require_digest(proof["package_digest"], "package_digest") + browser = proof["browser"] + if not isinstance(browser, dict) or browser.get("noBrowserAuthorizationHeader") is not True: + raise CandidateError("candidate Coordinator receipt lacks checked browser evidence") + + result = proof["coordinator"] + result_fields = {"workflow_id", "workflow_revision", "run_id", "state"} + if not isinstance(result, dict) or result.keys() != result_fields: + raise CandidateError("candidate Coordinator receipt has unexpected workflow result fields") + run_id = result["run_id"] + if not isinstance(run_id, str) or re.fullmatch( + r"[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}", run_id + ) is None: + raise CandidateError("candidate Coordinator receipt has an invalid run identifier") + if result["state"] != "finished": + raise CandidateError("candidate Coordinator receipt requires a finished run") + workflow_id, workflow_revision = expected_coordinator_workflow(stage, binding) + if (result["workflow_id"], result["workflow_revision"]) != (workflow_id, workflow_revision): + raise CandidateError("candidate receipt differs from the expected Coordinator workflow identity or revision") + runtime = proof["coordinator_runtime"] + expected_runtime = { + "workflow": workflow_id, + "workflowRevision": workflow_revision, + "runId": run_id, + "state": "finished", + "outcome": "issuer-checked", + "output": {"issuer": "https://identity.reference.test:9443"}, + "uncertain": False, + "restoreReviewRequired": False, + } + if ( + runtime != expected_runtime + or runtime["uncertain"] is not False + or runtime["restoreReviewRequired"] is not False + ): + raise CandidateError("candidate Coordinator receipt differs from the expected authenticated runtime completion") + + def verify_and_stage(args): source = require_sha(args.source_sha, "candidate source SHA") git = ["git", "-C", str(ROOT)] @@ -149,6 +262,8 @@ def verify_and_stage(args): require_digest_match(destination, record["sha256"]) destination.chmod(0o400 if name == "client.tgz" else 0o500) staged[name] = {"asset": asset, "sha256": record["sha256"]} + if args.profile == "coordinator": + check_coordinator_tool_abi(args.output / "coordinatorctl") tree = args.output / "source" tree.mkdir() archive = Path(work) / "source.tar" @@ -179,10 +294,16 @@ def main(): verify.add_argument(f"--{option}", type=int, required=True) verify.add_argument("--profile", choices=PROFILES, required=True) verify.add_argument("--current-run", action="store_true") + receipt = commands.add_parser("verify-coordinator-receipt") + receipt.add_argument("--stage", type=Path, required=True) + receipt.add_argument("--receipt", type=Path, required=True) args = parser.parse_args() try: - verify_and_stage(args) - except (CandidateError, OSError, subprocess.CalledProcessError, json.JSONDecodeError) as exc: + if args.command == "verify": + verify_and_stage(args) + else: + verify_coordinator_receipt(args.stage, args.receipt) + except (CandidateError, OSError, subprocess.SubprocessError, json.JSONDecodeError) as exc: print(f"Candidate host verification failed: {exc}", file=sys.stderr) return 1 return 0 diff --git a/release/scripts/registry-release b/release/scripts/registry-release index 4565d23fcd..531bd5883f 100755 --- a/release/scripts/registry-release +++ b/release/scripts/registry-release @@ -3093,6 +3093,7 @@ def request_release_candidate( *, print_request: bool, unit: str = "stack", + coordinator_reference_host: bool = False, wait_for_ci: bool = False, wait_for_candidate: bool = False, verbose_wait: bool = False, @@ -3100,6 +3101,16 @@ def request_release_candidate( try: context = prepare_selected_context(repo, version, release_id, unit) selected_stack = context["selected"]["data"]["stack"] + if coordinator_reference_host: + parsed_version = release_roster.parse_version(version) + if ( + unit != "stack" + or not release_roster.session_image_in_release(parsed_version) + or not release_roster.coordinator_in_release(parsed_version) + ): + raise ReleasePlanError( + "Coordinator reference host requires a Stack candidate with Session and Coordinator images" + ) remote_default = refresh_protected_main(context["repo"], repository) resolved_source = resolve_commit(context["repo"], source_sha, "candidate source") resolved_default = resolve_commit( @@ -3173,6 +3184,8 @@ def request_release_candidate( ] if unit != "stack": command.extend(["-F", f"client_payload[release_unit]={unit}"]) + if coordinator_reference_host: + command.extend(["-F", "client_payload[coordinator_reference_host]=true"]) if print_request: print(" ".join(shlex.quote(part) for part in command)) else: @@ -4745,6 +4758,11 @@ def main() -> int: ) candidate_parser.add_argument("--repo", type=Path, default=ROOT) candidate_parser.add_argument("--print-request", action="store_true") + candidate_parser.add_argument( + "--coordinator-reference-host", + action="store_true", + help="also run the Coordinator Compose and browser proof on the sealed Stack candidate", + ) candidate_parser.add_argument( "--wait-for-ci", action="store_true", @@ -4882,6 +4900,7 @@ def main() -> int: args.repository, print_request=args.print_request, unit=args.unit, + coordinator_reference_host=args.coordinator_reference_host, wait_for_ci=args.wait_for_ci, wait_for_candidate=args.wait, verbose_wait=args.verbose_wait, diff --git a/release/scripts/test_candidate_host_smoke.py b/release/scripts/test_candidate_host_smoke.py index e42b787611..73e5993d8a 100644 --- a/release/scripts/test_candidate_host_smoke.py +++ b/release/scripts/test_candidate_host_smoke.py @@ -1,6 +1,7 @@ """Contract checks for the release-profile Compose proof.""" from argparse import Namespace +from copy import deepcopy import json import os from pathlib import Path @@ -66,10 +67,29 @@ def test_exact_host_candidates_and_asset_names(self): image for image in manifest["images"] if image["name"] != missing ]}, profile) with self.assertRaisesRegex(inputs.CandidateError, "profile"): - inputs.host_inputs(manifest, "coordinator") + inputs.host_inputs(manifest, "unknown") + + def test_coordinator_extends_only_the_breg_stage(self): + manifest = { + "release": {"version": "0.53.0"}, + "images": [ + {"name": name, "digest": DIGEST, "candidate_ref": candidate_ref(name)} + for name in ("breg", "registry-session", "coordinator") + ], + } + paths, refs = inputs.host_inputs(manifest, "breg") + self.assertEqual(inputs.host_inputs(manifest, "coordinator"), ( + {**paths, "coordinatorctl": "coordinatorctl-v0.53.0-linux-amd64"}, + {**refs, "coordinator": candidate_ref("coordinator")}, + )) + for missing in ("breg", "registry-session", "coordinator"): + with self.subTest(missing=missing), self.assertRaisesRegex(inputs.CandidateError, missing): + inputs.host_inputs({**manifest, "images": [ + image for image in manifest["images"] if image["name"] != missing + ]}, "coordinator") def test_image_selection_refuses_mutable_public_or_placeholder_refs(self): - for name in ("breg", "registry-session", "casework"): + for name in ("breg", "registry-session", "casework", "coordinator"): for digest, ref in ( (DIGEST, f"ghcr.io/registrystack/{name}-candidate:v0.52.0"), (DIGEST, f"ghcr.io/registrystack/{name}@{DIGEST}"), @@ -81,11 +101,149 @@ def test_image_selection_refuses_mutable_public_or_placeholder_refs(self): "images": [ {"name": image, "digest": DIGEST, "candidate_ref": candidate_ref(image)} if image != name else {"name": name, "digest": digest, "candidate_ref": ref} - for image in ("breg", "registry-session", "casework") + for image in ("breg", "registry-session", "casework", "coordinator") ], } with self.assertRaisesRegex(inputs.CandidateError, "real private digest"): - inputs.host_inputs(manifest, "casework") + inputs.host_inputs(manifest, "coordinator" if name == "coordinator" else "casework") + + def test_coordinator_tool_requires_amd64_elf_and_the_release_glibc_floor(self): + with tempfile.TemporaryDirectory() as work: + tool = Path(work) / "coordinatorctl" + ident = b"\x7fELF\x02\x01\x01" + bytes(9) + amd64 = b"\x03\x00\x3e\x00" + arm64 = b"\x03\x00\xb7\x00" + with mock.patch.object(inputs.subprocess, "run") as run: + for header in (ident + arm64, ident[:4] + b"\x01" + ident[5:] + amd64, b"wrong"): + tool.write_bytes(header) + with self.assertRaisesRegex(inputs.CandidateError, "Linux amd64"): + inputs.check_coordinator_tool_abi(tool) + run.assert_not_called() + tool.write_bytes(ident + amd64) + inputs.check_coordinator_tool_abi(tool) + self.assertEqual(run.call_args.args[0], [ + str(ROOT / "release/scripts/check-glibc-floor.sh"), str(tool), + ]) + self.assertTrue(run.call_args.kwargs["check"]) + self.assertIsNotNone(run.call_args.kwargs["timeout"]) + run.side_effect = subprocess.CalledProcessError(1, ["check-glibc-floor.sh"]) + with self.assertRaises(subprocess.CalledProcessError): + inputs.check_coordinator_tool_abi(tool) + + def test_coordinator_receipt_is_bounded_and_tied_to_the_sealed_stage(self): + with tempfile.TemporaryDirectory() as work: + stage = Path(work) + tool = stage / "coordinatorctl" + tool.write_bytes(b"fixture coordinatorctl") + project = stage / "source" / RECIPE.relative_to(ROOT) / "coordinator/workflow" + shutil.copytree(RECIPE / "coordinator/workflow", project) + binding = { + "profile": "coordinator", + "release": {"version": "0.53.0", "release_id": "beta", + "tag": "v0.53.0", "source_sha": "2" * 40}, + "workflow": {"path": inputs.WORKFLOW_PATH, "revision": "2" * 40, + "run_id": 1, "run_attempt": 1}, + "manifest_sha256": "3" * 64, + "bundle_sha256": "4" * 64, + "images": {name: candidate_ref(name) for name in ("breg", "registry-session", "coordinator")}, + "assets": {"coordinatorctl": { + "asset": "coordinatorctl-v0.53.0-linux-amd64", "sha256": inputs.sha256_file(tool), + }}, + } + (stage / "inputs.json").write_text(json.dumps(binding)) + receipt = stage / "receipt.json" + proof = { + **binding, + "package_digest": DIGEST, + "schema_test_receipt_sha256": "6" * 64, + "gateway_sha256": "7" * 64, + "preview_bundle_sha256": "8" * 64, + "browser": {"noBrowserAuthorizationHeader": True}, + "coordinator": { + "workflow_id": "reference-coordinator", + "workflow_revision": DIGEST, + "run_id": "34d7d1b3-edfb-4b3b-b57d-d9923ad14f6e", + "state": "finished", + }, + "coordinator_runtime": { + "workflow": "reference-coordinator", + "workflowRevision": DIGEST, + "runId": "34d7d1b3-edfb-4b3b-b57d-d9923ad14f6e", + "state": "finished", + "outcome": "issuer-checked", + "output": {"issuer": "https://identity.reference.test:9443"}, + "uncertain": False, + "restoreReviewRequired": False, + }, + } + check = self.enterContext(mock.patch.object(inputs.subprocess, "check_output", return_value=json.dumps({ + "ok": True, "command": "check", "status": "valid", "workflow": "reference-coordinator", + "workflowRevision": DIGEST, + }))) + receipt.write_text(json.dumps(proof)) + inputs.verify_coordinator_receipt(stage, receipt) + self.assertEqual(check.call_args.args[0], [ + str(tool), "--format", "json", "check", "--project", str(project), "--deny-warnings", + ]) + self.assertEqual(check.call_args.kwargs["env"], {"LC_ALL": "C"}) + for path, replacement in ( + (("profile",), "breg"), + (("release", "source_sha"), "9" * 40), + (("release", "version"), "0.52.0"), + (("workflow", "run_attempt"), 2), + (("workflow", "run_id"), True), + (("manifest_sha256",), "9" * 64), + (("bundle_sha256",), "9" * 64), + (("images", "coordinator"), candidate_ref("casework")), + (("images", "registry-session"), candidate_ref("casework")), + (("assets", "coordinatorctl"), {"asset": "coordinatorctl-v0.52.0-linux-amd64"}), + (("gateway_sha256",), "missing"), + (("browser", "noBrowserAuthorizationHeader"), False), + (("coordinator", "workflow_id"), "a" * 65), + (("coordinator", "workflow_revision"), "mutable"), + (("coordinator", "run_id"), "not-a-uuid"), + (("coordinator", "state"), "running"), + (("coordinator_runtime", "runId"), "51289567-e3f1-4746-abc9-56655cd1dc04"), + (("coordinator_runtime", "state"), "running"), + (("coordinator_runtime", "outcome"), "different-outcome"), + (("coordinator_runtime", "output"), {"issuer": "https://different.example"}), + (("coordinator_runtime", "uncertain"), 0), + (("coordinator_runtime", "restoreReviewRequired"), True), + ): + with self.subTest(path=path): + changed = deepcopy(proof) + parent = changed if len(path) == 1 else changed[path[0]] + parent[path[-1]] = replacement + receipt.write_text(json.dumps(changed)) + with self.assertRaises(inputs.CandidateError): + inputs.verify_coordinator_receipt(stage, receipt) + for summary_key, runtime_key, value in ( + ("workflow_id", "workflow", "other-workflow"), + ("workflow_revision", "workflowRevision", "sha256:" + "2" * 64), + ): + with self.subTest(summary_key=summary_key): + changed = deepcopy(proof) + changed["coordinator"][summary_key] = value + changed["coordinator_runtime"][runtime_key] = value + receipt.write_text(json.dumps(changed)) + with self.assertRaisesRegex(inputs.CandidateError, "expected Coordinator workflow"): + inputs.verify_coordinator_receipt(stage, receipt) + for invalid in ( + json.dumps({**proof, "coordinator": {**proof["coordinator"], "output": "extra"}}), + json.dumps({**proof, "coordinator_runtime": {**proof["coordinator_runtime"], "token": "unexpected"}}), + json.dumps({**proof, "extra": "extra"}), + json.dumps(proof)[:-1] + ', "profile": "coordinator"}', + json.dumps(proof) + " " * (256 * 1024), + ): + receipt.write_text(invalid) + with self.assertRaises(inputs.CandidateError): + inputs.verify_coordinator_receipt(stage, receipt) + receipt.write_text(json.dumps(proof)) + tool.write_bytes(b"different binary") + check.reset_mock() + with self.assertRaisesRegex(inputs.CandidateError, "sha256 mismatch"): + inputs.verify_coordinator_receipt(stage, receipt) + check.assert_not_called() def test_current_run_verification_rejects_external_context_before_gh(self): source = "2" * 40 @@ -126,6 +284,62 @@ def test_bundle_digest_is_verified_before_extraction(self): self.assertIn("--source-digest", call.args[0]) self.assertEqual(len(run.call_args_list), 3) + def test_coordinator_stage_checks_the_sealed_tool_before_writing_a_binding(self): + source = "2" * 40 + with tempfile.TemporaryDirectory() as work: + scratch = Path(work) + root = scratch / "bundle" + root.mkdir() + manifest_path = scratch / "manifest.json" + manifest_path.write_text("{}") + bundle = scratch / "bundle.tar.gz" + bundle.write_bytes(b"fixture") + manifest = { + "release": {"version": "0.53.0", "source_sha": source}, + "workflow": {"run_id": 1, "run_attempt": 1}, + "images": [ + {"name": name, "digest": DIGEST, "candidate_ref": candidate_ref(name)} + for name in ("breg", "registry-session", "coordinator") + ], + "bundle": {"name": bundle.name, "sha256": inputs.sha256_file(bundle), + "size": bundle.stat().st_size}, + "payloads": [], + } + paths, refs = inputs.host_inputs(manifest, "coordinator") + for name, asset in paths.items(): + (root / asset).write_text(name) + manifest["payloads"].append({ + "name": asset, "sha256": inputs.sha256_file(root / asset), + "kind": "client-package" if name == "client.tgz" else "binary", + }) + for valid in (False, True): + stage = scratch / str(valid) + args = Namespace( + source_sha=source, run_id=1, run_attempt=1, current_run=False, + manifest=manifest_path, bundle=bundle, output=stage, + version="0.53.0", release_id="beta", profile="coordinator", + ) + with ( + mock.patch.object(inputs.subprocess, "check_output", side_effect=[source, "{}"]), + mock.patch.object(inputs.subprocess, "run"), + mock.patch.object(inputs, "workflow_run_from_json"), + mock.patch.object(inputs, "validate_candidate_manifest", return_value=manifest), + mock.patch.object(inputs, "extract_candidate_bundle", return_value=root), + mock.patch.object(inputs, "check_coordinator_tool_abi") as abi, + ): + if valid: + inputs.verify_and_stage(args) + else: + abi.side_effect = inputs.CandidateError("invalid tool ABI") + with self.assertRaisesRegex(inputs.CandidateError, "invalid tool ABI"): + inputs.verify_and_stage(args) + abi.assert_called_once_with(stage / "coordinatorctl") + self.assertEqual((stage / "inputs.json").exists(), valid) + if valid: + binding = json.loads((stage / "inputs.json").read_text()) + self.assertEqual(binding["images"], refs) + self.assertEqual(binding["assets"]["coordinatorctl"]["asset"], paths["coordinatorctl"]) + def test_staged_bytes_reject_substitution(self): with tempfile.TemporaryDirectory() as work: scratch = Path(work) @@ -253,7 +467,9 @@ def test_workflow_is_same_run_and_read_only(self): "contents": "read", "packages": "read", }) self.assertEqual(job["strategy"], { - "fail-fast": False, "matrix": {"profile": ["breg", "casework"]}, + "fail-fast": False, "matrix": { + "profile": "${{ fromJSON(needs.validate.outputs.reference_host_profiles) }}", + }, }) self.assertNotIn("environment", job) self.assertIn("outputs.unit == 'stack'", job["if"]) @@ -270,6 +486,20 @@ def test_workflow_is_same_run_and_read_only(self): self.assertNotIn("env", steps[run]) self.assertIn('"${RUNNER_TEMP}/candidate-host-receipt.json" --with-deps', steps[run]["run"]) + self.assertLess(steps[run]["run"].index('"${stage}/coordinatorctl" --version'), + steps[run]["run"].index("candidate-host-smoke.sh")) + fixture = 'node --test "${stage}/source/deploy/examples/business-registration/tests/coordinator.test.mjs"' + coordinator_only = steps[run]["run"].split('if [[ "${profile}" == coordinator ]]; then')[1].split('\nfi')[0] + self.assertIn(fixture, coordinator_only) + self.assertLess(steps[run]["run"].index(fixture), steps[run]["run"].index("candidate-host-smoke.sh")) + self.assertLess(steps[run]["run"].index('sha256sum "${stage}/inputs.json"'), + steps[run]["run"].index('"${stage}/coordinatorctl" --version')) + self.assertLess(steps[run]["run"].index(".assets.coordinatorctl.sha256"), + steps[run]["run"].index('"${stage}/coordinatorctl" --version')) + self.assertLess(steps[run]["run"].index("candidate-host-smoke.sh"), + steps[run]["run"].index('sha256sum --check --strict --quiet <<<"${input_sha256}"')) + self.assertLess(steps[run]["run"].index('sha256sum --check --strict --quiet <<<"${input_sha256}"'), + steps[run]["run"].index("verify-coordinator-receipt")) self.assertEqual(steps[verify]["env"]["REFERENCE_PROFILE"], "${{ matrix.profile }}") self.assertIn('--profile "${REFERENCE_PROFILE}"', steps[verify]["run"]) self.assertIn('--run-id "${GITHUB_RUN_ID}" --run-attempt "${GITHUB_RUN_ATTEMPT}"', @@ -281,6 +511,40 @@ def test_workflow_is_same_run_and_read_only(self): self.assertEqual(steps[-1]["with"]["name"], "candidate-host-receipt-${{ github.run_id }}-${{ github.run_attempt }}-${{ matrix.profile }}") + def test_candidate_profiles_require_an_explicit_boolean_opt_in_and_both_images(self): + validate = yaml.safe_load(WORKFLOW.read_text())["jobs"]["validate"] + self.assertEqual(validate["outputs"]["reference_host_profiles"], + "${{ steps.request.outputs.reference_host_profiles }}") + step = next(step for step in validate["steps"] if step.get("id") == "request") + self.assertEqual(step["env"]["REFERENCE_HOST_COORDINATOR"], + "${{ toJSON(github.event.client_payload.coordinator_reference_host) }}") + script = step["run"] + selection = script[script.index("reference_host_profiles="):script.index('if [[ ! "${REQUEST_RELEASE_ID}"')] + for opt_in, unit, images, expected in ( + ("null", "stack", "breg registry-session coordinator", ["breg", "casework"]), + ("false", "stack", "breg registry-session coordinator", ["breg", "casework"]), + ("true", "stack", "breg registry-session coordinator", ["breg", "casework", "coordinator"]), + ("true", "stack", "breg registry-session coordinator-other", None), + ("true", "stack", "breg coordinator registry-session-other", None), + ("true", "discovery", "breg registry-session coordinator", None), + ('"true"', "stack", "breg registry-session coordinator", None), + ): + with self.subTest(opt_in=opt_in, unit=unit, images=images): + result = subprocess.run( + ["bash", "-eu", "-c", selection + '\nprintf "%s\\n" "$reference_host_profiles"'], + env={"REFERENCE_HOST_COORDINATOR": opt_in, "REQUEST_UNIT": unit, + "release_image_names": images}, + capture_output=True, text=True, + ) + if expected is None: + self.assertEqual(result.returncode, 1) + self.assertEqual(result.stdout, "") + self.assertIn("Coordinator reference host", result.stderr) + else: + self.assertEqual(result.returncode, 0, result.stderr) + self.assertEqual(result.stderr, "") + self.assertEqual(json.loads(result.stdout), expected) + def test_candidate_uses_the_shared_runner_and_receipt_validator(self): self.assertIn('tests/run-reference.sh" --candidate "$@"', DRIVER.read_text()) driver = RUNNER.read_text() @@ -290,6 +554,9 @@ def test_candidate_uses_the_shared_runner_and_receipt_validator(self): self.assertIn('fixture="$recipe/tests/prepare-inputs.mjs"', driver) self.assertIn('bash "$recipe/tests/cleanup-preview.sh"', driver) self.assertIn('node "$recipe/tests/receipt.mjs" "$profile"', driver) + self.assertIn('coordinator-proof >"$scratch/coordinator-runtime.json"', driver) + self.assertIn('--slurpfile coordinator_runtime "$scratch/coordinator-runtime.json"', driver) + self.assertIn('coordinator_runtime:$ARGS.named.coordinator_runtime[0]', driver) self.assertIn('run+=(--pull never)', driver) browser = (RECIPE / "tests/browser.mjs").read_text() self.assertIn("'--no-deps', '--pull', 'never', 'casework-seed'", browser) diff --git a/release/scripts/test_registry_release.py b/release/scripts/test_registry_release.py index 618f0b891c..157332b27e 100755 --- a/release/scripts/test_registry_release.py +++ b/release/scripts/test_registry_release.py @@ -389,6 +389,7 @@ def test_candidate_request_requires_current_source_workflow_revision( self.assertTrue( any(part.startswith("client_payload[request_id]=") for part in request) ) + self.assertNotIn("coordinator_reference_host", " ".join(request)) stale_source = "b" * 40 @@ -431,6 +432,49 @@ def resolve(_repo: Path, revision: str, _description: str) -> str: no_dispatch.assert_not_called() no_run_lookup.assert_not_called() + def test_candidate_request_opts_in_with_a_typed_field_and_keeps_run_identity(self) -> None: + registry_release = load_registry_release() + source = "a" * 40 + request_id = "b" * 32 + context = {"repo": ROOT, "selected": {"data": {"stack": {}}}} + repository = "registrystack/registry-stack" + with ( + mock.patch.object(registry_release, "prepare_selected_context", return_value=context), + mock.patch.object(registry_release, "refresh_protected_main", return_value=source), + mock.patch.object(registry_release, "resolve_commit", return_value=source), + mock.patch.object(registry_release, "validate_candidate_source_commit"), + mock.patch.object(registry_release.secrets, "token_hex", return_value=request_id), + mock.patch.object(registry_release, "run_checked") as dispatch, + mock.patch.object(registry_release, "wait_for_dispatched_run", return_value={ + "id": 42, "html_url": f"https://github.com/{repository}/actions/runs/42", + }) as lookup, + redirect_stdout(io.StringIO()), + redirect_stderr(io.StringIO()) as errors, + ): + self.assertEqual(0, registry_release.request_release_candidate( + ROOT, "0.53.0", "beta-example", source, "origin/main", repository, + print_request=False, coordinator_reference_host=True, + )) + command = dispatch.call_args.args[0] + self.assertEqual(command[-2:], ["-F", "client_payload[coordinator_reference_host]=true"]) + self.assertNotIn("client_payload[release_unit]=stack", command) + self.assertIn(f"client_payload[request_id]={request_id}", command) + lookup.assert_called_once_with( + repository, source_sha=source, request_id=request_id, + display_title=f"Release candidate beta-example v0.53.0 ({request_id})", + ) + for unit, version in (("discovery", "0.53.0"), ("stack", "0.51.0")): + with self.subTest(unit=unit, version=version): + dispatch.reset_mock() + lookup.reset_mock() + self.assertEqual(1, registry_release.request_release_candidate( + ROOT, version, "beta-example", source, "origin/main", repository, + print_request=False, unit=unit, coordinator_reference_host=True, + )) + dispatch.assert_not_called() + lookup.assert_not_called() + self.assertIn("requires a Stack candidate with Session and Coordinator images", errors.getvalue()) + def test_candidate_run_lookup_uses_unique_display_title(self) -> None: registry_release = load_registry_release() source = "a" * 40 diff --git a/release/scripts/test_registry_release_plans.py b/release/scripts/test_registry_release_plans.py index 0e479f25e9..7d124ce6ce 100644 --- a/release/scripts/test_registry_release_plans.py +++ b/release/scripts/test_registry_release_plans.py @@ -1439,6 +1439,7 @@ def test_finalize_and_capsule_commands_are_not_active(self) -> None: self.assertNotIn("--measurement-bootstrap", request_help.stdout) self.assertIn("--wait-for-ci", request_help.stdout) self.assertIn("--wait", request_help.stdout) + self.assertIn("--coordinator-reference-host", request_help.stdout) public_help = run("verify-public", "--help") self.assertEqual(0, public_help.returncode, public_help.stderr) self.assertIn("--tag", public_help.stdout)