Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
60 changes: 60 additions & 0 deletions .github/scripts/wait-for-staging-deploys.ts
Original file line number Diff line number Diff line change
@@ -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<Array<{ id: number; status: string; sha: string }>> {
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);
}
3 changes: 3 additions & 0 deletions .github/workflows/platform-deploy-staging.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
11 changes: 10 additions & 1 deletion .github/workflows/platform-smoke-test.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
Expand Down
223 changes: 220 additions & 3 deletions platform/packages/api/test/smoke-security-flow.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<string, unknown>) => unknown;
const scan = (status: string) => ({
id: 'ss_1',
Expand Down Expand Up @@ -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' },
Expand All @@ -71,8 +84,16 @@ function harness(
}),
};
const api: Api = {
async call<T>(method: string, path: string, call: { body?: unknown } = {}) {
async call<T>(
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<string, unknown>;
calls.push(call.body === undefined ? key : `${key} ${JSON.stringify(call.body)}`);
return ((options.routes?.[key] ?? defaults[key])?.(body) ?? { ok: true }) as T;
Expand Down Expand Up @@ -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');
Expand All @@ -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 } }) },
Expand Down
Loading