From bd8a515973c1c3c95f42a2784feb4f8108194466 Mon Sep 17 00:00:00 2001 From: Dave Jong Date: Tue, 17 Nov 2026 22:08:59 +0100 Subject: [PATCH] Add a signed readiness gate for hosted deployments --- AGENT-INSTALL.md | 2 +- README.md | 22 ++++++++ field-test/hosted-startup.md | 5 +- scripts/framework-consumers.mjs | 87 ++++++++++++++++++++++++----- src/activation-check.ts | 14 +++-- src/cli.ts | 22 +++++++- src/protect/protect.d.ts | 2 + src/protect/rules/refresh.js | 4 +- src/protect/runtime.js | 9 ++- src/register.ts | 1 + src/verify-deploy.ts | 60 ++++++++++++++++++++ tests/protect/verify-deploy.test.ts | 86 ++++++++++++++++++++++++++++ 12 files changed, 289 insertions(+), 25 deletions(-) create mode 100644 src/verify-deploy.ts create mode 100644 tests/protect/verify-deploy.test.ts diff --git a/AGENT-INSTALL.md b/AGENT-INSTALL.md index c3ba057d..ffb0f4cf 100644 --- a/AGENT-INSTALL.md +++ b/AGENT-INSTALL.md @@ -8,7 +8,7 @@ This versioned reference ships inside `@patchstack/connect` and documents each s - **Source and releases:** MIT-licensed, source at https://github.com/patchstack/connect. Each version is published to npm from that repository's GitHub Actions workflow with an npm provenance attestation. - **How to check it yourself:** `npm view @patchstack/connect` shows the live registry metadata, including the repository and the attestation. After installing, `npm audit signatures` verifies the registry signatures and provenance attestations of the installed packages, this one included. - **What it does:** it sends the project's package names and versions to Patchstack for vulnerability matching, adds the Patchstack Connector widget to the site when asked (`setup --widget`, or `widget`), installs a runtime exploit guard (`protect`) in the server's request path, and adds scan steps to the install and build scripts. `setup` and the `prebuild` hook also upload a structural map of the server (routes, input names, the packages behind each sink, file:line) so protection rules can target the app's own parameters — never source text or environment values. Run on its own, `map` sends nothing unless you pass `--upload`. The [Command reference](#command-reference) lists every command, what it reads and writes, and what it sends. -- **Host-managed Node applications:** The optional `@patchstack/connect/register` preload starts the existing live guard for a site configured by the host. It can enable outbound screening. The host can mount its Express adapter for request and response screening. The `@patchstack/connect/register/fastify` pilot attaches the Fastify 5.12.1 adapter at startup without editing the app. The optional `prepare-deploy` command uploads the dependency manifest and structural input map for an existing site and writes a credential-free deployment metadata file for the preload. See the [host-managed Node setup](README.md#host-managed-node-applications). +- **Host-managed Node applications:** The optional `@patchstack/connect/register` preload starts the existing live guard for a site configured by the host. It can enable outbound screening. The host can mount its Express adapter for request and response screening. The `@patchstack/connect/register/fastify` pilot attaches the Fastify 5.12.1 adapter at startup without editing the app. The optional `prepare-deploy` command uploads the dependency manifest and structural input map for an existing site and writes a credential-free deployment metadata file for the preload. `verify-deploy` reads that file and waits for a signed readiness verdict at an explicitly configured running app URL. See the [host-managed Node setup](README.md#host-managed-node-applications). - **How setup ends:** run outside a terminal, as you run it, `setup` ends with `──── Summary ────` and a short message written for the person: what Patchstack found, the link to connect the site, what is left to do and the next step. **That summary is your final message.** Show it exactly as written, with every section. It ends by telling the person to say "done" once they have done the one thing it asks — usually connecting their account. When they say "done", run `npx @patchstack/connect next`, which checks where the project stands and says the next thing to do; show what it prints the same way. Do not add a list of the files `setup` changed: the setup output lists them, so answer from it if the person asks. Do not reword it, drop a section, or add your own: no recap, no account of the commands you ran. Add at most one line, after it, for something you did beyond `setup`. If the summary did not reach you (long output can be cut short), run `npx @patchstack/connect summary`: it prints the same summary again, from `.patchstack/summary.md`, where `setup` saves it. "The message you end on" below has the details, and "Commands for later" lists what to run when the person asks for more (`vulns` shows the vulnerabilities). ## Choose the project path first diff --git a/README.md b/README.md index ccc5d801..b504a11e 100644 --- a/README.md +++ b/README.md @@ -600,6 +600,28 @@ with the build you activate. For a custom Patchstack service, configure `PATCHSTACK_ENDPOINT` for the build and the corresponding `PATCHSTACK_PULSE_RULES_URL` for the server. +### Gate traffic on signed readiness + +With the candidate process running, set `PATCHSTACK_READINESS_URL` to a route +served by that candidate and run: + +```sh +patchstack-connect verify-deploy +``` + +The verifier reads the same deployment file and site credentials as the +preload. It polls the selected URL with signed OPTIONS requests and checks the +site, map identity, manifest checksum, and rules service's readiness verdict. +Zero applicable rules is a valid ready state. The verifier exits nonzero if the +candidate cannot prove readiness within 60 seconds. Use `--url` to select a +candidate explicitly, `--timeout ` to change the wait, or +`--require-block` when the candidate should already run in blocking mode. + +Point the verifier at the candidate before sending it production traffic. A +shared live URL could reach a different replica. Check each candidate the host +will admit. The verifier checks the chosen route and the guard's loaded +metadata. Use a separate enforcement test to prove specific rule behavior. + ## Programmatic API ```ts diff --git a/field-test/hosted-startup.md b/field-test/hosted-startup.md index 543c74fd..f28416dd 100644 --- a/field-test/hosted-startup.md +++ b/field-test/hosted-startup.md @@ -59,7 +59,10 @@ PS_FASTIFY_LIVE=1 npm run test:frameworks -- fastify-startup-cjs "$tarball" This uploads the fixture's package inventory and input map, starts Fastify in dry-run mode, and checks a signed activation response over loopback HTTP. It compares the uploaded build ID with a different local ID, and checks the -service's verdict in both cases. Use a sandbox site reserved for this fixture +service's verdict in both cases. The fixture uses `prepare-deploy` with the +runtime's configured artifact path, and runs `verify-deploy` before sending +ordinary fixture traffic. Readiness must pass on the matching candidate and +refuse the different deployment. Use a sandbox site reserved for this fixture because each run uploads an app map. Rule delivery and a matching build do not establish that this fixture has any generated rules to enforce. diff --git a/scripts/framework-consumers.mjs b/scripts/framework-consumers.mjs index 3ffda85d..faae1485 100644 --- a/scripts/framework-consumers.mjs +++ b/scripts/framework-consumers.mjs @@ -1,5 +1,5 @@ import assert from 'node:assert/strict'; -import { spawn, spawnSync } from 'node:child_process'; +import { execFile, spawn, spawnSync } from 'node:child_process'; import { once } from 'node:events'; import { createServer as createHttpServer } from 'node:http'; import { copyFileSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'; @@ -7,6 +7,7 @@ import { createServer } from 'node:net'; import { tmpdir } from 'node:os'; import { dirname, join, resolve } from 'node:path'; import { fileURLToPath } from 'node:url'; +import { promisify } from 'node:util'; import { ACTIVATION_HEADER, activationChallenge, verifyActivationResponse } from '../src/protect/activation.js'; const output = `({ label: body.label, sample: 'fixture-private' })`; @@ -221,8 +222,18 @@ function run(command, args, childEnv = env) { const child = spawnSync(command, args, { cwd, env: childEnv, encoding: 'utf8', timeout: 180_000 }); assert.equal(child.status, 0, [child.error?.message, child.stdout, child.stderr].join('\n').replaceAll(cwd, '')); } +const packageDir = 'node_modules/@patchstack/connect'; +const cli = join(packageDir, 'dist/cli.js'); +const deployment = 'host/deployment.json'; +const exec = promisify(execFile); const fixtureSite = '11111111-1111-4111-8111-111111111111'; +const fixtureCredentials = { PATCHSTACK_SITE_UUID: fixtureSite, PATCHSTACK_API_KEY: 'synthetic-key-1' }; let localRulesUrl; +let revalidatedFixtureRules = false; + +function runHostedCli(args, childEnv) { + return exec(process.execPath, [cli, ...args], { cwd, env: childEnv, timeout: 45_000 }); +} async function check(protectedApp, liveBuild) { const listener = createServer().listen(0, '127.0.0.1'); @@ -245,9 +256,9 @@ async function check(protectedApp, liveBuild) { }); } else if (protectedApp && localRulesUrl) { Object.assign(processEnv, { - PATCHSTACK_SITE_UUID: fixtureSite, - PATCHSTACK_API_KEY: 'synthetic-key-1', + ...fixtureCredentials, PATCHSTACK_PULSE_RULES_URL: localRulesUrl, + PATCHSTACK_DEPLOYMENT_FILE: deployment, PATCHSTACK_MODE: 'block', }); } @@ -262,6 +273,23 @@ async function check(protectedApp, liveBuild) { }); let scopedCheckCompleted = false; try { + if (protectedApp && fixture.preload) { + const expected = { + ...processEnv, + PATCHSTACK_DEPLOYMENT_FILE: deployment, + PATCHSTACK_READINESS_URL: processEnv.ORIGIN + '/fixture', + }; + if (liveBuild?.matched === false) { + await assert.rejects(runHostedCli(['verify-deploy', '--timeout', '2'], expected), /different deployment metadata/); + console.log('Readiness refused a different deployment.'); + } else { + const args = ['verify-deploy', '--timeout', '25']; + if (processEnv.PATCHSTACK_MODE === 'block') args.push('--require-block'); + const { stdout } = await runHostedCli(args, expected); + assert.match(stdout, /Deployment ready at the checked URL/); + console.log(stdout.trim()); + } + } let normal; for (let attempt = 0; attempt < (liveBuild ? 350 : 200) && app.exitCode === null; attempt++) { try { normal = await post('ordinary'); break; } catch { await new Promise(done => setTimeout(done, 100)); } @@ -287,7 +315,7 @@ async function check(protectedApp, liveBuild) { assert.equal(status.buildId, buildId); assert.equal(status.matched, liveBuild.matched); assert.equal(status.source.ok, true); - assert.equal(status.source.origin, 'api'); + assert.ok(['api', 'cache'].includes(status.source.origin)); console.log(reported); if (scopedRule) { assert.equal(status.mode, 'block'); @@ -350,14 +378,12 @@ try { run('npm', ['install', '--no-audit', '--no-fund', '--ignore-scripts']); if (fixture.build) run(process.execPath, fixture.build); await check(false); - const packageDir = 'node_modules/@patchstack/connect'; if (fixture.preload) { if (live) { mkdirSync(join(cwd, 'host'), { recursive: true }); copyFileSync(fileURLToPath(new URL('./fastify-startup-live.mjs', import.meta.url)), join(cwd, 'host/live.mjs')); } } else { - const cli = join(packageDir, 'dist/cli.js'); run(process.execPath, [cli, 'protect']); run(process.execPath, [cli, 'protect', '--check']); readFileSync(join(cwd, fixture.rules)); @@ -370,28 +396,60 @@ try { rule_v2: [{ parameter: 'response.header.x-fixture', match: { type: 'regex', value: '/fixture-stream-private/' } }] }, ], whitelists: [], whitelist_keys: {} }); if (fixture.preload && !live) { - mockRules = createHttpServer((incoming, reply) => { - incoming.resume(); - if (incoming.method === 'POST' && incoming.url === '/monitor/pulse/token') { + let reportedBuild; + let lookups = 0; + mockRules = createHttpServer(async (incoming, reply) => { + const path = incoming.url; + if (incoming.method === 'POST' && path === '/monitor/pulse/token') { + incoming.resume(); reply.writeHead(200, { 'content-type': 'application/json' }).end('{"access_token":"synthetic-token"}'); - } else if (incoming.method === 'GET' && incoming.url === `/monitor/pulse/rules/${fixtureSite}` - && incoming.headers.authorization === 'Bearer synthetic-token') { - reply.writeHead(200, { 'content-type': 'application/json' }).end(fixtureBundle); + return; + } + if (incoming.headers.authorization !== 'Bearer synthetic-token') { + incoming.resume(); + reply.writeHead(401).end(); + return; + } + if (incoming.method === 'POST' && path === `/monitor/pulse/manifest/${fixtureSite}`) { + incoming.resume(); + reply.writeHead(200, { 'content-type': 'application/json' }).end(JSON.stringify({ uuid: fixtureSite, stored: true })); + } else if (incoming.method === 'POST' && path === `/monitor/pulse/input-map/${fixtureSite}`) { + let map = ''; + for await (const chunk of incoming.setEncoding('utf8')) map += chunk; + reportedBuild = JSON.parse(map).build_id; + reply.writeHead(200, { 'content-type': 'application/json' }).end('{"result":"stored","revision":1}'); + } else if (incoming.method === 'GET' && path === `/monitor/pulse/rules/${fixtureSite}` + && reportedBuild && incoming.headers['x-patchstack-build'] === reportedBuild) { + const etag = '"fixture-bundle"'; + reply.setHeader('X-Patchstack-Build-Match', 'match'); + reply.setHeader('X-Patchstack-Build-ID', reportedBuild); + reply.setHeader('X-Patchstack-Map-Rules', ++lookups === 1 ? 'pending' : 'ready'); + reply.setHeader('ETag', etag); + if (incoming.headers['if-none-match'] === etag) { + revalidatedFixtureRules = true; + reply.writeHead(304).end(); + } else reply.writeHead(200, { 'content-type': 'application/json' }).end(fixtureBundle); } else { + incoming.resume(); reply.writeHead(404).end(); } }); mockRules.listen(0, '127.0.0.1'); await once(mockRules, 'listening'); localRulesUrl = `http://127.0.0.1:${mockRules.address().port}/monitor/pulse`; + mkdirSync(join(cwd, 'host'), { recursive: true }); + await runHostedCli(['prepare-deploy'], { + ...env, ...fixtureCredentials, PATCHSTACK_ENVIRONMENT: 'sandbox', PATCHSTACK_DEPLOYMENT_FILE: deployment, + PATCHSTACK_ENDPOINT: localRulesUrl + '/manifest', + }); } else if (!fixture.preload) { put(fixture.rules, fixtureBundle); } if (fixture.build) run(process.execPath, fixture.build); if (live) { - const deployment = 'host/deployment.json'; - run(process.execPath, [join(packageDir, 'dist/cli.js'), 'prepare-deploy', '--out', deployment], { + await runHostedCli(['prepare-deploy'], { ...env, PATCHSTACK_SITE_UUID: siteUuid, PATCHSTACK_API_KEY: apiKey, PATCHSTACK_ENVIRONMENT: 'sandbox', + PATCHSTACK_DEPLOYMENT_FILE: deployment, ...(localSaas ? { PATCHSTACK_ENDPOINT: localSaas + '/manifest' } : {}), }); await check(true, { file: deployment, matched: true, scopedOutcome: 'block' }); @@ -405,6 +463,7 @@ try { } } else { await check(true); + if (fixture.preload) assert.equal(revalidatedFixtureRules, true, 'Readiness must follow a conditional rules check.'); } if (fixture.preload) { for (const [file, source] of Object.entries(fixture.files)) assert.equal(readFileSync(join(cwd, file), 'utf8'), source); diff --git a/src/activation-check.ts b/src/activation-check.ts index e727582c..c5d83d61 100644 --- a/src/activation-check.ts +++ b/src/activation-check.ts @@ -8,6 +8,15 @@ import type { Config } from './types.js'; export interface ActivationResult { ok: boolean; message: string; summary?: string } +export async function probeActivation(target: string, secret: string, signal: AbortSignal): Promise | null> { + const challenge = await activationChallenge(secret, target); + const response = await fetch(target, { + method: 'OPTIONS', redirect: 'error', signal, headers: { [ACTIVATION_HEADER]: challenge }, + }); + const body = await readBoundedText(response, 16_384); + return response.ok ? verifyActivationResponse(secret, challenge, body, response.headers.get(ACTIVATION_HEADER)) : null; +} + /** Inspect only an explicitly selected running URL. Never discover ports, start, or restart an app. */ export async function checkActivation(url: string, config: Config, cwd: string, expectedBuildId?: string | null): Promise { const target = safeRemoteUrl(url); @@ -23,10 +32,7 @@ export async function checkActivation(url: string, config: Config, cwd: string, let timer: ReturnType | undefined; try { const work = async (): Promise => { - const challenge = await activationChallenge(secret, target); - const response = await fetch(target, {method:'OPTIONS',redirect:'error',signal:controller.signal,headers:{[ACTIVATION_HEADER]:challenge}}); - const body = await readBoundedText(response,16_384); - const status = response.ok ? await verifyActivationResponse(secret,challenge,body,response.headers.get(ACTIVATION_HEADER)) : null; + const status = await probeActivation(target, secret, controller.signal); if (!status || status.siteUuid !== config.siteUuid) return {ok:false,message:'The selected URL did not prove activation for this site. Check the server credential, guard integration and deployed package version.'}; if (!expectedBuildId || status.buildId !== expectedBuildId) return {ok:false,message:'The guard answered, but its loaded map is absent or different. Let the framework reload, or restart/rebuild/deploy, then check again.'}; const readiness = ['ready','pending'].includes(String(status.mapRules)) ? status.mapRules : 'unknown'; diff --git a/src/cli.ts b/src/cli.ts index 06be7247..5626c0e4 100644 --- a/src/cli.ts +++ b/src/cli.ts @@ -125,6 +125,7 @@ import { runDevelopment } from './dev-command.js'; import { checkActivation } from './activation-check.js'; import { syncSetupProtection } from './setup-sync.js'; import { prepareDeploy } from './prepare-deploy.js'; +import { verifyDeploy } from './verify-deploy.js'; import { isInstallOrBuildHook, isPreBundleBuildHook, undeliveredReportLines } from './build-hook.js'; import { applyBuildStamp, applyManifestChecksum } from './build-stamp.js'; import { detectStack, type StackDescriptor } from './stack.js'; @@ -190,6 +191,10 @@ Usage: patchstack-connect prepare-deploy [--out ] Report dependencies and upload the input map for a host-managed site. Write PATCHSTACK_DEPLOYMENT_FILE (or --out). Requires site credentials + patchstack-connect verify-deploy [--url ] Wait for signed readiness at PATCHSTACK_READINESS_URL + (or --url), using the deployment metadata. + --timeout defaults to 60. --require-block + also requires blocking mode patchstack-connect init Optional: pre-seed .patchstackrc.json with an existing site UUID patchstack-connect status [options] Show current configuration and whether the @@ -371,7 +376,7 @@ Examples: npx @patchstack/connect demo-guide node-serialize `; -const VALUE_FLAGS = new Set(['site-uuid', 'endpoint', 'dir', 'url', 'out', 'claim-token', 'host', 'runtime-url']); +const VALUE_FLAGS = new Set(['site-uuid', 'endpoint', 'dir', 'url', 'out', 'timeout', 'claim-token', 'host', 'runtime-url']); /** Set from `--verbose`. The default output is a plain status report; this adds the technical lines. */ let verbose = false; @@ -2385,6 +2390,21 @@ async function main(): Promise { } return prepareDeploy(out); } + if (args.command === 'verify-deploy') { + const url = getStringFlag(args.flags, 'url'); + const rawTimeout = getStringFlag(args.flags, 'timeout'); + const seconds = args.flags.has('timeout') ? Number(rawTimeout) : 60; + if ((args.flags.has('url') && !url?.trim()) || !Number.isInteger(seconds) || seconds < 1 || seconds > 300) { + console.error('verify-deploy expects an explicit --url if supplied, and --timeout between 1 and 300 seconds.'); + return 1; + } + const requireBlock = args.flags.get('require-block'); + if (requireBlock !== undefined && requireBlock !== true) { + console.error('--require-block takes no value.'); + return 1; + } + return verifyDeploy(url, seconds, requireBlock === true); + } if (!KNOWN_COMMANDS.has(args.command)) return runCommand(args); let code = 1; try { diff --git a/src/protect/protect.d.ts b/src/protect/protect.d.ts index 526d47a9..93ce9093 100644 --- a/src/protect/protect.d.ts +++ b/src/protect/protect.d.ts @@ -454,6 +454,8 @@ export interface CreateProtectionOptions { buildId?: string; /** Package manifest checksum for the running deployment report. */ manifestChecksum?: string; + /** Recheck build rule readiness more frequently during the first minute after startup. */ + startupRulesRetry?: boolean; /** * Take responsibility for `rules` you supply yourself, including any `build_scope` they carry. * diff --git a/src/protect/rules/refresh.js b/src/protect/rules/refresh.js index d8f1bfc4..37035633 100644 --- a/src/protect/rules/refresh.js +++ b/src/protect/rules/refresh.js @@ -15,7 +15,7 @@ import { notify } from '../notify.js'; const JITTER_FRACTION = 0.1; const MAX_BACKOFF_MULTIPLIER = 8; // cap consecutive-failure backoff at 8× the base interval -export function startRefresh(tick, { refreshMs, onError } = {}) { +export function startRefresh(tick, { refreshMs, startupInterval, onError } = {}) { let stopped = false; let failures = 0; let timer = null; @@ -24,7 +24,7 @@ export function startRefresh(tick, { refreshMs, onError } = {}) { if (stopped) return; const backoff = Math.min(2 ** failures, MAX_BACKOFF_MULTIPLIER); const jitter = 1 - Math.random() * JITTER_FRACTION; // shorten by up to 10% so clients don't align - const delay = refreshMs * backoff * jitter; + const delay = Math.min(refreshMs, startupInterval?.() ?? refreshMs) * backoff * jitter; timer = setTimeout(run, delay); timer?.unref?.(); }; diff --git a/src/protect/runtime.js b/src/protect/runtime.js index 933b84e1..c6b4c5d7 100644 --- a/src/protect/runtime.js +++ b/src/protect/runtime.js @@ -1807,7 +1807,9 @@ export async function createProtection(options = {}) { }, }, }); - const answerActivation = request => options.activationCheck === false ? null : activationResponse(request, pulseAuth, runtimeStatus); + const answerActivation = request => options.activationCheck === false ? null : activationResponse(request, pulseAuth, () => ({ + ...runtimeStatus(), manifestChecksum: options.manifestChecksum ?? null, + })); const withRequestSync = handler => (req, res, next) => { const screen = () => { const refresh = requestRefresher?.check(Boolean(req.headers?.[SYNC_HEADER])); @@ -2173,8 +2175,11 @@ export async function createProtection(options = {}) { protection.refreshHandler = () => makeRefreshHandler(refreshTick, refreshSecret); } + const startupDeadline = options.startupRulesRetry === true && localBuildId ? Date.now() + 60_000 : 0; + const startupInterval = () => Date.now() < startupDeadline + && (ruleSource.ok !== true || synchronization?.matched !== true || synchronization.mapRules !== 'ready') ? 5000 : undefined; const loop = refreshMs > 0 && live - ? startRefresh(refreshTick, { refreshMs, onError }) + ? startRefresh(refreshTick, { refreshMs, startupInterval, onError }) : null; // No loop to try again later, and the first resolution was not clean: retry until it is, rather than // serving stale or fallback rules for the life of the process. Only with a credential to ask with: the diff --git a/src/register.ts b/src/register.ts index 970237cc..de68b975 100644 --- a/src/register.ts +++ b/src/register.ts @@ -29,6 +29,7 @@ export const protection: Protection = await createProtection({ siteUuid: siteUuid.toLowerCase(), buildId: deployment?.buildId, manifestChecksum: deployment?.manifestChecksum, + startupRulesRetry: deployment !== undefined, apiKey, pulseAuth: apiKey, pulseRulesUrl, diff --git a/src/verify-deploy.ts b/src/verify-deploy.ts new file mode 100644 index 00000000..4804d7fc --- /dev/null +++ b/src/verify-deploy.ts @@ -0,0 +1,60 @@ +import { setTimeout as delay } from 'node:timers/promises'; + +import { probeActivation } from './activation-check.js'; +import { readHostedDeployment, type HostedDeployment } from './deployment-metadata.js'; +import { isCanonicalUuid, isCredential, safeRemoteUrl } from './endpoint-policy.js'; + +function waitingFor( + status: Record | null, + expected: HostedDeployment, + requireBlock: boolean, +): string | null { + if (!status || status.siteUuid !== expected.siteUuid) return 'The selected URL did not prove activation for this site.'; + if (status.buildId !== expected.buildId || status.manifestChecksum !== expected.manifestChecksum) { + return 'The guard is serving different deployment metadata.'; + } + const source = status.source as { ok?: boolean } | undefined; + if (source?.ok !== true || status.matched !== true) return 'The rules service has not confirmed this build.'; + if (status.mapRules !== 'ready') return 'The rules service has not marked this build ready.'; + if (status.mode !== 'block' && status.mode !== 'dry-run') return 'The guard did not report its enforcement mode.'; + if (requireBlock && (status.mode !== 'block' || status.devSync === true)) return 'The guard is not ready for blocking mode.'; + return null; +} + +export async function verifyDeploy(url: string | undefined, seconds: number, requireBlock: boolean): Promise { + const target = safeRemoteUrl(url ?? process.env.PATCHSTACK_READINESS_URL); + if (!target || new URL(target).hash) { + console.error('verify-deploy requires --url or PATCHSTACK_READINESS_URL with HTTPS or loopback HTTP, without credentials or a fragment.'); + return 1; + } + const siteUuid = process.env.PATCHSTACK_SITE_UUID; + const secret = process.env.PATCHSTACK_API_KEY; + const file = process.env.PATCHSTACK_DEPLOYMENT_FILE; + if (!file?.trim() || !isCanonicalUuid(siteUuid) || !isCredential(secret)) { + console.error('verify-deploy requires PATCHSTACK_DEPLOYMENT_FILE, PATCHSTACK_SITE_UUID and PATCHSTACK_API_KEY.'); + return 1; + } + const expected = readHostedDeployment(file, siteUuid.toLowerCase()); + const deadline = performance.now() + seconds * 1000; + let reason = 'The selected URL did not answer the readiness check.'; + for (;;) { + const remaining = Math.ceil(deadline - performance.now()); + if (remaining <= 0) break; + + let status: Record | null; + try { + status = await probeActivation(target, secret, AbortSignal.timeout(Math.min(remaining, 5000))); + } catch { + status = null; + } + const waiting = waitingFor(status, expected, requireBlock); + if (waiting === null) { + console.log(`Deployment ready at the checked URL (${status?.mode}).`); + return 0; + } + reason = waiting; + await delay(Math.max(0, Math.min(1000, deadline - performance.now()))); + } + console.error(`Deployment readiness timed out. ${reason}`); + return 1; +} diff --git a/tests/protect/verify-deploy.test.ts b/tests/protect/verify-deploy.test.ts new file mode 100644 index 00000000..ebc68398 --- /dev/null +++ b/tests/protect/verify-deploy.test.ts @@ -0,0 +1,86 @@ +import { mkdtempSync, rmSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; + +import { afterEach, beforeEach, expect, it, vi } from 'vitest'; + +import { activationResponse, ACTIVATION_HEADER } from '../../src/protect/activation.js'; +import { verifyDeploy } from '../../src/verify-deploy.js'; + +const siteUuid = '11111111-1111-4111-8111-111111111111'; +const secret = 'synthetic-key-1'; +const deployment = { siteUuid, buildId: 'a'.repeat(64), manifestChecksum: 'a1234567890c' }; +const ready = { ...deployment, source: { ok: true, origin: 'cache' }, matched: true, mapRules: 'ready', mode: 'block' }; +const url = 'https://candidate.example.test/fixture'; +let dir: string; + +beforeEach(() => { + dir = mkdtempSync(join(tmpdir(), 'connect-readiness-')); + const file = join(dir, 'deployment.json'); + writeFileSync(file, JSON.stringify(deployment)); + vi.stubEnv('PATCHSTACK_DEPLOYMENT_FILE', file); + vi.stubEnv('PATCHSTACK_SITE_UUID', siteUuid); + vi.stubEnv('PATCHSTACK_API_KEY', secret); + vi.stubEnv('PATCHSTACK_READINESS_URL', url); + vi.spyOn(console, 'log').mockImplementation(() => {}); + vi.spyOn(console, 'error').mockImplementation(() => {}); +}); + +afterEach(() => { + vi.unstubAllGlobals(); + vi.unstubAllEnvs(); + vi.restoreAllMocks(); + rmSync(dir, { recursive: true, force: true }); +}); + +function signed(getStatus: () => Record) { + return vi.fn(async (target: string, init: RequestInit) => { + expect(target).toBe(url); + expect(init.redirect).toBe('error'); + const headers = new Headers(init.headers); + expect([...headers.keys()]).toEqual([ACTIVATION_HEADER]); + expect(headers.get(ACTIVATION_HEADER)).not.toContain(secret); + return activationResponse(new Request(target, init), secret, getStatus); + }); +} + +it('waits for pending rules to become ready, even when the rules were revalidated', async () => { + let probes = 0; + vi.stubGlobal('fetch', signed(() => ({ ...ready, mapRules: ++probes === 1 ? 'pending' : 'ready' }))); + expect(await verifyDeploy(undefined, 3, true)).toBe(0); + expect(probes).toBe(2); +}); + +it.each([ + [{ siteUuid: '22222222-2222-4222-8222-222222222222' }, 'did not prove activation for this site'], + [{ buildId: 'b'.repeat(64) }, 'different deployment metadata'], + [{ manifestChecksum: 'b1234567890c' }, 'different deployment metadata'], + [{ source: { ok: false, origin: 'cache' } }, 'has not confirmed this build'], + [{ matched: false }, 'has not confirmed this build'], + [{ mapRules: 'unknown' }, 'has not marked this build ready'], + [{ mode: 'dry-run' }, 'not ready for blocking mode'], + [{ devSync: true }, 'not ready for blocking mode'], +])('keeps the gate closed for %j', async (override, reason) => { + vi.stubGlobal('fetch', signed(() => ({ ...ready, ...override }))); + expect(await verifyDeploy(undefined, 1, true)).toBe(1); + expect(console.error).toHaveBeenCalledWith(expect.stringContaining(reason)); +}); + +it('accepts a ready detect-only deployment when blocking is optional', async () => { + vi.stubGlobal('fetch', signed(() => ({ ...ready, rules: { request: 0, response: 0 }, mode: 'dry-run' }))); + expect(await verifyDeploy(undefined, 1, false)).toBe(0); +}); + +it('rejects an unsigned response carrying the same deployment metadata', async () => { + vi.stubGlobal('fetch', async () => Response.json(ready)); + expect(await verifyDeploy(undefined, 1, false)).toBe(1); + expect(console.error).toHaveBeenCalledWith(expect.stringContaining('did not prove activation')); +}); + +it('checks the artifact before contacting the candidate', async () => { + const fetch = vi.fn(); + vi.stubGlobal('fetch', fetch); + writeFileSync(join(dir, 'deployment.json'), 'null'); + await expect(verifyDeploy(undefined, 1, false)).rejects.toThrow('completed build'); + expect(fetch).not.toHaveBeenCalled(); +});