From efbdb982a5a8b4c5412b80fedb23539cc575adfd Mon Sep 17 00:00:00 2001 From: LongYinan Date: Mon, 30 Nov 2026 17:26:49 +0800 Subject: [PATCH 1/3] feat(platform): turn on security audits for Void Cloud - Hosted capability on, with the AI binding in all API envs. Scan still defaults to Off, so nothing scans until an admin turns it on. - The hourly copy sweep waits until the first probe set up the scanner. - Pin the Engine A/C scanner image digests. - Add a release smoke test for a test platform, with offline tests and docs. Co-Authored-By: Claude Opus 5.5 --- .../meta/design-docs/0095-security-audits.md | 75 ++-- platform/meta/operations.md | 35 +- platform/packages/api/src/capabilities.ts | 4 +- .../packages/api/src/security/maintenance.ts | 6 +- .../api/src/security/scanner-images.json | 4 +- .../test/integration/admin-dashboard.test.ts | 12 +- .../test/integration/admin-security.test.ts | 8 +- .../integration/api-project-security.test.ts | 3 +- .../integration/operator-security.test.ts | 3 +- .../test/integration/security-enqueue.test.ts | 13 +- .../api/test/integration/security-fixtures.ts | 5 + .../integration/security-local-check.test.ts | 5 +- .../integration/security-maintenance.test.ts | 54 +++ .../api/test/smoke-security-flow.test.ts | 331 ++++++++++++++ .../api/test/smoke-security-target.test.ts | 83 ++++ .../api/test/unit/admin-page-loading.test.ts | 8 +- .../api/test/unit/capabilities.test.ts | 2 +- .../api/test/unit/hosted-config.test.ts | 6 +- .../test/unit/security-scheduler-stub.test.ts | 3 +- platform/packages/api/wrangler.jsonc | 3 + .../security-smoke/routes/api/users/search.ts | 8 + platform/scripts/security-smoke-flow.ts | 418 ++++++++++++++++++ platform/scripts/security-smoke-test.md | 90 ++++ platform/scripts/security-smoke-test.ts | 139 ++++++ 24 files changed, 1247 insertions(+), 71 deletions(-) create mode 100644 platform/packages/api/test/integration/security-maintenance.test.ts create mode 100644 platform/packages/api/test/smoke-security-flow.test.ts create mode 100644 platform/packages/api/test/smoke-security-target.test.ts create mode 100644 platform/scripts/fixtures/security-smoke/routes/api/users/search.ts create mode 100644 platform/scripts/security-smoke-flow.ts create mode 100644 platform/scripts/security-smoke-test.md create mode 100644 platform/scripts/security-smoke-test.ts diff --git a/platform/meta/design-docs/0095-security-audits.md b/platform/meta/design-docs/0095-security-audits.md index 08019a30d3..6eec073750 100644 --- a/platform/meta/design-docs/0095-security-audits.md +++ b/platform/meta/design-docs/0095-security-audits.md @@ -460,26 +460,27 @@ Migration `0065_security_audits.sql`, 11 tables in `security/schema.ts`: unknown, and after 7 days they stay `NULL`. - A crash between an email send and the row update sends it twice on retry. Accepted. - Not built: admin finding detail and resolve forms (spec §13.1; use the CLI or operator API), - deploy `--json` `security` field (R4), the release smoke script. + deploy `--json` `security` field (R4). - Codex `bio policy`, `misalignment policy violation`, `invalid prompt` and `content_filter` end `failed (infrastructure)` and are retried (product call; none of them opens the gate). ## Live check status -| Check | Status | -| ---------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| S1 egress, S1b image copy | S1 results are not recorded here; its egress lock is in M6 and S2 / S3 / S11 check egress again. S1b ran with a small image only (R1); a full engine image copy is unmeasured | -| S2 / S3 lockdown (Engines A / C) | PASS locally through the gateway; live quality BLOCKED (scratch account had no Unified Billing credits) | -| S4 / S8 Engine B quality, cost, time | PASS on the default `@cf/deepseek-ai/deepseek-v4.1-flash-1017` (10/10, 0 false, 8/8 valid); glm-5.3 FAILS | -| S5 static confirmations | PASS (20/20 planted bugs confirmed with a trace) | -| S6 engine parity | Not run (needs Engines A / C live) | -| S7 inputs, S9 refusals, S11 red team | PASS locally after fixes (S7 26/26, S9 24/24, S11 160/160); S9 live refusal rates not run | -| S10 gateway | PASS for no bodies and no cache on REST; binding path and meter vs gateway not run (0094 check A pending) | -| S12 legal | Open for the user (checklist below) | -| S13 runtime copy | PASS (guard added); the M30 copy code itself is not run live | -| BYOK (M33) | Not run live; needs a real provider key. The first live probe with a saved key is the check | -| Engine A / C images | Digests stay `null` until the images are published at release (ghcr, then copied by the probe); until then probe check 5 keeps `openai/*` and `anthropic/*` unpickable | -| Release smoke (`security-smoke-test.ts`) | Not written; to do before release | +| Check | Status | +| --------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| S1 egress, S1b image copy | S1 results are not recorded here; its egress lock is in M6 and S2 / S3 / S11 check egress again. S1b ran with a small image only (R1); a full engine image copy is unmeasured | +| S2 / S3 lockdown (Engines A / C) | PASS locally through the gateway; live quality BLOCKED (scratch account had no Unified Billing credits) | +| S4 / S8 Engine B quality, cost, time | PASS on the default `@cf/deepseek-ai/deepseek-v4.1-flash-1017` (10/10, 0 false, 8/8 valid); glm-5.3 FAILS | +| S5 static confirmations | PASS (20/20 planted bugs confirmed with a trace) | +| S6 engine parity | Not run (needs Engines A / C live) | +| S7 inputs, S9 refusals, S11 red team | PASS locally after fixes (S7 26/26, S9 24/24, S11 160/160); S9 live refusal rates not run | +| S10 gateway | PASS for no bodies and no cache on REST; binding path and meter vs gateway not run (0094 check A pending) | +| S12 legal | Open for the user (checklist below) | +| S13 runtime copy | PASS (guard added); the M30 copy code itself is not run live | +| BYOK (M33) | Not run live; needs a real provider key. The first live probe with a saved key is the check | +| Engine A / C images | Published 2026-11-30 from main `556e0dd47` (workflow run 46373075151); both digests pinned in `scanner-images.json`. The first probe copies them into the operator registry; a full-size copy is still unmeasured (S1b) | +| Hosted (Void Cloud) | Capability on, with the AI binding in every API environment; Scan defaults to Off until an admin sets it on the Security page | +| Release smoke (`platform/scripts/security-smoke-test.ts`) | Offline-tested; the first live run on staging is a release step (`platform/meta/operations.md`) | ## Phase 0 spike conclusions @@ -649,28 +650,28 @@ Not decided here. Each needs a written answer before MVP. Items that need a user call are marked **(user)**. -| # | Item | Plan | -| --- | ------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| R1 | **(user)** Image source. A `durable_object` container app only runs `registry.cloudflare.com//…` images. | Engine B uses the managed image plus the streamed runner. Engines A/C: the probe copies a digest-pinned public image from `ghcr.io/voidzero-dev/void-security-scanner-engine-{a,c}` (option A). Pins stay `null` until the user agrees. | -| R2 | One PR vs spec "DO migration one release before the feature". **Decided: single PR.** | The class and its `security-audits-v1` tag ship with the feature, idle while off. A Worker rollback cannot cross that release; roll forward. | -| R3 | **(user)** All three phases in one PR. | Very large review; the user chose one PR. | -| R4 | Deploy `--json` does not exist, so spec "deploy result gains `security`" has nothing to attach to. | Not built. | -| R5 | **(user)** Skill upstream repo URL for "security-audit-skill @ c1c8a8c" is not in the spec or repo. | Prompts and report schema are Void's own until the skill is vendored. | -| R6 | **(user)** Sonnet 5.5 price is missing; the meter needs a price for every model. | Listed but not pickable (`price: null`) until a price is filled in. | -| R7 | **(user)** Legal (S12). | A/C models stay unpickable until S12 is OK; `@cf` + Engine B ship first. | -| R8 | Compensate `post_routing_recovery` writes `live` outside any transaction. | Enqueue there in its own short tx, logged on failure. Gap accepted. | -| R9 | Codex SDK cannot pass the lockdown flags. | Wrapper script via `codexPathOverride`, version checked by the drift test. | -| R10 | REST `/ai/v1/*` needs an AI permission and `cf-aig-gateway-id`; binding calls may ignore the payload-off header (0094 check A). | `@cf` on the binding, third party on REST; probe check 5 names a missing permission; `credentials.md` has the row. | -| R11 | Uninstall keeps platform Workers unless `--purge-resources`; the PRD says uninstall removes the scanner. | Uninstall always deletes the scanner Worker, gate, apps and copied images, found by name and ownership marker. R2 data follows the bucket rule. | -| R12 | Input build runs in the API Worker; large T3 inputs may hit CPU limits. | Modules are read one at a time; S7/S8 stayed in limits. | -| R13 | Local check findings would break reopen and gate rules. | Separate short-lived result (I12). | -| R14 | Does BYOK spend count toward caps? | Yes, metered and counted. | -| R15 | Per-plan caps in `PlanLimits` need the exact key set; the two-release rule cannot fit one PR. | Separate settings key `plans:security-caps` (0094 precedent). | -| R16 | Paging: spec asks for cursors; operator API uses page/limit. | Operator routes keep page/limit; project routes use a cursor. | -| R17 | Old CLI on `void platform upgrade` drops the flag. | Manifest v7 when on (old CLIs refuse). | -| R18 | Cron fast tier is missing on some self-hosted installs. | All security jobs in the hourly tier. | -| R19 | Admin shell has no banner or badge slot. | New shared page data through `renderAdminPage` and fate renders. | -| R20 | Model ids and prices may change before release. | One list in `@void/platform/security-models`, updated per release. | +| # | Item | Plan | +| --- | ------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| R1 | **(user)** Image source. A `durable_object` container app only runs `registry.cloudflare.com//…` images. | Engine B uses the managed image plus the streamed runner. Engines A/C: the probe copies a digest-pinned public image from `ghcr.io/voidzero-dev/void-security-scanner-engine-{a,c}` (option A). Pinned to the images published from `556e0dd47` (2026-11-30). | +| R2 | One PR vs spec "DO migration one release before the feature". **Decided: single PR.** | The class and its `security-audits-v1` tag ship with the feature, idle while off. A Worker rollback cannot cross that release; roll forward. | +| R3 | **(user)** All three phases in one PR. | Very large review; the user chose one PR. | +| R4 | Deploy `--json` does not exist, so spec "deploy result gains `security`" has nothing to attach to. | Not built. | +| R5 | **(user)** Skill upstream repo URL for "security-audit-skill @ c1c8a8c" is not in the spec or repo. | Prompts and report schema are Void's own until the skill is vendored. | +| R6 | **(user)** Sonnet 5.5 price is missing; the meter needs a price for every model. | Listed but not pickable (`price: null`) until a price is filled in. | +| R7 | **(user)** Legal (S12). | A/C models stay unpickable until S12 is OK; `@cf` + Engine B ship first. | +| R8 | Compensate `post_routing_recovery` writes `live` outside any transaction. | Enqueue there in its own short tx, logged on failure. Gap accepted. | +| R9 | Codex SDK cannot pass the lockdown flags. | Wrapper script via `codexPathOverride`, version checked by the drift test. | +| R10 | REST `/ai/v1/*` needs an AI permission and `cf-aig-gateway-id`; binding calls may ignore the payload-off header (0094 check A). | `@cf` on the binding, third party on REST; probe check 5 names a missing permission; `credentials.md` has the row. | +| R11 | Uninstall keeps platform Workers unless `--purge-resources`; the PRD says uninstall removes the scanner. | Uninstall always deletes the scanner Worker, gate, apps and copied images, found by name and ownership marker. R2 data follows the bucket rule. | +| R12 | Input build runs in the API Worker; large T3 inputs may hit CPU limits. | Modules are read one at a time; S7/S8 stayed in limits. | +| R13 | Local check findings would break reopen and gate rules. | Separate short-lived result (I12). | +| R14 | Does BYOK spend count toward caps? | Yes, metered and counted. | +| R15 | Per-plan caps in `PlanLimits` need the exact key set; the two-release rule cannot fit one PR. | Separate settings key `plans:security-caps` (0094 precedent). | +| R16 | Paging: spec asks for cursors; operator API uses page/limit. | Operator routes keep page/limit; project routes use a cursor. | +| R17 | Old CLI on `void platform upgrade` drops the flag. | Manifest v7 when on (old CLIs refuse). | +| R18 | Cron fast tier is missing on some self-hosted installs. | All security jobs in the hourly tier. | +| R19 | Admin shell has no banner or badge slot. | New shared page data through `renderAdminPage` and fate renders. | +| R20 | Model ids and prices may change before release. | One list in `@void/platform/security-models`, updated per release. | Hard or impossible as written in the PRD (flagged, not silently changed): R1, R2, R4, R8, R15, and the `/internal/security-scans/*` HTTP routes (replaced by RPC with the same diff --git a/platform/meta/operations.md b/platform/meta/operations.md index f95aee60b4..77a397f2cc 100644 --- a/platform/meta/operations.md +++ b/platform/meta/operations.md @@ -32,12 +32,13 @@ The `deploy` and `deploy:staging` scripts in `platform/package.json` target thes ### GitHub Actions -| Workflow | Purpose | -| ----------------------------- | ------------------------------------------------------------ | -| `platform-ci.yml` | Source validation and database schema compatibility checks | -| `platform-deploy.yml` | Production deployment from `prod` | -| `platform-deploy-staging.yml` | Staging deployment from `main` | -| `platform-smoke-test.yml` | Deploy and exercise a disposable kitchen-sink app in staging | +| Workflow | Purpose | +| -------------------------------------- | ----------------------------------------------------------------- | +| `platform-ci.yml` | Source validation and database schema compatibility checks | +| `platform-deploy.yml` | Production deployment from `prod` | +| `platform-deploy-staging.yml` | Staging deployment from `main` | +| `platform-smoke-test.yml` | Deploy and exercise a disposable kitchen-sink app in staging | +| `platform-security-scanner-images.yml` | Publish the Engine A / C security scanner images to ghcr (manual) | These deployment and smoke-test workflows target Void Cloud, from `prod` for production or `main` for staging, with `VOID_PLATFORM_DEPLOY_ENABLED=true`. They use the `Prod` and `Staging` GitHub environments. Restrict those environments to the same refs and appropriate reviewers, and keep deployment credentials in environment secrets. Forks use their own source-runtime release workflow. @@ -45,6 +46,12 @@ Both deploy workflows serialize deployments without cancelling an active rollout Hosted API and email gateway deploys report the release version from `packages/platform/package.json` as `PLATFORM_VERSION`. The `void` CLI refuses platforms older than its minimum platform version, so release in this order: advance `prod` and wait for the production deployment to succeed, then push the release tag that publishes the npm packages. +When `platform/packages/security-scanner` changes, also before advancing `prod`: + +1. Run "Publish Security Scanner Images" with `gh workflow run platform-security-scanner-images.yml --ref main`. +2. Commit the two digests from the run summary to `platform/packages/api/src/security/scanner-images.json`. +3. After staging deploys that commit, run the security smoke test against staging: `node platform/scripts/security-smoke-test.ts` (see [its README](../scripts/security-smoke-test.md)). + Consult the workflow files for their current inputs. Store credentials in the selected GitHub environment and the deployment owner's secret manager. Keep secret-manager locations, account access assignments and credential-issuance @@ -148,6 +155,22 @@ openssl pkcs8 -topk8 -nocrypt -in github-app-pkcs1.pem -out github-app-pkcs8.pem Container builds use the configured `BuildManager` or `BuildManagerLarge` class for the project's plan. GitHub Actions builds run in the repository's Actions environment and authenticate through `/auth/github-oidc`. Follow build logs with `void platform build logs --follow`. +## Security audits on Void Cloud + +Hosted has the `securityAudits` capability on. Scan defaults to Off; an admin sets it on the admin Security page. The first move away from Off runs the probe and creates the scanner (controller Worker, gate, copy namespace, container apps, image copies). This can take a few minutes; the page waits for it. + +The runtime `CF_API_TOKEN` needs: + +| Permission | Used for | +| ------------------------------------------------------------------------- | --------------------------------------------------------------------------------------- | +| Account → Containers → Edit, Account → Cloudchamber → Edit | Container apps, image preparation, registry credentials for the Engine A / C image copy | +| Account → Workers Scripts → Edit | Controller Worker, copy sandbox, dispatch namespace, gate and runtime copy scripts | +| Account → D1 → Edit, Workers KV Storage → Edit, Workers R2 Storage → Edit | Runtime copy stores, the live D1 schema read, and the hourly copy sweep | +| Account → Workers AI → Read | `openai/*` and `anthropic/*` calls through AI Gateway (`/ai/v1`) | +| Account → Account Analytics → Read | Gateway cost of ended scans (GraphQL) | + +`@cf/*` models use the API Worker's `AI` binding. Engines A and C (`anthropic/*`, `openai/*`) also need Unified Billing credits on the account or saved BYOK keys. The pull request comment needs the GitHub App permission described in [GitHub Deployment Integration](#github-deployment-integration). + ## Email The dedicated email gateway receives inbound mail and dispatches bounded requests to tenant handlers. The proxy handles outbound sends and receipt verification. The API owns zone connections, exact domain assignments, policy, quota reservations, and durable operation and delivery records in PostgreSQL. diff --git a/platform/packages/api/src/capabilities.ts b/platform/packages/api/src/capabilities.ts index 39ce1c70ce..06643881a5 100644 --- a/platform/packages/api/src/capabilities.ts +++ b/platform/packages/api/src/capabilities.ts @@ -12,8 +12,8 @@ const HOSTED_CAPABILITIES: PlatformCapabilities = { googleOAuth: true, managedBuilds: true, sandbox: true, - // Off until hosted turns it on in wrangler.jsonc (AI binding) and here. - securityAudits: false, + // The admin Security page turns scanning on (Scan defaults to Off). + securityAudits: true, }; const CAPABILITY_NAMES = Object.keys(HOSTED_CAPABILITIES) as Array; diff --git a/platform/packages/api/src/security/maintenance.ts b/platform/packages/api/src/security/maintenance.ts index 4f606bfdd7..591957e53f 100644 --- a/platform/packages/api/src/security/maintenance.ts +++ b/platform/packages/api/src/security/maintenance.ts @@ -151,7 +151,11 @@ export async function runSecurityMaintenance( releaseStrandedSecurityScanReserves(db), ); // After the reaper, so a copy of a scan it just ended goes in the same run. - const copiesReaped = await step('runtime copies', 0, () => deps.reapCopies()); + // A copy needs the scanner, which only the probe sets up and records as the entitlement. + // Before the first probe (hosted with Scan never turned on) skip the Cloudflare listing. + const copiesReaped = await step('runtime copies', 0, () => + policy.entitlement ? deps.reapCopies() : Promise.resolve(0), + ); // Ended scans keep their cost row while the policy is Off too (Scans screen, spec §16). const gatewayCosts = await step('gateway cost', 0, () => deps.gatewayCosts(now)); // Email rows wait for the alarm whatever the policy says: a lost poke is retried here. diff --git a/platform/packages/api/src/security/scanner-images.json b/platform/packages/api/src/security/scanner-images.json index c86999a3ea..0101aa5fe7 100644 --- a/platform/packages/api/src/security/scanner-images.json +++ b/platform/packages/api/src/security/scanner-images.json @@ -1,10 +1,10 @@ { "agent_sdk": { "repository": "ghcr.io/voidzero-dev/void-security-scanner-engine-a", - "digest": null + "digest": "sha256:1a8de2bbcc745fb68b91d20b2c2fbef2cff001b83e0208911932997574eb6cbb" }, "codex_sdk": { "repository": "ghcr.io/voidzero-dev/void-security-scanner-engine-c", - "digest": null + "digest": "sha256:363b46158a2becba2c53243e16af655d43f2205342227ba122d03167dc58e1fc" } } diff --git a/platform/packages/api/test/integration/admin-dashboard.test.ts b/platform/packages/api/test/integration/admin-dashboard.test.ts index 144b9f0a17..c59fd8affe 100644 --- a/platform/packages/api/test/integration/admin-dashboard.test.ts +++ b/platform/packages/api/test/integration/admin-dashboard.test.ts @@ -1388,9 +1388,11 @@ describe('GET /admin/ (dashboard)', () => { heading.textContent?.startsWith('Builds ('), )!.parentElement!; const zeroTrust = document.getElementById('zero-trust')!; + // Security audits are on in the hosted test env: its section sits in between. + const security = document.getElementById('security')!; const team = document.getElementById('team')!; const ownership = document.getElementById('owner-transfer')!; - const sections = [builds, zeroTrust, team, ownership]; + const sections = [builds, zeroTrust, security, team, ownership]; return sections.slice(1).map((section, index) => { const previous = sections[index].getBoundingClientRect(); return section.getBoundingClientRect().top - previous.bottom; @@ -1410,11 +1412,11 @@ describe('GET /admin/ (dashboard)', () => { const configure = (await zeroTrust .getByRole('link', { name: 'Configure Zero Trust' }) .boundingBox())!; - const teamHeading = (await page - .locator('#team') - .getByRole('heading', { name: 'Team members (1)' }) + const nextHeading = (await page + .locator('#security') + .getByRole('heading', { name: 'Security' }) .boundingBox())!; - expect(teamHeading.y - (configure.y + configure.height)).toBeCloseTo(32, 0); + expect(nextHeading.y - (configure.y + configure.height)).toBeCloseTo(32, 0); expect(configure.width).toBeLessThan((await zeroTrust.boundingBox())!.width); const teamTables = page.locator('.void-admin-team-table-scroll'); expect(await teamTables.count()).toBe(2); diff --git a/platform/packages/api/test/integration/admin-security.test.ts b/platform/packages/api/test/integration/admin-security.test.ts index fac57dea23..b0d3700b51 100644 --- a/platform/packages/api/test/integration/admin-security.test.ts +++ b/platform/packages/api/test/integration/admin-security.test.ts @@ -23,6 +23,7 @@ import { liveProject, saveSecurityPolicy, securityBindings, + securityOff, storedSecurityPolicy, } from './security-fixtures.ts'; import { askPublic, setupGate } from './security-gate-fixtures.ts'; @@ -91,10 +92,11 @@ async function readPolicy(): Promise { describe('admin security pages', () => { it('capability off: shows the install command, hides the nav item, refuses every write (I13)', async () => { const { project } = await liveProject(env); - expect(text(await (await get('/admin/security', env)).text())).toContain( + const offEnv = securityOff(env); + expect(text(await (await get('/admin/security', offEnv)).text())).toContain( 'void platform upgrade --security-audits', ); - expect(text(await (await get('/admin/users', env)).text())).not.toContain('/admin/security'); + expect(text(await (await get('/admin/users', offEnv)).text())).not.toContain('/admin/security'); for (const path of [ '/admin/security/policy', '/admin/security/budget', @@ -102,7 +104,7 @@ describe('admin security pages', () => { `/admin/projects/${project.id}/security/model`, `/admin/projects/${project.id}/security/rescan`, ]) { - expect([path, (await post(path, {}, env)).status]).toEqual([path, 501]); + expect([path, (await post(path, {}, offEnv)).status]).toEqual([path, 501]); } expect(await env.db.select().from(operatorEvents)).toEqual([]); }); diff --git a/platform/packages/api/test/integration/api-project-security.test.ts b/platform/packages/api/test/integration/api-project-security.test.ts index 9d9493fe9d..3827f1251d 100644 --- a/platform/packages/api/test/integration/api-project-security.test.ts +++ b/platform/packages/api/test/integration/api-project-security.test.ts @@ -15,6 +15,7 @@ import { insertSecurityFinding, projectWithRoles, saveSecurityPolicy, + securityOff, securityOn, } from './security-fixtures.ts'; import { @@ -170,7 +171,7 @@ describe('project security routes', () => { body, bindings, }); - expect((await put({ model: '@cf/zai-org/glm-5.3' }, env)).status).toBe(501); + expect((await put({ model: '@cf/zai-org/glm-5.3' }, securityOff(env))).status).toBe(501); expect(await env.db.select().from(projectSecuritySettings)).toEqual([]); const needsNotice = await put({ model: FOREIGN }); diff --git a/platform/packages/api/test/integration/operator-security.test.ts b/platform/packages/api/test/integration/operator-security.test.ts index 8dc05b589a..1dd920ba92 100644 --- a/platform/packages/api/test/integration/operator-security.test.ts +++ b/platform/packages/api/test/integration/operator-security.test.ts @@ -32,6 +32,7 @@ import { liveProject, saveSecurityPolicy, securityBindings, + securityOff, } from './security-fixtures.ts'; import { askPublic, setupGate } from './security-gate-fixtures.ts'; @@ -97,7 +98,7 @@ describe('operator security routes', () => { ).toBe(409); const written = await call('/security/budget', { body }); expect(written.body).toMatchObject({ ok: true, revision: 5 }); - expect((await call('/security/budget', { body, bindings: env })).status).toBe(501); + expect((await call('/security/budget', { body, bindings: securityOff(env) })).status).toBe(501); }); it('resolves and reopens a finding as the installation admin, with a preview first', async () => { diff --git a/platform/packages/api/test/integration/security-enqueue.test.ts b/platform/packages/api/test/integration/security-enqueue.test.ts index 6e25f0d598..bf22824009 100644 --- a/platform/packages/api/test/integration/security-enqueue.test.ts +++ b/platform/packages/api/test/integration/security-enqueue.test.ts @@ -31,7 +31,12 @@ import { teardownEnv, } from './helpers.ts'; import type { TestEnv } from './helpers.ts'; -import { saveSecurityPolicy, securityBindings, seedProtectedProject } from './security-fixtures.ts'; +import { + saveSecurityPolicy, + securityBindings, + securityOff, + seedProtectedProject, +} from './security-fixtures.ts'; let env: TestEnv; let onEnv: TestEnv; @@ -165,7 +170,9 @@ describe('enqueue in the go-live transaction (I1)', () => { await savePolicy(kind === 'policy' ? 'disabled' : 'all'); const { project } = await setup(); const deployment = await createTestDeployment(env.db, project.id); - expect(await enqueue(project.id, deployment.id, kind === 'off' ? env : onEnv)).toBeNull(); + expect( + await enqueue(project.id, deployment.id, kind === 'off' ? securityOff(env) : onEnv), + ).toBeNull(); expect(await scans(project.id)).toEqual([]); }); @@ -291,7 +298,7 @@ describe('real deploys', () => { it('nothing changes with the capability off (I13)', async () => { await savePolicy('all'); - const { project, operation } = await deployQueued(env); + const { project, operation } = await deployQueued(securityOff(env)); expect(operation).toMatchObject({ inputs_deleted: true }); expect(await scans(project.id)).toEqual([]); expect(pokes).toBe(0); diff --git a/platform/packages/api/test/integration/security-fixtures.ts b/platform/packages/api/test/integration/security-fixtures.ts index 2f48703da3..0ea951060a 100644 --- a/platform/packages/api/test/integration/security-fixtures.ts +++ b/platform/packages/api/test/integration/security-fixtures.ts @@ -36,6 +36,11 @@ export function securityOn(env: TestEnv, capabilities: Record = }; } +/** The bindings with the security audits capability off (hosted has it on). */ +export function securityOff(env: TestEnv): TestEnv { + return securityOn(env, { securityAudits: false }); +} + /** A scheduler namespace whose stub answers `fetch` with ok, plus the given methods. */ export function schedulerStub( methods: Record = {}, diff --git a/platform/packages/api/test/integration/security-local-check.test.ts b/platform/packages/api/test/integration/security-local-check.test.ts index 44c1922b89..c1c70f7927 100644 --- a/platform/packages/api/test/integration/security-local-check.test.ts +++ b/platform/packages/api/test/integration/security-local-check.test.ts @@ -28,6 +28,7 @@ import { saveSecurityPolicy, scanResult, securityBindings, + securityOff, } from './security-fixtures.ts'; const CF = '@cf/deepseek-ai/deepseek-v4.1-flash-1017'; @@ -124,7 +125,9 @@ describe('local checks (I12)', () => { const { archive, request } = tree(); const path = `/projects/${project.id}/security/checks`; expect((await call(path, reader.jwt, { body: request })).status).toBe(403); - expect((await call(path, owner.jwt, { body: request, bindings: env })).status).toBe(501); + expect( + (await call(path, owner.jwt, { body: request, bindings: securityOff(env) })).status, + ).toBe(501); const response = await call(path, owner.jwt, { body: request }); expect(response.status).toBe(201); diff --git a/platform/packages/api/test/integration/security-maintenance.test.ts b/platform/packages/api/test/integration/security-maintenance.test.ts new file mode 100644 index 0000000000..60cac2e481 --- /dev/null +++ b/platform/packages/api/test/integration/security-maintenance.test.ts @@ -0,0 +1,54 @@ +import { afterAll, beforeAll, beforeEach, expect, it, vi } from 'vite-plus/test'; +import type { MockInstance } from 'vite-plus/test'; +import type { ApiEnv } from '../../src/env.ts'; +import { CF_API_BASE } from '../../src/provisioning/cloudflare-api.ts'; +import { securityScannerNames } from '../../src/provisioning/security-scanner.ts'; +import { runSecurityMaintenance } from '../../src/security/maintenance.ts'; +import { runtimeCopyScriptName } from '../../src/security/runtime-copy-names.ts'; +import { clearTables, setupEnv, teardownEnv } from './helpers.ts'; +import type { TestEnv } from './helpers.ts'; +import { freshEntitlement, saveSecurityPolicy, securityBindings } from './security-fixtures.ts'; + +let env: TestEnv; +let fetchSpy: MockInstance; + +beforeAll(async () => { + env = await setupEnv(); +}); +afterAll(teardownEnv); +beforeEach(async () => { + await clearTables(env.db); + vi.restoreAllMocks(); +}); + +/** Fake Cloudflare API: the copy namespace lists `scripts`; every other call is empty. */ +function cloudflare(scripts: Array = []) { + fetchSpy = vi.spyOn(globalThis, 'fetch').mockImplementation(async (input) => { + const url = String(input instanceof Request ? input.url : input); + const result = url.endsWith('/scripts') ? scripts.map((id) => ({ id })) : []; + return Response.json({ success: true, errors: [], result }); + }); +} + +const onEnv = () => securityBindings(env) as unknown as ApiEnv['Bindings']; +const calls = () => fetchSpy.mock.calls.map(([input, init]) => `${init?.method ?? 'GET'} ${input}`); + +// Hosted has the capability on with Scan Off: the hourly run must not list the account. +it('makes no Cloudflare call before the scanner was ever set up', async () => { + cloudflare(); + const report = await runSecurityMaintenance(onEnv(), env.db, Date.now()); + expect(report).toMatchObject({ copiesReaped: 0, gatewayCosts: 0, probed: false }); + expect(fetchSpy).not.toHaveBeenCalled(); +}); + +// Scan rows go with their project, so a copy can outlive every scan row. +it('sweeps left-over runtime copies once the scanner was set up, even with no scan row', async () => { + await saveSecurityPolicy(env, { mode: 'disabled', entitlement: freshEntitlement() }); + const names = await securityScannerNames('void-api'); + const leftover = runtimeCopyScriptName(names.copyPrefix, 'ss_gone', 1); + cloudflare([leftover]); + const report = await runSecurityMaintenance(onEnv(), env.db, Date.now()); + expect(report).toMatchObject({ copiesReaped: 1 }); + const scripts = `${CF_API_BASE}/${env.CF_ACCOUNT_ID}/workers/dispatch/namespaces/${names.copyNamespace}/scripts`; + expect(calls()).toContain(`DELETE ${scripts}/${leftover}?force=true`); +}); diff --git a/platform/packages/api/test/smoke-security-flow.test.ts b/platform/packages/api/test/smoke-security-flow.test.ts new file mode 100644 index 0000000000..de8df7fc4b --- /dev/null +++ b/platform/packages/api/test/smoke-security-flow.test.ts @@ -0,0 +1,331 @@ +import { existsSync, readFileSync } from 'node:fs'; +import { join } from 'node:path'; +import { describe, expect, it } from 'vite-plus/test'; +import { + ApiError, + createApi, + PLANTED_FILE, + runSecuritySmoke, + SmokeError, +} from '../../../scripts/security-smoke-flow.ts'; +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 : ''); +type Handler = (body: Record) => unknown; +const scan = (status: string) => ({ + id: 'ss_1', + status, + statusReason: null, + trigger: 'deploy', + createdAt: '2026-11-30T00:00:00Z', +}); + +/** A fake platform. `routes` replaces the default answer for `METHOD path`. */ +function harness( + options: { + mode?: string; + deploy?: number; + routes?: Record; + onDeploy?: (state: { mode: string; extra: Record }) => void; + signal?: AbortSignal; + } = {}, +) { + const state = { + mode: options.mode ?? 'disabled', + revision: 7, + now: 0, + extra: {} as Record, + }; + const calls: Array = []; + const log: Array = []; + const scans = [[], [scan('queued')], [scan('running')], [scan('succeeded')]]; + const defaults: Record = { + 'GET /operator/v1/session': () => ({ + capabilities: { securityAudits: true }, + hostedWorkerOperations: false, + }), + 'GET /operator/v1/security/policy': () => ({ + policy: { mode: state.mode, revision: state.revision, ...state.extra }, + }), + 'POST /projects': () => ({ id: 'p1' }), + 'POST /operator/v1/security/policy': (body) => { + if (body.dryRun) { + return { expectedRevision: state.revision }; + } + state.mode = String(body.mode); + state.revision++; + return { ok: true }; + }, + 'GET /projects/p1/security/scans?limit=10': () => ({ + scans: scans.shift() ?? [scan('running')], + }), + 'GET /projects/p1/security/findings?state=open&limit=100': () => ({ + findings: [ + { id: 'F-2', severity: 'low', verdict: 'lead', file: 'routes/api/hello.ts' }, + { id: 'F-1', severity: 'critical', verdict: 'confirmed', file: PLANTED_FILE }, + ], + }), + }; + const api: Api = { + async call(method: string, path: string, call: { body?: unknown } = {}) { + const key = `${method} ${path}`; + 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; + }, + async logout() { + calls.push('logout'); + }, + }; + const run = () => + runSecuritySmoke({ + api, + origin: 'https://api.platform.example.test', + slug: 'security-smoke-test', + deploy: async () => { + calls.push('deploy'); + options.onDeploy?.(state); + return options.deploy ?? 0; + }, + sleep: async (ms) => { + options.signal?.throwIfAborted(); + state.now += ms; + }, + signal: options.signal, + now: () => state.now, + log: (line) => log.push(line), + }); + return { state, calls, log, run }; +} + +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([ + '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}', + '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 /projects/p1/security/findings?state=open&limit=100', + 'DELETE /projects/p1', + 'GET /operator/v1/security/policy', + 'POST /operator/v1/security/policy {"mode":"disabled","dryRun":true}', + 'POST /operator/v1/security/policy {"mode":"disabled","expectedRevision":8}', + 'logout', + ]); + expect(state.mode).toBe('disabled'); + expect(log).toContain('Finding F-1: severity critical, verdict confirmed.'); + }); + + it('writes no policy when scanning is already on', async () => { + 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(state.revision).toBe(7); + }); + + it('stops before any write when the capability is off', async () => { + const { calls, log, run } = harness({ + routes: { 'GET /operator/v1/session': () => ({ capabilities: { securityAudits: false } }) }, + }); + expect(await run()).toBe(1); + expect(calls).toEqual(['GET /operator/v1/session', 'logout']); + expect(log.join('\n')).toContain('securityAudits capability is off'); + }); + + it.each([ + ['the deploy fails', { deploy: 2 }, 'void deploy exited with code 2.'], + [ + 'the scan fails', + { + routes: { 'GET /projects/p1/security/scans?limit=10': () => ({ scans: [scan('failed')] }) }, + }, + 'Scan ss_1 ended failed.', + ], + [ + 'the planted bug is missed', + { + routes: { + 'GET /projects/p1/security/findings?state=open&limit=100': () => ({ findings: [] }), + }, + }, + `has no open finding in ${PLANTED_FILE}`, + ], + ])('deletes the project and restores the policy when %s', async (_name, options, message) => { + const { state, calls, log, run } = harness(options); + expect(await run()).toBe(1); + expect(log.join('\n')).toContain(message); + expect(calls).toContain('DELETE /projects/p1'); + expect(calls.at(-1)).toBe('logout'); + expect(state.mode).toBe('disabled'); + }); + + it('gives up at the deadline from the policy timeout', async () => { + const { state, log, run } = harness({ + routes: { 'GET /projects/p1/security/scans?limit=10': () => ({ scans: [scan('running')] }) }, + }); + expect(await run()).toBe(1); + expect(state.now).toBe(55 * 60_000); + expect(log.join('\n')).toContain('No finished deploy scan before the deadline (ss_1 running)'); + expect(state.mode).toBe('disabled'); + }); + + it('leaves the policy alone when someone else changed the mode', async () => { + const { calls, log, run } = harness({ onDeploy: (state) => (state.mode = 'all') }); + expect(await run()).toBe(0); + expect(log).toContain('Policy is now all; someone changed it, so it is left as is.'); + expect(calls.some((call) => call.includes('"mode":"disabled"'))).toBe(false); + }); + + it('leaves the policy alone when someone changed another setting during the run', async () => { + const { calls, log, run } = harness({ + onDeploy: (state) => (state.extra = { defaultModel: '@cf/other' }), + }); + expect(await run()).toBe(0); + expect(log).toContain('Policy settings changed during the run, so it is left as is.'); + expect(calls.some((call) => call.includes('"mode":"disabled"'))).toBe(false); + }); + + it('does not turn scanning off, and says so, when the apply call failed', async () => { + const h = harness({ + routes: { + 'POST /operator/v1/security/policy': (body) => { + if (body.dryRun) { + return { expectedRevision: 7 }; + } + h.state.mode = String(body.mode); // The server applied it, but the answer was lost. + throw new SmokeError('POST /operator/v1/security/policy -> network error'); + }, + }, + }); + expect(await h.run()).toBe(1); + expect(h.calls.some((call) => call.includes('"mode":"disabled"'))).toBe(false); + expect(h.calls).toContain('DELETE /projects/p1'); + expect(h.log.at(-1)).toBe( + 'Manual cleanup needed on https://api.platform.example.test: void platform security policy disabled (only if this run turned it on)', + ); + }); + + it('finds and deletes the project by slug when the create answer was lost', async () => { + const { calls, run } = harness({ + routes: { + 'POST /projects': () => { + throw new SmokeError('POST /projects -> network error'); + }, + 'GET /projects/resolve?slug=security-smoke-test': () => ({ project: { id: 'p1' } }), + }, + }); + expect(await run()).toBe(1); + expect(calls).toContain('DELETE /projects/p1'); + expect(calls.at(-1)).toBe('logout'); + }); + + it('cleans up when a signal stops the run', async () => { + const stop = new AbortController(); + const { state, calls, log, run } = harness({ + signal: stop.signal, + onDeploy: () => stop.abort(), + }); + expect(await run()).toBe(1); + expect(log).toContain('Security smoke failed: stopped by a signal'); + expect(calls).toContain('DELETE /projects/p1'); + expect(calls.at(-1)).toBe('logout'); + expect(state.mode).toBe('disabled'); + }); + + it('retries the restore once on a revision conflict', async () => { + let conflicts = 0; + const h = harness({ + routes: { + 'POST /operator/v1/security/policy': (body) => { + if (body.mode === 'disabled' && !body.dryRun && conflicts++ === 0) { + throw new ApiError('POST', '/operator/v1/security/policy', 409, 'revision_conflict'); + } + if (!body.dryRun) { + h.state.mode = String(body.mode); + } + return { expectedRevision: 7 }; + }, + }, + }); + expect(await h.run()).toBe(0); + expect(conflicts).toBe(2); + expect(h.state.mode).toBe('disabled'); + }); + + it('still restores the policy and prints one manual line when the delete fails', async () => { + const { state, log, run } = harness({ + routes: { + 'DELETE /projects/p1': () => { + throw new ApiError('DELETE', '/projects/p1', 500); + }, + }, + }); + expect(await run()).toBe(1); + expect(state.mode).toBe('disabled'); + expect(log).toContain('Cleanup: DELETE /projects/p1 -> HTTP 500'); + expect(log.filter((line) => line.startsWith('Manual cleanup'))).toEqual([ + 'Manual cleanup needed on https://api.platform.example.test: void project delete security-smoke-test --force', + ]); + }); +}); + +describe('security smoke API client', () => { + it('prints METHOD path -> status only, and sends operator calls with an operator token', async () => { + const seen: Array = []; + const api = createApi({ + origin: 'https://api.platform.example.test', + token: 'user-SECRET', + fetch: async (url, init) => { + const path = new URL(String(url)).pathname; + const auth = new Headers(init?.headers).get('Authorization'); + seen.push(`${init?.method} ${path} ${auth} ${init?.redirect}`); + if (path.startsWith('/operator/v1/session')) { + return Response.json({ token: 'op-SECRET' }); + } + if (path === '/operator/v1/security/policy') { + return Response.json({ error: 'revision_conflict', echo: auth }, { status: 409 }); + } + return new Response(`${auth}`, { status: 500 }); + }, + now: () => 0, + }); + const failures = await Promise.all([ + api.call('POST', '/projects', { body: { slug: 'x' } }).catch(message), + api.call('GET', '/operator/v1/security/policy', { operator: true }).catch(message), + ]); + expect(failures).toEqual([ + 'POST /projects -> HTTP 500', + 'GET /operator/v1/security/policy -> HTTP 409 (revision_conflict)', + ]); + await api.logout(); + expect(seen).toEqual([ + 'POST /projects Bearer user-SECRET manual', + 'POST /operator/v1/session Bearer user-SECRET manual', + 'GET /operator/v1/security/policy Bearer op-SECRET manual', + 'POST /operator/v1/session/logout Bearer op-SECRET manual', + ]); + }); +}); + +describe('security smoke fixture', () => { + it('copies playground/spa with the planted route and without crons', () => { + const fixture = prepareSecuritySmokeFixture(); + try { + expect(readFileSync(join(fixture.root, PLANTED_FILE), 'utf8')).toContain( + '"SELECT * FROM users WHERE email = \'" + email', + ); + expect(existsSync(join(fixture.root, 'routes/api/users/index.ts'))).toBe(true); + expect(existsSync(join(fixture.root, 'crons'))).toBe(false); + } finally { + fixture.cleanup(); + } + }); +}); diff --git a/platform/packages/api/test/smoke-security-target.test.ts b/platform/packages/api/test/smoke-security-target.test.ts new file mode 100644 index 0000000000..7863c28ec5 --- /dev/null +++ b/platform/packages/api/test/smoke-security-target.test.ts @@ -0,0 +1,83 @@ +import { spawnSync } from 'node:child_process'; +import { resolve } from 'node:path'; +import { describe, expect, it } from 'vite-plus/test'; + +const script = resolve(import.meta.dirname, '../../../scripts/security-smoke-test.ts'); +const staging = 'https://api.staging.void.cloud'; +const scratch = 'https://api.platform.example.test'; + +function run(env: Record, preload: string) { + return spawnSync( + process.execPath, + ['--import', `data:text/javascript,${encodeURIComponent(preload)}`, script], + { + encoding: 'utf8', + timeout: 20_000, + env: { + ...process.env, + SECURITY_SMOKE_API_URL: '', + SECURITY_SMOKE_CONFIRM: '', + VOID_TOKEN: '', + CF_ACCESS_CLIENT_ID: '', + CF_ACCESS_CLIENT_SECRET: '', + ...env, + }, + }, + ); +} + +describe('security smoke target guards', () => { + const noNetwork = `globalThis.fetch = async () => { throw new Error('NETWORK_USED'); };`; + + it.each([ + [{}, 'Set SECURITY_SMOKE_API_URL'], + [{ SECURITY_SMOKE_API_URL: 'https://api.void.cloud' }, 'never runs against the hosted'], + [{ SECURITY_SMOKE_API_URL: 'https://api.void.cloud:443/' }, 'never runs against the hosted'], + [{ SECURITY_SMOKE_API_URL: 'https://void.cloud' }, 'never runs against the hosted'], + [ + { SECURITY_SMOKE_API_URL: 'https://api.void.cloud.' }, + 'must not end its host name with a dot', + ], + [{ SECURITY_SMOKE_API_URL: 'https://admin.void.cloud' }, 'never runs against the hosted'], + [{ SECURITY_SMOKE_API_URL: 'http://api.platform.example.test' }, 'must be an https origin'], + [{ SECURITY_SMOKE_API_URL: `${scratch}/v1` }, 'must be an https origin'], + [{ SECURITY_SMOKE_API_URL: 'https://user:pw@api.platform.example.test' }, 'must be an https'], + [{ SECURITY_SMOKE_API_URL: scratch }, `Set SECURITY_SMOKE_CONFIRM=${scratch}`], + [ + { SECURITY_SMOKE_API_URL: scratch, SECURITY_SMOKE_CONFIRM: staging }, + 'SECURITY_SMOKE_CONFIRM', + ], + [{ SECURITY_SMOKE_API_URL: scratch, SECURITY_SMOKE_CONFIRM: scratch }, 'Set VOID_TOKEN'], + ])('refuses %j before any network call', (env, message) => { + const result = run(env, noNetwork); + expect(result.status).toBe(1); + expect(result.stderr).toContain(message); + expect(`${result.stdout}${result.stderr}`).not.toContain('NETWORK_USED'); + }); + + it('refuses a hosted platform that is not staging, logs out, and never prints a token', () => { + // Every body echoes the request, so a leaked token would show up in the output. + const preload = `globalThis.fetch = async (url, init) => { + const path = new URL(url).pathname; + const echo = init.headers.Authorization + ' ' + (init.body ?? ''); + if (init.method === 'POST' && path === '/operator/v1/session') return Response.json({ token: 'op-SECRET-1', echo }); + if (init.method === 'GET' && path === '/operator/v1/session') return Response.json({ capabilities: { securityAudits: true }, hostedWorkerOperations: true, echo }); + if (path === '/operator/v1/session/logout') { console.log('LOGOUT ' + (init.headers.Authorization === 'Bearer op-SECRET-1')); return Response.json({ ok: true }); } + return Response.json({ error: echo }, { status: 500 }); + };`; + const result = run( + { + SECURITY_SMOKE_API_URL: scratch, + SECURITY_SMOKE_CONFIRM: scratch, + VOID_TOKEN: 'user-SECRET-0', + }, + preload, + ); + const output = `${result.stdout}${result.stderr}`; + expect(result.status).toBe(1); + expect(output).toContain('is a hosted platform but not staging. Nothing was changed.'); + expect(output).toContain('LOGOUT true'); + expect(output).not.toContain('SECRET'); + expect(output).not.toContain('/projects'); + }); +}); diff --git a/platform/packages/api/test/unit/admin-page-loading.test.ts b/platform/packages/api/test/unit/admin-page-loading.test.ts index 1971e37708..6caf5c3f50 100644 --- a/platform/packages/api/test/unit/admin-page-loading.test.ts +++ b/platform/packages/api/test/unit/admin-page-loading.test.ts @@ -1,5 +1,7 @@ import { Hono } from 'hono'; import { expect, it, vi } from 'vite-plus/test'; +import { adminComponents, adminLayoutTree, matchAdminRoute } from '../../src/admin/react/pages.ts'; +import { renderAdminPage } from '../../src/admin/react/server.ts'; import type { ApiEnv } from '../../src/env.ts'; const { loaded } = vi.hoisted(() => ({ loaded: [] as Array })); @@ -14,11 +16,9 @@ vi.mock('../../src/admin/react/views/DashboardPage.tsx', () => { return { DashboardPage: () => null }; }); +// Top-level imports: a cold import of the admin graph is slow under a loaded test run and +// must not count toward the test timeout. vi.mock is hoisted, so the views stay unloaded. it('loads only requested views and skips them for page-protocol responses', async () => { - const { adminComponents, adminLayoutTree, matchAdminRoute } = - await import('../../src/admin/react/pages.ts'); - const { renderAdminPage } = await import('../../src/admin/react/server.ts'); - expect(loaded).toEqual([]); expect(adminLayoutTree.dashboard).toEqual(['adminLayout']); expect(matchAdminRoute('/admin/')).toBe('dashboard'); diff --git a/platform/packages/api/test/unit/capabilities.test.ts b/platform/packages/api/test/unit/capabilities.test.ts index ae6c3723cd..1c9c5393bb 100644 --- a/platform/packages/api/test/unit/capabilities.test.ts +++ b/platform/packages/api/test/unit/capabilities.test.ts @@ -12,7 +12,7 @@ describe('platform capabilities', () => { googleOAuth: true, managedBuilds: true, sandbox: true, - securityAudits: false, + securityAudits: true, }); }); diff --git a/platform/packages/api/test/unit/hosted-config.test.ts b/platform/packages/api/test/unit/hosted-config.test.ts index 57018b75f8..e78d6cf5dc 100644 --- a/platform/packages/api/test/unit/hosted-config.test.ts +++ b/platform/packages/api/test/unit/hosted-config.test.ts @@ -43,15 +43,15 @@ it.each([ expect(routingId(proxy)).toBe(routingId(api)); }); -// Hosted keeps `securityAudits` off: the scheduler class ships idle, with no AI binding. -it('binds the idle security scan scheduler without AI, in its own SQLite migration', () => { +// Hosted has `securityAudits` on: the scan scheduler and the AI binding in every environment. +it('binds the security scan scheduler and AI, in its own SQLite migration', () => { type Worker = { durable_objects?: { bindings?: Array }; ai?: unknown }; for (const worker of [config, config.env.production, config.env.staging] as Array) { expect(worker.durable_objects?.bindings).toContainEqual({ name: 'SECURITY_SCAN_SCHEDULER', class_name: 'SecurityScanScheduler', }); - expect(worker.ai).toBeUndefined(); + expect(worker.ai).toEqual({ binding: 'AI' }); } const migrations = (config as unknown as { migrations: Array }).migrations; expect(migrations.at(-1)).toEqual({ diff --git a/platform/packages/api/test/unit/security-scheduler-stub.test.ts b/platform/packages/api/test/unit/security-scheduler-stub.test.ts index c7278908af..ac3de05230 100644 --- a/platform/packages/api/test/unit/security-scheduler-stub.test.ts +++ b/platform/packages/api/test/unit/security-scheduler-stub.test.ts @@ -1,4 +1,5 @@ import { expect, it, vi } from 'vite-plus/test'; +import { getPlatformCapabilities } from '../../src/capabilities.ts'; import { SecurityScanScheduler } from '../../src/security/scheduler.ts'; // I13: with the capability off the scheduler class ships idle and reads no binding. @@ -11,7 +12,7 @@ it('does no work and reads no binding when the alarm fires with the capability o if (key !== 'PLATFORM_CAPABILITIES') { throw new Error(`unexpected binding ${String(key)}`); } - return undefined; + return JSON.stringify({ ...getPlatformCapabilities({}), securityAudits: false }); }, }, ); diff --git a/platform/packages/api/wrangler.jsonc b/platform/packages/api/wrangler.jsonc index 252209070f..1f48cf28f0 100644 --- a/platform/packages/api/wrangler.jsonc +++ b/platform/packages/api/wrangler.jsonc @@ -21,6 +21,7 @@ "assets": { "directory": "./dist/admin-assets" }, "compatibility_date": "2026-02-12", "compatibility_flags": ["nodejs_compat"], + "ai": { "binding": "AI" }, "observability": { "enabled": true, }, @@ -237,6 +238,7 @@ }, ], "name": "void-api", + "ai": { "binding": "AI" }, "version_metadata": { "binding": "VERSION_METADATA" }, "secrets": { "required": ["EMAIL_SIGNING_SECRET"] }, "hyperdrive": [ @@ -396,6 +398,7 @@ }, ], "name": "void-api-staging", + "ai": { "binding": "AI" }, "version_metadata": { "binding": "VERSION_METADATA" }, "secrets": { "required": ["EMAIL_SIGNING_SECRET"] }, "hyperdrive": [ diff --git a/platform/scripts/fixtures/security-smoke/routes/api/users/search.ts b/platform/scripts/fixtures/security-smoke/routes/api/users/search.ts new file mode 100644 index 0000000000..46b17d6456 --- /dev/null +++ b/platform/scripts/fixtures/security-smoke/routes/api/users/search.ts @@ -0,0 +1,8 @@ +import { defineHandler } from 'void'; + +// Planted on purpose for the security smoke: user input goes straight into SQL. +// The deploy scan must report this file. Never copy this pattern. +export const GET = defineHandler(async (c) => { + const email = c.req.query('email'); + return c.json(await c.env.DB.prepare("SELECT * FROM users WHERE email = '" + email + "'").all()); +}); diff --git a/platform/scripts/security-smoke-flow.ts b/platform/scripts/security-smoke-flow.ts new file mode 100644 index 0000000000..426a9037ad --- /dev/null +++ b/platform/scripts/security-smoke-flow.ts @@ -0,0 +1,418 @@ +/** + * The release smoke for security audits, without any I/O of its own. The entry + * (security-smoke-test.ts) passes in fetch, the deploy step and the clock, so tests can + * run every step offline. See security-smoke-test.md. + */ +import { SECURITY_ERRORS } from '../../packages/platform/src/security-policy.ts'; +import { STAGING_API } from './kitchen-sink-staging-env-setup.ts'; + +export const PRODUCTION_API = 'https://api.void.cloud'; +/** The route the fixture plants; the scan must report a finding in it. */ +export const PLANTED_FILE = 'routes/api/users/search.ts'; +const OPERATOR_SESSION_MS = 40 * 60 * 1000; // The server gives 60 minutes. +const POLL_MS = 15_000; +const WAITING = new Set(['pending_input', 'queued', 'running']); +// Only these error codes are printed; any other response text stays out of the log. +const KNOWN_CODES = new Set([ + 'revision_conflict', + ...Object.values(SECURITY_ERRORS).map((entry) => entry.code), +]); + +export class SmokeError extends Error {} + +/** Checks the target before any network call. Throws a SmokeError with the fix. */ +export function readTarget(env: Record) { + const raw = env.SECURITY_SMOKE_API_URL; + if (!raw) { + throw new SmokeError('Set SECURITY_SMOKE_API_URL to the https origin of a test platform API.'); + } + let url: URL; + try { + url = new URL(raw); + } catch { + throw new SmokeError('SECURITY_SMOKE_API_URL is not a URL.'); + } + if ( + url.protocol !== 'https:' || + url.username || + url.password || + url.pathname !== '/' || + url.search || + url.hash + ) { + throw new SmokeError( + 'SECURITY_SMOKE_API_URL must be an https origin with no credentials, path, query or fragment.', + ); + } + const host = url.hostname; + if (host.endsWith('.')) { + throw new SmokeError('SECURITY_SMOKE_API_URL must not end its host name with a dot.'); + } + const voidCloud = host === 'void.cloud' || host.endsWith('.void.cloud'); + if (url.origin === PRODUCTION_API || (voidCloud && url.origin !== STAGING_API)) { + throw new SmokeError('The security smoke never runs against the hosted production API.'); + } + if (env.SECURITY_SMOKE_CONFIRM !== url.origin) { + throw new SmokeError(`Set SECURITY_SMOKE_CONFIRM=${url.origin} to confirm the target.`); + } + if (!env.VOID_TOKEN) { + throw new SmokeError(`Set VOID_TOKEN to an admin login token for ${url.origin}.`); + } + return { origin: url.origin, token: env.VOID_TOKEN }; +} + +/** Replaces every secret in `text` with `***`. */ +export function redact(text: string, secrets: ReadonlyArray): string { + let out = text; + for (const secret of secrets) { + if (secret) { + out = out.split(secret).join('***'); + } + } + return out; +} + +/** Its message is `METHOD path -> HTTP status`, never the response body. */ +export class ApiError extends Error { + readonly status: number; + readonly code?: string; + constructor(method: string, path: string, status: number, code?: string) { + super(`${method} ${path} -> HTTP ${status}${code ? ` (${code})` : ''}`); + this.status = status; + this.code = code; + } +} + +type CallOptions = { body?: unknown; operator?: boolean; timeoutMs?: number; signal?: AbortSignal }; +export type Api = { + call>( + method: string, + path: string, + options?: CallOptions, + ): Promise; + /** Ends every operator session this run made. */ + logout(): Promise; +}; + +/** A small API client: one origin, no redirects, user or operator token. */ +export function createApi(options: { + origin: string; + token: string; + headers?: Record; + fetch: typeof fetch; + now: () => number; +}): Api { + const sessions: Array = []; + let mintedAt = 0; + const send = async (method: string, path: string, token: string, call: CallOptions = {}) => { + let response: Response; + try { + response = await options.fetch(`${options.origin}${path}`, { + method, + redirect: 'manual', + signal: AbortSignal.any([ + AbortSignal.timeout(call.timeoutMs ?? 60_000), + ...(call.signal ? [call.signal] : []), + ]), + headers: { + ...options.headers, + Authorization: `Bearer ${token}`, + ...(call.body === undefined ? {} : { 'Content-Type': 'application/json' }), + }, + ...(call.body === undefined ? {} : { body: JSON.stringify(call.body) }), + }); + } catch { + throw new SmokeError( + `${method} ${path} -> ${call.signal?.aborted ? 'stopped' : 'network error'}`, + ); + } + let json: Record | undefined; + try { + // A JSON.parse error quotes the text, so its message is never used. + json = JSON.parse(await response.text()) as Record; + } catch { + // Not JSON: refused below. + } + if (!response.ok || !json) { + const code = typeof json?.error === 'string' && KNOWN_CODES.has(json.error) ? json.error : ''; + throw new ApiError( + method, + path, + response.status, + response.ok ? 'not JSON' : code || undefined, + ); + } + return json as T; + }; + const operatorToken = async () => { + const current = sessions.at(-1); + if (current && options.now() - mintedAt < OPERATOR_SESSION_MS) { + return current; + } + const path = '/operator/v1/session'; + const { token } = await send<{ token: string }>('POST', path, options.token, { body: {} }); + sessions.push(token); + mintedAt = options.now(); + return token; + }; + return { + async call(method, path, call = {}) { + return send(method, path, call.operator ? await operatorToken() : options.token, call); + }, + async logout() { + for (let token = sessions.pop(); token; token = sessions.pop()) { + await send('POST', '/operator/v1/session/logout', token, { body: {} }); + } + }, + }; +} + +type Policy = { + mode: string; + revision: number; + limits?: { timeoutMinutes?: number }; + [key: string]: unknown; +}; + +/** What an admin set: everything but the probe result and the revision the probe bumps. */ +function adminSettings({ revision: _revision, entitlement: _entitlement, ...rest }: Policy) { + return JSON.stringify(rest); +} +type Scan = { + id: string; + status: string; + statusReason: string | null; + trigger: string; + createdAt: string; +}; +type Finding = { id: string; severity: string | null; verdict: string; file?: string | null }; + +export type SmokeDeps = { + api: Api; + origin: string; + slug: string; + /** Deploys the fixture as `slug`; resolves to the CLI exit code. */ + deploy(slug: string): Promise; + sleep(ms: number): Promise; + now(): number; + log(line: string): void; + /** Aborts on SIGINT/SIGTERM: the run stops, then cleanup runs without it. */ + signal?: AbortSignal; +}; + +/** `unsure`: the apply call failed, so the server may or may not have turned scanning on. */ +type Restore = { kind: 'none' } | { kind: 'unsure' } | { kind: 'ours'; settings: string }; + +const describe = (error: unknown) => (error instanceof Error ? error.message : 'Unknown error.'); + +/** Runs the smoke and always cleans up. Resolves to the process exit code. */ +export async function runSecuritySmoke(d: SmokeDeps): Promise { + const op = { operator: true, signal: d.signal }; + const user = { signal: d.signal }; + let projectId: string | undefined; + let createTried = false; + let restore: Restore = { kind: 'none' }; + let ok = false; + try { + const session = await d.api.call<{ + capabilities?: { securityAudits?: boolean }; + hostedWorkerOperations?: boolean; + }>('GET', '/operator/v1/session', op); + if (session.hostedWorkerOperations && d.origin !== STAGING_API) { + throw new SmokeError( + `${d.origin} is a hosted platform but not staging. Nothing was changed.`, + ); + } + if (!session.capabilities?.securityAudits) { + throw new SmokeError(`securityAudits capability is off on ${d.origin}. Nothing was changed.`); + } + const { policy: before } = await d.api.call<{ policy: Policy }>( + 'GET', + '/operator/v1/security/policy', + op, + ); + d.log(`Policy before: mode ${before.mode}, revision ${before.revision}.`); + + createTried = true; + const project = await d.api.call<{ id: string }>('POST', '/projects', { + ...user, + body: { slug: d.slug }, + }); + projectId = project.id; + d.log(`Created project ${d.slug} (${projectId}).`); + const base = `/operator/v1/projects/${encodeURIComponent(projectId)}/security`; + await d.api.call('POST', `${base}/policy`, { ...op, body: { override: 'always' } }); + await d.api.call('POST', `${base}/budget`, { ...op, body: { monthlyUsd: 5 } }); + + if (before.mode === 'disabled') { + const preview = await d.api.call<{ expectedRevision: number }>( + 'POST', + '/operator/v1/security/policy', + { ...op, body: { mode: 'public', dryRun: true } }, + ); + restore = { kind: 'unsure' }; + // Leaving Off runs the entitlement probe and sets up the scanner: minutes long. + await d.api.call('POST', '/operator/v1/security/policy', { + ...op, + body: { mode: 'public', expectedRevision: preview.expectedRevision }, + timeoutMs: 30 * 60_000, + }); + const { policy: applied } = await d.api.call<{ policy: Policy }>( + 'GET', + '/operator/v1/security/policy', + op, + ); + restore = { kind: 'ours', settings: adminSettings(applied) }; + d.log('Policy set to public for this run.'); + } + + const code = await d.deploy(d.slug); + d.signal?.throwIfAborted(); + if (code !== 0) { + throw new SmokeError(`void deploy exited with code ${code}.`); + } + const waitMinutes = (before.limits?.timeoutMinutes ?? 20) * 2 + 15; + const scan = await waitForScan(d, projectId, d.now() + waitMinutes * 60_000); + if (scan.status !== 'succeeded') { + throw new SmokeError( + `Scan ${scan.id} ended ${scan.status}${scan.statusReason ? `:${scan.statusReason}` : ''}.`, + ); + } + const { findings } = await d.api.call<{ findings: Array }>( + 'GET', + `/projects/${encodeURIComponent(projectId)}/security/findings?state=open&limit=100`, + user, + ); + const hit = findings.find((finding) => finding.file?.endsWith(PLANTED_FILE)); + if (!hit) { + throw new SmokeError(`Scan ${scan.id} has no open finding in ${PLANTED_FILE}.`); + } + d.log(`Finding ${hit.id}: severity ${hit.severity ?? 'none'}, verdict ${hit.verdict}.`); + ok = true; + } 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; +} + +async function waitForScan(d: SmokeDeps, projectId: string, deadline: number): Promise { + let last = ''; + for (;;) { + const { scans } = await d.api.call<{ scans: Array }>( + 'GET', + `/projects/${encodeURIComponent(projectId)}/security/scans?limit=10`, + { signal: d.signal }, + ); + const scan = scans + .filter((entry) => entry.trigger === 'deploy') + .sort((a, b) => b.createdAt.localeCompare(a.createdAt))[0]; + if (scan && `${scan.id} ${scan.status}` !== last) { + last = `${scan.id} ${scan.status}`; + d.log(`Scan ${scan.id}: ${scan.status}.`); + } + if (scan && !WAITING.has(scan.status)) { + return scan; + } + if (d.now() >= deadline) { + throw new SmokeError(`No finished deploy scan before the deadline (${last || 'no scan'}).`); + } + await d.sleep(POLL_MS); + } +} + +/** + * 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. + */ +async function cleanUp(d: SmokeDeps, projectId: string | null | undefined, restore: Restore) { + const manual: Array = []; + if (projectId !== undefined) { + try { + const id = + projectId ?? + ( + await d.api.call<{ project: { id: string } | null }>( + 'GET', + `/projects/resolve?slug=${encodeURIComponent(d.slug)}`, + ) + ).project?.id; + if (id) { + await d.api.call('DELETE', `/projects/${encodeURIComponent(id)}`); + d.log(`Deleted project ${d.slug}.`); + } + } catch (error) { + d.log(`Cleanup: ${describe(error)}`); + 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) { + d.log(`Cleanup: ${describe(error)}`); + manual.push('the operator session ends on its own within an hour'); + } + if (manual.length > 0) { + d.log(`Manual cleanup needed on ${d.origin}: ${manual.join('; ')}`); + } + return manual.length === 0; +} + +/** + * 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. + */ +async function restorePolicy(d: SmokeDeps, settings: string | undefined): Promise { + const op = { operator: true }; + for (let attempt = 0; ; attempt++) { + const { policy } = await d.api.call<{ policy: Policy }>( + 'GET', + '/operator/v1/security/policy', + 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 (settings === undefined) { + d.log('Policy is public, but this run cannot tell whether it set that.'); + return false; + } + if (adminSettings(policy) !== settings) { + d.log('Policy settings changed during the run, so it is left as is.'); + return true; + } + const preview = await d.api.call<{ expectedRevision: number }>( + 'POST', + '/operator/v1/security/policy', + { ...op, body: { mode: 'disabled', dryRun: true } }, + ); + try { + await d.api.call('POST', '/operator/v1/security/policy', { + ...op, + body: { mode: 'disabled', expectedRevision: preview.expectedRevision }, + }); + d.log('Policy set back to Off.'); + return true; + } 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 new file mode 100644 index 0000000000..af9adf078c --- /dev/null +++ b/platform/scripts/security-smoke-test.md @@ -0,0 +1,90 @@ +# Security Audits Smoke Test + +Maintainer-only. Run it before a release that changes security audits. It deploys a copy of +`playground/spa` with one planted SQL injection route +(`fixtures/security-smoke/routes/api/users/search.ts`) to a test platform, waits for the +deploy scan, and passes only when the scan reports an open finding in that file. + +```sh +vp run build +SECURITY_SMOKE_API_URL=https://api.staging.void.cloud \ +SECURITY_SMOKE_CONFIRM=https://api.staging.void.cloud \ +VOID_TOKEN= \ +node platform/scripts/security-smoke-test.ts +``` + +## Inputs + +| Variable | Required | Meaning | +| ------------------------------------------------- | -------- | ---------------------------------------------------------------------------- | +| `SECURITY_SMOKE_API_URL` | yes | The platform API origin, `https://` only, no path, query or credentials. | +| `SECURITY_SMOKE_CONFIRM` | yes | The same origin again, typed by hand, to confirm the target. | +| `VOID_TOKEN` | yes | A full login token of an installation admin (not a project or deploy token). | +| `CF_ACCESS_CLIENT_ID` / `CF_ACCESS_CLIENT_SECRET` | no | An Access service token, when Access protects the API. | + +The platform needs the `securityAudits` capability and the Cloudflare products listed in +design doc 0095 (Workers Paid, Containers, Workers AI credits). Without the capability the +script stops after reading the operator session and changes nothing. + +## Safety rules + +- No network call happens until all inputs pass the checks above. +- `https://api.void.cloud`, `void.cloud` and every other `*.void.cloud` host except + `https://api.staging.void.cloud` are always refused, and so is a host name ending in a dot. After login, a platform that says it is + hosted (`hostedWorkerOperations`) is refused unless it is staging, so a production alias is + caught too. +- Tokens go to the CLI through env only. They are replaced with `***` in all CLI output and + log lines. API errors print `METHOD path -> HTTP status` and a known error code, never a + response body. +- The scratch project slug is `security-smoke-