diff --git a/.github/scripts/wait-for-staging-deploys.ts b/.github/scripts/wait-for-staging-deploys.ts new file mode 100644 index 000000000..2a8e359e6 --- /dev/null +++ b/.github/scripts/wait-for-staging-deploys.ts @@ -0,0 +1,60 @@ +// Waits until no "Deploy Platform Staging" run is queued or running. The security smoke +// runs one long scan on staging: a platform deploy in the middle replaces the scanner's +// API under it, and the kitchen-sink deploy at the end of each staging run gets its own +// scan while the smoke has scanning on, which takes the only slot for the scan model. +import { setTimeout as delay } from 'node:timers/promises'; + +const WORKFLOW = 'platform-deploy-staging.yml'; +const POLL_MS = 30_000; +const LIMIT_MS = 60 * 60_000; + +const repository = process.env.GITHUB_REPOSITORY ?? ''; +const token = process.env.GITHUB_TOKEN; +const [owner, repo, ...rest] = repository.split('/'); +if (!owner || !repo || rest.length > 0 || !token) { + console.error('Set GITHUB_REPOSITORY (owner/name) and GITHUB_TOKEN with actions: read.'); + process.exit(1); +} + +async function activeRuns(): Promise> { + const response = await fetch( + `https://api.github.com/repos/${owner}/${repo}/actions/workflows/${WORKFLOW}/runs?per_page=30`, + { + headers: { + Accept: 'application/vnd.github+json', + Authorization: `Bearer ${token}`, + 'X-GitHub-Api-Version': '2026-03-10', + }, + redirect: 'error', + signal: AbortSignal.timeout(60_000), + }, + ); + if (!response.ok) { + throw new Error(`Reading ${WORKFLOW} runs failed (HTTP ${response.status}).`); + } + const body = (await response.json()) as { + workflow_runs?: Array<{ id: number; status: string; head_sha: string }>; + }; + if (!Array.isArray(body.workflow_runs)) { + throw new Error(`Reading ${WORKFLOW} runs returned no run list.`); + } + return body.workflow_runs + .filter((run) => run.status !== 'completed') + .map((run) => ({ id: run.id, status: run.status, sha: run.head_sha.slice(0, 9) })); +} + +const deadline = Date.now() + LIMIT_MS; +for (;;) { + const runs = await activeRuns(); + if (runs.length === 0) { + console.log('No staging deploy is running.'); + break; + } + const list = runs.map((run) => `${run.id} (${run.sha}, ${run.status})`).join(', '); + if (Date.now() >= deadline) { + console.error(`::error::Staging deploys still running after 60 minutes: ${list}.`); + process.exit(1); + } + console.log(`Waiting for staging deploys to finish: ${list}.`); + await delay(POLL_MS); +} diff --git a/.github/workflows/platform-deploy-staging.yml b/.github/workflows/platform-deploy-staging.yml index c98a464c0..f975a92f3 100644 --- a/.github/workflows/platform-deploy-staging.yml +++ b/.github/workflows/platform-deploy-staging.yml @@ -72,7 +72,10 @@ jobs: if: ${{ vars.VOID_PLATFORM_DEPLOY_ENABLED == 'true' && github.ref == 'refs/heads/main' }} needs: deploy uses: ./.github/workflows/platform-smoke-test.yml + # GitHub checks every called job's permissions, even skipped ones. The security + # audit job, which never runs from here, reads Actions runs. permissions: + actions: read contents: read # Pass only the smoke-test credentials. The called job resolves their values # from Staging; omitting this mapping leaves them empty on reusable runs. diff --git a/.github/workflows/platform-smoke-test.yml b/.github/workflows/platform-smoke-test.yml index 952106c85..337d4c0a2 100644 --- a/.github/workflows/platform-smoke-test.yml +++ b/.github/workflows/platform-smoke-test.yml @@ -128,8 +128,11 @@ jobs: concurrency: group: staging-security-audits-smoke cancel-in-progress: false - timeout-minutes: 210 + # Up to 60 minutes waiting for staging deploys, 30 for the policy apply call and + # 2 × timeoutMinutes + 15 (135 at the default 60) for the scan, plus build and deploy. + timeout-minutes: 270 permissions: + actions: read contents: read steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 @@ -139,6 +142,12 @@ jobs: with: cache: true node-version-file: .node-version + # A staging deploy during the scan replaces the platform under it, and its + # kitchen-sink deploy gets a scan that takes the scan model's only slot. + - name: Wait for staging deploys to finish + run: node .github/scripts/wait-for-staging-deploys.ts + env: + GITHUB_TOKEN: ${{ github.token }} - run: vp run build - name: Run security audit smoke test run: node platform/scripts/security-smoke-test.ts diff --git a/platform/packages/api/test/smoke-security-flow.test.ts b/platform/packages/api/test/smoke-security-flow.test.ts index de589e292..70336e218 100644 --- a/platform/packages/api/test/smoke-security-flow.test.ts +++ b/platform/packages/api/test/smoke-security-flow.test.ts @@ -12,6 +12,18 @@ import type { Api } from '../../../scripts/security-smoke-flow.ts'; import { prepareSecuritySmokeFixture } from '../../../scripts/security-smoke-test.ts'; const message = (error: unknown) => (error instanceof Error ? error.message : ''); +const ALL_SCANS = 'GET /operator/v1/security/scans?limit=100'; +const short = (call: string) => (call === ALL_SCANS ? 'GET all scans' : call); +/** A scan of another project, as the operator list shows it. */ +const other = (id: string, status: string, trigger = 'deploy') => ({ + ...scan(status), + id, + trigger, + projectId: `p-${id}`, + project: `app-${id}`, + model: '@cf/deepseek-ai/deepseek-v4.1-flash-1017', +}); +const cancel = (id: string) => `POST /operator/v1/security/scans/${id}/cancel {}`; type Handler = (body: Record) => unknown; const scan = (status: string) => ({ id: 'ss_1', @@ -63,6 +75,7 @@ function harness( 'GET /projects/p1/security/scans?limit=10': () => ({ scans: scans.shift() ?? [scan('running')], }), + 'GET /operator/v1/security/scans?limit=100': () => ({ scans: [] }), 'GET /projects/p1/security/findings?state=open&limit=100': () => ({ findings: [ { id: 'F-2', severity: 'low', verdict: 'lead', file: 'routes/api/hello.ts' }, @@ -71,8 +84,16 @@ function harness( }), }; const api: Api = { - async call(method: string, path: string, call: { body?: unknown } = {}) { + async call( + method: string, + path: string, + call: { body?: unknown; signal?: AbortSignal } = {}, + ) { const key = `${method} ${path}`; + if (call.signal?.aborted) { + // As createApi: a stopped call fails before it is sent. + throw new SmokeError(`${key} -> stopped`); + } const body = (call.body ?? {}) as Record; calls.push(call.body === undefined ? key : `${key} ${JSON.stringify(call.body)}`); return ((options.routes?.[key] ?? defaults[key])?.(body) ?? { ok: true }) as T; @@ -106,20 +127,28 @@ describe('security smoke flow', () => { it('turns an Off policy on for the run, finds the planted bug, then undoes everything', async () => { const { state, calls, log, run } = harness(); expect(await run()).toBe(0); - expect(calls.filter((call) => !call.startsWith('GET /projects/p1/security/scans'))).toEqual([ + expect( + calls.filter((call) => !call.startsWith('GET /projects/p1/security/scans')).map(short), + ).toEqual([ 'GET /operator/v1/session', 'GET /operator/v1/security/policy', 'POST /projects {"slug":"security-smoke-test"}', 'POST /operator/v1/projects/p1/security/policy {"override":"always"}', 'POST /operator/v1/projects/p1/security/budget {"monthlyUsd":5}', + 'GET all scans', 'POST /operator/v1/security/policy {"mode":"public","dryRun":true}', 'POST /operator/v1/security/policy {"mode":"public","expectedRevision":7}', 'GET /operator/v1/security/policy', 'deploy', + 'GET all scans', + 'GET all scans', 'GET /projects/p1/security/findings?state=open&limit=100', - 'DELETE /projects/p1', + // The scans to cancel are picked before Off. Off goes first, so no other deploy gets a + // scan while the project goes. + 'GET all scans', 'GET /operator/v1/security/policy', 'POST /operator/v1/security/policy {"mode":"disabled","expectedRevision":8}', + 'DELETE /projects/p1', 'logout', ]); expect(state.mode).toBe('disabled'); @@ -130,9 +159,197 @@ describe('security smoke flow', () => { const { state, calls, run } = harness({ mode: 'all' }); expect(await run()).toBe(0); expect(calls.some((call) => call.startsWith('POST /operator/v1/security/policy'))).toBe(false); + expect(calls).not.toContain(ALL_SCANS); expect(state.revision).toBe(7); }); + it('cancels only the scans of other projects that this run turned on, while its scan waits', async () => { + let deployed = false; + const { calls, log, run } = harness({ + onDeploy: () => (deployed = true), + routes: { + [ALL_SCANS]: () => ({ + scans: deployed + ? [ + other('ks', 'running'), + other('gate', 'queued', 'gate'), + other('backfill', 'queued', 'backfill'), + other('fallback', 'running', 'fallback'), + other('done', 'succeeded'), + other('old', 'running'), + ] + : [other('old', 'running')], + }), + }, + }); + expect(await run()).toBe(0); + expect(calls.filter((call) => call.includes('/cancel'))).toEqual([cancel('ks')]); + expect(log).toContain( + "Scan old of project app-old (deploy, @cf/deepseek-ai/deepseek-v4.1-flash-1017) is already running; this run's scan may wait for it.", + ); + expect(log).toContain( + 'Canceled Scan ks of project app-ks (deploy, @cf/deepseek-ai/deepseek-v4.1-flash-1017): it exists only because this run turned scanning on.', + ); + }); + + it('turns the policy Off, then cancels a scan that started after its own and before Off', async () => { + let checked = false; + const h = harness({ + routes: { + [ALL_SCANS]: () => ({ scans: checked ? [other('ks', 'running')] : [] }), + 'GET /projects/p1/security/findings?state=open&limit=100': () => { + checked = true; + return { + findings: [ + { id: 'F-1', severity: 'critical', verdict: 'confirmed', file: PLANTED_FILE }, + ], + }; + }, + }, + }); + expect(await h.run()).toBe(0); + const off = h.calls.indexOf( + 'POST /operator/v1/security/policy {"mode":"disabled","expectedRevision":8}', + ); + expect(off).toBeGreaterThan(0); + expect(h.calls.indexOf(cancel('ks'))).toBeGreaterThan(off); + expect(h.calls.indexOf('DELETE /projects/p1')).toBeGreaterThan(h.calls.indexOf(cancel('ks'))); + }); + + it('leaves alone a scan someone starts after this run turned the policy Off', async () => { + let checked = false; + let off = false; + const h = harness({ + routes: { + [ALL_SCANS]: () => ({ + scans: off + ? [other('ks', 'running'), other('late', 'running')] + : checked + ? [other('ks', 'running')] + : [], + }), + 'GET /projects/p1/security/findings?state=open&limit=100': () => { + checked = true; + return { + findings: [ + { id: 'F-1', severity: 'critical', verdict: 'confirmed', file: PLANTED_FILE }, + ], + }; + }, + 'POST /operator/v1/security/policy': (body) => { + if (body.dryRun) { + return { expectedRevision: h.state.revision }; + } + h.state.mode = String(body.mode); + h.state.revision++; + off = body.mode === 'disabled'; + return { ok: true }; + }, + }, + }); + expect(await h.run()).toBe(0); + expect(h.calls.filter((call) => call.includes('/cancel'))).toEqual([cancel('ks')]); + }); + + it('leaves other scans alone once someone else changed the policy', async () => { + let deployed = false; + const { calls, run } = harness({ + onDeploy: (state) => { + deployed = true; + state.extra = { defaultModel: '@cf/other' }; + }, + routes: { [ALL_SCANS]: () => ({ scans: deployed ? [other('ks', 'queued')] : [] }) }, + }); + expect(await run()).toBe(0); + expect(calls.some((call) => call.includes('/cancel'))).toBe(false); + }); + + it('still cancels the scans this run caused after a signal stopped it', async () => { + const stop = new AbortController(); + let deployed = false; + const { calls, run } = harness({ + signal: stop.signal, + onDeploy: () => { + deployed = true; + stop.abort(); + }, + routes: { [ALL_SCANS]: () => ({ scans: deployed ? [other('ks', 'running')] : [] }) }, + }); + expect(await run()).toBe(1); + expect(calls).toContain(cancel('ks')); + expect(calls.at(-1)).toBe('logout'); + }); + + it('cancels nothing at cleanup when someone else already turned the policy Off', async () => { + let deployed = false; + const { calls, log, run } = harness({ + onDeploy: (state) => { + deployed = true; + state.mode = 'disabled'; + }, + routes: { + [ALL_SCANS]: () => ({ scans: deployed ? [other('ks', 'running')] : [] }), + 'GET /projects/p1/security/scans?limit=10': () => ({ scans: [scan('succeeded')] }), + }, + }); + expect(await run()).toBe(0); + expect(log).toContain('Policy is already Off.'); + expect(calls.some((call) => call.includes('/cancel'))).toBe(false); + }); + + it('names the running scans in the manual steps when the policy restore fails', async () => { + let deployed = false; + const h = harness({ + onDeploy: () => (deployed = true), + routes: { + 'GET /operator/v1/security/policy': () => { + if (deployed) { + throw new ApiError('GET', '/operator/v1/security/policy', 503); + } + return { policy: { mode: h.state.mode, revision: h.state.revision } }; + }, + 'GET /projects/p1/security/scans?limit=10': () => ({ scans: [scan('succeeded')] }), + }, + }); + expect(await h.run()).toBe(1); + expect(h.log.at(-1)).toBe( + 'Manual cleanup needed on https://api.platform.example.test: void platform security policy disabled; cancel the running scans this run caused (void platform security scans)', + ); + }); + + it('takes a scan that ended meanwhile as done, and names a cancel that failed', async () => { + let checked = false; + const { calls, log, run } = harness({ + routes: { + [ALL_SCANS]: () => ({ + scans: checked ? [other('ended', 'running'), other('stuck', 'running')] : [], + }), + 'GET /projects/p1/security/findings?state=open&limit=100': () => { + checked = true; + return { + findings: [ + { id: 'F-1', severity: 'critical', verdict: 'confirmed', file: PLANTED_FILE }, + ], + }; + }, + 'POST /operator/v1/security/scans/ended/cancel': () => { + throw new ApiError('POST', '/operator/v1/security/scans/ended/cancel', 409); + }, + 'POST /operator/v1/security/scans/stuck/cancel': () => { + throw new ApiError('POST', '/operator/v1/security/scans/stuck/cancel', 502); + }, + }, + }); + expect(await run()).toBe(1); + expect(calls).toContain('DELETE /projects/p1'); + expect(log).toContain( + 'Could not cancel scan stuck: POST /operator/v1/security/scans/stuck/cancel -> HTTP 502', + ); + expect(log.at(-1)).toBe( + 'Manual cleanup needed on https://api.platform.example.test: void platform security cancel stuck', + ); + }); + it('stops before any write when the capability is off', async () => { const { calls, log, run } = harness({ routes: { 'GET /operator/v1/session': () => ({ capabilities: { securityAudits: false } }) }, diff --git a/platform/scripts/security-smoke-flow.ts b/platform/scripts/security-smoke-flow.ts index e518798c8..dcb828354 100644 --- a/platform/scripts/security-smoke-flow.ts +++ b/platform/scripts/security-smoke-flow.ts @@ -13,6 +13,16 @@ const OPERATOR_SESSION_LIFE_MS = 60 * 60 * 1000; // What the server gives. const OPERATOR_SESSION_MS = 40 * 60 * 1000; // Renew well before that. const POLL_MS = 15_000; const WAITING = new Set(['pending_input', 'queued', 'running']); +/** The newest scans of the whole platform. A run makes far fewer than this. */ +const ALL_SCANS = '/operator/v1/security/scans?limit=100'; +/** + * Scans the platform starts on its own while the policy is on. Made while this run had it + * on, they exist because of the run, and one running on the default `@cf` model holds the + * only slot for that model, so the run's own scan waits for it. Scans someone asked for are + * never canceled: gate, rescan, local and backfill, and fallback, which can follow a gate scan + * or a rescan. + */ +const POLICY_TRIGGERS = new Set(['deploy', 'recovery', 'exposure', 'sweep']); // Only these error codes are printed; any other response text stays out of the log. const KNOWN_CODES = new Set([ 'revision_conflict', @@ -195,6 +205,19 @@ type Scan = { createdAt: string; }; type Finding = { id: string; severity: string | null; verdict: string; file?: string | null }; +type PlatformScan = Scan & { projectId: string; project: string; model: string | null }; + +/** + * The scans this run turned on: any scan that was not waiting or running before the run + * turned the policy on. `settings` are the policy settings the run applied. + */ +type Window = { + projectId: string; + before: ReadonlySet; + settings: string; + canceled: Set; + reported: Set; +}; export type SmokeDeps = { api: Api; @@ -221,6 +244,7 @@ export async function runSecuritySmoke(d: SmokeDeps): Promise { let projectId: string | undefined; let createTried = false; let restore: Restore = { kind: 'none' }; + let window: Window | undefined; let ok = false; try { const session = await d.api.call<{ @@ -257,6 +281,12 @@ export async function runSecuritySmoke(d: SmokeDeps): Promise { await d.api.call('POST', `${base}/budget`, { ...op, body: { monthlyUsd: 5 } }); if (before.mode === 'disabled') { + const earlier = await listPlatformScans(d, d.signal); + for (const scan of earlier) { + if (scan.status === 'running') { + d.log(`${describeScan(scan)} is already running; this run's scan may wait for it.`); + } + } const preview = await d.api.call<{ expectedRevision: number }>( 'POST', '/operator/v1/security/policy', @@ -275,6 +305,13 @@ export async function runSecuritySmoke(d: SmokeDeps): Promise { op, ); restore = { kind: 'ours', settings: adminSettings(applied) }; + window = { + projectId, + before: new Set(earlier.map((scan) => scan.id)), + settings: restore.settings, + canceled: new Set(), + reported: new Set(), + }; d.log('Policy set to public for this run.'); } @@ -284,7 +321,7 @@ export async function runSecuritySmoke(d: SmokeDeps): Promise { throw new SmokeError(`void deploy exited with code ${code}.`); } const waitMinutes = (before.limits?.timeoutMinutes ?? 60) * 2 + 15; - const scan = await waitForScan(d, projectId, d.now() + waitMinutes * 60_000); + const scan = await waitForScan(d, projectId, d.now() + waitMinutes * 60_000, window); if (scan.status !== 'succeeded') { await logScanFailure(d, projectId, scan); throw new SmokeError( @@ -305,7 +342,94 @@ export async function runSecuritySmoke(d: SmokeDeps): Promise { } catch (error) { d.log(`Security smoke failed: ${d.signal?.aborted ? 'stopped by a signal' : describe(error)}`); } - return (await cleanUp(d, createTried ? (projectId ?? null) : undefined, restore)) && ok ? 0 : 1; + return (await cleanUp(d, createTried ? (projectId ?? null) : undefined, restore, window)) && ok + ? 0 + : 1; +} + +const describeScan = (scan: PlatformScan) => + `Scan ${scan.id} of project ${scan.project} (${scan.trigger}, ${scan.model ?? 'no model yet'})`; + +/** Cleanup passes no signal: it must run after a stop too. */ +async function listPlatformScans(d: SmokeDeps, signal: AbortSignal | undefined) { + const { scans } = await d.api.call<{ scans: Array }>('GET', ALL_SCANS, { + operator: true, + signal, + }); + return scans; +} + +/** + * The waiting or running scans of other projects that exist only because this run turned + * the policy on (see `POLICY_TRIGGERS`). Names any other running scan once. + */ +async function findWindowScans( + d: SmokeDeps, + w: Window, + signal: AbortSignal | undefined, +): Promise> { + const others = (await listPlatformScans(d, signal)).filter( + (scan) => + WAITING.has(scan.status) && scan.projectId !== w.projectId && !w.canceled.has(scan.id), + ); + const extra = others.filter( + (scan) => !w.before.has(scan.id) && POLICY_TRIGGERS.has(scan.trigger), + ); + for (const scan of others) { + if (scan.status === 'running' && !extra.includes(scan) && !w.reported.has(scan.id)) { + w.reported.add(scan.id); + d.log(`${describeScan(scan)} is running; this run's scan may wait for it.`); + } + } + return extra; +} + +/** + * While the run's own scan waits: cancels the scans this run caused, only while the policy + * still has the settings this run applied. After anyone else changes it, the scans may be + * wanted. + */ +async function stopWindowScans(d: SmokeDeps, w: Window) { + const extra = await findWindowScans(d, w, d.signal); + if (extra.length === 0) { + return; + } + const { policy } = await d.api.call<{ policy: Policy }>('GET', '/operator/v1/security/policy', { + operator: true, + signal: d.signal, + }); + if (policy.mode === 'public' && adminSettings(policy) === w.settings) { + await cancelScans(d, w, extra, d.signal); + } +} + +/** Resolves to the scans it could not cancel. A scan that has ended counts as done. */ +async function cancelScans( + d: SmokeDeps, + w: Window, + scans: ReadonlyArray, + signal: AbortSignal | undefined, +): Promise> { + const failed: Array = []; + for (const scan of scans) { + try { + await d.api.call( + 'POST', + `/operator/v1/security/scans/${encodeURIComponent(scan.id)}/cancel`, + { operator: true, signal, body: {} }, + ); + d.log(`Canceled ${describeScan(scan)}: it exists only because this run turned scanning on.`); + } catch (error) { + // 404 or 409: the scan or its project is already gone, or the scan has ended. + if (!(error instanceof ApiError) || (error.status !== 404 && error.status !== 409)) { + d.log(`Could not cancel scan ${scan.id}: ${describe(error)}`); + failed.push(scan.id); + continue; + } + } + w.canceled.add(scan.id); + } + return failed; } async function logScanFailure(d: SmokeDeps, projectId: string, scan: Scan) { @@ -335,7 +459,12 @@ async function logScanFailure(d: SmokeDeps, projectId: string, scan: Scan) { } } -async function waitForScan(d: SmokeDeps, projectId: string, deadline: number): Promise { +async function waitForScan( + d: SmokeDeps, + projectId: string, + deadline: number, + window: Window | undefined, +): Promise { let last = ''; for (;;) { const { scans } = await d.api.call<{ scans: Array }>( @@ -356,6 +485,15 @@ async function waitForScan(d: SmokeDeps, projectId: string, deadline: number): P if (d.now() >= deadline) { throw new SmokeError(`No finished deploy scan before the deadline (${last || 'no scan'}).`); } + // Until the run's own scan starts, nothing it caused may take its slot. + if (window && scan?.status !== 'running') { + try { + await stopWindowScans(d, window); + } catch (error) { + d.signal?.throwIfAborted(); + d.log(`Could not check other scans: ${describe(error)}`); + } + } await d.sleep(POLL_MS); } } @@ -364,9 +502,52 @@ async function waitForScan(d: SmokeDeps, projectId: string, deadline: number): P * Each step runs even when an earlier one fails, with no abort signal. `projectId` is null * when the create call failed (the server may still have made the project), undefined when * it was never tried. Resolves to false when a step failed. + * + * The policy goes Off first, so no other deploy gets a scan while the project is deleted. + * Off cancels queued scans only, so the scans this run caused are picked before it and + * canceled after it, only when this run set it Off: someone who changed the policy may want + * them, and a scan someone starts after Off is not this run's. */ -async function cleanUp(d: SmokeDeps, projectId: string | null | undefined, restore: Restore) { +async function cleanUp( + d: SmokeDeps, + projectId: string | null | undefined, + restore: Restore, + window: Window | undefined, +) { const manual: Array = []; + let off = false; + let picked: Array | null = null; + if (window) { + try { + picked = await findWindowScans(d, window, undefined); + } catch (error) { + d.log(`Cleanup: ${describe(error)}`); + } + } + if (restore.kind !== 'none') { + try { + const result = await restorePolicy(d, restore.kind === 'ours' ? restore.settings : undefined); + off = result === 'turned_off'; + if (result === 'unsure') { + manual.push('void platform security policy disabled (only if this run turned it on)'); + } + } catch (error) { + d.log(`Cleanup: ${describe(error)}`); + manual.push('void platform security policy disabled'); + if (window) { + manual.push('cancel the running scans this run caused (void platform security scans)'); + } + } + } + if (window && off) { + if (picked === null) { + manual.push('cancel the running scans this run caused (void platform security scans)'); + } else { + for (const id of await cancelScans(d, window, picked, undefined)) { + manual.push(`void platform security cancel ${id}`); + } + } + } if (projectId !== undefined) { try { const id = @@ -386,16 +567,6 @@ async function cleanUp(d: SmokeDeps, projectId: string | null | undefined, resto manual.push(`void project delete ${d.slug} --force`); } } - if (restore.kind !== 'none') { - try { - if (!(await restorePolicy(d, restore.kind === 'ours' ? restore.settings : undefined))) { - manual.push('void platform security policy disabled (only if this run turned it on)'); - } - } catch (error) { - d.log(`Cleanup: ${describe(error)}`); - manual.push('void platform security policy disabled'); - } - } try { await d.api.logout(); } catch (error) { @@ -411,9 +582,14 @@ async function cleanUp(d: SmokeDeps, projectId: string | null | undefined, resto /** * Turns the policy back Off, only while its admin settings are still the ones this run * applied. With no `settings` (the apply call failed) it changes nothing and resolves to - * false when the policy is public, so the caller prints the manual step. + * `unsure` when the policy is public, so the caller prints the manual step. `turned_off`: this + * run set it Off. `off`: someone else already did. `left`: someone else changed the policy, so + * it stays as they set it. */ -async function restorePolicy(d: SmokeDeps, settings: string | undefined): Promise { +async function restorePolicy( + d: SmokeDeps, + settings: string | undefined, +): Promise<'turned_off' | 'off' | 'left' | 'unsure'> { const op = { operator: true }; for (let attempt = 0; ; attempt++) { const { policy } = await d.api.call<{ policy: Policy }>( @@ -422,20 +598,20 @@ async function restorePolicy(d: SmokeDeps, settings: string | undefined): Promis op, ); if (policy.mode !== 'public') { - d.log( - policy.mode === 'disabled' - ? 'Policy is already Off.' - : `Policy is now ${policy.mode}; someone changed it, so it is left as is.`, - ); - return true; + if (policy.mode === 'disabled') { + d.log('Policy is already Off.'); + return 'off'; + } + d.log(`Policy is now ${policy.mode}; someone changed it, so it is left as is.`); + return 'left'; } if (settings === undefined) { d.log('Policy is public, but this run cannot tell whether it set that.'); - return false; + return 'unsure'; } if (adminSettings(policy) !== settings) { d.log('Policy settings changed during the run, so it is left as is.'); - return true; + return 'left'; } try { // The revision just inspected: a change since then fails with revision_conflict, @@ -445,7 +621,7 @@ async function restorePolicy(d: SmokeDeps, settings: string | undefined): Promis body: { mode: 'disabled', expectedRevision: policy.revision }, }); d.log('Policy set back to Off.'); - return true; + return 'turned_off'; } catch (error) { if (attempt > 0 || !(error instanceof ApiError) || error.code !== 'revision_conflict') { throw error; diff --git a/platform/scripts/security-smoke-test.md b/platform/scripts/security-smoke-test.md index c2fa16cff..2229f6325 100644 --- a/platform/scripts/security-smoke-test.md +++ b/platform/scripts/security-smoke-test.md @@ -40,13 +40,14 @@ script stops after reading the operator session and changes nothing. ## Changes and cleanup -| Step | Undo (always runs, each step on its own) | -| ------------------------------------------------- | ------------------------------------------------ | -| Mints an operator session | Logs it out | -| Creates the scratch project | Deletes it | -| Sets the project rule to `always`, ceiling `$5` | Gone with the project | -| Sets the policy mode Off to `public`, only if Off | Sets it back to Off, only if nobody changed it | -| Deploys the fixture | Gone with the project; the local copy is removed | +| Step | Undo (always runs, each step on its own) | +| ------------------------------------------------- | ------------------------------------------------------ | +| Mints an operator session | Logs it out | +| Creates the scratch project | Deletes it | +| Sets the project rule to `always`, ceiling `$5` | Gone with the project | +| Sets the policy mode Off to `public`, only if Off | Sets it back to Off, only if nobody changed it | +| Scans other projects while the mode is `public` | Cancels them (see below), after turning the policy Off | +| Deploys the fixture | Gone with the project; the local copy is removed | If the mode is already `public` or `all`, the policy is not touched. If someone changed any policy setting during the run, the script leaves the policy as is and says so. If the call that @@ -61,7 +62,12 @@ Known side effects: - Turning the mode on from Off sets up the installation scanner. Turning it Off again does not remove it. - While the mode is `public`, other projects on that platform that are not behind Zero Trust - are scanned on deploy too, and those scans cost money. + are scanned on deploy too. Only one scan runs at a time per `@cf` model, so such a scan can + hold up the smoke's own scan for as long as it runs. The script cancels the deploy, sweep, + exposure and recovery scans of other projects that start during its run, while its own scan + waits and again after it turns the policy Off. Gate, rescan, local, backfill and fallback scans + are left alone, and so is every scan once someone else changes the policy. It also prints any + other running scan its scan may wait for. - Turning the mode Off cancels every queued scan on the platform, not only the smoke's. - `void connect` saves the platform in your local CLI config. @@ -74,6 +80,11 @@ take several minutes. The scan wait ends at `2 × timeoutMinutes + 15` minutes ( the default 60). One scan of the small fixture usually costs well under the `$5` project ceiling. +The scan itself usually takes 8 to 15 minutes. Each `@cf` model call waits for the platform's +rate guard of 10 calls a minute per model, and a full first scan of the fixture makes about 90 +to 150 calls. In CI the job first waits for any running staging deploy, so the platform is not +replaced during the scan. + ## Manual cleanup If cleanup fails, the script exits with status 1 and prints `Manual cleanup needed`. Run only the steps it names, against the same platform: