diff --git a/.github/workflows/platform-ci.yml b/.github/workflows/platform-ci.yml index a939f4b5b..ebda6be6e 100644 --- a/.github/workflows/platform-ci.yml +++ b/.github/workflows/platform-ci.yml @@ -38,6 +38,37 @@ jobs: - name: Build API build container run: docker build --pull --tag void-api-build-container:ci --file platform/packages/api/container/Dockerfile . + build-security-scanner-images: + if: github.event_name == 'pull_request' + runs-on: ${{ github.repository == 'voidzero-dev/void' && 'blacksmith-4vcpu-ubuntu-2404' || 'ubuntu-latest' }} + timeout-minutes: 20 + permissions: + contents: read + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - uses: voidzero-dev/setup-vp@1b32467adbe183473499fd9d5d372c3ed9641754 # v1.18.0 + with: + cache: true + node-version-file: .node-version + - run: vp install + - run: vp run --filter ./platform/packages/security-scanner build + - name: Build Engine A scanner image + run: docker build --platform linux/amd64 --tag void-scanner-claude:ci --file platform/packages/security-scanner/image/Dockerfile.claude . + - name: Build Engine C scanner image + run: docker build --platform linux/amd64 --tag void-scanner-codex:ci --file platform/packages/security-scanner/image/Dockerfile.codex . + - name: Check the Engine C image pins its Codex version and keeps only our models + run: | + docker run --rm --entrypoint /opt/void-scanner/codex-bin void-scanner-codex:ci --version + docker run --rm --entrypoint node void-scanner-codex:ci -e "const m=require('/opt/void-scanner/codex-models.json').models.map(x=>x.slug);console.log(m.join());if(m.length!==2)process.exit(1)" + # Both images run a whole scan with no network against a scripted fake model (design + # doc 0095 M13b). The builds above leave the layers cached for this run. + - name: Run a recorded scan in both scanner images + env: + VOID_SCANNER_E2E: '1' + run: vp test run platform/packages/security-scanner/test/e2e/recorded-run.e2e.test.ts + lint-build-check: runs-on: ${{ github.repository == 'voidzero-dev/void' && 'blacksmith-4vcpu-ubuntu-2404' || 'ubuntu-latest' }} permissions: diff --git a/.github/workflows/platform-security-scanner-images.yml b/.github/workflows/platform-security-scanner-images.yml new file mode 100644 index 000000000..2bd0d2748 --- /dev/null +++ b/.github/workflows/platform-security-scanner-images.yml @@ -0,0 +1,50 @@ +name: Publish Security Scanner Images + +# Manual release step for security audits Engines A and C (design doc 0095 M13b): build +# both scanner images for linux/amd64, push them to ghcr.io, and print the digests to pin +# in platform/packages/api/src/security/scanner-images.json. Commit that file before the +# platform release that should turn those engines on. The ghcr.io packages must be public: +# each install copies the image by digest without credentials. Runs only on main or a +# release tag, with no build cache, and labels each image with the commit it was built +# from (org.opencontainers.image.revision), so a pinned digest can be traced to reviewed code. +on: + workflow_dispatch: + +concurrency: + group: platform-security-scanner-images + cancel-in-progress: false + +permissions: {} + +jobs: + publish: + if: github.ref == 'refs/heads/main' || startsWith(github.ref, 'refs/tags/') + runs-on: ubuntu-latest + timeout-minutes: 30 + permissions: + contents: read + packages: write + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - uses: voidzero-dev/setup-vp@1b32467adbe183473499fd9d5d372c3ed9641754 # v1.18.0 + with: + cache: false + node-version-file: .node-version + - run: vp install + - name: Log in to ghcr.io + env: + GHCR_TOKEN: ${{ secrets.GITHUB_TOKEN }} + run: printf '%s' "$GHCR_TOKEN" | docker login ghcr.io --username "$GITHUB_ACTOR" --password-stdin + - name: Build, push and pin both images + run: node platform/scripts/publish-security-scanner-images.ts --push + - name: Show the digests to commit + run: | + { + echo '### platform/packages/api/src/security/scanner-images.json' + echo "Built from \`$GITHUB_SHA\` ($GITHUB_REF)." + echo '```json' + cat platform/packages/api/src/security/scanner-images.json + echo '```' + } >> "$GITHUB_STEP_SUMMARY" diff --git a/docs/.vitepress/config.ts b/docs/.vitepress/config.ts index 8129bf1ca..ec203c342 100644 --- a/docs/.vitepress/config.ts +++ b/docs/.vitepress/config.ts @@ -109,6 +109,7 @@ const referenceItems: Array = [ { text: 'Platform Configuration', link: '/reference/cli/platform-config' }, { text: 'Platform Users and Projects', link: '/reference/cli/platform-users' }, { text: 'Project Zero Trust', link: '/reference/cli/platform-zero-trust' }, + { text: 'Platform Security Audits', link: '/reference/cli/platform-security' }, { text: 'Platform Operations', link: '/reference/cli/platform-operations' }, { text: 'Platform Email', link: '/reference/cli/platform-email' }, ], @@ -195,6 +196,7 @@ const platformSidebar = [ { text: 'Users and Projects', link: '/guide/platform/administration/projects' }, { text: 'Plans and Limits', link: '/guide/platform/administration/plans' }, { text: 'Project Zero Trust', link: '/guide/platform/administration/zero-trust' }, + { text: 'Security Audits', link: '/guide/platform/administration/security-audits' }, { text: 'Email', link: '/guide/platform/administration/email' }, { text: 'Operations', link: '/guide/platform/administration/operations' }, ], diff --git a/docs/guide/platform-administration.md b/docs/guide/platform-administration.md index d76e8d75d..9de232cc6 100644 --- a/docs/guide/platform-administration.md +++ b/docs/guide/platform-administration.md @@ -15,5 +15,6 @@ The operator commands for users, projects, deployments, and system status requir - [Users and Projects](/guide/platform/administration/projects) - [Plans and Limits](/guide/platform/administration/plans) - [Project Zero Trust](/guide/platform/administration/zero-trust) +- [Security Audits](/guide/platform/administration/security-audits) - [Email](/guide/platform/administration/email) - [Operations](/guide/platform/administration/operations) diff --git a/docs/guide/platform/administration/plans.md b/docs/guide/platform/administration/plans.md index 3c1fa9322..7822ddc63 100644 --- a/docs/guide/platform/administration/plans.md +++ b/docs/guide/platform/administration/plans.md @@ -122,6 +122,19 @@ Moving an account to another plan, replacing a removed plan, or transferring a p Inspect a plan's default with `void platform config plans show ` or the dashboard's user detail page. If the CLI reports that your platform does not support plan defaults, run `void platform upgrade` first. +## Security Scan Cap {#security-scan-cap} + +With [security audits](./security-audits.md) on, a plan can set the most each of its projects may spend on scans in a calendar month (UTC). In the dashboard, edit the plan's **Security scan cap**: **Policy default**, **Monthly amount**, or **No cap**. From the CLI: + +```sh +void platform config plans set team --security-cap 200 --plan +void platform config plans set team --security-cap 200 --yes +``` + +`--security-cap` takes a USD amount, `none` for no cap, or `inherit` for the default project cap. Plan files use the `securityCap` field with the same values. A plan amount applies even while project caps are off, and `none` lifts the default project cap for the plan's projects. A limit you set for one project comes first. The platform cap still stops every scan once it is used up. + +A change applies right away: to the next scan that starts, and to scans already running from their next model call, so a lower cap can stop one. Copying a plan copies its scan cap, and accounts moved to a replacement plan get that plan's cap. See [Spending caps](./security-audits.md#spending-caps). + ## Archive or Remove a Plan Archive a plan to stop assigning it to new accounts while preserving its current accounts: diff --git a/docs/guide/platform/administration/security-audits.md b/docs/guide/platform/administration/security-audits.md new file mode 100644 index 000000000..332c1cf5e --- /dev/null +++ b/docs/guide/platform/administration/security-audits.md @@ -0,0 +1,244 @@ +--- +description: 'Run an AI security review of each deploy on your Void platform, choose which projects and models it covers, cap its cost, and hold a project private until a scan passes.' +outline: deep +--- + +# Security Audits + +Security audits run an AI review of the code that changed in each deploy, and report serious problems to the people who own the project. The scan starts after the deploy is live. A scan or a finding never blocks, delays, or fails a deploy. + +AI review can be wrong. "No findings" means nothing was found, not that the code is safe. Treat it as a second pair of eyes next to human review. + +This feature is off until you turn it on. Projects deployed directly to Cloudflare are not affected. + +## Requirements + +- A platform installed or upgraded with `--security-audits`. See [Turn security audits on](/reference/cli/platform-security#enable). +- Workers Paid on the platform's Cloudflare account, with Cloudflare Containers. +- Workers AI access for the default model: Workers Paid or prepaid AI credits. +- For the optional scan before a project goes public, [project Zero Trust](./zero-trust.md) must be on and not public-only. + +The scanner runs in its own container with no internet access. It reaches models only through the platform. Uninstalling the platform removes the scanner Worker, its container applications, the scanner images it copied, and any leftover scan copies. See [Disable and Uninstall](/guide/platform/installation/uninstall). + +::: warning Roll forward after you upgrade +The upgrade that adds security audits includes a database migration for the scan scheduler. Cloudflare does not roll a Worker back past such a migration, so after you upgrade, fix a bad release by deploying a newer one. +::: + +## Turn it on + +```sh +void platform upgrade --security-audits +void platform security probe +void platform security budget --platform-usd 500 +void platform security policy public +``` + +The probe checks that the account can run scans and names anything missing. Spending caps are off by default, so set a [platform cap](#spending-caps) before you choose a mode. Turning a scan mode on runs the probe first and refuses when it fails. The probe runs again each day while scans are on. If it starts failing, the policy stays on, new deploys are not scanned, and the admin pages show a banner. + +Choose a scan mode: + +| Mode | Scans | +| -------------------- | --------------------------------------------------------------- | +| Off (default) | Nothing | +| Public projects only | Projects that are public, or that have no Zero Trust protection | +| All projects | Every project | + +Turning a mode on scans nothing right away. Each project is scanned at its next deploy, and the first scan of a project reviews the whole deployment. Later scans review what changed since the last good scan. Use `--plan` to preview how many projects a change reaches. To scan apps that are already live, see [Scan live apps again](#scan-live-apps). + +A platform admin can also give one project its own rule, from the project's **Security** section in the administrator UI or with the CLI: + +```sh +void platform security policy --project +``` + +| Rule | Scans | +| ----------------- | ----------------------------------------------------------------------- | +| inherit (default) | What the scan mode says | +| always | Every deploy, also while Zero Trust protects the project | +| never | Nothing, except the scan before the project goes public when that is on | + +A project's rule has no effect while the mode is Off. Its project page and `void project security status` say why the project is or is not scanned. + +Platform administrators can also manage all of this from **Security** in the administrator UI. + +## What is scanned + +A scan starts when a deploy goes live. Rollbacks, failed deploys, and `preview-*` projects are not scanned. A newer deploy replaces a scan that is still queued. A redeploy with no code change is recorded as "no changes" and costs nothing. + +Void reviews the source that changed when it can see it, and otherwise the built output mapped back to source. Third-party package code, lockfiles, binaries, and secret-like files are left out, and stored secret values are replaced before any model sees the code. Void tells registry packages from your own code by the project's `pnpm-lock.yaml` or `package-lock.json`; without one of those, package code is reviewed too and the result notes `third-party-unverified`. A full rescan can also review the sources of the client bundles, from the source maps deployed with them: `void project security scan --client-assets`. Each result states what it covered, such as `Changes since dpl_7c20 · source diff · 14 files · complete`. Large changes are scanned in parts, and the page shows the files still waiting. + +### Check code before you deploy + +Developers who can deploy a project can scan their code before it goes out: + +```sh +void project security check +``` + +It sends the git-tracked files of the current folder, as they are on disk, to the platform, and the scan runs on the project's model. Untracked files, secret-like files, lockfiles, and binaries stay on the developer's machine. The command shows what it sends, which model reviews it, and the most it can cost, then asks before it uploads anything. The check needs the policy to apply to the project, and is refused while a platform admin has set the project's rule to `never`. It waits in the queue like any scan and counts toward the monthly caps. Its result is shown in the terminal and kept for 30 days. It is not saved as project findings, sends no email, and does not affect a request to go public. See [`void project security check`](../../../reference/cli/project.md#void-project-security). + +## Models and the provider notice + +| Model | Run by | +| ---------------------------------------------------- | ---------- | +| `@cf/deepseek-ai/deepseek-v4.1-flash-1017` (default) | Cloudflare | +| `@cf/zai-org/glm-5.3` | Cloudflare | +| `openai/gpt-6.1-terra`, `openai/gpt-6.1-sol` | OpenAI | +| `anthropic/claude-sonnet-5.5` | Anthropic | +| `anthropic/claude-opus-5.5` | Anthropic | + +A model run by a third party sees the project's changed code, the files it uses, and past findings and comments. The provider may keep request data for a limited time and may refuse security-looking code. A refused scan shows as refused, never as passed. For that reason code does not go to a third party until someone has accepted the notice: you accept it once for a third-party platform default, and a project owner or administrator accepts it once per project. Until then the project uses a Cloudflare model. To keep all code in Cloudflare, block the third-party models. + +A project that picks a third-party model also needs an AI permission on the platform's runtime token, unless you [saved your own key](#own-provider-key) for that provider. See [Permissions to select for each token](/guide/platform/installation/credentials). The probe names a missing permission and lists models that cannot be picked yet. For these models the probe also copies a scanner image into the account's container registry. The first copy can take more than one probe run; until it is done, those models cannot be picked. When you block every model of one provider, the probe does not copy that provider's image. + +Project owners and administrators pick their project's model from the same list with `void project security model`. + +### Use your own provider key {#own-provider-key} + +By default, OpenAI and Anthropic models are paid from the platform account's [AI Gateway Unified Billing](https://developers.cloudflare.com/ai-gateway/features/unified-billing/) credits. To use your own API key and your own agreement with the provider instead, save the key: + +```sh +printf "%s" "$ANTHROPIC_API_KEY" | void platform security models --provider anthropic --key-stdin --yes +void platform security probe +``` + +Void makes a 1-token test call with the key and saves it only if the call works. The key is stored encrypted and never reaches the scanner; the platform adds it to each model call. Scans with that provider then bill to your key, still through AI Gateway. They are still metered at list price and count toward the [spending caps](#spending-caps). The provider notice and model blocking work the same way. + +Run the probe after saving a key if that provider's models could not be picked before. Saving a new key replaces the old one right away. `void platform security models --provider anthropic --remove-key` deletes it: that provider's scans go back to Unified Billing credits, and its models cannot be picked until the probe passes again. `void platform security status` shows which keys are saved and when, never the key itself. + +## Findings + +Only a human closes a finding. A scan can add one, confirm it again, or reopen it, but never close it. Resolve a finding as fixed, false positive, or accepted risk, with a comment of up to 4,000 characters. The comment and the resolution feed the next scan, so the same false alarm does not come back. Comments never hide anything; only a false-positive resolution does. + +A finding is **urgent** when it is confirmed, critical or high, and still open. Weaker or unconfirmed findings are listed as leads or lower severity and are never urgent. + +A project admin or the owner can change the severity of an open finding, with a comment: `void project security severity F-12 medium --comment "Only reachable by admins"`. The new severity sticks across scans. Lowering a critical or high finding takes it out of the urgent count, as a resolve does. See [`void project security`](../../../reference/cli/project.md#void-project-security). + +When the value of a project secret appears in the deployed Worker code or in a static text file (`.js`, `.html`, `.json`, `.css`, `.txt`, up to 8 MB), as is or encoded, the platform reports it itself as a `secret-in-output` finding that names the secret but never shows its value. There is one finding per secret for static files and one for Worker code, whatever files it is in. In a static file it is high and urgent, since anyone can download the file once the project is public: rotate the secret and keep it on the server. In Worker code it is medium: read it from `env` instead of writing it into the code. If the value is meant to be public, such as a publishable key, resolve the finding as accepted risk; it stays resolved when later deploys change the bundle. + +When a project uses a Cloudflare model, a scan can also test a possible finding on a throwaway copy of the deployment: the same code with empty databases, fake secrets, and no internet access. Only the scanner can reach the copy, and it is deleted when the scan ends. A finding proven this way shows as `confirmed (runtime)` in `void project security show`. The copy is part of the scan cost. + +| Who sees what | Reader | Collaborator and up | +| ------------------------------- | ------ | ------------------- | +| Urgent count and finding ids | Yes | Yes | +| Titles, files, and details | No | Yes | +| Scans, cost, and bypass reasons | No | Yes | + +Open urgent findings show: + +- at the end of each `void deploy` to a Void platform, with titles only for a signed-in user who can deploy. CI runs and readers see counts and ids, +- in `void project security status`, and as a `Security` line in `void project status`, +- on the project's security page, opened with `void project security open`, where collaborators and up can comment, and the owner and project admins can also resolve, pick the model, set the budget, and bypass a held public request. A platform with the user dashboard has the same page behind **Security** on its **Projects** list, +- on GitHub, for deploys built from a [connected repository](#github-checks), +- in the administrator UI, with an **Urgent** filter. + +To use findings in a code scanning tool, export them as SARIF with `void project security list --format sarif` (or `void platform security findings --format sarif` for every project). + +Every scan that does not succeed says what happened, and the next scan covers those changes. A refused, timed-out, or failed scan is never counted as clean. + +## Scan live apps again {#scan-live-apps} + +Deploy scans review what changed. These scans review more. Each one costs money and counts toward the [spending caps](#spending-caps): + +| To | Run | Who | +| ------------------------------------------------------- | ----------------------------------------------------------------------------- | --------------------------------------------------- | +| Scan one project's live deployment in full now | `void project security scan`, or `void platform security rescan ` | Project owner or admin, or a platform administrator | +| Scan live apps deployed before security audits were on | `void platform security backfill` | Platform administrators | +| Review every live app in full on a schedule | `void platform security sweeps on --every-days 30` | Platform administrators | +| Scan again on Cloudflare when a third-party model fails | `void platform security fallback on` | Platform administrators | + +A full scan names its model and the most it can cost, then asks first. Backfill handles up to 50 projects at a time; run it again for the rest. A sweep is a deeper review than a deploy scan, and only a few start each hour, so deploy scans keep moving. Fallback scans the same changes once more on the default `@cf` model when a third-party model refuses, times out, or returns output that cannot be read. It never sends code from a `@cf` scan to a third party. Sweeps and fallback are off by default. A deployment whose code is no longer stored cannot be scanned again until the project deploys. See [Findings and scans](/reference/cli/platform-security#findings-scans). + +## GitHub checks {#github-checks} + +Each scan of a deploy built from a repository connected with `void github connect` adds a `Void Security Audit` check to the commit. This works with either executor, `container` or `github_actions`. A `void deploy` from a terminal, or from a CI job that is not a connected build, gets no check. The check is always **neutral**, so it never blocks a merge. It shows only the number of urgent findings and a link to the project's security page, never titles or files, because anyone who can see the repository can read it. A scan that did not finish says so, and is never shown as clean. + +While an urgent finding is open, each open pull request for that commit (up to five) also gets one comment with the same counts, which later scans update in place. The comment needs the GitHub App's **Pull requests: Read and write** permission. With read-only access, only the check is posted. + +**Re-run** on the check starts a full rescan of the live deployment when the person who clicks it signs in to the platform with that GitHub account and is the project's owner or an admin. For anyone else, or on a check of an older deployment, it does nothing. **Re-run all** reruns the build instead. + +## Spending caps + +The platform pays for scans, and they do not count against the plan's AI limits. Two monthly caps, both off by default, use the calendar month in UTC: + +- A **platform cap** that stops all scans when it is used up. +- A **project cap**, with a default amount for every project. A project owner or administrator can set a lower cap for their own project. The most they can set is the limit you give that project, else the cap of the owner's plan, else the default when project caps are on. + +A scan starts only if its worst case fits under both caps. The Scans page in the administrator UI shows the metered cost next to what AI Gateway reports, which arrives about an hour after a scan ends. A used-up cap skips scans, never deploys, and the first scan after the reset or a raise covers what was skipped. Rescans and scans before public count too. At 80% and 100% of a cap, the owner and project administrators (project cap) or platform administrators (platform cap) get one email per month. + +```sh +void platform security budget --platform-usd 500 --project-default-usd 50 +void platform config plans set pro --security-cap 200 +``` + +A plan cap applies to each project whose owner is on that plan, even with project caps off. `--security-cap none` gives the plan's projects no cap, and `inherit` returns it to the default. See [Security scan cap](./plans.md#security-scan-cap). + +## Emails + +| Email | Sent to | +| ---------------------------------------------------------------------- | -------------------------------------------------- | +| New findings, one per scan | Owner, project admins, and the people who deployed | +| A human reopens an urgent finding | Owner and project admins | +| Project cap at 80% and 100% | Owner and project admins | +| Platform cap at 80% and 100% | Platform administrators | +| Public request held, now public, or canceled | Who asked, the owner, and project admins | +| Scan bypassed | Every platform administrator, with the reason | +| Three scans of a project in a row failed | Owner, project admins, and platform administrators | +| Many scans failed for a platform reason, at most once a day | Platform administrators | +| Weekly summary, when turned on with `void platform security digest on` | Platform administrators | + +Emails carry titles, severity, and file paths, never code. A scan that finishes after the scan mode was set to Off sends no email. Without a configured [email domain](./email.md) the same information is in the CLI and on the project page, and bypasses still show in the admin pages. A `void project security check` sends no email. + +To send these events to your own system, set a webhook with `void platform security webhook `. Its signed body holds ids and counts only, and it is sent even without an email domain. See [Alerts, summary, and webhook](/reference/cli/platform-security#alerts). + +## Scan before a project goes public {#scan-before-public} + +With [project Zero Trust](./zero-trust.md) on, you can hold a project's change from protected to public until a scan of the live deployment finds nothing urgent: + +```sh +void platform security public-gate on +``` + +The gate needs a scan mode of Public or All, a recent probe pass, and platform Zero Trust on and not public-only. While it is on, platform Zero Trust cannot be disabled or switched to public-only. Turn the gate off first. Turning it off, or setting the scan mode to Off, cancels open requests. Those projects stay protected. + +When someone runs `void project zero-trust public`, the project **stays protected** and the request waits for a scan. Deploys keep working. The request is in one of these states: + +| State | Meaning | What to do | +| ---------------- | ------------------------------------------------------------ | ------------------------------------------- | +| Waiting | The scan is queued or running | Wait, or bypass | +| Held by findings | An urgent finding is open | Resolve it. There is no bypass | +| No result | The scan failed, was refused, timed out, or hit a cap | Run `public` again, deploy again, or bypass | +| Needs a deploy | The live code cannot prove it, or a fix needs a newer deploy | Deploy again, or bypass | + +A finding resolved as false positive or accepted risk lets the request go on at once. A finding resolved as **fixed** only counts after a clean scan of a newer deploy. A rescan of the same deployment proves nothing. An unchanged Worker redeploy is enough to prove a fix. A static site needs a changed deploy. + +The gate covers only the change from protected to public for an existing project. Projects that start public, and `preview-*` projects, are not covered. After a project is public, a later finding never makes it private again. + +### Bypass the scan + +An owner or a project administrator can skip the scan with a reason: + +```sh +void project zero-trust bypass --reason "Scanner down since 09:00; launch today." +``` + +Platform administrators use the platform command with the project ID: + +```sh +void platform security bypass --reason "Scanner down since 09:00; launch today." +``` + +A bypass skips the scan, never an open urgent finding. With one open, it is refused and nothing is recorded. Every bypass is recorded with its reason, and every platform administrator gets an email. Platform administrators can list them with `void platform security bypasses`. Later findings follow the normal flow. + +## What users see + +Project members use these commands. See [Projects](/reference/cli/project#void-project-security). + +```sh +void project security status +void project security list --urgent +void project security check +void project zero-trust status +``` + +A new CLI talking to a platform without security audits says so and asks the user to contact a platform administrator. Older CLIs print nothing extra after a deploy, and they never report a held request as public. diff --git a/docs/guide/platform/administration/zero-trust.md b/docs/guide/platform/administration/zero-trust.md index 66cd53246..28cc4c1d8 100644 --- a/docs/guide/platform/administration/zero-trust.md +++ b/docs/guide/platform/administration/zero-trust.md @@ -70,6 +70,12 @@ Installation administrators can do the same from the project page in the adminis Deploys and rollbacks wait until a project's protection change is finished. If one is refused, run `void project zero-trust status` to see why; the owner or a project administrator can run `void project zero-trust reconcile` before you try again. A protected project can have up to 100 custom domains. +## Scan Before Public + +If you turn on [scan before a project goes public](./security-audits.md#scan-before-public), making a protected project public no longer takes effect at once. The project stays protected until a scan of its live deployment finds no urgent finding, or until an allowed person bypasses the scan with a reason. Deploys keep working while the request waits. + +While it is on, `void platform zero-trust disable` and public-only configuration are refused. Turn the gate off first with `void platform security public-gate off`. In the administrator UI, **Disable** and the public-only option are unavailable, and **Make project public** says that the project stays protected until the scan passes. + ## Disable Zero Trust ```sh diff --git a/docs/guide/platform/installation/credentials.md b/docs/guide/platform/installation/credentials.md index c4b09b9af..571de56a6 100644 --- a/docs/guide/platform/installation/credentials.md +++ b/docs/guide/platform/installation/credentials.md @@ -44,24 +44,25 @@ Compare each token's form with the permission checklist below. The installer sav Use the following permissions for the core platform. Cloudflare may label write access as **Edit** or **Write**, depending on the token screen; see its [permission reference](https://developers.cloudflare.com/fundamentals/api/reference/permissions/). -| Scope | Permission | Management | Runtime | -| ------- | ------------------ | ---------- | --------------------------------------- | -| Account | Account Settings | Read | Read | -| Account | Workers Scripts | Edit | Edit | -| Account | Workers Tail | Read | Read | -| Account | D1 | Edit | Edit | -| Account | Workers KV Storage | Edit | Edit | -| Account | Workers R2 Storage | Edit | Edit | -| Account | Queues | Edit | Edit | -| Account | Hyperdrive | Write | Write | -| Account | Account Analytics | Read | Read | -| Account | AI Gateway | Edit | Edit when installing with browser login | -| Account | Containers | — | Edit | -| Account | Cloudchamber | — | Edit | -| Zone | Zone | Read | — | -| Zone | DNS | Edit | — | -| Zone | Workers Routes | Edit | — | -| Zone | Cache Purge | — | Purge | +| Scope | Permission | Management | Runtime | +| ------- | ------------------ | ---------- | ------------------------------------------------------------------------------------------------------------------------------------- | +| Account | Account Settings | Read | Read | +| Account | Workers Scripts | Edit | Edit | +| Account | Workers Tail | Read | Read | +| Account | D1 | Edit | Edit | +| Account | Workers KV Storage | Edit | Edit | +| Account | Workers R2 Storage | Edit | Edit | +| Account | Queues | Edit | Edit | +| Account | Hyperdrive | Write | Write | +| Account | Account Analytics | Read | Read | +| Account | AI Gateway | Edit | Edit when installing with browser login | +| Account | Containers | — | Edit | +| Account | Cloudchamber | — | Edit | +| Account | Workers AI | — | Read, for [security audit](/guide/platform/administration/security-audits#models-and-the-provider-notice) models run by third parties | +| Zone | Zone | Read | — | +| Zone | DNS | Edit | — | +| Zone | Workers Routes | Edit | — | +| Zone | Cache Purge | — | Purge | When Void configures Access in the installation account, the initial management-token link also selects **Account → Access: Apps and Policies → Edit** and **Account → Access: Organizations, Identity Providers, and Groups → Read**. Protection adds **Account → Access: Service Tokens → Edit**. When the authentication configuration or saved setup selects existing applications, the link requests Read access instead of Edit. These permissions belong to the management token; the runtime token does not need them. diff --git a/docs/guide/platform/installation/uninstall.md b/docs/guide/platform/installation/uninstall.md index 4aee68fc9..6e93af4c2 100644 --- a/docs/guide/platform/installation/uninstall.md +++ b/docs/guide/platform/installation/uninstall.md @@ -57,6 +57,8 @@ void platform uninstall [id] --purge-resources `--purge-resources` includes `--purge-data`. It also deletes the platform Workers, Queues, the application Workers left in the dispatch namespace, the R2 bucket and its objects, the AI Gateway, the platform DNS record, Worker routes and custom domains, and the Access applications and service tokens the installer created. The plan lists each resource in deletion order, and everything that stays. If Cloudflare shows that the AI Gateway was created after installation, for example because it was deleted and created again under the same name, it is kept and listed. +With [security audits](/guide/platform/administration/security-audits) on, uninstall also deletes the scanner Worker, its container applications, the scanner images copied into the account's container registry, the scan copy namespace, its sandbox Worker, and any leftover scan copies before the platform Workers, even without `--purge-resources`. Stored scan data lives under `security-scans/` in the platform's R2 bucket, so it stays with the bucket: `--purge-resources` deletes it, and otherwise empty the bucket yourself. Deleting a project deletes its findings and scan data. A scanner object that another installation owns is kept and named in a warning. + If the platform sends email, it first deletes the Email Routing rules in the sender domain's zone that send mail to the platform email gateway Worker, and resets such a catch-all rule to drop mail. It leaves Email Routing enabled and keeps the sender domain's MX, SPF, and DKIM records. It never removes zones, adopted resources, external PostgreSQL, other Email Routing settings, Analytics Engine datasets, Access policies or identity providers you chose, or API tokens. Revoke the API tokens you created for the platform afterward. diff --git a/docs/guide/self-hosted-platform.md b/docs/guide/self-hosted-platform.md index 5de6d821d..a3fed0fa9 100644 --- a/docs/guide/self-hosted-platform.md +++ b/docs/guide/self-hosted-platform.md @@ -17,19 +17,20 @@ The core installation also includes managed Sandboxes and an email gateway. Conf Both targets use the same application APIs. A core platform adds shared access and retained deployment history: -| Feature | Direct Cloudflare | Core self-hosted platform | -| ------------------------------------------------ | -------------------------------- | --------------------------------------------- | -| Static sites, SPAs, and native Pages SSR | Supported | Supported | -| Routing rules, WebSockets, queues, cron, and ISR | Supported | Supported | -| D1, KV, R2, and external SQL through Hyperdrive | Supported | Supported | -| Workers AI and provider requests | Your account and gateway | Installation gateway and proxy | -| Runtime logs | Live Cloudflare tail | Retained platform logs | -| Application rollback | Worker versions | Retained platform deployments | -| Typed Durable State and native Durable Objects | Supported | Supported | -| Sandboxes | Requires Workers Paid and Docker | Requires Workers Paid on the platform account | -| Custom application domains | Supported | Enable with `--custom-domains` | -| Generated GitHub deployment workflow | Supported | Use your CI with a scoped developer token | -| User dashboard and managed GitHub builds | Not required | Not included in a standard installation | +| Feature | Direct Cloudflare | Core self-hosted platform | +| ------------------------------------------------ | -------------------------------- | ------------------------------------------------------------------------------------------------- | +| Static sites, SPAs, and native Pages SSR | Supported | Supported | +| Routing rules, WebSockets, queues, cron, and ISR | Supported | Supported | +| D1, KV, R2, and external SQL through Hyperdrive | Supported | Supported | +| Workers AI and provider requests | Your account and gateway | Installation gateway and proxy | +| Runtime logs | Live Cloudflare tail | Retained platform logs | +| Application rollback | Worker versions | Retained platform deployments | +| Typed Durable State and native Durable Objects | Supported | Supported | +| Sandboxes | Requires Workers Paid and Docker | Requires Workers Paid on the platform account | +| Security audits of each deploy | Not available | Enable with `--security-audits`; needs Workers Paid, Containers, and Workers AI access or credits | +| Custom application domains | Supported | Enable with `--custom-domains` | +| Generated GitHub deployment workflow | Supported | Use your CI with a scoped developer token | +| User dashboard and managed GitHub builds | Not required | Not included in a standard installation | A team platform requires Workers for Platforms and the [documented infrastructure](/guide/platform/installation/domains#cloudflare-footprint). Features depend on the installation's configuration. diff --git a/docs/reference/cli.md b/docs/reference/cli.md index ed7955920..5dc4cc95d 100644 --- a/docs/reference/cli.md +++ b/docs/reference/cli.md @@ -59,13 +59,15 @@ Use this page as a command reference. If you are setting up a project for the fi | `void account login` | Authenticate with a Void platform | | `void cloudflare login` | Authenticate with Cloudflare through Void | | `void platform install` | Install a company Void platform in Cloudflare | +| `void platform security` | Administer security audits: scan mode, models, caps, findings, and alerts | | `void connect ` | Connect the CLI to a Void platform; hostnames default to HTTPS | | `void project link` | Link directory to a project | | `void project logs` | Show runtime logs from deployed project | | `void project requests` | Show request-level traffic (status, method, timing) | | `void project rollback` | Roll back to a previous deployment | | `void project cancel` | Cancel an active deployment | -| `void project zero-trust` | Inspect or override project Zero Trust protection | +| `void project zero-trust` | Inspect or override project Zero Trust protection, or bypass a security scan | +| `void project security` | Review findings and scans, set model and budget, scan, check code pre-deploy | | `void project purge-cache` | Purge all cached pages (Void platform) | | `void build logs` | Stream, tail, or download build logs | | `void email status` | Show email readiness on your own Cloudflare account (`--platform cloudflare`) | diff --git a/docs/reference/cli/deploy.md b/docs/reference/cli/deploy.md index ed923e1bf..6a56158ea 100644 --- a/docs/reference/cli/deploy.md +++ b/docs/reference/cli/deploy.md @@ -81,6 +81,10 @@ project is created. The same applies to `VOID_PROJECT` and to another project on the current platform. A first deployment still links the project when no destination is configured. See [Deploy to another Void platform](../../guide/deployment.md#deploy-to-another-void-platform). +### Security notice + +When the platform has [security audits](../../guide/platform/administration/security-audits.md) turned on, `void deploy` prints the scan state and any open urgent findings after the deploy is live. The deploy has already gone out, and the notice never changes the exit code. In a signed-in terminal it lists finding titles and files. In CI, and for readers, it prints counts and finding ids only. Review them with `void project security list --urgent`. + ## `void deploy --platform cloudflare` {#void-deploy-platform-cloudflare} Build and deploy to your Cloudflare account using `void.config.ts`: diff --git a/docs/reference/cli/platform-config.md b/docs/reference/cli/platform-config.md index 78bddb5da..12b9e7c84 100644 --- a/docs/reference/cli/platform-config.md +++ b/docs/reference/cli/platform-config.md @@ -13,8 +13,8 @@ Use your administrator session for these commands. See [Platform Management](./p ```sh void platform config plans show [plan-id] -void platform config plans add --copy --name "Team" -void platform config plans set [--name "Team"] [--file plan.json] +void platform config plans add --copy --name "Team" [--security-cap ] +void platform config plans set [--name "Team"] [--file plan.json] [--security-cap ] void platform config plans reset void platform config plans archive void platform config plans restore @@ -27,7 +27,8 @@ Use `--plan` to preview changes and affected accounts, then `--yes` to apply the ### Inspect and Manage Plans -- `show` reports limits, the signup default, assignments, and pending updates. `show ` includes the plan's AI logging default. +- `show` reports limits, the signup default, assignments, and pending updates. `show ` includes the plan's AI logging default and security scan cap. +- `--security-cap` on `add` or `set` sets the most each project on the plan may spend on [security scans](./platform-security.md#models-limits-budget) in a month: a USD amount, `none` for no cap, or `inherit` for the default project cap. A limit set for one project comes first. `add` copies the source plan's cap. - `reset` restores a built-in plan's original limits and build size. - `archive` stops new assignments while keeping existing accounts. Choose another signup default before archiving the current one. - `remove` requires a replacement if the plan has accounts or is the signup default. @@ -44,6 +45,7 @@ For `add` and `set`, `--file` reads a JSON object. All fields are optional; omit | `buildInstanceType` | `standard-3` or `standard-4` | | `allowShortSlugs` | `true` permits future project slugs of five characters or fewer; `false` requires longer names | | `aiLogging` | `off`, `metadata`, or `full`; `inherit` clears the plan's override | +| `securityCap` | Monthly security scan cap per project: a USD amount, `"none"`, or `"inherit"` | Build timeouts have a platform maximum of 60 minutes; `0` uses that maximum. Storage quotas are not editable. Changing `allowShortSlugs` preserves existing URLs. See [Plans and Limits](../../guide/platform/administration/plans.md) for the supported limits and file examples, and [AI Gateway logging](./platform-users.md#ai-gateway-logging) for logging modes. diff --git a/docs/reference/cli/platform-installation.md b/docs/reference/cli/platform-installation.md index a88b5d4aa..b7e5b5cbb 100644 --- a/docs/reference/cli/platform-installation.md +++ b/docs/reference/cli/platform-installation.md @@ -9,32 +9,33 @@ outline: deep void platform install [options] [--yes] ``` -| Option | Purpose | -| ----------------------------------------- | ------------------------------------------------------------------------------------ | -| `--name ` | Installation name used in `void--` resource names; choose an unused name | -| `--display-name ` | Human-readable platform name | -| `--account ` | Cloudflare account id | -| `--auth-config ` | Login methods, signup policy, and environment references for provider secrets | -| `--login-methods ` | Comma-separated `github`, `google`, `oidc`, or `cloudflare-access` login methods | -| `--access-protection` | Protect the platform UI and APIs with Cloudflare Access | -| `--no-access-protection` | Skip Cloudflare Access protection | -| `--app-access ` | Public apps, the platform's Access policy, or separately selected app policies | -| `--hyperdrive ` | Create Hyperdrive or use the specified existing configuration | -| `--application-domain ` | Base domain for deployed apps | -| `--workers-dev` | Explicit testing mode; add an application domain later | -| `--zone ` | Cloudflare zone containing the application domain | -| `--dedicated-zone` | Add zone-wide catch-all routes; valid only when the app domain is the whole zone | -| `--no-dedicated-zone` | Skip zone-wide application catch-all routes | -| `--custom-domains` | Let projects add their own domains; needs a dedicated zone | -| `--runtime-logs ` | `minimal` keeps request URLs and log and exception messages out of runtime logs | -| `--storage-location ` | Default location hint for new project R2 buckets; `automatic` clears it | -| `--control-plane-domain ` | Optional API custom hostname; defaults to `workers.dev` | -| `--no-control-plane-domain` | Use the default `workers.dev` API hostname | -| `--dashboard-url ` | HTTPS origin of an optional dashboard deployed separately | -| `--plan` | Preview Cloudflare changes and save installation choices locally | -| `--resume` | Continue the matching checkpointed installation | -| `--runtime ` | Deploy a locally built, integrity-checked runtime directory | -| `--yes` | Acknowledge Cloudflare changes in non-interactive use | +| Option | Purpose | +| ----------------------------------------- | --------------------------------------------------------------------------------------- | +| `--name ` | Installation name used in `void--` resource names; choose an unused name | +| `--display-name ` | Human-readable platform name | +| `--account ` | Cloudflare account id | +| `--auth-config ` | Login methods, signup policy, and environment references for provider secrets | +| `--login-methods ` | Comma-separated `github`, `google`, `oidc`, or `cloudflare-access` login methods | +| `--access-protection` | Protect the platform UI and APIs with Cloudflare Access | +| `--no-access-protection` | Skip Cloudflare Access protection | +| `--app-access ` | Public apps, the platform's Access policy, or separately selected app policies | +| `--hyperdrive ` | Create Hyperdrive or use the specified existing configuration | +| `--application-domain ` | Base domain for deployed apps | +| `--workers-dev` | Explicit testing mode; add an application domain later | +| `--zone ` | Cloudflare zone containing the application domain | +| `--dedicated-zone` | Add zone-wide catch-all routes; valid only when the app domain is the whole zone | +| `--no-dedicated-zone` | Skip zone-wide application catch-all routes | +| `--custom-domains` | Let projects add their own domains; needs a dedicated zone | +| `--security-audits` | Allow [security audits](./platform-security.md#enable); needs Containers and Workers AI | +| `--runtime-logs ` | `minimal` keeps request URLs and log and exception messages out of runtime logs | +| `--storage-location ` | Default location hint for new project R2 buckets; `automatic` clears it | +| `--control-plane-domain ` | Optional API custom hostname; defaults to `workers.dev` | +| `--no-control-plane-domain` | Use the default `workers.dev` API hostname | +| `--dashboard-url ` | HTTPS origin of an optional dashboard deployed separately | +| `--plan` | Preview Cloudflare changes and save installation choices locally | +| `--resume` | Continue the matching checkpointed installation | +| `--runtime ` | Deploy a locally built, integrity-checked runtime directory | +| `--yes` | Acknowledge Cloudflare changes in non-interactive use | For a first installation, follow [Install a Void Platform](../../guide/self-hosted-platform.md). The interactive installer recommends using a domain and offers **Use workers.dev for testing** as a visible alternative. Void creates the platform infrastructure and tables. External PostgreSQL and a configured login method are required in either mode. Select all login methods you want to enable; none are selected initially. Non-interactive installation defaults to GitHub when no login configuration is supplied. `--workers-dev` skips zone/DNS/certificate operations and cannot be combined with `--application-domain`, `--zone`, or `--dedicated-zone`. @@ -104,9 +105,9 @@ Use these commands to recover, update, pause, or remove an installation: ```sh void platform discover [--account ] [--installation ] -void platform upgrade [id] [--runtime ] [--dashboard-url ] [--custom-domains] [--runtime-logs ] [--storage-location ] [--plan] [--yes] +void platform upgrade [id] [--runtime ] [--dashboard-url ] [--custom-domains] [--security-audits] [--runtime-logs ] [--storage-location ] [--plan] [--yes] void platform rollback [id] --runtime [--from-runtime ] [--plan] [--yes] -void platform repair [id] [--runtime ] [--dashboard-url ] [--custom-domains] [--auth-config ] [--plan] [--yes] +void platform repair [id] [--runtime ] [--dashboard-url ] [--custom-domains] [--security-audits] [--auth-config ] [--plan] [--yes] void platform disable [id] [--plan] [--yes] void platform enable [id] [--runtime ] [--plan] [--yes] void platform uninstall [id] [--plan] [--purge-data | --purge-resources] [--yes] diff --git a/docs/reference/cli/platform-security.md b/docs/reference/cli/platform-security.md new file mode 100644 index 000000000..8f825a095 --- /dev/null +++ b/docs/reference/cli/platform-security.md @@ -0,0 +1,98 @@ +--- +description: 'Turn security audits on, choose a scan mode and model, set monthly spending caps, and handle findings and public requests from an administrator session.' +outline: deep +--- + +# Platform Security Audits {#operator-security} + +Use your administrator session for these commands. See [Platform Management](./platform.md#operator-commands) for platform selection, previews, and confirmation. Projects are named by id; `--project` filters also accept a slug. + +## Turn security audits on {#enable} + +Security audits need Cloudflare Containers and Workers AI on the platform's Cloudflare account. Allow them when you install or upgrade: + +```sh +void platform install --security-audits [options] +void platform upgrade [id] --security-audits +void platform repair [id] --security-audits +``` + +This allows the feature and nothing more. No project is scanned until you set a scan mode. The runtime token needs the Containers permissions that the token page lists. Uninstalling the platform also deletes the scanner, its container applications, and the scanner images it copied. + +Then check the account and choose a mode: + +```sh +void platform security probe +void platform security policy [--plan] [--yes] +void platform security policy --project [--plan] [--yes] +void platform security status +``` + +`probe` checks that the account can run scans and reports each missing requirement. `policy` selects which projects are scanned, and `--plan` shows how many projects the change reaches. Turning the mode on runs the probe first and refuses when it fails. + +`policy --project` sets one project's own rule. `always` scans it at each deploy, also while Zero Trust protects it. `never` stops its scans: deploys, rescans, sweeps, backfill, and `void project security check`. With [Scan before a project goes public](/guide/platform/administration/security-audits#scan-before-public) on, a request to make it public still scans it first. `inherit` makes the project follow the scan mode again. The rule changes nothing while the mode is `disabled`. It starts no scan by itself; use `rescan` to scan the project now. `status` lists the projects that have their own rule. + +## Models, limits, and spending {#models-limits-budget} + +```sh +void platform security models [--default ] [--block ] [--unblock ] [--accept-provider-notice] [--plan] [--yes] +void platform security models --provider (--key-stdin | --remove-key) [--plan] [--yes] +void platform security limits [--concurrency ] [--scan-timeout ] [--plan] [--yes] +void platform security budget [--platform-usd | --platform-off] [--project-default-usd | --project-caps ] [--plan] [--yes] +void platform security budget --project (--usd | --clear) [--plan] [--yes] +void platform security model [--accept-provider-notice] [--plan] [--yes] +``` + +A model run by a third party needs its provider notice accepted with `--accept-provider-notice`. `--provider --key-stdin` saves your own OpenAI or Anthropic API key, read from standard input, for that provider's models; pipe it from your password manager and add `--yes`. Void makes a 1-token test call with the key and saves it only if the call works. `--remove-key` deletes it. See [Use your own provider key](/guide/platform/administration/security-audits#own-provider-key). `budget` with no flags shows the caps and this month's spend; with a cap flag it changes them. `--platform-usd` sets the platform cap and turns it on. `--project-default-usd` sets the default cap for every project and turns project caps on; `--project-caps off` removes it. `--project --usd ` sets the most that project's admins may give it, and `--clear` removes that limit. A lower cap that a project admin set for their own project still applies. Without a project limit, a project gets the [plan cap](./platform-config.md#plans) of its owner's plan, then the default. + +## Findings and scans {#findings-scans} + +```sh +void platform security findings [--project ] [--urgent] [--state ] [--severity ] [--format sarif] +void platform security show +void platform security resolve --reason --comment "" [--yes] +void platform security reopen --comment "" [--yes] +void platform security comment "" [--yes] +void platform security scans [--project ] [--status ] [--trigger gate] +void platform security rescan [--client-assets] [--yes] +void platform security backfill [--plan] [--yes] +void platform security sweeps [--every-days ] [--plan] [--yes] +void platform security fallback [--plan] [--yes] +void platform security cancel [--yes] +``` + +Lists show one page at a time; use `--limit` (up to 100) and `--page`. Findings list the oldest first. `findings --format sarif` prints every matching finding, across projects, as one SARIF 2.1.0 file (up to 10,000 findings); it does not take `--limit` or `--page`. Name several findings with commas to change them together; they are checked before any change is made. + +`rescan` runs a full scan of the live deployment. It tells you which model it uses and the most it can cost, then asks before it starts. Monthly caps apply to rescans too. `--client-assets` also reviews the sources of the project's client bundles from the source maps deployed with them. Project admins can start the same scan with `void project security scan`. + +Turning security audits on scans nothing that is already live. `backfill` scans each live deployment in scope that has never been scanned, up to 50 projects at a time; run it again for the rest. `--plan` shows how many projects it reaches and the most the scans can cost. A deployment whose code is no longer stored cannot be scanned; the preview counts these, and the next deploy of each project scans it. + +`sweeps on` reviews every live app in full on a schedule, with a deeper review than a deploy scan: a project is swept when it has had no full scan for `--every-days` days (7 to 90, default 30). A few sweeps start each hour, so deploy scans keep moving. Projects whose live code is no longer stored are not swept until they deploy again. Sweeps are off by default; each one costs more than a deploy scan, and the monthly caps apply. + +`fallback on` scans a deployment once more on the `@cf` default model when a scan on a third-party model is refused, returns output that cannot be read, or times out. That scan keeps the code on Cloudflare and covers the same changes. It never switches from a `@cf` model to a third-party one. Fallback is off by default; each fallback scan costs one more scan, and the monthly caps apply. + +## Alerts, summary, and webhook {#alerts} + +```sh +void platform security digest [--plan] [--yes] +void platform security webhook [--plan] [--yes] +``` + +When three scans of a project in a row do not succeed for a project reason (refused, unreadable output, timed out, or incomplete), the project owner, its admins, and every installation admin get one email for that run of failures. When more than 20% of the scans in the last 24 hours fail for a platform reason (no AI credits, a scanner error, or a long queue), installation admins get one email that day. + +`digest on` sends installation admins a weekly email each Monday with the counts for the week before: scans, new and resolved findings, urgent findings still open, and public requests. It is off by default. + +`webhook` sends each security event to an `https` URL as a signed JSON body that holds ids and counts only, never titles, file paths, or code. Setting the URL shows a signing secret once; setting it again makes a new secret. Each request has an `X-Void-Event` type such as `security.findings`, an `X-Void-Delivery` id that stays the same on retries, and `X-Void-Signature: t=,v1=`, where `t` is the send time and `v1` the HMAC-SHA256 of `.` with the secret. A request that does not answer 2xx within 10 seconds is retried twice. Webhooks are sent even when platform email is off. + +## Scan before a project goes public {#public-gate} + +With [project Zero Trust](./platform-zero-trust.md) on, you can hold a project's change from protected to public until a scan passes: + +```sh +void platform security public-gate [--plan] [--yes] +void platform security public-requests [--project ] [--state ] +void platform security bypass --reason "" [--yes] +void platform security bypasses [--project ] +``` + +`public-gate on` is refused while platform Zero Trust is off. A bypass skips the scan, never an open urgent finding, and is recorded with its reason. diff --git a/docs/reference/cli/platform-zero-trust.md b/docs/reference/cli/platform-zero-trust.md index 20d29a4e3..0a3add818 100644 --- a/docs/reference/cli/platform-zero-trust.md +++ b/docs/reference/cli/platform-zero-trust.md @@ -41,6 +41,8 @@ Public-only rules cannot be combined with protected project choices. To switch a already protected configuration to public-only rules, first disable it; Access may block traffic during that transition in a Default-Deny account. +`project-public` follows the same [scan before public](./platform-security.md#public-gate) rule as the project command. With it on, the project stays protected and the command reports the waiting request; use `void platform security bypass` to skip the scan. `disable` and public-only `configure` are refused while the gate is on. Turn it off first with `void platform security public-gate off`. + Mutations support `--plan`, `--yes`, and `--timeout`; use `--plan` instead of `--yes` to inspect this change without applying it. The Access management token is accepted only on standard input. Zero Trust uses the Cloudflare account that diff --git a/docs/reference/cli/platform.md b/docs/reference/cli/platform.md index 44a003a3a..2ddea10ea 100644 --- a/docs/reference/cli/platform.md +++ b/docs/reference/cli/platform.md @@ -74,5 +74,6 @@ With `--json`, results go to standard output and command errors go to standard e - [Plans and authentication configuration](./platform-config.md) - [Users, projects, and signup access](./platform-users.md) - [Project Zero Trust](./platform-zero-trust.md) +- [Security audits](./platform-security.md) - [Deployments, builds, and system operations](./platform-operations.md) - [Email administration](./platform-email.md) diff --git a/docs/reference/cli/project.md b/docs/reference/cli/project.md index ec427f8c2..f159978ef 100644 --- a/docs/reference/cli/project.md +++ b/docs/reference/cli/project.md @@ -12,6 +12,7 @@ Show deployments for the configured target. - Void targets show recent hosted deployments; `[name]` looks up a project by slug and otherwise the linked project is used. - Cloudflare targets list Worker Versions, identify the active version, and show the recorded migration count. A project name is not accepted because the Worker name comes from `cloudflare.name` in `void.config.ts`. - Owners and admins also see a warning when the platform cannot finish [replacing the project's credentials](../../guide/project-collaboration.md#change-or-remove-access). +- On a platform with [security audits](../../guide/platform/administration/security-audits.md), a `Security` line shows how many urgent findings are open, for example `Security 2 urgent open · 3 leads`. It is left out when scans are off. ## `void project link [name]` {#void-project-link-name} @@ -59,6 +60,7 @@ Inspect or override protection for a project on a Void platform: void project zero-trust status [--project ] void project zero-trust protect [--project ] void project zero-trust public [--project ] +void project zero-trust bypass --reason "" [--yes] [--project ] void project zero-trust reconcile [--project ] ``` @@ -72,6 +74,60 @@ protection change is finished; if one is refused, the owner or a project administrator can run `void project zero-trust reconcile` before you retry. These commands do not apply to direct Cloudflare deployments. +When the platform scans before a project goes public, `public` does not make the +project public at once. The project stays protected, and the command prints why +and what to do next. It exits successfully, because the request was saved. +`status` shows the open request: + +```text +Public request: Waiting for a security scan of dpl_a3f0 before acme-web goes public. It stays protected by Zero Trust until the scan passes. +``` + +A request waits for a scan, is held by urgent findings (resolve them, there is no bypass), has no usable scan result, or needs a new deploy. Running `public` again asks for a new scan. `protect` cancels the request and keeps the project protected. With `--json`, a held request prints the saved state with `"held": true`. + +`bypass` skips the scan and makes the project public. The owner or a project administrator can run it (platform administrators use `void platform security bypass`) while the request is waiting, has no result, or needs a deploy. It needs a `--reason` of up to 4,000 characters and asks for confirmation unless you pass `--yes`; `--json` and non-interactive shells require `--yes`. Every bypass is recorded and emailed to the platform administrators. A bypass never skips an open urgent finding: it is refused, and the message lists the findings to resolve first. See [Scan before a project goes public](../../guide/platform/administration/security-audits.md#scan-before-public). + +## `void project security` {#void-project-security} + +Review security audit findings for a project on a Void platform that has security audits turned on: + +```sh +void project security status +void project security list [--urgent] [--state open|resolved|all] [--severity ] [--leads] [--format sarif] +void project security show +void project security comment "" +void project security resolve ... --reason fixed|false-positive|accepted-risk --comment "" +void project security reopen --comment "" +void project security severity --comment "" +void project security scans [--limit ] +void project security scan [--client-assets] [--yes] +void project security check [] [--yes] [--no-wait] +void project security model [ | --default] [--accept-provider-notice] +void project security budget [--usd | --off] +void project security open +``` + +Every command takes `--project ` (then `VOID_PROJECT`, then the linked project) and `--json`. + +| Command | Who can run it | +| ---------------------------------------------------------------------- | --------------------------------------------------------------------- | +| `status`, `list`, `open` | Any project member. Readers see finding ids, severity and state only. | +| `show` | Any project member. Collaborators and up see title, file and details. | +| `comment` | Collaborators, admins and the owner. | +| `resolve`, `reopen`, `severity`, `scan`, `model` (set), `budget` (set) | Project admins and the owner. | +| `scans`, `check`, `budget` (show) | Collaborators, admins and the owner. | + +- `resolve` needs `--reason` and a `--comment` of up to 4,000 characters. Pass several ids to resolve them together. +- `severity` changes the severity of an open, confirmed finding and needs a `--comment` of up to 4,000 characters. Your value is what everyone sees from then on: later scans do not change it, and if you then resolve it as false-positive or accepted-risk, a scan reporting a higher severity does not reopen it (a change to its file still does). Lowering a critical or high finding to medium or below takes it out of the urgent count, as a resolve does, so it no longer holds a public request. `scan` goes back to the severity the scans report. Leads have no severity; resolved findings must be reopened first. +- `list` hides leads unless you pass `--leads`. `--format sarif` prints the list as a [SARIF 2.1.0](https://docs.oasis-open.org/sarif/sarif/v2.1.0/sarif-v2.1.0.html) file for code scanning tools, such as GitHub code scanning: `void project security list --format sarif > void-security.sarif`. Resolved findings in it are marked as suppressed. Notes go to stderr. +- `model` with a third-party model prints the provider notice. Repeat the command with `--accept-provider-notice` to accept it. +- `budget --usd` cannot exceed the platform limit. `--off` clears this project's own cap. +- `scan` runs a full scan of the live deployment. It names the model and the most the scan can cost, then asks first; `--json` and non-interactive shells need `--yes`. Monthly caps apply. `--client-assets` also reviews the sources of your client bundles, read from the source maps deployed with them (`app.js.map` next to `app.js`, or the bundle's `sourceMappingURL`). Without deployed source maps it reviews the bundles only. It sends more code, so it can cost more. +- `check` scans the code in the current folder before you deploy it. It sends only git-tracked files, as they are on disk now (uncommitted edits included); untracked files, secret-like files (`.env*`, keys, `.npmrc`), lockfiles, binaries and media stay on your machine. It lists what it sends, names the model (with the provider notice for a third-party model) and the most it can cost, then asks first; `--json` and non-interactive shells need `--yes`. Up to 10,000 files and 32 MB of code; run it from the app's folder in a large repository. It waits in the scan queue like any scan, monthly caps apply, and the command waits for the result unless you pass `--no-wait`. The result lists what it found but is not saved as project findings: it does not change the findings list, emails, or a public request. The platform keeps it for 30 days; show it again with `void project security check `. The command fails when the check ends without a result, for example when the model refuses it. +- `open` prints a page link that works for 15 minutes and opens it in a browser when run in a terminal. On the page, members can do what the commands above allow their role: comment, resolve, pick the model, set the budget, and bypass a held public request. + +On a platform without security audits, these commands tell you to ask the administrator to upgrade. They do not apply to direct Cloudflare deployments. + ## `void project token ` {#void-project-token-create-list-renew-revoke} Manage revocable `aud: deploy` credentials for one Void platform project. The diff --git a/packages/platform/package.json b/packages/platform/package.json index 19db54c9d..59914ff30 100644 --- a/packages/platform/package.json +++ b/packages/platform/package.json @@ -40,6 +40,22 @@ "./browser-page": { "types": "./dist/browser-page.d.mts", "import": "./dist/browser-page.mjs" + }, + "./security-models": { + "types": "./dist/security-models.d.mts", + "import": "./dist/security-models.mjs" + }, + "./security-policy": { + "types": "./dist/security-policy.d.mts", + "import": "./dist/security-policy.mjs" + }, + "./security-local-check": { + "types": "./dist/security-local-check.d.mts", + "import": "./dist/security-local-check.mjs" + }, + "./security-lockfile": { + "types": "./dist/security-lockfile.d.mts", + "import": "./dist/security-lockfile.mjs" } }, "publishConfig": { diff --git a/packages/platform/scripts/build-runtime.mjs b/packages/platform/scripts/build-runtime.mjs index 413440639..e71232813 100644 --- a/packages/platform/scripts/build-runtime.mjs +++ b/packages/platform/scripts/build-runtime.mjs @@ -5,6 +5,7 @@ import { tmpdir } from 'node:os'; import { fileURLToPath, pathToFileURL } from 'node:url'; import { basename, dirname, join } from 'pathslash'; import { buildSandboxController } from '../../../platform/packages/api/scripts/build-sandbox-controller.mjs'; +import { buildSecurityScannerController } from '../../../platform/packages/api/scripts/build-security-scanner-controller.mjs'; const packageRoot = join(dirname(fileURLToPath(import.meta.url)), '..'); const repositoryRoot = join(packageRoot, '..', '..'); @@ -78,6 +79,7 @@ try { const adminStyleContents = readFileSync(adminStyleAsset); const artifacts = {}; const controller = buildSandboxController(temporaryRoot); + const scannerController = await buildSecurityScannerController(temporaryRoot); for (const [name, entrypoint] of workers) { const configPath = join(temporaryRoot, `${name}.json`); @@ -89,7 +91,12 @@ try { main: entrypoint, alias: { ...sourceAliases, - ...(name === 'api' ? { 'void:sandbox-controller-source': controller.modulePath } : {}), + ...(name === 'api' + ? { + 'void:sandbox-controller-source': controller.modulePath, + 'void:security-scanner-controller-source': scannerController.modulePath, + } + : {}), }, compatibility_date: '2026-02-24', compatibility_flags: @@ -158,6 +165,7 @@ try { deploymentExecution: 1, appAccessSetup: 1, runtimeLogs: 1, + securityAudits: 1, storageLocationHint: 1, emailProtocolVersion: 1, database, diff --git a/packages/platform/src/discovery.ts b/packages/platform/src/discovery.ts index 7eb34b319..623cc1b59 100644 --- a/packages/platform/src/discovery.ts +++ b/packages/platform/src/discovery.ts @@ -8,6 +8,7 @@ import { parseUsageProtocolVersion } from './installation.ts'; import { normalizeApplicationDomain, normalizePlatformDashboardUrl, + readPlatformCapability, type PlatformCapabilities, } from './manifest.ts'; import { assertRecord, record } from './validate.ts'; @@ -176,10 +177,11 @@ export function parsePlatformDiscoveryDocument(value: unknown): PlatformDiscover 'googleOAuth', 'managedBuilds', 'sandbox', + 'securityAudits', ]; const parsedCapabilities = {} as Record; for (const name of capabilityNames) { - const enabled = capabilities[name]; + const enabled = readPlatformCapability(capabilities, name); if (typeof enabled !== 'boolean') { throw new Error(`capabilities.${name} must be a boolean.`); } diff --git a/packages/platform/src/index.ts b/packages/platform/src/index.ts index b34b4fc1c..d53dbe296 100644 --- a/packages/platform/src/index.ts +++ b/packages/platform/src/index.ts @@ -48,6 +48,8 @@ export { normalizeInstallationSlug, platformDashboardUrl, parsePlatformDeploymentManifest, + readPlatformCapability, + serializePlatformCapabilities, type PlatformApplicationRoute, type PlatformAppAccess, type PlatformCapabilities, diff --git a/packages/platform/src/installer.ts b/packages/platform/src/installer.ts index b8e60b73c..05470e391 100644 --- a/packages/platform/src/installer.ts +++ b/packages/platform/src/installer.ts @@ -45,6 +45,8 @@ export type PlatformRuntimeManifest = Readonly<{ /** The runtime honours `runtimeLogs: minimal` (PLATFORM_RUNTIME_LOGS). */ runtimeLogs?: 1; storageLocationHint?: 1; + /** The runtime ships the `SecurityScanScheduler` class and reads `capabilities.securityAudits`. */ + securityAudits?: 1; /** Durable deployment Queue payload and PostgreSQL operation journal contract. */ deploymentExecution?: 1; authenticationProtocolVersion?: 1; @@ -114,6 +116,9 @@ export function parsePlatformRuntimeManifest(value: unknown): PlatformRuntimeMan if (root.runtimeLogs !== undefined && root.runtimeLogs !== 1) { throw new Error('Unsupported runtime logs protocol.'); } + if (root.securityAudits !== undefined && root.securityAudits !== 1) { + throw new Error('Unsupported security audits protocol.'); + } if (root.deploymentExecution !== undefined && root.deploymentExecution !== 1) { throw new Error('Unsupported deployment execution protocol.'); } @@ -235,6 +240,7 @@ export function parsePlatformRuntimeManifest(value: unknown): PlatformRuntimeMan ...(root.appAccessSetup === 1 ? { appAccessSetup: 1 as const } : {}), ...(root.storageLocationHint === 1 ? { storageLocationHint: 1 as const } : {}), ...(root.runtimeLogs === 1 ? { runtimeLogs: 1 as const } : {}), + ...(root.securityAudits === 1 ? { securityAudits: 1 as const } : {}), ...(root.deploymentExecution === 1 ? { deploymentExecution: 1 as const } : {}), ...(assets ? { assets } : {}), ...(root.authenticationProtocolVersion === 1 diff --git a/packages/platform/src/manifest.ts b/packages/platform/src/manifest.ts index 1b24c42ec..a4e3f2858 100644 --- a/packages/platform/src/manifest.ts +++ b/packages/platform/src/manifest.ts @@ -14,6 +14,11 @@ export type PlatformCapabilities = Readonly<{ googleOAuth: boolean; managedBuilds: boolean; sandbox: boolean; + /** + * The installation may run security audits. Optional in stored documents: + * missing means `false`. `true` requires deployment schema version 7. + */ + securityAudits: boolean; }>; export type PlatformControlPlane = Readonly<{ @@ -75,7 +80,11 @@ export type PlatformDeploymentManifest = Readonly<{ runtimeLogs?: PlatformRuntimeLogs; /** Requires schema version 6 so older CLIs cannot silently drop this setting. */ storageLocationHint?: R2LocationHint; - schemaVersion: typeof PLATFORM_DEPLOYMENT_SCHEMA_VERSION | 2 | 3 | 4 | 5 | 6; + /** + * Version 7 means `capabilities.securityAudits` is on, so an older CLI refuses + * the manifest instead of dropping the capability. + */ + schemaVersion: typeof PLATFORM_DEPLOYMENT_SCHEMA_VERSION | 2 | 3 | 4 | 5 | 6 | 7; }>; export type PlatformDeploymentManifestInput = Readonly<{ @@ -117,8 +126,39 @@ const CORE_CAPABILITIES: PlatformCapabilities = { googleOAuth: false, managedBuilds: false, sandbox: false, + securityAudits: false, }; +/** Capabilities that older documents may omit; a missing value means `false`. */ +const OPTIONAL_CAPABILITIES: ReadonlySet = new Set(['securityAudits']); + +/** + * Reads one capability from an untrusted record. An optional capability that + * older documents omit reads as `false`; anything else is returned unchanged + * for the caller to validate. + */ +export function readPlatformCapability( + record: Readonly>, + name: keyof PlatformCapabilities, +): unknown { + const value = record[name]; + return value === undefined && OPTIONAL_CAPABILITIES.has(name) ? false : value; +} + +/** + * `PLATFORM_CAPABILITIES` for the platform Workers. An optional capability that + * is off is left out, so an installation without it gets the same value as before. + */ +export function serializePlatformCapabilities(capabilities: PlatformCapabilities): string { + return JSON.stringify( + Object.fromEntries( + Object.entries(capabilities).filter( + ([key, value]) => value || !OPTIONAL_CAPABILITIES.has(key as keyof PlatformCapabilities), + ), + ), + ); +} + const CONTROL_PLANE_DEFAULTS: PlatformControlPlane = { apiHostname: null, dashboardHostname: null, @@ -349,17 +389,19 @@ export function createPlatformDeploymentManifest( resources, ...(input.runtimeLogs ? { runtimeLogs: input.runtimeLogs } : {}), ...(input.storageLocationHint ? { storageLocationHint: input.storageLocationHint } : {}), - schemaVersion: input.storageLocationHint - ? 6 - : input.runtimeLogs - ? 5 - : input.appAccess !== undefined - ? 4 - : configurable - ? 3 - : workersDev - ? 2 - : PLATFORM_DEPLOYMENT_SCHEMA_VERSION, + schemaVersion: capabilities.securityAudits + ? 7 + : input.storageLocationHint + ? 6 + : input.runtimeLogs + ? 5 + : input.appAccess !== undefined + ? 4 + : configurable + ? 3 + : workersDev + ? 2 + : PLATFORM_DEPLOYMENT_SCHEMA_VERSION, }; createApplicationRoutes(manifest.application); for (const [key, value] of Object.entries(manifest.controlPlane)) { @@ -390,7 +432,8 @@ export function parsePlatformDeploymentManifest(value: unknown): PlatformDeploym value.schemaVersion !== 3 && value.schemaVersion !== 4 && value.schemaVersion !== 5 && - value.schemaVersion !== 6 + value.schemaVersion !== 6 && + value.schemaVersion !== 7 ) { throw new Error( `Unsupported platform deployment schema version: ${String(value.schemaVersion)}.`, @@ -425,12 +468,18 @@ export function parsePlatformDeploymentManifest(value: unknown): PlatformDeploym const capabilityKeys = Object.keys(CORE_CAPABILITIES) as Array; const capabilities: Partial> = {}; for (const key of capabilityKeys) { - const entry = rawCapabilities[key]; + const entry = readPlatformCapability(rawCapabilities, key); if (typeof entry !== 'boolean') { throw new Error(`capabilities.${key} must be a boolean.`); } capabilities[key] = entry; } + if (capabilities.securityAudits && Number(value.schemaVersion) < 7) { + throw new Error('Security audits require deployment schema version 7.'); + } + if (value.schemaVersion === 7 && !capabilities.securityAudits) { + throw new Error('Deployment schema version 7 requires capabilities.securityAudits.'); + } const providers = authentication.providers; if ( !Array.isArray(providers) || @@ -469,7 +518,7 @@ export function parsePlatformDeploymentManifest(value: unknown): PlatformDeploym if ( value.schemaVersion === 5 ? value.runtimeLogs !== 'minimal' - : value.schemaVersion === 6 + : Number(value.schemaVersion) >= 6 ? value.runtimeLogs !== undefined && value.runtimeLogs !== 'minimal' : value.runtimeLogs !== undefined ) { @@ -478,7 +527,9 @@ export function parsePlatformDeploymentManifest(value: unknown): PlatformDeploym if ( value.schemaVersion === 6 ? !isR2LocationHint(value.storageLocationHint) - : value.storageLocationHint !== undefined + : value.schemaVersion === 7 + ? value.storageLocationHint !== undefined && !isR2LocationHint(value.storageLocationHint) + : value.storageLocationHint !== undefined ) { throw new Error( 'storageLocationHint requires deployment schema version 6 and a valid R2 location hint.', @@ -541,7 +592,7 @@ export function parsePlatformDeploymentManifest(value: unknown): PlatformDeploym installationSlug: requiredString(value.installationSlug, 'installationSlug'), resources, ...(value.runtimeLogs === 'minimal' ? { runtimeLogs: 'minimal' as const } : {}), - ...(value.schemaVersion === 6 + ...(Number(value.schemaVersion) >= 6 && value.storageLocationHint !== undefined ? { storageLocationHint: value.storageLocationHint as R2LocationHint } : {}), }); diff --git a/packages/platform/src/security-local-check.ts b/packages/platform/src/security-local-check.ts new file mode 100644 index 000000000..575d8b293 --- /dev/null +++ b/packages/platform/src/security-local-check.ts @@ -0,0 +1,271 @@ +/** + * Local tree checks (`void project security check`, design doc 0095 M32), shared by + * the CLI that packs the tree and the platform API that reads it. + * + * git-tracked files ─► securityInputFilter ─► secret: never sent, counted + * └► skipped: never sent (lockfiles, binaries…) + * the rest ─► securityLocalTreeTar (ustar, `tree/` top folder) ─► gzip ─► one R2 PUT + * + * The same filter runs on every scan input on the platform side, so a file the CLI + * would never send is also never read from a deployed bundle. + */ + +/** + * - `secret`: secret-like files, always dropped and listed in the coverage notes + * (`.env*`, `*.pem`, `*.key`, `id_*` key files, `*.p12`, `.npmrc`, `.git*`). + * - `skipped`: lockfiles, `.void/` generated files, `.d.ts`, binaries, images, + * fonts and wasm. Out of scope, not counted as dropped code. + * + * Plain string checks on the path, no regex. Never drop first-party code because it + * looks minified. + */ +export type SecurityInputFilter = 'secret' | 'skipped'; + +const LOCKFILES = new Set([ + 'package-lock.json', + 'npm-shrinkwrap.json', + 'pnpm-lock.yaml', + 'yarn.lock', + 'bun.lock', + 'bun.lockb', + 'deno.lock', +]); + +const SKIPPED_EXTENSIONS = new Set([ + // binaries and archives + 'wasm', + 'exe', + 'dll', + 'so', + 'dylib', + 'node', + 'bin', + 'dat', + 'zip', + 'gz', + 'tgz', + 'br', + 'zst', + 'tar', + '7z', + 'pdf', + // images + 'png', + 'jpg', + 'jpeg', + 'gif', + 'webp', + 'avif', + 'ico', + 'bmp', + 'tif', + 'tiff', + 'heic', + // fonts + 'woff', + 'woff2', + 'ttf', + 'otf', + 'eot', + // media + 'mp3', + 'mp4', + 'webm', + 'ogg', + 'wav', + 'mov', +]); + +const SECRET_EXTENSIONS = new Set(['pem', 'key', 'p12', 'pfx']); + +function baseName(path: string): string { + const slash = path.lastIndexOf('/'); + return slash === -1 ? path : path.slice(slash + 1); +} + +function extension(name: string): string { + const dot = name.lastIndexOf('.'); + return dot <= 0 ? '' : name.slice(dot + 1).toLowerCase(); +} + +/** + * `id_*` names an SSH key file (`id_rsa`, `id_ed25519.pub`), not code: it matches + * only with no extension or `.pub`, so `id_utils.ts` stays. + */ +function isKeyFileName(name: string): boolean { + if (!name.startsWith('id_')) { + return false; + } + const dot = name.indexOf('.'); + return dot === -1 || name.slice(dot) === '.pub'; +} + +export function securityInputFilter(path: string): SecurityInputFilter | null { + const segments = path.split('/'); + const name = baseName(path); + const lower = name.toLowerCase(); + for (const segment of segments) { + if (segment.startsWith('.git')) { + return 'secret'; + } + } + if ( + lower.startsWith('.env') || + lower === '.npmrc' || + SECRET_EXTENSIONS.has(extension(lower)) || + isKeyFileName(lower) + ) { + return 'secret'; + } + if (segments.includes('.void')) { + return 'skipped'; + } + if (LOCKFILES.has(lower)) { + return 'skipped'; + } + if (lower.endsWith('.d.ts') || lower.endsWith('.d.mts') || lower.endsWith('.d.cts')) { + return 'skipped'; + } + if (SKIPPED_EXTENSIONS.has(extension(lower))) { + return 'skipped'; + } + return null; +} + +/** + * What one local check may send. The CLI checks them before it uploads; the API + * checks the declared sizes when it signs the upload, and the real ones while it reads. + */ +export const SECURITY_LOCAL_CHECK_LIMITS: Readonly<{ + maxFiles: number; + maxBytes: number; + maxArchiveBytes: number; +}> = { + /** Files in the tree. */ + maxFiles: 10_000, + /** Their bytes, uncompressed (what one scan input can hold). */ + maxBytes: 32 * 1024 * 1024, + /** The gzip archive. */ + maxArchiveBytes: 32 * 1024 * 1024, +}; + +/** The archive's top folder; the reader cuts it off, as for a GitHub tarball. */ +export const SECURITY_LOCAL_TREE_ROOT = 'tree'; + +/** + * Whether `path` (relative to the project folder) can go in the archive: no empty, + * `.` or `..` part, no leading `/`, no control character or backslash. + */ +export function isSecurityLocalTreePath(path: string): boolean { + if (path.length === 0 || path.startsWith('/')) { + return false; + } + for (const segment of path.split('/')) { + if (segment === '' || segment === '.' || segment === '..') { + return false; + } + } + for (let index = 0; index < path.length; index++) { + const code = path.charCodeAt(index); + if (code < 0x20 || code === 0x7f || code === 0x5c) { + return false; + } + } + return true; +} + +const BLOCK = 512; +const encoder = new TextEncoder(); + +function writeString(block: Uint8Array, offset: number, length: number, text: string): void { + block.set(encoder.encode(text).subarray(0, length), offset); +} + +function writeOctal(block: Uint8Array, offset: number, length: number, value: number): void { + writeString(block, offset, length, `${value.toString(8).padStart(length - 1, '0')}\0`); +} + +function header(name: string, size: number, type: '0' | 'x'): Uint8Array { + const block = new Uint8Array(BLOCK); + writeString(block, 0, 100, name); + writeOctal(block, 100, 8, 0o644); + writeOctal(block, 108, 8, 0); + writeOctal(block, 116, 8, 0); + writeOctal(block, 124, 12, size); + writeOctal(block, 136, 12, 0); + block.fill(0x20, 148, 156); + block[156] = type.charCodeAt(0); + writeString(block, 257, 6, 'ustar\0'); + writeString(block, 263, 2, '00'); + let sum = 0; + for (const byte of block) { + sum += byte; + } + writeString(block, 148, 8, `${sum.toString(8).padStart(6, '0')}\0 `); + return block; +} + +/** ` path=\n`, where length counts the whole record. */ +function paxPathRecord(path: string): Uint8Array { + const body = ` path=${path}\n`; + const bodyLength = encoder.encode(body).length; + let length = bodyLength + 1; + while (String(length).length + bodyLength !== length) { + length = String(length).length + bodyLength; + } + return encoder.encode(`${length}${body}`); +} + +function isPlainAscii(text: string): boolean { + for (let index = 0; index < text.length; index++) { + if (text.charCodeAt(index) > 0x7e) { + return false; + } + } + return true; +} + +export type SecurityLocalTreeFile = Readonly<{ path: string; data: Uint8Array }>; + +/** + * The tree as one uncompressed ustar archive under `tree/`. A long or non-ASCII name + * gets a pax `path` record. Throws on a path `isSecurityLocalTreePath` refuses. + */ +export function securityLocalTreeTar(files: ReadonlyArray): Uint8Array { + const chunks: Array = []; + let total = 0; + const push = (chunk: Uint8Array) => { + chunks.push(chunk); + total += chunk.length; + }; + const pad = (size: number) => { + const rest = size % BLOCK; + if (rest !== 0) { + push(new Uint8Array(BLOCK - rest)); + } + }; + for (const file of files) { + if (!isSecurityLocalTreePath(file.path)) { + throw new Error(`security check: ${JSON.stringify(file.path)} is not a usable path`); + } + let name = `${SECURITY_LOCAL_TREE_ROOT}/${file.path}`; + if (encoder.encode(name).length > 99 || !isPlainAscii(name)) { + const record = paxPathRecord(name); + push(header('PaxHeader', record.length, 'x')); + push(record); + pad(record.length); + name = `${SECURITY_LOCAL_TREE_ROOT}/pax-entry`; + } + push(header(name, file.data.length, '0')); + push(file.data); + pad(file.data.length); + } + push(new Uint8Array(BLOCK * 2)); + const out = new Uint8Array(total); + let at = 0; + for (const chunk of chunks) { + out.set(chunk, at); + at += chunk.length; + } + return out; +} diff --git a/packages/platform/src/security-lockfile.ts b/packages/platform/src/security-lockfile.ts new file mode 100644 index 000000000..3cdec8521 --- /dev/null +++ b/packages/platform/src/security-lockfile.ts @@ -0,0 +1,318 @@ +/** + * Third-party code by package identity (security audits, design doc 0095 M10), shared by + * the CLI that reads the project's lockfile at deploy and the platform API that drops + * registry packages from a scan input. + * + * source path ─► package name (after the last `node_modules/`) + * lockfile ─► name → registry | local + * pnpm-lock.yaml: `importers` (direct) + `packages` (every resolved package) + * package-lock.json / npm-shrinkwrap.json: `packages["node_modules/…"]` + * + * A package seen as both local and registry is local: code that may be the owner's is + * never dropped. Hand-written readers, no YAML library and no regex. + */ + +export type SecurityPackageSource = 'registry' | 'local'; + +/** Package name → where the lockfile says it comes from. */ +export type SecurityLockfileIndex = ReadonlyMap; + +/** Lockfiles the readers understand, in the order a directory is searched. */ +export const SECURITY_LOCKFILE_NAMES: ReadonlyArray = [ + 'pnpm-lock.yaml', + 'package-lock.json', + 'npm-shrinkwrap.json', +]; + +/** Package names one deploy may claim, at most (the deploy body stays small). */ +export const SECURITY_PACKAGE_CLAIMS_MAX = 5_000; +/** npm's own limit on a package name. */ +const MAX_PACKAGE_NAME = 214; + +/** + * What a deploy sends (`securityPackages`): the packages its Worker bundle's source maps + * name, as the project's lockfile resolves them. Names it cannot place are left out. + */ +export type SecurityPackageClaims = Readonly<{ + registry: ReadonlyArray; + local: ReadonlyArray; +}>; + +/** The package a path sits in: the part after its last `node_modules/`. */ +export function packageNameOfPath(path: string): string | null { + const segments = path.split('/'); + let last = -1; + for (let index = 0; index < segments.length; index++) { + if (segments[index] === 'node_modules') { + last = index; + } + } + if (last === -1) { + return null; + } + const first = segments[last + 1]; + if (!first || first.startsWith('.')) { + return null; + } + if (first.startsWith('@')) { + const second = segments[last + 2]; + return second ? `${first}/${second}` : null; + } + return first; +} + +function sourceOfSpecifier(version: string): SecurityPackageSource { + if ( + version.startsWith('link:') || + version.startsWith('file:') || + version.startsWith('workspace:') || + version.startsWith('git') || + version.startsWith('github:') || + version.includes('://') + ) { + return 'local'; + } + return 'registry'; +} + +function record( + index: Map, + name: string, + source: SecurityPackageSource, +) { + if (index.get(name) !== 'local') { + index.set(name, source); + } +} + +/** `package-lock.json` v2/v3: `packages["node_modules/x"]` with `resolved` or `link`. */ +export function parsePackageLock(text: string): SecurityLockfileIndex | null { + let value: unknown; + try { + value = JSON.parse(text); + } catch { + return null; + } + if (typeof value !== 'object' || value === null) { + return null; + } + const packages = (value as { packages?: unknown }).packages; + if (typeof packages !== 'object' || packages === null) { + return null; + } + const index = new Map(); + for (const [key, entry] of Object.entries(packages as Record)) { + const name = packageNameOfPath(key); + if (name === null || typeof entry !== 'object' || entry === null) { + continue; + } + const { link, resolved } = entry as { link?: unknown; resolved?: unknown }; + // A registry tarball is an `https://` URL; a link, a `file:` path or a git URL is local. + const local = + link === true || + typeof resolved !== 'string' || + resolved.startsWith('file:') || + resolved.startsWith('git'); + record(index, name, local ? 'local' : 'registry'); + } + return index; +} + +function unquote(text: string): string { + if ( + text.length >= 2 && + (text[0] === "'" || text[0] === '"') && + text[text.length - 1] === text[0] + ) { + return text.slice(1, -1); + } + return text; +} + +/** + * The name in a `packages:` key: `hono@4.0.0` (v9), `/hono@4.0.0` (v6–v8), + * `'@acme/x@1.0.0(react@18.3.1)'`. `null` when there is no version part. + */ +function nameOfPnpmPackageKey(key: string): string | null { + let text = unquote(key); + if (text.startsWith('/')) { + text = text.slice(1); + } + const at = text.indexOf('@', 1); + if (at <= 0) { + return null; + } + return text.slice(0, at); +} + +/** A `resolution` that is not a registry tarball: a local folder, a `file:` tarball or git. */ +function localResolution(text: string): boolean { + return ( + text.includes('directory:') || + text.includes('tarball: file:') || + text.includes('type: git') || + text.includes('repo:') + ); +} + +/** + * `pnpm-lock.yaml` (v6–v9), read line by line from its indentation: + * + * - `importers`: each direct dependency's `version:`; `link:`/`file:` or a git URL is + * local, anything else came from the registry. + * - `packages`: every resolved package, direct or not. A `resolution` with an + * `integrity` and no folder, `file:` tarball or git repo is a registry package. + * + * Workspace packages are importers, never `packages` entries, so they stay local. + */ +export function parsePnpmLock(text: string): SecurityLockfileIndex | null { + const index = new Map(); + let top: 'importers' | 'packages' | null = null; + let section = false; + let current: string | null = null; + // `packages`: the entry being read and its resolution text (one line or nested lines). + let entry: string | null = null; + let resolution: string | null = null; + let nested = false; + const closeEntry = () => { + if (entry !== null && resolution !== null) { + record(index, entry, localResolution(resolution) ? 'local' : 'registry'); + } + entry = null; + resolution = null; + nested = false; + }; + for (const raw of text.split('\n')) { + const line = raw.endsWith('\r') ? raw.slice(0, -1) : raw; + if (line.trim() === '' || line.trimStart().startsWith('#')) { + continue; + } + const indent = line.length - line.trimStart().length; + const content = line.trim(); + if (indent === 0) { + closeEntry(); + top = content === 'importers:' ? 'importers' : content === 'packages:' ? 'packages' : null; + section = false; + current = null; + continue; + } + if (top === 'packages') { + if (indent === 2) { + closeEntry(); + if (content.endsWith(':')) { + entry = nameOfPnpmPackageKey(content.slice(0, -1)); + } + continue; + } + if (entry === null) { + continue; + } + if (indent === 4) { + nested = false; + if (content.startsWith('resolution:')) { + resolution = content.slice('resolution:'.length).trim(); + // `resolution:` alone: its fields follow on deeper lines. + nested = resolution === ''; + } + continue; + } + if (nested && resolution !== null) { + resolution += ` ${content}`; + } + continue; + } + if (top !== 'importers') { + continue; + } + if (indent === 4) { + section = + content === 'dependencies:' || + content === 'devDependencies:' || + content === 'optionalDependencies:'; + current = null; + continue; + } + if (!section) { + continue; + } + if (indent === 6 && content.endsWith(':')) { + current = unquote(content.slice(0, -1)); + continue; + } + if (indent === 8 && current !== null && content.startsWith('version:')) { + record(index, current, sourceOfSpecifier(unquote(content.slice('version:'.length).trim()))); + } + } + closeEntry(); + return index.size > 0 ? index : null; +} + +/** Reads a lockfile by its file name; `null` for a name or text it does not understand. */ +export function parseSecurityLockfile( + fileName: string, + text: string, +): SecurityLockfileIndex | null { + const base = fileName.slice(fileName.lastIndexOf('/') + 1); + if (base === 'pnpm-lock.yaml') { + return parsePnpmLock(text); + } + if (base === 'package-lock.json' || base === 'npm-shrinkwrap.json') { + return parsePackageLock(text); + } + return null; +} + +/** The claims a deploy sends for `names` (the packages its source maps name). */ +export function securityPackageClaims( + index: SecurityLockfileIndex, + names: Iterable, +): SecurityPackageClaims { + const registry: Array = []; + const local: Array = []; + for (const name of new Set(names)) { + const source = index.get(name); + if (source === 'registry') { + registry.push(name); + } else if (source === 'local') { + local.push(name); + } + } + return { registry: registry.sort(), local: local.sort() }; +} + +function validName(value: unknown): value is string { + return ( + typeof value === 'string' && + value.length > 0 && + value.length <= MAX_PACKAGE_NAME && + packageNameOfPath(`node_modules/${value}/x`) === value + ); +} + +/** + * The server reads a deploy's `securityPackages` back into an index; `null` for anything + * malformed or too long (the scan then keeps third-party code, ranked last). + */ +export function parseSecurityPackageClaims(value: unknown): SecurityLockfileIndex | null { + if (typeof value !== 'object' || value === null || Array.isArray(value)) { + return null; + } + const { registry, local } = value as { registry?: unknown; local?: unknown }; + if (!Array.isArray(registry) || !Array.isArray(local)) { + return null; + } + if (registry.length + local.length > SECURITY_PACKAGE_CLAIMS_MAX) { + return null; + } + if (!registry.every(validName) || !local.every(validName)) { + return null; + } + const index = new Map(); + for (const name of registry) { + record(index, name, 'registry'); + } + for (const name of local) { + record(index, name, 'local'); + } + return index; +} diff --git a/packages/platform/src/security-models.ts b/packages/platform/src/security-models.ts new file mode 100644 index 000000000..1e2ab956d --- /dev/null +++ b/packages/platform/src/security-models.ts @@ -0,0 +1,255 @@ +/** + * The models a security audit scan can run on, shared by the platform API (scheduler, + * model proxy, budget, picker) and the CLI. This is the only list: a platform release + * updates it when models or prices change. + * + * Prices are list prices in USD per million tokens. The spend meter and the scan + * reserve use them; a model without a price cannot be picked until one is filled in. + */ + +/** How the scanner runs a model (spec §8.1). Stored on `security_scans.engine`. */ +export type SecurityEngine = 'void_loop' | 'agent_sdk' | 'codex_sdk'; + +/** Who runs the model. `workers-ai` is Cloudflare; the others are reached through AI Gateway. */ +export type SecurityModelHost = 'workers-ai' | 'openai' | 'anthropic'; + +/** Hosts checked one by one by probe check 5 and named in the provider notice. */ +export type SecurityThirdPartyHost = 'openai' | 'anthropic'; + +export type SecurityRefusalRisk = 'low' | 'medium' | 'medium-high'; + +export const SECURITY_MODEL_IDS = [ + '@cf/deepseek-ai/deepseek-v4.1-flash-1017', + '@cf/zai-org/glm-5.3', + 'openai/gpt-6.1-terra', + 'openai/gpt-6.1-sol', + 'anthropic/claude-sonnet-5.5', + 'anthropic/claude-opus-5.5', +] as const; + +export type SecurityModelId = (typeof SECURITY_MODEL_IDS)[number]; + +/** The installation default when the policy names none. */ +export const DEFAULT_SECURITY_MODEL: SecurityModelId = '@cf/deepseek-ai/deepseek-v4.1-flash-1017'; + +export type SecurityModelPrice = Readonly<{ + /** USD per million input tokens. */ + inputUsdPerMillion: number; + /** USD per million output tokens. */ + outputUsdPerMillion: number; +}>; + +export type SecurityModel = Readonly<{ + id: SecurityModelId; + host: SecurityModelHost; + engine: SecurityEngine; + /** Zero data retention listed in the AI Gateway catalog. */ + zeroDataRetention: boolean; + refusalRisk: SecurityRefusalRisk; + /** `null` until the list price is known; the model cannot be picked without it. */ + price: SecurityModelPrice | null; +}>; + +/** In `SECURITY_MODEL_IDS` order, so the first `@cf/*` entry is the fallback model. */ +export const SECURITY_MODELS: ReadonlyArray = [ + { + id: '@cf/deepseek-ai/deepseek-v4.1-flash-1017', + host: 'workers-ai', + engine: 'void_loop', + zeroDataRetention: true, + refusalRisk: 'low', + price: { inputUsdPerMillion: 0.3, outputUsdPerMillion: 1.2 }, + }, + { + id: '@cf/zai-org/glm-5.3', + host: 'workers-ai', + engine: 'void_loop', + zeroDataRetention: true, + refusalRisk: 'low', + price: { inputUsdPerMillion: 1.4, outputUsdPerMillion: 4.4 }, + }, + { + id: 'openai/gpt-6.1-terra', + host: 'openai', + engine: 'codex_sdk', + zeroDataRetention: true, + refusalRisk: 'medium-high', + // Short-context price. + price: { inputUsdPerMillion: 1, outputUsdPerMillion: 5 }, + }, + { + id: 'openai/gpt-6.1-sol', + host: 'openai', + engine: 'codex_sdk', + zeroDataRetention: true, + refusalRisk: 'medium-high', + // Short-context price. + price: { inputUsdPerMillion: 2, outputUsdPerMillion: 10 }, + }, + { + id: 'anthropic/claude-sonnet-5.5', + host: 'anthropic', + engine: 'agent_sdk', + // The catalog shows no ZDR badge, so it is treated as not ZDR. + zeroDataRetention: false, + refusalRisk: 'medium', + // The list price is not known yet (design doc 0095, R6). Until it is, the model + // is listed but cannot be picked. + price: null, + }, + { + id: 'anthropic/claude-opus-5.5', + host: 'anthropic', + engine: 'agent_sdk', + zeroDataRetention: true, + refusalRisk: 'medium', + price: { inputUsdPerMillion: 4, outputUsdPerMillion: 20 }, + }, +]; + +/** Display names used in the provider notice and in copy. */ +export const SECURITY_PROVIDER_NAMES: Readonly> = { + 'workers-ai': 'Cloudflare', + openai: 'OpenAI', + anthropic: 'Anthropic', +}; + +/** + * Version of the provider notice text below. Bump it when the text changes: a stored + * acceptance with an older version no longer counts, so admins and projects are asked again. + */ +export const SECURITY_PROVIDER_NOTICE_VERSION = 1; + +/** Token counts a scan reserve is computed from when no limits are given (spec §16.1). */ +export const SECURITY_RESERVE_INPUT_TOKENS = 1_200_000; +export const SECURITY_RESERVE_OUTPUT_TOKENS = 120_000; + +export function isSecurityModelId(value: unknown): value is SecurityModelId { + return SECURITY_MODEL_IDS.some((id) => id === value); +} + +export function getSecurityModel(id: SecurityModelId): SecurityModel { + const model = SECURITY_MODELS.find((entry) => entry.id === id); + if (!model) { + throw new Error(`Unknown security model: ${id}.`); + } + return model; +} + +/** Third-party host of a model, or `null` for Cloudflare-hosted models. */ +export function securityModelThirdPartyHost(id: SecurityModelId): SecurityThirdPartyHost | null { + const host = getSecurityModel(id).host; + return host === 'workers-ai' ? null : host; +} + +export function isThirdPartySecurityModel(id: SecurityModelId): boolean { + return securityModelThirdPartyHost(id) !== null; +} + +/** + * A model is listed but not pickable while its price is unknown: the spend meter and + * the caps need a price for every model that can run. + */ +export function isSecurityModelPriced(id: SecurityModelId): boolean { + return getSecurityModel(id).price !== null; +} + +/** + * Up to three badges for the picker (spec §8.2); the refusal badge only when refusal + * risk is not low. + */ +export function securityModelBadges(id: SecurityModelId): ReadonlyArray { + const model = getSecurityModel(id); + const badges = [ + model.host === 'workers-ai' ? 'Cloudflare-hosted' : 'Third-party', + model.zeroDataRetention ? 'Zero data retention' : 'No ZDR listed', + ]; + if (model.refusalRisk !== 'low') { + badges.push('May refuse security reviews'); + } + return badges; +} + +// Prices are kept as whole nano-dollars per token (USD per million × 1000), so costs +// add up in integers and a sum of many calls does not drift. +function nanoUsdPerToken(usdPerMillion: number): number { + return Math.round(usdPerMillion * 1000); +} + +function assertTokenCount(value: number, label: string): void { + if (!Number.isSafeInteger(value) || value < 0) { + throw new Error(`${label} must be a nonnegative safe integer.`); + } +} + +/** + * Cost of `inputTokens` and `outputTokens` at the model's list price, in whole + * nano-dollars. `null` when the model has no price. + */ +export function securityModelCostNanoUsd( + id: SecurityModelId, + inputTokens: number, + outputTokens: number, +): number | null { + assertTokenCount(inputTokens, 'inputTokens'); + assertTokenCount(outputTokens, 'outputTokens'); + const price = getSecurityModel(id).price; + if (!price) { + return null; + } + return ( + inputTokens * nanoUsdPerToken(price.inputUsdPerMillion) + + outputTokens * nanoUsdPerToken(price.outputUsdPerMillion) + ); +} + +/** The same cost in USD. `null` when the model has no price. */ +export function securityModelCostUsd( + id: SecurityModelId, + inputTokens: number, + outputTokens: number, +): number | null { + const nano = securityModelCostNanoUsd(id, inputTokens, outputTokens); + return nano === null ? null : nano / 1_000_000_000; +} + +/** + * Worst-case cost of one scan, reserved against the caps when the scan starts: + * `maxInputTokens × input price + maxOutputTokens × output price` (spec §16.1). + * Defaults to the default policy limits. `null` when the model has no price. + */ +export function securityScanReserveUsd( + id: SecurityModelId, + limits: Readonly<{ maxInputTokens: number; maxOutputTokens: number }> = { + maxInputTokens: SECURITY_RESERVE_INPUT_TOKENS, + maxOutputTokens: SECURITY_RESERVE_OUTPUT_TOKENS, + }, +): number | null { + return securityModelCostUsd(id, limits.maxInputTokens, limits.maxOutputTokens); +} + +/** + * The provider notice (spec §8.3), shown before a third-party model is used. The same + * text goes to the admin panel, the CLI and the project page. Changing it needs a + * `SECURITY_PROVIDER_NOTICE_VERSION` bump. + */ +export function securityProviderNotice(host: SecurityThirdPartyHost): ReadonlyArray { + const provider = SECURITY_PROVIDER_NAMES[host]; + return [ + `This model is run by ${provider}, not by Cloudflare.`, + `Scans with this model send this project's changed code, the files it uses from this project, past findings and comments to ${provider} through Cloudflare AI Gateway. ${provider}'s own usage policy and safety filters apply.`, + `${provider} may refuse to review code that looks security-related, even when the review is harmless. A refused scan shows as Refused, never as passed, and records no findings. The next deploy's scan covers the same changes.`, + `${provider} may keep request data for a limited time, for example for abuse checks. Cloudflare-hosted models (@cf/…) do not keep or train on your code.`, + 'Scans run only on code this project deploys. Pick this model only if you own the code or may have it reviewed.', + 'Policies: anthropic.com/legal/aup · openai.com/policies/usage-policies · developers.cloudflare.com/workers-ai/platform/data-usage', + ]; +} + +/** One-line form for deploy output, `status` and the findings email. */ +export function securityProviderNoticeShort(id: SecurityModelId): string | null { + const host = securityModelThirdPartyHost(id); + if (!host) { + return null; + } + return `Model ${id} is run by ${SECURITY_PROVIDER_NAMES[host]}. Its usage policy applies and it may refuse.`; +} diff --git a/packages/platform/src/security-policy.ts b/packages/platform/src/security-policy.ts new file mode 100644 index 000000000..1c16a6a3d --- /dev/null +++ b/packages/platform/src/security-policy.ts @@ -0,0 +1,855 @@ +/** + * The installation security audit policy (spec §5.3), shared by the platform API and + * the CLI: type, defaults, the strict parser, limit ranges and the error codes the API + * returns and the CLI reads. + * + * The policy is one `platform_settings` row. The API reads the stored row with + * `readSecurityPolicy` (its lenient reader turns a throw into `disabled`) and checks a + * new policy with the strict `parseSecurityPolicy` before the revision CAS write. + */ +import { + DEFAULT_SECURITY_MODEL, + isSecurityModelId, + isSecurityModelPriced, + isThirdPartySecurityModel, + SECURITY_MODEL_IDS, + type SecurityModelId, +} from './security-models.ts'; +import { isPrintableText, record } from './validate.ts'; + +/** `platform_settings` key that holds the policy. */ +export const SECURITY_POLICY_SETTINGS_KEY = 'securityAudits.policy'; + +export const SECURITY_MODES = ['disabled', 'public', 'all'] as const; +export type SecurityMode = (typeof SECURITY_MODES)[number]; + +/** Names shown in the admin panel and CLI output. */ +export const SECURITY_MODE_LABELS: Readonly> = { + disabled: 'Off', + public: 'Public projects only', + all: 'All projects', +}; + +export type SecurityPolicyLimits = Readonly<{ + /** Running scans per installation. */ + concurrency: number; + /** Wall clock per scan, the only timeout setting. */ + timeoutMinutes: number; + maxInputTokens: number; + maxOutputTokens: number; + modelCallsPerScan: number; +}>; + +export type SecurityLimitKey = keyof SecurityPolicyLimits; + +export type SecurityLimitRange = Readonly<{ min: number; max: number; default: number }>; + +/** + * Allowed whole-number range and default of every limit. Concurrency and timeout come + * from the spec. The token and call ranges are ours: at their top, the most expensive + * priced model reserves $12 per scan. + */ +export const SECURITY_LIMIT_RANGES: Readonly> = { + concurrency: { min: 1, max: 10, default: 2 }, + timeoutMinutes: { min: 5, max: 60, default: 20 }, + maxInputTokens: { min: 50_000, max: 2_000_000, default: 1_200_000 }, + maxOutputTokens: { min: 5_000, max: 200_000, default: 120_000 }, + modelCallsPerScan: { min: 10, max: 200, default: 80 }, +}; + +export const SECURITY_LIMIT_KEYS: ReadonlyArray = [ + 'concurrency', + 'timeoutMinutes', + 'maxInputTokens', + 'maxOutputTokens', + 'modelCallsPerScan', +]; + +export type SecurityPolicyBudgets = Readonly<{ + platformCapOn: boolean; + /** Whole-installation cap in USD per calendar month (UTC). */ + platformMonthlyUsd: number; + /** Applies `projectDefaultMonthlyUsd` to every project. */ + projectCapsOn: boolean; + projectDefaultMonthlyUsd: number; +}>; + +/** Highest USD amount a cap may be set to. */ +export const SECURITY_MAX_MONTHLY_USD = 1_000_000; + +/** + * Scheduled full sweeps (spec §20 Phase 2): every `everyDays` days the hourly job + * scans the live deployment of each project in scope in full, with the deeper + * `standard` profile. Off by default: sweeps cost money and nothing asks for them. + */ +export type SecuritySweeps = Readonly<{ + on: boolean; + everyDays: number; +}>; + +/** Allowed range of `sweeps.everyDays`. */ +export const SECURITY_SWEEP_DAYS_RANGE: SecurityLimitRange = { min: 7, max: 90, default: 30 }; + +export type SecurityThirdPartyNotice = Readonly<{ + acceptedByUserId: string; + /** ISO 8601 timestamp. */ + acceptedAt: string; + version: number; +}>; + +export type SecurityEntitlement = Readonly<{ + /** ISO 8601 timestamp of the last probe. */ + checkedAt: string; + /** Checks 1–4 passed. */ + ok: boolean; + /** Names of the failed required checks. */ + missing: ReadonlyArray; + /** Probe check 5, per third-party host. */ + hosts: Readonly<{ openai: boolean; anthropic: boolean }>; +}>; + +export type SecurityPolicy = Readonly<{ + mode: SecurityMode; + defaultModel: SecurityModelId; + blockedModels: ReadonlyArray; + thirdPartyNotice: SecurityThirdPartyNotice | null; + limits: SecurityPolicyLimits; + budgets: SecurityPolicyBudgets; + entitlement: SecurityEntitlement | null; + /** "Scan before a project goes public" (spec §5.5). */ + publicGate: boolean; + sweeps: SecuritySweeps; + /** + * Phase 2 (spec §8.5): after a third-party scan is refused, gives bad output or times + * out, scan the same deployment once more on the `@cf` default. Off by default; it + * never goes from `@cf` to a third-party model. + */ + fallbackToCf: boolean; + /** Phase 2 (spec §20): a weekly summary email to installation admins. Off by default. */ + digest: boolean; + revision: number; +}>; + +/** A fresh probe is needed to leave `disabled` or to turn the public gate on. */ +export const SECURITY_ENTITLEMENT_MAX_AGE_MS: number = 24 * 60 * 60 * 1000; + +/** + * Error codes (the `error` field) the API returns for security audits, with their HTTP + * status. The CLI matches on these strings. Capability off reuses the existing + * `platform capability unavailable` (501). + */ +export type SecurityErrorCode = + | 'security model not allowed' + | 'provider notice not accepted' + | 'security entitlement missing' + | 'finding changed' + | 'security budget above platform limit' + | 'security public gate needs zero trust' + | 'security public gate needs policy' + | 'security public gate on' + | 'no public request' + | 'public request closed' + | 'security public request has urgent findings' + | 'scan bypass reason required' + | 'security policy unreadable'; + +export type SecurityErrorName = + | 'modelNotAllowed' + | 'providerNoticeNotAccepted' + | 'entitlementMissing' + | 'findingChanged' + | 'budgetAbovePlatformLimit' + | 'publicGateNeedsZeroTrust' + | 'publicGateNeedsPolicy' + | 'publicGateOn' + | 'noPublicRequest' + | 'publicRequestClosed' + | 'publicRequestHasUrgentFindings' + | 'scanBypassReasonRequired' + | 'policyUnreadable'; + +export type SecurityError = Readonly<{ code: SecurityErrorCode; status: 409 | 422 | 503 }>; + +export const SECURITY_ERRORS: Readonly> = { + modelNotAllowed: { code: 'security model not allowed', status: 422 }, + providerNoticeNotAccepted: { code: 'provider notice not accepted', status: 422 }, + entitlementMissing: { code: 'security entitlement missing', status: 409 }, + findingChanged: { code: 'finding changed', status: 409 }, + budgetAbovePlatformLimit: { code: 'security budget above platform limit', status: 422 }, + publicGateNeedsZeroTrust: { code: 'security public gate needs zero trust', status: 409 }, + publicGateNeedsPolicy: { code: 'security public gate needs policy', status: 409 }, + publicGateOn: { code: 'security public gate on', status: 409 }, + noPublicRequest: { code: 'no public request', status: 409 }, + publicRequestClosed: { code: 'public request closed', status: 409 }, + publicRequestHasUrgentFindings: { + code: 'security public request has urgent findings', + status: 409, + }, + scanBypassReasonRequired: { code: 'scan bypass reason required', status: 422 }, + policyUnreadable: { code: 'security policy unreadable', status: 503 }, +}; + +export function isSecurityErrorCode(value: unknown): value is SecurityErrorCode { + return Object.values(SECURITY_ERRORS).some((entry) => entry.code === value); +} + +export function defaultSecurityLimits(): SecurityPolicyLimits { + return { + concurrency: SECURITY_LIMIT_RANGES.concurrency.default, + timeoutMinutes: SECURITY_LIMIT_RANGES.timeoutMinutes.default, + maxInputTokens: SECURITY_LIMIT_RANGES.maxInputTokens.default, + maxOutputTokens: SECURITY_LIMIT_RANGES.maxOutputTokens.default, + modelCallsPerScan: SECURITY_LIMIT_RANGES.modelCallsPerScan.default, + }; +} + +export function defaultSecurityBudgets(): SecurityPolicyBudgets { + return { + platformCapOn: false, + platformMonthlyUsd: 1000, + projectCapsOn: false, + projectDefaultMonthlyUsd: 100, + }; +} + +export function defaultSecuritySweeps(): SecuritySweeps { + return { on: false, everyDays: SECURITY_SWEEP_DAYS_RANGE.default }; +} + +/** `sweeps.everyDays`: a whole number of days in `SECURITY_SWEEP_DAYS_RANGE`. */ +export function parseSecuritySweepDays(value: unknown): number { + const range = SECURITY_SWEEP_DAYS_RANGE; + if ( + typeof value !== 'number' || + !Number.isSafeInteger(value) || + value < range.min || + value > range.max + ) { + throw new Error(`sweeps.everyDays must be a whole number from ${range.min} to ${range.max}.`); + } + return value; +} + +/** + * The sweep setting. A row saved before sweeps existed has none: that reads as Off. + * The strict parser checks the range. The lenient reader clamps the days into it and + * reads anything else it cannot use as Off, so bad data never starts paid scans. + */ +function parseSweeps(value: unknown, strict: boolean): SecuritySweeps { + if (value === undefined) { + return defaultSecuritySweeps(); + } + if (strict) { + const input = record(value, 'sweeps'); + return { + on: parseBoolean(input.on, 'sweeps.on'), + everyDays: parseSecuritySweepDays(input.everyDays), + }; + } + const input = + typeof value === 'object' && value !== null ? (value as Record) : {}; + const days = input.everyDays; + if (typeof input.on !== 'boolean' || typeof days !== 'number' || !Number.isSafeInteger(days)) { + return defaultSecuritySweeps(); + } + const range = SECURITY_SWEEP_DAYS_RANGE; + return { on: input.on, everyDays: Math.min(range.max, Math.max(range.min, days)) }; +} + +/** + * An on/off setting added after the first release. A row saved before it existed reads + * as Off. The strict parser refuses anything but a boolean; the lenient reader reads it + * as Off, so bad data never starts paid scans or sends mail. + */ +function parseAddedFlag(value: unknown, label: string, strict: boolean): boolean { + if (value === undefined) { + return false; + } + if (typeof value === 'boolean') { + return value; + } + if (strict) { + throw new Error(`${label} must be true or false.`); + } + return false; +} + +/** Longest webhook URL the API stores. */ +export const SECURITY_WEBHOOK_URL_MAX = 2048; + +/** + * The security webhook URL (spec §20): `https` only, no user name or password in it + * (the body is signed instead), at most `SECURITY_WEBHOOK_URL_MAX` characters. + * Returns the normalized URL. + */ +export function parseSecurityWebhookUrl(value: unknown): string { + if (typeof value !== 'string' || value.length === 0 || value.length > SECURITY_WEBHOOK_URL_MAX) { + throw new Error( + `The webhook URL must be an https URL of at most ${SECURITY_WEBHOOK_URL_MAX} characters.`, + ); + } + let url: URL; + try { + url = new URL(value); + } catch { + throw new Error('The webhook URL must be an https URL.'); + } + if (url.protocol !== 'https:' || url.hostname === '') { + throw new Error('The webhook URL must be an https URL.'); + } + if (url.username !== '' || url.password !== '') { + throw new Error('The webhook URL must not hold a user name or password.'); + } + if (url.hash !== '') { + throw new Error('The webhook URL must not have a #fragment.'); + } + return url.href; +} + +/** The policy of an installation that never saved one: Off, nothing accepted or probed. */ +export function defaultSecurityPolicy(): SecurityPolicy { + return { + mode: 'disabled', + defaultModel: DEFAULT_SECURITY_MODEL, + blockedModels: [], + thirdPartyNotice: null, + limits: defaultSecurityLimits(), + budgets: defaultSecurityBudgets(), + entitlement: null, + publicGate: false, + sweeps: defaultSecuritySweeps(), + fallbackToCf: false, + digest: false, + revision: 0, + }; +} + +export function isSecurityMode(value: unknown): value is SecurityMode { + return SECURITY_MODES.some((mode) => mode === value); +} + +export function parseSecurityMode(value: unknown): SecurityMode { + if (!isSecurityMode(value)) { + throw new Error('Security audit mode must be disabled, public or all.'); + } + return value; +} + +export function parseSecurityModelId(value: unknown, label = 'Model'): SecurityModelId { + if (!isSecurityModelId(value)) { + throw new Error(`${label} must be one of: ${SECURITY_MODEL_IDS.join(', ')}.`); + } + return value; +} + +export function parseSecurityLimit(key: SecurityLimitKey, value: unknown): number { + const range = SECURITY_LIMIT_RANGES[key]; + if ( + typeof value !== 'number' || + !Number.isSafeInteger(value) || + value < range.min || + value > range.max + ) { + throw new Error(`${key} must be a whole number from ${range.min} to ${range.max}.`); + } + return value; +} + +/** A full limits object: every key present, each in range. */ +export function parseSecurityLimits(value: unknown): SecurityPolicyLimits { + const input = record(value, 'Security limits'); + return { + concurrency: parseSecurityLimit('concurrency', input.concurrency), + timeoutMinutes: parseSecurityLimit('timeoutMinutes', input.timeoutMinutes), + maxInputTokens: parseSecurityLimit('maxInputTokens', input.maxInputTokens), + maxOutputTokens: parseSecurityLimit('maxOutputTokens', input.maxOutputTokens), + modelCallsPerScan: parseSecurityLimit('modelCallsPerScan', input.modelCallsPerScan), + }; +} + +/** A change to some limits. Unknown keys are refused so a typo is not silently ignored. */ +export function parseSecurityLimitsPatch(value: unknown): Partial { + const input = record(value, 'Security limits'); + const patch: Partial> = {}; + for (const [key, limit] of Object.entries(input)) { + const known = SECURITY_LIMIT_KEYS.find((candidate) => candidate === key); + if (!known) { + throw new Error(`Unknown security limit: ${key}.`); + } + patch[known] = parseSecurityLimit(known, limit); + } + return patch; +} + +/** A USD amount for a monthly cap: 0 to `SECURITY_MAX_MONTHLY_USD`, whole cents. */ +export function parseSecurityUsd(value: unknown, label: string): number { + if ( + typeof value !== 'number' || + !Number.isFinite(value) || + value < 0 || + value > SECURITY_MAX_MONTHLY_USD || + Math.round(value * 100) / 100 !== value + ) { + throw new Error( + `${label} must be a USD amount from 0 to ${SECURITY_MAX_MONTHLY_USD} with at most two decimals.`, + ); + } + return value; +} + +function parseBoolean(value: unknown, label: string): boolean { + if (typeof value !== 'boolean') { + throw new Error(`${label} must be true or false.`); + } + return value; +} + +export function parseSecurityBudgets(value: unknown): SecurityPolicyBudgets { + const input = record(value, 'Security budgets'); + return { + platformCapOn: parseBoolean(input.platformCapOn, 'platformCapOn'), + platformMonthlyUsd: parseSecurityUsd(input.platformMonthlyUsd, 'platformMonthlyUsd'), + projectCapsOn: parseBoolean(input.projectCapsOn, 'projectCapsOn'), + projectDefaultMonthlyUsd: parseSecurityUsd( + input.projectDefaultMonthlyUsd, + 'projectDefaultMonthlyUsd', + ), + }; +} + +/** A timestamp written by `Date.prototype.toISOString`. */ +function parseIsoTimestamp(value: unknown, label: string): string { + if (typeof value !== 'string') { + throw new Error(`${label} must be an ISO 8601 timestamp.`); + } + const time = Date.parse(value); + if (!Number.isFinite(time) || new Date(time).toISOString() !== value) { + throw new Error(`${label} must be an ISO 8601 timestamp.`); + } + return value; +} + +function parseNoticeVersion(value: unknown, label: string): number { + if (typeof value !== 'number' || !Number.isSafeInteger(value) || value < 1) { + throw new Error(`${label} must be a positive whole number.`); + } + return value; +} + +export function parseSecurityThirdPartyNotice(value: unknown): SecurityThirdPartyNotice { + const input = record(value, 'thirdPartyNotice'); + if (!isPrintableText(input.acceptedByUserId, 200)) { + throw new Error('thirdPartyNotice.acceptedByUserId must be a user ID.'); + } + return { + acceptedByUserId: input.acceptedByUserId, + acceptedAt: parseIsoTimestamp(input.acceptedAt, 'thirdPartyNotice.acceptedAt'), + version: parseNoticeVersion(input.version, 'thirdPartyNotice.version'), + }; +} + +export function parseSecurityEntitlement(value: unknown): SecurityEntitlement { + const input = record(value, 'entitlement'); + // Check names stay open text so a probe from a later release still reads. + if ( + !Array.isArray(input.missing) || + input.missing.length > 20 || + !input.missing.every((name) => isPrintableText(name, 64)) + ) { + throw new Error('entitlement.missing must list at most 20 check names.'); + } + const ok = parseBoolean(input.ok, 'entitlement.ok'); + if (ok !== (input.missing.length === 0)) { + throw new Error('entitlement.ok must be true exactly when no check is missing.'); + } + const hosts = record(input.hosts, 'entitlement.hosts'); + return { + checkedAt: parseIsoTimestamp(input.checkedAt, 'entitlement.checkedAt'), + ok, + missing: input.missing.slice(), + hosts: { + openai: parseBoolean(hosts.openai, 'entitlement.hosts.openai'), + anthropic: parseBoolean(hosts.anthropic, 'entitlement.hosts.anthropic'), + }, + }; +} + +export function parseSecurityBlockedModels(value: unknown): ReadonlyArray { + if (!Array.isArray(value)) { + throw new Error('blockedModels must be a list of model IDs.'); + } + const blocked: Array = []; + for (const entry of value) { + const id = parseSecurityModelId(entry, 'Each blocked model'); + if (blocked.includes(id)) { + throw new Error(`Blocked model listed twice: ${id}.`); + } + blocked.push(id); + } + return blocked; +} + +/** + * Checks the rules that tie policy fields together. Runtime conditions (a fresh probe, + * Zero Trust state, a running operation) are checked by the API when it writes. + */ +export function assertSecurityPolicyConsistent(policy: SecurityPolicy): void { + if (policy.blockedModels.includes(policy.defaultModel)) { + throw new Error(`The default model ${policy.defaultModel} is blocked.`); + } + if (!isSecurityModelPriced(policy.defaultModel)) { + throw new Error(`The default model ${policy.defaultModel} has no price yet.`); + } + if (isThirdPartySecurityModel(policy.defaultModel) && policy.thirdPartyNotice === null) { + throw new Error( + `The default model ${policy.defaultModel} is third-party and needs the accepted provider notice.`, + ); + } + if (policy.publicGate && policy.mode === 'disabled') { + throw new Error('Scan before public needs the policy to be public or all.'); + } +} + +function parseRevision(value: unknown): number { + if (typeof value !== 'number' || !Number.isSafeInteger(value) || value < 0) { + throw new Error('Security policy revision must be a nonnegative whole number.'); + } + return value; +} + +/** + * Strict check of a policy about to be written. Every known field must be present and + * valid, and the fields must agree with each other. Unknown fields are ignored. Throws + * on bad data. Read a stored row with `readSecurityPolicy` instead. + */ +export function parseSecurityPolicy(value: unknown): SecurityPolicy { + const input = record(value, 'Security policy'); + const revision = parseRevision(input.revision); + const policy: SecurityPolicy = { + mode: parseSecurityMode(input.mode), + defaultModel: parseSecurityModelId(input.defaultModel, 'defaultModel'), + blockedModels: parseSecurityBlockedModels(input.blockedModels), + thirdPartyNotice: + input.thirdPartyNotice === null + ? null + : parseSecurityThirdPartyNotice(input.thirdPartyNotice), + limits: parseSecurityLimits(input.limits), + budgets: parseSecurityBudgets(input.budgets), + entitlement: input.entitlement === null ? null : parseSecurityEntitlement(input.entitlement), + publicGate: parseBoolean(input.publicGate, 'publicGate'), + sweeps: parseSweeps(input.sweeps, true), + fallbackToCf: parseAddedFlag(input.fallbackToCf, 'fallbackToCf', true), + digest: parseAddedFlag(input.digest, 'digest', true), + revision, + }; + assertSecurityPolicyConsistent(policy); + return policy; +} + +/** Known ids only, each once. Ids a later release added are dropped. */ +function readBlockedModels(value: unknown): ReadonlyArray { + if (!Array.isArray(value)) { + throw new Error('blockedModels must be a list of model IDs.'); + } + const blocked: Array = []; + for (const entry of value) { + if (isSecurityModelId(entry) && !blocked.includes(entry)) { + blocked.push(entry); + } + } + return blocked; +} + +/** + * Each limit clamped into today's range. A limit this release has and the row lacks + * takes its default. + */ +function readLimits(value: unknown): SecurityPolicyLimits { + const input = record(value, 'Security limits'); + const read = (key: SecurityLimitKey): number => { + const range = SECURITY_LIMIT_RANGES[key]; + const limit = input[key]; + if (limit === undefined) { + return range.default; + } + if (typeof limit !== 'number' || !Number.isSafeInteger(limit)) { + throw new Error(`${key} must be a whole number.`); + } + return Math.min(range.max, Math.max(range.min, limit)); + }; + return { + concurrency: read('concurrency'), + timeoutMinutes: read('timeoutMinutes'), + maxInputTokens: read('maxInputTokens'), + maxOutputTokens: read('maxOutputTokens'), + modelCallsPerScan: read('modelCallsPerScan'), + }; +} + +function canBeDefaultModel( + id: SecurityModelId, + blocked: ReadonlyArray, + notice: SecurityThirdPartyNotice | null, +): boolean { + return ( + !blocked.includes(id) && + isSecurityModelPriced(id) && + (notice !== null || !isThirdPartySecurityModel(id)) + ); +} + +/** + * The stored default if this release can still run it, else the first non-blocked, + * priced `@cf` model (spec §8.2, edge case 23). `SECURITY_MODEL_IDS` lists `@cf` + * models first, so a third-party model is only reached when every `@cf` model is + * blocked, and only with the notice accepted. + */ +function readDefaultModel( + value: unknown, + blocked: ReadonlyArray, + notice: SecurityThirdPartyNotice | null, +): SecurityModelId { + if (isSecurityModelId(value) && canBeDefaultModel(value, blocked, notice)) { + return value; + } + const fallback = SECURITY_MODEL_IDS.find((id) => canBeDefaultModel(id, blocked, notice)); + if (!fallback) { + throw new Error('No model can run: every priced model is blocked.'); + } + return fallback; +} + +/** + * Reader of the stored policy row. Data another release could have written still + * reads: unknown blocked models are dropped, an unknown, unpriced or blocked default + * falls back (`readDefaultModel`), limits are clamped into range. Anything else that + * `parseSecurityPolicy` refuses throws here too; the API decides whether that reads + * as `disabled` or fails closed. + */ +export function readSecurityPolicy(value: unknown): SecurityPolicy { + const input = record(value, 'Security policy'); + const revision = parseRevision(input.revision); + const thirdPartyNotice = + input.thirdPartyNotice === null ? null : parseSecurityThirdPartyNotice(input.thirdPartyNotice); + const blockedModels = readBlockedModels(input.blockedModels); + const policy: SecurityPolicy = { + mode: parseSecurityMode(input.mode), + defaultModel: readDefaultModel(input.defaultModel, blockedModels, thirdPartyNotice), + blockedModels, + thirdPartyNotice, + limits: readLimits(input.limits), + budgets: parseSecurityBudgets(input.budgets), + entitlement: input.entitlement === null ? null : parseSecurityEntitlement(input.entitlement), + publicGate: parseBoolean(input.publicGate, 'publicGate'), + sweeps: parseSweeps(input.sweeps, false), + fallbackToCf: parseAddedFlag(input.fallbackToCf, 'fallbackToCf', false), + digest: parseAddedFlag(input.digest, 'digest', false), + revision, + }; + assertSecurityPolicyConsistent(policy); + return policy; +} + +/** The last probe passed checks 1–4 less than 24 hours before `now` (ms). */ +export function isSecurityEntitlementFresh( + entitlement: SecurityEntitlement | null, + now: number, +): boolean { + if (!entitlement || !entitlement.ok) { + return false; + } + const age = now - Date.parse(entitlement.checkedAt); + return age >= 0 && age < SECURITY_ENTITLEMENT_MAX_AGE_MS; +} + +// --------------------------------------------------------------------------- +// Per-plan scan caps (Phase 2, M27) +// --------------------------------------------------------------------------- + +/** + * `platform_settings` key of the per-plan monthly scan caps. Kept out of + * `plans:catalog` (and `PlanLimits`): the saved-catalog parser needs the exact limit + * keys, and an older API rebuilds the catalog from known keys on every write, so a cap + * stored there would break deploys or be lost after a rollback (same as + * `plans:ai-logging`). + */ +export const PLAN_SECURITY_CAPS_SETTING = 'plans:security-caps'; + +/** Plan ID -> monthly cap in whole cents, or `null` = no cap for that plan. Missing = policy default. */ +export type PlanSecurityCaps = Readonly>; + +/** + * One plan's cap: whole cents, `none` (no cap from the plan, even with project caps + * on) or `inherit` (the policy's default project cap applies while project caps are on). + */ +export type SecurityPlanCap = number | 'none' | 'inherit'; + +const PLAN_KEY_MAX = 64; +const MAX_PLAN_CAP_CENTS = SECURITY_MAX_MONTHLY_USD * 100; + +function isPlanSecurityCapCents(value: unknown): value is number { + return ( + typeof value === 'number' && + Number.isSafeInteger(value) && + value >= 0 && + value <= MAX_PLAN_CAP_CENTS + ); +} + +/** One stored entry as a plan cap; `undefined` when it is neither whole cents nor `null`. */ +export function readStoredPlanSecurityCap(entry: unknown): SecurityPlanCap | undefined { + if (entry === null) { + return 'none'; + } + return isPlanSecurityCapCents(entry) ? entry : undefined; +} + +/** A plan ID: a lowercase letter, then lowercase letters, digits or hyphens, at most 64. */ +function isPlanKey(key: string): boolean { + if (key.length === 0 || key.length > PLAN_KEY_MAX || key[0]! < 'a' || key[0]! > 'z') { + return false; + } + for (const char of key) { + const ok = (char >= 'a' && char <= 'z') || (char >= '0' && char <= '9') || char === '-'; + if (!ok) { + return false; + } + } + return true; +} + +/** + * Reads a stored caps row. Lenient: an entry that is not a plan ID with whole cents or + * `null` is left out (that plan inherits) and counted in `dropped`, so one bad entry + * never stops plan edits or scans. A row that is not an object reads as empty. + */ +export function readPlanSecurityCaps( + value: unknown, +): Readonly<{ caps: PlanSecurityCaps; dropped: number }> { + if (value === null || value === undefined) { + return { caps: {}, dropped: 0 }; + } + if (typeof value !== 'object' || Array.isArray(value)) { + return { caps: {}, dropped: 1 }; + } + const caps: Record = {}; + let dropped = 0; + for (const [key, entry] of Object.entries(value as Record)) { + if (isPlanKey(key) && (entry === null || isPlanSecurityCapCents(entry))) { + caps[key] = entry; + } else { + dropped++; + } + } + return { caps, dropped }; +} + +/** One stored entry (`undefined` when the plan has none) as a plan cap. */ +export function securityPlanCapOf(entry: number | null | undefined): SecurityPlanCap { + if (entry === undefined) { + return 'inherit'; + } + return entry === null ? 'none' : entry; +} + +/** The cap of one plan in a caps row. */ +export function planSecurityCap(caps: PlanSecurityCaps, planId: string): SecurityPlanCap { + return securityPlanCapOf(Object.hasOwn(caps, planId) ? caps[planId] : undefined); +} + +/** + * Reads a plan change's `securityCap` field: a USD amount (0 to + * `SECURITY_MAX_MONTHLY_USD`, whole cents), `none` or `inherit`. `undefined` keeps the + * plan's current cap. An amount comes back in cents. + */ +export function parsePlanSecurityCapInput(value: unknown): SecurityPlanCap | undefined { + if (value === undefined) { + return undefined; + } + if (value === 'none' || value === 'inherit') { + return value; + } + if (typeof value === 'number') { + return Math.round(parseSecurityUsd(value, 'securityCap') * 100); + } + throw new Error( + `securityCap must be a USD amount from 0 to ${SECURITY_MAX_MONTHLY_USD}, "none" or "inherit".`, + ); +} + +/** A caps row with one plan's cap changed; `inherit` leaves the plan out. */ +export function withPlanSecurityCap( + caps: PlanSecurityCaps, + planId: string, + cap: SecurityPlanCap, +): PlanSecurityCaps { + const next: Record = {}; + for (const [key, entry] of Object.entries(caps)) { + if (key !== planId) { + next[key] = entry; + } + } + if (cap !== 'inherit') { + next[planId] = cap === 'none' ? null : cap; + } + return next; +} + +/** `$50.00 / month`, `no cap` or `policy default`, for the CLI and the admin panel. */ +export function formatPlanSecurityCap(cap: SecurityPlanCap): string { + if (cap === 'inherit') { + return 'policy default'; + } + if (cap === 'none') { + return 'no cap'; + } + const dollars = Math.floor(cap / 100); + const cents = String(cap % 100).padStart(2, '0'); + return `$${dollars.toLocaleString('en-US')}.${cents} / month`; +} + +// --------------------------------------------------------------------------- +// Form text (the project security page on the API host and the dashboard) +// --------------------------------------------------------------------------- + +/** `text` as a whole number written with 1 to `maxDigits` ASCII digits, else `null`. */ +export function parseSecurityDigits(text: string, maxDigits: number): number | null { + if (text.length === 0 || text.length > maxDigits) { + return null; + } + for (const char of text) { + if (char < '0' || char > '9') { + return null; + } + } + return Number(text); +} + +/** A finding label as the page prints it (`F-12`): its number, else `null`. */ +export function parseSecurityFindingLabel(text: string): number | null { + return text.startsWith('F-') ? parseSecurityDigits(text.slice(2), 9) : null; +} + +/** + * A dollar amount typed in a budget form, such as `50`, `12.50` or `$12.50`. Empty text + * is `null` (no cap of its own); text that is not an amount is `undefined`. The range is + * checked by `parseSecurityUsd` on the server. + */ +export function parseSecurityUsdText(text: string): number | null | undefined { + let amount = text.trim(); + if (amount === '') { + return null; + } + if (amount.startsWith('$')) { + amount = amount.slice(1); + } + const dot = amount.indexOf('.'); + const whole = dot === -1 ? amount : amount.slice(0, dot); + if (parseSecurityDigits(whole, 7) === null) { + return undefined; + } + if (dot !== -1 && parseSecurityDigits(amount.slice(dot + 1), 2) === null) { + return undefined; + } + return Number(amount); +} diff --git a/packages/platform/src/worker-config.ts b/packages/platform/src/worker-config.ts index f4700e789..3644b938e 100644 --- a/packages/platform/src/worker-config.ts +++ b/packages/platform/src/worker-config.ts @@ -2,6 +2,7 @@ import { createPlatformResourceOwnershipMarker } from './installation.ts'; import { createApplicationRoutes, platformDashboardUrl, + serializePlatformCapabilities, type PlatformDeploymentManifest, } from './manifest.ts'; @@ -33,6 +34,11 @@ export function createPlatformWorkerConfigs(input: { proxyUrl: string; emailGatewayUrl: string; resources: PlatformProvisionedResourceIds; + /** + * The runtime exports `SecurityScanScheduler` (runtime manifest `securityAudits: 1`). + * The class and its migration then ship whatever the capability says. + */ + securityScanScheduler?: boolean; runtimeEntrypoints: Readonly< Record<'api' | 'dispatch' | 'proxy' | 'tail' | 'emailGateway', string> >; @@ -79,6 +85,7 @@ export function createPlatformWorkerConfigs(input: { }), ), }); + const capabilitiesVar = serializePlatformCapabilities(deployment.capabilities); // Sent only in minimal mode, so default Worker configs stay unchanged. const runtimeLogs = deployment.runtimeLogs ? { PLATFORM_RUNTIME_LOGS: deployment.runtimeLogs } @@ -147,6 +154,8 @@ export function createPlatformWorkerConfigs(input: { hyperdrive: [{ binding: 'HYPERDRIVE', id: resources.hyperdrive }], kv_namespaces: kv, ...(deployment.capabilities.email ? { send_email: [{ name: 'EMAIL' }] } : {}), + // Security scans call the default Workers AI model through this binding. + ...(deployment.capabilities.securityAudits ? { ai: { binding: 'AI' } } : {}), r2_buckets: r2, dispatch_namespaces: dispatchNamespace, durable_objects: { @@ -155,6 +164,11 @@ export function createPlatformWorkerConfigs(input: { { name: 'CRON_SCHEDULER', class_name: 'CronScheduler' }, { name: 'ERROR_ALERT_MONITOR', class_name: 'ErrorAlertMonitor' }, { name: 'SANDBOX_CONCURRENCY_COUNTER', class_name: 'SandboxConcurrencyCounter' }, + // Bound whatever the capability says: an idle SQLite DO works on Workers + // Free, and dropping the class later would need a delete migration. + ...(input.securityScanScheduler + ? [{ name: 'SECURITY_SCAN_SCHEDULER', class_name: 'SecurityScanScheduler' }] + : []), ], }, migrations: [ @@ -162,6 +176,10 @@ export function createPlatformWorkerConfigs(input: { { tag: 'v2', new_sqlite_classes: ['CronScheduler'] }, { tag: 'v3', new_sqlite_classes: ['ErrorAlertMonitor'] }, { tag: 'v4', new_sqlite_classes: ['SandboxConcurrencyCounter'] }, + // Named tag so it never clashes with the hosted Worker's v5/v6. + ...(input.securityScanScheduler + ? [{ tag: 'security-audits-v1', new_sqlite_classes: ['SecurityScanScheduler'] }] + : []), ], queues: { producers: [ @@ -199,7 +217,7 @@ export function createPlatformWorkerConfigs(input: { DISPATCH_NAMESPACE: names.dispatchNamespace, DISPATCH_WORKER_NAME: names.dispatchWorker, LOGS_DATASET: names.logsDataset, - PLATFORM_CAPABILITIES: JSON.stringify(deployment.capabilities), + PLATFORM_CAPABILITIES: capabilitiesVar, ...(input.authenticationDatabaseUncached ? { PLATFORM_AUTH_DATABASE_UNCACHED: 'true' } : {}), PLATFORM_DISPLAY_NAME: deployment.displayName, PLATFORM_ENV: 'production', @@ -249,7 +267,7 @@ export function createPlatformWorkerConfigs(input: { ...(deployment.capabilities.email ? { send_email: [{ name: 'SEND_EMAIL' }] } : {}), vars: { AI_GATEWAY_ID: names.aiGateway, - PLATFORM_CAPABILITIES: JSON.stringify(deployment.capabilities), + PLATFORM_CAPABILITIES: capabilitiesVar, PLATFORM_HEALTH_PROBE_TOKEN: healthProbeToken, PLATFORM_INSTALLATION_ID: installationId, PLATFORM_TRAFFIC_STATE: trafficState, @@ -276,7 +294,7 @@ export function createPlatformWorkerConfigs(input: { dispatch_namespaces: dispatchNamespace, ...(deployment.capabilities.email ? { send_email: [{ name: 'SEND_EMAIL' }] } : {}), vars: { - PLATFORM_CAPABILITIES: JSON.stringify(deployment.capabilities), + PLATFORM_CAPABILITIES: capabilitiesVar, PLATFORM_INSTALLATION_ID: installationId, PLATFORM_VERSION: platformVersion, PLATFORM_TRAFFIC_STATE: trafficState, diff --git a/packages/platform/test/unit/auth-discovery.test.ts b/packages/platform/test/unit/auth-discovery.test.ts index f5cd5d862..060edb76b 100644 --- a/packages/platform/test/unit/auth-discovery.test.ts +++ b/packages/platform/test/unit/auth-discovery.test.ts @@ -21,6 +21,7 @@ const base = { googleOAuth: false, managedBuilds: false, sandbox: false, + securityAudits: false, }, }; const modern = { @@ -131,3 +132,35 @@ describe('direct Worker upload discovery', () => { ); }); }); + +describe('security audits discovery', () => { + it('reads a platform released before security audits as off', () => { + const discovery = createPlatformDiscoveryDocument(base); + const { securityAudits: _, ...olderCapabilities } = discovery.capabilities; + const parsed = parsePlatformDiscoveryDocument({ + ...discovery, + capabilities: olderCapabilities, + }); + expect(parsed.capabilities.securityAudits).toBe(false); + expect(parsed).toEqual(discovery); + }); + + it('round-trips an installation that allows security audits', () => { + const discovery = createPlatformDiscoveryDocument({ + ...base, + capabilities: { ...base.capabilities, securityAudits: true }, + }); + expect(discovery.schemaVersion).toBe(1); + expect(parsePlatformDiscoveryDocument(discovery).capabilities.securityAudits).toBe(true); + }); + + it.each(['true', 1, null])('rejects securityAudits %j', (securityAudits) => { + const discovery = createPlatformDiscoveryDocument(base); + expect(() => + parsePlatformDiscoveryDocument({ + ...discovery, + capabilities: { ...discovery.capabilities, securityAudits }, + }), + ).toThrow('capabilities.securityAudits must be a boolean.'); + }); +}); diff --git a/packages/platform/test/unit/auth-manifest.test.ts b/packages/platform/test/unit/auth-manifest.test.ts index 9366aafa5..9fc21ff85 100644 --- a/packages/platform/test/unit/auth-manifest.test.ts +++ b/packages/platform/test/unit/auth-manifest.test.ts @@ -1,4 +1,5 @@ import { describe, expect, it } from 'vite-plus/test'; +import { parsePlatformRuntimeManifest, platformDatabaseSchemaDigest } from '../../src/installer.ts'; import { createPlatformDeploymentManifest, parsePlatformDeploymentManifest, @@ -50,3 +51,149 @@ describe('configurable authentication deployment manifests', () => { ).toThrow('schema version 3'); }); }); + +describe('security audits deployment manifests', () => { + const input = { + application: { baseDomain: 'apps.example.com', zoneName: 'example.com' }, + displayName: 'Team', + installationSlug: 'team', + }; + const roundTrip = (manifest: unknown) => + parsePlatformDeploymentManifest(JSON.parse(JSON.stringify(manifest))); + + it('keeps the schema version and reads a missing capability as off', () => { + const manifest = createPlatformDeploymentManifest(input); + expect(manifest.schemaVersion).toBe(1); + expect(manifest.capabilities.securityAudits).toBe(false); + const { securityAudits: _, ...olderCapabilities } = manifest.capabilities; + const older = { ...manifest, capabilities: olderCapabilities }; + expect(roundTrip(older)).toEqual(manifest); + }); + + it('writes schema version 7 when on and round-trips it', () => { + const manifest = createPlatformDeploymentManifest({ + ...input, + capabilities: { securityAudits: true }, + }); + expect(manifest.schemaVersion).toBe(7); + expect(manifest).not.toHaveProperty('runtimeLogs'); + expect(manifest).not.toHaveProperty('storageLocationHint'); + expect(manifest).not.toHaveProperty('appAccess'); + expect(roundTrip(manifest)).toEqual(manifest); + }); + + it('keeps every other setting at schema version 7', () => { + const manifest = createPlatformDeploymentManifest({ + ...input, + appAccess: 'platform', + authentication: { providers: ['oidc'], configurable: true }, + capabilities: { githubOAuth: false, securityAudits: true }, + runtimeLogs: 'minimal', + storageLocationHint: 'apac', + }); + expect(manifest.schemaVersion).toBe(7); + expect(roundTrip(manifest)).toEqual(manifest); + expect(manifest).toMatchObject({ + appAccess: 'platform', + authentication: { providers: ['oidc'], configurable: true }, + runtimeLogs: 'minimal', + storageLocationHint: 'apac', + }); + }); + + it.each([1, 2, 3, 4, 5, 6])('refuses the capability at schema version %i', (schemaVersion) => { + const manifest = createPlatformDeploymentManifest({ + ...input, + // Version 2 is the workers.dev document, so give it one. + ...(schemaVersion === 2 + ? { + application: { + baseDomain: 'team.workers.dev', + zoneName: '', + workersDev: { subdomain: 'team', installationId: 'team-12345678' }, + }, + } + : {}), + capabilities: { securityAudits: true }, + }); + expect(() => roundTrip({ ...manifest, schemaVersion })).toThrow( + 'Security audits require deployment schema version 7.', + ); + }); + + it('refuses schema version 7 without the capability', () => { + const manifest = createPlatformDeploymentManifest(input); + expect(() => roundTrip({ ...manifest, schemaVersion: 7 })).toThrow( + 'Deployment schema version 7 requires capabilities.securityAudits.', + ); + const { securityAudits: _, ...olderCapabilities } = manifest.capabilities; + expect(() => + roundTrip({ ...manifest, capabilities: olderCapabilities, schemaVersion: 7 }), + ).toThrow('Deployment schema version 7 requires capabilities.securityAudits.'); + }); + + it('refuses a schema version newer than 7', () => { + const manifest = createPlatformDeploymentManifest({ + ...input, + capabilities: { securityAudits: true }, + }); + expect(() => roundTrip({ ...manifest, schemaVersion: 8 })).toThrow( + 'Unsupported platform deployment schema version: 8.', + ); + }); + + it.each(['true', 1, null])('rejects securityAudits %j', (securityAudits) => { + const manifest = createPlatformDeploymentManifest(input); + expect(() => + roundTrip({ ...manifest, capabilities: { ...manifest.capabilities, securityAudits } }), + ).toThrow('capabilities.securityAudits must be a boolean.'); + }); + + it('validates the storage hint when present at schema version 7', () => { + const manifest = createPlatformDeploymentManifest({ + ...input, + capabilities: { securityAudits: true }, + }); + expect(() => roundTrip({ ...manifest, storageLocationHint: 'APAC' })).toThrow( + 'storageLocationHint', + ); + expect(() => roundTrip({ ...manifest, runtimeLogs: 'full' })).toThrow('runtime logs'); + }); +}); + +describe('runtime manifest securityAudits protocol', () => { + const digest = '0'.repeat(64); + const artifact = (path: string) => ({ path, sha256: digest, size: 1 }); + const runtime = { + artifacts: { + api: artifact('api.mjs'), + dispatch: artifact('dispatch.mjs'), + proxy: artifact('proxy.mjs'), + tail: artifact('tail.mjs'), + }, + database: { + journalSha256: digest, + lineage: 'void', + migrations: [], + protocolVersion: 1, + rollbackSafeFrom: [], + schemaDigest: platformDatabaseSchemaDigest('void', []), + }, + platformVersion: '1.0.0', + schemaVersion: 2, + }; + + it('leaves the protocol out of older runtime manifests', () => { + expect(parsePlatformRuntimeManifest(runtime)).not.toHaveProperty('securityAudits'); + }); + + it('accepts and keeps securityAudits: 1', () => { + expect(parsePlatformRuntimeManifest({ ...runtime, securityAudits: 1 }).securityAudits).toBe(1); + }); + + it.each([0, 2, '1', true, null])('rejects securityAudits %j', (securityAudits) => { + expect(() => parsePlatformRuntimeManifest({ ...runtime, securityAudits })).toThrow( + 'Unsupported security audits protocol.', + ); + }); +}); diff --git a/packages/platform/test/unit/security-models.test.ts b/packages/platform/test/unit/security-models.test.ts new file mode 100644 index 000000000..2878248a0 --- /dev/null +++ b/packages/platform/test/unit/security-models.test.ts @@ -0,0 +1,194 @@ +import { describe, expect, it } from 'vite-plus/test'; +import { + DEFAULT_SECURITY_MODEL, + getSecurityModel, + isSecurityModelId, + isSecurityModelPriced, + isThirdPartySecurityModel, + SECURITY_MODEL_IDS, + SECURITY_MODELS, + SECURITY_PROVIDER_NOTICE_VERSION, + securityModelBadges, + securityModelCostNanoUsd, + securityModelCostUsd, + securityModelThirdPartyHost, + securityProviderNotice, + securityProviderNoticeShort, + securityScanReserveUsd, + type SecurityModelId, +} from '../../src/security-models.ts'; + +describe('security model list', () => { + it('lists six models in fallback order, the default first', () => { + expect(SECURITY_MODELS.map((model) => model.id)).toEqual([...SECURITY_MODEL_IDS]); + expect(SECURITY_MODEL_IDS).toHaveLength(6); + expect(DEFAULT_SECURITY_MODEL).toBe('@cf/deepseek-ai/deepseek-v4.1-flash-1017'); + expect(SECURITY_MODEL_IDS[0]).toBe(DEFAULT_SECURITY_MODEL); + expect(new Set(SECURITY_MODEL_IDS).size).toBe(SECURITY_MODEL_IDS.length); + }); + + it('uses the AI Gateway catalog spelling for ids', () => { + const prefixes: Record = { + 'workers-ai': '@cf/', + openai: 'openai/', + anthropic: 'anthropic/', + }; + for (const model of SECURITY_MODELS) { + expect(model.id.startsWith(prefixes[model.host])).toBe(true); + expect(model.id).toBe(model.id.toLowerCase()); + expect(model.id.includes(' ')).toBe(false); + } + // Versions keep their dots: `claude-opus-5.5`, not the API spelling `claude-opus-5-5`. + expect(SECURITY_MODEL_IDS).toContain('anthropic/claude-opus-5.5'); + expect(SECURITY_MODEL_IDS).toContain('anthropic/claude-sonnet-5.5'); + expect(SECURITY_MODEL_IDS.some((id) => id.endsWith('-5-5'))).toBe(false); + }); + + it('maps each host to its engine', () => { + for (const model of SECURITY_MODELS) { + const expected = + model.host === 'workers-ai' + ? 'void_loop' + : model.host === 'openai' + ? 'codex_sdk' + : 'agent_sdk'; + expect(model.engine).toBe(expected); + } + expect(securityModelThirdPartyHost('@cf/zai-org/glm-5.3')).toBeNull(); + expect(securityModelThirdPartyHost('openai/gpt-6.1-sol')).toBe('openai'); + expect(securityModelThirdPartyHost('anthropic/claude-opus-5.5')).toBe('anthropic'); + expect(isThirdPartySecurityModel('@cf/deepseek-ai/deepseek-v4.1-flash-1017')).toBe(false); + expect(isThirdPartySecurityModel('openai/gpt-6.1-terra')).toBe(true); + }); + + it('recognizes only listed ids', () => { + for (const id of SECURITY_MODEL_IDS) { + expect(isSecurityModelId(id)).toBe(true); + } + for (const value of [ + 'anthropic/claude-opus-5-5', + 'claude-opus-5.5', + '@cf/zai-org/GLM-5.3', + '', + null, + undefined, + 1, + ]) { + expect(isSecurityModelId(value)).toBe(false); + } + expect(() => getSecurityModel('nope' as SecurityModelId)).toThrow('Unknown security model'); + }); +}); + +describe('security model prices', () => { + it('has a price for every model except Sonnet, which cannot be picked yet', () => { + for (const model of SECURITY_MODELS) { + if (model.id === 'anthropic/claude-sonnet-5.5') { + expect(model.price).toBeNull(); + expect(isSecurityModelPriced(model.id)).toBe(false); + continue; + } + expect(model.price).not.toBeNull(); + expect(model.price!.inputUsdPerMillion).toBeGreaterThan(0); + expect(model.price!.outputUsdPerMillion).toBeGreaterThan(0); + expect(isSecurityModelPriced(model.id)).toBe(true); + } + }); + + it('matches the spec §8.2 list prices', () => { + const prices = Object.fromEntries( + SECURITY_MODELS.map((model) => [ + model.id, + model.price && [model.price.inputUsdPerMillion, model.price.outputUsdPerMillion], + ]), + ); + expect(prices).toEqual({ + '@cf/zai-org/glm-5.3': [1.4, 4.4], + '@cf/deepseek-ai/deepseek-v4.1-flash-1017': [0.3, 1.2], + 'openai/gpt-6.1-terra': [1, 5], + 'openai/gpt-6.1-sol': [2, 10], + 'anthropic/claude-sonnet-5.5': null, + 'anthropic/claude-opus-5.5': [4, 20], + }); + }); + + it('reserves 1.2M input and 120k output tokens per scan (S4/S8 follow-up of spec §16.1)', () => { + const reserves = Object.fromEntries( + SECURITY_MODEL_IDS.map((id) => [id, securityScanReserveUsd(id)?.toFixed(2) ?? null]), + ); + expect(reserves).toEqual({ + '@cf/deepseek-ai/deepseek-v4.1-flash-1017': '0.50', + 'openai/gpt-6.1-terra': '1.80', + '@cf/zai-org/glm-5.3': '2.21', + 'openai/gpt-6.1-sol': '3.60', + 'anthropic/claude-opus-5.5': '7.20', + 'anthropic/claude-sonnet-5.5': null, + }); + expect(securityScanReserveUsd('@cf/zai-org/glm-5.3')).toBe(2.208); + }); + + it('follows the policy token limits', () => { + expect( + securityScanReserveUsd('anthropic/claude-opus-5.5', { + maxInputTokens: 100_000, + maxOutputTokens: 10_000, + }), + ).toBe(0.6); + }); + + it('adds call costs in whole nano-dollars without drift', () => { + expect(securityModelCostNanoUsd('@cf/deepseek-ai/deepseek-v4.1-flash-1017', 1, 1)).toBe(1500); + let total = 0; + for (let call = 0; call < 1000; call += 1) { + total += securityModelCostNanoUsd('@cf/zai-org/glm-5.3', 1234, 56)!; + } + expect(total).toBe(1000 * (1234 * 1400 + 56 * 4400)); + expect(securityModelCostUsd('openai/gpt-6.1-sol', 1_000_000, 0)).toBe(2); + expect(securityModelCostUsd('anthropic/claude-sonnet-5.5', 10, 10)).toBeNull(); + expect(securityModelCostUsd('openai/gpt-6.1-sol', 0, 0)).toBe(0); + }); + + it('refuses token counts that are not whole and nonnegative', () => { + for (const tokens of [-1, 1.5, Number.NaN, Number.POSITIVE_INFINITY]) { + expect(() => securityModelCostNanoUsd('@cf/zai-org/glm-5.3', tokens, 0)).toThrow( + 'inputTokens', + ); + expect(() => securityModelCostNanoUsd('@cf/zai-org/glm-5.3', 0, tokens)).toThrow( + 'outputTokens', + ); + } + }); +}); + +describe('security model badges and notice', () => { + it('shows host, data retention and refusal badges', () => { + expect(securityModelBadges('@cf/zai-org/glm-5.3')).toEqual([ + 'Cloudflare-hosted', + 'Zero data retention', + ]); + expect(securityModelBadges('anthropic/claude-sonnet-5.5')).toEqual([ + 'Third-party', + 'No ZDR listed', + 'May refuse security reviews', + ]); + expect(securityModelBadges('openai/gpt-6.1-terra')).toEqual([ + 'Third-party', + 'Zero data retention', + 'May refuse security reviews', + ]); + }); + + it('names the provider in the notice and short line', () => { + expect(SECURITY_PROVIDER_NOTICE_VERSION).toBe(1); + const notice = securityProviderNotice('anthropic'); + expect(notice[0]).toBe('This model is run by Anthropic, not by Cloudflare.'); + expect(notice.join('\n')).not.toContain('OpenAI may'); + expect(securityProviderNotice('openai')[0]).toBe( + 'This model is run by OpenAI, not by Cloudflare.', + ); + expect(securityProviderNoticeShort('anthropic/claude-opus-5.5')).toBe( + 'Model anthropic/claude-opus-5.5 is run by Anthropic. Its usage policy applies and it may refuse.', + ); + expect(securityProviderNoticeShort('@cf/zai-org/glm-5.3')).toBeNull(); + }); +}); diff --git a/packages/platform/test/unit/security-policy.test.ts b/packages/platform/test/unit/security-policy.test.ts new file mode 100644 index 000000000..47a7f42b2 --- /dev/null +++ b/packages/platform/test/unit/security-policy.test.ts @@ -0,0 +1,628 @@ +import { describe, expect, it } from 'vite-plus/test'; +import { + defaultSecurityPolicy, + isSecurityEntitlementFresh, + isSecurityErrorCode, + parseSecurityBudgets, + parseSecurityDigits, + parseSecurityFindingLabel, + parseSecurityLimits, + parseSecurityLimitsPatch, + parseSecurityMode, + parseSecurityPolicy, + parseSecuritySweepDays, + parseSecurityWebhookUrl, + parseSecurityUsd, + parseSecurityUsdText, + readSecurityPolicy, + SECURITY_ENTITLEMENT_MAX_AGE_MS, + SECURITY_ERRORS, + SECURITY_LIMIT_KEYS, + SECURITY_LIMIT_RANGES, + SECURITY_MODE_LABELS, + SECURITY_MODES, + SECURITY_POLICY_SETTINGS_KEY, + SECURITY_SWEEP_DAYS_RANGE, + type SecurityPolicy, + formatPlanSecurityCap, + parsePlanSecurityCapInput, + planSecurityCap, + readPlanSecurityCaps, + withPlanSecurityCap, +} from '../../src/security-policy.ts'; + +const CHECKED_AT = '2026-11-18T03:00:00.000Z'; + +function stored(overrides: Partial> = {}): unknown { + return JSON.parse(JSON.stringify({ ...defaultSecurityPolicy(), ...overrides })); +} + +const passingEntitlement = { + checkedAt: CHECKED_AT, + ok: true, + missing: [], + hosts: { openai: true, anthropic: false }, +}; + +/** Strict refusals the stored-row reader repairs instead (another release wrote them). */ +const READER_FALLS_BACK = new Set([ + 'unknown model', + 'blocked default', + 'duplicate block', + 'unpriced default', + 'third-party default with no notice', + 'missing limit', +]); + +describe('security policy defaults', () => { + it('starts Off with the spec defaults', () => { + expect(SECURITY_POLICY_SETTINGS_KEY).toBe('securityAudits.policy'); + expect(defaultSecurityPolicy()).toEqual({ + mode: 'disabled', + defaultModel: '@cf/deepseek-ai/deepseek-v4.1-flash-1017', + blockedModels: [], + thirdPartyNotice: null, + limits: { + concurrency: 2, + timeoutMinutes: 20, + maxInputTokens: 1_200_000, + maxOutputTokens: 120_000, + modelCallsPerScan: 80, + }, + budgets: { + platformCapOn: false, + platformMonthlyUsd: 1000, + projectCapsOn: false, + projectDefaultMonthlyUsd: 100, + }, + entitlement: null, + publicGate: false, + sweeps: { on: false, everyDays: 30 }, + fallbackToCf: false, + digest: false, + revision: 0, + }); + }); + + it('keeps every default inside its range', () => { + expect(SECURITY_LIMIT_KEYS).toEqual(Object.keys(SECURITY_LIMIT_RANGES)); + for (const key of SECURITY_LIMIT_KEYS) { + const range = SECURITY_LIMIT_RANGES[key]; + expect(range.min).toBeLessThanOrEqual(range.default); + expect(range.default).toBeLessThanOrEqual(range.max); + expect(defaultSecurityPolicy().limits[key]).toBe(range.default); + } + expect(SECURITY_LIMIT_RANGES.concurrency).toMatchObject({ min: 1, max: 10 }); + expect(SECURITY_LIMIT_RANGES.timeoutMinutes).toMatchObject({ min: 5, max: 60 }); + }); + + it('reads back its own default', () => { + expect(parseSecurityPolicy(stored())).toEqual(defaultSecurityPolicy()); + }); + + it('labels the three modes', () => { + expect(SECURITY_MODES).toEqual(['disabled', 'public', 'all']); + expect(SECURITY_MODE_LABELS).toEqual({ + disabled: 'Off', + public: 'Public projects only', + all: 'All projects', + }); + expect(parseSecurityMode('all')).toBe('all'); + for (const value of ['off', 'Public', '', null, 1]) { + expect(() => parseSecurityMode(value)).toThrow('disabled, public or all'); + } + }); +}); + +describe('security policy strict parser', () => { + it('round-trips a full policy', () => { + const policy = stored({ + mode: 'all', + defaultModel: 'anthropic/claude-opus-5.5', + blockedModels: ['openai/gpt-6.1-sol'], + thirdPartyNotice: { acceptedByUserId: 'usr_1', acceptedAt: CHECKED_AT, version: 1 }, + limits: { + concurrency: 10, + timeoutMinutes: 5, + maxInputTokens: 2_000_000, + maxOutputTokens: 5_000, + modelCallsPerScan: 10, + }, + budgets: { + platformCapOn: true, + platformMonthlyUsd: 1500.5, + projectCapsOn: true, + projectDefaultMonthlyUsd: 0, + }, + entitlement: passingEntitlement, + publicGate: true, + sweeps: { on: true, everyDays: 7 }, + fallbackToCf: true, + digest: true, + revision: 7, + }); + expect(parseSecurityPolicy(policy)).toEqual(policy); + }); + + it('ignores unknown fields', () => { + const policy = parseSecurityPolicy({ ...(stored() as object), laterField: 1 }); + expect(policy).toEqual(defaultSecurityPolicy()); + expect(Object.hasOwn(policy, 'laterField')).toBe(false); + }); + + it.each([ + ['not an object', null, 'must be an object'], + ['missing revision', { ...(stored() as object), revision: undefined }, 'revision'], + ['negative revision', stored({ revision: -1 }), 'revision'], + ['unknown mode', stored({ mode: 'on' }), 'disabled, public or all'], + ['unknown model', stored({ defaultModel: 'openai/gpt-4' }), 'defaultModel must be one of'], + [ + 'blocked default', + stored({ blockedModels: ['@cf/deepseek-ai/deepseek-v4.1-flash-1017'] }), + 'is blocked', + ], + [ + 'duplicate block', + stored({ blockedModels: ['openai/gpt-6.1-sol', 'openai/gpt-6.1-sol'] }), + 'listed twice', + ], + ['block not a list', stored({ blockedModels: 'openai/gpt-6.1-sol' }), 'list of model IDs'], + [ + 'unpriced default', + stored({ + defaultModel: 'anthropic/claude-sonnet-5.5', + thirdPartyNotice: { acceptedByUserId: 'usr_1', acceptedAt: CHECKED_AT, version: 1 }, + }), + 'has no price', + ], + [ + 'third-party default with no notice', + stored({ defaultModel: 'openai/gpt-6.1-terra' }), + 'needs the accepted provider notice', + ], + ['gate while Off', stored({ publicGate: true }), 'public or all'], + ['gate not boolean', stored({ publicGate: 'true' }), 'publicGate'], + [ + 'missing limit', + stored({ limits: { ...defaultSecurityPolicy().limits, modelCallsPerScan: undefined } }), + 'modelCallsPerScan', + ], + [ + 'bad notice time', + stored({ thirdPartyNotice: { acceptedByUserId: 'u', acceptedAt: 'yesterday', version: 1 } }), + 'acceptedAt', + ], + [ + 'bad notice version', + stored({ thirdPartyNotice: { acceptedByUserId: 'u', acceptedAt: CHECKED_AT, version: 0 } }), + 'version', + ], + [ + 'notice without user', + stored({ thirdPartyNotice: { acceptedByUserId: '', acceptedAt: CHECKED_AT, version: 1 } }), + 'acceptedByUserId', + ], + [ + 'entitlement ok with missing checks', + stored({ entitlement: { ...passingEntitlement, missing: ['egress'] } }), + 'ok must be true exactly', + ], + [ + 'entitlement with more than 20 check names', + stored({ + entitlement: { + ...passingEntitlement, + ok: false, + missing: Array.from({ length: 21 }, (_, index) => `check-${index}`), + }, + }), + 'at most 20 check names', + ], + [ + 'entitlement with a check name that is not text', + stored({ entitlement: { ...passingEntitlement, ok: false, missing: [7] } }), + 'at most 20 check names', + ], + [ + 'entitlement with an empty check name', + stored({ entitlement: { ...passingEntitlement, ok: false, missing: [''] } }), + 'at most 20 check names', + ], + [ + 'entitlement with a control character in a check name', + stored({ entitlement: { ...passingEntitlement, ok: false, missing: ['egress\n'] } }), + 'at most 20 check names', + ], + [ + 'entitlement not ok with no missing check', + stored({ entitlement: { ...passingEntitlement, ok: false, missing: [] } }), + 'ok must be true exactly', + ], + [ + 'entitlement without hosts', + stored({ entitlement: { ...passingEntitlement, hosts: { openai: true } } }), + 'hosts.anthropic', + ], + [ + 'entitlement with a non-ISO time', + stored({ entitlement: { ...passingEntitlement, checkedAt: '2026-11-18' } }), + 'checkedAt', + ], + ])('refuses %s', (name, value, message) => { + expect(() => parseSecurityPolicy(value)).toThrow(message); + if (READER_FALLS_BACK.has(name)) { + expect(() => readSecurityPolicy(value)).not.toThrow(); + } else { + expect(() => readSecurityPolicy(value)).toThrow(message); + } + }); + + it('reads check names from a later probe', () => { + const policy = parseSecurityPolicy( + stored({ + entitlement: { ...passingEntitlement, ok: false, missing: ['scanner', 'future-check'] }, + }), + ); + expect(policy.entitlement?.missing).toEqual(['scanner', 'future-check']); + }); +}); + +describe('stored security policy written by another release', () => { + const notice = { acceptedByUserId: 'u', acceptedAt: CHECKED_AT, version: 1 }; + + it('reads a valid row the same as the strict parser', () => { + const value = stored({ + mode: 'all', + defaultModel: 'openai/gpt-6.1-sol', + blockedModels: ['@cf/zai-org/glm-5.3'], + thirdPartyNotice: notice, + entitlement: passingEntitlement, + publicGate: true, + revision: 4, + }); + expect(readSecurityPolicy(value)).toEqual(parseSecurityPolicy(value)); + }); + + it('drops a retired blocked model and replaces a retired default', () => { + const value = stored({ + mode: 'public', + defaultModel: 'openai/gpt-5-retired', + blockedModels: ['openai/gpt-5-retired', '@cf/zai-org/glm-5.3', '@cf/zai-org/glm-5.3'], + }); + expect(() => parseSecurityPolicy(value)).toThrow('defaultModel must be one of'); + const policy = readSecurityPolicy(value); + expect(policy.blockedModels).toEqual(['@cf/zai-org/glm-5.3']); + expect(policy.defaultModel).toBe('@cf/deepseek-ai/deepseek-v4.1-flash-1017'); + expect(policy.mode).toBe('public'); + }); + + it('replaces an unpriced default (a later release priced it)', () => { + const value = stored({ defaultModel: 'anthropic/claude-sonnet-5.5', thirdPartyNotice: notice }); + expect(() => parseSecurityPolicy(value)).toThrow('has no price yet'); + expect(readSecurityPolicy(value).defaultModel).toBe('@cf/deepseek-ai/deepseek-v4.1-flash-1017'); + }); + + it('replaces a blocked default, and a third-party default without the notice', () => { + const blocked = stored({ blockedModels: ['@cf/deepseek-ai/deepseek-v4.1-flash-1017'] }); + expect(() => parseSecurityPolicy(blocked)).toThrow('is blocked'); + expect(readSecurityPolicy(blocked).defaultModel).toBe('@cf/zai-org/glm-5.3'); + const noNotice = stored({ defaultModel: 'openai/gpt-6.1-terra' }); + expect(() => parseSecurityPolicy(noNotice)).toThrow('needs the accepted provider notice'); + expect(readSecurityPolicy(noNotice).defaultModel).toBe( + '@cf/deepseek-ai/deepseek-v4.1-flash-1017', + ); + }); + + it('falls back to a third-party model only when every @cf model is blocked', () => { + const allCfBlocked = ['@cf/zai-org/glm-5.3', '@cf/deepseek-ai/deepseek-v4.1-flash-1017']; + expect( + readSecurityPolicy( + stored({ + defaultModel: 'openai/gpt-5-retired', + blockedModels: allCfBlocked, + thirdPartyNotice: notice, + }), + ).defaultModel, + ).toBe('openai/gpt-6.1-terra'); + expect(() => + readSecurityPolicy( + stored({ defaultModel: 'openai/gpt-5-retired', blockedModels: allCfBlocked }), + ), + ).toThrow('No model can run'); + }); + + it('clamps limits into range and fills a missing one with its default', () => { + const { maxInputTokens: _dropped, ...rest } = SECURITY_LIMIT_RANGES; + const limits = { + ...Object.fromEntries(Object.keys(rest).map((key) => [key, 1])), + concurrency: 50, + timeoutMinutes: 120, + }; + const value = stored({ limits }); + expect(() => parseSecurityPolicy(value)).toThrow(); + expect(readSecurityPolicy(value).limits).toEqual({ + concurrency: SECURITY_LIMIT_RANGES.concurrency.max, + timeoutMinutes: SECURITY_LIMIT_RANGES.timeoutMinutes.max, + maxInputTokens: SECURITY_LIMIT_RANGES.maxInputTokens.default, + maxOutputTokens: SECURITY_LIMIT_RANGES.maxOutputTokens.min, + modelCallsPerScan: SECURITY_LIMIT_RANGES.modelCallsPerScan.min, + }); + }); + + it('still refuses a limit that is not a whole number', () => { + for (const bad of [2.5, '2', null]) { + expect(() => + readSecurityPolicy( + stored({ limits: { ...defaultSecurityPolicy().limits, concurrency: bad } }), + ), + ).toThrow('concurrency must be a whole number'); + } + }); + + it('refuses the same values on the write path', () => { + for (const overrides of [ + { blockedModels: ['openai/gpt-5-retired'] }, + { defaultModel: 'openai/gpt-5-retired' }, + { limits: { ...defaultSecurityPolicy().limits, concurrency: 50 } }, + ]) { + const value = stored(overrides); + expect(() => parseSecurityPolicy(value)).toThrow(); + expect(() => readSecurityPolicy(value)).not.toThrow(); + } + }); +}); + +describe('scheduled sweeps setting (M25)', () => { + it('reads a row saved before sweeps existed as off', () => { + const { sweeps: _sweeps, ...old } = stored() as Record; + expect(parseSecurityPolicy(old).sweeps).toEqual({ on: false, everyDays: 30 }); + expect(readSecurityPolicy(old).sweeps).toEqual({ on: false, everyDays: 30 }); + }); + + it('checks the range strictly on write and repairs on read', () => { + expect(SECURITY_SWEEP_DAYS_RANGE).toEqual({ min: 7, max: 90, default: 30 }); + expect(parseSecuritySweepDays(7)).toBe(7); + expect(parseSecuritySweepDays(90)).toBe(90); + for (const days of [6, 91, 1.5, '30']) { + expect(() => parseSecuritySweepDays(days)).toThrow('from 7 to 90'); + } + for (const sweeps of [{ on: true, everyDays: 6 }, { on: 'yes', everyDays: 30 }, 'on']) { + expect(() => parseSecurityPolicy(stored({ sweeps }))).toThrow('sweeps'); + } + expect(readSecurityPolicy(stored({ sweeps: { on: true, everyDays: 400 } })).sweeps).toEqual({ + on: true, + everyDays: 90, + }); + // Bad data never starts paid scans. + expect(readSecurityPolicy(stored({ sweeps: { on: 'yes' } })).sweeps.on).toBe(false); + expect(readSecurityPolicy(stored({ sweeps: null })).sweeps.on).toBe(false); + }); +}); + +describe('fallback and digest settings (M26)', () => { + it('reads a row saved before M26 as off', () => { + const { fallbackToCf: _f, digest: _d, ...old } = stored() as Record; + for (const read of [parseSecurityPolicy, readSecurityPolicy]) { + expect(read(old)).toMatchObject({ fallbackToCf: false, digest: false }); + } + }); + + it('refuses a non-boolean on write and reads it as off', () => { + for (const field of ['fallbackToCf', 'digest'] as const) { + expect(() => parseSecurityPolicy(stored({ [field]: 'yes' }))).toThrow(field); + expect(readSecurityPolicy(stored({ [field]: 'yes' }))[field]).toBe(false); + expect(readSecurityPolicy(stored({ [field]: null }))[field]).toBe(false); + } + }); +}); + +describe('security webhook URL (M26)', () => { + it('takes an https URL and normalizes it', () => { + expect(parseSecurityWebhookUrl('https://hooks.example.com/void?x=1')).toBe( + 'https://hooks.example.com/void?x=1', + ); + expect(parseSecurityWebhookUrl('HTTPS://Hooks.Example.com')).toBe('https://hooks.example.com/'); + }); + + it('refuses http, credentials, fragments, junk and very long URLs', () => { + for (const value of [ + 'http://hooks.example.com/', + 'https://user:pass@hooks.example.com/', + 'https://hooks.example.com/#x', + 'not a url', + '', + null, + `https://example.com/${'a'.repeat(2048)}`, + ]) { + expect(() => parseSecurityWebhookUrl(value)).toThrow('webhook URL'); + } + }); +}); + +describe('security limits and budgets', () => { + it('accepts each range edge and refuses one past it', () => { + for (const key of SECURITY_LIMIT_KEYS) { + const { min, max } = SECURITY_LIMIT_RANGES[key]; + expect(parseSecurityLimitsPatch({ [key]: min })).toEqual({ [key]: min }); + expect(parseSecurityLimitsPatch({ [key]: max })).toEqual({ [key]: max }); + for (const bad of [min - 1, max + 1, min + 0.5, String(min), null]) { + expect(() => parseSecurityLimitsPatch({ [key]: bad })).toThrow( + `${key} must be a whole number from ${min} to ${max}.`, + ); + } + } + }); + + it('refuses unknown limit keys and partial full limits', () => { + expect(() => parseSecurityLimitsPatch({ timeout: 10 })).toThrow('Unknown security limit'); + expect(parseSecurityLimitsPatch({})).toEqual({}); + expect(() => parseSecurityLimits({ concurrency: 2 })).toThrow('timeoutMinutes'); + }); + + it('takes USD amounts in whole cents up to the maximum', () => { + for (const amount of [0, 0.01, 0.29, 40, 1500.5, 1_000_000]) { + expect(parseSecurityUsd(amount, 'cap')).toBe(amount); + } + for (const amount of [-0.01, 0.001, 1_000_000.01, Number.NaN, Infinity, '100', null]) { + expect(() => parseSecurityUsd(amount, 'cap')).toThrow('cap must be a USD amount'); + } + }); + + it('needs every budget field', () => { + expect(() => + parseSecurityBudgets({ platformCapOn: true, platformMonthlyUsd: 10, projectCapsOn: false }), + ).toThrow('projectDefaultMonthlyUsd'); + expect(() => + parseSecurityBudgets({ + platformCapOn: 'yes', + platformMonthlyUsd: 10, + projectCapsOn: false, + projectDefaultMonthlyUsd: 1, + }), + ).toThrow('platformCapOn must be true or false'); + }); +}); + +describe('security entitlement freshness', () => { + const now = Date.parse(CHECKED_AT); + + it('counts a passing probe for 24 hours', () => { + const entitlement = parseSecurityPolicy( + stored({ entitlement: passingEntitlement }), + ).entitlement; + expect(isSecurityEntitlementFresh(entitlement, now)).toBe(true); + expect(isSecurityEntitlementFresh(entitlement, now + SECURITY_ENTITLEMENT_MAX_AGE_MS - 1)).toBe( + true, + ); + expect(isSecurityEntitlementFresh(entitlement, now + SECURITY_ENTITLEMENT_MAX_AGE_MS)).toBe( + false, + ); + // A probe time in the future (clock skew or bad data) is not fresh. + expect(isSecurityEntitlementFresh(entitlement, now - 1)).toBe(false); + }); + + it('never counts a failed or missing probe', () => { + expect(isSecurityEntitlementFresh(null, now)).toBe(false); + expect( + isSecurityEntitlementFresh({ ...passingEntitlement, ok: false, missing: ['egress'] }, now), + ).toBe(false); + }); +}); + +describe('security error codes', () => { + it('lists the spec §13.5 codes with their status', () => { + expect(Object.values(SECURITY_ERRORS).map((entry) => `${entry.status} ${entry.code}`)).toEqual([ + '422 security model not allowed', + '422 provider notice not accepted', + '409 security entitlement missing', + '409 finding changed', + '422 security budget above platform limit', + '409 security public gate needs zero trust', + '409 security public gate needs policy', + '409 security public gate on', + '409 no public request', + '409 public request closed', + '409 security public request has urgent findings', + '422 scan bypass reason required', + '503 security policy unreadable', + ]); + }); + + it('does not reuse the removed deploy gate names', () => { + expect(isSecurityErrorCode('security policy unreadable')).toBe(true); + expect(isSecurityErrorCode('security findings unresolved')).toBe(false); + expect(isSecurityErrorCode('security bypass invalid')).toBe(false); + expect(isSecurityErrorCode('platform capability unavailable')).toBe(false); + }); +}); + +describe('per-plan scan caps (M27)', () => { + it('reads a stored row leniently: bad entries inherit, a JSON null is no cap', () => { + expect(readPlanSecurityCaps(null)).toEqual({ caps: {}, dropped: 0 }); + expect(readPlanSecurityCaps([5000])).toEqual({ caps: {}, dropped: 1 }); + expect( + readPlanSecurityCaps({ + pro: 5000, + team: null, + free: 0, + bad: -1, + half: 12.5, + Upper: 10, + huge: 100_000_001, + text: '5', + }), + ).toEqual({ caps: { pro: 5000, team: null, free: 0 }, dropped: 5 }); + const caps = { pro: 5000, team: null }; + expect(planSecurityCap(caps, 'pro')).toBe(5000); + expect(planSecurityCap(caps, 'team')).toBe('none'); + expect(planSecurityCap(caps, 'free')).toBe('inherit'); + expect(planSecurityCap(caps, 'constructor')).toBe('inherit'); + }); + + it('parses a change and writes a new row without touching other plans', () => { + expect(parsePlanSecurityCapInput(undefined)).toBeUndefined(); + expect(parsePlanSecurityCapInput(12.5)).toBe(1250); + expect(parsePlanSecurityCapInput(0)).toBe(0); + expect(parsePlanSecurityCapInput('none')).toBe('none'); + expect(parsePlanSecurityCapInput('inherit')).toBe('inherit'); + for (const bad of [12.345, -1, 1_000_001, '50', null, true]) { + expect(() => parsePlanSecurityCapInput(bad)).toThrow(); + } + const caps = { pro: 5000, team: null }; + expect(withPlanSecurityCap(caps, 'pro', 'inherit')).toEqual({ team: null }); + expect(withPlanSecurityCap(caps, 'free', 'none')).toEqual({ + pro: 5000, + team: null, + free: null, + }); + expect(withPlanSecurityCap(caps, 'team', 700)).toEqual({ pro: 5000, team: 700 }); + expect(caps).toEqual({ pro: 5000, team: null }); + }); + + it('formats a cap for the CLI and the admin panel', () => { + expect(formatPlanSecurityCap(123_456)).toBe('$1,234.56 / month'); + expect(formatPlanSecurityCap(0)).toBe('$0.00 / month'); + expect(formatPlanSecurityCap('none')).toBe('no cap'); + expect(formatPlanSecurityCap('inherit')).toBe('policy default'); + }); +}); + +describe('security form text (M29)', () => { + it('reads whole numbers of a bounded length', () => { + expect(parseSecurityDigits('0', 3)).toBe(0); + expect(parseSecurityDigits('123', 3)).toBe(123); + for (const text of ['', '1234', '-1', '1.0', ' 1', '1e3', '١']) { + expect(parseSecurityDigits(text, 3), text).toBeNull(); + } + }); + + it('reads finding labels as the page prints them', () => { + expect(parseSecurityFindingLabel('F-12')).toBe(12); + expect(parseSecurityFindingLabel('F-123456789')).toBe(123456789); + for (const text of ['F-', 'F-1234567890', 'f-1', '12', 'F-1x', 'sf_1']) { + expect(parseSecurityFindingLabel(text), text).toBeNull(); + } + }); + + it('reads a typed dollar amount, empty as no cap', () => { + expect(parseSecurityUsdText('')).toBeNull(); + expect(parseSecurityUsdText(' ')).toBeNull(); + expect(parseSecurityUsdText('50')).toBe(50); + expect(parseSecurityUsdText(' $12.50 ')).toBe(12.5); + expect(parseSecurityUsdText('0.5')).toBe(0.5); + for (const text of [ + '$', + 'abc', + '-1', + '1.234', + '12.', + '.5', + '1.2.3', + '$$5', + '12345678', + '1e3', + ]) { + expect(parseSecurityUsdText(text), text).toBeUndefined(); + } + }); +}); diff --git a/packages/platform/test/unit/worker-config.test.ts b/packages/platform/test/unit/worker-config.test.ts index fe4fe618d..c18fbf117 100644 --- a/packages/platform/test/unit/worker-config.test.ts +++ b/packages/platform/test/unit/worker-config.test.ts @@ -203,11 +203,104 @@ describe('platform usage queue bindings', () => { }); it('creates core Durable Objects with SQLite while preserving migration tags', () => { - expect(workerConfigs().api.migrations).toEqual([ + const core = [ { tag: 'v1', new_sqlite_classes: ['UsageCounter'] }, { tag: 'v2', new_sqlite_classes: ['CronScheduler'] }, { tag: 'v3', new_sqlite_classes: ['ErrorAlertMonitor'] }, { tag: 'v4', new_sqlite_classes: ['SandboxConcurrencyCounter'] }, + ]; + // A runtime released before security audits has no scheduler class to migrate. + expect(workerConfigs().api.migrations).toEqual(core); + expect(workerConfigs({ securityScanScheduler: true }).api.migrations).toEqual([ + ...core, + { tag: 'security-audits-v1', new_sqlite_classes: ['SecurityScanScheduler'] }, ]); }); }); + +describe('security audits Worker configs', () => { + const workers = ['api', 'dispatch', 'emailGateway', 'proxy', 'tail'] as const; + const current = () => workerConfigs({ securityScanScheduler: true }); + const enabled = () => + workerConfigs({ + securityScanScheduler: true, + deployment: createPlatformDeploymentManifest({ + ...deploymentInput, + capabilities: { securityAudits: true }, + }), + }); + // PLATFORM_CAPABILITIES as written before security audits existed. + const legacyCapabilities = JSON.stringify({ + ai: true, + customDomains: false, + email: false, + githubActions: false, + githubOAuth: true, + googleOAuth: false, + managedBuilds: false, + sandbox: false, + }); + + it('adds only the scheduler binding and its migration when the capability is off', () => { + const configs = current(); + const older = workerConfigs(); + const { durable_objects: _bindings, migrations, ...rest } = configs.api; + const { + durable_objects: _olderBindings, + migrations: olderMigrations, + ...olderRest + } = older.api; + expect(rest).toEqual(olderRest); + expect(migrations).toEqual([ + ...(olderMigrations as Array), + { tag: 'security-audits-v1', new_sqlite_classes: ['SecurityScanScheduler'] }, + ]); + for (const worker of ['dispatch', 'emailGateway', 'proxy', 'tail'] as const) { + expect(configs[worker]).toEqual(older[worker]); + } + expect(Object.keys(configs).sort()).toEqual([...workers]); + expect((configs.api.durable_objects as { bindings: Array }).bindings).toEqual([ + { name: 'USAGE_COUNTER', class_name: 'UsageCounter' }, + { name: 'CRON_SCHEDULER', class_name: 'CronScheduler' }, + { name: 'ERROR_ALERT_MONITOR', class_name: 'ErrorAlertMonitor' }, + { name: 'SANDBOX_CONCURRENCY_COUNTER', class_name: 'SandboxConcurrencyCounter' }, + { name: 'SECURITY_SCAN_SCHEDULER', class_name: 'SecurityScanScheduler' }, + ]); + expect(configs.api).not.toHaveProperty('ai'); + expect(configs.api).not.toHaveProperty('containers'); + for (const worker of ['api', 'proxy', 'emailGateway'] as const) { + expect((configs[worker].vars as Record).PLATFORM_CAPABILITIES).toBe( + legacyCapabilities, + ); + } + expect(JSON.stringify(configs)).not.toContain('securityAudits'); + }); + + it('adds only the AI binding on the API Worker when the capability is on', () => { + const off = current(); + const on = enabled(); + expect(Object.keys(on).sort()).toEqual([...workers]); + expect(on.api.ai).toEqual({ binding: 'AI' }); + for (const worker of workers) { + const { ai, vars, ...rest } = on[worker]; + const { ai: offAi, vars: offVars, ...offRest } = off[worker]; + expect(rest).toEqual(offRest); + expect(ai).toEqual(worker === 'api' ? { binding: 'AI' } : offAi); + const { PLATFORM_CAPABILITIES: capabilities, ...otherVars } = (vars ?? {}) as Record< + string, + unknown + >; + const { PLATFORM_CAPABILITIES: offCapabilities, ...offOtherVars } = (offVars ?? {}) as Record< + string, + unknown + >; + expect(otherVars).toEqual(offOtherVars); + if (offCapabilities !== undefined) { + expect(JSON.parse(String(capabilities))).toEqual({ + ...JSON.parse(String(offCapabilities)), + securityAudits: true, + }); + } + } + }); +}); diff --git a/packages/platform/vite.config.ts b/packages/platform/vite.config.ts index d9151121e..e53d9a2f3 100644 --- a/packages/platform/vite.config.ts +++ b/packages/platform/vite.config.ts @@ -29,6 +29,10 @@ export default defineConfig({ 'src/plans.ts', 'src/ai-logging.ts', 'src/browser-page.ts', + 'src/security-models.ts', + 'src/security-policy.ts', + 'src/security-local-check.ts', + 'src/security-lockfile.ts', ], format: 'esm', dts: true, diff --git a/packages/void/skills/void/SKILL.md b/packages/void/skills/void/SKILL.md index f36ee0b6e..13d61d278 100644 --- a/packages/void/skills/void/SKILL.md +++ b/packages/void/skills/void/SKILL.md @@ -36,52 +36,54 @@ Use `void deploy --skip-migrations` when database migrations run separately; it ## Task Routing -| User intent | Docs file(s) | -| ------------------------------------------ | ----------------------------------------------------------------------------------------- | -| CLI command syntax, flags, env vars | `docs/reference/cli.md` | -| Initial setup, onboarding, first app | `docs/guide/quickstart.md`, `docs/reference/cli/setup.md` | -| App type detection and mode behavior | `docs/guide/app-types.md`, `docs/reference/config.md` | -| Server/API routing and middleware | `docs/guide/server-routing.md`, `docs/integrations/hono.md` | -| Pages mode, loader/action, forms, layouts | `docs/guide/pages-routing/*.md`, `docs/guide/type-safety.md` | -| Database and migrations | `docs/guide/database.md`, `docs/guide/type-safety.md` | -| D1 replicas, bookmarks, read-after-write | `docs/guide/database/d1.md`, `docs/reference/api/database.md` | -| Typed fetch and end-to-end typing | `docs/guide/typed-fetch.md`, `docs/guide/type-safety.md` | -| Authentication | `docs/guide/auth.md`, `docs/reference/api/auth.md`, `docs/guide/env-vars.md` | -| Cloudflare runtime bindings and config | `docs/integrations/cloudflare.md`, `docs/reference/config.md`, `docs/guide/env-vars.md` | -| AI inference (Workers AI, providers) | `docs/guide/ai.md` | -| Platform AI logging policy | `docs/reference/cli/platform-users.md#ai-gateway-logging` | -| Durable State and WebSockets | `docs/guide/durable-state.md`, `docs/guide/websockets.md` | -| Server-sent events and live streams | `docs/guide/sse.md`, `docs/guide/live.md` | -| Sandboxes | `docs/guide/sandboxes.md` | -| Email | `docs/guide/email.md`, then the matching guide under `docs/guide/email/` | -| KV / storage / queues / cron jobs | `docs/guide/kv.md`, `docs/guide/storage.md`, `docs/guide/queues.md`, `docs/guide/jobs.md` | -| SSR and caching | `docs/guide/ssr.md`, `docs/guide/edge/*.md` | -| HTTPS, rewrites, redirects, fallbacks | `docs/guide/edge/rewrites.md`, `docs/guide/edge/redirects.md`, `docs/reference/config.md` | -| Static site generation | `docs/guide/ssg.md` | -| Testing an app with Vitest (`vp test`) | `docs/guide/testing.md` | -| Connected apps and artifact preparation | `docs/guide/platform/administration/connected-apps.md`, `docs/reference/api/deploy.md` | -| Deployment and CI | `docs/guide/deployment.md`, `docs/reference/cli/deploy.md` | -| Install or maintain a company platform | `docs/guide/self-hosted-platform.md`, `docs/reference/cli/platform-installation.md` | -| Develop or deploy a platform fork | `docs/guide/platform-development.md`, `docs/guide/self-hosted-platform.md` | -| Platform administration | `docs/guide/platform-administration.md`, `docs/reference/cli/platform.md` | -| Platform plans and account limits | `docs/guide/platform/administration/plans.md`, `docs/reference/cli/platform-config.md` | -| Self-host deploy to own Cloudflare account | `docs/integrations/cloudflare.md`, `docs/reference/cli/deploy.md` | -| Project status, deployment history | `docs/reference/cli/project.md` | -| Cache purging | `docs/reference/cli/project.md` | -| Project logs, runtime errors | `docs/reference/cli/project.md` | -| Secrets management (put/sync/delete) | `docs/reference/cli/secrets.md`, `docs/guide/env-vars.md` | -| Typed env vars (`defineEnv`, `env.ts`) | `docs/guide/env-vars.md` | -| Custom domain setup | `docs/reference/cli/domains.md` | -| Database status, reset, seed, export | `docs/reference/cli/database.md`, `docs/guide/database.md` | -| Auth login/logout/whoami | `docs/reference/cli/auth.md` | -| Overview / introduction | `docs/guide/index.md` | -| API surface details | `docs/reference/api.md` | -| Meta framework integration | `docs/integrations/frameworks/*.md` | -| Coding agent setup | `docs/integrations/agents.md` | -| Node.js / Bun / Deno targets | `docs/integrations/nodejs-bun-deno.md` | -| ORMs and external databases | `docs/guide/database.md` | -| Project structure and conventions | `docs/reference/structure.md` | -| Resource/binding inference | `docs/reference/resource-inference.md` | +| User intent | Docs file(s) | +| ------------------------------------------ | -------------------------------------------------------------------------------------------------- | +| CLI command syntax, flags, env vars | `docs/reference/cli.md` | +| Initial setup, onboarding, first app | `docs/guide/quickstart.md`, `docs/reference/cli/setup.md` | +| App type detection and mode behavior | `docs/guide/app-types.md`, `docs/reference/config.md` | +| Server/API routing and middleware | `docs/guide/server-routing.md`, `docs/integrations/hono.md` | +| Pages mode, loader/action, forms, layouts | `docs/guide/pages-routing/*.md`, `docs/guide/type-safety.md` | +| Database and migrations | `docs/guide/database.md`, `docs/guide/type-safety.md` | +| D1 replicas, bookmarks, read-after-write | `docs/guide/database/d1.md`, `docs/reference/api/database.md` | +| Typed fetch and end-to-end typing | `docs/guide/typed-fetch.md`, `docs/guide/type-safety.md` | +| Authentication | `docs/guide/auth.md`, `docs/reference/api/auth.md`, `docs/guide/env-vars.md` | +| Cloudflare runtime bindings and config | `docs/integrations/cloudflare.md`, `docs/reference/config.md`, `docs/guide/env-vars.md` | +| AI inference (Workers AI, providers) | `docs/guide/ai.md` | +| Platform AI logging policy | `docs/reference/cli/platform-users.md#ai-gateway-logging` | +| Durable State and WebSockets | `docs/guide/durable-state.md`, `docs/guide/websockets.md` | +| Server-sent events and live streams | `docs/guide/sse.md`, `docs/guide/live.md` | +| Sandboxes | `docs/guide/sandboxes.md` | +| Email | `docs/guide/email.md`, then the matching guide under `docs/guide/email/` | +| KV / storage / queues / cron jobs | `docs/guide/kv.md`, `docs/guide/storage.md`, `docs/guide/queues.md`, `docs/guide/jobs.md` | +| SSR and caching | `docs/guide/ssr.md`, `docs/guide/edge/*.md` | +| HTTPS, rewrites, redirects, fallbacks | `docs/guide/edge/rewrites.md`, `docs/guide/edge/redirects.md`, `docs/reference/config.md` | +| Static site generation | `docs/guide/ssg.md` | +| Testing an app with Vitest (`vp test`) | `docs/guide/testing.md` | +| Connected apps and artifact preparation | `docs/guide/platform/administration/connected-apps.md`, `docs/reference/api/deploy.md` | +| Deployment and CI | `docs/guide/deployment.md`, `docs/reference/cli/deploy.md` | +| Install or maintain a company platform | `docs/guide/self-hosted-platform.md`, `docs/reference/cli/platform-installation.md` | +| Develop or deploy a platform fork | `docs/guide/platform-development.md`, `docs/guide/self-hosted-platform.md` | +| Platform administration | `docs/guide/platform-administration.md`, `docs/reference/cli/platform.md` | +| Security audits, scan before public | `docs/guide/platform/administration/security-audits.md`, `docs/reference/cli/platform-security.md` | +| Security findings, check before deploy | `docs/reference/cli/project.md` | +| Platform plans and account limits | `docs/guide/platform/administration/plans.md`, `docs/reference/cli/platform-config.md` | +| Self-host deploy to own Cloudflare account | `docs/integrations/cloudflare.md`, `docs/reference/cli/deploy.md` | +| Project status, deployment history | `docs/reference/cli/project.md` | +| Cache purging | `docs/reference/cli/project.md` | +| Project logs, runtime errors | `docs/reference/cli/project.md` | +| Secrets management (put/sync/delete) | `docs/reference/cli/secrets.md`, `docs/guide/env-vars.md` | +| Typed env vars (`defineEnv`, `env.ts`) | `docs/guide/env-vars.md` | +| Custom domain setup | `docs/reference/cli/domains.md` | +| Database status, reset, seed, export | `docs/reference/cli/database.md`, `docs/guide/database.md` | +| Auth login/logout/whoami | `docs/reference/cli/auth.md` | +| Overview / introduction | `docs/guide/index.md` | +| API surface details | `docs/reference/api.md` | +| Meta framework integration | `docs/integrations/frameworks/*.md` | +| Coding agent setup | `docs/integrations/agents.md` | +| Node.js / Bun / Deno targets | `docs/integrations/nodejs-bun-deno.md` | +| ORMs and external databases | `docs/guide/database.md` | +| Project structure and conventions | `docs/reference/structure.md` | +| Resource/binding inference | `docs/reference/resource-inference.md` | ## Working rules @@ -101,6 +103,10 @@ Use `void deploy --skip-migrations` when database migrations run separately; it `docs/guide/self-hosted-platform.md`. Use `void platform list` to find the installation slug for maintenance. For recovery, use its documented resume or repair workflow and preserve the installation's credentials and resources. +- Findings from security audits are advice from an AI review. Resolve them or change their severity + only with a reason the user gave, and never bypass a scan before public without the user's explicit + request. Scans and `void project security check` cost money and send code to a model; run them only + when the user asks. - Use `--plan` to review platform changes. If an operation has an uncertain outcome, inspect its status and events before retrying. diff --git a/packages/void/src/cli/cli-main.ts b/packages/void/src/cli/cli-main.ts index df41fe534..5173fdad8 100644 --- a/packages/void/src/cli/cli-main.ts +++ b/packages/void/src/cli/cli-main.ts @@ -96,6 +96,22 @@ async function runSubcommandGroup( process.exit(1); } const message = formatCloudflareUserMessage(err instanceof Error ? err.message : String(err)); + if ( + command === 'project' && + (args[1] === 'zero-trust' || args[1] === 'security') && + args.includes('--json') + ) { + const status = (err as { status?: unknown }).status; + const code = (err as { code?: unknown }).code; + console.error( + JSON.stringify({ + error: typeof code === 'string' ? code : 'invalid_command', + message, + ...(typeof status === 'number' ? { status } : {}), + }), + ); + process.exit(1); + } if (command === 'platform') { const platformMessage = message.replace(/^platform:/, pc.bold(pc.red('platform:'))); console.error( @@ -310,7 +326,7 @@ if (helpPath) { }, { name: 'project', - hint: 'status | link | list | team | token | zero-trust | logs | requests | rollback | cancel | delete | purge-cache', + hint: 'status | link | list | team | token | zero-trust | security | logs | requests | rollback | cancel | delete | purge-cache', description: 'Manage projects, teams, deployments, and scoped CI credentials', }, { name: 'secret', hint: 'list | put | delete | sync', description: 'Manage project secrets' }, diff --git a/packages/void/src/cli/client.ts b/packages/void/src/cli/client.ts index 0d4971b04..d64c9296d 100644 --- a/packages/void/src/cli/client.ts +++ b/packages/void/src/cli/client.ts @@ -1,4 +1,5 @@ import { readFileSync } from 'node:fs'; +import type { SecurityPackageClaims } from '@void/platform/security-lockfile'; import { join } from 'pathslash'; import { cfAccessHeaders } from '../shared/cf-access.ts'; import { getPackageDir } from './agents.ts'; @@ -13,6 +14,23 @@ import { type ProjectPermission, } from './platform-errors.ts'; import { normalizePlatformApiUrl } from './platform-registry.ts'; +import type { + ProjectSecurityStatus, + SecurityPublicRequest, + SecurityBudgetChange, + SecurityCheckCreated, + SecurityCheckPreview, + SecurityCheckView, + SecurityFindingChange, + SecurityFindingDetail, + SecurityFindingList, + SecurityFindingQuery, + SecurityModelChange, + SecurityRescanPreview, + SecurityRescanQueued, + SecurityScanList, + SecuritySeverityChange, +} from './security-api-types.ts'; import type { DeployAssetUploadRequest, DeployEvent, @@ -155,6 +173,28 @@ async function throwPlatformApiError( ); } +/** + * Turns a refused security route into the sentence the user should read. A 404 with no JSON body + * is the router of a platform that has no security routes; a 404 with JSON is a real miss (unknown + * project or finding). The platform's own message is the copy for the other refusals. + */ +export function securityApiError(error: unknown): unknown { + if (!(error instanceof PlatformApiError)) { + return error; + } + const parsed = parsePlatformErrorBody(error.body); + if (error.status === 404 && parsed === null) { + return new Error( + 'project: This Void platform does not support security audits. Ask its administrator to upgrade with `void platform upgrade`.', + ); + } + const message = platformErrorMessage(parsed); + if (message && [400, 409, 413, 422, 501, 503].includes(error.status)) { + error.message = message; + } + return error; +} + export function isExpiredTokenError(error: unknown): boolean { if (error instanceof PlatformApiError) { return error.status === 401 && error.code === 'invalid or expired token'; @@ -279,6 +319,9 @@ export type ProjectZeroTrustResponse = { | 'disabling' | 'error'; protectNewProjects: boolean; + /** Present on platforms with security audits (the gate and the open public request). */ + publicGate?: boolean; + publicRequest?: SecurityPublicRequest | null; project: ProjectZeroTrustState | null; }; @@ -286,6 +329,15 @@ export type ProjectZeroTrustResponse = { export type ProjectZeroTrustUpdateResponse = { ok: true; project: ProjectZeroTrustState; + /** Set when a public gate request exists for the project (a held request answers 202). */ + publicRequest?: SecurityPublicRequest | null; + /** The platform's copy for a held request. */ + message?: string; +}; + +/** `POST /projects/:id/zero-trust/public-request/bypass`. */ +export type ProjectPublicRequestBypassResponse = ProjectZeroTrustUpdateResponse & { + skipped: string | null; }; export type IssuedProjectDeployCredentialResponse = ProjectDeployCredentialResponse & { @@ -573,7 +625,14 @@ export type GithubConnection = { updated_at: string; }; -export type ManifestOnlyDeployPayload = DeployUploadPayload; +/** + * `securityPackages`: what the project lockfile says about the packages the Worker + * bundle names, for security scans (`deploy-security-packages.ts`). Older platforms + * ignore it. + */ +export type ManifestOnlyDeployPayload = DeployUploadPayload & { + securityPackages?: SecurityPackageClaims; +}; // Only fetch rejections (TypeError, including a headers timeout) are retried; any // HTTP response is final. Every attempt sends the same idempotency key, so the @@ -839,11 +898,17 @@ export class PlatformClient { private async call( url: string | URL, action: string, - options: { method?: string; body?: unknown; permission?: ProjectPermission } = {}, + options: { + method?: string; + body?: unknown; + permission?: ProjectPermission; + signal?: AbortSignal; + } = {}, ): Promise { - const { method, body, permission } = options; + const { method, body, permission, signal } = options; const res = await this.request(url, { ...(method !== undefined && { method }), + ...(signal !== undefined && { signal }), headers: body === undefined ? { ...this.authHeaders } @@ -859,7 +924,12 @@ export class PlatformClient { private async json( url: string | URL, action: string, - options?: { method?: string; body?: unknown; permission?: ProjectPermission }, + options?: { + method?: string; + body?: unknown; + permission?: ProjectPermission; + signal?: AbortSignal; + }, ): Promise { return (await this.call(url, action, options)).json() as Promise; } @@ -949,6 +1019,278 @@ export class PlatformClient { ); } + private async security( + path: string, + action: string, + options: { + method?: string; + body?: unknown; + permission: ProjectPermission; + signal?: AbortSignal; + }, + ): Promise { + try { + return await this.json(`${this.baseUrl}/projects/${path}`, action, options); + } catch (error) { + throw securityApiError(error); + } + } + + async getProjectSecurity( + projectId: string, + options: { signal?: AbortSignal } = {}, + ): Promise { + return this.security(`${projectId}/security`, 'Failed to read project security', { + permission: 'read', + ...(options.signal !== undefined && { signal: options.signal }), + }); + } + + async listProjectSecurityFindings( + projectId: string, + query: SecurityFindingQuery, + ): Promise { + const params = new URLSearchParams({ state: query.state, limit: String(query.limit) }); + if (query.urgent) { + params.set('urgent', '1'); + } + if (query.severity) { + params.set('severity', query.severity); + } + if (query.cursor) { + params.set('cursor', query.cursor); + } + return this.security( + `${projectId}/security/findings?${params}`, + 'Failed to list security findings', + { permission: 'read' }, + ); + } + + async getProjectSecurityFinding( + projectId: string, + findingId: string, + ): Promise { + return this.security( + `${projectId}/security/findings/${encodeURIComponent(findingId)}`, + 'Failed to read security finding', + { permission: 'read' }, + ); + } + + async commentOnProjectSecurityFinding( + projectId: string, + findingId: string, + text: string, + ): Promise<{ ok: true; id: string }> { + return this.security( + `${projectId}/security/findings/${encodeURIComponent(findingId)}/comments`, + 'Failed to comment on security finding', + { method: 'POST', body: { text }, permission: 'configure' }, + ); + } + + async resolveProjectSecurityFinding( + projectId: string, + findingId: string, + body: { reason: string; comment: string; expectedRevision: number }, + ): Promise { + return this.security( + `${projectId}/security/findings/${encodeURIComponent(findingId)}/resolve`, + 'Failed to resolve security finding', + { method: 'POST', body, permission: 'settings' }, + ); + } + + async reopenProjectSecurityFinding( + projectId: string, + findingId: string, + body: { comment: string; expectedRevision: number }, + ): Promise { + return this.security( + `${projectId}/security/findings/${encodeURIComponent(findingId)}/reopen`, + 'Failed to reopen security finding', + { method: 'POST', body, permission: 'settings' }, + ); + } + + /** Sets a finding's severity (`null`: back to the scan value). */ + async editProjectSecurityFindingSeverity( + projectId: string, + findingId: string, + body: { severity: string | null; comment: string; expectedRevision: number }, + ): Promise { + try { + return await this.json( + `${this.baseUrl}/projects/${projectId}/security/findings/${encodeURIComponent(findingId)}/severity`, + 'Failed to change the severity of the security finding', + { method: 'POST', body, permission: 'settings' }, + ); + } catch (error) { + // The finding was read just before, so a 404 with no JSON body is a platform without this route. + if ( + error instanceof PlatformApiError && + error.status === 404 && + parsePlatformErrorBody(error.body) === null + ) { + throw new Error( + 'project: This Void platform cannot change finding severity yet. Ask its administrator to upgrade with `void platform upgrade`.', + ); + } + throw securityApiError(error); + } + } + + async listProjectSecurityScans(projectId: string, limit: number): Promise { + return this.security( + `${projectId}/security/scans?${new URLSearchParams({ limit: String(limit) })}`, + 'Failed to list security scans', + { permission: 'deploy' }, + ); + } + + /** The rescan cost check: what a project rescan would run, queuing nothing. */ + async previewProjectSecurityScan( + projectId: string, + options: { clientAssets?: boolean } = {}, + ): Promise { + return this.security(`${projectId}/security/scans`, 'Failed to preview the security scan', { + method: 'POST', + body: { dryRun: true, ...(options.clientAssets ? { clientAssets: true } : {}) }, + permission: 'settings', + }); + } + + async startProjectSecurityScan( + projectId: string, + options: { clientAssets?: boolean } = {}, + ): Promise { + return this.security(`${projectId}/security/scans`, 'Failed to start the security scan', { + method: 'POST', + body: options.clientAssets ? { clientAssets: true } : {}, + permission: 'settings', + }); + } + + /** + * M32 local check. A platform without the check routes answers a plain 404: it is + * named as too old, not as one without security audits. + */ + private async securityCheck( + path: string, + action: string, + options: { method?: string; body?: unknown }, + ): Promise { + try { + return await this.json(`${this.baseUrl}/projects/${path}`, action, { + ...options, + permission: 'deploy', + }); + } catch (error) { + if ( + error instanceof PlatformApiError && + error.status === 404 && + parsePlatformErrorBody(error.body) === null + ) { + throw new Error( + 'project: This Void platform cannot run local security checks yet. Ask its administrator to upgrade with `void platform upgrade`.', + ); + } + throw securityApiError(error); + } + } + + /** What a local check would run (model, provider notice, most it can cost). Sends no code. */ + async previewProjectSecurityCheck( + projectId: string, + tree: { files: number; bytes: number; size: number; md5: string }, + ): Promise { + return this.securityCheck( + `${projectId}/security/checks`, + 'Failed to prepare the security check', + { + method: 'POST', + body: { dryRun: true, ...tree }, + }, + ); + } + + /** Stores the check and returns the one presigned upload for its archive. */ + async createProjectSecurityCheck( + projectId: string, + tree: { files: number; bytes: number; size: number; md5: string }, + ): Promise { + return this.securityCheck( + `${projectId}/security/checks`, + 'Failed to start the security check', + { + method: 'POST', + body: tree, + }, + ); + } + + async startProjectSecurityCheck( + projectId: string, + checkId: string, + ): Promise<{ checkId: string; status: string }> { + return this.securityCheck( + `${projectId}/security/checks/${encodeURIComponent(checkId)}/start`, + 'Failed to start the security check', + { method: 'POST', body: {} }, + ); + } + + async getProjectSecurityCheck(projectId: string, checkId: string): Promise { + return this.securityCheck( + `${projectId}/security/checks/${encodeURIComponent(checkId)}`, + 'Failed to read the security check', + {}, + ); + } + + async setProjectSecurityModel( + projectId: string, + body: { model: string | null; acceptProviderNoticeVersion?: number }, + ): Promise { + return this.security(`${projectId}/security/model`, 'Failed to set security model', { + method: 'PUT', + body, + permission: 'settings', + }); + } + + async setProjectSecurityBudget( + projectId: string, + monthlyUsd: number | null, + ): Promise { + return this.security(`${projectId}/security/budget`, 'Failed to set security budget', { + method: 'PUT', + body: { monthlyUsd }, + permission: 'settings', + }); + } + + async createProjectSecurityPageLink( + projectId: string, + ): Promise<{ url: string; expiresAt: string }> { + return this.security(`${projectId}/security/page-link`, 'Failed to create security page link', { + method: 'POST', + permission: 'read', + }); + } + + async bypassProjectPublicRequest( + projectId: string, + reason: string, + ): Promise { + return this.security( + `${projectId}/zero-trust/public-request/bypass`, + 'Failed to bypass the security scan', + { method: 'POST', body: { reason }, permission: 'settings' }, + ); + } + async reconcileProjectZeroTrust(projectId: string): Promise { return this.json( `${this.baseUrl}/projects/${projectId}/zero-trust/reconcile`, diff --git a/packages/void/src/cli/deploy-managed-events.ts b/packages/void/src/cli/deploy-managed-events.ts index 8f62953d3..ffbc3e6cb 100644 --- a/packages/void/src/cli/deploy-managed-events.ts +++ b/packages/void/src/cli/deploy-managed-events.ts @@ -11,6 +11,7 @@ import { formatStreamDeployError, } from './deploy-errors.ts'; import { log, DeployEventError } from './deploy-helpers.ts'; +import { readSecurityPackageClaims } from './deploy-security-packages.ts'; import { type ApplyDeployEventResult, type StreamDeployResult } from './deploy-types.ts'; import { uploadAssetsToR2, type DirectR2PutItem } from './direct-r2-upload.ts'; import { type GitDeployMetadata } from './git-metadata.ts'; @@ -283,6 +284,7 @@ export async function streamDirectR2Deploy({ gitMetadata, preflightUsed, workerFiles, + root, spinner: s, cliLog, }: { @@ -296,6 +298,8 @@ export async function streamDirectR2Deploy({ /** Whether preflight let the server reuse any stored asset. */ preflightUsed: boolean; workerFiles?: Map; + /** The project folder: its nearest lockfile gives the security package claims. */ + root?: string; spinner: SpinnerResult; cliLog?: CliLogger; }): Promise { @@ -304,6 +308,11 @@ export async function streamDirectR2Deploy({ if (manifest.database?.readReplication !== undefined) { await client.requireD1ReadReplicationSupport(); } + // Read before the upload, which empties `workerFiles`. + const securityPackages = + root && workerFiles && workerFiles.size > 0 + ? readSecurityPackageClaims(root, workerFiles) + : null; const workerInput = workerFiles && workerFiles.size > 0 && (await client.supportsDirectWorkerUpload()) ? await uploadWorkerModules(client, projectId, workerFiles, s, cliLog) @@ -436,6 +445,9 @@ export async function streamDirectR2Deploy({ }, workerInput, ); + if (securityPackages) { + payload.securityPackages = securityPackages; + } s.message('Finalizing deploy...'); cliLog?.info('finalize_start', { diff --git a/packages/void/src/cli/deploy-managed-framework.ts b/packages/void/src/cli/deploy-managed-framework.ts index 26353a95c..9e3e4611a 100644 --- a/packages/void/src/cli/deploy-managed-framework.ts +++ b/packages/void/src/cli/deploy-managed-framework.ts @@ -23,6 +23,7 @@ import { streamDirectR2Deploy, warnUnpublishedRouting, } from './deploy-managed-events.ts'; +import { printDeploySecurityNotice } from './deploy-security-notice.ts'; import { formatDeploySummary, printDeploySuccess } from './deploy-summary.ts'; import { MANAGED_DEPLOY_BUILD_ENV } from './deploy-transport.ts'; import { type GitDeployMetadata } from './git-metadata.ts'; @@ -243,6 +244,7 @@ export async function runFrameworkDeploy( gitMetadata, preflightUsed: skipped > 0, workerFiles, + root, spinner: s, cliLog, }); @@ -267,4 +269,11 @@ export async function runFrameworkDeploy( warnUnpublishedRouting(result); printDeploySuccess(result.published !== false); + await printDeploySecurityNotice({ + client, + projectId: config.projectId, + slug: config.slug, + deploymentId: result.deployment, + cliLog, + }); } diff --git a/packages/void/src/cli/deploy-managed-full.ts b/packages/void/src/cli/deploy-managed-full.ts index 890792d33..87fac162d 100644 --- a/packages/void/src/cli/deploy-managed-full.ts +++ b/packages/void/src/cli/deploy-managed-full.ts @@ -47,6 +47,7 @@ import { warnUnpublishedRouting, } from './deploy-managed-events.ts'; import { runStaticDeploy, assembleVoidManifest } from './deploy-managed-static.ts'; +import { printDeploySecurityNotice } from './deploy-security-notice.ts'; import { formatDeploySummary, printDeploySuccess } from './deploy-summary.ts'; import { MANAGED_DEPLOY_BUILD_ENV } from './deploy-transport.ts'; import { type GitDeployMetadata } from './git-metadata.ts'; @@ -484,6 +485,7 @@ export async function runFullDeploy( gitMetadata, preflightUsed: skipped > 0, workerFiles, + root, spinner: s, cliLog, }); @@ -506,4 +508,11 @@ export async function runFullDeploy( warnUnpublishedRouting(result); printDeploySuccess(result.published !== false); + await printDeploySecurityNotice({ + client, + projectId: config.projectId, + slug: config.slug, + deploymentId: result.deployment, + cliLog, + }); } diff --git a/packages/void/src/cli/deploy-managed-static.ts b/packages/void/src/cli/deploy-managed-static.ts index 113ee785d..efc07c5ed 100644 --- a/packages/void/src/cli/deploy-managed-static.ts +++ b/packages/void/src/cli/deploy-managed-static.ts @@ -11,6 +11,7 @@ import { streamDirectR2Deploy, warnUnpublishedRouting, } from './deploy-managed-events.ts'; +import { printDeploySecurityNotice } from './deploy-security-notice.ts'; import { formatDeploySummary, printDeploySuccess } from './deploy-summary.ts'; import { MANAGED_DEPLOY_BUILD_ENV } from './deploy-transport.ts'; import { type GitDeployMetadata } from './git-metadata.ts'; @@ -172,4 +173,11 @@ export async function runStaticDeploy( warnUnpublishedRouting(result); printDeploySuccess(result.published !== false); + await printDeploySecurityNotice({ + client, + projectId: config.projectId, + slug: config.slug, + deploymentId: result.deployment, + cliLog, + }); } diff --git a/packages/void/src/cli/deploy-security-notice.ts b/packages/void/src/cli/deploy-security-notice.ts new file mode 100644 index 000000000..c46fbeb83 --- /dev/null +++ b/packages/void/src/cli/deploy-security-notice.ts @@ -0,0 +1,358 @@ +import { PlatformApiError, type PlatformClient } from './client.ts'; +import type { CliLogger } from './log-file.ts'; +import { cleanLine, day, usd } from './project-security.ts'; +import type { + ProjectSecurityStatus, + SecurityScanSummary, + SecurityUrgentFinding, +} from './security-api-types.ts'; + +/** The read is best-effort: it may add this long to CLI exit, never to the deploy. */ +const NOTICE_TIMEOUT_MS = 5_000; +const MAX_ROWS = 5; +const MAX_TITLE = 120; +const PROVIDERS: Record = { + anthropic: 'Anthropic', + openai: 'OpenAI', + google: 'Google', + deepseek: 'DeepSeek', + meta: 'Meta', + mistral: 'Mistral', +}; + +export type DeploySecurityNoticeInput = { + client: PlatformClient; + projectId: string; + slug: string; + deploymentId: string; + cliLog?: CliLogger; + env?: NodeJS.ProcessEnv; + timeoutMs?: number; + write?: (line: string) => void; +}; + +function isObject(value: unknown): value is Record { + return typeof value === 'object' && value !== null; +} + +/** CI logs can be public: print counts and ids only. */ +function inCi(env: NodeJS.ProcessEnv): boolean { + const ci = env.CI; + return ( + (ci !== undefined && ci !== '' && ci !== '0' && ci !== 'false') || Boolean(env.GITHUB_ACTIONS) + ); +} + +function providerName(model: string): string { + const prefix = model.startsWith('@') ? '' : model.split('/')[0]!; + return PROVIDERS[prefix] ?? (prefix ? cleanLine(prefix) : 'a third-party provider'); +} + +function scanLines( + slug: string, + deploymentId: string, + status: ProjectSecurityStatus, +): Array { + const { policy, lastScan, model, budget } = status; + if (!policy.applies || !lastScan || lastScan.deploymentId !== deploymentId) { + return []; + } + const reason = lastScan.statusReason ?? ''; + switch (lastScan.status) { + case 'queued': + case 'running': + case 'pending_input': { + const lines = [ + ` Security scan queued · model ${cleanLine(model.id ?? lastScan.model ?? 'none')} · usually 5–15 min`, + ]; + if (model.thirdParty && model.id) { + lines.push( + ` Run by ${providerName(model.id)}: its usage policy applies and it may refuse. See: void project security model`, + ); + } + if (model.pendingDefault) { + lines.push( + ` Platform default is ${cleanLine(model.pendingDefault)}. Accept to use it:`, + ' void project security model --default --accept-provider-notice', + ); + } + if (status.publicRequest) { + lines.push( + ` ${slug} stays protected by Zero Trust until this scan passes (public request). void project zero-trust status`, + ); + } + lines.push(' Check it: void project security status'); + return lines; + } + case 'skipped': + if (reason === 'budget') { + if (budget && budget.capSource === 'own' && budget.capUsd !== null) { + const lines = [ + ` Not security-scanned: this project's monthly scan budget is used up (${usd(budget.spentUsd)} of ${usd(budget.capUsd)}). Resets ${day(budget.resetsAt)}.`, + ]; + if (budget.ceilingUsd !== null) { + lines.push( + ` A project admin can raise it (up to ${usd(budget.ceilingUsd)}): void project security budget --usd ${Math.floor(budget.ceilingUsd)}`, + ); + } + return lines; + } + return [ + ` Not security-scanned: the platform's monthly scan budget is used up. Resets ${day(budget?.resetsAt)}. Ask your platform admin.`, + ]; + } + if (reason === 'protected') { + return [ + ' Not security-scanned: project is protected by Zero Trust and the platform scans public projects only.', + ]; + } + return []; + case 'succeeded': + return reason === 'no_changes' && lastScan.baseDeploymentId + ? [` Security scan: no code changes since ${cleanLine(lastScan.baseDeploymentId)}.`] + : []; + default: + return []; + } +} + +function failedScanLines(deploymentId: string, status: ProjectSecurityStatus): Array { + const { lastScan, lastSuccessfulScan, deploysSinceLastSuccess, policy } = status; + if (!policy.applies || !lastScan || lastScan.deploymentId === deploymentId) { + return []; + } + const why = failureWhy(lastScan); + if (!why) { + return []; + } + const lines = [ + ` Warning: the security scan of ${cleanLine(lastScan.deploymentId ?? 'the last deploy')} did not finish (${why}).`, + ]; + if (lastSuccessfulScan?.deploymentId && deploysSinceLastSuccess && deploysSinceLastSuccess >= 2) { + lines.push( + ` ${deploysSinceLastSuccess} deploys since the last successful scan (${cleanLine(lastSuccessfulScan.deploymentId)}). This scan covers all changes since then.`, + ); + } + lines.push(' void project security scans'); + return lines; +} + +function failureWhy(scan: SecurityScanSummary): string | null { + switch (scan.status) { + case 'refused': + return 'refused by model'; + case 'timed_out': + return 'timed out'; + case 'failed': + return scan.failureCause === 'installation' + ? 'a platform problem' + : cleanLine(scan.statusReason ?? 'failed'); + default: + return null; + } +} + +function clip(text: string): string { + const line = cleanLine(text); + return line.length > MAX_TITLE ? `${line.slice(0, MAX_TITLE - 1)}…` : line; +} + +function rowHint(finding: SecurityUrgentFinding): string { + if (finding.possibleDuplicateOf) { + const { id, resolution } = finding.possibleDuplicateOf; + return ` (possible duplicate of ${cleanLine(id)}${resolution ? `, resolved ${cleanLine(resolution).split('_').join(' ')}` : ''})`; + } + return finding.notSeenInLatest ? ' (not seen in latest scan; may already be fixed)' : ''; +} + +/** Oldest first inside a severity; a missing or bad date keeps the server order. */ +function firstSeen(finding: SecurityUrgentFinding): number { + const time = finding.firstSeenAt ? Date.parse(finding.firstSeenAt) : Number.NaN; + return Number.isNaN(time) ? 0 : time; +} + +function urgentLines(slug: string, status: ProjectSecurityStatus, counts: boolean): Array { + const { urgent, publicRequest } = status; + if (urgent.count <= 0) { + return []; + } + const sorted = urgent.findings + .map((finding, index) => ({ finding, index })) + .sort( + (a, b) => + Number(b.finding.severity === 'critical') - Number(a.finding.severity === 'critical') || + firstSeen(a.finding) - firstSeen(b.finding) || + a.index - b.index, + ) + .map(({ finding }) => finding); + const shown = sorted.slice(0, MAX_ROWS); + const more = Math.max(0, urgent.count - shown.length); + const parts = [ + urgent.counts.critical ? `${urgent.counts.critical} critical` : '', + urgent.counts.high ? `${urgent.counts.high} high` : '', + ] + .filter(Boolean) + .join(', '); + const plural = urgent.count === 1 ? 'finding is' : 'findings are'; + const ids = shown.map((finding) => cleanLine(finding.id)); + if (counts) { + return [ + ` ⚠ ${urgent.count} urgent security ${plural} open (${parts})${ids.length ? `: ${ids.join(', ')}${more ? `, … and ${more} more` : ''}` : ''}`, + ' Details are not printed in CI logs. Run: void project security list --urgent', + ]; + } + const lines = [ + ` ⚠ ${urgent.count} urgent security ${plural} open in ${cleanLine(slug)} (${parts}):`, + ]; + for (const finding of shown) { + const place = finding.file + ? `${clip(finding.file)}${finding.line ? `:${finding.line}` : ''}` + : ''; + lines.push( + ` ${[ + cleanLine(finding.id).padEnd(5), + cleanLine(finding.severity ?? '-').padEnd(8), + finding.title === undefined ? '' : clip(finding.title), + place, + ] + .join(' ') + .trimEnd()}${rowHint(finding)}`, + ); + } + if (more > 0) { + lines.push(` … and ${more} more: void project security list --urgent`); + } + lines.push( + ' They come from earlier scans and still need a fix. Your deploy went out.', + ` Read: void project security show ${ids[0] ?? 'F-1'}`, + ' Page: void project security open', + // The server says whether this caller may resolve (`settings`); older platforms do not. + status.canResolve === true + ? ` Fixed? void project security resolve ${ids[0] ?? 'F-1'} --reason fixed --comment "…"` + : ' A project admin or owner can resolve them.', + ); + if (publicRequest) { + lines.push( + ` ${cleanLine(slug)} stays protected by Zero Trust until these are resolved (public request).`, + ); + } + return lines; +} + +/** Everything the notice prints for one security reply; empty when there is nothing to say. */ +export function formatDeploySecurityNotice( + input: { slug: string; deploymentId: string; env?: NodeJS.ProcessEnv }, + status: ProjectSecurityStatus, +): Array { + if (status.policy.mode === 'disabled' || input.slug.startsWith('preview-')) { + return []; + } + const counts = status.urgent.detail === 'counts' || inCi(input.env ?? process.env); + const groups = [ + scanLines(input.slug, input.deploymentId, status), + failedScanLines(input.deploymentId, status), + urgentLines(input.slug, status, counts), + ].filter((group) => group.length > 0); + return groups.flatMap((group, index) => (index === 0 ? group : ['', ...group])); +} + +function usable(value: unknown): value is ProjectSecurityStatus { + return ( + isObject(value) && + isObject(value.policy) && + isObject(value.urgent) && + isObject(value.model) && + Array.isArray(value.urgent.findings) + ); +} + +/** One best-effort read of the project security reply: `null` on any error, 404 or timeout. */ +export async function readSecurityStatusQuietly( + client: PlatformClient, + projectId: string, + options: { timeoutMs?: number; cliLog?: CliLogger } = {}, +): Promise { + const timeoutMs = options.timeoutMs ?? NOTICE_TIMEOUT_MS; + const abort = new AbortController(); + const timer = setTimeout(() => abort.abort(), timeoutMs); + let hardStop: ReturnType | undefined; + try { + const status = await Promise.race([ + client.getProjectSecurity(projectId, { signal: abort.signal }), + new Promise((_, reject) => { + hardStop = setTimeout(() => reject(new Error('timed out')), timeoutMs + 250); + }), + ]); + if (!usable(status)) { + options.cliLog?.debug('security_notice_skipped', { reason: 'unexpected_reply' }); + return null; + } + return status; + } catch (error) { + options.cliLog?.debug('security_notice_skipped', { + reason: error instanceof PlatformApiError ? `http_${error.status}` : 'error', + }); + return null; + } finally { + clearTimeout(timer); + clearTimeout(hardStop); + } +} + +/** The `Security` line of `void project status`; `null` when audits are off or not for this project. */ +export function formatProjectStatusSecurityLine( + slug: string, + status: ProjectSecurityStatus, +): string | null { + if (status.policy.mode === 'disabled' || slug.startsWith('preview-')) { + return null; + } + const { urgent, counts } = status; + if (urgent.count <= 0) { + return 'Security no urgent findings open'; + } + return `Security ${urgent.count} urgent open · ${counts.leads} ${counts.leads === 1 ? 'lead' : 'leads'} → void project security list --urgent`; +} + +/** + * After a managed deploy is live, says what the security scan is doing and lists open urgent + * findings (spec §6.5, §11.1). One read with a 5 s limit. Any error, a 404 from a platform without + * security audits, or a timeout prints nothing, and the exit code is never touched. + */ +export async function printDeploySecurityNotice(input: DeploySecurityNoticeInput): Promise { + // A deploy whose routing was not published is still committed live, so it still gets the notice. + if (input.slug.startsWith('preview-')) { + return; + } + try { + const status = await readSecurityStatusQuietly(input.client, input.projectId, { + timeoutMs: input.timeoutMs, + cliLog: input.cliLog, + }); + if (!status) { + return; + } + const lines = formatDeploySecurityNotice( + { slug: input.slug, deploymentId: input.deploymentId, env: input.env }, + status, + ); + input.cliLog?.info('security_notice', { + printed: lines.length > 0, + urgent: status.urgent.count, + scan: status.lastScan?.deploymentId === input.deploymentId ? status.lastScan.status : null, + }); + if (lines.length === 0) { + return; + } + const write = input.write ?? ((line: string) => console.log(line)); + write(''); + for (const line of lines) { + write(line); + } + } catch (error) { + // Formatting must never fail a deploy that is already live. + input.cliLog?.debug('security_notice_skipped', { + reason: error instanceof Error ? error.name : 'error', + }); + } +} diff --git a/packages/void/src/cli/deploy-security-packages.ts b/packages/void/src/cli/deploy-security-packages.ts new file mode 100644 index 000000000..8544cda93 --- /dev/null +++ b/packages/void/src/cli/deploy-security-packages.ts @@ -0,0 +1,98 @@ +/** + * The package claims a deploy sends for security scans (`securityPackages`, design doc + * 0095 M10): which packages named by the Worker bundle's source maps come from the + * registry, read from the project's lockfile. The platform drops registry code from the + * scan input by package identity; with no claims it keeps that code, ranked last. + * + * worker *.map ─► `sources` ─► package names (after the last `node_modules/`) + * nearest lockfile (project folder, then up to the repository root) + * ─► registry | local per name ─► { registry, local } + * + * Best effort: any problem sends no claims and never fails the deploy. + */ +import { existsSync, readFileSync, statSync } from 'node:fs'; +import { + packageNameOfPath, + parseSecurityLockfile, + SECURITY_LOCKFILE_NAMES, + SECURITY_PACKAGE_CLAIMS_MAX, + securityPackageClaims, + type SecurityPackageClaims, +} from '@void/platform/security-lockfile'; +import { basename, dirname, join } from 'pathslash'; + +/** A lockfile bigger than this is not read. */ +const MAX_LOCKFILE_BYTES = 32 * 1024 * 1024; + +/** The lockfile nearest `root`, walking up and stopping at the repository root. */ +export function findProjectLockfile(root: string): string | null { + let dir = root; + for (;;) { + for (const name of SECURITY_LOCKFILE_NAMES) { + const path = join(dir, name); + if (existsSync(path)) { + return path; + } + } + const parent = dirname(dir); + if (parent === dir || existsSync(join(dir, '.git'))) { + return null; + } + dir = parent; + } +} + +/** The packages the bundle's source maps name. */ +export function bundlePackageNames(workerFiles: ReadonlyMap): Set { + const names = new Set(); + for (const [name, bytes] of workerFiles) { + if (!name.endsWith('.map')) { + continue; + } + let sources: unknown; + try { + sources = (JSON.parse(bytes.toString('utf8')) as { sources?: unknown }).sources; + } catch { + continue; + } + if (!Array.isArray(sources)) { + continue; + } + for (const source of sources) { + if (typeof source !== 'string') { + continue; + } + const packageName = packageNameOfPath(source.split('\\').join('/')); + if (packageName !== null) { + names.add(packageName); + } + } + } + return names; +} + +/** The claims for this deploy, or `null` when there is nothing to claim or no lockfile. */ +export function readSecurityPackageClaims( + root: string, + workerFiles: ReadonlyMap, +): SecurityPackageClaims | null { + try { + const names = bundlePackageNames(workerFiles); + if (names.size === 0) { + return null; + } + const lockfile = findProjectLockfile(root); + if (lockfile === null || statSync(lockfile).size > MAX_LOCKFILE_BYTES) { + return null; + } + const index = parseSecurityLockfile(basename(lockfile), readFileSync(lockfile, 'utf8')); + if (index === null) { + return null; + } + const claims = securityPackageClaims(index, names); + const total = claims.registry.length + claims.local.length; + return total === 0 || total > SECURITY_PACKAGE_CLAIMS_MAX ? null : claims; + } catch { + return null; + } +} diff --git a/packages/void/src/cli/help.ts b/packages/void/src/cli/help.ts index 27a9f8449..3f402d4e3 100644 --- a/packages/void/src/cli/help.ts +++ b/packages/void/src/cli/help.ts @@ -54,15 +54,19 @@ function operatorHelpTree(): HelpTree { }, ...(entry.method ? [ - { - command: '--plan', - description: 'Validate and preview without changing anything', - }, - { - command: '--yes', - description: - 'Apply after preview without prompting; required in unattended scripts', - }, + ...(entry.noConfirm + ? [] + : [ + { + command: '--plan', + description: 'Validate and preview without changing anything', + }, + { + command: '--yes', + description: + 'Apply after preview without prompting; required in unattended scripts', + }, + ]), { command: '--timeout ', description: @@ -70,9 +74,8 @@ function operatorHelpTree(): HelpTree { }, ] : []), - ...(['list', 'events', 'logs', 'attempts', 'shared-recipients'].includes( - entry.action, - ) + ...(entry.paged || + ['list', 'events', 'logs', 'attempts', 'shared-recipients'].includes(entry.action) ? [ { command: '--limit ', @@ -337,7 +340,8 @@ const HELP_TREE: HelpTree = { }, { command: 'set ', - description: 'Edit a plan name, limits, build size, or AI Gateway logging default', + description: + 'Edit a plan name, limits, build size, AI Gateway logging default, or security scan cap', }, { command: 'reset ', @@ -368,13 +372,19 @@ const HELP_TREE: HelpTree = { }, { command: '--file ', - description: 'Read plan settings, partial limits, and aiLogging from JSON', + description: + 'Read plan settings, partial limits, aiLogging, and securityCap from JSON', }, { command: '--name ', description: 'Set the display name when adding or editing', }, { command: '--copy ', description: 'Copy this plan when adding a new one' }, + { + command: '--security-cap ', + description: + 'Monthly security scan cap for each project on the plan (inherit = policy default)', + }, { command: '--replacement ', description: 'Move accounts and any default before removing a plan', @@ -549,6 +559,11 @@ const HELP_TREE: HelpTree = { command: '--custom-domains', description: 'Let projects add their own domains (requires --dedicated-zone)', }, + { + command: '--security-audits', + description: + 'Allow security audits. Needs Cloudflare Containers and Workers AI; it turns nothing on until an administrator sets a scan mode', + }, { command: '--control-plane-domain ', description: 'Optional API hostname' }, { command: '--no-control-plane-domain', @@ -638,6 +653,7 @@ const HELP_TREE: HelpTree = { command: 'zero-trust ', description: 'Inspect or override Cloudflare Zero Trust protection', }, + { command: 'security ', description: 'Review security audit findings and settings' }, { command: 'logs', description: 'Show runtime logs from the deployed project' }, { command: 'requests', description: 'Show request-level traffic (status, method, timing)' }, { command: 'rollback [deployId]', description: 'Roll back to a previous deployment' }, @@ -735,29 +751,160 @@ const HELP_TREE: HelpTree = { }, 'zero-trust': { summary: 'Inspect and manage Zero Trust protection for a Void platform project.', - usage: ['void project zero-trust [options]'], + usage: ['void project zero-trust [options]'], commands: [ { command: 'status', description: 'Show desired and effective protection state' }, { command: 'protect', description: 'Protect the project' }, - { command: 'public', description: 'Make the project public' }, + { + command: 'public', + description: 'Make the project public (may wait for a security scan)', + }, + { + command: 'bypass --reason ""', + description: 'Skip the security scan for a waiting request (admin or owner)', + }, { command: 'reconcile', description: 'Repair Cloudflare Access configuration drift' }, ], - options: [{ command: '--project ', description: 'Project name override' }], - children: Object.fromEntries( - ['status', 'protect', 'public', 'reconcile'].map((action) => [ - action, - withProjectOption( - action === 'status' - ? 'Show desired and effective Zero Trust protection.' - : action === 'protect' - ? 'Protect the project with the platform Access policy.' - : action === 'public' - ? 'Make the project public with a managed Access bypass.' - : 'Repair Cloudflare Access configuration drift for the project.', - `void project zero-trust ${action} [options]`, - ), - ]), - ), + options: [ + { command: '--project ', description: 'Project name override' }, + { command: '--json', description: 'Print machine-readable output' }, + { command: '--reason ', description: 'bypass: why the scan is skipped (required)' }, + { command: '--yes', description: 'bypass: skip the confirmation prompt' }, + ], + children: { + status: zeroTrustHelp( + 'Show desired and effective Zero Trust protection and any open public request.', + 'void project zero-trust status [options]', + ), + protect: zeroTrustHelp( + 'Protect the project with the platform Access policy.', + 'void project zero-trust protect [options]', + ), + public: zeroTrustHelp( + 'Make the project public with a managed Access bypass. When the platform scans projects before they go public, the project stays protected until the scan passes.', + 'void project zero-trust public [options]', + ), + bypass: { + summary: + 'Skip the security scan for the open public request and make the project public. Not allowed while urgent findings are open. Platform admins are emailed with your reason, and the bypass is recorded.', + usage: ['void project zero-trust bypass --reason "" [--yes] [options]'], + options: [ + { command: '--reason ', description: 'Why the scan is skipped (required)' }, + { command: '--yes', description: 'Skip the confirmation prompt (needed in CI)' }, + { command: '--project ', description: 'Project name override' }, + { command: '--json', description: 'Print machine-readable output' }, + ], + }, + reconcile: zeroTrustHelp( + 'Repair Cloudflare Access configuration drift for the project.', + 'void project zero-trust reconcile [options]', + ), + }, + }, + security: { + summary: + 'Review security audit findings, scans, model and budget for a Void platform project.', + usage: ['void project security [options]'], + commands: [ + { + command: 'status', + description: 'Urgent findings, policy, model, budget and last scan', + }, + { + command: 'list', + description: 'List findings (--urgent, --state, --severity, --leads, --format sarif)', + }, + { command: 'show ', description: 'Show one finding with its history' }, + { + command: 'comment ""', + description: 'Add a comment (collaborator or higher)', + }, + { + command: 'resolve ...', + description: 'Resolve findings with --reason and --comment', + }, + { command: 'reopen ', description: 'Reopen a resolved finding with --comment' }, + { + command: 'severity ', + description: + 'Set the severity of an open finding with --comment (scan: use the scan value)', + }, + { command: 'scans', description: 'Show scan history (--limit, up to 100)' }, + { + command: 'scan', + description: + 'Run a full scan of the live deployment (asks first; it costs money; --client-assets)', + }, + { + command: 'check []', + description: + 'Scan the git-tracked code in this folder before you deploy (asks first; uploads it), or show an earlier check', + }, + { command: 'model [ | --default]', description: 'Show or set the scan model' }, + { + command: 'budget [--usd N | --off]', + description: 'Show or set this project monthly scan budget', + }, + { + command: 'open', + description: 'Open the read-only security page (link works for 15 minutes)', + }, + ], + options: [ + { command: '--project ', description: 'Project name override' }, + { command: '--json', description: 'Print machine-readable output' }, + { command: '--urgent', description: 'list: only urgent findings' }, + { + command: '--state ', + description: 'list: open, resolved or all (default: open)', + }, + { + command: '--severity ', + description: 'list: critical, high, medium, low or informational', + }, + { command: '--leads', description: 'list: include leads that need a human look' }, + { + command: '--format sarif', + description: 'list: print a SARIF 2.1.0 file for code scanning tools', + }, + { + command: '--reason ', + description: 'resolve: fixed, false-positive or accepted-risk', + }, + { + command: '--comment ', + description: 'resolve, reopen, severity: why (up to 4,000 characters)', + }, + { command: '--limit ', description: 'scans: how many scans, 1 to 100' }, + { command: '--default', description: 'model: use the platform default model' }, + { + command: '--accept-provider-notice', + description: 'model: accept the third-party provider notice', + }, + { command: '--usd ', description: 'budget: monthly cap in dollars' }, + { command: '--off', description: 'budget: clear this project own cap' }, + { command: '--yes', description: 'scan, check: start without the prompt' }, + { command: '--no-wait', description: 'check: queue it and return without waiting' }, + { + command: '--client-assets', + description: 'scan: also review client bundle sources from their source maps', + }, + ], + examples: [ + { + command: 'void project security list --urgent', + description: 'Show findings to fix first', + }, + { + command: + 'void project security resolve F-12 --reason fixed --comment "Bound params in 4e1b9a3"', + description: 'Resolve a finding', + }, + { + command: 'void project security check', + description: 'Check the code in this folder before you deploy it', + }, + ], }, logs: { summary: 'Show runtime logs from the deployed project.', @@ -1490,6 +1637,17 @@ function basicSubcommand(summary: string, usage: string, example?: string): Help }; } +function zeroTrustHelp(summary: string, usage: string): HelpPage { + return { + summary, + usage: [usage], + options: [ + { command: '--project ', description: 'Project name override' }, + { command: '--json', description: 'Print machine-readable output' }, + ], + }; +} + function withProjectOption(summary: string, usage: string): HelpPage { return { summary, @@ -1505,7 +1663,7 @@ function lifecycleHelp( return { summary, usage: [ - `void platform ${command} [id] [--plan]${command === 'disable' ? '' : ' [--runtime ]'}${command === 'upgrade' || command === 'repair' ? ' [--dashboard-url ] [--custom-domains]' : ''}${command === 'upgrade' ? ' [--runtime-logs ] [--storage-location ]' : ''}${command === 'repair' ? ' [--auth-config ]' : ''} [--yes]`, + `void platform ${command} [id] [--plan]${command === 'disable' ? '' : ' [--runtime ]'}${command === 'upgrade' || command === 'repair' ? ' [--dashboard-url ] [--custom-domains] [--security-audits]' : ''}${command === 'upgrade' ? ' [--runtime-logs ] [--storage-location ]' : ''}${command === 'repair' ? ' [--auth-config ]' : ''} [--yes]`, ], options: [ { command: '--plan', description: 'Print the exact plan without making changes' }, @@ -1528,6 +1686,11 @@ function lifecycleHelp( command: '--custom-domains', description: 'Turn on project custom domains; omission keeps the saved setting', }, + { + command: '--security-audits', + description: + 'Allow security audits (needs Containers and Workers AI); omission keeps the saved setting', + }, ] : []), ...(command === 'upgrade' diff --git a/packages/void/src/cli/list.ts b/packages/void/src/cli/list.ts index b2d746a86..dcabb3f4f 100644 --- a/packages/void/src/cli/list.ts +++ b/packages/void/src/cli/list.ts @@ -1,6 +1,10 @@ import { outro, log } from '@voidzero-dev/vite-plus-prompts'; import { getToken } from './auth.ts'; import { PlatformClient, type DeploymentResponse } from './client.ts'; +import { + formatProjectStatusSecurityLine, + readSecurityStatusQuietly, +} from './deploy-security-notice.ts'; import { dim, formatCount, @@ -107,6 +111,14 @@ async function showDeployments( return; } + const securityStatus = await readSecurityStatusQuietly(client, projectId); + const securityLine = securityStatus + ? formatProjectStatusSecurityLine(slug, securityStatus) + : null; + if (securityLine) { + console.log(`${tablePrefix()}${securityLine}`); + } + const latest = deployments[0]; if (latest.status === 'failed' && latest.error_message) { log.error(`project: Latest deploy failed: '${latest.error_message}'.`); diff --git a/packages/void/src/cli/operator-args.ts b/packages/void/src/cli/operator-args.ts index 70f715132..5dcac0037 100644 --- a/packages/void/src/cli/operator-args.ts +++ b/packages/void/src/cli/operator-args.ts @@ -1,5 +1,6 @@ import { parsePlatformLoginId } from '@void/platform'; import { OPERATOR_MAX_TIMEOUT_MS } from './operator-client.ts'; +import { applySecurityArgs, securityOperatorCommands } from './operator-security-args.ts'; /** Public operator commands. This table also drives nested CLI help. */ export type OperatorCommand = { @@ -12,6 +13,10 @@ export type OperatorCommand = { values?: Record; booleans?: Record; method?: 'POST'; + /** Lists take `--limit` and `--page`; without this only the generic list names do. */ + paged?: boolean; + /** A POST that is an action, not a change: no preview, no `--plan` or `--yes`. */ + noConfirm?: boolean; path: string; }; @@ -213,6 +218,7 @@ export const operatorCommands: Array = [ positional: ['id'], method: 'POST', }, + ...securityOperatorCommands, { group: 'deployment', action: 'list', @@ -610,6 +616,41 @@ export type OperatorArgs = { body: Record; }; +/** + * A flag name can be a switch in one command and take a value in another (`security + * model --default` against `security models --default `). Those names are switches + * only for the command that declares them as switches. + */ +function booleanFlagsFor(args: Array): Array { + const valueNames = new Set( + operatorCommands.flatMap((command) => Object.keys(command.values ?? {})), + ); + const declared = operatorCommands.flatMap((command) => Object.keys(command.booleans ?? {})); + const ambiguous = new Set(declared.filter((name) => valueNames.has(name))); + const names = declared.filter((name) => !ambiguous.has(name)); + if (ambiguous.size === 0) { + return names; + } + // Find the command from its first two words, skipping flags and their values. + const words: Array = []; + for (let index = 0; index < args.length && words.length < 2; index++) { + const arg = args[index]!; + if (!arg.startsWith('--')) { + words.push(arg); + } else if ( + !names.includes(arg.slice(2)) && + !ambiguous.has(arg.slice(2)) && + !['json', 'plan', 'yes', 'force'].includes(arg.slice(2)) + ) { + index++; + } + } + const selected = operatorCommands.find( + (command) => command.group === words[0] && command.action === words[1], + ); + return [...names, ...Object.keys(selected?.booleans ?? {}).filter((name) => ambiguous.has(name))]; +} + export function parseOperatorArgs(args: Array): OperatorArgs { const positional: Array = []; const values: Record = {}; @@ -620,7 +661,7 @@ export function parseOperatorArgs(args: Array): OperatorArgs { 'yes', // No command declares `--force`; parsing it as a boolean reports it as an unknown flag. 'force', - ...operatorCommands.flatMap((command) => Object.keys(command.booleans ?? {})), + ...booleanFlagsFor(args), ]); for (let index = 0; index < args.length; index++) { const arg = args[index]!; @@ -697,6 +738,7 @@ export function parseOperatorArgs(args: Array): OperatorArgs { ); } const paged = + command.paged === true || action === 'list' || action === 'events' || action === 'logs' || @@ -717,7 +759,7 @@ export function parseOperatorArgs(args: Array): OperatorArgs { if ( ![ 'json', - ...(command.method ? ['yes', 'plan'] : []), + ...(command.method && !command.noConfirm ? ['yes', 'plan'] : []), ...Object.keys(command.booleans ?? {}), ].includes(name) ) { @@ -805,7 +847,9 @@ export function parseOperatorArgs(args: Array): OperatorArgs { parsed.body[name] = true; } } - if (group === 'zero-trust' && action === 'configure') { + if (group === 'security') { + applySecurityArgs(command, parameters, values, flags, parsed); + } else if (group === 'zero-trust' && action === 'configure') { if (!parsed.tokenStdin) { throw new Error('platform: zero-trust configure requires --token-stdin.'); } diff --git a/packages/void/src/cli/operator-cmd.ts b/packages/void/src/cli/operator-cmd.ts index 9876af11a..f878e742f 100644 --- a/packages/void/src/cli/operator-cmd.ts +++ b/packages/void/src/cli/operator-cmd.ts @@ -21,6 +21,12 @@ import { dim, printSuccess, sanitizeTerminalText } from './output.ts'; import { MINIMAL_RUNTIME_LOGS_NOTE } from './platform-runtime-logs.ts'; const MAX_RUNTIME_FOLLOW_ROWS = 10_000; +const OPEN_PUBLIC_REQUEST_STATES = [ + 'waiting_scan', + 'held_findings', + 'held_no_result', + 'needs_deploy', +]; export const BUILD_LOG_DRAIN_TIMEOUT_MS: number = 2 * 60_000; function printable(value: unknown): string { @@ -144,17 +150,21 @@ export function humanLines(value: unknown, indent = ''): Array { }); } -function output(value: unknown, json: boolean): void { +export function output(value: unknown, json: boolean): void { console.log(json ? JSON.stringify(value) : humanLines(value).join('\n')); } -function outputMutation(result: Record, args: OperatorArgs): void { +export function outputMutation(result: Record, args: OperatorArgs): void { output(result, args.json); // Some successful HTTP responses checkpoint work rather than complete it. const configuration = result.configuration as { status?: string } | undefined; const project = result.project as { state?: string; last_error?: string | null } | undefined; + // A public request that is still open has not made the project public. + const publicRequest = result.publicRequest as { state?: string } | null | undefined; if ( args.json || + (publicRequest?.state !== undefined && + OPEN_PUBLIC_REQUEST_STATES.includes(publicRequest.state)) || result.ok === false || result.partial === true || result.complete === false || @@ -671,6 +681,27 @@ export async function runOperatorCommand(args: OperatorArgs): Promise { return runAuth(origin, args); } const client = new OperatorClient(origin, readOperatorToken(origin)); + if (args.group === 'security') { + // The probe is a check, not a change, so it needs no confirmation. + if ( + args.method === 'POST' && + args.action !== 'probe' && + !args.plan && + !args.yes && + (!process.stdin.isTTY || !process.stderr.isTTY) + ) { + throw new OperatorClientError( + 'Mutations in non-interactive mode require --yes or --plan.', + 'confirmation_required', + ); + } + const { runSecurityOperatorCommand } = await import('./operator-security.ts'); + return runSecurityOperatorCommand(client, origin, args, { + output, + outputMutation, + confirm: confirmOperatorMutation, + }); + } if (args.method === 'POST') { // Fail before contacting the server when unattended mutation authorization is missing. if (!args.plan && !args.yes && (!process.stdin.isTTY || !process.stderr.isTTY)) { diff --git a/packages/void/src/cli/operator-security-args.ts b/packages/void/src/cli/operator-security-args.ts new file mode 100644 index 000000000..4776773eb --- /dev/null +++ b/packages/void/src/cli/operator-security-args.ts @@ -0,0 +1,664 @@ +import type { OperatorCommand } from './operator-args.ts'; + +/** + * `void platform security …` (spec §13.4). The table feeds the generic operator parser + * and the nested help. `applySecurityArgs` turns the raw flags into request bodies. + * Projects are addressed by id, like every other operator command; the lists also take + * a slug in `--project`. + */ +export const securityOperatorCommands: Array = [ + { + group: 'security', + action: 'status', + description: + 'Inspect capability, last probe, policy, queue depth, running scans and month totals', + path: '/security/status', + }, + { + group: 'security', + action: 'probe', + description: 'Run the entitlement probe (checks Containers, Workers AI and model hosts)', + path: '/security/probe', + method: 'POST', + noConfirm: true, + }, + { + group: 'security', + action: 'policy', + description: 'Set the scan mode (disabled, public or all), or one project’s own scan rule', + path: '/security/policy', + positional: ['mode'], + usage: [ + 'void platform security policy [options]', + 'void platform security policy --project [options]', + ], + values: { + project: + 'Project id whose own rule to set: inherit follows the mode, always scans it, never skips it', + }, + method: 'POST', + }, + { + group: 'security', + action: 'models', + description: + 'Set the default model, block or unblock models, or save your own OpenAI or Anthropic key', + path: '/security/policy', + usage: [ + 'void platform security models [--default ] [--block ] [--unblock ] [--accept-provider-notice] [options]', + 'void platform security models --provider (--key-stdin | --remove-key) [options]', + ], + values: { + default: 'Default model id', + block: 'Comma-separated model ids to block', + unblock: 'Comma-separated model ids to unblock', + provider: 'openai or anthropic: the provider whose key --key-stdin or --remove-key changes', + }, + booleans: { + 'accept-provider-notice': + 'Accept the current provider notice (needed for a third-party model)', + 'key-stdin': 'Read your own provider API key from stdin; scans with that provider bill to it', + 'remove-key': 'Remove your saved provider key; scans go back to Unified Billing credits', + }, + method: 'POST', + }, + { + group: 'security', + action: 'limits', + description: 'Set scan limits: concurrent scans and the time one scan may run', + path: '/security/policy', + values: { + concurrency: 'Scans that run at once (1 to 10)', + 'scan-timeout': 'Minutes one scan may run (5 to 60)', + }, + method: 'POST', + }, + { + group: 'security', + action: 'budget', + description: + 'Show the monthly caps and this month’s spend, or set the platform cap, the default project cap or one project’s limit', + path: '/security/budget', + usage: [ + 'void platform security budget [--platform-usd | --platform-off] [--project-default-usd ] [--project-caps ] [--project (--usd | --clear)] [options]', + ], + values: { + 'platform-usd': 'Platform cap in USD per month (turns the cap on)', + 'project-default-usd': 'Default project cap in USD per month (turns project caps on)', + 'project-caps': 'on applies the saved default to every project; off removes it', + project: 'Project id whose limit to change (use with --usd or --clear)', + usd: 'That project’s limit in USD per month, any amount', + }, + booleans: { + 'platform-off': 'Turn the platform cap off', + clear: 'Remove the project’s limit (the default applies again)', + }, + method: 'POST', + }, + { + group: 'security', + action: 'findings', + description: 'List findings across projects, oldest first', + path: '/security/findings', + values: { + project: 'Project id or slug', + state: 'open, resolved or all', + severity: 'critical, high, medium, low or informational', + format: 'sarif prints every matching finding as a SARIF 2.1.0 log', + }, + booleans: { urgent: 'Only open critical or high findings that are confirmed' }, + paged: true, + }, + { + group: 'security', + action: 'show', + description: 'Show findings of a project, by comma-separated finding ids', + path: '/projects/:id/security/findings/:fid', + positional: ['id', 'fid'], + usage: ['void platform security show [options]'], + }, + { + group: 'security', + action: 'resolve', + description: 'Resolve findings as an installation admin', + path: '/projects/:id/security/findings/:fid/resolve', + positional: ['id', 'fid'], + usage: [ + 'void platform security resolve --reason --comment [options]', + ], + values: { + reason: 'fixed, false-positive or accepted-risk', + comment: 'Why (required)', + }, + method: 'POST', + }, + { + group: 'security', + action: 'reopen', + description: 'Reopen resolved findings as an installation admin', + path: '/projects/:id/security/findings/:fid/reopen', + positional: ['id', 'fid'], + usage: ['void platform security reopen --comment [options]'], + values: { comment: 'Why (required)' }, + method: 'POST', + }, + { + group: 'security', + action: 'comment', + description: 'Add a comment to findings as an installation admin', + path: '/projects/:id/security/findings/:fid/comments', + positional: ['id', 'fid', 'text'], + usage: ['void platform security comment [options]'], + method: 'POST', + }, + { + group: 'security', + action: 'model', + description: 'Set one project’s scan model, or go back to the platform default', + path: '/projects/:id/security/model', + positional: ['id', 'model'], + optionalPositional: true, + usage: ['void platform security model [options]'], + booleans: { + default: 'Use the platform default model', + 'accept-provider-notice': + 'Accept the current provider notice (needed for a third-party model)', + }, + method: 'POST', + }, + { + group: 'security', + action: 'scans', + description: 'List scans across projects, newest first, with month totals', + path: '/security/scans', + values: { + project: 'Project id or slug', + status: 'Scan status, such as failed, refused or running', + trigger: 'gate for public-request scans', + }, + paged: true, + }, + { + group: 'security', + action: 'rescan', + description: 'Run a full scan of the live deployment (asks first; it can cost real money)', + path: '/projects/:id/security/scans', + positional: ['id'], + booleans: { + 'client-assets': 'Also read the sources of the client bundles from their source maps', + }, + method: 'POST', + }, + { + group: 'security', + action: 'backfill', + description: + 'Scan every live deployment that was never scanned (asks first; it can cost real money)', + path: '/security/backfill', + method: 'POST', + }, + { + group: 'security', + action: 'sweeps', + description: 'Turn scheduled full sweeps of every live app on or off', + path: '/security/policy', + positional: ['state'], + usage: ['void platform security sweeps [--every-days ] [options]'], + values: { 'every-days': 'Days between two sweeps of one project (7 to 90, default 30)' }, + method: 'POST', + }, + { + group: 'security', + action: 'fallback', + description: + 'Re-scan once on the @cf default after a third-party scan is refused, fails or times out', + path: '/security/policy', + positional: ['state'], + usage: ['void platform security fallback [options]'], + method: 'POST', + }, + { + group: 'security', + action: 'digest', + description: 'Turn the weekly security summary email to installation admins on or off', + path: '/security/policy', + positional: ['state'], + usage: ['void platform security digest [options]'], + method: 'POST', + }, + { + group: 'security', + action: 'webhook', + description: + 'Send signed security events (ids and counts only) to an https URL, or turn it off', + path: '/security/webhook', + positional: ['url'], + usage: ['void platform security webhook [options]'], + method: 'POST', + }, + { + group: 'security', + action: 'cancel', + description: 'Cancel a waiting or running scan', + path: '/security/scans/:sid/cancel', + positional: ['sid'], + method: 'POST', + }, + { + group: 'security', + action: 'public-gate', + description: 'Turn “Scan before a project goes public” on or off', + path: '/security/policy', + positional: ['state'], + usage: ['void platform security public-gate [options]'], + method: 'POST', + }, + { + group: 'security', + action: 'public-requests', + description: 'List public requests across projects, longest waiting first', + path: '/security/public-requests', + values: { + project: 'Project id or slug', + state: 'open, closed, all or one request state', + }, + paged: true, + }, + { + group: 'security', + action: 'bypass', + description: 'Bypass the gate scan of a project’s public request', + path: '/projects/:id/security/public-request/bypass', + positional: ['id'], + values: { reason: 'Why the scan is skipped (required, up to 4,000 characters)' }, + method: 'POST', + }, + { + group: 'security', + action: 'bypasses', + description: 'List bypass records, newest first', + path: '/security/bypasses', + values: { project: 'Project id or slug' }, + paged: true, + }, +]; + +const MODES = ['disabled', 'public', 'all']; +/** One project's own scan rule (M34). */ +const OVERRIDES = ['inherit', 'always', 'never']; +const SEVERITIES = ['critical', 'high', 'medium', 'low', 'informational']; +const REASONS: Record = { + fixed: 'fixed', + 'false-positive': 'false_positive', + false_positive: 'false_positive', + 'accepted-risk': 'accepted_risk', + accepted_risk: 'accepted_risk', +}; +const MAX_FINDING_IDS = 20; + +function list(value: string, name: string): Array { + const items = [ + ...new Set( + value + .split(',') + .map((entry) => entry.trim()) + .filter(Boolean), + ), + ]; + if (items.length === 0) { + throw new Error(`platform: --${name} needs at least one id.`); + } + return items; +} + +function wholeNumber(value: string, name: string): number { + if (!/^[1-9]\d*$/.test(value) || !Number.isSafeInteger(Number(value))) { + throw new Error(`platform: --${name} must be a whole number.`); + } + return Number(value); +} + +function dollars(value: string, name: string): number { + if (!/^\d+(\.\d{1,2})?$/.test(value)) { + throw new Error(`platform: --${name} must be a dollar amount such as 50 or 12.50.`); + } + return Number(value); +} + +export type SecurityParsed = { + /** `budget` reads with no flags and writes with any cap flag, so the request is chosen here. */ + method?: 'GET' | 'POST'; + action?: string; + path: string; + query: Record; + body: Record; +}; + +/** + * Fills the request for one security command. The path keeps `:fid` when the command + * takes finding ids, and the ids ride the body as `findingIds` for the runner, which + * sends one request per id. Internal body keys (`findingIds`, `acceptProviderNotice`, + * `projectCapsOn`, `keyStdin`) never reach the server. + */ +export function applySecurityArgs( + command: OperatorCommand, + parameters: Array, + values: Record, + flags: Set, + parsed: SecurityParsed, +): void { + const action = command.action; + parsed.body = {}; + parsed.path = command.path; + if (action === 'budget') { + const writes = + ['platform-usd', 'project-default-usd', 'project-caps', 'project', 'usd'].some( + (name) => values[name] !== undefined, + ) || + flags.has('platform-off') || + flags.has('clear'); + if (!writes) { + parsed.method = 'GET'; + return; + } + parsed.method = 'POST'; + parsed.action = 'budget-set'; + } + const projectId = parameters[0]; + if (projectId !== undefined) { + if (projectId === '.' || projectId === '..') { + throw new Error('platform: An object ID cannot be a dot path segment.'); + } + if (command.path.includes(':id')) { + parsed.path = parsed.path.replace(':id', encodeURIComponent(projectId)); + } + } + if (action === 'cancel') { + parsed.path = parsed.path.replace(':sid', encodeURIComponent(parameters[0]!)); + return; + } + if (action === 'rescan' && flags.has('client-assets')) { + parsed.body = { clientAssets: true }; + return; + } + if (action === 'findings') { + if (flags.has('urgent')) { + parsed.query.urgent = 'true'; + } + if (values.format !== undefined) { + if (values.format !== 'sarif') { + throw new Error('platform: --format must be sarif.'); + } + if (flags.has('json')) { + throw new Error('platform: Use --format sarif or --json, not both.'); + } + if (parsed.query.page !== undefined || parsed.query.limit !== undefined) { + throw new Error( + 'platform: --format sarif exports every matching finding; drop --page and --limit.', + ); + } + // The export reads every page itself (`findings-sarif`); the server never sees it. + delete parsed.query.format; + parsed.action = 'findings-sarif'; + } + if (values.state !== undefined && !['open', 'resolved', 'all'].includes(values.state)) { + throw new Error('platform: --state must be open, resolved or all.'); + } + if (values.severity !== undefined && !SEVERITIES.includes(values.severity)) { + throw new Error(`platform: --severity must be one of: ${SEVERITIES.join(', ')}.`); + } + return; + } + if (action === 'scans' && values.trigger !== undefined && values.trigger !== 'gate') { + throw new Error('platform: --trigger must be gate.'); + } + if (action === 'show' || action === 'resolve' || action === 'reopen' || action === 'comment') { + const ids = list(parameters[1]!, 'finding ids'); + if (ids.length > MAX_FINDING_IDS) { + throw new Error(`platform: Name at most ${MAX_FINDING_IDS} findings at a time.`); + } + parsed.body.findingIds = ids; + if (action === 'show') { + return; + } + } + switch (action) { + case 'policy': { + const mode = parameters[0]!; + const project = values.project; + if (project !== undefined) { + if (!OVERRIDES.includes(mode)) { + throw new Error( + 'platform: Usage: void platform security policy --project .', + ); + } + if (project === '.' || project === '..') { + throw new Error('platform: An object ID cannot be a dot path segment.'); + } + parsed.action = 'project-policy'; + parsed.path = `/projects/${encodeURIComponent(project)}/security/policy`; + parsed.body = { override: mode }; + return; + } + if (OVERRIDES.includes(mode)) { + throw new Error( + `platform: ${mode} is a project rule; name the project: void platform security policy --project ${mode}.`, + ); + } + if (!MODES.includes(mode)) { + throw new Error('platform: Usage: void platform security policy .'); + } + parsed.body = { mode }; + return; + } + case 'sweeps': { + const state = parameters[0]!; + if (state !== 'on' && state !== 'off') { + throw new Error( + 'platform: Usage: void platform security sweeps [--every-days ].', + ); + } + parsed.body = { + sweeps: { + on: state === 'on', + ...(values['every-days'] !== undefined + ? { everyDays: wholeNumber(values['every-days'], 'every-days') } + : {}), + }, + }; + return; + } + case 'fallback': + case 'digest': { + const state = parameters[0]!; + if (state !== 'on' && state !== 'off') { + throw new Error(`platform: Usage: void platform security ${action} .`); + } + parsed.body = { [action === 'fallback' ? 'fallbackToCf' : 'digest']: state === 'on' }; + return; + } + case 'webhook': { + const url = parameters[0]!; + if (url !== 'off' && !url.startsWith('https://')) { + throw new Error('platform: Usage: void platform security webhook .'); + } + parsed.body = { url: url === 'off' ? null : url }; + return; + } + case 'public-gate': { + const state = parameters[0]!; + if (state !== 'on' && state !== 'off') { + throw new Error('platform: Usage: void platform security public-gate .'); + } + parsed.body = { publicGate: state === 'on' }; + return; + } + case 'models': { + const provider = values.provider; + const keyStdin = flags.has('key-stdin'); + const removeKey = flags.has('remove-key'); + if (provider !== undefined || keyStdin || removeKey) { + // A provider key has its own route and is changed apart from the policy. + if ( + values.default || + values.block || + values.unblock || + flags.has('accept-provider-notice') + ) { + throw new Error( + 'platform: Change a provider key on its own; set models in a separate command.', + ); + } + if (provider !== 'openai' && provider !== 'anthropic') { + throw new Error('platform: --provider must be openai or anthropic.'); + } + if (keyStdin === removeKey) { + throw new Error( + 'platform: Usage: void platform security models --provider (--key-stdin | --remove-key).', + ); + } + parsed.action = 'provider-key'; + parsed.path = '/security/provider-keys'; + // `keyStdin` is internal: the runner reads the key and sends it as `key`. + parsed.body = keyStdin ? { host: provider, keyStdin: true } : { host: provider, key: null }; + return; + } + if (!values.default && !values.block && !values.unblock) { + throw new Error( + 'platform: Usage: void platform security models [--default ] [--block ] [--unblock ] [--accept-provider-notice], or --provider (--key-stdin | --remove-key).', + ); + } + parsed.body = { + ...(values.default ? { defaultModel: values.default } : {}), + ...(values.block ? { block: list(values.block, 'block') } : {}), + ...(values.unblock ? { unblock: list(values.unblock, 'unblock') } : {}), + ...(flags.has('accept-provider-notice') ? { acceptProviderNotice: true } : {}), + }; + return; + } + case 'limits': { + const limits = { + ...(values.concurrency + ? { concurrency: wholeNumber(values.concurrency, 'concurrency') } + : {}), + ...(values['scan-timeout'] + ? { timeoutMinutes: wholeNumber(values['scan-timeout'], 'scan-timeout') } + : {}), + }; + if (Object.keys(limits).length === 0) { + throw new Error( + 'platform: Usage: void platform security limits [--concurrency ] [--scan-timeout ].', + ); + } + parsed.body = { limits }; + return; + } + case 'budget': { + const project = values.project; + const platformFlags = ['platform-usd', 'project-default-usd', 'project-caps'].filter( + (name) => values[name] !== undefined, + ); + if (flags.has('platform-off')) { + platformFlags.push('platform-off'); + } + if (project !== undefined) { + if (platformFlags.length > 0) { + throw new Error( + 'platform: --project changes one project; do not combine it with platform cap flags.', + ); + } + if ((values.usd === undefined) === !flags.has('clear')) { + throw new Error( + 'platform: Usage: void platform security budget --project (--usd | --clear).', + ); + } + if (project === '.' || project === '..') { + throw new Error('platform: An object ID cannot be a dot path segment.'); + } + parsed.path = `/projects/${encodeURIComponent(project)}/security/budget`; + parsed.body = { monthlyUsd: values.usd === undefined ? null : dollars(values.usd, 'usd') }; + return; + } + if (values.usd !== undefined || flags.has('clear')) { + throw new Error('platform: --usd and --clear need --project .'); + } + if (values['platform-usd'] !== undefined && flags.has('platform-off')) { + throw new Error('platform: Choose --platform-usd or --platform-off, not both.'); + } + const caps = values['project-caps']; + if (caps !== undefined && caps !== 'on' && caps !== 'off') { + throw new Error('platform: --project-caps must be on or off.'); + } + if (caps === 'off' && values['project-default-usd'] !== undefined) { + throw new Error( + 'platform: --project-caps off cannot be combined with --project-default-usd.', + ); + } + const body: Record = {}; + if (values['platform-usd'] !== undefined) { + body.platformMonthlyUsd = dollars(values['platform-usd'], 'platform-usd'); + } else if (flags.has('platform-off')) { + body.platformMonthlyUsd = null; + } + if (values['project-default-usd'] !== undefined) { + body.projectDefaultMonthlyUsd = dollars( + values['project-default-usd'], + 'project-default-usd', + ); + } else if (caps === 'off') { + body.projectDefaultMonthlyUsd = null; + } else if (caps === 'on') { + // The saved default amount; the runner reads it. + body.projectCapsOn = true; + } + if (Object.keys(body).length === 0) { + throw new Error( + 'platform: Usage: void platform security budget [--platform-usd | --platform-off] [--project-default-usd | --project-caps on|off] | --project (--usd | --clear).', + ); + } + parsed.body = body; + return; + } + case 'resolve': { + const reason = values.reason === undefined ? undefined : REASONS[values.reason]; + if (!reason) { + throw new Error('platform: --reason is required: fixed, false-positive or accepted-risk.'); + } + parsed.body.reason = reason; + parsed.body.comment = requireText(values.comment, 'comment'); + return; + } + case 'reopen': + parsed.body.comment = requireText(values.comment, 'comment'); + return; + case 'comment': + parsed.body.text = requireText(parameters[2], 'text'); + return; + case 'model': { + const useDefault = flags.has('default'); + const model = parameters[1]; + if (useDefault === (model !== undefined)) { + throw new Error( + 'platform: Usage: void platform security model .', + ); + } + parsed.body = { + model: useDefault ? null : model, + ...(flags.has('accept-provider-notice') ? { acceptProviderNotice: true } : {}), + }; + return; + } + case 'bypass': + parsed.body.reason = requireText(values.reason, 'reason'); + return; + default: + return; + } +} + +function requireText(value: string | undefined, name: string): string { + if (value === undefined || value.trim() === '') { + throw new Error(`platform: ${name} is required.`); + } + return value; +} diff --git a/packages/void/src/cli/operator-security.ts b/packages/void/src/cli/operator-security.ts new file mode 100644 index 000000000..bf9044cbf --- /dev/null +++ b/packages/void/src/cli/operator-security.ts @@ -0,0 +1,557 @@ +import type { OperatorArgs } from './operator-args.ts'; +import { OperatorClientError, type OperatorClient } from './operator-client.ts'; +import { dim, printSuccess } from './output.ts'; +import { type SarifFinding, sarifToolVersion, securityFindingsSarif } from './security-sarif.ts'; + +type Result = Record; + +/** What the runner borrows from `operator-cmd.ts` (passed in, so the two files do not import each other). */ +export type SecurityIo = { + output: (value: unknown, json: boolean) => void; + outputMutation: (result: Result, args: OperatorArgs) => void; + confirm: ( + origin: string, + preview: Result, + args: Pick, + ) => Promise; +}; + +const NOT_INSTALLED = + 'Security audits are not installed. Run: void platform upgrade --security-audits'; + +/** The platform answers 501 `platform capability unavailable` when the capability is off. */ +async function guarded(run: () => Promise): Promise { + try { + return await run(); + } catch (error) { + if ( + error instanceof OperatorClientError && + error.status === 501 && + error.code === 'platform capability unavailable' + ) { + throw new OperatorClientError(NOT_INSTALLED, error.code, error.status, error.details); + } + throw error; + } +} + +/** The path of one finding: the command path keeps `:fid` until here. */ +function findingPath(path: string, id: string): string { + return path.replace(':fid', encodeURIComponent(id)); +} + +function findingIds(args: OperatorArgs): Array { + const ids = args.body.findingIds; + return Array.isArray(ids) ? ids.filter((id): id is string => typeof id === 'string') : []; +} + +function validPreview(preview: Result): void { + if ( + preview.dryRun !== true || + typeof preview.action !== 'string' || + !Object.hasOwn(preview, 'target') + ) { + throw new OperatorClientError( + 'The server did not return a valid mutation preview. No change was requested.', + 'invalid_preview', + ); + } +} + +async function previewOf( + client: OperatorClient, + args: OperatorArgs, + path: string, + body: Result, +): Promise { + const preview = await client.request(path, { + method: 'POST', + body: { ...body, dryRun: true }, + timeoutMs: args.timeoutMs, + }); + validPreview(preview); + return preview; +} + +/** The policy preview carries the whole policy; the change lines are what a person reads. */ +function shown(preview: Result): Result { + const { policy: _policy, ...rest } = preview; + return rest; +} + +function money(value: unknown): string { + return typeof value === 'number' ? `$${value.toFixed(2)}` : 'an unknown amount'; +} + +function number(value: unknown): number | undefined { + return typeof value === 'number' && Number.isSafeInteger(value) ? value : undefined; +} + +/** Reads. `show` takes comma-separated finding ids. */ +async function runRead(client: OperatorClient, args: OperatorArgs, io: SecurityIo): Promise { + if (args.action === 'show') { + const ids = findingIds(args); + const details: Array = []; + for (const id of ids) { + details.push(await client.request(findingPath(args.path, id))); + } + io.output(details.length === 1 ? details[0] : { findings: details }, args.json); + return; + } + if (args.action === 'findings-sarif') { + return exportFindingsSarif(client, args); + } + io.output(await client.request(args.path, { query: args.query }), args.json); +} + +/** The SARIF export reads this many pages of 100 findings, at most. */ +const SARIF_MAX_PAGES = 100; + +/** `findings --format sarif`: every matching finding, page by page, as one SARIF log. */ +async function exportFindingsSarif(client: OperatorClient, args: OperatorArgs): Promise { + const findings: Array = []; + let totalPages = 1; + for (let page = 1; page <= Math.min(totalPages, SARIF_MAX_PAGES); page++) { + const result = await client.request(args.path, { + query: { ...args.query, page: String(page), limit: '100' }, + }); + const rows = Array.isArray(result.findings) ? (result.findings as Array) : []; + findings.push(...rows); + totalPages = number(result.totalPages) ?? 1; + if (rows.length === 0) { + break; + } + } + console.log( + JSON.stringify(securityFindingsSarif(findings, { version: sarifToolVersion() }), null, 2), + ); + if (totalPages > SARIF_MAX_PAGES) { + process.stderr.write( + `Only the first ${SARIF_MAX_PAGES * 100} findings are in the file. Narrow it with --project, --severity or --urgent.\n`, + ); + } +} + +/** One policy-shaped change: preview, confirm, then apply at the previewed revision. */ +async function changeWithRevision( + client: OperatorClient, + origin: string, + args: OperatorArgs, + io: SecurityIo, + body: Result, +): Promise { + const preview = await previewOf(client, args, args.path, body); + if (!(await io.confirm(origin, shown(preview), args))) { + return; + } + const revision = number(preview.expectedRevision); + if (revision === undefined) { + throw new OperatorClientError( + 'The server did not return a policy revision. No change was requested.', + 'invalid_preview', + ); + } + const result = await client.request(args.path, { + method: 'POST', + body: { ...body, expectedRevision: revision }, + timeoutMs: args.timeoutMs, + }); + io.outputMutation(result, args); +} + +/** The notice version the platform currently asks operators to accept. */ +async function currentNoticeVersion(client: OperatorClient): Promise { + const policy = await client.request('/security/policy'); + const notice = policy.providerNotice as { version?: unknown } | undefined; + const version = number(notice?.version); + if (version === undefined) { + throw new OperatorClientError( + 'The platform did not report its provider notice version.', + 'invalid_response', + ); + } + return version; +} + +async function runFindings( + client: OperatorClient, + origin: string, + args: OperatorArgs, + io: SecurityIo, +): Promise { + const ids = findingIds(args); + const { findingIds: _ids, ...fields } = args.body; + const items: Array<{ id: string; path: string; body: Result; preview: Result }> = []; + // Preview every finding before the first write, so a typo in the last id changes nothing. + for (const id of ids) { + const path = findingPath(args.path, id); + let body: Result = { ...fields }; + if (args.action !== 'comment') { + // The path ends in `/resolve` or `/reopen`; the finding itself is one level up. + const show = await client.request(path.slice(0, path.lastIndexOf('/'))); + const finding = show.finding as { revision?: unknown } | undefined; + const revision = number(finding?.revision); + if (revision === undefined) { + throw new OperatorClientError( + `The platform did not report the revision of ${id}.`, + 'invalid_response', + ); + } + body = { ...body, expectedRevision: revision }; + } + items.push({ id, path, body, preview: await previewOf(client, args, path, body) }); + } + const combined: Result = + items.length === 1 + ? items[0]!.preview + : { + dryRun: true, + action: items[0]!.preview.action, + target: { findings: items.map((item) => item.id) }, + previews: items.map((item) => item.preview), + }; + if (!(await io.confirm(origin, combined, args))) { + return; + } + const results: Array = []; + let failed = 0; + for (const item of items) { + try { + results.push( + await client.request(item.path, { + method: 'POST', + body: item.body, + timeoutMs: args.timeoutMs, + }), + ); + } catch (error) { + failed++; + results.push({ + ok: false, + id: item.id, + error: error instanceof Error ? error.message : String(error), + }); + } + } + if (items.length === 1 && failed === 0) { + io.outputMutation(results[0]!, args); + return; + } + io.output({ results }, args.json); + if (failed > 0) { + throw new OperatorClientError( + `${failed} of ${items.length} findings were not changed. See the results above; the others were.`, + 'partial_failure', + ); + } + if (!args.json) { + printSuccess(`Platform security ${args.action} completed.`); + } +} + +async function runBudget( + client: OperatorClient, + origin: string, + args: OperatorArgs, + io: SecurityIo, +): Promise { + const body: Result = { ...args.body }; + if (args.path.startsWith('/projects/')) { + // One project's limit: a plain write, no revision. + const preview = await previewOf(client, args, args.path, body); + if (!(await io.confirm(origin, preview, args))) { + return; + } + const result = await client.request(args.path, { + method: 'POST', + body, + timeoutMs: args.timeoutMs, + }); + io.outputMutation(result, args); + const budget = result.budget as { capSource?: unknown; capUsd?: unknown } | undefined; + const set = body.monthlyUsd; + if ( + !args.json && + typeof set === 'number' && + budget?.capSource === 'own' && + typeof budget.capUsd === 'number' && + budget.capUsd < set + ) { + const project = decodeURIComponent(args.path.split('/')[2]!); + console.log( + `${project}'s own cap (${money(budget.capUsd)}) is lower and still applies. A project admin can raise it: void project security budget --usd ${set}`, + ); + } + return; + } + if (body.projectCapsOn === true) { + // `--project-caps on` with no amount applies the saved default to every project. + delete body.projectCapsOn; + const current = await client.request('/security/budget'); + const saved = (current.projectDefault as { monthlyUsd?: unknown } | undefined)?.monthlyUsd; + if (typeof saved !== 'number') { + throw new OperatorClientError( + 'The platform did not report the default project cap. Set one: --project-default-usd .', + 'invalid_response', + ); + } + body.projectDefaultMonthlyUsd = saved; + } + await changeWithRevision(client, origin, args, io, body); +} + +async function runRescan( + client: OperatorClient, + origin: string, + args: OperatorArgs, + io: SecurityIo, +): Promise { + const preview = await previewOf(client, args, args.path, args.body); + if (args.body.clientAssets === true && preview.clientAssets !== true) { + throw new OperatorClientError( + 'This platform cannot read client bundle sources yet. Upgrade it, or run the rescan without --client-assets.', + 'unsupported', + ); + } + if (!args.json && !args.plan) { + // The server's preview is the cost check (edge #43): say what it would run and what it can cost. + const target = preview.target as unknown; + const id = typeof preview.deploymentId === 'string' ? preview.deploymentId : String(target); + const model = typeof preview.model === 'string' ? preview.model : 'the scan model'; + const whole = + preview.clientAssets === true + ? 'This reviews the whole app, and the sources of its client bundles.' + : 'This reviews the whole app.'; + const first = + preview.alreadyScanned === true + ? `Live deployment ${id} was already scanned. Run a full scan with ${model}? ${whole}` + : `Run a full scan of live deployment ${id} with ${model}? ${whole}`; + process.stderr.write( + `${first}${typeof preview.worstCaseUsd === 'number' ? ` It can cost up to ${money(preview.worstCaseUsd)}.` : ''}\n${dim('Monthly caps apply; raise the cap first if a rescan is refused.')}\n`, + ); + } + if (!(await io.confirm(origin, preview, args))) { + return; + } + const result = await client.request(args.path, { + method: 'POST', + body: args.body, + timeoutMs: args.timeoutMs, + }); + io.outputMutation(result, args); +} + +async function runBackfill( + client: OperatorClient, + origin: string, + args: OperatorArgs, + io: SecurityIo, +): Promise { + const preview = await previewOf(client, args, args.path, args.body); + const count = number(preview.willQueue) ?? 0; + if (!args.json && !args.plan) { + const remaining = number(preview.remaining) ?? 0; + const cost = + typeof preview.worstCaseUsd === 'number' + ? ` Together they can cost up to ${money(preview.worstCaseUsd)}.` + : ''; + const missing = number(preview.noStoredCode) ?? 0; + const missingText = + missing > 0 + ? `${missing} never-scanned live ${missing === 1 ? 'deployment has' : 'deployments have'} no stored code, so ${missing === 1 ? 'it cannot' : 'they cannot'} be scanned. Deploy ${missing === 1 ? 'that project' : 'those projects'} again.\n` + : ''; + process.stderr.write( + count === 0 + ? `${missing > 0 ? 'Nothing to backfill.' : 'Every live deployment in scope already has a scan. Nothing to backfill.'}\n${missingText}` + : `Scan ${count} live ${count === 1 ? 'deployment' : 'deployments'} that were never scanned?${cost}${remaining > 0 ? ` ${remaining} more wait for the next backfill.` : ''}\n${missingText}${dim('Monthly caps apply when each scan starts.')}\n`, + ); + } + if (count === 0 && !args.plan) { + io.output(preview, args.json); + return; + } + if (!(await io.confirm(origin, preview, args))) { + return; + } + const result = await client.request(args.path, { + method: 'POST', + body: args.body, + timeoutMs: args.timeoutMs, + }); + io.outputMutation(result, args); +} + +async function runWebhook( + client: OperatorClient, + origin: string, + args: OperatorArgs, + io: SecurityIo, +): Promise { + const preview = await previewOf(client, args, args.path, args.body); + if (!(await io.confirm(origin, preview, args))) { + return; + } + const result = await client.request(args.path, { + method: 'POST', + body: args.body, + timeoutMs: args.timeoutMs, + }); + io.outputMutation(result, args); + if (!args.json && typeof result.secret === 'string') { + process.stderr.write( + `${dim('Save the signing secret above now; it is not shown again. Check each request: X-Void-Signature is t=,v1=.">.')}\n`, + ); + } +} + +/** Longest provider key read from stdin; the server takes at most 1,024 characters. */ +const MAX_PROVIDER_KEY_INPUT = 8_192; + +/** Reads one provider API key piped on stdin. The key is never printed. */ +export async function readProviderKeyStdin( + stdin: NodeJS.ReadableStream & { isTTY?: boolean } = process.stdin, +): Promise { + if (stdin.isTTY) { + throw new OperatorClientError( + '--key-stdin needs the key piped on standard input, for example from your password manager.', + 'invalid_key_input', + ); + } + let input = ''; + for await (const chunk of stdin) { + input += String(chunk); + if (input.length > MAX_PROVIDER_KEY_INPUT) { + throw new OperatorClientError('The key on standard input is too long.', 'invalid_key_input'); + } + } + const key = input.trim(); + if (!key || [...key].some((char) => char <= ' ')) { + throw new OperatorClientError( + 'Standard input must hold one API key on one line.', + 'invalid_key_input', + ); + } + return key; +} + +/** `models --provider --key-stdin | --remove-key`: preview, confirm, apply. */ +async function runProviderKey( + client: OperatorClient, + origin: string, + args: OperatorArgs, + io: SecurityIo, +): Promise { + const { keyStdin, ...fields } = args.body; + // Read before any request, once for the preview and the change. + const body: Result = + keyStdin === true ? { ...fields, key: await readProviderKeyStdin() } : fields; + const preview = await previewOf(client, args, args.path, body); + if (!(await io.confirm(origin, preview, args))) { + return; + } + const result = await client.request(args.path, { + method: 'POST', + body, + timeoutMs: args.timeoutMs, + }); + io.outputMutation(result, args); + if (!args.json && typeof result.message === 'string') { + process.stderr.write(`${dim(result.message)}\n`); + } +} + +async function runModel( + client: OperatorClient, + origin: string, + args: OperatorArgs, + io: SecurityIo, +): Promise { + const { acceptProviderNotice, ...fields } = args.body; + const body: Result = { ...fields }; + if (acceptProviderNotice === true) { + body.acceptProviderNoticeVersion = await currentNoticeVersion(client); + } + const preview = await previewOf(client, args, args.path, body); + if (!(await io.confirm(origin, preview, args))) { + return; + } + const result = await client.request(args.path, { + method: 'POST', + body, + timeoutMs: args.timeoutMs, + }); + io.outputMutation(result, args); +} + +async function runMutation( + client: OperatorClient, + origin: string, + args: OperatorArgs, + io: SecurityIo, +): Promise { + switch (args.action) { + case 'probe': { + // A check, not a change: it records the result and has no preview. + io.output( + await client.request(args.path, { method: 'POST', body: {}, timeoutMs: args.timeoutMs }), + args.json, + ); + return; + } + case 'policy': + case 'limits': + case 'public-gate': + case 'sweeps': + case 'fallback': + case 'digest': + return changeWithRevision(client, origin, args, io, { ...args.body }); + case 'webhook': + return runWebhook(client, origin, args, io); + case 'provider-key': + return runProviderKey(client, origin, args, io); + case 'models': { + const { acceptProviderNotice, ...fields } = args.body; + const body: Result = { ...fields }; + if (acceptProviderNotice === true) { + body.acceptProviderNoticeVersion = await currentNoticeVersion(client); + } + return changeWithRevision(client, origin, args, io, body); + } + case 'budget-set': + return runBudget(client, origin, args, io); + case 'resolve': + case 'reopen': + case 'comment': + return runFindings(client, origin, args, io); + case 'model': + return runModel(client, origin, args, io); + case 'rescan': + return runRescan(client, origin, args, io); + case 'backfill': + return runBackfill(client, origin, args, io); + default: { + // cancel, bypass: a preview, then the same body. + const preview = await previewOf(client, args, args.path, args.body); + if (!(await io.confirm(origin, preview, args))) { + return; + } + const result = await client.request(args.path, { + method: 'POST', + body: args.body, + timeoutMs: args.timeoutMs, + }); + io.outputMutation(result, args); + } + } +} + +export async function runSecurityOperatorCommand( + client: OperatorClient, + origin: string, + args: OperatorArgs, + io: SecurityIo, +): Promise { + await guarded(() => + args.method === 'POST' ? runMutation(client, origin, args, io) : runRead(client, args, io), + ); +} diff --git a/packages/void/src/cli/platform-args.ts b/packages/void/src/cli/platform-args.ts index 490f3adfb..5ef12d9b3 100644 --- a/packages/void/src/cli/platform-args.ts +++ b/packages/void/src/cli/platform-args.ts @@ -82,6 +82,7 @@ export type PlatformArgs = noControlPlaneDomain?: true; dedicatedZoneSpecified?: true; customDomains?: true; + securityAudits?: true; account: string; applicationDomain: string; controlPlaneDomain: string; @@ -105,6 +106,7 @@ export type PlatformArgs = authConfig?: string; dashboardUrl?: string; customDomains?: true; + securityAudits?: true; /** upgrade only: omitted keeps the recorded value; `full` clears it. */ runtimeLogs?: PlatformRuntimeLogsChoice; storageLocation?: PlatformStorageLocation; @@ -187,6 +189,7 @@ function parseLifecycleSelector( authConfig?: string; dashboardUrl?: string; customDomains?: true; + securityAudits?: true; runtimeLogs?: PlatformRuntimeLogsChoice; storageLocation?: PlatformStorageLocation; } { @@ -198,6 +201,7 @@ function parseLifecycleSelector( let authConfig: string | undefined; let dashboardUrl: string | undefined; let customDomains = false; + let securityAudits = false; for (let index = 0; index < rest.length; index++) { const arg = rest[index]!; if (arg === '--runtime') { @@ -216,6 +220,11 @@ function parseLifecycleSelector( (subcommand === 'upgrade' || subcommand === 'repair') ) { customDomains = true; + } else if ( + arg === '--security-audits' && + (subcommand === 'upgrade' || subcommand === 'repair') + ) { + securityAudits = true; } else if (arg === '--storage-location' && subcommand === 'upgrade') { const [value, next] = readValue(rest, index, arg); storageLocation = parsePlatformStorageLocation(value); @@ -247,6 +256,7 @@ function parseLifecycleSelector( ...(authConfig !== undefined ? { authConfig } : {}), ...(dashboardUrl !== undefined ? { dashboardUrl } : {}), ...(customDomains ? { customDomains: true as const } : {}), + ...(securityAudits ? { securityAudits: true as const } : {}), ...(runtimeLogs !== undefined ? { runtimeLogs } : {}), ...(storageLocation !== undefined ? { storageLocation } : {}), }; @@ -368,6 +378,7 @@ export function parsePlatformArgs(args: Array): PlatformArgs { authConfig, dashboardUrl, customDomains, + securityAudits, runtimeLogs, storageLocation, } = parseLifecycleSelector(rest, subcommand); @@ -382,6 +393,7 @@ export function parsePlatformArgs(args: Array): PlatformArgs { ...(authConfig !== undefined ? { authConfig } : {}), ...(dashboardUrl !== undefined ? { dashboardUrl } : {}), ...(customDomains ? { customDomains } : {}), + ...(securityAudits ? { securityAudits } : {}), ...(runtimeLogs !== undefined ? { runtimeLogs } : {}), ...(storageLocation !== undefined ? { storageLocation } : {}), }; @@ -429,6 +441,7 @@ export function parsePlatformArgs(args: Array): PlatformArgs { ]); let workersDev = false; let customDomains = false; + let securityAudits = false; for (let i = 0; i < rest.length; i++) { const arg = rest[i]!; if (valueFlags.has(arg)) { @@ -457,6 +470,8 @@ export function parsePlatformArgs(args: Array): PlatformArgs { workersDev = true; } else if (arg === '--custom-domains') { customDomains = true; + } else if (arg === '--security-audits') { + securityAudits = true; } else { throw new Error(`platform: Unexpected argument '${arg}'.`); } @@ -514,6 +529,7 @@ export function parsePlatformArgs(args: Array): PlatformArgs { ...(noControlPlaneDomain ? { noControlPlaneDomain: true as const } : {}), ...(noDedicatedZone ? { dedicatedZoneSpecified: true as const } : {}), ...(customDomains ? { customDomains: true as const } : {}), + ...(securityAudits ? { securityAudits: true as const } : {}), ...(values.has('--hyperdrive') ? { hyperdrive: values.get('--hyperdrive')! } : {}), ...(loginMethods ? { loginMethods: [...new Set(loginMethods)] as Array } diff --git a/packages/void/src/cli/platform-installer.ts b/packages/void/src/cli/platform-installer.ts index 8d95bf721..e7ab6cd8b 100644 --- a/packages/void/src/cli/platform-installer.ts +++ b/packages/void/src/cli/platform-installer.ts @@ -89,6 +89,7 @@ import { } from './platform-registry.ts'; import { assertPlatformRuntimeLogsSupported } from './platform-runtime-logs.ts'; import { assertPlatformWorkerSecretUpdateAuthority } from './platform-secret-update-authority.ts'; +import { assertPlatformSecurityAuditsSupported } from './platform-security-audits.ts'; import { assertPlatformStorageSupported } from './platform-storage.ts'; import { platformManagedWorkerTraffic } from './platform-traffic.ts'; @@ -243,6 +244,7 @@ export async function installPlatform( throw new Error('platform: This runtime does not support the installation’s app access setup.'); } assertPlatformRuntimeLogsSupported(plan.deployment, runtime); + assertPlatformSecurityAuditsSupported(plan.deployment, runtime); assertPlatformStorageSupported(plan.deployment, runtime); const hasEmailGatewayArtifact = runtime.artifacts.emailGateway !== undefined; if ( @@ -609,6 +611,7 @@ export async function installPlatform( deployment: state.plan.deployment, deploymentExecution: runtime.deploymentExecution, healthProbeToken: createPlatformHealthProbeToken(state.manifest.ownershipNonce), + securityScanScheduler: runtime.securityAudits === 1, installationId: state.manifest.id, ownershipNonce: state.manifest.ownershipNonce, platformVersion: version, diff --git a/packages/void/src/cli/platform-lifecycle.ts b/packages/void/src/cli/platform-lifecycle.ts index db56ab540..13b773869 100644 --- a/packages/void/src/cli/platform-lifecycle.ts +++ b/packages/void/src/cli/platform-lifecycle.ts @@ -87,6 +87,7 @@ import { savePlatformInstallChoices, removeSavedPlatformInstallPlan, } from './platform-saved-plans.ts'; +import { assertPlatformSecurityAuditsSupported } from './platform-security-audits.ts'; import { completePlatformSetupDraft, isPlatformSetupDraft, @@ -255,6 +256,7 @@ export async function runPlatformLifecycleCommand(commandArgs: PlatformArgs): Pr !args.dedicatedZoneSpecified && args.dashboardUrl === undefined && !args.customDomains && + !args.securityAudits && args.runtimeLogs === undefined && args.storageLocation === undefined ? listSavedPlatformInstallPlans().filter( @@ -789,6 +791,7 @@ export async function runPlatformLifecycleCommand(commandArgs: PlatformArgs): Pr controlPlaneDomain, ...(args.dashboardUrl !== undefined ? { dashboardUrl: args.dashboardUrl } : {}), ...(args.customDomains ? { customDomains: true } : {}), + ...(args.securityAudits ? { securityAudits: true } : {}), dedicatedZone, displayName, ...(externalHyperdrive ? { externalHyperdrive } : {}), @@ -815,6 +818,7 @@ export async function runPlatformLifecycleCommand(commandArgs: PlatformArgs): Pr createPlatformInstallPlan(client, planInput, existing, planOptions), ); assertPlatformRuntimeLogsSupported(plan.deployment, runtime.manifest); + assertPlatformSecurityAuditsSupported(plan.deployment, runtime.manifest); assertPlatformStorageSupported(plan.deployment, runtime.manifest); const commandOptions = { commandName: cliCommandName(), @@ -826,6 +830,7 @@ export async function runPlatformLifecycleCommand(commandArgs: PlatformArgs): Pr controlPlaneDomain, ...(args.dashboardUrl !== undefined ? { dashboardUrl: args.dashboardUrl } : {}), ...(args.customDomains ? { customDomains: true } : {}), + ...(args.securityAudits ? { securityAudits: true } : {}), dedicatedZone, workersDev, authConfig: args.authConfig, diff --git a/packages/void/src/cli/platform-management.ts b/packages/void/src/cli/platform-management.ts index e587c09a1..5df51a80b 100644 --- a/packages/void/src/cli/platform-management.ts +++ b/packages/void/src/cli/platform-management.ts @@ -89,6 +89,11 @@ import { shouldUpdateProjectWorkerRuntimeLogs, updateProjectWorkerRuntimeLogs, } from './platform-runtime-logs.ts'; +import { + assertPlatformSecurityAuditsSupported, + deletePlatformSecurityScanner, + type SecurityScannerTeardown, +} from './platform-security-audits.ts'; import { assertPlatformStorageSupported } from './platform-storage.ts'; import { assertNoPlatformProjects, @@ -218,6 +223,10 @@ type PlatformManagementDependencies = Readonly<{ readProjects?: () => Promise>; /** Where the operator credential came from; --purge-resources checks it before any change. */ credential?: PurgeResourcesCredential; + /** Deletes the security scanner Worker and container application; required when security audits are on. */ + deleteSecurityScanner?: ( + manifest: PlatformInstallationManifest, + ) => Promise; }>; export function selectAuthoritativePlatformManifest( @@ -261,6 +270,9 @@ export function platformLifecycleResumeCommand( if ('customDomains' in args && args.customDomains) { command.push('--custom-domains'); } + if ('securityAudits' in args && args.securityAudits) { + command.push('--security-audits'); + } if ('runtimeLogs' in args && args.runtimeLogs) { command.push('--runtime-logs', args.runtimeLogs); } @@ -368,6 +380,7 @@ export async function runInstalledPlatformCommand(args: PlatformArgs): Promise readPlatformProjectSlugs(databaseUrl, manifest.id, manifest.ownershipNonce), credential: { source: operatorCredential.source, aiGatewayToken: !!gatewayToken }, + deleteSecurityScanner: (current) => deletePlatformSecurityScanner(client, current), ...(apiUrl && appAccessSetupToken ? { turnOffProjectZeroTrust: async () => { @@ -447,6 +460,7 @@ export async function runInstalledPlatformCommand(args: PlatformArgs): Promise resource.key === 'routing-kv'); // --purge-resources also uses routing KV that an uninstall which stopped before it // finished recorded as retained. @@ -1194,6 +1226,11 @@ export async function uninstallPlatform( ] : ['Turn off project Zero Trust; no platform user exists yet.'] : []), + ...(securityAudits + ? [ + 'Delete the security scanner Worker, its container applications, and the scanner images it copied.', + ] + : []), purgeResources ? purgeResourcesPlanText(manifest) : [ @@ -1409,6 +1446,14 @@ export async function uninstallPlatform( } } } + if (securityAudits) { + // The scanner holds no data. It is billable, so uninstall always removes it; an + // object that is not this installation's is left alone. + const teardown = await dependencies.deleteSecurityScanner!(next); + for (const entry of teardown.kept) { + log.warn(`Kept ${entry}: it does not belong to this installation.`); + } + } if (purgeResources && hasRoutingCheckpoint) { next = await runPurgeResourcesTeardown( { diff --git a/packages/void/src/cli/platform-plan.ts b/packages/void/src/cli/platform-plan.ts index 956fadeb8..fc799565b 100644 --- a/packages/void/src/cli/platform-plan.ts +++ b/packages/void/src/cli/platform-plan.ts @@ -73,6 +73,8 @@ type PlatformInstallPlanInput = Readonly<{ controlPlaneDomain: string; dashboardUrl?: string; customDomains?: boolean; + /** Turns the security audits capability on; omitted keeps the recorded value. */ + securityAudits?: boolean; dedicatedZone: boolean; displayName: string; externalHyperdrive?: PlatformExternalHyperdrive; @@ -211,6 +213,7 @@ export async function createPlatformInstallPlan( : {}), ...(enableEmail ? { email: true } : {}), ...(input.customDomains ? { customDomains: true } : {}), + ...(input.securityAudits ? { securityAudits: true } : {}), }; // Custom hostnames reach dispatch through the dedicated zone's catch-all routes. if (capabilities.customDomains && (testing || !input.dedicatedZone)) { @@ -319,6 +322,18 @@ export async function createPlatformInstallPlan( capabilities: { ...existingWithCustomDomains.capabilities, email: true }, } : existingWithCustomDomains; + // Turning security audits on is the one change here that also moves the schema + // version (7), so an older CLI refuses the document instead of dropping the flag. + const existingWithSecurityAudits = + existing && + deployment.capabilities.securityAudits && + !existing.deployment.capabilities.securityAudits + ? { + ...existingWithEmail, + capabilities: { ...existingWithEmail.capabilities, securityAudits: true }, + schemaVersion: deployment.schemaVersion, + } + : existingWithEmail; // Upgrade may change runtime logs. The setting also moves the schema version, // so leave both out of the comparison. const comparable = ( @@ -339,7 +354,7 @@ export async function createPlatformInstallPlan( }; if ( existing && - (comparable(existingWithEmail) !== comparable(deploymentWithoutEmailZone) || + (comparable(existingWithSecurityAudits) !== comparable(deploymentWithoutEmailZone) || (recordedEmailZone !== undefined && recordedEmailZone !== configuredEmailZone) || (recordedSenderDomain !== undefined && recordedSenderDomain !== configuredSenderDomain)) ) { diff --git a/packages/void/src/cli/platform-plans-args.ts b/packages/void/src/cli/platform-plans-args.ts index 4d4b047e2..a9ddddb0c 100644 --- a/packages/void/src/cli/platform-plans-args.ts +++ b/packages/void/src/cli/platform-plans-args.ts @@ -1,4 +1,5 @@ import { parsePlatformPlanId } from '@void/platform/plans'; +import { parsePlanSecurityCapInput } from '@void/platform/security-policy'; import { parseConfigFlags } from './platform-config-args.ts'; const PLATFORM_PLAN_ACTIONS = [ @@ -23,6 +24,8 @@ export type PlatformPlansArgs = Readonly<{ name: string; copy: string; replacement: string; + /** `--security-cap`: a USD amount, `none` or `inherit`; `undefined` keeps the plan's cap. */ + securityCap: number | 'none' | 'inherit' | undefined; json: boolean; plan: boolean; yes: boolean; @@ -35,6 +38,7 @@ export function parsePlatformPlansArgs(args: ReadonlyArray): PlatformPla 'name', 'copy', 'replacement', + 'security-cap', ]); const [action = '', target = '', ...extra] = positional; if (extra.length || (action && !PLATFORM_PLAN_ACTIONS.includes(action as PlatformPlanAction))) { @@ -62,6 +66,7 @@ export function parsePlatformPlansArgs(args: ReadonlyArray): PlatformPla ['name', ['add', 'set']], ['copy', ['add']], ['replacement', ['remove']], + ['security-cap', ['add', 'set']], ] as const) { if (values.has(name) && !(actions as ReadonlyArray).includes(action)) { throw new Error(`platform: --${name} is only valid for ${actions.join(' or ')}.`); @@ -77,8 +82,28 @@ export function parsePlatformPlansArgs(args: ReadonlyArray): PlatformPla name: values.get('name') ?? '', copy: values.get('copy') ?? '', replacement: values.get('replacement') ?? '', + securityCap: parseSecurityCapFlag(values.get('security-cap')), json: flags.has('json'), plan: flags.has('plan'), yes: flags.has('yes'), }; } + +/** `--security-cap 50`, `--security-cap 12.50`, `none` (no cap) or `inherit` (policy default). */ +function parseSecurityCapFlag(value: string | undefined): number | 'none' | 'inherit' | undefined { + if (value === undefined) { + return undefined; + } + if (value === 'none' || value === 'inherit') { + return value; + } + const usd = value.trim() === '' ? Number.NaN : Number(value); + try { + parsePlanSecurityCapInput(usd); + } catch { + throw new Error( + 'platform: --security-cap must be a USD amount with at most two decimals (for example 50 or 12.50), none, or inherit.', + ); + } + return usd; +} diff --git a/packages/void/src/cli/platform-plans-config.ts b/packages/void/src/cli/platform-plans-config.ts index b9accb217..48f9aba70 100644 --- a/packages/void/src/cli/platform-plans-config.ts +++ b/packages/void/src/cli/platform-plans-config.ts @@ -15,6 +15,15 @@ import { type PlatformPlanCatalog, type PlatformPlanDefinition, } from '@void/platform/plans'; +import { + formatPlanSecurityCap, + parsePlanSecurityCapInput, + planSecurityCap, + readPlanSecurityCaps, + readStoredPlanSecurityCap, + type PlanSecurityCaps, + type SecurityPlanCap, +} from '@void/platform/security-policy'; import { type CANCEL_SYMBOL, confirm, @@ -41,8 +50,24 @@ type Listing = { accounts: Array<{ planId: string; count: number }>; /** Plan AI logging defaults. Platforms before plan defaults do not send it. */ aiLogging?: AiLoggingListing; + /** Per-plan security scan caps (cents or `null`). Platforms before them do not send it. */ + securityCaps?: PlanSecurityCaps; }; +/** A plan's scan cap from an API answer, read leniently (bad entries read as `inherit`). */ +function securityCapOf(caps: unknown, planId: string): SecurityPlanCap { + return planSecurityCap(readPlanSecurityCaps(caps).caps, planId); +} + +/** Refuses a plan scan cap on a platform whose API would refuse or drop it. */ +function assertPlanSecurityCapSupported(listing: Listing, body: Record): void { + if (body.securityCap !== undefined && !listing.securityCaps) { + throw new Error( + 'platform: This platform does not support plan security scan caps. Upgrade the platform first with `void platform upgrade`.', + ); + } +} + const aiLoggingLabels: Record = { inherit: 'inherit (AI Gateway setting)', off: 'off', @@ -98,10 +123,16 @@ function writePlanDiff( to: PlatformPlanDefinition, write: (line: string) => void, aiLogging?: Readonly<{ from: string; to: string }>, + securityCap?: Readonly<{ from: SecurityPlanCap; to: SecurityPlanCap }>, ): void { if (aiLogging && aiLogging.from !== aiLogging.to) { write(`AI Gateway logging: ${aiLogging.from} → ${aiLogging.to}`); } + if (securityCap && securityCap.from !== securityCap.to) { + write( + `Security scan cap: ${formatPlanSecurityCap(securityCap.from)} → ${formatPlanSecurityCap(securityCap.to)}`, + ); + } if (from.buildInstanceType !== to.buildInstanceType) { write(`Build size: ${from.buildInstanceType} → ${to.buildInstanceType}`); } @@ -156,6 +187,12 @@ function showPreview( afterAiLogging ? { from: planAiLogging(savedAiLogging, from), to: planAiLogging(afterAiLogging, to) } : undefined; + // The dry run reads the saved caps under the plan lock; platforms before caps send none. + const caps = preview.securityCaps as { caps?: unknown; capsBefore?: unknown } | undefined; + const securityCap = (from: string, to: string) => + caps + ? { from: securityCapOf(caps.capsBefore, from), to: securityCapOf(caps.caps, to) } + : undefined; write(`Change: ${preview.action} ${preview.target}`); write(`Accounts affected: ${preview.affectedAccounts}`); const publish = preview.aiLoggingPublish as { remaining?: unknown } | undefined; @@ -182,6 +219,9 @@ function showPreview( if (afterAiLogging) { write(` AI Gateway logging: ${planAiLogging(afterAiLogging, plan.id)}`); } + if (caps) { + write(` Security scan cap: ${formatPlanSecurityCap(securityCapOf(caps.caps, plan.id))}`); + } continue; } if (previous.name !== plan.name) { @@ -190,7 +230,13 @@ function showPreview( if (previous.archived !== plan.archived) { write(`${plan.id}: ${plan.archived ? 'archive for new assignments' : 'restore assignments'}`); } - writePlanDiff(previous, plan, write, aiLogging(plan.id, plan.id)); + writePlanDiff( + previous, + plan, + write, + aiLogging(plan.id, plan.id), + securityCap(plan.id, plan.id), + ); } for (const plan of before.plans) { if (!after.plans.some((entry) => entry.id === plan.id)) { @@ -198,7 +244,13 @@ function showPreview( const replacement = after.plans.find((entry) => entry.id === preview.replacementPlanId); if (replacement) { write(`Move accounts to ${label(replacement)}`); - writePlanDiff(plan, replacement, write, aiLogging(plan.id, replacement.id)); + writePlanDiff( + plan, + replacement, + write, + aiLogging(plan.id, replacement.id), + securityCap(plan.id, replacement.id), + ); } } } @@ -252,6 +304,7 @@ async function changesInput( plan?: PlatformPlanDefinition, listing?: Listing, ): Promise> { + const cap = args.securityCap === undefined ? {} : { securityCap: args.securityCap }; if (args.file) { const input: unknown = JSON.parse(await readFile(args.file, 'utf8')); if (!input || typeof input !== 'object' || Array.isArray(input)) { @@ -259,14 +312,24 @@ async function changesInput( } const object = input as Record; for (const key of Object.keys(object)) { - if (!['name', 'limits', 'buildInstanceType', 'allowShortSlugs', 'aiLogging'].includes(key)) { + if ( + ![ + 'name', + 'limits', + 'buildInstanceType', + 'allowShortSlugs', + 'aiLogging', + 'securityCap', + ].includes(key) + ) { throw new Error( - `platform: Unknown plan field ${key}. Use name, limits, buildInstanceType, allowShortSlugs, or aiLogging.`, + `platform: Unknown plan field ${key}. Use name, limits, buildInstanceType, allowShortSlugs, aiLogging, or securityCap.`, ); } } try { parsePlanAiLoggingInput(object.aiLogging); + parsePlanSecurityCapInput(object.securityCap); } catch (error) { throw new Error(`platform: ${(error as Error).message}`); } @@ -281,10 +344,14 @@ async function changesInput( : {}), ...(object.limits !== undefined ? { limits: parsePlanLimitsPatch(object.limits) } : {}), ...(args.name ? { name: parsePlanName(args.name) } : {}), + ...cap, }; } if (args.name) { - return { name: parsePlanName(args.name) }; + return { name: parsePlanName(args.name), ...cap }; + } + if (args.action === 'set' && args.securityCap !== undefined) { + return cap; } if (!process.stdin.isTTY || args.json) { if (args.action === 'add') { @@ -297,6 +364,7 @@ async function changesInput( if (args.action === 'add') { return { name: parsePlanName(value(await text({ message: 'Plan name:', initialValue: args.target }))), + ...cap, }; } const field = value( @@ -317,9 +385,20 @@ async function changesInput( }, ] : []), + ...(listing?.securityCaps + ? [ + { + value: 'securityCap', + label: `Security scan cap: ${formatPlanSecurityCap(securityCapOf(listing.securityCaps, plan!.id))}`, + }, + ] + : []), ], }), ); + if (field === 'securityCap') { + return { securityCap: await chooseSecurityCap(securityCapOf(listing!.securityCaps, plan!.id)) }; + } if (field === 'aiLogging') { return { aiLogging: value( @@ -364,6 +443,39 @@ async function changesInput( return { limits: parsePlanLimitsPatch({ [field]: Number(input) }) }; } +/** The interactive scan cap picker: policy default, an amount, or no cap. */ +async function chooseSecurityCap(current: SecurityPlanCap): Promise { + const mode = value( + await select({ + message: 'Monthly security scan cap for each project on this plan:', + initialValue: typeof current === 'number' ? 'amount' : current, + options: [ + { value: 'inherit', label: 'Policy default (the default project cap, when it is on)' }, + { value: 'amount', label: 'A monthly amount in USD' }, + { value: 'none', label: 'No cap' }, + ], + }), + ); + if (mode !== 'amount') { + return mode as 'none' | 'inherit'; + } + const input = value( + await text({ + message: 'USD per project per month:', + initialValue: typeof current === 'number' ? String(current / 100) : '', + validate: (entry) => { + try { + parsePlanSecurityCapInput(entry?.trim() ? Number(entry) : Number.NaN); + return undefined; + } catch { + return 'Enter a USD amount with at most two decimals.'; + } + }, + }), + ); + return Number(input); +} + async function apply( client: OperatorClient, path: string, @@ -373,6 +485,7 @@ async function apply( ): Promise { const { catalog } = listing; assertPlanAiLoggingSupported(listing, body); + assertPlanSecurityCapSupported(listing, body); if (!args.plan && !args.yes && (!process.stdin.isTTY || args.json)) { throw new Error( 'platform: Configuration changes require --yes or --plan in non-interactive mode.', @@ -593,6 +706,13 @@ export async function runPlatformPlansConfig(args: PlatformPlansArgs): Promise, +): void { + if (deployment.capabilities.securityAudits && runtime.securityAudits !== 1) { + throw new Error( + 'platform: This platform runtime does not include security audits. Use a current packaged runtime, or leave out --security-audits.', + ); + } +} + +// The scanner is created by the API Worker at turn-on (platform/packages/api/src/provisioning/ +// security-scanner.ts). Names and the ownership marker are derived the same way here, because +// the installer record does not list resources the API creates. +const OWNER_BINDING = '__VOID_SECURITY_SCANNER_OWNER'; +const PROTOCOL = 1; + +type ScannerClient = Pick; + +type Binding = { type: string; name: string; text?: string; namespace_id?: string }; + +/** Engines A and C each have a container application and a copied image (API M13b). */ +const ENGINES = [ + { slug: 'engine-a', binding: 'SCANNER_ENGINE_A' }, + { slug: 'engine-c', binding: 'SCANNER_ENGINE_C' }, +] as const; + +export type SecurityScannerEngineNames = { application: string; repository: string }; + +export function securityScannerNames(installationId: string): { + worker: string; + application: string; + gate: string; + engines: { 'engine-a': SecurityScannerEngineNames; 'engine-c': SecurityScannerEngineNames }; +} { + const suffix = createHash('sha256') + .update(`void-security-scanner:${installationId}`) + .digest('hex') + .slice(0, 12); + const engine = (slug: string): SecurityScannerEngineNames => ({ + application: `void-security-scanner-${slug}-${suffix}`, + repository: `void-security-scanner-${slug}-${suffix}`, + }); + return { + worker: `void-security-scanner-${suffix}`, + application: `void-security-scanner-${suffix}`, + gate: `void-security-scanner-gate-${suffix}`, + engines: { 'engine-a': engine('engine-a'), 'engine-c': engine('engine-c') }, + }; +} + +function ownerMarker(installationId: string): string { + return JSON.stringify({ protocol: PROTOCOL, installation: installationId }); +} + +function plainText(bindings: ReadonlyArray): string | undefined { + return bindings.find((binding) => binding.type === 'plain_text' && binding.name === OWNER_BINDING) + ?.text; +} + +async function optional(read: () => Promise): Promise { + try { + return await read(); + } catch (error) { + if (error instanceof PlatformCloudflareApiError && error.status === 404) { + return undefined; + } + throw error; + } +} + +async function optionalOrForbidden(read: () => Promise): Promise { + try { + return await read(); + } catch (error) { + if ( + error instanceof PlatformCloudflareApiError && + (error.status === 403 || error.status === 404) + ) { + return undefined; + } + throw error; + } +} + +async function deleteIfPresent(client: ScannerClient, path: string): Promise { + await optional(() => client.request(path, { method: 'DELETE' })); +} + +type Deleted = 'gate' | 'container application' | 'controller' | 'scanner images'; + +export type SecurityScannerTeardown = Readonly<{ + /** Cloudflare objects removed, in order. */ + deleted: ReadonlyArray; + /** Objects with the scanner's name that are not this installation's. They stay. */ + kept: ReadonlyArray; +}>; + +const REGISTRY = 'registry.cloudflare.com'; +const MANIFEST_ACCEPT = [ + 'application/vnd.oci.image.manifest.v1+json', + 'application/vnd.docker.distribution.manifest.v2+json', +].join(', '); + +type RegistryFetch = (input: string, init?: RequestInit) => Promise; + +/** + * Removes every manifest in the engine image repositories the API copied into this + * account (one per engine, named per installation), then the unreferenced layers. + * Returns whether anything was removed. + */ +async function deleteScannerImages( + client: ScannerClient, + registryFetch: RegistryFetch, + account: string, + repositories: ReadonlyArray, + controllerExists: boolean, +): Promise { + const read = () => + client.request<{ username?: unknown; password?: unknown }>( + `/accounts/${encodeURIComponent(account)}/containers/registries/${REGISTRY}/credentials`, + { + method: 'POST', + body: JSON.stringify({ expiration_minutes: 15, permissions: ['push', 'pull'] }), + }, + ); + // With no controller the images are most likely not there either, so a token without + // Containers rights is not a failure (as for the application list). + const credentials = controllerExists ? await read() : await optionalOrForbidden(read); + if ( + !credentials || + typeof credentials.username !== 'string' || + typeof credentials.password !== 'string' + ) { + return false; + } + const auth = `Basic ${Buffer.from(`${credentials.username}:${credentials.password}`).toString('base64')}`; + const call = async (url: string, init: RequestInit = {}) => + registryFetch(url, { + ...init, + headers: { Authorization: auth, Accept: MANIFEST_ACCEPT, ...init.headers }, + signal: AbortSignal.timeout(30_000), + }); + let removed = false; + for (const repository of repositories) { + const base = `https://${REGISTRY}/v2/${account}/${repository}`; + const list = await call(`${base}/tags/list`); + if (list.status === 404) { + await list.body?.cancel(); + continue; + } + if (!list.ok) { + await list.body?.cancel(); + throw new Error( + `platform: Listing the security scanner images failed (HTTP ${list.status}).`, + ); + } + const { tags } = (await list.json()) as { tags?: unknown }; + for (const tag of Array.isArray(tags) ? tags : []) { + if (typeof tag !== 'string') { + continue; + } + const head = await call(`${base}/manifests/${encodeURIComponent(tag)}`, { method: 'HEAD' }); + await head.body?.cancel(); + if (head.status === 404) { + continue; + } + const digest = head.headers.get('docker-content-digest'); + if (head.status !== 200 || !digest) { + // Never report the cleanup as done while an image may still be stored. + throw new Error( + `platform: Reading security scanner image ${repository}:${tag} failed (HTTP ${head.status}).`, + ); + } + const deleted = await call(`${base}/manifests/${digest}`, { method: 'DELETE' }); + await deleted.body?.cancel(); + if (!deleted.ok && deleted.status !== 404) { + throw new Error( + `platform: Deleting a security scanner image failed (HTTP ${deleted.status}).`, + ); + } + removed = true; + } + } + if (removed) { + const gc = await call(`https://${REGISTRY}/v2/gc/layers`, { method: 'PUT' }); + await gc.body?.cancel(); + if (!gc.ok) { + throw new Error(`platform: The registry layer cleanup failed (HTTP ${gc.status}).`); + } + } + return removed; +} + +/** + * Uninstall: the gate first (nothing can call in), then the billable container + * applications (Engine B and one per engine image), then the controller Worker, then the + * engine images copied into the account registry. Each is found by its derived name and + * proven ours by the ownership marker (an application also by its controller's Durable + * Object namespace); one that is not ours is left alone and reported. With the + * capability off this makes no Cloudflare call at all. + */ +export async function deletePlatformSecurityScanner( + client: ScannerClient, + manifest: PlatformInstallationManifest, + registryFetch: RegistryFetch = (input, init) => fetch(input, init), +): Promise { + if (!manifest.deployment.capabilities.securityAudits) { + return { deleted: [], kept: [] }; + } + const account = encodeURIComponent(manifest.account.id); + const names = securityScannerNames(manifest.id); + const marker = ownerMarker(manifest.id); + const deleted: Array = []; + const kept: Array = []; + + const gatePath = `/accounts/${account}/workers/dispatch/namespaces/${encodeURIComponent( + manifest.deployment.resources.dispatchNamespace, + )}/scripts/${names.gate}`; + const gate = await optional(() => client.request(gatePath)); + if (gate !== undefined) { + const bindings = await client.request>(`${gatePath}/bindings`); + if (plainText(bindings) === marker) { + await deleteIfPresent(client, gatePath); + deleted.push('gate'); + } else { + kept.push(`security scanner gate ${names.gate}`); + } + } + + const workerPath = `/accounts/${account}/workers/scripts/${names.worker}`; + const settings = await optional(() => + client.request<{ bindings: ReadonlyArray }>(`${workerPath}/settings`), + ); + // The capability is on from install, but the scanner is created only when an admin + // first leaves `disabled`. With no controller there is nothing to remove, so a token + // without Containers rights (403) or a missing list (404) is not a failure. + const targets = [ + { name: names.application, binding: 'SCANNER' }, + ...ENGINES.map((engine) => ({ + name: names.engines[engine.slug].application, + binding: engine.binding, + })), + ]; + const found: Array<{ name: string; binding: string; id: string; namespace?: string }> = []; + for (const target of targets) { + const listApplications = () => + client.request< + ReadonlyArray<{ id: string; name: string; durable_objects?: { namespace_id?: string } }> + >(`/accounts/${account}/containers/applications?name=${encodeURIComponent(target.name)}`); + const applications = settings + ? await listApplications() + : ((await optionalOrForbidden(listApplications)) ?? []); + const application = applications.find((entry) => entry.name === target.name); + if (application) { + found.push({ + ...target, + id: application.id, + namespace: application.durable_objects?.namespace_id, + }); + } + } + const repositories = ENGINES.map((engine) => names.engines[engine.slug].repository); + if (!settings) { + // A container application whose controller is gone cannot be proven ours. + for (const application of found) { + kept.push(`security scanner container application ${application.name}`); + } + if ( + await deleteScannerImages(client, registryFetch, manifest.account.id, repositories, false) + ) { + deleted.push('scanner images'); + } + return { deleted, kept }; + } + if (plainText(settings.bindings) !== marker) { + kept.push(`security scanner controller ${names.worker}`); + for (const application of found) { + kept.push(`security scanner container application ${application.name}`); + } + return { deleted, kept }; + } + let removedApplication = false; + for (const application of found) { + const namespace = settings.bindings.find( + (binding) => + binding.type === 'durable_object_namespace' && binding.name === application.binding, + )?.namespace_id; + if (namespace !== undefined && application.namespace === namespace) { + await deleteIfPresent( + client, + `/accounts/${account}/containers/applications/${application.id}`, + ); + removedApplication = true; + } else { + kept.push(`security scanner container application ${application.name}`); + } + } + if (removedApplication) { + deleted.push('container application'); + } + await deleteIfPresent(client, workerPath); + deleted.push('controller'); + if (await deleteScannerImages(client, registryFetch, manifest.account.id, repositories, true)) { + deleted.push('scanner images'); + } + return { deleted, kept }; +} diff --git a/packages/void/src/cli/platform-setup.ts b/packages/void/src/cli/platform-setup.ts index b407bf9fc..f4897c727 100644 --- a/packages/void/src/cli/platform-setup.ts +++ b/packages/void/src/cli/platform-setup.ts @@ -109,6 +109,13 @@ export function platformManagementSetupPage( const appAccessLevel = appAccess ? 'edit' : accessLevel; const permissions = [ ...platformAccountTokenPermissions(true), + // Uninstall deletes the security scanner's container application. + ...(plan.deployment.capabilities.securityAudits + ? [ + { key: 'containers', type: 'edit' }, + { key: 'cloudchamber', type: 'edit' }, + ] + : []), ...(zoneName || apiHostname || createsZone ? [ { key: 'zone', type: createsZone ? 'edit' : 'read' }, @@ -165,7 +172,8 @@ export function platformSetupPages(plan: PlatformInstallPlan): { ...(plan.deployment.capabilities.customDomains ? [{ key: 'ssl_and_certificates', type: 'edit' }] : []), - ...(plan.deployment.capabilities.sandbox + // Security audits run the scanner on Containers, as Sandbox does. + ...(plan.deployment.capabilities.sandbox || plan.deployment.capabilities.securityAudits ? [ { key: 'containers', type: 'edit' }, { key: 'cloudchamber', type: 'edit' }, @@ -299,6 +307,7 @@ export type PlatformInstallCommandOptions = { controlPlaneDomain: string; dashboardUrl?: string; customDomains?: boolean; + securityAudits?: boolean; dedicatedZone: boolean; workersDev: boolean; authConfig?: string; @@ -359,6 +368,9 @@ export function platformInstallCommandArguments( ); } flag('--dashboard-url', options.dashboardUrl ?? ''); + if (options.securityAudits) { + parts.push('--security-audits'); + } flag('--runtime', options.runtime); flag('--runtime-logs', options.runtimeLogs ?? ''); flag('--storage-location', options.storageLocation ?? ''); diff --git a/packages/void/src/cli/project-args.ts b/packages/void/src/cli/project-args.ts index 7640fd398..8afa1a002 100644 --- a/packages/void/src/cli/project-args.ts +++ b/packages/void/src/cli/project-args.ts @@ -1,3 +1,4 @@ +import { parseSecurityArgs, type ProjectSecurityArgs } from './project-security-args.ts'; import type { SubcommandDef } from './subcommand-prompt.ts'; const LOG_LEVELS = new Set(['error', 'warn', 'info', 'log', 'debug', 'all']); @@ -25,9 +26,14 @@ export const projectSubcommands: Array = [ }, { name: 'zero-trust', - hint: 'status | protect | public | reconcile', + hint: 'status | protect | public | bypass | reconcile', description: 'Inspect or override Cloudflare Zero Trust protection', }, + { + name: 'security', + hint: 'status | list | show | comment | resolve | reopen | scans | model | budget | open', + description: 'Review security audit findings and settings', + }, { name: 'logs', description: 'Show runtime logs from the deployed project' }, { name: 'requests', description: 'Show request-level traffic (status, method, timing)' }, { @@ -51,15 +57,95 @@ export const projectSubcommands: Array = [ { name: 'purge-cache', description: 'Purge all cached pages (Void platform)' }, ]; +export type ProjectZeroTrustArgs = { + subcommand: 'zero-trust'; + projectSlug: string; + json: boolean; +} & ( + | { action: '' | 'status' | 'protect' | 'public' | 'reconcile' } + | { action: 'bypass'; reason: string; yes: boolean } +); + +const ZERO_TRUST_ACTIONS = ['status', 'protect', 'public', 'bypass', 'reconcile']; +const BYPASS_REASON_MAX_CHARS = 4000; + +function parseZeroTrustArgs(rest: Array): ProjectZeroTrustArgs { + const [action = '', ...args] = rest; + if (action && !ZERO_TRUST_ACTIONS.includes(action)) { + throw new Error( + 'project: Usage: void project zero-trust [--project ] [--json].', + ); + } + let projectSlug = ''; + let reason: string | undefined; + let yes = false; + let json = false; + for (let index = 0; index < args.length; index++) { + const arg = args[index]!; + if (arg === '--project') { + const value = args[++index]; + if (!value || value.startsWith('-')) { + throw new Error('project: --project requires a value.'); + } + if (projectSlug) { + throw new Error("project: Duplicate flag '--project'."); + } + projectSlug = value; + } else if (arg === '--json') { + if (json) { + throw new Error("project: Duplicate flag '--json'."); + } + json = true; + } else if (arg === '--reason' || arg === '--yes') { + if (action !== 'bypass') { + throw new Error(`project: ${arg} is not used with zero-trust ${action || ''}.`); + } + if (arg === '--yes') { + if (yes) { + throw new Error("project: Duplicate flag '--yes'."); + } + yes = true; + continue; + } + if (reason !== undefined) { + throw new Error("project: Duplicate flag '--reason'."); + } + // A reason is free text and may start with a dash. + const value = args[++index]; + if (value === undefined) { + throw new Error('project: --reason requires a value.'); + } + reason = value; + } else { + throw new Error(`project: Unexpected argument '${arg}'.`); + } + } + if (action === 'bypass') { + const text = reason?.trim() ?? ''; + if (text === '') { + throw new Error( + 'project: A reason is required. Say why, for example: --reason "Launch today; scanner is down. Will re-check."', + ); + } + if ([...text].length > BYPASS_REASON_MAX_CHARS) { + throw new Error(`project: A reason can be at most ${BYPASS_REASON_MAX_CHARS} characters.`); + } + return { subcommand: 'zero-trust', projectSlug, json, action, reason: text, yes }; + } + return { + subcommand: 'zero-trust', + projectSlug, + json, + action: action as '' | 'status' | 'protect' | 'public' | 'reconcile', + }; +} + export type ProjectArgs = | { subcommand: 'status'; name: string } | { subcommand: 'link'; name: string } | { subcommand: 'list' } - | { - subcommand: 'zero-trust'; - action: '' | 'status' | 'protect' | 'public' | 'reconcile'; - projectSlug: string; - } + | ProjectZeroTrustArgs + | ProjectSecurityArgs | { subcommand: 'team'; action: '' } | { subcommand: 'team'; @@ -194,33 +280,11 @@ export function parseProjectArgs(args: Array): ProjectArgs { } if (subcommand === 'zero-trust') { - const [action = '', ...args] = rest; - if (action && !['status', 'protect', 'public', 'reconcile'].includes(action)) { - throw new Error( - 'project: Usage: void project zero-trust [--project ].', - ); - } - let projectSlug = ''; - for (let index = 0; index < args.length; index++) { - const arg = args[index]!; - if (arg === '--project') { - const value = args[++index]; - if (!value || value.startsWith('-')) { - throw new Error('project: --project requires a value.'); - } - if (projectSlug) { - throw new Error("project: Duplicate flag '--project'."); - } - projectSlug = value; - } else { - throw new Error(`project: Unexpected argument '${arg}'.`); - } - } - return { - subcommand, - action: action as '' | 'status' | 'protect' | 'public' | 'reconcile', - projectSlug, - }; + return parseZeroTrustArgs(rest); + } + + if (subcommand === 'security') { + return parseSecurityArgs(rest); } if (subcommand === 'logs') { @@ -329,7 +393,7 @@ export function parseProjectArgs(args: Array): ProjectArgs { } throw new Error( - 'project: Usage: void project .', + 'project: Usage: void project .', ); } diff --git a/packages/void/src/cli/project-cmd.ts b/packages/void/src/cli/project-cmd.ts index 08ea03263..9ab0464e1 100644 --- a/packages/void/src/cli/project-cmd.ts +++ b/packages/void/src/cli/project-cmd.ts @@ -60,9 +60,22 @@ export async function runProjectCommand(root: string, args: ProjectArgs): Promis printHelpPage(['project', 'zero-trust']); return; } - const action = args.action; const { runProjectZeroTrustCommand } = await import('./project-zero-trust.ts'); - return runProjectZeroTrustCommand(root, { ...args, action }); + return runProjectZeroTrustCommand(root, args); + } + if (args.subcommand === 'security') { + if (cloudflare) { + throw new Error( + 'project: Security audits are available only for projects hosted on a Void platform.', + ); + } + if (args.action === '') { + const { printHelpPage } = await import('./help.ts'); + printHelpPage(['project', 'security']); + return; + } + const { runProjectSecurityCommand } = await import('./project-security.ts'); + return runProjectSecurityCommand(root, args); } if (args.subcommand === 'logs') { const { runLogsCommand } = await import('./logs.ts'); diff --git a/packages/void/src/cli/project-security-args.ts b/packages/void/src/cli/project-security-args.ts new file mode 100644 index 000000000..e355d39ab --- /dev/null +++ b/packages/void/src/cli/project-security-args.ts @@ -0,0 +1,399 @@ +/** Arguments of `void project security …` (spec §13.3). */ + +export const SECURITY_COMMENT_MAX_CHARS = 4000; +const SECURITY_ACTIONS = [ + 'status', + 'list', + 'show', + 'comment', + 'resolve', + 'reopen', + 'severity', + 'scans', + 'scan', + 'check', + 'model', + 'budget', + 'open', +] as const; +const SEVERITIES = ['critical', 'high', 'medium', 'low', 'informational']; +const STATES = ['open', 'resolved', 'all']; +const REASONS: Record = { + fixed: 'fixed', + 'false-positive': 'false_positive', + 'accepted-risk': 'accepted_risk', +}; +// The platform takes up to $1,000,000 a month (`MAX_CAP_CENTS`); "any amount" when no ceiling applies. +const MAX_BUDGET_USD = 1_000_000; + +export type SecurityResolutionReason = 'fixed' | 'false_positive' | 'accepted_risk'; + +export type ProjectSecurityArgs = { + subcommand: 'security'; + projectSlug: string; + json: boolean; +} & ( + | { action: '' | 'status' | 'open' } + | { + action: 'list'; + urgent: boolean; + state: 'open' | 'resolved' | 'all'; + severity: string | null; + leads: boolean; + /** M31: `sarif` prints a SARIF 2.1.0 log instead of the table. */ + format: 'text' | 'sarif'; + } + | { action: 'show'; id: string } + | { action: 'comment'; id: string; text: string } + | { action: 'resolve'; ids: Array; reason: SecurityResolutionReason; comment: string } + | { action: 'reopen'; id: string; comment: string } + /** M35: `severity` is `null` for `scan` (use the scan value again). */ + | { action: 'severity'; id: string; severity: string | null; comment: string } + | { action: 'scans'; limit: number } + | { action: 'scan'; yes: boolean; clientAssets: boolean } + /** M32: scan the local tree (`checkId` empty), or show / wait for an earlier check. */ + | { action: 'check'; checkId: string; yes: boolean; wait: boolean } + | { + action: 'model'; + change: 'show' | 'set' | 'default'; + model: string; + acceptNotice: boolean; + } + | { action: 'budget'; change: 'show' | 'set' | 'off'; usd: number } +); + +const VALUE_FLAGS = new Set([ + '--project', + '--reason', + '--comment', + '--state', + '--severity', + '--limit', + '--usd', + '--format', +]); +const BOOLEAN_FLAGS = new Set([ + '--json', + '--urgent', + '--leads', + '--default', + '--accept-provider-notice', + '--off', + '--yes', + '--client-assets', + '--no-wait', +]); +// Flags each action accepts besides `--project` and `--json`. +const ACTION_FLAGS: Record> = { + status: [], + open: [], + list: ['--urgent', '--state', '--severity', '--leads', '--format'], + show: [], + comment: [], + resolve: ['--reason', '--comment'], + reopen: ['--comment'], + severity: ['--comment'], + scans: ['--limit'], + scan: ['--yes', '--client-assets'], + check: ['--yes', '--no-wait'], + model: ['--default', '--accept-provider-notice'], + budget: ['--usd', '--off'], +}; + +/** `F-12`, `f-12` or `12` → `F-12`; anything else is `null`. */ +export function normalizeFindingId(value: string): string | null { + const text = value.trim(); + let digits = text; + if (text[0] === 'F' || text[0] === 'f') { + digits = text.slice(1); + if (digits[0] === '-') { + digits = digits.slice(1); + } + } + if (digits.length === 0 || digits.length > 9 || digits.startsWith('0')) { + return null; + } + for (const char of digits) { + if (char < '0' || char > '9') { + return null; + } + } + return `F-${digits}`; +} + +function parseFindingIds(values: Array): Array { + const ids: Array = []; + for (const value of values) { + for (const part of value.split(',')) { + if (part.trim() === '') { + continue; + } + const id = normalizeFindingId(part); + if (!id) { + throw new Error(`project: '${part.trim()}' is not a finding id. Use a form like F-12.`); + } + if (!ids.includes(id)) { + ids.push(id); + } + } + } + return ids; +} + +/** A dollar amount with at most two decimals, as whole cents of precision. */ +function parseUsd(value: string): number { + const [whole = '', fraction = '', ...extra] = value.split('.'); + const digits = (text: string) => [...text].every((char) => char >= '0' && char <= '9'); + if ( + extra.length > 0 || + whole === '' || + !digits(whole) || + !digits(fraction) || + fraction.length > 2 || + value.includes('.') === (fraction === '') + ) { + throw new Error('project: --usd must be a dollar amount such as 40 or 12.50.'); + } + const usd = Number(value); + if (!Number.isFinite(usd) || usd > MAX_BUDGET_USD) { + throw new Error(`project: --usd must be at most ${MAX_BUDGET_USD}.`); + } + return usd; +} + +function requireComment(value: string | undefined): string { + const text = value?.trim() ?? ''; + if (text === '') { + throw new Error( + 'project: A comment is required. Say why, for example: --comment "Added requireAdmin() in a1b2c3"', + ); + } + if ([...text].length > SECURITY_COMMENT_MAX_CHARS) { + throw new Error(`project: A comment can be at most ${SECURITY_COMMENT_MAX_CHARS} characters.`); + } + return text; +} + +export function parseSecurityArgs(rest: Array): ProjectSecurityArgs { + const [action = '', ...args] = rest; + if (action !== '' && !(SECURITY_ACTIONS as ReadonlyArray).includes(action)) { + throw new Error( + `project: Usage: void project security <${SECURITY_ACTIONS.join('|')}> [--project ] [--json].`, + ); + } + const values = new Map(); + const flags = new Set(); + const positionals: Array = []; + const allowed = new Set(['--project', '--json', ...(ACTION_FLAGS[action] ?? [])]); + for (let index = 0; index < args.length; index++) { + const arg = args[index]!; + if (BOOLEAN_FLAGS.has(arg) || VALUE_FLAGS.has(arg)) { + if (!allowed.has(arg)) { + throw new Error(`project: ${arg} is not used with security ${action || ''}.`); + } + if (flags.has(arg) || values.has(arg)) { + throw new Error(`project: Duplicate flag '${arg}'.`); + } + if (BOOLEAN_FLAGS.has(arg)) { + flags.add(arg); + continue; + } + const value = args[++index]; + // A comment may start with a dash; every other value is a word. + const dashOk = arg === '--comment' || arg === '--usd'; + if (value === undefined || (!dashOk && value.startsWith('-'))) { + throw new Error(`project: ${arg} requires a value.`); + } + values.set(arg, value); + } else if (arg.startsWith('-') && !(action === 'comment' && positionals.length >= 1)) { + throw new Error(`project: Unknown flag '${arg}'.`); + } else { + positionals.push(arg); + } + } + const base = { subcommand: 'security' as const, projectSlug: values.get('--project') ?? '' }; + const json = flags.has('--json'); + const noPositionals = () => { + if (positionals.length > 0) { + throw new Error(`project: Unexpected argument '${positionals[0]}'.`); + } + }; + + if (action === '') { + noPositionals(); + return { ...base, json, action }; + } + if (action === 'status' || action === 'open') { + noPositionals(); + return { ...base, json, action }; + } + if (action === 'list') { + noPositionals(); + const state = values.get('--state') ?? 'open'; + if (!STATES.includes(state)) { + throw new Error(`project: Invalid --state '${state}'. Use one of open|resolved|all.`); + } + const severity = values.get('--severity') ?? null; + if (severity !== null && !SEVERITIES.includes(severity)) { + throw new Error( + `project: Invalid --severity '${severity}'. Use one of ${SEVERITIES.join('|')}.`, + ); + } + const format = values.get('--format') ?? 'text'; + if (format !== 'text' && format !== 'sarif') { + throw new Error(`project: Invalid --format '${format}'. Use text or sarif.`); + } + if (format === 'sarif' && json) { + throw new Error('project: Use --format sarif or --json, not both.'); + } + return { + ...base, + json, + action, + format, + urgent: flags.has('--urgent'), + state: state as 'open' | 'resolved' | 'all', + severity, + leads: flags.has('--leads'), + }; + } + if (action === 'show' || action === 'reopen') { + if (positionals.length !== 1) { + throw new Error( + `project: Usage: void project security ${action} ${action === 'reopen' ? ' --comment ""' : ''}.`, + ); + } + const id = parseFindingIds(positionals)[0]; + if (!id) { + throw new Error(`project: '${positionals[0]}' is not a finding id. Use a form like F-12.`); + } + if (action === 'show') { + return { ...base, json, action, id }; + } + return { ...base, json, action, id, comment: requireComment(values.get('--comment')) }; + } + if (action === 'comment') { + if (positionals.length !== 2) { + throw new Error('project: Usage: void project security comment "".'); + } + const id = parseFindingIds([positionals[0]!])[0]; + if (!id) { + throw new Error(`project: '${positionals[0]}' is not a finding id. Use a form like F-12.`); + } + return { ...base, json, action, id, text: requireComment(positionals[1]) }; + } + if (action === 'resolve') { + const ids = parseFindingIds(positionals); + if (ids.length === 0) { + throw new Error( + 'project: Usage: void project security resolve … --reason fixed|false-positive|accepted-risk --comment "".', + ); + } + const reasonText = values.get('--reason'); + const reason = reasonText === undefined ? undefined : REASONS[reasonText]; + if (!reason) { + throw new Error('project: --reason is required: fixed, false-positive or accepted-risk.'); + } + return { ...base, json, action, ids, reason, comment: requireComment(values.get('--comment')) }; + } + if (action === 'severity') { + const usage = `project: Usage: void project security severity <${SEVERITIES.join('|')}|scan> --comment "".`; + if (positionals.length !== 2) { + throw new Error(usage); + } + const id = parseFindingIds([positionals[0]!])[0]; + if (!id) { + throw new Error(`project: '${positionals[0]}' is not a finding id. Use a form like F-12.`); + } + const level = positionals[1]!; + if (level !== 'scan' && !SEVERITIES.includes(level)) { + throw new Error( + `project: Invalid severity '${level}'. Use one of ${SEVERITIES.join('|')}, or scan to use the scan severity again.`, + ); + } + return { + ...base, + json, + action, + id, + severity: level === 'scan' ? null : level, + comment: requireComment(values.get('--comment')), + }; + } + if (action === 'scans') { + noPositionals(); + const text = values.get('--limit'); + let limit = 10; + if (text !== undefined) { + limit = Number(text); + if (!Number.isInteger(limit) || limit < 1 || limit > 100) { + throw new Error('project: --limit must be a whole number from 1 to 100.'); + } + } + return { ...base, json, action, limit }; + } + if (action === 'scan') { + noPositionals(); + return { + ...base, + json, + action, + yes: flags.has('--yes'), + clientAssets: flags.has('--client-assets'), + }; + } + if (action === 'check') { + if (positionals.length > 1) { + throw new Error(`project: Unexpected argument '${positionals[1]}'.`); + } + const checkId = positionals[0] ?? ''; + if (checkId.length > 64) { + throw new Error(`project: '${checkId.slice(0, 64)}…' is not a check id.`); + } + if (checkId !== '' && flags.has('--yes')) { + throw new Error('project: --yes is used only when a new check starts.'); + } + return { + ...base, + json, + action, + checkId, + yes: flags.has('--yes'), + wait: !flags.has('--no-wait'), + }; + } + if (action === 'model') { + if (positionals.length > 1) { + throw new Error(`project: Unexpected argument '${positionals[1]}'.`); + } + const useDefault = flags.has('--default'); + if (useDefault && positionals.length > 0) { + throw new Error('project: Pass a model id or --default, not both.'); + } + const acceptNotice = flags.has('--accept-provider-notice'); + if (acceptNotice && !useDefault && positionals.length === 0) { + throw new Error('project: --accept-provider-notice needs a model id or --default.'); + } + return { + ...base, + json, + action, + change: useDefault ? 'default' : positionals.length > 0 ? 'set' : 'show', + model: positionals[0] ?? '', + acceptNotice, + }; + } + // budget + noPositionals(); + const usdText = values.get('--usd'); + if (usdText !== undefined && flags.has('--off')) { + throw new Error('project: Pass --usd or --off, not both.'); + } + return { + ...base, + json, + action: 'budget', + change: flags.has('--off') ? 'off' : usdText === undefined ? 'show' : 'set', + usd: usdText === undefined ? 0 : parseUsd(usdText), + }; +} diff --git a/packages/void/src/cli/project-security-check.ts b/packages/void/src/cli/project-security-check.ts new file mode 100644 index 000000000..10cbd8499 --- /dev/null +++ b/packages/void/src/cli/project-security-check.ts @@ -0,0 +1,408 @@ +/** + * `void project security check` (design doc 0095 M32): a security scan of this + * folder's code before it is deployed. + * + * git ls-files ─► filter (same rules as the platform) ─► secret-like: never sent + * └► lockfiles, binaries: never sent + * the rest, as it is on disk ─► tar + gzip ─► preview (model, notice, cost) ─► confirm + * ─► create (one presigned upload) ─► PUT to storage ─► start ─► poll ─► print + * + * Only git-tracked files leave the machine. The result is not saved as project + * findings; the platform keeps it 30 days. + */ +import { execFileSync } from 'node:child_process'; +import { createHash } from 'node:crypto'; +import { closeSync, lstatSync, openSync, readFileSync, readSync } from 'node:fs'; +import { gzipSync } from 'node:zlib'; +import { + isSecurityLocalTreePath, + SECURITY_LOCAL_CHECK_LIMITS, + securityInputFilter, + securityLocalTreeTar, + type SecurityLocalTreeFile, +} from '@void/platform/security-local-check'; +import { join } from 'pathslash'; +import type { PlatformClient } from './client.ts'; +import { DirectR2PutError, uploadAssetsToR2 } from './direct-r2-upload.ts'; +import type { SecurityCheckFinding, SecurityCheckView } from './security-api-types.ts'; + +/** Secret-like file names listed before the upload, at most. */ +const LISTED_SECRET_FILES = 5; +/** How often the CLI asks for the result, and for how long. */ +export const SECURITY_CHECK_POLL_MS = 5_000; +export const SECURITY_CHECK_WAIT_MS: number = 60 * 60_000; +const ENDED_WITH_RESULT = ['succeeded', 'incomplete']; + +export type SecurityLocalTree = { + files: Array; + bytes: number; + /** Secret-like files, never sent. */ + secret: Array; + /** Lockfiles, generated files, binaries and media, never sent. */ + skipped: number; +}; + +/** Tracked files under `root`, relative to it (git prints them so with `-z`, unquoted). */ +function listTrackedFiles(root: string): Array { + try { + return execFileSync('git', ['ls-files', '-z', '--cached', '--', '.'], { + cwd: root, + encoding: 'utf-8', + stdio: ['ignore', 'pipe', 'ignore'], + maxBuffer: 64 * 1024 * 1024, + }) + .split('\0') + .filter((path) => path.length > 0); + } catch { + throw new Error( + 'project: void project security check sends only git-tracked files, and this folder is not in a git repository. Run `git init` and `git add` your code first.', + ); + } +} + +const NUL_SNIFF_BYTES = 8192; + +function hasNul(data: Uint8Array): boolean { + const end = Math.min(data.length, NUL_SNIFF_BYTES); + for (let index = 0; index < end; index++) { + if (data[index] === 0) { + return true; + } + } + return false; +} + +/** The first bytes of a file, to tell a binary without reading all of it. */ +function readHead(full: string): Uint8Array { + const fd = openSync(full, 'r'); + try { + const head = new Uint8Array(NUL_SNIFF_BYTES); + return head.subarray(0, readSync(fd, head, 0, NUL_SNIFF_BYTES, 0)); + } finally { + closeSync(fd); + } +} + +const MB = 1024 * 1024; + +function tooManyFiles(count: number): Error { + const max = SECURITY_LOCAL_CHECK_LIMITS.maxFiles; + return new Error( + `project: A security check sends at most ${max.toLocaleString('en-US')} files, and this folder has ${count.toLocaleString('en-US')} or more. Run it from the app's folder.`, + ); +} + +function tooManyBytes(bytes: number): Error { + return new Error( + `project: A security check sends at most ${SECURITY_LOCAL_CHECK_LIMITS.maxBytes / MB} MB of code, and this folder has ${(bytes / MB).toFixed(1)} MB or more. Run it from the app's folder.`, + ); +} + +/** + * A tracked file to send: `null` when there is nothing to send (deleted, a submodule + * folder, a symlink, unreadable, a binary over the room left), its `size` when it is + * bigger than `room`, known from its size on disk before the file is read. + */ +function readTrackedFile(full: string, room: number): Uint8Array | null | { size: number } { + try { + const stat = lstatSync(full); + if (!stat.isFile()) { + return null; + } + if (stat.size > room) { + // A binary is never sent, so it does not count; anything else is too large. + return hasNul(readHead(full)) ? null : { size: stat.size }; + } + return readFileSync(full); + } catch { + return null; + } +} + +/** + * The git-tracked files under `root`, as they are on disk now (edits included), with + * the files the platform would never read left out. Throws past the check's limits, + * from the sizes on disk, before a file over them is read. + */ +export function collectSecurityLocalTree( + root: string, + listFiles: (root: string) => Array = listTrackedFiles, +): SecurityLocalTree { + const tree: SecurityLocalTree = { files: [], bytes: 0, secret: [], skipped: 0 }; + const limits = SECURITY_LOCAL_CHECK_LIMITS; + for (const path of listFiles(root)) { + const filter = securityInputFilter(path); + if (filter === 'secret') { + tree.secret.push(path); + continue; + } + if (filter === 'skipped' || !isSecurityLocalTreePath(path)) { + tree.skipped++; + continue; + } + const data = readTrackedFile(join(root, path), limits.maxBytes - tree.bytes); + if (data === null) { + tree.skipped++; + continue; + } + if (!(data instanceof Uint8Array)) { + throw tooManyBytes(tree.bytes + data.size); + } + if (hasNul(data)) { + tree.skipped++; + continue; + } + if (tree.files.length >= limits.maxFiles) { + throw tooManyFiles(tree.files.length + 1); + } + tree.files.push({ path, data }); + tree.bytes += data.length; + } + if (tree.bytes > limits.maxBytes) { + // A file grew between its size and its read. + throw tooManyBytes(tree.bytes); + } + return tree; +} + +export type SecurityPackedTree = { + archive: Buffer; + request: { files: number; bytes: number; size: number; md5: string }; +}; + +export function packSecurityLocalTree(tree: SecurityLocalTree): SecurityPackedTree { + const archive = gzipSync(securityLocalTreeTar(tree.files)); + return { + archive, + request: { + files: tree.files.length, + bytes: tree.bytes, + size: archive.length, + md5: createHash('md5').update(archive).digest('hex'), + }, + }; +} + +function size(bytes: number): string { + return bytes < 1024 * 1024 + ? `${Math.max(1, Math.round(bytes / 1024))} KB` + : `${(bytes / MB).toFixed(1)} MB`; +} + +function plural(count: number, word: string): string { + return `${count.toLocaleString('en-US')} ${word}${count === 1 ? '' : 's'}`; +} + +/** What is sent and what is not, before the question. */ +export function checkSummaryLines( + slug: string, + tree: SecurityLocalTree, + clean: (value: unknown) => string, +): Array { + const lines = [ + `Security check of ${slug}: ${plural(tree.files.length, 'git-tracked file')} (${size(tree.bytes)}) from this folder.`, + ]; + if (tree.secret.length > 0) { + const shown = tree.secret.slice(0, LISTED_SECRET_FILES).map(clean).join(', '); + const more = + tree.secret.length > LISTED_SECRET_FILES + ? `, and ${tree.secret.length - LISTED_SECRET_FILES} more` + : ''; + lines.push(` Not sent: ${plural(tree.secret.length, 'secret-like file')} (${shown}${more}).`); + } + if (tree.skipped > 0) { + lines.push( + ` Not sent: ${plural(tree.skipped, 'other file')} (lockfiles, generated files, binaries, media).`, + ); + } + lines.push(' Untracked files are not sent. Add them with git add to include them.'); + return lines; +} + +const SEVERITY_LABEL: Record = { + critical: 'CRITICAL', + high: 'HIGH', + medium: 'MEDIUM', + low: 'LOW', + informational: 'INFO', +}; + +function where(finding: SecurityCheckFinding, clean: (value: unknown) => string): string { + return `${clean(finding.file)}${finding.lineStart === null ? '' : `:${finding.lineStart}`}`; +} + +/** + * The ended check: one line per finding, confirmed first, then leads. `fresh`: the + * check just ran, so a missing result is a fault, not the 30-day limit. + */ +export function checkResultLines( + slug: string, + view: SecurityCheckView, + clean: (value: unknown) => string, + options: { fresh?: boolean } = {}, +): Array { + const { check, result } = view; + const head = [ + `${slug} · local check ${clean(check.id)}`, + ` ${clean(check.status)}${check.statusReason ? ` (${clean(check.statusReason)})` : ''}${check.coverageLabel ? ` · ${clean(check.coverageLabel)}` : ''} · ${plural(check.filesScanned, 'file')}${check.model ? ` · ${clean(check.model)}` : ''}`, + ]; + if (!ENDED_WITH_RESULT.includes(check.status)) { + return head; + } + if (result === null) { + return [ + ...head, + options.fresh + ? ' The result is missing.' + : ' The result is no longer stored (results are kept for 30 days).', + ]; + } + const confirmed = result.findings.filter((finding) => finding.verdict === 'confirmed'); + const leads = result.findings.filter((finding) => finding.verdict !== 'confirmed'); + const lines = [...head]; + if (result.findings.length === 0) { + lines.push(' No security issues found.'); + } else { + const bySeverity = new Map(); + for (const finding of confirmed) { + const key = finding.severity ?? 'informational'; + bySeverity.set(key, (bySeverity.get(key) ?? 0) + 1); + } + const counts = [...bySeverity.entries()] + .map(([severity, count]) => `${count} ${severity}`) + .join(', '); + lines.push( + ` ${plural(confirmed.length, 'finding')}${counts ? ` (${counts})` : ''} · ${plural(leads.length, 'lead')}`, + ); + for (const finding of confirmed) { + lines.push( + ` ${(SEVERITY_LABEL[finding.severity ?? ''] ?? 'INFO').padEnd(9)} ${clean(finding.title)}`, + ` ${' '.repeat(9)} ${where(finding, clean)}`, + ); + } + for (const finding of leads) { + lines.push( + ` ${'LEAD'.padEnd(9)} ${clean(finding.title)}`, + ` ${' '.repeat(9)} ${where(finding, clean)}`, + ); + } + if (result.capped) { + lines.push(` Showing ${result.findings.length} of ${result.total}.`); + } + } + if (check.status === 'incomplete') { + lines.push(' The check stopped early: only confirmed findings it reached are listed.'); + } + lines.push( + ' Not saved as project findings. The platform keeps this result for 30 days. Details: --json', + ); + return lines; +} + +/** Why an ended check has no result, and what to do. */ +export function checkFailureMessage( + view: SecurityCheckView, + clean: (value: unknown) => string, + options: { fresh?: boolean } = {}, +): string { + const { check } = view; + const reason = clean(check.statusReason ?? 'unknown'); + switch (check.status) { + case 'succeeded': + case 'incomplete': + return options.fresh + ? 'project: The check ended, but its result could not be read. Run it again.' + : 'project: The result of this check is no longer stored (results are kept for 30 days). Run a new check.'; + case 'refused': + return `project: The check was refused by ${clean(check.model ?? 'the scan model')} (category: ${clean(check.refusalCategory ?? 'unknown')}). Pick another model with void project security model , then run the check again.`; + case 'timed_out': + return 'project: The check timed out. Run it again, or from a smaller folder.'; + case 'skipped': + return reason === 'budget' + ? 'project: The check did not run: the monthly scan budget is used up.' + : `project: The check did not run (${reason}).`; + case 'canceled': + return reason === 'upload_replaced' + ? 'project: The check was replaced by a newer one before its code was uploaded.' + : `project: The check was canceled (${reason}).`; + default: + return check.failureCause === 'installation' + ? 'project: The check failed because of a platform problem. Your platform admin can see it in the admin panel.' + : `project: The check failed (${reason}). Run it again.`; + } +} + +export type SecurityCheckDeps = { + sleep?: (ms: number) => Promise; + now?: () => number; + fetch?: typeof fetch; + listFiles?: (root: string) => Array; +}; + +/** Upload, start, and return the check id. */ +export async function sendSecurityLocalCheck( + client: PlatformClient, + projectId: string, + packed: SecurityPackedTree, + deps: SecurityCheckDeps = {}, +): Promise { + const created = await client.createProjectSecurityCheck(projectId, packed.request); + try { + await uploadAssetsToR2( + [ + { + path: 'security check archive', + hash: packed.request.md5, + body: packed.archive, + url: created.upload.url, + headers: created.upload.headers, + }, + ], + undefined, + deps.fetch ?? fetch, + ); + } catch (error) { + // The upload is signed `If-None-Match: *`: a 412 on a retry means an earlier PUT + // landed and only its reply was lost. Start checks the archive is there. + if (!(error instanceof DirectR2PutError && error.status === 412)) { + throw error; + } + } + await client.startProjectSecurityCheck(projectId, created.checkId); + return created.checkId; +} + +/** + * Polls until the check ends or the wait is over. `onState` hears each new state + * (queued, running) once. `null` when the wait ran out. + */ +export async function waitForSecurityLocalCheck( + client: PlatformClient, + projectId: string, + checkId: string, + onState: (status: string) => void, + deps: SecurityCheckDeps = {}, +): Promise { + const sleep = deps.sleep ?? ((ms: number) => new Promise((done) => setTimeout(done, ms))); + const now = deps.now ?? Date.now; + const until = now() + SECURITY_CHECK_WAIT_MS; + let last = ''; + for (;;) { + const view = await client.getProjectSecurityCheck(projectId, checkId); + if (view.ended) { + return view; + } + if (view.check.status !== last) { + last = view.check.status; + onState(last); + } + if (now() >= until) { + return null; + } + await sleep(SECURITY_CHECK_POLL_MS); + } +} + +export function checkEndedWithResult(view: SecurityCheckView): boolean { + return ENDED_WITH_RESULT.includes(view.check.status) && view.result !== null; +} diff --git a/packages/void/src/cli/project-security.ts b/packages/void/src/cli/project-security.ts new file mode 100644 index 000000000..5d3bd11b8 --- /dev/null +++ b/packages/void/src/cli/project-security.ts @@ -0,0 +1,1028 @@ +import { stripVTControlCharacters } from 'node:util'; +import { confirm, isCancel } from '@voidzero-dev/vite-plus-prompts'; +import { isCI } from 'ci-info'; +import { getToken, openBrowser } from './auth.ts'; +import { PlatformApiError, PlatformClient } from './client.ts'; +import type { ProjectSecurityArgs } from './project-security-args.ts'; +import { + checkEndedWithResult, + checkFailureMessage, + checkResultLines, + checkSummaryLines, + collectSecurityLocalTree, + packSecurityLocalTree, + sendSecurityLocalCheck, + waitForSecurityLocalCheck, + type SecurityCheckDeps, +} from './project-security-check.ts'; +import { readProjectConfig } from './project.ts'; +import { getRequestedProjectSlug, requireProjectBySlug } from './resolve-project.ts'; +import type { + ProjectSecurityStatus, + SecurityFinding, + SecurityFindingEvent, + SecurityPublicRequest, + SecurityRescanPreview, + SecurityScanSummary, +} from './security-api-types.ts'; +import { sarifToolVersion, securityFindingsSarif } from './security-sarif.ts'; + +type Args = ProjectSecurityArgs; + +function scrub(value: string, keepNewline: boolean): string { + let out = ''; + for (const char of stripVTControlCharacters(value)) { + const code = char.codePointAt(0)!; + const control = code < 0x20 || (code >= 0x7f && code <= 0x9f); + out += control && !(keepNewline && char === '\n') ? ' ' : char; + } + return out; +} + +/** Text from a model or a user: no escape sequences, one line. */ +export function cleanLine(value: unknown): string { + return scrub(String(value ?? ''), false); +} + +/** Text from a model that may span lines: keeps line breaks, drops every other control. */ +export function cleanBlock(value: unknown): string { + const text = typeof value === 'string' ? value : JSON.stringify(value, null, 2); + return scrub(text ?? '', true); +} + +export const usd = (value: number) => `$${value.toFixed(2)}`; + +export function day(iso: string | null | undefined): string { + const time = iso ? Date.parse(iso) : Number.NaN; + return Number.isNaN(time) + ? '-' + : new Date(time).toLocaleDateString('en-US', { + month: 'short', + day: 'numeric', + timeZone: 'UTC', + }); +} + +function stamp(iso: string | null | undefined): string { + const time = iso ? Date.parse(iso) : Number.NaN; + return Number.isNaN(time) + ? '-' + : `${day(iso)}, ${new Date(time).toISOString().slice(11, 16)} UTC`; +} + +/** Where a platform limit comes from (`ceilingSource`); older platforms send none. */ +function platformLimitLabel(source: 'project' | 'plan' | 'default' | null | undefined): string { + if (source === 'project') { + return 'platform limit for this project'; + } + if (source === 'plan') { + return 'platform limit for this plan'; + } + return 'platform limit for every project'; +} + +function duration(scan: SecurityScanSummary): string | null { + const start = scan.startedAt ? Date.parse(scan.startedAt) : Number.NaN; + const end = scan.finishedAt ? Date.parse(scan.finishedAt) : Number.NaN; + if (Number.isNaN(start) || Number.isNaN(end) || end < start) { + return null; + } + const minutes = Math.round((end - start) / 60_000); + return minutes < 1 + ? '<1 min' + : minutes < 60 + ? `${minutes} min` + : `${Math.floor(minutes / 60)} h ${minutes % 60} min`; +} + +const row = (label: string, text: string) => ` ${label.padEnd(10)} ${text}`; +const cont = (text: string) => ` ${' '.repeat(10)} ${text}`; + +/** Spec §11.4 status copy for the last scan; `null` when the scan needs no explanation. */ +export function scanStatusCopy(status: ProjectSecurityStatus): string | null { + const { lastScan, lastSuccessfulScan, budget } = status; + if (!lastScan) { + return null; + } + const since = lastSuccessfulScan?.deploymentId ?? null; + const next = since + ? `The next scan covers changes since ${since}.` + : 'The next scan reviews the whole app.'; + const reason = cleanLine(lastScan.statusReason ?? 'unknown'); + switch (lastScan.status) { + case 'queued': + case 'running': + case 'pending_input': + return 'Last security scan still running. Results show here when it ends.'; + case 'failed': + return lastScan.failureCause === 'installation' + ? 'Not scanned: a platform problem (your platform admin can see it in the admin panel).' + : `Last scan failed (${reason}). ${next}`; + case 'timed_out': + return `Last scan failed (timed out). ${next}`; + case 'refused': + return `Refused by ${cleanLine(lastScan.model ?? 'the scan model')} (category: ${cleanLine( + lastScan.refusalCategory ?? 'unknown', + )}). The next deploy is scanned again. To switch model: void project security model `; + case 'incomplete': + return reason.startsWith('budget') + ? `Last scan stopped early: the monthly scan budget ran out. Confirmed findings it found are kept. ${next}` + : `Last scan was partial (${reason}). Confirmed findings it found are kept. ${next}`; + case 'superseded': + return 'Replaced by the scan of a newer deploy.'; + case 'canceled': + return `Canceled by a platform admin. ${next}`; + case 'skipped': + if (reason === 'budget') { + if (budget && budget.capSource === 'own' && budget.capUsd !== null) { + return `Not scanned: this project's monthly scan budget is used up (${usd(budget.spentUsd)} of ${usd(budget.capUsd)}). Resets ${day(budget.resetsAt)}.`; + } + return "Not scanned: the platform's monthly scan budget is used up. Your platform admin can raise it."; + } + if (reason === 'backlog') { + return `Not scanned: the scan queue was full for 24 h. ${next}`; + } + if (reason === 'protected') { + return 'Not scanned: this project is protected by Zero Trust and the platform scans public projects only.'; + } + if (reason === 'project_policy') { + return 'Not scanned: a platform admin turned scans off for this project.'; + } + return `Not scanned (${reason}).`; + default: + return null; + } +} + +/** Spec §11.4 public request copy, with the command that moves it on. */ +export function publicRequestLines( + slug: string, + request: SecurityPublicRequest, + status: Pick, +): Array { + const ids = request.blockers.ids.map(cleanLine).join(', '); + const target = cleanLine(request.targetDeploymentId); + const bypass = 'void project zero-trust bypass --reason "…"'; + const reason = request.heldReason; + const lines: Array = []; + switch (request.state) { + case 'waiting_scan': + lines.push( + status.backlogFiles > 0 + ? `Scanning in parts: ${status.backlogFiles} files left. ${slug} stays protected until every file is scanned.` + : `Waiting for a security scan of ${target} before ${slug} goes public. It stays protected by Zero Trust until the scan passes.`, + ); + break; + case 'held_findings': { + const count = request.blockers.ids.length; + lines.push( + `Stays protected: ${count} urgent ${count === 1 ? 'finding' : 'findings'} must be resolved before Zero Trust is turned off (${ids}). Resolve each one as fixed (then deploy the fix), or as false-positive or accepted-risk with a comment; then the request unlocks.`, + '→ void project security list --urgent', + ); + break; + } + case 'needs_deploy': + lines.push( + reason === 'unproven_fix' + ? `Stays protected: ${ids} ${request.blockers.ids.length === 1 ? 'was' : 'were'} resolved as fixed. Deploy the fix (if it is already live, deploy again); ${slug} goes public when the scan of that deploy is clean.` + : `Stays protected: the live deployment ${target} cannot be scanned (its code was not kept for scanning). Deploy again; that deploy is scanned before ${slug} goes public.`, + `Or bypass the scan: ${bypass}`, + ); + break; + case 'held_no_result': { + if (reason === 'failed_installation') { + lines.push( + `Stays protected: the security scan could not run (a platform problem; your platform admin can see it). A project admin or owner can bypass the scan: ${bypass}`, + ); + } else if (reason === 'skipped_budget') { + const resets = status.budget ? ` Resets ${day(status.budget.resetsAt)}.` : ''; + lines.push( + `Stays protected: the monthly scan budget is used up, so the scan could not run.${resets} Ask your platform admin, or bypass the scan: ${bypass}`, + ); + } else { + const cause = + reason === 'refused' + ? 'refused' + : reason === 'timed_out' + ? 'timed out' + : reason === 'findings_capped' + ? 'it hit the findings limit, so more findings may be hidden' + : reason === 'failed_project' + ? 'the scan of this project failed' + : cleanLine((reason ?? 'no result').split('_').join(' ')); + lines.push( + `Stays protected: the security scan did not finish (${cause}). Ask again with void project zero-trust public, deploy again, or bypass the scan: ${bypass}`, + ); + if (reason === 'refused') { + lines.push('To switch model: void project security model , then ask again.'); + } + } + break; + } + case 'passed': + lines.push( + `Security scan passed (nothing urgent found). Zero Trust is being turned off for ${slug}.`, + ); + break; + case 'bypassed': + lines.push( + 'Public without a clean scan: a project admin bypassed the scan. Your platform admins were told.', + ); + break; + default: + lines.push(`Public request canceled. ${slug} stays protected.`); + } + return lines; +} + +export function formatStatus(slug: string, status: ProjectSecurityStatus): Array { + const lines = [`${slug} · security`]; + const { urgent, policy, model, budget, lastScan, lastSuccessfulScan, counts } = status; + if (urgent.count === 0) { + lines.push(row('Urgent', 'none open')); + } else { + const parts = [ + urgent.counts.critical ? `${urgent.counts.critical} critical` : '', + urgent.counts.high ? `${urgent.counts.high} high` : '', + ].filter(Boolean); + lines.push( + row( + 'Urgent', + `${urgent.count} open (${parts.join(', ')}) · oldest ${day(urgent.oldestFirstSeenAt)} → void project security list --urgent`, + ), + ); + } + const reason = cleanLine(policy.reason); + if (policy.mode === 'disabled') { + lines.push(row('Policy', reason)); + } else if (policy.applies) { + lines.push( + row( + 'Policy', + `applies: ${reason}${policy.mode === 'public' ? ' (Public projects only)' : ''}`, + ), + ); + } else { + lines.push(row('Policy', `does not apply: ${reason}`)); + } + const source = + model.source === 'project' + ? "your project's pick" + : model.source === 'default' + ? 'platform default' + : model.source === 'fallback' + ? 'fallback: the model you asked for cannot run now' + : 'no model can run now'; + lines.push(row('Model', `${cleanLine(model.id ?? 'none')} (${source})`)); + if (model.thirdParty && model.id) { + lines.push( + cont( + 'Run by a third-party provider, not Cloudflare. Its usage policy applies and it may refuse.', + ), + ); + } + if (model.pendingDefault) { + lines.push( + cont( + `The platform default ${cleanLine(model.pendingDefault)} waits for the provider notice: void project security model --default --accept-provider-notice`, + ), + ); + } + if (budget) { + const origin = budget.capSource === 'own' ? 'project cap' : 'platform limit'; + lines.push( + row( + 'Budget', + budget.capUsd === null + ? `${usd(budget.spentUsd)} this month · no cap` + : `${usd(budget.spentUsd)} of ${usd(budget.capUsd)} this month (${origin}) · resets ${day(budget.resetsAt)}`, + ), + ); + } + if (!lastScan) { + lines.push( + row( + 'Last scan', + 'none yet. The first scan runs after your next deploy and reviews the whole app.', + ), + ); + } else { + const parts = [ + cleanLine(lastScan.status + (lastScan.statusReason ? ` (${lastScan.statusReason})` : '')), + lastScan.deploymentId ? cleanLine(lastScan.deploymentId) : null, + duration(lastScan), + lastScan.coverageLabel ? cleanLine(lastScan.coverageLabel) : null, + ].filter(Boolean); + lines.push(row('Last scan', parts.join(' · '))); + } + if (lastSuccessfulScan?.deploymentId) { + const since = status.deploysSinceLastSuccess; + lines.push( + row( + 'Last good', + `${cleanLine(lastSuccessfulScan.deploymentId)}${since === null ? '' : ` (${since} ${since === 1 ? 'deploy' : 'deploys'} ago)`}`, + ), + ); + } + if (status.backlogFiles > 0) { + lines.push(row('Backlog', `${status.backlogFiles} files not scanned yet`)); + } + const copy = scanStatusCopy(status); + if (copy) { + lines.push(row('Note', copy)); + } + const other = + (counts.open.medium ?? 0) + (counts.open.low ?? 0) + (counts.open.informational ?? 0); + lines.push(row('Open', `${counts.urgent} urgent · ${other} other · ${counts.leads} leads`)); + if (status.publicRequest) { + const [first = '', ...rest] = publicRequestLines(slug, status.publicRequest, status); + lines.push(row('Public', first), ...rest.map(cont)); + } + return lines; +} + +function findingState(finding: SecurityFinding): string { + if (finding.state === 'resolved') { + return finding.resolution + ? `resolved (${cleanLine(finding.resolution).split('_').join('-')})` + : 'resolved'; + } + return finding.verdict === 'needs_validation' ? 'lead' : 'open'; +} + +export function formatFindingList(findings: Array): Array { + return findings.map((finding) => { + const place = finding.file + ? `${cleanLine(finding.file)}${finding.line ? `:${finding.line}` : ''}` + : ''; + return [ + cleanLine(finding.id).padEnd(7), + cleanLine(finding.severity ?? '-').padEnd(14), + findingState(finding).padEnd(26), + finding.title === undefined ? '' : cleanLine(finding.title), + place ? `(${place})` : '', + ] + .join(' ') + .trimEnd(); + }); +} + +function indent(text: string): Array { + return cleanBlock(text) + .split('\n') + .map((line) => ` ${line}`); +} + +export function formatFinding( + finding: SecurityFinding, + events: Array | undefined, +): Array { + const lines = [ + `${cleanLine(finding.id)} ${cleanLine(finding.severity ?? '-')} ${findingState(finding)}${finding.urgent ? ' (urgent)' : ''}`, + ]; + if (finding.title === undefined) { + lines.push( + ' Readers see the id, severity and state of open findings. Ask a project collaborator for the details.', + ); + return lines; + } + lines.push(` ${cleanLine(finding.title)}`); + const meta = [ + finding.file ? `${cleanLine(finding.file)}${finding.line ? `:${finding.line}` : ''}` : null, + finding.category ? cleanLine(finding.category) : null, + finding.cwe ? cleanLine(finding.cwe) : null, + finding.verdictSource === 'runtime' ? 'confirmed (runtime)' : null, + finding.confidence !== undefined && finding.confidence !== null + ? `confidence ${cleanLine(finding.confidence)}` + : null, + finding.deploymentId ? `first seen in ${cleanLine(finding.deploymentId)}` : null, + finding.firstSeenAt ? day(finding.firstSeenAt) : null, + ].filter(Boolean); + if (meta.length > 0) { + lines.push(` ${meta.join(' · ')}`); + } + if (finding.severityEdited) { + lines.push( + ` Severity set by a person${finding.scanSeverity ? ` (scans said ${cleanLine(finding.scanSeverity)})` : ''}.`, + ); + } + if (finding.notSeenInLatest) { + lines.push(' Not seen in the latest scan.'); + } + if (finding.possibleDuplicateOf) { + lines.push(` Possible duplicate of ${cleanLine(finding.possibleDuplicateOf.id)}.`); + } + for (const [label, value] of [ + ['Trace', finding.trace], + ['Evidence', finding.evidence], + [ + 'Runtime proof', + finding.runtimeProof + ? `${cleanLine(finding.runtimeProof.method)} ${cleanLine(finding.runtimeProof.path)} answered ${finding.runtimeProof.status} on a throwaway copy` + : null, + ], + ['Conditions', finding.conditions], + ['Suggested fix', finding.fix], + ] as const) { + if (value !== null && value !== undefined && value !== '') { + lines.push( + '', + ` ${label}`, + ...indent(typeof value === 'string' ? value : JSON.stringify(value, null, 2)), + ); + } + } + if (events && events.length > 0) { + lines.push('', ' History'); + for (const event of events) { + const who = event.actor ?? event.actorKind; + lines.push( + ` ${stamp(event.createdAt)} · ${cleanLine(event.action)}${event.resolution ? ` (${cleanLine(event.resolution).split('_').join('-')})` : ''}${event.severityFrom && event.severityTo ? ` (${cleanLine(event.severityFrom)} → ${cleanLine(event.severityTo)})` : ''} · ${cleanLine(who)}${event.actorRole ? ` (${cleanLine(event.actorRole)})` : ''}`, + ); + if (event.comment) { + lines.push(...indent(event.comment).map((line) => ` ${line}`)); + } + } + } + return lines; +} + +export function formatScans(scans: Array): Array { + return scans.map((scan) => + [ + day(scan.createdAt).padEnd(7), + cleanLine(scan.status + (scan.statusReason ? ` (${scan.statusReason})` : '')).padEnd(24), + cleanLine(scan.deploymentId ?? '-').padEnd(12), + cleanLine(scan.trigger).padEnd(9), + duration(scan) ?? '-', + scan.meteredUsd === null ? '' : usd(scan.meteredUsd), + scan.model ? cleanLine(scan.model) : '', + ] + .join(' ') + .trimEnd(), + ); +} + +async function resolveTarget(root: string, args: Args) { + const token = getToken(root); + if (!token) { + throw new Error('project: Not logged in. Run `void account login` first.'); + } + const client = new PlatformClient(token, { root }); + const requestedSlug = getRequestedProjectSlug({ projectSlug: args.projectSlug }); + if (requestedSlug) { + const project = await requireProjectBySlug(client, requestedSlug); + return { client, projectId: project.projectId, slug: project.slug }; + } + const linked = readProjectConfig(root); + if (!linked) { + throw new Error('project: No linked project. Pass --project or set VOID_PROJECT.'); + } + return { client, projectId: linked.projectId, slug: linked.slug }; +} + +function print(args: Args, value: unknown, lines: Array): void { + if (args.json) { + console.log(JSON.stringify(value)); + } else { + console.log(['', ...lines, ''].join('\n')); + } +} + +function reasonLabel(reason: string | null): string { + return (reason ?? 'resolved').split('_').join(' '); +} + +function noticeOf(error: unknown): { version: number; notice: Array } | null { + if (!(error instanceof PlatformApiError) || error.status !== 422) { + return null; + } + try { + const body = JSON.parse(error.body) as { error?: unknown; version?: unknown; notice?: unknown }; + if (body.error !== 'provider notice not accepted' || typeof body.version !== 'number') { + return null; + } + const notice = Array.isArray(body.notice) + ? body.notice.filter((x): x is string => typeof x === 'string') + : []; + return { version: body.version, notice }; + } catch { + return null; + } +} + +function severityChangeLine( + id: string, + level: string, + result: Readonly<{ changed: boolean; severityEdited: boolean; scanSeverity: string | null }>, +): string { + if (!result.changed) { + return result.severityEdited + ? `${id} is already ${level}. Nothing changed.` + : `${id} already uses the scan severity (${level}). Nothing changed.`; + } + if (!result.severityEdited) { + return `✓ ${id} uses the scan severity again: ${level}.`; + } + const scans = result.scanSeverity ? cleanLine(result.scanSeverity) : null; + return `✓ ${id} severity set to ${level}${scans && scans !== level ? ` (scans said ${scans})` : ''}. Later scans keep it.`; +} + +export type ProjectSecurityDeps = { + openUrl?: (url: string) => void; + interactive?: boolean; + confirm?: (message: string) => Promise; + /** M32 local check: poll timing, the upload fetch, the file list. */ + check?: SecurityCheckDeps; +}; + +/** The rescan cost confirm (spec §13.4 rescan rule): what it runs and what it can cost. */ +export function rescanConfirmLines(preview: SecurityRescanPreview): Array { + const id = cleanLine(preview.deploymentId); + const model = cleanLine(preview.model ?? 'the scan model'); + const cost = + typeof preview.worstCaseUsd === 'number' + ? ` It can cost up to ${usd(preview.worstCaseUsd)}.` + : ''; + const whole = preview.clientAssets + ? 'This reviews the whole app, and the sources of its client bundles.' + : 'This reviews the whole app.'; + const lines = [ + preview.alreadyScanned + ? `Live deployment ${id} was already scanned. Run a full scan with ${model}? ${whole}${cost}` + : `Run a full scan of live deployment ${id} with ${model}? ${whole}${cost}`, + ]; + const budget = preview.budget; + lines.push( + budget && budget.capUsd !== null + ? `Monthly caps apply: ${usd(budget.spentUsd)} of ${usd(budget.capUsd)} spent this month.` + : 'Monthly caps apply when the scan starts.', + ); + return lines; +} + +export async function runProjectSecurityCommand( + root: string, + args: Args, + deps: ProjectSecurityDeps = {}, +): Promise { + const { client, projectId, slug } = await resolveTarget(root, args); + + if (args.action === 'status') { + const status = await client.getProjectSecurity(projectId); + print(args, status, formatStatus(slug, status)); + return; + } + + if (args.action === 'list') { + const found: Array = []; + let cursor: string | null = null; + let more = false; + for (;;) { + const page = await client.listProjectSecurityFindings(projectId, { + state: args.state, + urgent: args.urgent, + severity: args.severity, + limit: 100, + cursor, + }); + found.push(...page.findings); + cursor = page.nextCursor; + if (!cursor) { + break; + } + if (found.length >= 500) { + more = true; + break; + } + } + const shown = args.leads + ? found + : found.filter((finding) => finding.verdict !== 'needs_validation'); + const hidden = found.length - shown.length; + if (args.format === 'sarif') { + // stdout holds the SARIF log only; what it leaves out goes to stderr. + console.log( + JSON.stringify(securityFindingsSarif(shown, { version: sarifToolVersion() }), null, 2), + ); + if (hidden > 0) { + console.error( + `${hidden} ${hidden === 1 ? 'lead is' : 'leads are'} left out. Add them with --leads.`, + ); + } + if (more) { + console.error( + 'Only the first 500 findings are in the file. Narrow it with --severity or --urgent.', + ); + } + return; + } + const lines = shown.length === 0 ? ['No findings.'] : formatFindingList(shown); + if (hidden > 0) { + lines.push( + `${hidden} ${hidden === 1 ? 'lead is' : 'leads are'} hidden. Show them with --leads.`, + ); + } + if (more) { + lines.push('Showing the first 500. Narrow the list with --severity or --urgent.'); + } + print(args, { findings: shown, more }, lines); + return; + } + + if (args.action === 'show') { + const detail = await client.getProjectSecurityFinding(projectId, args.id); + print(args, detail, formatFinding(detail.finding, detail.events)); + return; + } + + if (args.action === 'comment') { + const result = await client.commentOnProjectSecurityFinding(projectId, args.id, args.text); + print(args, result, [`✓ Comment added to ${cleanLine(result.id)}.`]); + return; + } + + if (args.action === 'reopen') { + const current = await client.getProjectSecurityFinding(projectId, args.id); + const result = await client.reopenProjectSecurityFinding(projectId, args.id, { + comment: args.comment, + expectedRevision: current.finding.revision, + }); + print(args, result, [`✓ ${cleanLine(result.id)} reopened.`]); + return; + } + + if (args.action === 'severity') { + const current = await client.getProjectSecurityFinding(projectId, args.id); + const result = await client.editProjectSecurityFindingSeverity(projectId, args.id, { + severity: args.severity, + comment: args.comment, + expectedRevision: current.finding.revision, + }); + const id = cleanLine(result.id); + const level = cleanLine(result.severity ?? '-'); + const lines = [severityChangeLine(id, level, result)]; + if (result.publicRequest) { + let status: ProjectSecurityStatus | null = null; + try { + status = await client.getProjectSecurity(projectId); + } catch { + // The line below is extra; the edit already happened. + } + const [first = '', ...rest] = publicRequestLines( + slug, + result.publicRequest, + status ?? { backlogFiles: 0, budget: null }, + ); + lines.push(` Public request: ${first}`, ...rest.map((line) => ` ${line}`)); + } + print(args, result, lines); + return; + } + + if (args.action === 'resolve') { + const results: Array> = []; + const lines: Array = []; + let lastRequest: SecurityPublicRequest | undefined; + let failed = 0; + for (const id of args.ids) { + try { + const current = await client.getProjectSecurityFinding(projectId, id); + const result = await client.resolveProjectSecurityFinding(projectId, id, { + reason: args.reason, + comment: args.comment, + expectedRevision: current.finding.revision, + }); + results.push(result); + lastRequest = result.publicRequest ?? lastRequest; + lines.push( + `✓ ${cleanLine(result.id)} resolved (${reasonLabel(result.resolution)}).${args.reason === 'fixed' ? ' The next scan will check that the fix holds.' : ''}`, + ); + } catch (error) { + failed++; + const message = error instanceof Error ? error.message : String(error); + results.push({ ok: false, id, error: message }); + lines.push(`✖ ${id}: ${cleanLine(message)}`); + } + } + if (failed < args.ids.length) { + let status: ProjectSecurityStatus | null = null; + try { + status = await client.getProjectSecurity(projectId); + } catch { + // The lines below are extra; the resolves already happened. + } + const open = status?.urgent.findings ?? []; + const describe = (id: string) => { + const found = open.find((finding) => finding.id === id); + return found?.severity ? `${id} (${cleanLine(found.severity)})` : id; + }; + if (lastRequest?.state === 'held_findings') { + lines.push( + ` Public request: still held by ${lastRequest.blockers.ids.map(describe).join(', ')}.`, + ); + } else if (lastRequest?.state === 'needs_deploy') { + lines.push( + ` Public request: deploy the fix. ${slug} goes public when the scan of that deploy is clean.`, + ); + } else if (lastRequest?.state === 'waiting_scan') { + lines.push(' Public request: waiting for a security scan.'); + } else if (status && status.urgent.count > 0) { + lines.push( + ` Still open and urgent: ${open.map((finding) => describe(finding.id)).join(', ')}${status.urgent.more > 0 ? `, and ${status.urgent.more} more` : ''}.`, + ); + } + } + print(args, { results }, lines); + if (failed > 0) { + throw new Error(`project: ${failed} of ${args.ids.length} findings were not resolved.`); + } + return; + } + + if (args.action === 'scans') { + const page = await client.listProjectSecurityScans(projectId, args.limit); + const lines = page.scans.length === 0 ? ['No scans yet.'] : formatScans(page.scans); + if (page.nextCursor) { + lines.push('Older scans exist. Raise --limit (up to 100) to see more.'); + } + print(args, page, lines); + return; + } + + if (args.action === 'scan') { + const scanOptions = { clientAssets: args.clientAssets }; + const preview = await client.previewProjectSecurityScan(projectId, scanOptions); + if (args.clientAssets && preview.clientAssets !== true) { + throw new Error( + 'project: This platform cannot read client bundle sources yet. Run the scan without --client-assets, or ask your platform admin to upgrade.', + ); + } + if (!args.yes) { + const interactive = deps.interactive ?? (Boolean(process.stdout.isTTY) && !isCI); + if (args.json || !interactive) { + throw new Error('project: Add --yes to start the scan without a prompt.'); + } + const [question, ...rest] = rescanConfirmLines(preview); + console.log(['', ...rest].join('\n')); + const ask = + deps.confirm ?? + (async (message: string) => { + const answer = await confirm({ message, initialValue: false }); + return !isCancel(answer) && answer; + }); + if (!(await ask(question!))) { + console.log('Nothing was queued.'); + return; + } + } + const queued = await client.startProjectSecurityScan(projectId, scanOptions); + print(args, queued, [ + `✓ Full scan ${cleanLine(queued.scanId)} of ${cleanLine(queued.deploymentId)} queued${queued.clientAssets ? ', with client bundle sources' : ''}.`, + ' It waits its turn like any scan. See the result: void project security status', + ]); + return; + } + + if (args.action === 'check') { + await runSecurityCheck(root, client, projectId, slug, args, deps); + return; + } + + if (args.action === 'model') { + if (args.change === 'show') { + const { model } = await client.getProjectSecurity(projectId); + const lines = [ + `${slug} · security model`, + row('Model', `${cleanLine(model.id ?? 'none')}${model.source ? ` (${model.source})` : ''}`), + row('Asked for', cleanLine(model.requested)), + row( + 'Notice', + model.noticeAccepted ? 'provider notice accepted' : 'provider notice not accepted', + ), + 'Change: void project security model or void project security model --default', + ]; + print(args, { model }, lines); + return; + } + const target = args.change === 'default' ? null : args.model; + const lines: Array = []; + let result; + if (args.acceptNotice) { + try { + // A version the platform does not know is refused with the current version and notice. + result = await client.setProjectSecurityModel(projectId, { + model: target, + acceptProviderNoticeVersion: 0, + }); + } catch (error) { + const notice = noticeOf(error); + if (!notice) { + throw error; + } + lines.push(...notice.notice.map((line) => cleanLine(line)), ''); + result = await client.setProjectSecurityModel(projectId, { + model: target, + acceptProviderNoticeVersion: notice.version, + }); + } + } else { + try { + result = await client.setProjectSecurityModel(projectId, { model: target }); + } catch (error) { + const notice = noticeOf(error); + if (notice && !args.json) { + console.log(['', ...notice.notice.map((line) => cleanLine(line)), ''].join('\n')); + } + throw error; + } + } + const used = result.model?.id; + lines.push( + args.change === 'default' + ? `✓ ${slug} uses the platform default model${used ? ` (${cleanLine(used)})` : ''}.` + : `✓ ${slug} scans now use ${cleanLine(args.model)}.`, + ); + if (result.model?.source === 'fallback') { + lines.push( + ' The next scan still falls back to a Cloudflare model until the provider notice is accepted on the platform.', + ); + } + print(args, result, lines); + return; + } + + if (args.action === 'budget') { + if (args.change === 'show') { + const { budget } = await client.getProjectSecurity(projectId); + if (!budget) { + print(args, { budget: null }, [ + 'Only project members who can deploy can see the scan budget.', + ]); + return; + } + const month = new Date(`${budget.month}-01T00:00:00Z`).toLocaleDateString('en-US', { + month: 'long', + timeZone: 'UTC', + }); + const cap = + budget.capUsd === null + ? 'no cap' + : `${usd(budget.capUsd)} / month (${budget.capSource === 'own' ? 'set for this project' : platformLimitLabel(budget.ceilingSource)})`; + print(args, { budget }, [ + `${slug} · scan budget (${month}, UTC; resets ${day(budget.resetsAt)})`, + row('Cap', cap), + row('Spent', `${usd(budget.spentUsd)} metered this month`), + ` Change: void project security budget --usd N (project admin; ${budget.ceilingUsd === null ? 'any amount' : `$0–${usd(budget.ceilingUsd)}`})`, + ]); + return; + } + const result = await client.setProjectSecurityBudget( + projectId, + args.change === 'off' ? null : args.usd, + ); + const budget = result.budget; + if (args.change === 'set') { + print(args, result, [ + `✓ ${slug} scan budget set to ${usd(args.usd)} / month. Spent so far: ${usd(budget.spentUsd)}.`, + ]); + } else { + print(args, result, [ + budget.capUsd === null + ? `✓ ${slug}'s own cap cleared. No cap applies.` + : `✓ ${slug}'s own cap cleared. The platform cap for each project still applies: ${usd(budget.capUsd)} / month.`, + ]); + } + return; + } + + if (args.action === 'open') { + const link = await client.createProjectSecurityPageLink(projectId); + let safe = false; + try { + const url = new URL(link.url); + safe = + (url.protocol === 'https:' || url.protocol === 'http:') && + !url.username && + !url.password && + url.pathname.startsWith('/security/projects/'); + } catch { + safe = false; + } + if (!safe) { + throw new Error('project: The platform returned an unexpected security page link.'); + } + print(args, link, [ + link.url, + `The link works for 15 minutes (until ${stamp(link.expiresAt)}).`, + ]); + const interactive = deps.interactive ?? (Boolean(process.stdout.isTTY) && !isCI); + if (interactive && !args.json) { + (deps.openUrl ?? openBrowser)(link.url); + } + return; + } + + if (args.action === '') { + return; + } +} + +async function askYesNo(deps: ProjectSecurityDeps, message: string): Promise { + const ask = + deps.confirm ?? + (async (text: string) => { + const answer = await confirm({ message: text, initialValue: false }); + return !isCancel(answer) && answer; + }); + return ask(message); +} + +/** + * `void project security check []` (M32). Without an id: pack this folder's + * git-tracked files, say what is sent and to which model, confirm, upload, wait. + * With an id: show (and wait for) that check. + */ +async function runSecurityCheck( + root: string, + client: PlatformClient, + projectId: string, + slug: string, + args: Extract, + deps: ProjectSecurityDeps, +): Promise { + const log = (lines: Array) => { + if (!args.json) { + console.log(lines.join('\n')); + } + }; + let checkId = args.checkId; + const fresh = checkId === ''; + if (fresh) { + const interactive = deps.interactive ?? (Boolean(process.stdout.isTTY) && !isCI); + if (!args.yes && (args.json || !interactive)) { + throw new Error('project: Add --yes to send the code without a prompt.'); + } + const tree = collectSecurityLocalTree(root, deps.check?.listFiles); + if (tree.files.length === 0) { + throw new Error( + 'project: No git-tracked code to check in this folder. Add your code with git add first.', + ); + } + const packed = packSecurityLocalTree(tree); + const preview = await client.previewProjectSecurityCheck(projectId, packed.request); + const model = cleanLine(preview.model); + const lines = ['', ...checkSummaryLines(slug, tree, cleanLine)]; + if (preview.notice) { + lines.push('', ...preview.notice.map((line) => ` ${cleanLine(line)}`)); + } + lines.push( + '', + ` The code goes to the platform and is reviewed by ${model}.${typeof preview.worstCaseUsd === 'number' ? ` It can cost up to ${usd(preview.worstCaseUsd)}; monthly caps apply.` : ' Monthly caps apply.'}`, + ' The result is not saved as project findings. The platform keeps it for 30 days.', + ); + if (!args.yes) { + log(lines); + if (!(await askYesNo(deps, `Send these files for a security check with ${model}?`))) { + console.log('Nothing was sent.'); + return; + } + } else { + log(lines); + } + checkId = await sendSecurityLocalCheck(client, projectId, packed, deps.check); + log([`✓ Check ${cleanLine(checkId)} queued. It waits its turn like any scan.`]); + } else { + // An earlier check whose start never came (Ctrl-C, a lost reply): start it now. + // The platform checks the upload is there, and a second start only reads the state. + const earlier = await client.getProjectSecurityCheck(projectId, checkId); + if (earlier.check.status === 'pending_input') { + await client.startProjectSecurityCheck(projectId, checkId); + } + } + if (!args.wait) { + const view = await client.getProjectSecurityCheck(projectId, checkId); + print(args, view, [ + ` Check ${cleanLine(checkId)}: ${cleanLine(view.check.status)}.`, + ` See the result: void project security check ${cleanLine(checkId)}`, + ]); + return; + } + const view = await waitForSecurityLocalCheck( + client, + projectId, + checkId, + (status) => log([status === 'running' ? ' Running…' : ' Waiting in the scan queue…']), + deps.check, + ); + if (view === null) { + print(args, { checkId, ended: false }, [ + ` Still not done. See it later: void project security check ${cleanLine(checkId)}`, + ]); + return; + } + print(args, view, checkResultLines(slug, view, cleanLine, { fresh })); + if (!checkEndedWithResult(view)) { + throw new Error(checkFailureMessage(view, cleanLine, { fresh })); + } +} diff --git a/packages/void/src/cli/project-zero-trust.ts b/packages/void/src/cli/project-zero-trust.ts index 76ff70358..f8caa4b13 100644 --- a/packages/void/src/cli/project-zero-trust.ts +++ b/packages/void/src/cli/project-zero-trust.ts @@ -1,19 +1,32 @@ -import { log, outro } from '@voidzero-dev/vite-plus-prompts'; +import { confirm, isCancel, log, outro } from '@voidzero-dev/vite-plus-prompts'; +import { isCI } from 'ci-info'; import { getToken } from './auth.ts'; import { + PlatformApiError, PlatformClient, type ProjectZeroTrustResponse, type ProjectZeroTrustUpdateResponse, } from './client.ts'; import { printSuccess, note, sanitizeTerminalText } from './output.ts'; -import type { ProjectArgs } from './project-args.ts'; +import type { ProjectZeroTrustArgs } from './project-args.ts'; +import { cleanLine, publicRequestLines } from './project-security.ts'; import { readProjectConfig } from './project.ts'; import { getRequestedProjectSlug, requireProjectBySlug } from './resolve-project.ts'; +import type { ProjectSecurityStatus, SecurityPublicRequest } from './security-api-types.ts'; -type ZeroTrustArgs = Extract & { - action: 'status' | 'protect' | 'public' | 'reconcile'; +type ZeroTrustArgs = Exclude; + +export type ProjectZeroTrustDeps = { + interactive?: boolean; + confirm?: (message: string) => Promise; }; +const OPEN_REQUEST_STATES = ['waiting_scan', 'held_findings', 'held_no_result', 'needs_deploy']; + +function isOpenRequest(request: SecurityPublicRequest | null | undefined): boolean { + return Boolean(request && OPEN_REQUEST_STATES.includes(request.state)); +} + async function resolveTarget(root: string, args: ZeroTrustArgs) { const token = getToken(root); if (!token) { @@ -32,7 +45,20 @@ async function resolveTarget(root: string, args: ZeroTrustArgs) { return { client, projectId: linked.projectId, slug: linked.slug }; } -function statusLines(result: ProjectZeroTrustResponse): string { +function requestBlock( + slug: string, + request: SecurityPublicRequest, + security: Pick, +): Array { + const [first = '', ...rest] = publicRequestLines(slug, request, security); + return [`Public request: ${first}`, ...rest.map((line) => ` ${line}`)]; +} + +function statusLines( + result: ProjectZeroTrustResponse, + security: Pick, + slug: string, +): string { const project = result.project; const platformStatus = sanitizeTerminalText(result.platformStatus); const unavailableMessage = @@ -59,14 +85,158 @@ function statusLines(result: ProjectZeroTrustResponse): string { `State: ${project?.state ?? 'not initialized'}`, ...(project?.last_error ? [`Last error: ${sanitizeTerminalText(project.last_error)}`] : []), ...(!result.available ? [unavailableMessage] : []), + ...(isOpenRequest(result.publicRequest) + ? requestBlock(slug, result.publicRequest!, security) + : []), ].join('\n'); } -export async function runProjectZeroTrustCommand(root: string, args: ZeroTrustArgs): Promise { - console.log(); - const { client, projectId, slug } = await resolveTarget(root, args); +function printJson(value: unknown): void { + console.log(JSON.stringify(value)); +} + +/** The reply of a held request as JSON: the stored state, never the old-CLI stand-in. */ +function heldJson(result: ProjectZeroTrustUpdateResponse) { + return { + ...result, + held: true, + project: { ...result.project, state: 'protected' as const, last_error: null }, + }; +} + +function urgentRefusal(slug: string, error: PlatformApiError): Error | null { + let body: { error?: unknown; blockers?: { ids?: unknown } }; + try { + body = JSON.parse(error.body) as typeof body; + } catch { + return null; + } + if (body.error === 'no public request') { + return new Error( + `project: ${slug} has no public request to bypass. Run: void project zero-trust public`, + ); + } + if (body.error !== 'security public request has urgent findings') { + return null; + } + const ids = Array.isArray(body.blockers?.ids) + ? body.blockers.ids.filter((id): id is string => typeof id === 'string').map(cleanLine) + : []; + const count = ids.length; + return new Error( + `project: ${slug} has ${count} urgent ${count === 1 ? 'finding' : 'findings'} open (${ids.join(', ')}). A bypass skips only the scan, not open findings.\n Resolve them first: fixed (then deploy the fix), or false-positive / accepted-risk with a comment.\n Then the request unlocks. → void project security list --urgent`, + ); +} + +function skipLine(request: SecurityPublicRequest): string { + const target = cleanLine(request.targetDeploymentId); + if (request.state === 'waiting_scan') { + return `The scan of ${target} has not finished.`; + } + if (request.state === 'needs_deploy') { + return request.heldReason === 'unproven_fix' + ? 'A fix you resolved is not checked by a scan yet.' + : `The live deployment ${target} cannot be scanned until you deploy again.`; + } + const why = request.heldReason ? cleanLine(request.heldReason.split('_').join(' ')) : ''; + return `The scan of ${target} did not finish${why ? ` (${why})` : ''}.`; +} + +async function runBypass( + args: Extract, + target: { client: PlatformClient; projectId: string; slug: string }, + deps: ProjectZeroTrustDeps, +): Promise { + const { client, projectId, slug } = target; + const state = await client.getProjectZeroTrust(projectId); + // An old platform sends no request field; the bypass route then answers with the + // "does not support security audits" copy. + if (state.publicRequest === null) { + throw new Error( + `project: ${slug} has no public request to bypass. Run: void project zero-trust public`, + ); + } + const request = state.publicRequest; + if (request && !args.yes && request.state !== 'held_findings') { + const interactive = deps.interactive ?? (Boolean(process.stdout.isTTY) && !isCI); + if (args.json || !interactive) { + throw new Error('project: Add --yes to bypass the scan without a prompt.'); + } + const ask = + deps.confirm ?? + (async (message: string) => { + const answer = await confirm({ message, initialValue: false }); + return !isCancel(answer) && answer; + }); + log.info( + [ + 'This skips the security scan. ' + skipLine(request), + 'Your platform admins get an email with your reason, and the bypass is recorded.', + ].join('\n'), + ); + if (!(await ask(`Bypass the scan and make ${slug} public?`))) { + outro('Nothing was changed.'); + return; + } + } + let result; + try { + result = await client.bypassProjectPublicRequest(projectId, args.reason); + } catch (error) { + if (error instanceof PlatformApiError && error.status === 409) { + throw urgentRefusal(slug, error) ?? error; + } + throw error; + } + if (args.json) { + printJson(result); + return; + } + if (result.project?.last_error) { + log.warn(sanitizeTerminalText(result.project.last_error)); + } + const settled = + result.project?.state === 'public' && + !result.project.desired_protected && + !result.project.effective_protected; + printSuccess( + settled + ? `Scan bypassed. ${slug} is public.` + : `Scan bypassed. ${slug} is going public (Zero Trust update in progress).`, + ); +} + +export async function runProjectZeroTrustCommand( + root: string, + args: ZeroTrustArgs, + deps: ProjectZeroTrustDeps = {}, +): Promise { + if (!args.json) { + console.log(); + } + const target = await resolveTarget(root, args); + const { client, projectId, slug } = target; + if (args.action === 'bypass') { + return runBypass(args, target, deps); + } if (args.action === 'status') { - note(statusLines(await client.getProjectZeroTrust(projectId)), slug); + const result = await client.getProjectZeroTrust(projectId); + if (args.json) { + printJson(result); + return; + } + let security: Pick = { + backlogFiles: 0, + budget: null, + }; + if (isOpenRequest(result.publicRequest)) { + try { + security = await client.getProjectSecurity(projectId); + } catch { + // The request copy still reads right without the backlog and budget lines. + } + } + note(statusLines(result, security, slug), slug); outro(`${slug} Zero Trust status`); return; } @@ -74,6 +244,23 @@ export async function runProjectZeroTrustCommand(root: string, args: ZeroTrustAr args.action === 'reconcile' ? await client.reconcileProjectZeroTrust(projectId) : await client.setProjectZeroTrust(projectId, args.action === 'protect'); + const held = + args.action === 'public' && result.publicRequest && isOpenRequest(result.publicRequest); + if (args.json) { + printJson(held ? heldJson(result) : result); + return; + } + if (held) { + // Held for a scan: the project stays protected, so nothing here says "public". + const copy = result.message + ? sanitizeTerminalText(result.message) + : publicRequestLines(slug, result.publicRequest!, { backlogFiles: 0, budget: null }).join( + '\n', + ); + log.warn(copy); + outro(`${slug} stays protected by Zero Trust until the request clears.`); + return; + } if (result.project.last_error) { log.warn(sanitizeTerminalText(result.project.last_error)); } diff --git a/packages/void/src/cli/security-api-types.ts b/packages/void/src/cli/security-api-types.ts new file mode 100644 index 000000000..c1ebc9357 --- /dev/null +++ b/packages/void/src/cli/security-api-types.ts @@ -0,0 +1,254 @@ +/** Replies of the project security routes (spec §13.5), as the CLI reads them. */ + +export type SecurityScanSummary = { + id: string; + status: string; + statusReason: string | null; + failureCause: string | null; + refusalCategory: string | null; + trigger: string; + deploymentId: string | null; + baseDeploymentId: string | null; + coverageLabel: string | null; + backlogFiles: number; + filesScanned: number; + model: string | null; + meteredUsd: number | null; + startedAt: string | null; + finishedAt: string | null; + createdAt: string; +}; + +export type SecurityPublicRequest = { + id: string; + state: string; + heldReason: string | null; + targetDeploymentId: string; + gateScanId: string | null; + blockers: { count: number; ids: Array }; + requestedAt: string; + requestedByRole: string | null; +}; + +export type SecurityUrgentFinding = { + id: string; + severity: string | null; + title?: string; + file?: string | null; + line?: number | null; + firstSeenAt?: string | null; + notSeenInLatest?: boolean; + possibleDuplicateOf?: { + id: string; + resolution: string | null; + resolvedAt?: string | null; + } | null; +}; + +export type ProjectSecurityStatus = { + policy: { mode: string; applies: boolean; reason: string; publicGate: boolean }; + urgent: { + count: number; + counts: { critical: number; high: number }; + oldestFirstSeenAt: string | null; + findings: Array; + more: number; + detail: 'full' | 'counts'; + }; + model: { + id: string | null; + requested: string; + source: 'project' | 'default' | 'fallback' | null; + thirdParty: boolean; + noticeAccepted: boolean; + pendingDefault: string | null; + }; + budget: { + capUsd: number | null; + capSource: 'own' | 'limit' | 'none'; + ceilingUsd: number | null; + /** Where `ceilingUsd` comes from; older platforms do not send it. */ + ceilingSource?: 'project' | 'plan' | 'default' | null; + spentUsd: number; + month: string; + resetsAt: string; + } | null; + lastScan: SecurityScanSummary | null; + lastSuccessfulScan: SecurityScanSummary | null; + deploysSinceLastSuccess: number | null; + backlogFiles: number; + counts: { + open: Record; + leads: number; + resolved: number; + urgent: number; + }; + publicRequest: SecurityPublicRequest | null; + /** The caller may resolve findings (`settings`, a user session); older platforms do not send it. */ + canResolve?: boolean; +}; + +export type SecurityFinding = { + id: string; + verdict: string; + severity: string | null; + state: string; + urgent: boolean; + revision: number; + title?: string; + category?: string | null; + cwe?: string | null; + confidence?: string | number | null; + file?: string | null; + line?: number | null; + lineEnd?: number | null; + resolution?: string | null; + resolvedAt?: string | null; + resolvedBy?: string | null; + /** `severity` was set by a person; `scanSeverity` is what the scans said. Newer platforms only. */ + severityEdited?: boolean; + scanSeverity?: string | null; + notSeenInLatest?: boolean; + possibleDuplicateOf?: { id: string; resolution: string | null } | null; + reopenCount?: number; + fixChecked?: boolean; + deploymentId?: string | null; + firstSeenAt?: string | null; + trace?: unknown; + evidence?: unknown; + conditions?: unknown; + fix?: unknown; + /** `runtime` when a request to a throwaway copy of the deployment proved it. */ + verdictSource?: 'static' | 'runtime' | null; + runtimeProof?: { request: string; method: string; path: string; status: number } | null; +}; + +export type SecurityFindingEvent = { + action: string; + actorKind: string; + actorRole: string | null; + actor: string | null; + resolution: string | null; + comment: string | null; + /** `severity_edited` only: the severity before and after. */ + severityFrom?: string | null; + severityTo?: string | null; + createdAt: string | null; +}; + +export type SecurityFindingList = { findings: Array; nextCursor: string | null }; + +export type SecurityFindingDetail = { + finding: SecurityFinding; + events?: Array; +}; + +export type SecurityFindingChange = { + ok: true; + id: string; + state: string; + resolution: string | null; + revision: number; + publicRequest?: SecurityPublicRequest; +}; + +/** `POST …/findings/:fid/severity`: the finding after a severity edit. */ +export type SecuritySeverityChange = { + ok: true; + id: string; + severity: string | null; + scanSeverity: string | null; + severityEdited: boolean; + urgent: boolean; + revision: number; + changed: boolean; + publicRequest?: SecurityPublicRequest; +}; + +export type SecurityScanList = { scans: Array; nextCursor: string | null }; + +export type SecurityModelChange = { ok: true; model: ProjectSecurityStatus['model'] }; + +/** `POST /projects/:id/security/scans` with `dryRun: true`: what a rescan would run. */ +export type SecurityRescanPreview = { + dryRun: true; + deploymentId: string; + alreadyScanned: boolean; + tier: string; + /** M31: the scan also reads client bundle sources; older platforms omit it. */ + clientAssets?: boolean; + model: string | null; + thirdParty: boolean; + worstCaseUsd: number | null; + budget: ProjectSecurityStatus['budget']; +}; + +export type SecurityRescanQueued = { + ok: true; + scanId: string; + deploymentId: string; + tier: string; + clientAssets?: boolean; + model: string | null; + alreadyScanned: boolean; +}; + +export type SecurityBudgetChange = { + ok: true; + budget: NonNullable; +}; + +export type SecurityFindingQuery = { + state: 'open' | 'resolved' | 'all'; + urgent: boolean; + severity: string | null; + limit: number; + cursor: string | null; +}; + +/** M32: what a local check would run, before any code is sent. */ +export type SecurityCheckPreview = { + dryRun: true; + model: string; + thirdParty: boolean; + /** The provider notice, for a third-party model; `null` for a Cloudflare model. */ + notice: Array | null; + worstCaseUsd: number | null; + budget: ProjectSecurityStatus['budget']; + limits: { maxFiles: number; maxBytes: number; maxArchiveBytes: number }; +}; + +export type SecurityCheckCreated = { + ok: true; + checkId: string; + upload: { url: string; headers: Record }; + expiresAt: string; + model: string; + thirdParty: boolean; +}; + +export type SecurityCheckFinding = { + verdict: 'confirmed' | 'needs_validation'; + severity: string | null; + confidence: string | null; + title: string; + category: string; + cwe: string | null; + file: string; + lineStart: number | null; + lineEnd: number | null; + source: 'scanner' | 'server'; + verdictSource: 'static' | 'runtime'; + detail: Record; +}; + +export type SecurityCheckView = { + check: SecurityScanSummary & { coverageNotes: Array }; + ended: boolean; + result: { + version: 1; + findings: Array; + total: number; + capped: boolean; + } | null; +}; diff --git a/packages/void/src/cli/security-sarif.ts b/packages/void/src/cli/security-sarif.ts new file mode 100644 index 000000000..5790456b8 --- /dev/null +++ b/packages/void/src/cli/security-sarif.ts @@ -0,0 +1,198 @@ +/** + * SARIF 2.1.0 export of security audit findings (design doc 0095, M31), for + * `void project security list --format sarif` and `void platform security findings + * --format sarif`. Code scanning tools (GitHub, editors) read it. + * + * finding ─► result: rule = category, level from severity, file and lines, + * fingerprint = project + finding id, resolved ─► suppression + * categories ─► rules, with the highest `security-severity` of their results + * + * Paths are as the scan saw them: source paths from the repository or the source maps, + * `_assets/…` for deployed static files, `_client/…` for client bundle sources and + * `_worker/…` for built code with no source map. + */ +import { stripVTControlCharacters } from 'node:util'; +import { getOwnVersion } from './agents.ts'; + +/** The CLI version for the SARIF tool entry; `null` when it cannot be read. */ +export function sarifToolVersion(): string | null { + try { + const version: unknown = getOwnVersion(); + return typeof version === 'string' ? version : null; + } catch { + return null; + } +} + +/** Text from a model or a user: no escape sequences, one line. */ +function cleanLine(value: unknown): string { + let out = ''; + for (const char of stripVTControlCharacters(String(value ?? ''))) { + const code = char.codePointAt(0)!; + out += code < 0x20 || (code >= 0x7f && code <= 0x9f) ? ' ' : char; + } + return out; +} + +/** The fields of a finding the export reads; readers see only some of them. */ +export type SarifFinding = Readonly<{ + id: string; + /** The project slug; the operator export spans projects. */ + project?: string; + verdict: string; + severity: string | null; + state: string; + resolution?: string | null; + urgent?: boolean; + title?: string; + category?: string | null; + cwe?: string | null; + file?: string | null; + line?: number | null; + lineEnd?: number | null; + verdictSource?: 'static' | 'runtime' | null; +}>; + +export const SARIF_SCHEMA_URI = 'https://json.schemastore.org/sarif-2.1.0.json'; +const TOOL_NAME = 'Void Security Audit'; +const TOOL_URI = 'https://void.cloud/guide/platform/administration/security-audits'; +/** A finding a reader cannot see the details of has no category. */ +const UNKNOWN_RULE = 'finding'; + +/** GitHub code scanning ranks by `security-severity` (0.1 to 10). */ +const SECURITY_SEVERITY: Readonly> = { + critical: 9.5, + high: 8, + medium: 5.5, + low: 3, + informational: 0.5, +}; + +function level(severity: string | null): 'error' | 'warning' | 'note' { + if (severity === 'critical' || severity === 'high') { + return 'error'; + } + return severity === 'medium' ? 'warning' : 'note'; +} + +function positiveLine(value: number | null | undefined): number | null { + return typeof value === 'number' && Number.isSafeInteger(value) && value > 0 ? value : null; +} + +/** A relative path as a SARIF URI: each segment percent-encoded, slashes kept. */ +function fileUri(path: string): string { + return path + .split('/') + .filter((segment) => segment !== '' && segment !== '.') + .map((segment) => encodeURIComponent(segment)) + .join('/'); +} + +function result(finding: SarifFinding): Record { + const id = cleanLine(finding.id); + const project = finding.project === undefined ? null : cleanLine(finding.project); + const ruleId = finding.category ? cleanLine(finding.category) : UNKNOWN_RULE; + const text = + finding.title === undefined + ? `${id}: ${cleanLine(finding.severity ?? 'unrated')} finding. Ask a project collaborator for the details.` + : `${id}: ${cleanLine(finding.title)}`; + const out: Record = { + ruleId, + level: level(finding.severity), + message: { text }, + }; + const file = finding.file ? fileUri(cleanLine(finding.file)) : ''; + if (file !== '') { + const startLine = positiveLine(finding.line); + const endLine = positiveLine(finding.lineEnd); + out.locations = [ + { + physicalLocation: { + artifactLocation: { uri: file, uriBaseId: '%SRCROOT%' }, + ...(startLine === null + ? {} + : { + region: { + startLine, + ...(endLine !== null && endLine >= startLine ? { endLine } : {}), + }, + }), + }, + }, + ]; + } + // The finding id is stable across scans: code scanning keeps one alert per finding. + out.partialFingerprints = { 'voidFinding/v1': project === null ? id : `${project}/${id}` }; + if (finding.state === 'resolved') { + out.suppressions = [ + { + kind: 'external', + status: 'accepted', + justification: cleanLine(finding.resolution ?? 'resolved') + .split('_') + .join(' '), + }, + ]; + } + out.properties = { + id, + ...(project === null ? {} : { project }), + severity: finding.severity, + verdict: + finding.verdict === 'confirmed' && finding.verdictSource === 'runtime' + ? 'confirmed (runtime)' + : finding.verdict === 'needs_validation' + ? 'lead' + : cleanLine(finding.verdict), + state: cleanLine(finding.state), + ...(finding.urgent === undefined ? {} : { urgent: finding.urgent }), + ...(finding.cwe ? { cwe: cleanLine(finding.cwe) } : {}), + }; + return out; +} + +/** + * One SARIF log with one run. `version` is the CLI's; findings keep their order. + */ +export function securityFindingsSarif( + findings: ReadonlyArray, + options: Readonly<{ version: string | null }>, +): Record { + const results = findings.map(result); + const rules = new Map }>(); + for (const [index, finding] of findings.entries()) { + const ruleId = results[index]!.ruleId as string; + const rule = rules.get(ruleId) ?? { id: ruleId, score: 0, cwes: new Set() }; + rule.score = Math.max(rule.score, SECURITY_SEVERITY[finding.severity ?? ''] ?? 0); + if (finding.cwe) { + rule.cwes.add(cleanLine(finding.cwe)); + } + rules.set(ruleId, rule); + } + return { + $schema: SARIF_SCHEMA_URI, + version: '2.1.0', + runs: [ + { + tool: { + driver: { + name: TOOL_NAME, + ...(options.version ? { version: options.version } : {}), + informationUri: TOOL_URI, + rules: [...rules.values()].map((rule) => ({ + id: rule.id, + shortDescription: { + text: rule.id === UNKNOWN_RULE ? 'Security finding' : rule.id.split('-').join(' '), + }, + properties: { + tags: ['security', ...rule.cwes], + ...(rule.score > 0 ? { 'security-severity': rule.score.toFixed(1) } : {}), + }, + })), + }, + }, + results, + }, + ], + }; +} diff --git a/packages/void/test/unit/cli-help.test.ts b/packages/void/test/unit/cli-help.test.ts index e6cb530ea..fa0fb76ee 100644 --- a/packages/void/test/unit/cli-help.test.ts +++ b/packages/void/test/unit/cli-help.test.ts @@ -110,6 +110,62 @@ describe('CLI help resolver', () => { }); describe('rendered help advertises the flags the parser honours', () => { + it('generates the platform security help tree from the operator commands', () => { + const group = render(['platform', 'security']); + for (const action of [ + 'status', + 'probe', + 'policy', + 'models', + 'limits', + 'budget', + 'findings', + 'show', + 'resolve', + 'reopen', + 'comment', + 'model', + 'scans', + 'rescan', + 'cancel', + 'public-gate', + 'public-requests', + 'bypass', + 'bypasses', + ]) { + expect(group).toContain(action); + expect(hasHelpPage(['platform', 'security', action])).toBe(true); + } + expect(render(['platform'])).toContain('security '); + // The scan time limit has its own name, apart from the request deadline. + expect(render(['platform', 'security', 'limits'])).toContain('--scan-timeout '); + expect(render(['platform', 'security', 'policy'])).toContain( + 'void platform security policy ', + ); + }); + + it('shows the paging flags on the security lists and no confirmation flags on the probe', () => { + for (const list of ['findings', 'scans', 'public-requests', 'bypasses']) { + const page = render(['platform', 'security', list]); + expect(page).toContain('--limit '); + expect(page).toContain('--page '); + } + expect(render(['platform', 'security', 'status'])).not.toContain('--limit'); + const probe = render(['platform', 'security', 'probe']); + expect(probe).not.toContain('--plan'); + expect(probe).not.toContain('--yes'); + expect(probe).toContain('--timeout '); + }); + + it('shows --security-audits on platform install, upgrade and repair only', () => { + for (const command of ['install', 'upgrade', 'repair']) { + expect(render(['platform', command])).toContain('--security-audits'); + } + for (const command of ['disable', 'enable']) { + expect(render(['platform', command])).not.toContain('--security-audits'); + } + }); + it('shows both Git initialization flags on init', () => { const page = render(['init']); expect(page).toContain('--git'); @@ -153,6 +209,13 @@ describe('rendered help advertises the flags the parser honours', () => { expect(page).toContain('--project '); }); + it('lists the project security commands', () => { + const page = render(['project', 'security']); + expect(page).toContain('resolve '); + expect(page).toContain('--accept-provider-notice'); + expect(render(['project'])).toContain('security '); + }); + it('states plain limits for remote studio and purge-cache', () => { const studio = render(['db', 'studio']); expect(studio).not.toContain('not yet'); diff --git a/packages/void/test/unit/cloudflare-deploy.test.ts b/packages/void/test/unit/cloudflare-deploy.test.ts index ee451ed1a..e9d543aa5 100644 --- a/packages/void/test/unit/cloudflare-deploy.test.ts +++ b/packages/void/test/unit/cloudflare-deploy.test.ts @@ -1372,6 +1372,33 @@ describe('existing Cloudflare site handoff', () => { ); expect(existsSync(join(root, '.void/cloudflare-link.json'))).toBe(false); }); + it('never reads project security, touches containers or adds an AI binding on a native deploy', async () => { + const root = migratedSite(); + const requested: Array = []; + vi.stubGlobal( + 'fetch', + vi.fn(async (input: string | URL | Request) => { + requested.push(String(input instanceof Request ? input.url : input)); + return new Response('{}', { status: 404 }); + }), + ); + const { deps, trace, wranglerArgs } = harness({ + readExistingWorker: async () => existing, + runBuild: () => build(root), + verifyDeployConfig: verifyGeneratedDeployConfig, + }); + try { + await runCloudflareDeploy(root, { reuseExistingWorker: true }, silentCliLog, deps); + } finally { + vi.unstubAllGlobals(); + } + expect(trace).toContain('wrangler:deploy'); + expect(requested.filter((url) => url.includes('/security'))).toEqual([]); + expect(requested.filter((url) => url.includes('/containers/'))).toEqual([]); + expect(wranglerArgs.some((args) => args[0] === 'containers')).toBe(false); + expect(parseRootWranglerConfig(join(root, '.void-wrangler.jsonc')).ai).toBeUndefined(); + expect(parseRootWranglerConfig(join(root, 'dist/ssr/wrangler.json')).ai).toBeUndefined(); + }); it('accepts comments in the generated config during an existing site deploy', async () => { const root = site(); const { deps } = harness({ diff --git a/packages/void/test/unit/deploy-platform-target.test.ts b/packages/void/test/unit/deploy-platform-target.test.ts index 07c5168e5..a6a959f38 100644 --- a/packages/void/test/unit/deploy-platform-target.test.ts +++ b/packages/void/test/unit/deploy-platform-target.test.ts @@ -100,7 +100,10 @@ beforeEach(() => { const url = new URL(input instanceof Request ? input.url : input); const method = init?.method ?? 'GET'; const authorization = new Headers(init?.headers).get('Authorization'); - requests.push({ origin: url.origin, path: url.pathname, method, authorization }); + // The best-effort security read after a deploy is not part of the deploy flow. + if (!url.pathname.endsWith('/security')) { + requests.push({ origin: url.origin, path: url.pathname, method, authorization }); + } expect([originalOrigin, alternateOrigin]).toContain(url.origin); const id = url.origin === originalOrigin ? 'project-original' : 'project-alternate'; const project = { id, slug: 'my-app', role: 'owner' }; diff --git a/packages/void/test/unit/deploy-security-notice.test.ts b/packages/void/test/unit/deploy-security-notice.test.ts new file mode 100644 index 000000000..a3f1d6086 --- /dev/null +++ b/packages/void/test/unit/deploy-security-notice.test.ts @@ -0,0 +1,404 @@ +import { describe, expect, it, vi } from 'vite-plus/test'; +import { PlatformApiError, type PlatformClient } from '../../src/cli/client.ts'; +import { + formatProjectStatusSecurityLine, + printDeploySecurityNotice, +} from '../../src/cli/deploy-security-notice.ts'; +import type { CliLogger } from '../../src/cli/log-file.ts'; +import type { ProjectSecurityStatus } from '../../src/cli/security-api-types.ts'; + +const scan = (overrides: Record = {}) => ({ + id: 'ss_1', + status: 'queued', + statusReason: null, + failureCause: null, + refusalCategory: null, + trigger: 'deploy', + deploymentId: 'dpl_9a1d', + baseDeploymentId: 'dpl_7c20', + coverageLabel: null, + backlogFiles: 0, + filesScanned: 0, + model: '@cf/deepseek-ai/deepseek-v4.1-flash-1017', + meteredUsd: null, + startedAt: null, + finishedAt: null, + createdAt: '2026-11-17T10:00:00.000Z', + ...overrides, +}); + +function status(overrides: Partial = {}): ProjectSecurityStatus { + return { + policy: { + mode: 'all', + applies: true, + reason: 'the platform scans all projects', + publicGate: false, + }, + urgent: { + count: 0, + counts: { critical: 0, high: 0 }, + oldestFirstSeenAt: null, + findings: [], + more: 0, + detail: 'full', + }, + model: { + id: '@cf/deepseek-ai/deepseek-v4.1-flash-1017', + requested: '@cf/deepseek-ai/deepseek-v4.1-flash-1017', + source: 'default', + thirdParty: false, + noticeAccepted: false, + pendingDefault: null, + }, + budget: null, + lastScan: scan(), + lastSuccessfulScan: null, + deploysSinceLastSuccess: null, + backlogFiles: 0, + counts: { open: {}, leads: 3, resolved: 0, urgent: 0 }, + publicRequest: null, + ...overrides, + } as ProjectSecurityStatus; +} + +const urgent = ( + n: number, + detail: 'full' | 'counts' = 'full', +): ProjectSecurityStatus['urgent'] => ({ + count: n, + counts: { critical: Math.min(n, 1), high: Math.max(0, n - 1) }, + oldestFirstSeenAt: '2026-11-01T00:00:00.000Z', + more: 0, + detail, + findings: Array.from({ length: Math.min(n, 5) }, (_, index) => + detail === 'full' + ? { + id: `F-${index + 1}`, + severity: index === 0 ? 'high' : index === 1 ? 'critical' : 'high', + title: `Title ${index + 1}\u001b[31m red`, + file: 'src/a.ts', + line: 4, + } + : { id: `F-${index + 1}`, severity: 'high' }, + ), +}); + +async function run( + reply: () => Promise, + extra: { + env?: NodeJS.ProcessEnv; + slug?: string; + timeoutMs?: number; + cliLog?: CliLogger; + } = {}, +) { + const lines: Array = []; + const getProjectSecurity = vi.fn(reply); + await printDeploySecurityNotice({ + client: { getProjectSecurity } as unknown as PlatformClient, + projectId: 'project_1', + slug: extra.slug ?? 'acme-web', + deploymentId: 'dpl_9a1d', + cliLog: extra.cliLog, + env: extra.env ?? {}, + timeoutMs: extra.timeoutMs, + write: (line) => lines.push(line), + }); + return { lines, getProjectSecurity }; +} + +describe('deploy security notice', () => { + it('prints the queued scan line', async () => { + const { lines } = await run(async () => status()); + expect(lines.join('\n')).toContain( + 'Security scan queued · model @cf/deepseek-ai/deepseek-v4.1-flash-1017 · usually 5–15 min', + ); + expect(lines.at(-1)).toBe(' Check it: void project security status'); + }); + + it('names the third-party provider and a pending default', async () => { + const reply = status({ + model: { + id: 'anthropic/claude-opus-5.5', + requested: 'anthropic/claude-opus-5.5', + source: 'project', + thirdParty: true, + noticeAccepted: true, + pendingDefault: 'openai/gpt-6', + }, + }); + const text = (await run(async () => reply)).lines.join('\n'); + expect(text).toContain('Run by Anthropic: its usage policy applies and it may refuse.'); + expect(text).toContain('Platform default is openai/gpt-6. Accept to use it:'); + }); + + it('says what a public request waits for', async () => { + const reply = status({ + publicRequest: { + id: 'pr_1', + state: 'waiting_scan', + heldReason: null, + targetDeploymentId: 'dpl_9a1d', + gateScanId: 'ss_1', + blockers: { count: 0, ids: [] }, + requestedAt: '2026-11-17T10:00:00.000Z', + requestedByRole: 'admin', + }, + }); + expect((await run(async () => reply)).lines.join('\n')).toContain( + 'acme-web stays protected by Zero Trust until this scan passes (public request).', + ); + }); + + it('prints the budget, protected and no-change lines', async () => { + const own = status({ + lastScan: scan({ status: 'skipped', statusReason: 'budget' }), + budget: { + capUsd: 40, + capSource: 'own', + ceilingUsd: 100, + spentUsd: 40, + month: '2026-11', + resetsAt: '2026-12-01T00:00:00.000Z', + }, + }); + const ownText = (await run(async () => own)).lines.join('\n'); + expect(ownText).toContain('monthly scan budget is used up ($40.00 of $40.00). Resets Dec 1.'); + expect(ownText).toContain('void project security budget --usd 100'); + + const platform = status({ + lastScan: scan({ status: 'skipped', statusReason: 'budget' }), + budget: { + capUsd: null, + capSource: 'none', + ceilingUsd: null, + spentUsd: 0, + month: '2026-11', + resetsAt: '2026-12-01T00:00:00.000Z', + }, + }); + expect((await run(async () => platform)).lines.join('\n')).toContain( + "the platform's monthly scan budget is used up. Resets Dec 1. Ask your platform admin.", + ); + + const protectedText = ( + await run(async () => + status({ lastScan: scan({ status: 'skipped', statusReason: 'protected' }) }), + ) + ).lines.join('\n'); + expect(protectedText).toContain('project is protected by Zero Trust'); + + const same = status({ lastScan: scan({ status: 'succeeded', statusReason: 'no_changes' }) }); + expect((await run(async () => same)).lines.join('\n')).toContain( + 'Security scan: no code changes since dpl_7c20.', + ); + }); + + it('warns when the last scan did not finish', async () => { + const reply = status({ + lastScan: scan({ id: 'ss_0', status: 'refused', deploymentId: 'dpl_7c20' }), + lastSuccessfulScan: scan({ status: 'succeeded', deploymentId: 'dpl_5c01' }) as never, + deploysSinceLastSuccess: 2, + }); + const text = (await run(async () => reply)).lines.join('\n'); + expect(text).toContain( + 'Warning: the security scan of dpl_7c20 did not finish (refused by model).', + ); + expect(text).toContain('2 deploys since the last successful scan (dpl_5c01).'); + const one = status({ ...reply, deploysSinceLastSuccess: 1 }); + expect((await run(async () => one)).lines.join('\n')).not.toContain('deploys since'); + }); + + it('lists urgent rows for a user session, critical first, with ANSI stripped', async () => { + const reply = status({ urgent: urgent(2), lastScan: null }); + const text = (await run(async () => reply)).lines.join('\n'); + expect(text).toContain( + '⚠ 2 urgent security findings are open in acme-web (1 critical, 1 high):', + ); + expect(text.indexOf('F-2')).toBeLessThan(text.indexOf('F-1 ')); + expect(text).toContain('Title 2 red'); + expect(text).not.toContain('\u001b'); + expect(text).toContain('src/a.ts:4'); + expect(text).toContain('Your deploy went out.'); + expect(text).toContain('void project security show F-2'); + expect(text).toContain('A project admin or owner can resolve them.'); + expect(text).not.toContain('Fixed?'); + }); + + it('names the resolve command for a caller who can resolve (settings)', async () => { + const reply = status({ urgent: urgent(2), lastScan: null, canResolve: true }); + const text = (await run(async () => reply)).lines.join('\n'); + expect(text).toContain( + ' Fixed? void project security resolve F-2 --reason fixed --comment "…"', + ); + expect(text).not.toContain('A project admin or owner can resolve them.'); + }); + + it('cuts to five rows and counts the rest', async () => { + const big = urgent(8); + const text = (await run(async () => status({ urgent: big, lastScan: null }))).lines.join('\n'); + expect(text).toContain('… and 3 more: void project security list --urgent'); + expect(text).not.toContain('F-6'); + }); + + it('prints counts and ids only when the server says counts', async () => { + const text = ( + await run(async () => status({ urgent: urgent(2, 'counts'), lastScan: null })) + ).lines.join('\n'); + expect(text).toContain('2 urgent security findings are open (1 critical, 1 high): F-1, F-2'); + expect(text).toContain('Details are not printed in CI logs.'); + expect(text).not.toContain('Title'); + }); + + it.each([{ CI: 'true' }, { GITHUB_ACTIONS: 'true' }])( + 'drops to counts under %j even when the server sent titles', + async (env) => { + const text = ( + await run(async () => status({ urgent: urgent(2), lastScan: null }), { env }) + ).lines.join('\n'); + expect(text).toContain('Details are not printed in CI logs.'); + expect(text).not.toContain('Title'); + expect(text).not.toContain('src/a.ts'); + }, + ); + + it('prints the public request line under the urgent block', async () => { + const reply = status({ + urgent: urgent(1), + lastScan: null, + publicRequest: { + id: 'pr_1', + state: 'held_findings', + heldReason: 'findings', + targetDeploymentId: 'dpl_9a1d', + gateScanId: null, + blockers: { count: 1, ids: ['F-1'] }, + requestedAt: '2026-11-17T10:00:00.000Z', + requestedByRole: 'admin', + }, + }); + expect((await run(async () => reply)).lines.join('\n')).toContain( + 'acme-web stays protected by Zero Trust until these are resolved (public request).', + ); + }); + + it('prints nothing when the policy is off or for a preview project', async () => { + const off = status({ + policy: { mode: 'disabled', applies: false, reason: 'off', publicGate: false }, + urgent: urgent(2), + }); + expect((await run(async () => off)).lines).toEqual([]); + expect( + (await run(async () => status(), { slug: 'preview-abc' })).getProjectSecurity, + ).not.toHaveBeenCalled(); + }); + + it('still prints urgent findings when routing was not published but the deploy is live', async () => { + const reply = status({ urgent: urgent(1), lastScan: null }); + expect((await run(async () => reply)).lines.join('\n')).toContain('Your deploy went out.'); + }); + + it('lists rows oldest first inside a severity', async () => { + const found = (id: string, firstSeenAt: string) => ({ id, severity: 'high', firstSeenAt }); + const reply = status({ + lastScan: null, + urgent: { + ...urgent(3), + findings: [ + found('F-7', '2026-11-05T00:00:00.000Z'), + found('F-3', '2026-11-01T00:00:00.000Z'), + found('F-5', '2026-11-03T00:00:00.000Z'), + ], + }, + }); + const text = (await run(async () => reply)).lines.join('\n'); + expect(text.indexOf('F-3')).toBeLessThan(text.indexOf('F-5')); + expect(text.indexOf('F-5')).toBeLessThan(text.indexOf('F-7 ')); + }); + + it('hints at a possible duplicate and a finding not seen in the latest scan', async () => { + const reply = status({ + lastScan: null, + urgent: { + ...urgent(2), + findings: [ + { + id: 'F-1', + severity: 'high', + title: 'a', + possibleDuplicateOf: { id: 'F-9', resolution: 'wont_fix' }, + }, + { id: 'F-2', severity: 'high', title: 'b', notSeenInLatest: true }, + ], + }, + }); + const text = (await run(async () => reply)).lines.join('\n'); + expect(text).toContain('(possible duplicate of F-9, resolved wont fix)'); + expect(text).toContain('(not seen in latest scan; may already be fixed)'); + }); + + it('writes the cliLog entries', async () => { + const cliLog = { info: vi.fn(), debug: vi.fn() } as unknown as CliLogger; + await run(async () => status({ urgent: urgent(2) }), { cliLog }); + expect(cliLog.info).toHaveBeenCalledWith('security_notice', { + printed: true, + urgent: 2, + scan: 'queued', + }); + const quiet = { info: vi.fn(), debug: vi.fn() } as unknown as CliLogger; + await run(() => Promise.reject(new PlatformApiError('nope', 403, '')), { cliLog: quiet }); + expect(quiet.debug).toHaveBeenCalledWith('security_notice_skipped', { reason: 'http_403' }); + await run(async () => ({ ok: true }), { cliLog: quiet }); + expect(quiet.debug).toHaveBeenCalledWith('security_notice_skipped', { + reason: 'unexpected_reply', + }); + }); + + it.each([ + ['404', () => Promise.reject(new PlatformApiError('not found', 404, ''))], + ['401', () => Promise.reject(new PlatformApiError('no session', 401, ''))], + ['403', () => Promise.reject(new PlatformApiError('forbidden', 403, ''))], + [ + 'non-JSON 404', + () => Promise.reject(new PlatformApiError('Not found', 404, 'not found')), + ], + ['500', () => Promise.reject(new PlatformApiError('boom', 500, ''))], + ['network error', () => Promise.reject(new TypeError('fetch failed'))], + ['non-object reply', () => Promise.resolve('nope')], + ['old reply shape', () => Promise.resolve({ ok: true })], + ])('prints nothing and keeps the exit code on a %s', async (_name, reply) => { + const before = process.exitCode; + const { lines } = await run(reply); + expect(lines).toEqual([]); + expect(process.exitCode).toBe(before); + }); + + it('gives up on a read that never answers', async () => { + const before = process.exitCode; + const started = Date.now(); + const { lines } = await run(() => new Promise(() => {}), { timeoutMs: 20 }); + expect(lines).toEqual([]); + expect(Date.now() - started).toBeLessThan(2000); + expect(process.exitCode).toBe(before); + }); +}); + +describe('project status security line', () => { + it('shows urgent count and leads, or none', () => { + expect(formatProjectStatusSecurityLine('acme-web', status({ urgent: urgent(2) }))).toBe( + 'Security 2 urgent open · 3 leads → void project security list --urgent', + ); + expect(formatProjectStatusSecurityLine('acme-web', status())).toBe( + 'Security no urgent findings open', + ); + }); + + it('is empty when audits are off or the project is a preview', () => { + const off = status({ + policy: { mode: 'disabled', applies: false, reason: 'off', publicGate: false }, + }); + expect(formatProjectStatusSecurityLine('acme-web', off)).toBeNull(); + expect(formatProjectStatusSecurityLine('preview-x', status())).toBeNull(); + }); +}); diff --git a/packages/void/test/unit/deploy-security-packages.test.ts b/packages/void/test/unit/deploy-security-packages.test.ts new file mode 100644 index 000000000..64304753b --- /dev/null +++ b/packages/void/test/unit/deploy-security-packages.test.ts @@ -0,0 +1,111 @@ +import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { afterEach, describe, expect, it } from 'vite-plus/test'; +import { + bundlePackageNames, + findProjectLockfile, + readSecurityPackageClaims, +} from '../../src/cli/deploy-security-packages.ts'; + +const dirs: Array = []; +afterEach(() => { + for (const dir of dirs.splice(0)) { + rmSync(dir, { recursive: true, force: true }); + } +}); + +function repo(): string { + const dir = mkdtempSync(join(tmpdir(), 'void-security-packages-')); + dirs.push(dir); + return dir; +} + +const LOCK = [ + "lockfileVersion: '9.0'", + 'importers:', + ' apps/web:', + ' dependencies:', + ' hono:', + ' specifier: ^4.0.0', + ' version: 4.0.0', + " '@acme/shared':", + ' specifier: workspace:*', + ' version: link:../../packages/shared', + 'packages:', + ' hono@4.0.0:', + ' resolution: {integrity: sha512-x}', + ' scheduler@0.23.2:', + ' resolution: {integrity: sha512-y}', +].join('\n'); + +function map(sources: Array): Buffer { + return Buffer.from(JSON.stringify({ version: 3, sources, mappings: '' })); +} + +describe('deploy security package claims', () => { + it('reads the packages the source maps name, not the code', () => { + const files = new Map([ + ['index.js', Buffer.from('export default {}')], + [ + 'index.js.map', + map([ + '../src/server.ts', + '../../../node_modules/.pnpm/hono@4.0.0/node_modules/hono/dist/index.js', + '..\\node_modules\\@acme\\shared\\src\\auth.ts', + ]), + ], + ['broken.js.map', Buffer.from('{not json')], + ]); + expect([...bundlePackageNames(files)].sort()).toEqual(['@acme/shared', 'hono']); + }); + + it('finds the nearest lockfile up to the repository root, and none above it', () => { + const root = repo(); + mkdirSync(join(root, '.git')); + mkdirSync(join(root, 'apps', 'web'), { recursive: true }); + expect(findProjectLockfile(join(root, 'apps', 'web'))).toBeNull(); + writeFileSync(join(root, 'pnpm-lock.yaml'), LOCK); + expect(findProjectLockfile(join(root, 'apps', 'web'))).toBe(join(root, 'pnpm-lock.yaml')); + writeFileSync(join(root, 'apps', 'web', 'package-lock.json'), '{}'); + expect(findProjectLockfile(join(root, 'apps', 'web'))).toBe( + join(root, 'apps', 'web', 'package-lock.json'), + ); + }); + + it('claims each bundle package the lockfile places (transitive ones too)', () => { + const root = repo(); + mkdirSync(join(root, '.git')); + mkdirSync(join(root, 'apps', 'web'), { recursive: true }); + writeFileSync(join(root, 'pnpm-lock.yaml'), LOCK); + const files = new Map([ + [ + 'index.js.map', + map([ + '../node_modules/hono/dist/index.js', + '../node_modules/scheduler/index.js', + '../node_modules/@acme/shared/src/auth.ts', + '../node_modules/unknown/index.js', + ]), + ], + ]); + expect(readSecurityPackageClaims(join(root, 'apps', 'web'), files)).toEqual({ + registry: ['hono', 'scheduler'], + local: ['@acme/shared'], + }); + }); + + it('sends nothing without a lockfile, a map or a placed package', () => { + const root = repo(); + mkdirSync(join(root, '.git')); + const files = new Map([['index.js.map', map(['../node_modules/hono/index.js'])]]); + expect(readSecurityPackageClaims(root, files)).toBeNull(); + writeFileSync(join(root, 'pnpm-lock.yaml'), LOCK); + expect(readSecurityPackageClaims(root, new Map([['index.js', Buffer.from('x')]]))).toBeNull(); + expect( + readSecurityPackageClaims(root, new Map([['a.js.map', map(['../node_modules/zz/x.js'])]])), + ).toBeNull(); + writeFileSync(join(root, 'pnpm-lock.yaml'), 'not a lockfile'); + expect(readSecurityPackageClaims(root, files)).toBeNull(); + }); +}); diff --git a/packages/void/test/unit/direct-r2-deploy.test.ts b/packages/void/test/unit/direct-r2-deploy.test.ts index bbb0beb26..4909133a6 100644 --- a/packages/void/test/unit/direct-r2-deploy.test.ts +++ b/packages/void/test/unit/direct-r2-deploy.test.ts @@ -611,6 +611,7 @@ describe('Worker module uploads', () => { origin: string, files: Map, needed: Array = [], + root?: string, ): Promise { const { assetManifest, assetFiles } = await collectAndHashAssets(assetsDir); await streamDirectR2Deploy({ @@ -622,6 +623,7 @@ describe('Worker module uploads', () => { needed, preflightUsed: false, workerFiles: files, + root, spinner: noopSpinner as unknown as SpinnerResult, }); } @@ -658,10 +660,41 @@ describe('Worker module uploads', () => { const body = JSON.parse(state.finalizeCalls[0].init.body as string); expect(body.workerInput).toEqual({ id: 'wup_test', modules }); expect(body).not.toHaveProperty('workerFiles'); + // No lockfile root given: no security package claims. + expect(body).not.toHaveProperty('securityPackages'); // Each buffer is released once R2 has it. expect(files.size).toBe(0); }); + it('sends the security package claims of the bundle, read from the project lockfile', async () => { + advertiseDirectWorkerUpload(); + const state = installPlatformMocks(); + const root = mkdtempSync(join(tmpdir(), 'void-deploy-claims-')); + try { + mkdirSync(join(root, '.git')); + writeFileSync( + join(root, 'pnpm-lock.yaml'), + ['packages:', ' hono@4.0.0:', ' resolution: {integrity: sha512-x}'].join('\n'), + ); + const files = workerFiles(); + files.set( + 'index.js.map', + Buffer.from( + JSON.stringify({ + version: 3, + sources: ['../node_modules/hono/dist/index.js'], + mappings: '', + }), + ), + ); + await deployWorker(directOrigin, files, [], root); + const body = JSON.parse(state.finalizeCalls[0].init.body as string); + expect(body.securityPackages).toEqual({ registry: ['hono'], local: [] }); + } finally { + rmSync(root, { recursive: true, force: true }); + } + }); + it('keeps sending modules inline when discovery does not advertise direct uploads', async () => { const state = installPlatformMocks(); diff --git a/packages/void/test/unit/list-command.test.ts b/packages/void/test/unit/list-command.test.ts index 8eaa141f2..e71777df3 100644 --- a/packages/void/test/unit/list-command.test.ts +++ b/packages/void/test/unit/list-command.test.ts @@ -196,4 +196,91 @@ describe('runListCommand', () => { const quiet = await run(); expect(quiet.warn).not.toHaveBeenCalled(); }); + + describe('security line', () => { + const listBody = { + deployments: [ + { + id: 'dep-live', + status: 'live', + source: 'cli', + commit: null, + manifest: JSON.stringify({ type: 'ssr' }), + error_message: null, + retained: true, + applied_migrations: null, + created_at: '2026-01-01T00:00:00Z', + deployed_at: '2026-01-01T00:00:00Z', + }, + ], + activeDeploymentId: 'dep-live', + }; + + const run = async (security: () => Response | Promise) => { + setIsolatedHome(); + mockGetToken.mockReturnValue('test-token'); + const root = mkdtempSync(join(tmpdir(), 'void-list-')); + tempHomes.push(root); + mkdirSync(join(root, '.void'), { recursive: true }); + writeFileSync( + join(root, '.void', 'project.json'), + JSON.stringify({ projectId: 'proj-1', slug: 'demo' }), + ); + vi.stubGlobal( + 'fetch', + vi.fn(async (input: string | URL | Request) => + String(input).includes('/security') ? security() : Response.json(listBody), + ), + ); + const capture = captureOutput(); + const runListCommand = await importRunListCommand(); + await runListCommand(root); + const out = capture.output(); + capture.restore(); + return out; + }; + + const reply = (urgent: number, mode = 'all') => + Response.json({ + policy: { mode, applies: true, reason: 'x', publicGate: false }, + urgent: { + count: urgent, + counts: { critical: urgent, high: 0 }, + findings: [], + more: 0, + detail: 'full', + }, + model: { + id: null, + requested: 'x', + source: null, + thirdParty: false, + noticeAccepted: false, + pendingDefault: null, + }, + counts: { open: {}, leads: 3, resolved: 0, urgent }, + }); + + it('shows the urgent count and leads', async () => { + const out = await run(() => reply(2)); + expect(out).toContain( + 'Security 2 urgent open · 3 leads → void project security list --urgent', + ); + expect(out.indexOf('Security 2')).toBeLessThan(out.indexOf('dep-live')); + }); + + it('says none are open', async () => { + expect(await run(() => reply(0))).toContain('Security no urgent findings open'); + }); + + it.each([ + ['audits off', () => reply(2, 'disabled')], + ['404 from an old platform', () => new Response('Not Found', { status: 404 })], + ['500', () => new Response('boom', { status: 500 })], + ])('prints no security line on %s', async (_name, security) => { + const out = await run(security); + expect(out).not.toContain('Security '); + expect(out).toContain('dep-live'); + }); + }); }); diff --git a/packages/void/test/unit/operator-cli.test.ts b/packages/void/test/unit/operator-cli.test.ts index 534fe905a..58817710e 100644 --- a/packages/void/test/unit/operator-cli.test.ts +++ b/packages/void/test/unit/operator-cli.test.ts @@ -8,7 +8,11 @@ import { } from '@void/platform'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vite-plus/test'; import { hasHelpPage } from '../../src/cli/help.ts'; -import { operatorCommands, parseOperatorArgs } from '../../src/cli/operator-args.ts'; +import { + operatorCommands, + operatorGroups, + parseOperatorArgs, +} from '../../src/cli/operator-args.ts'; import { OPERATOR_KEYRING_SERVICE, readOperatorToken, @@ -123,13 +127,45 @@ describe('operator mutation completion output', () => { }); }); +/** Arguments after `security ` that each security command accepts. */ +const SECURITY_SAMPLES: Record> = { + status: [], + probe: [], + policy: ['public'], + models: ['--default', '@cf/zai-org/glm-5.3'], + limits: ['--concurrency', '3'], + budget: [], + findings: [], + show: ['p1', 'F-1'], + resolve: ['p1', 'F-1', '--reason', 'fixed', '--comment', 'done'], + reopen: ['p1', 'F-1', '--comment', 'again'], + comment: ['p1', 'F-1', 'note'], + model: ['p1', '--default'], + scans: [], + rescan: ['p1'], + backfill: [], + sweeps: ['on'], + fallback: ['on'], + digest: ['off'], + webhook: ['https://hooks.example.com/void'], + cancel: ['scan-1'], + 'public-gate': ['on'], + 'public-requests': [], + bypass: ['p1', '--reason', 'launch'], + bypasses: [], +}; + describe('operator argument and help coverage', () => { it('has nested help and routable arguments for every operation', () => { for (const command of operatorCommands) { expect(hasHelpPage(['platform', command.group, command.action])).toBe(true); - const parameters = (command.positional ?? []).map((name) => - name === 'type' ? 'email' : `${name}-value`, - ); + // Security commands check their own words and flags; each has a sample. + const security = command.group === 'security' ? SECURITY_SAMPLES[command.action] : []; + expect(command.group !== 'security' || security !== undefined).toBe(true); + const parameters = + command.group === 'security' + ? security! + : (command.positional ?? []).map((name) => (name === 'type' ? 'email' : `${name}-value`)); const configureFlags = command.group === 'zero-trust' && command.action === 'configure' ? [ @@ -1953,3 +1989,760 @@ describe('project AI logging commands', () => { }, ); }); + +describe('platform security arguments', () => { + const parse = (...args: Array) => parseOperatorArgs(['security', ...args]); + + it('routes the scan mode, models and limits to the policy route', () => { + expect(parse('policy', 'public')).toMatchObject({ + method: 'POST', + path: '/security/policy', + body: { mode: 'public' }, + }); + expect(() => parse('policy', 'everything')).toThrow('disabled|public|all'); + // One project's own rule (M34) has its own route. + expect(parse('policy', '--project', 'proj_1', 'never')).toMatchObject({ + method: 'POST', + action: 'project-policy', + path: '/projects/proj_1/security/policy', + body: { override: 'never' }, + }); + expect(() => parse('policy', '--project', 'proj_1', 'public')).toThrow( + '--project ', + ); + expect(() => parse('policy', 'always')).toThrow('name the project'); + expect(() => parse('policy', '--project', '..', 'always')).toThrow('dot path segment'); + expect( + parse( + 'models', + '--default', + '@cf/zai-org/glm-5.3', + '--block', + 'a, b', + '--unblock', + 'c', + '--accept-provider-notice', + ).body, + ).toEqual({ + defaultModel: '@cf/zai-org/glm-5.3', + block: ['a', 'b'], + unblock: ['c'], + acceptProviderNotice: true, + }); + expect(() => parse('models')).toThrow('Usage'); + // `--timeout` is the request deadline; the scan time limit has its own name. + expect( + parse('limits', '--concurrency', '4', '--scan-timeout', '30', '--timeout', '60'), + ).toMatchObject({ + body: { limits: { concurrency: 4, timeoutMinutes: 30 } }, + timeoutMs: 60_000, + }); + expect(() => parse('limits')).toThrow('Usage'); + expect(() => parse('limits', '--concurrency', 'many')).toThrow('whole number'); + expect(parse('public-gate', 'off').body).toEqual({ publicGate: false }); + expect(() => parse('public-gate', 'maybe')).toThrow('on|off'); + expect(parse('sweeps', 'on', '--every-days', '14')).toMatchObject({ + method: 'POST', + path: '/security/policy', + body: { sweeps: { on: true, everyDays: 14 } }, + }); + expect(parse('sweeps', 'off').body).toEqual({ sweeps: { on: false } }); + expect(() => parse('sweeps', 'weekly')).toThrow('on|off'); + expect(() => parse('sweeps', 'on', '--every-days', 'often')).toThrow('whole number'); + expect(parse('backfill')).toMatchObject({ method: 'POST', path: '/security/backfill' }); + // M26: fallback and digest are policy switches; the webhook has its own route. + expect(parse('fallback', 'on')).toMatchObject({ + method: 'POST', + path: '/security/policy', + body: { fallbackToCf: true }, + }); + expect(parse('digest', 'off').body).toEqual({ digest: false }); + expect(() => parse('fallback', 'sometimes')).toThrow('fallback '); + expect(parse('webhook', 'https://hooks.example.com/void')).toMatchObject({ + method: 'POST', + path: '/security/webhook', + body: { url: 'https://hooks.example.com/void' }, + }); + expect(parse('webhook', 'off').body).toEqual({ url: null }); + expect(() => parse('webhook', 'http://hooks.example.com/')).toThrow('https-url|off'); + }); + + it('routes a provider key change apart from the model policy (M33)', () => { + expect(parse('models', '--provider', 'anthropic', '--key-stdin')).toMatchObject({ + method: 'POST', + action: 'provider-key', + path: '/security/provider-keys', + body: { host: 'anthropic', keyStdin: true }, + }); + expect(parse('models', '--provider', 'openai', '--remove-key')).toMatchObject({ + action: 'provider-key', + path: '/security/provider-keys', + body: { host: 'openai', key: null }, + }); + expect(() => parse('models', '--provider', 'google', '--key-stdin')).toThrow( + '--provider must be openai or anthropic', + ); + expect(() => parse('models', '--provider', 'openai')).toThrow('--key-stdin | --remove-key'); + expect(() => parse('models', '--provider', 'openai', '--key-stdin', '--remove-key')).toThrow( + '--key-stdin | --remove-key', + ); + expect(() => parse('models', '--key-stdin')).toThrow('--provider must be'); + expect(() => + parse('models', '--provider', 'openai', '--key-stdin', '--default', '@cf/zai-org/glm-5.3'), + ).toThrow('on its own'); + // Without a provider flag, models still changes the policy. + expect(parse('models', '--default', '@cf/zai-org/glm-5.3')).toMatchObject({ + action: 'models', + path: '/security/policy', + }); + }); + + it('reads --default as a switch for one project and as a value for the platform', () => { + expect(parse('model', 'p1', '--default')).toMatchObject({ + path: '/projects/p1/security/model', + body: { model: null }, + }); + expect(parse('model', 'p1', '@cf/zai-org/glm-5.3').body).toEqual({ + model: '@cf/zai-org/glm-5.3', + }); + expect(() => parse('model', 'p1')).toThrow('Usage'); + expect(() => parse('model', 'p1', 'm', '--default')).toThrow('Usage'); + expect(parse('models', '--default', 'm').body).toEqual({ defaultModel: 'm' }); + }); + + it('builds budget changes for the platform, the default and one project', () => { + expect(parse('budget', '--platform-usd', '500', '--project-default-usd', '25.5').body).toEqual({ + platformMonthlyUsd: 500, + projectDefaultMonthlyUsd: 25.5, + }); + expect(parse('budget', '--platform-off', '--project-caps', 'off').body).toEqual({ + platformMonthlyUsd: null, + projectDefaultMonthlyUsd: null, + }); + expect(parse('budget', '--project-caps', 'on').body).toEqual({ projectCapsOn: true }); + expect(parse('budget', '--project', 'p/1', '--usd', '150')).toMatchObject({ + path: '/projects/p%2F1/security/budget', + body: { monthlyUsd: 150 }, + }); + expect(parse('budget', '--project', 'p1', '--clear').body).toEqual({ monthlyUsd: null }); + expect(parse('budget')).toMatchObject({ method: 'GET', path: '/security/budget' }); + expect(parse('budget', '--platform-off')).toMatchObject({ method: 'POST' }); + expect(() => parse('budget', '--platform-usd', '1', '--platform-off')).toThrow('not both'); + expect(() => parse('budget', '--project', 'p1')).toThrow('Usage'); + expect(() => parse('budget', '--project', 'p1', '--usd', '5', '--clear')).toThrow('Usage'); + expect(() => parse('budget', '--project', 'p1', '--usd', '5', '--platform-usd', '5')).toThrow( + 'do not combine', + ); + expect(() => parse('budget', '--usd', '5')).toThrow('--project'); + expect(() => parse('budget', '--platform-usd', '1.234')).toThrow('dollar amount'); + expect(() => parse('budget', '--project-caps', 'maybe')).toThrow('on or off'); + }); + + it('moves --urgent to the query and pages the lists', () => { + expect( + parse('findings', '--urgent', '--project', 'acme', '--limit', '50', '--page', '2'), + ).toMatchObject({ + method: 'GET', + path: '/security/findings', + query: { urgent: 'true', project: 'acme', limit: '50', page: '2' }, + body: {}, + }); + expect(() => parse('findings', '--state', 'gone')).toThrow('--state'); + expect(() => parse('findings', '--severity', 'info')).toThrow('--severity'); + for (const list of ['scans', 'public-requests', 'bypasses']) { + expect(parse(list, '--limit', '10').query).toEqual({ limit: '10' }); + } + expect(() => parse('status', '--limit', '10')).toThrow("Unknown flag '--limit'"); + expect(() => parse('scans', '--trigger', 'sweep')).toThrow('gate'); + }); + + it('takes comma-separated finding ids and requires the words a change needs', () => { + const resolve = parse( + 'resolve', + 'p1', + 'F-1,F-2,F-1', + '--reason', + 'false-positive', + '--comment', + 'Reviewed', + ); + expect(resolve).toMatchObject({ + path: '/projects/p1/security/findings/:fid/resolve', + body: { findingIds: ['F-1', 'F-2'], reason: 'false_positive', comment: 'Reviewed' }, + }); + expect(() => parse('resolve', 'p1', 'F-1', '--comment', 'x')).toThrow('--reason'); + expect(() => parse('resolve', 'p1', 'F-1', '--reason', 'meh', '--comment', 'x')).toThrow( + '--reason', + ); + expect(() => parse('resolve', 'p1', 'F-1', '--reason', 'fixed')).toThrow('comment'); + expect(() => parse('reopen', 'p1', 'F-1')).toThrow('comment'); + expect(parse('comment', 'p1', 'F-1,F-2', 'Looks real').body).toEqual({ + findingIds: ['F-1', 'F-2'], + text: 'Looks real', + }); + expect(parse('show', 'p1', 'F-3')).toMatchObject({ + method: 'GET', + path: '/projects/p1/security/findings/:fid', + }); + expect(() => parse('show', 'p1', ',')).toThrow('at least one id'); + expect(() => + parse('show', 'p1', Array.from({ length: 21 }, (_, i) => `F-${i}`).join(',')), + ).toThrow('at most 20'); + expect(parse('bypass', 'p1', '--reason', 'launch').body).toEqual({ reason: 'launch' }); + expect(() => parse('bypass', 'p1')).toThrow('reason'); + expect(parse('cancel', 'scan/1').path).toBe('/security/scans/scan%2F1/cancel'); + }); + + it('joins the operator groups, which feed the platform hint in the interactive menu', () => { + expect(operatorGroups).toContain('security'); + }); + + it('makes the probe a check without --plan or --yes', () => { + expect(parse('probe')).toMatchObject({ method: 'POST', path: '/security/probe' }); + expect(() => parse('probe', '--yes')).toThrow("Unknown flag '--yes'"); + expect(() => parse('probe', '--plan')).toThrow("Unknown flag '--plan'"); + expect(parse('probe', '--timeout', '600').timeoutMs).toBe(600_000); + }); +}); + +describe('platform security commands', () => { + type Call = { method: string; path: string; query: string; body: Record | null }; + + /** Serves operator replies in order and records each request. */ + function serve(replies: Array | Response>) { + vi.stubEnv('VOID_API_URL', 'https://one.example'); + vi.stubEnv('VOID_OPERATOR_TOKEN', 'operator'); + const queue = [...replies]; + const calls: Array = []; + vi.stubGlobal( + 'fetch', + vi.fn().mockImplementation(async (input, init) => { + const url = new URL(String(input)); + calls.push({ + method: init?.method ?? 'GET', + path: url.pathname.replace('/operator/v1', ''), + query: url.search, + body: init?.body ? (JSON.parse(String(init.body)) as Record) : null, + }); + const reply = queue.shift() ?? { error: 'unexpected_request' }; + return reply instanceof Response ? reply : Response.json(reply); + }), + ); + return calls; + } + + function quiet() { + const log = vi.spyOn(console, 'log').mockImplementation(() => {}); + const stderr = vi.spyOn(process.stderr, 'write').mockReturnValue(true); + const stdout = vi.spyOn(process.stdout, 'write').mockReturnValue(true); + return { + log, + stderr, + stdout, + printed: () => log.mock.calls.map(([line]) => String(line)).join('\n'), + errors: () => stderr.mock.calls.map(([chunk]) => String(chunk)).join(''), + terminal: () => stripVTControlCharacters(stdout.mock.calls.map(([c]) => String(c)).join('')), + }; + } + + const run = (...args: Array) => + runOperatorCommand(parseOperatorArgs(['security', ...args])); + + it('previews a mode change, then applies it at the previewed revision', async () => { + const out = quiet(); + const calls = serve([ + { + dryRun: true, + action: 'security.policy', + target: 'platform', + expectedRevision: 7, + policy: { mode: 'disabled' }, + preview: ['Mode: disabled → public'], + }, + { ok: true, policy: { mode: 'public' } }, + ]); + await run('policy', 'public', '--yes'); + expect(calls.map(({ method, path }) => `${method} ${path}`)).toEqual([ + 'POST /security/policy', + 'POST /security/policy', + ]); + expect(calls[0]!.body).toEqual({ mode: 'public', dryRun: true }); + expect(calls[1]!.body).toEqual({ mode: 'public', expectedRevision: 7 }); + // The preview is shown without the whole stored policy. + expect(out.errors()).toContain('Mode: disabled → public'); + expect(out.errors()).not.toContain('"policy"'); + expect(out.terminal()).toContain('Platform security policy completed.'); + }); + + it('previews a project scan rule, then sends the same body (M34)', async () => { + const out = quiet(); + const calls = serve([ + { + dryRun: true, + action: 'security.project-policy', + target: 'proj_1', + override: { from: 'inherit', to: 'always' }, + preview: ['acme: always scanned, also while Zero Trust protects it.'], + }, + { ok: true, slug: 'acme', override: { from: 'inherit', to: 'always' } }, + ]); + await run('policy', '--project', 'proj_1', 'always', '--yes'); + expect(calls.map(({ method, path }) => `${method} ${path}`)).toEqual([ + 'POST /projects/proj_1/security/policy', + 'POST /projects/proj_1/security/policy', + ]); + expect(calls[0]!.body).toEqual({ override: 'always', dryRun: true }); + expect(calls[1]!.body).toEqual({ override: 'always' }); + expect(out.errors()).toContain('always scanned, also while Zero Trust protects it'); + expect(out.terminal()).toContain('Platform security project-policy completed.'); + }); + + it('reads a provider key from stdin once, sends it for the preview and the change, never prints it', async () => { + const out = quiet(); + const stdin = vi + .spyOn(process.stdin, Symbol.asyncIterator) + .mockImplementation(async function* () { + yield 'sk-ant-secret-value-123\n'; + return undefined; + }); + const calls = serve([ + { + dryRun: true, + action: 'security.provider-key', + target: 'anthropic', + providerKey: null, + preview: ['Save: your own Anthropic key for anthropic/* scans.'], + }, + { + ok: true, + host: 'anthropic', + providerKey: { setAt: '2026-11-20T00:00:00.000Z' }, + probeNeeded: false, + message: 'Saved your own Anthropic key.', + }, + ]); + await run('models', '--provider', 'anthropic', '--key-stdin', '--yes'); + expect(stdin).toHaveBeenCalledTimes(1); + expect(calls.map(({ method, path }) => `${method} ${path}`)).toEqual([ + 'POST /security/provider-keys', + 'POST /security/provider-keys', + ]); + expect(calls[0]!.body).toEqual({ + host: 'anthropic', + key: 'sk-ant-secret-value-123', + dryRun: true, + }); + expect(calls[1]!.body).toEqual({ host: 'anthropic', key: 'sk-ant-secret-value-123' }); + expect(out.errors()).toContain('Saved your own Anthropic key.'); + expect(out.printed() + out.errors() + out.terminal()).not.toContain('sk-ant-secret-value-123'); + }); + + it('refuses an empty or multi-word key on stdin before any request', async () => { + quiet(); + vi.spyOn(process.stdin, Symbol.asyncIterator).mockImplementation(async function* () { + yield 'two words\n'; + return undefined; + }); + const calls = serve([]); + await expect(run('models', '--provider', 'openai', '--key-stdin', '--yes')).rejects.toThrow( + 'one API key on one line', + ); + expect(calls).toEqual([]); + }); + + it('applies nothing for --plan and needs --yes without a terminal', async () => { + const out = quiet(); + const calls = serve([ + { dryRun: true, action: 'security.policy', target: 'platform', expectedRevision: 2 }, + ]); + await run('policy', 'all', '--plan'); + expect(calls).toHaveLength(1); + expect(out.printed()).toContain('security.policy'); + calls.length = 0; + await expect(run('policy', 'all')).rejects.toThrow('--yes'); + expect(calls).toHaveLength(0); + }); + + it('reads the provider notice version before accepting it', async () => { + quiet(); + const calls = serve([ + { providerNotice: { version: 3, accepted: false } }, + { dryRun: true, action: 'security.policy', target: 'platform', expectedRevision: 4 }, + { ok: true }, + ]); + await run( + 'models', + '--default', + 'anthropic/claude-opus-5.5', + '--accept-provider-notice', + '--yes', + ); + expect(calls.map(({ method, path }) => `${method} ${path}`)).toEqual([ + 'GET /security/policy', + 'POST /security/policy', + 'POST /security/policy', + ]); + expect(calls[2]!.body).toEqual({ + defaultModel: 'anthropic/claude-opus-5.5', + acceptProviderNoticeVersion: 3, + expectedRevision: 4, + }); + }); + + it('sends the gate switch and the limits as policy changes', async () => { + quiet(); + const calls = serve([ + { dryRun: true, action: 'security.policy', target: 'platform', expectedRevision: 1 }, + { ok: true }, + { dryRun: true, action: 'security.policy', target: 'platform', expectedRevision: 2 }, + { ok: true }, + ]); + await run('public-gate', 'on', '--yes'); + await run('limits', '--scan-timeout', '30', '--yes'); + expect(calls[1]!.body).toEqual({ publicGate: true, expectedRevision: 1 }); + expect(calls[3]!.body).toEqual({ limits: { timeoutMinutes: 30 }, expectedRevision: 2 }); + }); + + it('applies the saved default project cap for --project-caps on', async () => { + quiet(); + const calls = serve([ + { projectDefault: { capsOn: false, monthlyUsd: 40 } }, + { dryRun: true, action: 'security.budget', target: 'platform', expectedRevision: 9 }, + { ok: true }, + ]); + await run('budget', '--project-caps', 'on', '--yes'); + expect(calls[0]).toMatchObject({ method: 'GET', path: '/security/budget' }); + expect(calls[2]!.body).toEqual({ projectDefaultMonthlyUsd: 40, expectedRevision: 9 }); + }); + + it('sets a project limit and says when the project’s own lower cap still wins', async () => { + const out = quiet(); + const calls = serve([ + { dryRun: true, action: 'security.project-budget', target: 'p1', budget: {} }, + { ok: true, budget: { capSource: 'own', capUsd: 40, ceilingUsd: 150 } }, + ]); + await run('budget', '--project', 'p1', '--usd', '150', '--yes'); + expect(calls[1]).toMatchObject({ + path: '/projects/p1/security/budget', + body: { monthlyUsd: 150 }, + }); + expect(out.printed()).toContain("p1's own cap ($40.00) is lower and still applies"); + expect(out.printed()).toContain('void project security budget --usd 150'); + }); + + it('resolves several findings with each one’s own revision, after previewing all of them', async () => { + const out = quiet(); + const calls = serve([ + { finding: { id: 'F-1', revision: 3 } }, + { + dryRun: true, + action: 'security.finding-resolve', + target: { projectId: 'p1', finding: 'F-1' }, + }, + { finding: { id: 'F-2', revision: 5 } }, + { + dryRun: true, + action: 'security.finding-resolve', + target: { projectId: 'p1', finding: 'F-2' }, + }, + { ok: true, id: 'F-1', state: 'resolved' }, + { ok: true, id: 'F-2', state: 'resolved' }, + ]); + await run( + 'resolve', + 'p1', + 'F-1,F-2', + '--reason', + 'accepted-risk', + '--comment', + 'Known', + '--yes', + ); + expect(calls.map(({ method, path }) => `${method} ${path}`)).toEqual([ + 'GET /projects/p1/security/findings/F-1', + 'POST /projects/p1/security/findings/F-1/resolve', + 'GET /projects/p1/security/findings/F-2', + 'POST /projects/p1/security/findings/F-2/resolve', + 'POST /projects/p1/security/findings/F-1/resolve', + 'POST /projects/p1/security/findings/F-2/resolve', + ]); + expect(calls[4]!.body).toEqual({ + reason: 'accepted_risk', + comment: 'Known', + expectedRevision: 3, + }); + expect(calls[5]!.body).toMatchObject({ expectedRevision: 5 }); + expect(out.terminal()).toContain('Platform security resolve completed.'); + }); + + it('changes nothing when one finding fails its preview', async () => { + quiet(); + const calls = serve([ + { finding: { id: 'F-1', revision: 3 } }, + { dryRun: true, action: 'security.finding-resolve', target: 'F-1' }, + Response.json({ error: 'not_found', message: 'Finding not found.' }, { status: 404 }), + ]); + await expect( + run('resolve', 'p1', 'F-1,F-9', '--reason', 'fixed', '--comment', 'ok', '--yes'), + ).rejects.toThrow('Finding not found.'); + expect(calls.filter(({ body }) => body && !body.dryRun)).toHaveLength(0); + }); + + it('reports the findings that changed when a later write fails', async () => { + const out = quiet(); + serve([ + { finding: { revision: 1 } }, + { dryRun: true, action: 'security.finding-reopen', target: 'F-1' }, + { finding: { revision: 2 } }, + { dryRun: true, action: 'security.finding-reopen', target: 'F-2' }, + { ok: true, id: 'F-1' }, + Response.json({ error: 'finding changed', message: 'Finding changed.' }, { status: 409 }), + ]); + await expect( + run('reopen', 'p1', 'F-1,F-2', '--comment', 'again', '--yes'), + ).rejects.toMatchObject({ code: 'partial_failure' }); + const printed = out.printed(); + expect(printed).toContain('F-1'); + expect(printed).toContain('Finding changed.'); + }); + + it('comments without reading a revision', async () => { + quiet(); + const calls = serve([ + { dryRun: true, action: 'security.finding-comment', target: {} }, + { ok: true, id: 'F-1' }, + ]); + await run('comment', 'p1', 'F-1', 'Please look', '--yes'); + expect(calls.map(({ method }) => method)).toEqual(['POST', 'POST']); + expect(calls[1]!.body).toEqual({ text: 'Please look' }); + }); + + it('shows several findings and reads the lists with their filters', async () => { + const out = quiet(); + const calls = serve([ + { finding: { id: 'F-1' } }, + { finding: { id: 'F-2' } }, + { findings: [], total: 0 }, + ]); + await run('show', 'p1', 'F-1,F-2', '--json'); + expect(JSON.parse(out.printed())).toEqual({ + findings: [{ finding: { id: 'F-1' } }, { finding: { id: 'F-2' } }], + }); + await run('findings', '--urgent', '--project', 'acme'); + expect(calls[2]).toMatchObject({ + path: '/security/findings', + query: '?project=acme&urgent=true', + }); + }); + + it('asks before a rescan and names the model and the most it can cost', async () => { + const out = quiet(); + const calls = serve([ + { + dryRun: true, + action: 'security.rescan', + target: 'p1', + deploymentId: 'dpl_9a1d', + alreadyScanned: true, + model: 'anthropic/claude-opus-5.5', + worstCaseUsd: 12, + }, + { ok: true, scanId: 'scan-1' }, + ]); + await run('rescan', 'p1', '--yes'); + expect(out.errors()).toContain( + 'Live deployment dpl_9a1d was already scanned. Run a full scan with anthropic/claude-opus-5.5? This reviews the whole app. It can cost up to $12.00.', + ); + expect(calls[1]).toMatchObject({ path: '/projects/p1/security/scans', body: {} }); + }); + + it('asks before a backfill and says how many and the most it can cost', async () => { + const out = quiet(); + const calls = serve([ + { + dryRun: true, + action: 'security.backfill', + target: 'platform', + projects: 53, + willQueue: 50, + remaining: 3, + worstCaseUsd: 40, + }, + { ok: true, queued: [], skipped: {}, remaining: 3 }, + ]); + await run('backfill', '--yes'); + expect(out.errors()).toContain( + 'Scan 50 live deployments that were never scanned? Together they can cost up to $40.00. 3 more wait for the next backfill.', + ); + expect(calls[1]).toMatchObject({ method: 'POST', path: '/security/backfill', body: {} }); + }); + + it('does not ask or queue when nothing needs a backfill', async () => { + const out = quiet(); + const calls = serve([ + { dryRun: true, action: 'security.backfill', target: 'platform', willQueue: 0 }, + ]); + await run('backfill', '--yes'); + expect(calls).toHaveLength(1); + expect(out.errors()).toContain('Nothing to backfill.'); + }); + + it('names the never-scanned deployments whose code is no longer stored', async () => { + const out = quiet(); + const calls = serve([ + { + dryRun: true, + action: 'security.backfill', + target: 'platform', + willQueue: 0, + noStoredCode: 2, + }, + ]); + await run('backfill', '--yes'); + expect(calls).toHaveLength(1); + expect(out.errors()).toContain('Nothing to backfill.'); + expect(out.errors()).not.toContain('already has a scan'); + expect(out.errors()).toContain( + '2 never-scanned live deployments have no stored code, so they cannot be scanned. Deploy those projects again.', + ); + }); + + it('asks for the client asset pass on a rescan, and refuses it on an old platform (M31)', async () => { + const out = quiet(); + const calls = serve([ + { + dryRun: true, + action: 'security.rescan', + target: 'p1', + deploymentId: 'dpl_9a1d', + model: 'm', + clientAssets: true, + }, + { ok: true, scanId: 'scan-1', clientAssets: true }, + { dryRun: true, action: 'security.rescan', target: 'p1', deploymentId: 'dpl_9a1d' }, + ]); + await run('rescan', 'p1', '--client-assets', '--yes'); + expect(calls[0]!.body).toEqual({ clientAssets: true, dryRun: true }); + expect(calls[1]).toMatchObject({ body: { clientAssets: true } }); + expect(out.errors()).toContain('and the sources of its client bundles'); + await expect(run('rescan', 'p1', '--client-assets', '--yes')).rejects.toThrow( + 'cannot read client bundle sources yet', + ); + expect(calls).toHaveLength(3); + }); + + it('exports every matching finding as one SARIF log with --format sarif (M31)', async () => { + const out = quiet(); + const row = (id: string, project: string) => ({ + id, + project, + verdict: 'confirmed', + severity: 'high', + state: 'open', + title: `title ${id}`, + category: 'xss', + file: 'src/a.ts', + line: 2, + }); + const calls = serve([ + { findings: [row('F-1', 'acme')], page: 1, limit: 100, total: 2, totalPages: 2 }, + { findings: [row('F-1', 'beta')], page: 2, limit: 100, total: 2, totalPages: 2 }, + ]); + await run('findings', '--format', 'sarif', '--urgent'); + expect(calls.map(({ query }) => query)).toEqual([ + '?urgent=true&page=1&limit=100', + '?urgent=true&page=2&limit=100', + ]); + const log = JSON.parse(out.printed()); + expect( + log.runs[0].results.map( + (result: { partialFingerprints: Record }) => + result.partialFingerprints['voidFinding/v1'], + ), + ).toEqual(['acme/F-1', 'beta/F-1']); + expect(() => run('findings', '--format', 'csv')).toThrow('--format must be sarif'); + expect(() => run('findings', '--format', 'sarif', '--page', '2')).toThrow( + 'drop --page and --limit', + ); + expect(() => run('findings', '--format', 'sarif', '--json')).toThrow( + 'Use --format sarif or --json, not both.', + ); + }); + + it('does not rescan for --plan', async () => { + quiet(); + const calls = serve([ + { dryRun: true, action: 'security.rescan', target: 'p1', deploymentId: 'dpl_1', model: 'm' }, + ]); + await run('rescan', 'p1', '--plan'); + expect(calls).toHaveLength(1); + }); + + it('runs the probe once, without a preview or --yes', async () => { + const out = quiet(); + const calls = serve([{ ok: true, checks: [] }]); + await run('probe'); + expect(calls).toHaveLength(1); + expect(calls[0]).toMatchObject({ method: 'POST', path: '/security/probe', body: {} }); + expect(out.printed()).toContain('Ok: true'); + }); + + it('sets a project model, accepting the notice at the current version', async () => { + quiet(); + const calls = serve([ + { providerNotice: { version: 2 } }, + { dryRun: true, action: 'security.project-model', target: 'p1' }, + { ok: true }, + ]); + await run('model', 'p1', 'anthropic/claude-opus-5.5', '--accept-provider-notice', '--yes'); + expect(calls[2]!.body).toEqual({ + model: 'anthropic/claude-opus-5.5', + acceptProviderNoticeVersion: 2, + }); + }); + + it('cancels a scan and bypasses a request with a preview first', async () => { + quiet(); + const calls = serve([ + { dryRun: true, action: 'security.scan-cancel', target: 'scan-1' }, + { ok: true, canceled: 1 }, + { dryRun: true, action: 'security.public-request-bypass', target: 'p1' }, + { ok: true, project: { state: 'ready' } }, + ]); + await run('cancel', 'scan-1', '--yes'); + await run('bypass', 'p1', '--reason', 'launch today', '--yes'); + expect(calls[1]).toMatchObject({ path: '/security/scans/scan-1/cancel', body: {} }); + expect(calls[3]).toMatchObject({ + path: '/projects/p1/security/public-request/bypass', + body: { reason: 'launch today' }, + }); + }); + + it('does not claim success while a public request is still open', async () => { + const out = quiet(); + serve([ + { finding: { revision: 1 } }, + { dryRun: true, action: 'security.finding-resolve', target: 'F-1' }, + { ok: true, id: 'F-1', publicRequest: { state: 'held_findings' } }, + ]); + await run('resolve', 'p1', 'F-1', '--reason', 'fixed', '--comment', 'ok', '--yes'); + expect(out.terminal()).not.toContain('✓'); + }); + + it('names the upgrade command when security audits are not installed', async () => { + quiet(); + serve([ + Response.json( + { + error: 'platform capability unavailable', + capability: 'securityAudits', + message: 'This Void platform does not enable securityAudits.', + }, + { status: 501 }, + ), + ]); + await expect(run('probe')).rejects.toThrow( + 'Security audits are not installed. Run: void platform upgrade --security-audits', + ); + }); +}); diff --git a/packages/void/test/unit/platform-args.test.ts b/packages/void/test/unit/platform-args.test.ts index b34e6be84..dea05655b 100644 --- a/packages/void/test/unit/platform-args.test.ts +++ b/packages/void/test/unit/platform-args.test.ts @@ -104,6 +104,22 @@ describe('platform args', () => { ); } }); + it('allows security audits only in install, upgrade, and repair', () => { + for (const command of ['install', 'upgrade', 'repair']) { + expect(parsePlatformArgs([command, '--security-audits'])).toMatchObject({ + securityAudits: true, + }); + expect(parsePlatformArgs([command])).not.toHaveProperty('securityAudits'); + } + // It needs no dedicated zone, unlike custom domains. + expect(parsePlatformArgs(['install', '--security-audits', '--workers-dev'])).toMatchObject({ + securityAudits: true, + workersDev: true, + }); + for (const command of ['enable', 'disable', 'rollback', 'uninstall']) { + expect(() => parsePlatformArgs([command, '--security-audits'])).toThrow(); + } + }); it('accepts replacement login settings only in repair', () => { expect(parsePlatformArgs(['repair', 'team', '--auth-config', 'auth.json'])).toEqual({ subcommand: 'repair', diff --git a/packages/void/test/unit/platform-installer.test.ts b/packages/void/test/unit/platform-installer.test.ts index 29a50dbb8..c93703e56 100644 --- a/packages/void/test/unit/platform-installer.test.ts +++ b/packages/void/test/unit/platform-installer.test.ts @@ -783,6 +783,74 @@ describe('platform installer', () => { }, ); + it.each([true, false])( + 'binds the security scan scheduler only when the runtime ships it (securityAudits: %s)', + async (securityAudits) => { + useRegistryDirectory(); + const plan = await createPlatformInstallPlan( + planningClient(), + { + accountId: 'account', + applicationDomain: '', + zoneName: '', + workersDev: true, + controlPlaneDomain: '', + dedicatedZone: false, + displayName: 'Audits', + installationSlug: 'audits', + }, + null, + ); + const current = resolvePlatformRuntime(getPlatformRuntimeDirectory()); + const { securityAudits: _securityAudits, ...olderManifest } = current.manifest; + let index = 0; + const create = async (_account: string, name: string) => ({ + id: `resource-${index++}`, + name, + }); + const configs: Array> = []; + await installPlatform(plan, freshSecrets(), null, { + claimDatabase, + acquireDatabaseLifecycleLock, + client: { + ...unusedClient(), + createAiGateway: create, + createKvNamespace: create, + createR2Bucket: create, + createQueue: create, + createDispatchNamespace: create, + createHyperdrive: create, + }, + deployWorker: async (config) => { + configs.push(config); + }, + prepareDatabase, + revalidateBeforeWorkerDeploy: async () => {}, + runtime: { + ...current, + manifest: securityAudits ? { ...olderManifest, securityAudits: 1 } : olderManifest, + }, + verifyHealth: async () => {}, + }); + const apiConfigs = configs.filter( + (config) => config.name === plan.deployment.resources.apiWorker, + ); + expect(apiConfigs.length).toBeGreaterThan(0); + for (const apiConfig of apiConfigs) { + const bindings = + (apiConfig.durable_objects as { bindings?: Array<{ name: string }> } | undefined) + ?.bindings ?? []; + const tags = ((apiConfig.migrations ?? []) as Array<{ tag: string }>).map( + (migration) => migration.tag, + ); + expect(bindings.some((binding) => binding.name === 'SECURITY_SCAN_SCHEDULER')).toBe( + securityAudits, + ); + expect(tags.includes('security-audits-v1')).toBe(securityAudits); + } + }, + ); + it('lifts a left-over uninstall fence before traffic opens', async () => { useRegistryDirectory(); const plan = await createPlatformInstallPlan( diff --git a/packages/void/test/unit/platform-management-upgrade.test.ts b/packages/void/test/unit/platform-management-upgrade.test.ts index 9f14cec02..3b6470e94 100644 --- a/packages/void/test/unit/platform-management-upgrade.test.ts +++ b/packages/void/test/unit/platform-management-upgrade.test.ts @@ -267,7 +267,9 @@ import { writePendingInstallationSecrets, } from '../../src/cli/platform-registry.ts'; -const upgrade = (overrides: { plan?: boolean; yes?: boolean; customDomains?: true } = {}) => +const upgrade = ( + overrides: { plan?: boolean; yes?: boolean; customDomains?: true; securityAudits?: true } = {}, +) => runInstalledPlatformCommand({ subcommand: 'upgrade', selector: state.manifest!.id, @@ -296,6 +298,49 @@ describe('installed platform upgrade', () => { ).toBe(`void platform upgrade installation --storage-location ${storageLocation} --yes`); }, ); + it('replays --security-audits in the upgrade and repair resume commands', () => { + for (const subcommand of ['upgrade', 'repair'] as const) { + expect( + platformLifecycleResumeCommand( + { subcommand, selector: '', plan: false, yes: true, runtime: '', securityAudits: true }, + 'installation', + ), + ).toBe(`void platform ${subcommand} installation --security-audits --yes`); + } + }); + describe('allowing security audits', () => { + it('passes the flag to the plan and omits it when not given', async () => { + await upgrade({ securityAudits: true, plan: true }); + expect(vi.mocked(createPlatformInstallPlan).mock.calls.at(-1)![1]).toMatchObject({ + securityAudits: true, + }); + await upgrade({ plan: true }); + expect(vi.mocked(createPlatformInstallPlan).mock.calls.at(-1)![1]).not.toHaveProperty( + 'securityAudits', + ); + }); + + it('refuses a runtime without the scanner before anything changes', async () => { + const planner = vi.mocked(createPlatformInstallPlan).getMockImplementation()!; + vi.mocked(createPlatformInstallPlan).mockImplementationOnce(async (...args) => { + const plan = await planner(...args); + return { + ...plan, + deployment: createPlatformDeploymentManifest({ + ...plan.deployment, + capabilities: { ...plan.deployment.capabilities, securityAudits: true }, + }), + }; + }); + const { securityAudits: _omitted, ...manifest } = state.runtime!.manifest; + state.runtime = { ...state.runtime!, manifest }; + await expect(upgrade({ securityAudits: true })).rejects.toThrow( + 'does not include security audits', + ); + expect(installPlatform).not.toHaveBeenCalled(); + expect(state.events.filter((event) => event.startsWith('put:'))).toEqual([]); + }); + }); it('prints an exact rollback resume command with quoted custom runtime paths', () => { expect( platformLifecycleResumeCommand( diff --git a/packages/void/test/unit/platform-management.test.ts b/packages/void/test/unit/platform-management.test.ts index 237830778..c53a33416 100644 --- a/packages/void/test/unit/platform-management.test.ts +++ b/packages/void/test/unit/platform-management.test.ts @@ -18,7 +18,7 @@ import { type PlatformInstallationManifest, type ResourceOwnership, } from '@void/platform'; -import { note } from '@voidzero-dev/vite-plus-prompts'; +import { log, note } from '@voidzero-dev/vite-plus-prompts'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vite-plus/test'; import { printSuccess } from '../../src/cli/output.ts'; import { @@ -1936,3 +1936,118 @@ describe('platform lifecycle management', () => { expect(listInstallationManifests()[0]?.status).toBe('disabled'); }); }); + +describe('uninstall with security audits', () => { + function withSecurityAudits(securityAudits: boolean) { + const manifest = installedManifest(); + const installed = { + ...manifest, + deployment: { + ...manifest.deployment, + capabilities: { ...manifest.deployment.capabilities, securityAudits }, + ...(securityAudits ? { schemaVersion: 7 as const } : {}), + }, + }; + persistInstallation(installed, directories); + return installed; + } + + it('removes the scanner after traffic stops and before any resource is deleted', async () => { + const manifest = withSecurityAudits(true); + const fake = client(manifest); + const seen: Array<{ disabledWrites: number; deleted: number }> = []; + const deleteSecurityScanner = vi.fn(async () => { + seen.push({ disabledWrites: fake.disabledWrites.length, deleted: fake.deleted.length }); + return { deleted: ['gate', 'controller'] as Array<'gate' | 'controller'>, kept: [] }; + }); + await uninstallPlatform(fake, manifest, uninstallArgs, { + ...uninstallDependencies, + deleteSecurityScanner, + }); + expect(deleteSecurityScanner).toHaveBeenCalledTimes(1); + expect(deleteSecurityScanner).toHaveBeenCalledWith( + expect.objectContaining({ id: manifest.id }), + ); + expect(seen).toEqual([{ disabledWrites: 1, deleted: 0 }]); + expect(listInstallationManifests()[0]?.status).toBe('uninstalled'); + }); + + it('does not touch the scanner when security audits were never allowed', async () => { + const manifest = withSecurityAudits(false); + const fake = client(manifest); + const deleteSecurityScanner = vi.fn(); + await uninstallPlatform(fake, manifest, uninstallArgs, { + ...uninstallDependencies, + deleteSecurityScanner, + }); + expect(deleteSecurityScanner).not.toHaveBeenCalled(); + expect(listInstallationManifests()[0]?.status).toBe('uninstalled'); + }); + + it('refuses before any change when the scanner cannot be removed from here', async () => { + const manifest = withSecurityAudits(true); + const fake = client(manifest); + await expect( + uninstallPlatform(fake, manifest, uninstallArgs, uninstallDependencies), + ).rejects.toThrow('security scanner cannot be removed'); + expect(fake.disabledWrites).toEqual([]); + expect(fake.deleted).toEqual([]); + expect(listInstallationManifests()[0]?.status).toBe('installed'); + }); + + it('fails the uninstall so it can be run again when the scanner delete fails', async () => { + const manifest = withSecurityAudits(true); + const fake = client(manifest); + await expect( + uninstallPlatform(fake, manifest, uninstallArgs, { + ...uninstallDependencies, + deleteSecurityScanner: async () => { + throw new Error('Cloudflare API error: forbidden (HTTP 403)'); + }, + }), + ).rejects.toThrow('HTTP 403'); + expect(fake.deleted).toEqual([]); + expect(listInstallationManifests()[0]?.status).toBe('failed'); + }); + + it('names a scanner object of another installation and keeps it', async () => { + const warn = vi.spyOn(log, 'warn').mockImplementation(() => {}); + const manifest = withSecurityAudits(true); + await uninstallPlatform(client(manifest), manifest, uninstallArgs, { + ...uninstallDependencies, + deleteSecurityScanner: async () => ({ + deleted: [], + kept: ['security scanner gate void-security-scanner-gate-abc'], + }), + }); + expect(warn).toHaveBeenCalledWith( + 'Kept security scanner gate void-security-scanner-gate-abc: it does not belong to this installation.', + ); + warn.mockRestore(); + }); + + it('lists the scanner in the uninstall plan only when it applies', async () => { + for (const [securityAudits, listed] of [ + [true, true], + [false, false], + ] as const) { + vi.mocked(note).mockClear(); + const manifest = withSecurityAudits(securityAudits); + await uninstallPlatform( + client(manifest), + manifest, + { ...uninstallArgs, plan: true }, + { ...uninstallDependencies, deleteSecurityScanner: vi.fn() }, + ); + const plan = vi + .mocked(note) + .mock.calls.map(([text]) => String(text)) + .join('\n'); + expect( + plan.includes( + 'Delete the security scanner Worker, its container applications, and the scanner images it copied.', + ), + ).toBe(listed); + } + }); +}); diff --git a/packages/void/test/unit/platform-plan.test.ts b/packages/void/test/unit/platform-plan.test.ts index a8f2d6b4b..f921ad10b 100644 --- a/packages/void/test/unit/platform-plan.test.ts +++ b/packages/void/test/unit/platform-plan.test.ts @@ -589,6 +589,42 @@ describe('platform installation planning', () => { ); }); + it('allows security audits with a schema 7 document and no resource action', async () => { + const off = await createPlatformInstallPlan(client(), input, null); + expect(off.deployment.capabilities.securityAudits).toBe(false); + const on = await createPlatformInstallPlan(client(), { ...input, securityAudits: true }, null); + expect(on.deployment).toMatchObject({ + capabilities: { securityAudits: true }, + schemaVersion: 7, + }); + expect(on.actions).toEqual(off.actions); + + // An existing installation takes the flag on upgrade or repair without a drift error. + const recorded = manifestFor(off); + for (const options of [{}, { allowRuntimeLogsChange: true }]) { + const upgraded = await createPlatformInstallPlan( + client(), + { ...input, securityAudits: true }, + recorded, + options, + ); + expect(upgraded.deployment).toEqual(on.deployment); + } + // Omitted keeps the recorded value; the flag is never switched off here. + const recordedOn = manifestFor(on); + expect((await createPlatformInstallPlan(client(), input, recordedOn)).deployment).toEqual( + on.deployment, + ); + // Other drift still stops the run. + await expect( + createPlatformInstallPlan( + client(), + { ...input, displayName: 'Other', securityAudits: true }, + recorded, + ), + ).rejects.toThrow('--resume inputs do not match'); + }); + it('enables managed Sandbox for current installs and upgrades without adding a resource action', async () => { const legacy = legacyInstallation(); expect(legacy.deployment.capabilities.sandbox).toBe(false); diff --git a/packages/void/test/unit/platform-plans-config.test.ts b/packages/void/test/unit/platform-plans-config.test.ts index 56e04bec9..efb32211c 100644 --- a/packages/void/test/unit/platform-plans-config.test.ts +++ b/packages/void/test/unit/platform-plans-config.test.ts @@ -551,3 +551,144 @@ describe('platform config plans AI logging defaults', () => { expect(output()).toContain('AI logging publish pending: 4 projects remaining'); }); }); + +describe('platform config plans security scan caps', () => { + const catalog = { ...createDefaultPlanCatalog('free'), revision: 7 }; + + function platform(answer: (url: string, body?: Record) => unknown) { + vi.stubGlobal( + 'fetch', + vi.fn(async (input: string | URL | Request, init?: RequestInit) => { + const url = input.toString(); + const body = init?.body ? JSON.parse(init.body as string) : undefined; + calls.push({ url, body }); + return Response.json(answer(url, body)); + }), + ); + } + + function output() { + return vi + .mocked(console.log) + .mock.calls.map((call) => String(call[0])) + .join('\n'); + } + + it.each([ + [['plans', 'set', 'pro', '--security-cap', '50'], 50], + [['plans', 'set', 'pro', '--security-cap', '12.50'], 12.5], + [['plans', 'set', 'pro', '--security-cap', 'none'], 'none'], + [['plans', 'add', 'team', '--copy', 'pro', '--security-cap', 'inherit'], 'inherit'], + ])('reads %j', (args, expected) => { + expect(parsePlatformPlansArgs(args).securityCap).toBe(expected); + }); + + it.each([ + [['plans', 'set', 'pro', '--security-cap', '12.345'], 'at most two decimals'], + [['plans', 'set', 'pro', '--security-cap', '2000000'], 'at most two decimals'], + [['plans', 'set', 'pro', '--security-cap', 'lots'], 'at most two decimals'], + [ + ['plans', 'remove', 'pro', '--security-cap', '5'], + '--security-cap is only valid for add or set', + ], + ])('refuses %j', (args, message) => { + expect(() => parsePlatformPlansArgs(args)).toThrow(message); + }); + + it('refuses the flag before any change on a platform without plan caps', async () => { + platform(() => ({ catalog, accounts: [] })); + await expect( + runPlatformPlansConfig( + parsePlatformPlansArgs(['plans', 'set', 'pro', '--security-cap', '50', '--yes']), + ), + ).rejects.toThrow('does not support plan security scan caps'); + expect(calls.filter((call) => call.body)).toHaveLength(0); + }); + + it('sends the cap alone and previews it from the caps the dry run read', async () => { + platform((_url, body) => + body + ? { + dryRun: true, + action: 'plans.set', + target: 'pro', + expectedRevision: 7, + catalog: { ...catalog, revision: 8 }, + affectedAccounts: 3, + // Newer than the cached listing, which has no entry for pro. + securityCaps: { caps: { pro: 5000 }, capsBefore: { pro: null } }, + } + : { catalog, accounts: [], securityCaps: {} }, + ); + await runPlatformPlansConfig( + parsePlatformPlansArgs(['plans', 'set', 'pro', '--security-cap', '50', '--plan']), + ); + expect(calls.at(-1)?.body).toEqual({ securityCap: 50, dryRun: true }); + expect(output()).toContain('Security scan cap: no cap → $50.00 / month'); + }); + + it('merges the flag into a plan file and checks the file field', async () => { + platform((_url, body) => + body + ? { dryRun: true, expectedRevision: 7, catalog, affectedAccounts: 0 } + : { + catalog, + accounts: [], + securityCaps: {}, + }, + ); + const file = join(directory, 'plan.json'); + await writeFile(file, JSON.stringify({ name: 'Pro', securityCap: 'none' })); + await runPlatformPlansConfig( + parsePlatformPlansArgs(['plans', 'set', 'pro', '--file', file, '--plan']), + ); + expect(calls.at(-1)?.body).toEqual({ name: 'Pro', securityCap: 'none', dryRun: true }); + await writeFile(file, JSON.stringify({ securityCap: '50' })); + await expect( + runPlatformPlansConfig( + parsePlatformPlansArgs(['plans', 'set', 'pro', '--file', file, '--plan']), + ), + ).rejects.toThrow('securityCap must be a USD amount'); + }); + + it('offers the cap in the interactive picker', async () => { + vi.stubGlobal('process', { ...process, stdin: { ...process.stdin, isTTY: true } }); + platform((_url, body) => + body?.dryRun + ? { dryRun: true, expectedRevision: 7, catalog, affectedAccounts: 0 } + : body + ? { catalog, reconciliation: { complete: true, processed: 0 } } + : { catalog, accounts: [], securityCaps: { pro: 2500 } }, + ); + vi.mocked(select).mockResolvedValueOnce('securityCap').mockResolvedValueOnce('amount'); + vi.mocked(text).mockResolvedValueOnce('40'); + vi.mocked(confirm).mockResolvedValueOnce(true); + await runPlatformPlansConfig(parsePlatformPlansArgs(['plans', 'set', 'pro'])); + expect(select).toHaveBeenNthCalledWith( + 1, + expect.objectContaining({ + options: expect.arrayContaining([ + { value: 'securityCap', label: 'Security scan cap: $25.00 / month' }, + ]), + }), + ); + expect(text).toHaveBeenCalledWith(expect.objectContaining({ initialValue: '25' })); + expect(calls.at(-1)?.body).toEqual({ securityCap: 40, expectedRevision: 7 }); + }); + + it('shows the plan cap', async () => { + platform((url) => + url.endsWith('/config/plans') + ? { catalog, accounts: [], securityCaps: { pro: 1250 } } + : { + catalogRevision: 7, + default: false, + plan: catalog.plans.find((plan) => plan.id === 'pro'), + accounts: 2, + securityCap: 1250, + }, + ); + await runPlatformPlansConfig(parsePlatformPlansArgs(['plans', 'show', 'pro'])); + expect(output()).toContain('Security scan cap: $12.50 / month'); + }); +}); diff --git a/packages/void/test/unit/platform-rollback.test.ts b/packages/void/test/unit/platform-rollback.test.ts index e36da31d5..bb696a8ff 100644 --- a/packages/void/test/unit/platform-rollback.test.ts +++ b/packages/void/test/unit/platform-rollback.test.ts @@ -200,6 +200,48 @@ describe('platform post-success rollback', () => { ), ).not.toThrow(); }); + it('blocks rollback across the release that adds the security scan scheduler', () => { + const target = runtime({ + digest: 'a'.repeat(64), + migrations: [firstMigration], + platformVersion: '1.0.0', + schemaDigest: 'c'.repeat(64), + }); + const source = runtime({ + digest: 'b'.repeat(64), + migrations: [firstMigration, secondMigration], + platformVersion: '1.1.0', + rollbackSafeFrom: [{ platformVersion: '1.0.0', schemaDigest: 'c'.repeat(64) }], + schemaDigest: 'd'.repeat(64), + }); + const auditSource = { ...source, manifest: { ...source.manifest, securityAudits: 1 as const } }; + const auditTarget = { ...target, manifest: { ...target.manifest, securityAudits: 1 as const } }; + + expect(() => + assertPlatformRollbackCompatibility(installed(auditSource), target, auditSource), + ).toThrow('Roll forward'); + const enabled = installed(source); + expect(() => + assertPlatformRollbackCompatibility( + { + ...enabled, + deployment: { + ...enabled.deployment, + capabilities: { ...enabled.deployment.capabilities, securityAudits: true }, + schemaVersion: 7, + }, + }, + target, + source, + ), + ).toThrow('predates security audits'); + expect(() => + assertPlatformRollbackCompatibility(installed(auditSource), auditTarget, auditSource), + ).not.toThrow(); + expect(() => + assertPlatformRollbackCompatibility(installed(source), target, source), + ).not.toThrow(); + }); it('blocks rollback below the installed ownership-aware usage protocol', () => { const target = runtime({ digest: 'a'.repeat(64), diff --git a/packages/void/test/unit/platform-security-audits.test.ts b/packages/void/test/unit/platform-security-audits.test.ts new file mode 100644 index 000000000..6a3ec482b --- /dev/null +++ b/packages/void/test/unit/platform-security-audits.test.ts @@ -0,0 +1,326 @@ +import { createHash } from 'node:crypto'; +import { + createPlatformDeploymentManifest, + createPlatformInstallationManifest, +} from '@void/platform'; +import { describe, expect, it } from 'vite-plus/test'; +import { PlatformCloudflareApiError } from '../../src/cli/platform-cloudflare.ts'; +import { + assertPlatformSecurityAuditsSupported, + deletePlatformSecurityScanner, + securityScannerNames, +} from '../../src/cli/platform-security-audits.ts'; + +const INSTALLATION = 'example-a1b2c3d4'; + +function manifest(securityAudits: boolean) { + return createPlatformInstallationManifest({ + account: { id: 'account', name: 'Account' }, + createdAt: '2026-09-14T00:00:00.000Z', + deployment: createPlatformDeploymentManifest({ + application: { baseDomain: 'apps.example.com', zoneName: 'example.com' }, + capabilities: { securityAudits }, + controlPlane: { apiHostname: 'api.example.com' }, + displayName: 'Example', + installationSlug: 'example', + }), + id: INSTALLATION, + ownershipNonce: '0123456789abcdef0123456789abcdef', + platformVersion: '1.0.0', + }); +} + +const marker = (installation = INSTALLATION) => JSON.stringify({ protocol: 1, installation }); +const owner = (installation = INSTALLATION) => [ + { type: 'plain_text', name: '__VOID_SECURITY_SCANNER_OWNER', text: marker(installation) }, +]; + +/** A Cloudflare account holding the scanner: gate, controller Worker and container application. */ +function account( + options: { + gate?: 'ours' | 'foreign' | 'missing'; + controller?: 'ours' | 'foreign' | 'missing'; + application?: 'ours' | 'other-namespace' | 'missing'; + /** The Engine A container application and its copied image (M13b). */ + engineA?: boolean; + failOn?: string; + /** Registry answers for the image manifest HEAD and the layer cleanup. */ + headStatus?: number; + gcStatus?: number; + } = {}, +) { + const { + gate = 'ours', + controller = 'ours', + application = 'ours', + engineA = false, + failOn, + headStatus = 200, + gcStatus = 202, + } = options; + const names = securityScannerNames(INSTALLATION); + const calls: Array = []; + const registryCalls: Array = []; + const engineRepo = `account/${names.engines['engine-a'].repository}`; + let engineImage = engineA; + const registryFetch = async (url: string, init?: RequestInit): Promise => { + const method = init?.method ?? 'GET'; + const path = new URL(url).pathname; + registryCalls.push(`${method} ${path}`); + if (path === `/v2/${engineRepo}/tags/list`) { + return engineImage + ? Response.json({ tags: ['sha256-aaa'] }) + : new Response(null, { status: 404 }); + } + if (path === `/v2/${engineRepo}/manifests/sha256-aaa` && method === 'HEAD') { + return new Response(null, { + status: headStatus, + headers: headStatus === 200 ? { 'docker-content-digest': 'sha256:aaa' } : {}, + }); + } + if (path === `/v2/${engineRepo}/manifests/sha256:aaa` && method === 'DELETE') { + engineImage = false; + return new Response(null, { status: 202 }); + } + if (path === '/v2/gc/layers') { + return new Response(null, { status: gcStatus }); + } + return new Response(null, { status: 404 }); + }; + const gatePath = `/accounts/account/workers/dispatch/namespaces/${manifest(true).deployment.resources.dispatchNamespace}/scripts/${names.gate}`; + const workerPath = `/accounts/account/workers/scripts/${names.worker}`; + const request = async (path: string, init?: RequestInit): Promise => { + const method = init?.method ?? 'GET'; + calls.push(`${method} ${path}`); + if (failOn && `${method} ${path}`.includes(failOn)) { + throw new PlatformCloudflareApiError('forbidden', 403, path); + } + const missing = () => new PlatformCloudflareApiError('not found', 404, path); + if (path === gatePath) { + if (gate === 'missing') { + throw missing(); + } + return {} as T; + } + if (path === `${gatePath}/bindings`) { + return (gate === 'ours' ? owner() : owner('someone-else')) as T; + } + if (path === `${workerPath}/settings`) { + if (controller === 'missing') { + throw missing(); + } + return { + bindings: [ + ...(controller === 'ours' ? owner() : owner('someone-else')), + { type: 'durable_object_namespace', name: 'SCANNER', namespace_id: 'ns-1' }, + { type: 'durable_object_namespace', name: 'SCANNER_ENGINE_A', namespace_id: 'ns-a' }, + { type: 'durable_object_namespace', name: 'SCANNER_ENGINE_C', namespace_id: 'ns-c' }, + ], + } as T; + } + if (path === '/accounts/account/containers/registries/registry.cloudflare.com/credentials') { + return { username: 'v1', password: 'registry-password' } as T; + } + if (path.startsWith('/accounts/account/containers/applications?name=')) { + const name = decodeURIComponent(path.slice(path.indexOf('=') + 1)); + if (name === names.engines['engine-a'].application) { + return ( + engineA ? [{ id: 'app-a', name, durable_objects: { namespace_id: 'ns-a' } }] : [] + ) as T; + } + if (name !== names.application) { + return [] as T; + } + return ( + application === 'missing' + ? [] + : [ + { + id: 'app-1', + name: names.application, + durable_objects: { namespace_id: application === 'ours' ? 'ns-1' : 'ns-other' }, + }, + ] + ) as T; + } + if (method === 'DELETE') { + return null as T; + } + throw new Error(`unexpected ${method} ${path}`); + }; + return { request, calls, names, gatePath, workerPath, registryFetch, registryCalls }; +} + +describe('security scanner names', () => { + it('match the platform API, which derives them from the installation id', () => { + const suffix = createHash('sha256') + .update(`void-security-scanner:${INSTALLATION}`) + .digest('hex') + .slice(0, 12); + expect(securityScannerNames(INSTALLATION)).toEqual({ + worker: `void-security-scanner-${suffix}`, + application: `void-security-scanner-${suffix}`, + gate: `void-security-scanner-gate-${suffix}`, + engines: { + 'engine-a': { + application: `void-security-scanner-engine-a-${suffix}`, + repository: `void-security-scanner-engine-a-${suffix}`, + }, + 'engine-c': { + application: `void-security-scanner-engine-c-${suffix}`, + repository: `void-security-scanner-engine-c-${suffix}`, + }, + }, + }); + expect(securityScannerNames('other').worker).not.toBe( + securityScannerNames(INSTALLATION).worker, + ); + }); +}); + +describe('security audits runtime guard', () => { + const deployment = (securityAudits: boolean) => manifest(securityAudits).deployment; + it('refuses the capability on a runtime without the scanner', () => { + expect(() => assertPlatformSecurityAuditsSupported(deployment(true), {})).toThrow( + 'does not include security audits', + ); + expect(() => + assertPlatformSecurityAuditsSupported(deployment(true), { securityAudits: 1 }), + ).not.toThrow(); + expect(() => assertPlatformSecurityAuditsSupported(deployment(false), {})).not.toThrow(); + }); +}); + +describe('deleting the security scanner', () => { + it('makes no Cloudflare call when security audits were never allowed', async () => { + const cloudflare = account(); + expect(await deletePlatformSecurityScanner(cloudflare, manifest(false))).toEqual({ + deleted: [], + kept: [], + }); + expect(cloudflare.calls).toEqual([]); + }); + + it('deletes the gate, then the container application, then the controller', async () => { + const cloudflare = account(); + const result = await deletePlatformSecurityScanner( + cloudflare, + manifest(true), + cloudflare.registryFetch, + ); + expect(result).toEqual({ deleted: ['gate', 'container application', 'controller'], kept: [] }); + expect(cloudflare.calls.filter((call) => call.startsWith('DELETE'))).toEqual([ + `DELETE ${cloudflare.gatePath}`, + 'DELETE /accounts/account/containers/applications/app-1', + `DELETE ${cloudflare.workerPath}`, + ]); + }); + + it('also removes the engine container applications and the copied engine images', async () => { + const cloudflare = account({ engineA: true }); + const result = await deletePlatformSecurityScanner( + cloudflare, + manifest(true), + cloudflare.registryFetch, + ); + expect(result).toEqual({ + deleted: ['gate', 'container application', 'controller', 'scanner images'], + kept: [], + }); + expect(cloudflare.calls.filter((call) => call.startsWith('DELETE'))).toEqual([ + `DELETE ${cloudflare.gatePath}`, + 'DELETE /accounts/account/containers/applications/app-1', + 'DELETE /accounts/account/containers/applications/app-a', + `DELETE ${cloudflare.workerPath}`, + ]); + const repo = cloudflare.names.engines['engine-a'].repository; + expect(cloudflare.registryCalls).toContain(`DELETE /v2/account/${repo}/manifests/sha256:aaa`); + expect(cloudflare.registryCalls.at(-1)).toBe('PUT /v2/gc/layers'); + }); + + it('fails, so it can be run again, when an image cannot be read or the cleanup fails', async () => { + const unreadable = account({ engineA: true, headStatus: 500 }); + await expect( + deletePlatformSecurityScanner(unreadable, manifest(true), unreadable.registryFetch), + ).rejects.toThrow('(HTTP 500)'); + const cleanup = account({ engineA: true, gcStatus: 500 }); + await expect( + deletePlatformSecurityScanner(cleanup, manifest(true), cleanup.registryFetch), + ).rejects.toThrow('The registry layer cleanup failed (HTTP 500).'); + }); + + it('succeeds again when everything is already gone', async () => { + const cloudflare = account({ gate: 'missing', controller: 'missing', application: 'missing' }); + expect( + await deletePlatformSecurityScanner(cloudflare, manifest(true), cloudflare.registryFetch), + ).toEqual({ + deleted: [], + kept: [], + }); + expect(cloudflare.calls.some((call) => call.startsWith('DELETE'))).toBe(false); + }); + + it('keeps objects that carry another installation’s marker', async () => { + const cloudflare = account({ gate: 'foreign', controller: 'foreign' }); + const result = await deletePlatformSecurityScanner( + cloudflare, + manifest(true), + cloudflare.registryFetch, + ); + expect(result.deleted).toEqual([]); + expect(result.kept).toEqual([ + `security scanner gate ${cloudflare.names.gate}`, + `security scanner controller ${cloudflare.names.worker}`, + `security scanner container application ${cloudflare.names.application}`, + ]); + expect(cloudflare.calls.some((call) => call.startsWith('DELETE'))).toBe(false); + }); + + it('keeps a container application whose controller is gone or of another namespace', async () => { + const orphan = account({ controller: 'missing' }); + expect( + (await deletePlatformSecurityScanner(orphan, manifest(true), orphan.registryFetch)).kept, + ).toEqual([`security scanner container application ${orphan.names.application}`]); + expect(orphan.calls).not.toContain('DELETE /accounts/account/containers/applications/app-1'); + + const other = account({ application: 'other-namespace' }); + const result = await deletePlatformSecurityScanner(other, manifest(true), other.registryFetch); + expect(result.deleted).toEqual(['gate', 'controller']); + expect(result.kept).toEqual([ + `security scanner container application ${other.names.application}`, + ]); + }); + + it('treats a refused application list as nothing to remove when no controller exists', async () => { + const cloudflare = account({ + controller: 'missing', + application: 'missing', + failOn: 'GET /accounts/account/containers/applications', + }); + expect( + await deletePlatformSecurityScanner(cloudflare, manifest(true), cloudflare.registryFetch), + ).toEqual({ + deleted: ['gate'], + kept: [], + }); + }); + + it('still fails on a refused application list when the controller exists', async () => { + const cloudflare = account({ failOn: 'GET /accounts/account/containers/applications' }); + await expect( + deletePlatformSecurityScanner(cloudflare, manifest(true), cloudflare.registryFetch), + ).rejects.toThrow('forbidden'); + expect(cloudflare.calls).not.toContain(`DELETE ${cloudflare.workerPath}`); + }); + + it('stops on an API error so the uninstall can be run again', async () => { + const cloudflare = account({ + failOn: 'DELETE /accounts/account/containers/applications/app-1', + }); + await expect( + deletePlatformSecurityScanner(cloudflare, manifest(true), cloudflare.registryFetch), + ).rejects.toThrow('forbidden'); + // The controller is kept while its container application still exists. + expect(cloudflare.calls).not.toContain(`DELETE ${cloudflare.workerPath}`); + }); +}); diff --git a/packages/void/test/unit/platform-setup.test.ts b/packages/void/test/unit/platform-setup.test.ts index d29ab842d..9580be41f 100644 --- a/packages/void/test/unit/platform-setup.test.ts +++ b/packages/void/test/unit/platform-setup.test.ts @@ -357,6 +357,55 @@ describe('platform credential setup links', () => { ); }, ); + it.each([false, true])( + 'requests Containers and Cloudchamber for the scanner only when security audits are allowed, enabled: %s', + (securityAudits) => { + const original = plan(); + const selected = { + ...original, + deployment: { + ...original.deployment, + capabilities: { ...original.deployment.capabilities, securityAudits }, + }, + }; + const added = securityAudits + ? [ + { key: 'containers', type: 'edit' }, + { key: 'cloudchamber', type: 'edit' }, + ] + : []; + // The runtime token provisions the scanner; the management token deletes it on uninstall. + expect(permissionGroupKeys(platformSetupPages(selected).runtime.url)).toEqual([ + ...permissionGroupKeys(platformSetupPages(original).runtime.url), + ...added, + ]); + const management = (input: PlatformInstallPlan) => + permissionGroupKeys(platformManagementSetupPage(input, { access: false }).url); + expect(management(selected)).toEqual( + securityAudits ? expect.arrayContaining(added) : management(original), + ); + expect(management(original)).not.toContainEqual({ key: 'containers', type: 'edit' }); + }, + ); + it('keeps --security-audits in the copyable install and resume commands', () => { + const options = { + commandName: 'void' as const, + accountId: 'account', + installationSlug: 'team', + displayName: 'Team', + applicationDomain: 'apps.example.com', + zoneName: 'example.com', + controlPlaneDomain: 'api.example.com', + dedicatedZone: true, + workersDev: false, + runtime: '', + yes: false, + }; + expect(formatPlatformInstallCommand({ ...options, securityAudits: true })).toContain( + ' --security-audits', + ); + expect(formatPlatformInstallCommand(options)).not.toContain('--security-audits'); + }); it('requests the email zone and sending permissions only when email is enabled', () => { const original = plan('example.com'); const withEmail = { diff --git a/packages/void/test/unit/platform-teardown.test.ts b/packages/void/test/unit/platform-teardown.test.ts index 7c7592bf7..ff6236c37 100644 --- a/packages/void/test/unit/platform-teardown.test.ts +++ b/packages/void/test/unit/platform-teardown.test.ts @@ -696,6 +696,43 @@ describe('uninstall --purge-resources', () => { expect(printSuccess).not.toHaveBeenCalled(); }); + it('removes the security scanner before the Workers it is bound to, and not at all when it was never allowed', async () => { + for (const securityAudits of [true, false]) { + const base = installedManifest(); + const manifest = { + ...base, + deployment: { + ...base.deployment, + capabilities: { ...base.deployment.capabilities, securityAudits }, + ...(securityAudits ? { schemaVersion: 7 as const } : {}), + }, + }; + persistInstallation(manifest, directories); + const fake = cloudflare(manifest); + const deleteSecurityScanner = vi.fn(async () => { + fake.calls.push('DELETE security-scanner'); + return { deleted: ['controller' as const], kept: [] }; + }); + await uninstallPlatform( + fake, + manifest, + purgeResourcesArgs, + dependencies({ deleteSecurityScanner }), + ); + expect(deleteSecurityScanner).toHaveBeenCalledTimes(securityAudits ? 1 : 0); + if (securityAudits) { + expect(fake.calls.indexOf('PUT disabled')).toBeLessThan( + fake.calls.indexOf('DELETE security-scanner'), + ); + expect(fake.calls.indexOf('DELETE security-scanner')).toBeLessThan( + fake.calls.indexOf(FULL_ORDER[0]!), + ); + } + rmSync(process.env.VOID_PLATFORM_REGISTRY_DIR!, { force: true, recursive: true }); + directories.length = 0; + } + }); + it('deletes in an order Cloudflare accepts, with the tail Worker after its producers and routing KV last', async () => { const manifest = installedManifest(); persistInstallation(manifest, directories); diff --git a/packages/void/test/unit/project-args.test.ts b/packages/void/test/unit/project-args.test.ts index f7ddaed50..0413e2f7c 100644 --- a/packages/void/test/unit/project-args.test.ts +++ b/packages/void/test/unit/project-args.test.ts @@ -126,20 +126,63 @@ describe('parseProjectArgs', () => { subcommand: 'zero-trust', action: '', projectSlug: '', + json: false, }); for (const action of ['status', 'protect', 'public', 'reconcile'] as const) { expect(parseProjectArgs(['zero-trust', action, '--project', 'my-app'])).toEqual({ subcommand: 'zero-trust', action, projectSlug: 'my-app', + json: false, }); } }); + it('parses --json and the bypass flags', () => { + expect(parseProjectArgs(['zero-trust', 'status', '--json'])).toMatchObject({ json: true }); + expect( + parseProjectArgs(['zero-trust', 'bypass', '--reason', ' Scanner down ', '--yes']), + ).toEqual({ + subcommand: 'zero-trust', + action: 'bypass', + projectSlug: '', + json: false, + reason: 'Scanner down', + yes: true, + }); + expect( + parseProjectArgs(['zero-trust', 'bypass', '--reason', '- one', '--json']), + ).toMatchObject({ reason: '- one', yes: false, json: true }); + }); + + it('requires a bypass reason and keeps bypass flags off other actions', () => { + expect(() => parseProjectArgs(['zero-trust', 'bypass'])).toThrow( + 'A reason is required. Say why, for example: --reason "Launch today; scanner is down. Will re-check."', + ); + expect(() => parseProjectArgs(['zero-trust', 'bypass', '--reason', ' '])).toThrow( + 'A reason is required', + ); + expect(() => parseProjectArgs(['zero-trust', 'bypass', '--reason'])).toThrow( + '--reason requires a value', + ); + expect(() => + parseProjectArgs(['zero-trust', 'bypass', '--reason', 'x'.repeat(4001)]), + ).toThrow('at most 4000 characters'); + expect(() => + parseProjectArgs(['zero-trust', 'bypass', '--reason', 'a', '--reason', 'b']), + ).toThrow("Duplicate flag '--reason'"); + expect(() => parseProjectArgs(['zero-trust', 'public', '--yes'])).toThrow( + '--yes is not used with zero-trust public', + ); + expect(() => parseProjectArgs(['zero-trust', 'status', '--reason', 'x'])).toThrow( + '--reason is not used', + ); + }); + it('rejects unknown operations and malformed project selection', () => { for (const action of ['remove', 'enable', 'disable']) { expect(() => parseProjectArgs(['zero-trust', action])).toThrow( - 'status|protect|public|reconcile', + 'status|protect|public|bypass|reconcile', ); } expect(() => parseProjectArgs(['zero-trust', 'status', '--project'])).toThrow( @@ -376,3 +419,70 @@ describe('parseProjectArgs', () => { }); }); }); + +describe('security', () => { + const base = { subcommand: 'security', projectSlug: '', json: false }; + it('parses the actions', () => { + expect(parseProjectArgs(['security'])).toEqual({ ...base, action: '' }); + expect(parseProjectArgs(['security', 'status', '--json', '--project', 'a'])).toEqual({ + ...base, + json: true, + projectSlug: 'a', + action: 'status', + }); + expect(parseProjectArgs(['security', 'list', '--urgent', '--state', 'all'])).toMatchObject({ + action: 'list', + urgent: true, + state: 'all', + }); + expect( + parseProjectArgs([ + 'security', + 'resolve', + 'F-12,13', + 'f-12', + '--reason', + 'false-positive', + '--comment', + '- ok', + ]), + ).toMatchObject({ ids: ['F-12', 'F-13'], reason: 'false_positive', comment: '- ok' }); + expect(parseProjectArgs(['security', 'comment', '12', '-dash text'])).toMatchObject({ + id: 'F-12', + text: '-dash text', + }); + expect(parseProjectArgs(['security', 'budget', '--usd', '12.50'])).toMatchObject({ + change: 'set', + usd: 12.5, + }); + // Up to what the platform takes (PRD §13.2: any amount when no ceiling applies). + expect(parseProjectArgs(['security', 'budget', '--usd', '1000000'])).toMatchObject({ + usd: 1_000_000, + }); + expect(parseProjectArgs(['security', 'budget', '--off'])).toMatchObject({ change: 'off' }); + expect( + parseProjectArgs(['security', 'model', '--default', '--accept-provider-notice']), + ).toMatchObject({ + change: 'default', + acceptNotice: true, + }); + expect(parseProjectArgs(['security', 'scans', '--limit', '100'])).toMatchObject({ limit: 100 }); + }); + it.each([ + [['security', 'bogus'], 'Usage'], + [['security', 'resolve', 'F-1', '--reason', 'fixed'], 'comment is required'], + [['security', 'resolve', 'F-1', '--comment', 'x'], '--reason is required'], + [['security', 'resolve', 'x1', '--reason', 'fixed', '--comment', 'x'], 'not a finding id'], + [['security', 'comment', 'F-1', 'a'.repeat(4001)], 'at most 4000'], + [['security', 'scans', '--limit', '101'], '--limit'], + [['security', 'budget', '--usd', '1.234'], '--usd'], + [['security', 'budget', '--usd', '1000001'], 'at most 1000000'], + [['security', 'budget', '--usd', '5', '--off'], 'not both'], + [['security', 'list', '--severity', 'bad'], '--severity'], + [['security', 'status', '--urgent'], 'not used'], + [['security', 'model', 'x', '--default'], 'not both'], + [['security', 'model', '--accept-provider-notice'], 'needs a model id'], + ])('rejects %j', (args, text) => { + expect(() => parseProjectArgs(args)).toThrow(text); + }); +}); diff --git a/packages/void/test/unit/project-lookup-client.test.ts b/packages/void/test/unit/project-lookup-client.test.ts index 5aa927072..0350563f8 100644 --- a/packages/void/test/unit/project-lookup-client.test.ts +++ b/packages/void/test/unit/project-lookup-client.test.ts @@ -71,3 +71,33 @@ describe('targeted project lookup', () => { ]); }); }); + +describe('security routes', () => { + it('says an old platform has no security audits for a 404 without JSON', async () => { + fetchMock.mockResolvedValueOnce(new Response('404 Not Found', { status: 404 })); + await expect(client().getProjectSecurity('proj_1')).rejects.toThrow( + 'does not support security audits', + ); + }); + it('keeps a 404 with JSON as an API error', async () => { + fetchMock.mockResolvedValueOnce(Response.json({ error: 'finding not found' }, { status: 404 })); + await expect(client().getProjectSecurityFinding('proj_1', 'F-1')).rejects.toMatchObject({ + name: 'PlatformApiError', + status: 404, + }); + }); + it('shows the platform message for a 409 or 422', async () => { + fetchMock.mockResolvedValueOnce( + Response.json( + { + error: 'security budget above platform limit', + message: 'The platform limits each project.', + }, + { status: 422 }, + ), + ); + await expect(client().setProjectSecurityBudget('proj_1', 150)).rejects.toThrow( + /^The platform limits each project\.$/, + ); + }); +}); diff --git a/packages/void/test/unit/project-security-check-command.test.ts b/packages/void/test/unit/project-security-check-command.test.ts new file mode 100644 index 000000000..17c94828f --- /dev/null +++ b/packages/void/test/unit/project-security-check-command.test.ts @@ -0,0 +1,542 @@ +import { execFileSync } from 'node:child_process'; +import { mkdirSync, mkdtempSync, rmSync, symlinkSync, truncateSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { gunzipSync } from 'node:zlib'; +import { afterEach, describe, expect, it, vi } from 'vite-plus/test'; +import { savePlatformConnection } from '../../src/cli/platform-registry.ts'; +import { parseProjectArgs } from '../../src/cli/project-args.ts'; +import { runProjectCommand } from '../../src/cli/project-cmd.ts'; +import { + collectSecurityLocalTree, + type SecurityCheckDeps, +} from '../../src/cli/project-security-check.ts'; +import { runProjectSecurityCommand } from '../../src/cli/project-security.ts'; + +const roots: Array = []; + +function linked(): string { + const root = mkdtempSync(join(tmpdir(), 'void-security-check-')); + roots.push(root); + process.env.VOID_PLATFORM_REGISTRY_DIR = join(root, '.registry'); + savePlatformConnection({ + accountId: null, + apiUrl: 'https://api.example.test', + applicationDomain: 'apps.example.test', + displayName: 'Test platform', + installationId: null, + kind: 'connected', + proxyUrl: 'https://proxy.example.test', + }); + mkdirSync(join(root, '.void')); + writeFileSync( + join(root, '.void', 'project.json'), + JSON.stringify({ + platform: 'void', + platformUrl: 'https://api.example.test', + projectId: 'project_1', + slug: 'acme-web', + }), + ); + vi.stubEnv('VOID_TOKEN', 'test-token'); + vi.stubEnv('VOID_API_URL', 'https://api.example.test'); + return root; +} + +function write(root: string, files: Record) { + for (const [path, data] of Object.entries(files)) { + mkdirSync(join(root, path, '..'), { recursive: true }); + writeFileSync(join(root, path), data); + } +} + +afterEach(() => { + delete process.env.VOID_PLATFORM_REGISTRY_DIR; + vi.unstubAllEnvs(); + vi.unstubAllGlobals(); + vi.restoreAllMocks(); + for (const root of roots.splice(0)) { + rmSync(root, { recursive: true, force: true }); + } +}); + +function capture() { + const out: Array = []; + vi.spyOn(console, 'log').mockImplementation((...a) => void out.push(a.join(' '))); + return out; +} + +const CHECKS = '/projects/project_1/security/checks'; +const UPLOAD = + 'https://acct.r2.cloudflarestorage.com/bucket/security-scans/p/scans/scan_9/local-tree.tar.gz'; + +const preview = { + dryRun: true, + model: '@cf/deepseek-ai/deepseek-v4.1-flash-1017', + thirdParty: false, + notice: null, + worstCaseUsd: 0.5, + budget: null, + limits: { maxFiles: 10_000, maxBytes: 32 * 1024 * 1024, maxArchiveBytes: 32 * 1024 * 1024 }, +}; + +const check = { + id: 'scan_9', + status: 'queued', + statusReason: null, + failureCause: null, + refusalCategory: null, + trigger: 'local', + deploymentId: null, + baseDeploymentId: null, + coverageLabel: null, + backlogFiles: 0, + filesScanned: 0, + model: null, + meteredUsd: 0, + startedAt: null, + finishedAt: null, + createdAt: '2026-11-20T10:00:00.000Z', + coverageNotes: [], +}; + +const ended = { + check: { + ...check, + status: 'succeeded', + coverageLabel: 'full scan (local check)', + filesScanned: 2, + model: '@cf/deepseek-ai/deepseek-v4.1-flash-1017', + }, + ended: true, + result: { + version: 1, + total: 2, + capped: false, + findings: [ + { + verdict: 'confirmed', + severity: 'high', + confidence: 'high', + title: 'SQL injection in /users\u001b[31m', + category: 'sql-injection', + cwe: 'CWE-89', + file: 'src/routes/users.ts', + lineStart: 3, + lineEnd: 3, + source: 'scanner', + verdictSource: 'static', + detail: {}, + }, + { + verdict: 'needs_validation', + severity: null, + confidence: null, + title: 'Possible open redirect', + category: 'open-redirect', + cwe: null, + file: 'src/app.tsx', + lineStart: null, + lineEnd: null, + source: 'scanner', + verdictSource: 'static', + detail: {}, + }, + ], + }, +}; + +type Call = { method: string; url: string; body: unknown; headers: Record }; + +/** The platform and storage: handlers by `METHOD path` (the upload by its full URL). */ +function route(handlers: Record Response>) { + const calls: Array = []; + const impl = vi.fn(async (input: string | URL | Request, init?: RequestInit) => { + const url = new URL(String(input instanceof Request ? input.url : input)); + const method = init?.method ?? 'GET'; + if (url.pathname === '/.well-known/void-platform') { + return Response.json({}); + } + const upload = url.href === UPLOAD; + const headers: Record = {}; + new Headers(init?.headers).forEach((value, key) => { + headers[key] = value; + }); + calls.push({ + method, + url: upload ? 'UPLOAD' : url.pathname, + body: upload ? init?.body : init?.body ? JSON.parse(String(init.body)) : undefined, + headers, + }); + const handler = handlers[upload ? `${method} UPLOAD` : `${method} ${url.pathname}`]; + return handler ? handler() : new Response('404 Not Found', { status: 404 }); + }); + vi.stubGlobal('fetch', impl); + return { calls, fetch: impl as unknown as typeof fetch }; +} + +function platform(view: () => unknown = () => ended) { + return { + [`POST ${CHECKS}`]: (() => { + let posts = 0; + return () => + ++posts === 1 + ? Response.json(preview) + : Response.json( + { + ok: true, + checkId: 'scan_9', + upload: { url: UPLOAD, headers: { 'Content-Md5': 'x', 'Content-Length': '1' } }, + expiresAt: '2026-11-20T10:30:00.000Z', + model: preview.model, + thirdParty: false, + }, + { status: 201 }, + ); + })(), + 'PUT UPLOAD': () => new Response(null, { status: 200 }), + [`POST ${CHECKS}/scan_9/start`]: () => + Response.json({ checkId: 'scan_9', status: 'queued' }, { status: 202 }), + [`GET ${CHECKS}/scan_9`]: () => Response.json(view()), + }; +} + +const APP = { + 'src/routes/users.ts': 'export const GET = () => db.prepare(`... ${id}`);\n', + 'src/app.tsx': 'export const App = () => null;\n', +}; + +function deps(files: Array, extra: Partial = {}) { + return { + interactive: false, + check: { listFiles: () => files, sleep: async () => {}, ...extra }, + }; +} + +function args(overrides: Record = {}) { + return { + subcommand: 'security' as const, + projectSlug: '', + json: false, + action: 'check' as const, + checkId: '', + yes: true, + wait: true, + ...overrides, + }; +} + +describe('security check arguments', () => { + it('parses a new check, an earlier one and --no-wait', () => { + expect(parseProjectArgs(['security', 'check'])).toMatchObject({ + action: 'check', + checkId: '', + yes: false, + wait: true, + }); + expect(parseProjectArgs(['security', 'check', '--yes', '--no-wait'])).toMatchObject({ + yes: true, + wait: false, + }); + expect(parseProjectArgs(['security', 'check', 'scan_9'])).toMatchObject({ checkId: 'scan_9' }); + expect(() => parseProjectArgs(['security', 'check', 'scan_9', '--yes'])).toThrow( + '--yes is used only when a new check starts', + ); + expect(() => parseProjectArgs(['security', 'check', 'a', 'b'])).toThrow( + "Unexpected argument 'b'", + ); + expect(() => parseProjectArgs(['security', 'check', '--client-assets'])).toThrow( + '--client-assets is not used with security check', + ); + }); +}); + +describe('collecting the local tree', () => { + it('keeps code, drops secret-like files, lockfiles, binaries, links and deleted files', () => { + const root = linked(); + write(root, { + ...APP, + '.env.local': 'TOKEN=x', + 'certs/server.pem': 'KEY', + 'pnpm-lock.yaml': 'lockfileVersion: 9', + 'logo.png': 'png', + 'blob.dat2': new Uint8Array([1, 0, 2]), + }); + symlinkSync(join(root, 'src/app.tsx'), join(root, 'link.ts')); + const tree = collectSecurityLocalTree(root, () => [ + 'src/routes/users.ts', + 'src/app.tsx', + '.env.local', + 'certs/server.pem', + 'pnpm-lock.yaml', + 'logo.png', + 'blob.dat2', + 'link.ts', + 'deleted.ts', + ]); + expect(tree.files.map((file) => file.path)).toEqual(['src/routes/users.ts', 'src/app.tsx']); + expect(tree.secret).toEqual(['.env.local', 'certs/server.pem']); + expect(tree.skipped).toBe(5); + expect(tree.bytes).toBe(APP['src/routes/users.ts'].length + APP['src/app.tsx'].length); + }); + + it('sends only git-tracked files, with edits on disk, relative to this folder', () => { + const repo = mkdtempSync(join(tmpdir(), 'void-security-check-git-')); + roots.push(repo); + const git = (...cmd: Array) => + execFileSync('git', cmd, { cwd: repo, stdio: ['ignore', 'pipe', 'ignore'] }); + git('init', '-q'); + write(repo, { + 'apps/web/src/index.ts': 'one', + 'apps/web/README.md': 'docs', + 'other/x.ts': 'x', + }); + git('add', '.'); + write(repo, { 'apps/web/src/index.ts': 'edited', 'apps/web/src/new.ts': 'untracked' }); + const tree = collectSecurityLocalTree(join(repo, 'apps/web')); + expect(tree.files.map((file) => [file.path, Buffer.from(file.data).toString()]).sort()).toEqual( + [ + ['README.md', 'docs'], + ['src/index.ts', 'edited'], + ], + ); + }); + + it('refuses a folder that is not a git repository or is over the limits', () => { + const root = mkdtempSync(join(tmpdir(), 'void-security-check-nogit-')); + roots.push(root); + expect(() => collectSecurityLocalTree(root)).toThrow('not in a git repository'); + write(root, { 'big.ts': 'x'.repeat(33 * 1024 * 1024) }); + expect(() => collectSecurityLocalTree(root, () => ['big.ts'])).toThrow( + 'at most 32 MB of code, and this folder has 33.0 MB', + ); + }); + + it('stops at the limits from the sizes on disk, before reading a file over them', () => { + const root = mkdtempSync(join(tmpdir(), 'void-security-check-size-')); + roots.push(root); + // 3 GB on disk (sparse): reading it whole would not even fit in a buffer. + write(root, { 'a.ts': 'one', 'dump.sql': 'x'.repeat(8192), 'blob.dat2': new Uint8Array(8192) }); + truncateSync(join(root, 'dump.sql'), 3 * 1024 ** 3); + // A big binary is never sent, so it does not count. + truncateSync(join(root, 'blob.dat2'), 3 * 1024 ** 3); + expect(collectSecurityLocalTree(root, () => ['a.ts', 'blob.dat2']).files).toHaveLength(1); + expect(() => collectSecurityLocalTree(root, () => ['a.ts', 'dump.sql'])).toThrow( + 'at most 32 MB of code, and this folder has 3072.0 MB or more', + ); + }); +}); + +describe('project security check (M32)', () => { + it('previews, uploads the archive, starts it, waits and prints the result', async () => { + const root = linked(); + write(root, { ...APP, '.env': 'SECRET=1' }); + let gets = 0; + const { calls, fetch } = route( + platform(() => (++gets === 1 ? { check, ended: false, result: null } : ended)), + ); + const out = capture(); + await runProjectSecurityCommand( + root, + args(), + deps(['src/routes/users.ts', 'src/app.tsx', '.env'], { fetch }), + ); + expect(calls.map((c) => `${c.method} ${c.url}`)).toEqual([ + `POST ${CHECKS}`, + `POST ${CHECKS}`, + 'PUT UPLOAD', + `POST ${CHECKS}/scan_9/start`, + `GET ${CHECKS}/scan_9`, + `GET ${CHECKS}/scan_9`, + ]); + const [dry, create] = calls as [Call, Call]; + expect(dry.body).toMatchObject({ dryRun: true, files: 2 }); + expect(create.body).toEqual({ ...(dry.body as object), dryRun: undefined }); + // The upload is the gzip tar of the two files, under `tree/`, with the signed headers. + const put = calls[2]!; + expect(put.headers['content-md5']).toBe('x'); + const tar = gunzipSync(put.body as Buffer).toString('latin1'); + expect(tar).toContain('tree/src/routes/users.ts'); + expect(tar).toContain('tree/src/app.tsx'); + expect(tar).not.toContain('SECRET=1'); + const text = out.join('\n'); + expect(text).toContain('Security check of acme-web: 2 git-tracked files'); + expect(text).toContain('Not sent: 1 secret-like file (.env).'); + expect(text).toContain('It can cost up to $0.50; monthly caps apply.'); + expect(text).toContain('✓ Check scan_9 queued.'); + expect(text).toContain('Waiting in the scan queue…'); + expect(text).toContain('acme-web · local check scan_9'); + expect(text).toContain('1 finding (1 high) · 1 lead'); + expect(text).toContain('HIGH SQL injection in /users'); + expect(text).not.toContain('\u001b[31m'); + expect(text).toContain('src/routes/users.ts:3'); + expect(text).toContain('LEAD Possible open redirect'); + expect(text).toContain('Not saved as project findings.'); + }); + + it('asks first on a terminal, shows the provider notice, and sends nothing on no', async () => { + const root = linked(); + write(root, APP); + const third = { + ...preview, + model: 'anthropic/claude-opus-5.5', + thirdParty: true, + notice: ['This model is run by Anthropic, not by Cloudflare.'], + }; + const { calls } = route({ [`POST ${CHECKS}`]: () => Response.json(third) }); + const out = capture(); + const asked: Array = []; + await runProjectSecurityCommand(root, args({ yes: false }), { + interactive: true, + confirm: async (message) => { + asked.push(message); + return false; + }, + check: { listFiles: () => Object.keys(APP) }, + }); + expect(asked).toEqual([ + 'Send these files for a security check with anthropic/claude-opus-5.5?', + ]); + expect(out.join('\n')).toContain('This model is run by Anthropic, not by Cloudflare.'); + expect(out.join('\n')).toContain('Nothing was sent.'); + expect(calls).toHaveLength(1); + }); + + it('needs --yes without a terminal or with --json, before anything is sent', async () => { + const root = linked(); + write(root, APP); + const { calls } = route(platform()); + await expect( + runProjectSecurityCommand(root, args({ yes: false }), deps(Object.keys(APP))), + ).rejects.toThrow('Add --yes to send the code without a prompt.'); + await expect( + runProjectSecurityCommand(root, args({ yes: false, json: true }), { + ...deps(Object.keys(APP)), + interactive: true, + }), + ).rejects.toThrow('Add --yes'); + expect(calls).toHaveLength(0); + }); + + it('prints JSON and fails when the check ends with no result', async () => { + const root = linked(); + write(root, APP); + const refused = { + check: { + ...check, + status: 'refused', + failureCause: 'project', + refusalCategory: 'cyber', + model: 'anthropic/claude-opus-5.5', + }, + ended: true, + result: null, + }; + const { fetch } = route(platform(() => refused)); + const out = capture(); + await expect( + runProjectSecurityCommand(root, args({ json: true }), deps(Object.keys(APP), { fetch })), + ).rejects.toThrow( + 'The check was refused by anthropic/claude-opus-5.5 (category: cyber). Pick another model', + ); + expect(out).toHaveLength(1); + expect(JSON.parse(out[0]!)).toMatchObject({ check: { status: 'refused' }, ended: true }); + }); + + it('shows an earlier check without sending anything, and returns at once with --no-wait', async () => { + const root = linked(); + const { calls } = route(platform()); + const out = capture(); + await run(root, ['security', 'check', 'scan_9']); + expect(calls.map((c) => `${c.method} ${c.url}`)).toEqual([ + `GET ${CHECKS}/scan_9`, + `GET ${CHECKS}/scan_9`, + ]); + expect(out.join('\n')).toContain('HIGH SQL injection in /users'); + + const waiting = route({ + [`GET ${CHECKS}/scan_9`]: () => Response.json({ check, ended: false, result: null }), + }); + const later = capture(); + await run(root, ['security', 'check', 'scan_9', '--no-wait']); + expect(waiting.calls).toHaveLength(2); + expect(later.join('\n')).toContain('See the result: void project security check scan_9'); + }); + + it('goes on to start when the upload landed but its reply was lost (412 on the retry)', async () => { + const root = linked(); + write(root, APP); + let puts = 0; + const { calls, fetch } = route({ + ...platform(), + 'PUT UPLOAD': () => { + puts++; + if (puts === 1) { + throw new TypeError('fetch failed'); + } + return new Response('PreconditionFailed', { status: 412 }); + }, + }); + capture(); + vi.useFakeTimers({ toFake: ['setTimeout'] }); + try { + const done = runProjectSecurityCommand(root, args(), deps(Object.keys(APP), { fetch })); + await vi.runAllTimersAsync(); + await done; + } finally { + vi.useRealTimers(); + } + expect(calls.map((c) => `${c.method} ${c.url}`)).toContain(`POST ${CHECKS}/scan_9/start`); + }); + + it('starts an earlier check whose start was lost, once', async () => { + const root = linked(); + let gets = 0; + const { calls } = route({ + ...platform(), + [`GET ${CHECKS}/scan_9`]: () => + Response.json( + ++gets === 1 + ? { check: { ...check, status: 'pending_input' }, ended: false, result: null } + : ended, + ), + }); + capture(); + await run(root, ['security', 'check', 'scan_9']); + expect(calls.map((c) => `${c.method} ${c.url}`)).toEqual([ + `GET ${CHECKS}/scan_9`, + `POST ${CHECKS}/scan_9/start`, + `GET ${CHECKS}/scan_9`, + ]); + }); + + it('fails when a check that just ended has no result; an earlier one names the 30 days', async () => { + const root = linked(); + write(root, APP); + const missing = { ...ended, result: null }; + const { fetch } = route(platform(() => missing)); + const out = capture(); + await expect( + runProjectSecurityCommand(root, args(), deps(Object.keys(APP), { fetch })), + ).rejects.toThrow('The check ended, but its result could not be read. Run it again.'); + expect(out.join('\n')).toContain('The result is missing.'); + expect(out.join('\n')).not.toContain('30 days).'); + + const later = capture(); + await expect(run(root, ['security', 'check', 'scan_9'])).rejects.toThrow( + 'The result of this check is no longer stored', + ); + expect(later.join('\n')).toContain('results are kept for 30 days'); + }); + + it('names an older platform that has no local checks', async () => { + const root = linked(); + write(root, APP); + route({}); + await expect(runProjectSecurityCommand(root, args(), deps(Object.keys(APP)))).rejects.toThrow( + 'cannot run local security checks yet', + ); + }); +}); + +const run = (root: string, argv: Array) => runProjectCommand(root, parseProjectArgs(argv)); diff --git a/packages/void/test/unit/project-security-command.test.ts b/packages/void/test/unit/project-security-command.test.ts new file mode 100644 index 000000000..e678952ac --- /dev/null +++ b/packages/void/test/unit/project-security-command.test.ts @@ -0,0 +1,917 @@ +import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { afterEach, describe, expect, it, vi } from 'vite-plus/test'; +import { savePlatformConnection } from '../../src/cli/platform-registry.ts'; +import { parseProjectArgs } from '../../src/cli/project-args.ts'; +import { runProjectCommand } from '../../src/cli/project-cmd.ts'; +import { runProjectSecurityCommand } from '../../src/cli/project-security.ts'; +import type { ProjectSecurityStatus } from '../../src/cli/security-api-types.ts'; + +const roots: Array = []; + +function linked(): string { + const root = mkdtempSync(join(tmpdir(), 'void-project-security-')); + roots.push(root); + process.env.VOID_PLATFORM_REGISTRY_DIR = join(root, 'registry'); + savePlatformConnection({ + accountId: null, + apiUrl: 'https://api.example.test', + applicationDomain: 'apps.example.test', + displayName: 'Test platform', + installationId: null, + kind: 'connected', + proxyUrl: 'https://proxy.example.test', + }); + mkdirSync(join(root, '.void')); + writeFileSync( + join(root, '.void', 'project.json'), + JSON.stringify({ + platform: 'void', + platformUrl: 'https://api.example.test', + projectId: 'project_1', + slug: 'acme-web', + }), + ); + vi.stubEnv('VOID_TOKEN', 'test-token'); + vi.stubEnv('VOID_API_URL', 'https://api.example.test'); + return root; +} + +afterEach(() => { + delete process.env.VOID_PLATFORM_REGISTRY_DIR; + vi.unstubAllEnvs(); + vi.unstubAllGlobals(); + vi.restoreAllMocks(); + for (const root of roots.splice(0)) { + rmSync(root, { recursive: true, force: true }); + } +}); + +const scan = { + id: 'ss_1', + status: 'succeeded', + statusReason: null, + failureCause: null, + refusalCategory: null, + trigger: 'deploy', + deploymentId: 'dpl_8f2c', + baseDeploymentId: 'dpl_7c20', + coverageLabel: 'changes since dpl_7c20 · source diff · 14 files', + backlogFiles: 0, + filesScanned: 14, + model: '@cf/x', + meteredUsd: 0.4, + startedAt: '2026-11-17T10:00:00.000Z', + finishedAt: '2026-11-17T10:09:00.000Z', + createdAt: '2026-11-17T10:00:00.000Z', +}; + +const status: ProjectSecurityStatus = { + policy: { + mode: 'public', + applies: true, + reason: 'not protected by Zero Trust', + publicGate: false, + }, + urgent: { + count: 2, + counts: { critical: 1, high: 1 }, + oldestFirstSeenAt: '2026-11-10T00:00:00.000Z', + findings: [ + { id: 'F-12', severity: 'critical' }, + { id: 'F-15', severity: 'high' }, + ], + more: 0, + detail: 'full', + }, + model: { + id: '@cf/x', + requested: '@cf/x', + source: 'default', + thirdParty: false, + noticeAccepted: false, + pendingDefault: null, + }, + budget: { + capUsd: 100, + capSource: 'own', + ceilingUsd: 100, + spentUsd: 12.4, + month: '2026-11', + resetsAt: '2026-12-01T00:00:00.000Z', + }, + lastScan: scan, + lastSuccessfulScan: scan, + deploysSinceLastSuccess: 0, + backlogFiles: 0, + counts: { + open: { critical: 1, high: 1, medium: 1, low: 0, informational: 0 }, + leads: 3, + resolved: 0, + urgent: 2, + }, + publicRequest: null, +}; + +function capture() { + const out: Array = []; + vi.spyOn(console, 'log').mockImplementation((...a) => void out.push(a.join(' '))); + vi.spyOn(process.stdout, 'write').mockImplementation((chunk) => { + out.push(String(chunk)); + return true; + }); + return out; +} + +function route(handlers: Record Response>) { + const calls: Array<{ method: string; path: string; body: unknown }> = []; + vi.stubGlobal( + 'fetch', + vi.fn(async (input: string | URL | Request, init?: RequestInit) => { + const url = new URL(String(input instanceof Request ? input.url : input)); + const method = init?.method ?? 'GET'; + if (url.pathname === '/.well-known/void-platform') { + return Response.json({}); + } + calls.push({ + method, + path: url.pathname + url.search, + body: init?.body ? JSON.parse(String(init.body)) : undefined, + }); + const handler = handlers[`${method} ${url.pathname}`]; + return handler ? handler() : new Response('404 Not Found', { status: 404 }); + }), + ); + return calls; +} + +const run = (root: string, args: Array) => runProjectCommand(root, parseProjectArgs(args)); + +describe('project security command', () => { + it('prints the status in the spec layout', async () => { + const root = linked(); + route({ 'GET /projects/project_1/security': () => Response.json(status) }); + const out = capture(); + await run(root, ['security', 'status']); + const text = out.join('\n'); + expect(text).toContain('acme-web · security'); + expect(text).toContain('2 open (1 critical, 1 high) · oldest Nov 10'); + expect(text).toContain('applies: not protected by Zero Trust (Public projects only)'); + expect(text).toContain('$12.40 of $100.00 this month (project cap) · resets Dec 1'); + expect(text).toContain('succeeded · dpl_8f2c · 9 min'); + expect(text).toContain('2 urgent · 1 other · 3 leads'); + }); + + it('prints a held public request on the status', async () => { + const root = linked(); + route({ + 'GET /projects/project_1/security': () => + Response.json({ + ...status, + publicRequest: { + id: 'spr_1', + state: 'held_findings', + heldReason: null, + targetDeploymentId: 'dpl_9a1d', + gateScanId: null, + blockers: { count: 2, ids: ['F-12', 'F-15'] }, + requestedAt: '2026-11-17T14:02:00.000Z', + requestedByRole: 'admin', + }, + }), + }); + const out = capture(); + await run(root, ['security', 'status']); + expect(out.join('\n')).toContain( + '2 urgent findings must be resolved before Zero Trust is turned off (F-12, F-15)', + ); + }); + + it('strips terminal escapes from model text', async () => { + const root = linked(); + route({ + 'GET /projects/project_1/security/findings': () => + Response.json({ + findings: [ + { + id: 'F-1', + verdict: 'confirmed', + severity: 'high', + state: 'open', + urgent: true, + revision: 1, + title: 'bad \u001b[31mred\u001b]0;x\u0007 title', + }, + ], + nextCursor: null, + }), + }); + const out = capture(); + await run(root, ['security', 'list']); + const text = out.join('\n'); + expect(text).toContain('F-1'); + expect(text).not.toContain('\u001b'); + expect(text).not.toContain('\u0007'); + }); + + it('resolves with the revision it read and prints what is still urgent', async () => { + const root = linked(); + const calls = route({ + 'GET /projects/project_1/security/findings/F-12': () => + Response.json({ + finding: { + id: 'F-12', + verdict: 'confirmed', + severity: 'critical', + state: 'open', + urgent: true, + revision: 4, + }, + }), + 'POST /projects/project_1/security/findings/F-12/resolve': () => + Response.json({ + ok: true, + id: 'F-12', + state: 'resolved', + resolution: 'fixed', + revision: 5, + }), + 'GET /projects/project_1/security': () => + Response.json({ + ...status, + urgent: { ...status.urgent, count: 1, findings: [{ id: 'F-15', severity: 'high' }] }, + }), + }); + const out = capture(); + await run(root, [ + 'security', + 'resolve', + 'F-12', + '--reason', + 'fixed', + '--comment', + 'Bound params', + ]); + const text = out.join('\n'); + expect(text).toContain('✓ F-12 resolved (fixed). The next scan will check that the fix holds.'); + expect(text).toContain('Still open and urgent: F-15 (high).'); + expect(calls.find((c) => c.method === 'POST')?.body).toEqual({ + reason: 'fixed', + comment: 'Bound params', + expectedRevision: 4, + }); + }); + + it('fails when a resolve is refused as changed', async () => { + const root = linked(); + route({ + 'GET /projects/project_1/security/findings/F-12': () => + Response.json({ + finding: { + id: 'F-12', + verdict: 'confirmed', + severity: 'high', + state: 'open', + urgent: true, + revision: 4, + }, + }), + 'POST /projects/project_1/security/findings/F-12/resolve': () => + Response.json( + { + error: 'finding changed', + message: 'F-12 changed while you were working on it: resolved (fixed).', + }, + { status: 409 }, + ), + }); + const out = capture(); + await expect( + run(root, ['security', 'resolve', 'F-12', '--reason', 'fixed', '--comment', 'x']), + ).rejects.toThrow('1 of 1'); + expect(out.join('\n')).toContain('F-12 changed while you were working on it'); + }); + + it('shows the platform ceiling copy for a budget above the limit', async () => { + const root = linked(); + route({ + 'PUT /projects/project_1/security/budget': () => + Response.json( + { + error: 'security budget above platform limit', + message: + 'The platform limits each project to $100.00 / month. Ask your platform admin to raise it for acme-web: void platform security budget --project acme-web --usd 150', + }, + { status: 422 }, + ), + }); + await expect(run(root, ['security', 'budget', '--usd', '150'])).rejects.toThrow( + 'The platform limits each project to $100.00 / month. Ask your platform admin', + ); + }); + + it('accepts the provider notice with the version the platform names', async () => { + const root = linked(); + let puts = 0; + const calls = route({ + 'PUT /projects/project_1/security/model': () => + ++puts === 1 + ? Response.json( + { + error: 'provider notice not accepted', + message: 'read it', + version: 3, + notice: ['Run by Anthropic.'], + }, + { status: 422 }, + ) + : Response.json({ + ok: true, + model: { + ...status.model, + id: 'anthropic/claude-x', + source: 'project', + thirdParty: true, + }, + }), + }); + const out = capture(); + await run(root, ['security', 'model', 'anthropic/claude-x', '--accept-provider-notice']); + expect(out.join('\n')).toContain('Run by Anthropic.'); + expect( + calls.map( + (c) => (c.body as { acceptProviderNoticeVersion?: number }).acceptProviderNoticeVersion, + ), + ).toEqual([0, 3]); + }); + + it('says an old platform does not support security audits', async () => { + const root = linked(); + route({}); + await expect(run(root, ['security', 'status'])).rejects.toThrow( + 'does not support security audits', + ); + }); + + it('opens the page link only on a terminal', async () => { + const root = linked(); + route({ + 'POST /projects/project_1/security/page-link': () => + Response.json({ + url: 'https://api.example.test/security/projects/acme-web?t=abc', + expiresAt: '2026-11-17T10:15:00.000Z', + }), + }); + capture(); + const openUrl = vi.fn(); + await runProjectSecurityCommand(root, parseProjectArgs(['security', 'open']) as never, { + openUrl, + interactive: false, + }); + expect(openUrl).not.toHaveBeenCalled(); + await runProjectSecurityCommand(root, parseProjectArgs(['security', 'open']) as never, { + openUrl, + interactive: true, + }); + expect(openUrl).toHaveBeenCalledWith( + 'https://api.example.test/security/projects/acme-web?t=abc', + ); + }); +}); + +const F = '/projects/project_1/security/findings'; +const finding = (id: string, extra: Record = {}) => ({ + id, + verdict: 'confirmed', + severity: 'high', + state: 'open', + urgent: true, + revision: 2, + title: `title ${id}`, + file: 'src/a.ts', + line: 3, + ...extra, +}); + +describe('project security scan (M25)', () => { + const SCANS = '/projects/project_1/security/scans'; + const preview = { + dryRun: true, + deploymentId: 'dpl_9a1d', + alreadyScanned: true, + tier: 'full', + model: 'anthropic/claude-opus-5.5', + thirdParty: true, + worstCaseUsd: 12, + budget: status.budget, + }; + const queued = { + ok: true, + scanId: 'ss_new', + deploymentId: 'dpl_9a1d', + tier: 'full', + model: 'anthropic/claude-opus-5.5', + alreadyScanned: true, + }; + const handlers = () => ({ + [`POST ${SCANS}`]: (() => { + let posts = 0; + return () => + ++posts === 1 ? Response.json(preview) : Response.json(queued, { status: 202 }); + })(), + }); + + it('previews, then queues with --yes and says where the result shows', async () => { + const root = linked(); + const calls = route(handlers()); + const out = capture(); + await run(root, ['security', 'scan', '--yes']); + expect(calls.map((c) => c.body)).toEqual([{ dryRun: true }, {}]); + const text = out.join('\n'); + expect(text).toContain('✓ Full scan ss_new of dpl_9a1d queued.'); + expect(text).toContain('void project security status'); + }); + + it('asks first on a terminal, names the cost, and queues nothing on no', async () => { + const root = linked(); + const calls = route(handlers()); + const out = capture(); + const asked: Array = []; + await runProjectSecurityCommand( + root, + { + subcommand: 'security', + projectSlug: '', + json: false, + action: 'scan', + yes: false, + clientAssets: false, + }, + { + interactive: true, + confirm: async (message) => { + asked.push(message); + return false; + }, + }, + ); + expect(asked).toEqual([ + 'Live deployment dpl_9a1d was already scanned. Run a full scan with anthropic/claude-opus-5.5? This reviews the whole app. It can cost up to $12.00.', + ]); + expect(out.join('\n')).toContain('Monthly caps apply: $12.40 of $100.00 spent this month.'); + expect(out.join('\n')).toContain('Nothing was queued.'); + expect(calls).toHaveLength(1); + }); + + it('needs --yes without a terminal or with --json', async () => { + const root = linked(); + const calls = route(handlers()); + await expect( + runProjectSecurityCommand( + root, + { + subcommand: 'security', + projectSlug: '', + json: false, + action: 'scan', + yes: false, + clientAssets: false, + }, + { interactive: false }, + ), + ).rejects.toThrow('Add --yes to start the scan without a prompt.'); + await expect(run(root, ['security', 'scan', '--json'])).rejects.toThrow('Add --yes'); + expect(calls.every((c) => (c.body as { dryRun?: boolean }).dryRun === true)).toBe(true); + }); + + it('shows the platform refusal as is', async () => { + const root = linked(); + route({ + [`POST ${SCANS}`]: () => + Response.json( + { + error: 'security_scan_in_progress', + message: 'acme-web already has a scan waiting (ss_1). Wait for it to end.', + }, + { status: 409 }, + ), + }); + await expect(run(root, ['security', 'scan', '--yes'])).rejects.toThrow( + 'already has a scan waiting (ss_1). Wait for it to end.', + ); + }); + + it('asks for the client asset pass with --client-assets (M31)', async () => { + const root = linked(); + const calls = route({ + [`POST ${SCANS}`]: (() => { + let posts = 0; + return () => + ++posts === 1 + ? Response.json({ ...preview, clientAssets: true }) + : Response.json({ ...queued, clientAssets: true }, { status: 202 }); + })(), + }); + const out = capture(); + await run(root, ['security', 'scan', '--yes', '--client-assets']); + expect(calls.map((c) => c.body)).toEqual([ + { dryRun: true, clientAssets: true }, + { clientAssets: true }, + ]); + expect(out.join('\n')).toContain( + '✓ Full scan ss_new of dpl_9a1d queued, with client bundle sources.', + ); + }); + + it('refuses --client-assets on a platform that ignores it, before queuing', async () => { + const root = linked(); + const calls = route(handlers()); + await expect(run(root, ['security', 'scan', '--yes', '--client-assets'])).rejects.toThrow( + 'This platform cannot read client bundle sources yet.', + ); + expect(calls).toHaveLength(1); + }); + + it('parses only --yes, --project and --json', () => { + expect(parseProjectArgs(['security', 'scan', '--yes'])).toMatchObject({ + action: 'scan', + yes: true, + clientAssets: false, + }); + expect(() => parseProjectArgs(['security', 'scan', '--usd', '5'])).toThrow( + '--usd is not used with security scan', + ); + expect(() => parseProjectArgs(['security', 'scan', 'dpl_1'])).toThrow('Unexpected argument'); + }); +}); + +describe('project security command paths', () => { + it('lists findings, hides leads with a note and shows them with --leads', async () => { + const root = linked(); + route({ + [`GET ${F}`]: () => + Response.json({ + findings: [finding('F-1'), finding('F-2', { verdict: 'needs_validation' })], + nextCursor: null, + }), + }); + const out = capture(); + await run(root, ['security', 'list']); + let text = out.join('\n'); + expect(text).toContain('F-1'); + expect(text).not.toContain('F-2 '); + expect(text).toContain('1 lead is hidden. Show them with --leads.'); + out.length = 0; + await run(root, ['security', 'list', '--leads']); + text = out.join('\n'); + expect(text).toContain('F-2'); + expect(text).toContain('lead'); + expect(text).not.toContain('hidden'); + }); + + it('prints the list as a SARIF log with --format sarif (M31)', async () => { + const root = linked(); + route({ + [`GET ${F}`]: () => + Response.json({ + findings: [ + finding('F-1', { + category: 'secret-in-output', + cwe: 'CWE-200', + file: '_assets/app.js', + line: 2, + lineEnd: 2, + title: 'Secret STRIPE_KEY is in a public file: _assets/app.js', + }), + finding('F-2', { verdict: 'needs_validation', severity: null }), + ], + nextCursor: null, + }), + }); + const out = capture(); + const errors: Array = []; + vi.spyOn(console, 'error').mockImplementation((...a) => void errors.push(a.join(' '))); + await run(root, ['security', 'list', '--format', 'sarif']); + const log = JSON.parse(out.join('\n')); + expect(log.version).toBe('2.1.0'); + expect(log.runs[0].results).toEqual([ + expect.objectContaining({ + ruleId: 'secret-in-output', + level: 'error', + message: { text: 'F-1: Secret STRIPE_KEY is in a public file: _assets/app.js' }, + locations: [ + { + physicalLocation: { + artifactLocation: { uri: '_assets/app.js', uriBaseId: '%SRCROOT%' }, + region: { startLine: 2, endLine: 2 }, + }, + }, + ], + }), + ]); + expect(errors).toEqual(['1 lead is left out. Add them with --leads.']); + expect(() => parseProjectArgs(['security', 'list', '--format', 'csv'])).toThrow( + "Invalid --format 'csv'", + ); + expect(() => parseProjectArgs(['security', 'list', '--format', 'sarif', '--json'])).toThrow( + 'not both', + ); + }); + + it('stops listing at 500 findings and says so', async () => { + const root = linked(); + const calls = route({ + [`GET ${F}`]: () => + Response.json({ + findings: Array.from({ length: 100 }, (_, i) => finding(`F-${i + 1}`)), + nextCursor: '100', + }), + }); + const out = capture(); + await run(root, ['security', 'list']); + expect(calls).toHaveLength(5); + expect(out.join('\n')).toContain('Showing the first 500.'); + }); + + it('shows the full detail, and only the summary to a reader', async () => { + const root = linked(); + route({ + [`GET ${F}/F-1`]: () => + Response.json({ + finding: finding('F-1', { + evidence: 'EVID', + fix: 'FIXTEXT', + verdictSource: 'runtime', + runtimeProof: { request: 'r2', method: 'GET', path: '/users?id=1', status: 200 }, + }), + events: [ + { + createdAt: '2026-11-17T10:00:00.000Z', + action: 'comment', + actorKind: 'user', + actor: 'ana', + actorRole: 'admin', + comment: 'looked', + }, + ], + }), + [`GET ${F}/F-2`]: () => + Response.json({ finding: { ...finding('F-2'), title: undefined, file: undefined } }), + }); + const out = capture(); + await run(root, ['security', 'show', 'F-1']); + let text = out.join('\n'); + expect(text).toContain('title F-1'); + expect(text).toContain('EVID'); + expect(text).toContain('FIXTEXT'); + expect(text).toContain('confirmed (runtime)'); + expect(text).toContain('GET /users?id=1 answered 200 on a throwaway copy'); + expect(text).toContain('ana'); + out.length = 0; + await run(root, ['security', 'show', 'F-2']); + text = out.join('\n'); + expect(text).toContain('Readers see the id, severity and state'); + expect(text).not.toContain('Evidence'); + }); + + it('adds a comment', async () => { + const root = linked(); + const calls = route({ + [`POST ${F}/F-3/comments`]: () => Response.json({ ok: true, id: 'F-3' }), + }); + const out = capture(); + await run(root, ['security', 'comment', 'F-3', 'checked by hand']); + expect(out.join('\n')).toContain('Comment added to F-3.'); + expect(calls[0]?.body).toEqual({ text: 'checked by hand' }); + }); + + it('reopens with the revision it read first', async () => { + const root = linked(); + const calls = route({ + [`GET ${F}/F-4`]: () => Response.json({ finding: finding('F-4', { revision: 7 }) }), + [`POST ${F}/F-4/reopen`]: () => Response.json({ ok: true, id: 'F-4' }), + }); + const out = capture(); + await run(root, ['security', 'reopen', 'F-4', '--comment', 'still reachable']); + expect(out.join('\n')).toContain('F-4 reopened.'); + expect(calls.map((c) => c.method)).toEqual(['GET', 'POST']); + expect(calls[1]?.body).toEqual({ comment: 'still reachable', expectedRevision: 7 }); + }); + + it('lists scans and notes older ones', async () => { + const root = linked(); + const calls = route({ + 'GET /projects/project_1/security/scans': () => + Response.json({ scans: [scan], nextCursor: '9' }), + }); + const out = capture(); + await run(root, ['security', 'scans', '--limit', '5']); + const text = out.join('\n'); + expect(calls[0]?.path).toBe('/projects/project_1/security/scans?limit=5'); + expect(text).toContain('dpl_8f2c'); + expect(text).toContain('$0.40'); + expect(text).toContain('Older scans exist.'); + }); + + it('shows the model, then sets it, resets it to the default', async () => { + const root = linked(); + const calls = route({ + 'GET /projects/project_1/security': () => Response.json(status), + 'PUT /projects/project_1/security/model': () => + Response.json({ ok: true, model: { ...status.model, id: '@cf/y' } }), + }); + const out = capture(); + await run(root, ['security', 'model']); + expect(out.join('\n')).toContain('provider notice not accepted'); + out.length = 0; + await run(root, ['security', 'model', '@cf/y']); + expect(out.join('\n')).toContain('scans now use @cf/y'); + expect(calls.at(-1)?.body).toEqual({ model: '@cf/y' }); + out.length = 0; + await run(root, ['security', 'model', '--default']); + expect(out.join('\n')).toContain('uses the platform default model (@cf/y)'); + expect(calls.at(-1)?.body).toEqual({ model: null }); + }); + + it('shows the budget, sets it with --usd and clears it with --off', async () => { + const root = linked(); + const calls = route({ + 'GET /projects/project_1/security': () => Response.json(status), + 'PUT /projects/project_1/security/budget': () => + Response.json({ ok: true, budget: { ...status.budget, capUsd: 100 } }), + }); + const out = capture(); + await run(root, ['security', 'budget']); + expect(out.join('\n')).toContain('$100.00 / month (set for this project)'); + out.length = 0; + await run(root, ['security', 'budget', '--usd', '40']); + expect(out.join('\n')).toContain('scan budget set to $40.00 / month'); + expect(calls.at(-1)?.body).toEqual({ monthlyUsd: 40 }); + out.length = 0; + await run(root, ['security', 'budget', '--off']); + expect(out.join('\n')).toContain('own cap cleared'); + expect(calls.at(-1)?.body).toEqual({ monthlyUsd: null }); + }); + + it('resolves several ids, keeps going after one fails, then fails the command', async () => { + const root = linked(); + const calls = route({ + [`GET ${F}/F-1`]: () => Response.json({ finding: finding('F-1', { revision: 1 }) }), + [`GET ${F}/F-2`]: () => Response.json({ finding: finding('F-2', { revision: 1 }) }), + [`GET ${F}/F-3`]: () => Response.json({ finding: finding('F-3', { revision: 1 }) }), + [`POST ${F}/F-1/resolve`]: () => + Response.json({ ok: true, id: 'F-1', state: 'resolved', resolution: 'accepted_risk' }), + [`POST ${F}/F-2/resolve`]: () => + Response.json({ error: 'finding changed', message: 'F-2 changed.' }, { status: 409 }), + [`POST ${F}/F-3/resolve`]: () => + Response.json({ ok: true, id: 'F-3', state: 'resolved', resolution: 'accepted_risk' }), + 'GET /projects/project_1/security': () => Response.json(status), + }); + const out = capture(); + await expect( + run(root, [ + 'security', + 'resolve', + 'F-1,F-2,F-3', + '--reason', + 'accepted-risk', + '--comment', + 'ok', + ]), + ).rejects.toThrow('1 of 3 findings were not resolved'); + const text = out.join('\n'); + expect(text).toContain('F-1 resolved (accepted risk)'); + expect(text).toContain('F-2: F-2 changed.'); + expect(text).toContain('F-3 resolved (accepted risk)'); + expect(calls.filter((c) => c.method === 'POST')).toHaveLength(3); + }); + + it('prints one JSON document with --json', async () => { + const root = linked(); + route({ 'GET /projects/project_1/security': () => Response.json(status) }); + const out = capture(); + await run(root, ['security', 'status', '--json']); + expect(out).toHaveLength(1); + expect(JSON.parse(out[0]!)).toMatchObject({ policy: { mode: 'public' }, counts: { leads: 3 } }); + route({ [`GET ${F}`]: () => Response.json({ findings: [finding('F-1')], nextCursor: null }) }); + out.length = 0; + await run(root, ['security', 'list', '--json']); + expect(JSON.parse(out[0]!)).toMatchObject({ findings: [{ id: 'F-1' }], more: false }); + }); +}); + +describe('project security severity (M35)', () => { + it('parses a level or scan, and needs a comment', () => { + expect( + parseProjectArgs(['security', 'severity', 'f-12', 'medium', '--comment', 'admins only']), + ).toMatchObject({ action: 'severity', id: 'F-12', severity: 'medium', comment: 'admins only' }); + expect( + parseProjectArgs(['security', 'severity', 'F-12', 'scan', '--comment', 'undo']), + ).toMatchObject({ severity: null }); + expect(() => parseProjectArgs(['security', 'severity', 'F-12', 'medium'])).toThrow( + 'A comment is required', + ); + expect(() => + parseProjectArgs(['security', 'severity', 'F-12', 'urgent', '--comment', 'x']), + ).toThrow("Invalid severity 'urgent'"); + expect(() => parseProjectArgs(['security', 'severity', 'F-12', '--comment', 'x'])).toThrow( + 'Usage: void project security severity ', + ); + expect(() => + parseProjectArgs(['security', 'severity', 'F-12', 'low', '--reason', 'fixed']), + ).toThrow('--reason is not used with security severity'); + }); + + it('sends the level with the revision it read and says what changed', async () => { + const root = linked(); + const calls = route({ + [`GET ${F}/F-12`]: () => Response.json({ finding: finding('F-12', { revision: 4 }) }), + [`POST ${F}/F-12/severity`]: () => + Response.json({ + ok: true, + id: 'F-12', + severity: 'medium', + scanSeverity: 'high', + severityEdited: true, + urgent: false, + revision: 5, + changed: true, + }), + }); + const out = capture(); + await run(root, ['security', 'severity', 'F-12', 'medium', '--comment', 'behind admin auth']); + expect(out.join('\n')).toContain( + '✓ F-12 severity set to medium (scans said high). Later scans keep it.', + ); + expect(calls.map((c) => `${c.method} ${c.path}`)).toEqual([ + `GET ${F}/F-12`, + `POST ${F}/F-12/severity`, + ]); + expect(calls[1]?.body).toEqual({ + severity: 'medium', + comment: 'behind admin auth', + expectedRevision: 4, + }); + }); + + it('says when it goes back to the scan value, when nothing changed, and on an old platform', async () => { + const root = linked(); + let reply: Record = { + ok: true, + id: 'F-12', + severity: 'high', + scanSeverity: 'high', + severityEdited: false, + urgent: true, + revision: 6, + changed: true, + }; + const calls = route({ + [`GET ${F}/F-12`]: () => Response.json({ finding: finding('F-12', { revision: 5 }) }), + [`POST ${F}/F-12/severity`]: () => Response.json(reply), + }); + const out = capture(); + await run(root, ['security', 'severity', 'F-12', 'scan', '--comment', 'undo']); + expect(out.join('\n')).toContain('✓ F-12 uses the scan severity again: high.'); + expect(calls[1]?.body).toMatchObject({ severity: null }); + + out.length = 0; + reply = { ...reply, severity: 'low', severityEdited: true, changed: false }; + await run(root, ['security', 'severity', 'F-12', 'low', '--comment', 'again']); + expect(out.join('\n')).toContain('F-12 is already low. Nothing changed.'); + + route({ [`GET ${F}/F-12`]: () => Response.json({ finding: finding('F-12') }) }); + await expect( + run(root, ['security', 'severity', 'F-12', 'low', '--comment', 'x']), + ).rejects.toThrow('cannot change finding severity yet'); + }); + + it('shows who set the severity and the change in the history', async () => { + const root = linked(); + route({ + [`GET ${F}/F-12`]: () => + Response.json({ + finding: finding('F-12', { severity: 'low', severityEdited: true, scanSeverity: 'high' }), + events: [ + { + createdAt: '2026-11-17T10:00:00.000Z', + action: 'severity_edited', + actorKind: 'user', + actor: 'ana', + actorRole: 'admin', + resolution: null, + severityFrom: 'high', + severityTo: 'low', + comment: 'admins only', + }, + ], + }), + }); + const out = capture(); + await run(root, ['security', 'show', 'F-12']); + const text = out.join('\n'); + expect(text).toContain('Severity set by a person (scans said high).'); + expect(text).toContain('severity_edited (high → low) · ana (admin)'); + }); +}); diff --git a/packages/void/test/unit/project-zero-trust-command.test.ts b/packages/void/test/unit/project-zero-trust-command.test.ts index 0289b44b4..7a27e294a 100644 --- a/packages/void/test/unit/project-zero-trust-command.test.ts +++ b/packages/void/test/unit/project-zero-trust-command.test.ts @@ -1,9 +1,11 @@ import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; +import { stripVTControlCharacters } from 'node:util'; import { afterEach, describe, expect, it, vi } from 'vite-plus/test'; import { savePlatformConnection } from '../../src/cli/platform-registry.ts'; import { runProjectCommand } from '../../src/cli/project-cmd.ts'; +import { runProjectZeroTrustCommand } from '../../src/cli/project-zero-trust.ts'; import { withPlatformDiscovery } from '../helpers/platform-discovery.ts'; const roots: Array = []; @@ -71,7 +73,12 @@ describe('project Zero Trust command', () => { output.push(String(chunk)); return true; }); - await runProjectCommand(root, { subcommand: 'zero-trust', action: 'public', projectSlug: '' }); + await runProjectCommand(root, { + subcommand: 'zero-trust', + action: 'public', + projectSlug: '', + json: false, + }); expect(output.join('')).toContain('still in progress'); expect(output.join('')).toContain('void project zero-trust reconcile'); expect(output.join('')).not.toContain('linked-app is public'); @@ -102,7 +109,12 @@ describe('project Zero Trust command', () => { output += String(chunk); return true; }); - await runProjectCommand(root, { subcommand: 'zero-trust', action: 'protect', projectSlug: '' }); + await runProjectCommand(root, { + subcommand: 'zero-trust', + action: 'protect', + projectSlug: '', + json: false, + }); expect(output).toContain('needs attention'); expect(output).not.toContain('✓'); expect(output).not.toContain('is protected'); @@ -145,6 +157,7 @@ describe('project Zero Trust command', () => { subcommand: 'zero-trust', action: 'status', projectSlug: '', + json: false, }); expect(fetchMock.mock.calls.map(([input]) => String(input))).toEqual([ @@ -193,6 +206,7 @@ describe('project Zero Trust command', () => { subcommand: 'zero-trust', action: 'status', projectSlug: '', + json: false, }); const rendered = output.join(''); @@ -230,16 +244,19 @@ describe('project Zero Trust command', () => { subcommand: 'zero-trust', action: 'protect', projectSlug: '', + json: false, }); await runProjectCommand(root, { subcommand: 'zero-trust', action: 'public', projectSlug: '', + json: false, }); await runProjectCommand(root, { subcommand: 'zero-trust', action: 'reconcile', projectSlug: '', + json: false, }); expect(fetchMock.mock.calls).toEqual([ @@ -291,6 +308,7 @@ describe('project Zero Trust command', () => { subcommand: 'zero-trust', action: 'status', projectSlug: '', + json: false, }); const rendered = output.join(''); @@ -299,3 +317,337 @@ describe('project Zero Trust command', () => { expect(rendered).not.toContain('\u009d'); }); }); + +const project = { + project_id: 'project_1', + desired_protected: true, + effective_protected: true, + state: 'protected', + last_error: null, + updated_at: '2026-11-17T00:00:00Z', +}; + +function request(state: string, extra: Record = {}) { + return { + id: 'spr_1', + state, + heldReason: null, + targetDeploymentId: 'dpl_9a1d', + gateScanId: null, + blockers: { count: 0, ids: [] }, + requestedAt: '2026-11-17T00:00:00Z', + requestedByRole: 'admin', + ...extra, + }; +} + +function capture() { + const output: Array = []; + const logged: Array = []; + vi.spyOn(console, 'log').mockImplementation((...parts) => { + logged.push(parts.join(' ')); + }); + vi.spyOn(process.stdout, 'write').mockImplementation((chunk) => { + output.push(String(chunk)); + return true; + }); + return { text: () => output.join(''), logged }; +} + +function setup(fetchMock: unknown) { + const root = linkedProject(); + vi.stubEnv('VOID_TOKEN', 'test-token'); + vi.stubEnv('VOID_API_URL', 'https://api.example.test'); + vi.stubGlobal('fetch', withPlatformDiscovery(fetchMock)); + return root; +} + +const base = { subcommand: 'zero-trust', projectSlug: '', json: false } as const; + +describe('project Zero Trust command with a public request', () => { + it('prints a held 202 as protected, never as public', async () => { + const fetchMock = vi.fn(async () => + Response.json( + { + ok: true, + project: { + ...project, + state: 'reconciling', + last_error: 'old CLI line that must not print', + }, + publicRequest: request('waiting_scan'), + message: + 'Waiting for a security scan of dpl_9a1d before linked-app goes public. It stays protected by Zero Trust until the scan passes.', + }, + { status: 202 }, + ), + ); + const root = setup(fetchMock); + const out = capture(); + await runProjectCommand(root, { ...base, action: 'public' }); + const text = out.text(); + expect(text).toContain('Waiting for a security scan of dpl_9a1d'); + expect(text).toContain('stays protected'); + expect(text).not.toContain('is public'); + expect(text).not.toContain('old CLI line'); + expect(text).not.toContain('still in progress'); + expect(text).not.toContain('✓'); + }); + + it('falls back to the local copy when the held reply has no message', async () => { + const root = setup( + vi.fn(async () => + Response.json( + { + ok: true, + project: { ...project, state: 'reconciling' }, + publicRequest: request('held_findings', { blockers: { count: 1, ids: ['F-12'] } }), + }, + { status: 202 }, + ), + ), + ); + const out = capture(); + await runProjectCommand(root, { ...base, action: 'public' }); + expect(out.text()).toContain('1 urgent finding must be resolved'); + expect(out.text()).toContain('F-12'); + expect(out.text()).not.toContain('bypass the scan'); + }); + + it('prints the held reply as JSON with the stored state', async () => { + const root = setup( + vi.fn(async () => + Response.json( + { + ok: true, + project: { ...project, state: 'reconciling', last_error: 'old line' }, + publicRequest: request('waiting_scan'), + message: 'Waiting.', + }, + { status: 202 }, + ), + ), + ); + const out = capture(); + await runProjectCommand(root, { ...base, action: 'public', json: true }); + expect(out.logged).toHaveLength(1); + const printed = JSON.parse(out.logged[0]!); + expect(printed.held).toBe(true); + expect(printed.project).toMatchObject({ state: 'protected', last_error: null }); + expect(printed.publicRequest.state).toBe('waiting_scan'); + }); + + it('keeps an old platform reply exactly as before with --json off', async () => { + const root = setup( + vi.fn(async () => + Response.json({ + ok: true, + project: { + ...project, + desired_protected: false, + effective_protected: false, + state: 'public', + }, + }), + ), + ); + const out = capture(); + await runProjectCommand(root, { ...base, action: 'public' }); + expect(out.text()).toContain('linked-app is public.'); + }); + + it('shows the request block in status', async () => { + const fetchMock = vi.fn(async (input: RequestInfo | URL) => + String(input).endsWith('/security') + ? Response.json({ backlogFiles: 0, budget: null }) + : Response.json({ + available: true, + platformStatus: 'ready', + protectNewProjects: true, + publicGate: true, + publicRequest: request('held_no_result', { heldReason: 'timed_out' }), + project, + }), + ); + const root = setup(fetchMock); + const out = capture(); + await runProjectCommand(root, { ...base, action: 'status' }); + // CI forces colour: strip it so the box borders split cleanly. + const flat = stripVTControlCharacters(out.text()) + .split('│') + .join(' ') + .split('\n') + .join(' ') + .split(' ') + .filter(Boolean) + .join(' '); + expect(flat).toContain( + 'Public request: Stays protected: the security scan did not finish (timed out)', + ); + expect(flat).toContain('void project zero-trust bypass --reason'); + }); + + it('prints status as JSON', async () => { + const reply = { + available: true, + platformStatus: 'ready', + protectNewProjects: true, + publicRequest: null, + project, + }; + const root = setup(vi.fn(async () => Response.json(reply))); + const out = capture(); + await runProjectCommand(root, { ...base, action: 'status', json: true }); + expect(JSON.parse(out.logged[0]!)).toEqual(reply); + }); +}); + +describe('project Zero Trust bypass', () => { + function bypassFetch( + bypass: () => Response, + open = request('held_no_result', { heldReason: 'timed_out' }), + ) { + return vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => + String(input).endsWith('/public-request/bypass') && init?.method === 'POST' + ? bypass() + : Response.json({ + available: true, + platformStatus: 'ready', + protectNewProjects: true, + publicRequest: open, + project, + }), + ); + } + const goingPublic = () => + Response.json({ + ok: true, + project: { ...project, desired_protected: false, state: 'reconciling' }, + publicRequest: request('bypassed'), + skipped: 'the scan did not finish (timed out)', + }); + const args = { ...base, action: 'bypass', reason: 'Scanner down', yes: false } as const; + + it('confirms what is skipped, then posts the reason', async () => { + const fetchMock = bypassFetch(goingPublic); + const root = setup(fetchMock); + const out = capture(); + const ask = vi.fn(async () => true); + await runProjectZeroTrustCommand(root, args, { interactive: true, confirm: ask }); + expect(ask).toHaveBeenCalledWith('Bypass the scan and make linked-app public?'); + const post = fetchMock.mock.calls.find(([, init]) => init?.method === 'POST')!; + expect(JSON.parse(String(post[1]!.body))).toEqual({ reason: 'Scanner down' }); + expect(out.text()).toContain( + 'This skips the security scan. The scan of dpl_9a1d did not finish (timed out).', + ); + expect(out.text()).toContain('Your platform admins get an email with your reason'); + expect(out.text()).toContain( + 'Scan bypassed. linked-app is going public (Zero Trust update in progress).', + ); + }); + + it('changes nothing when the prompt is declined', async () => { + const fetchMock = bypassFetch(goingPublic); + const root = setup(fetchMock); + const out = capture(); + await runProjectZeroTrustCommand(root, args, { interactive: true, confirm: async () => false }); + expect(fetchMock.mock.calls.some(([, init]) => init?.method === 'POST')).toBe(false); + expect(out.text()).toContain('Nothing was changed.'); + }); + + it('needs --yes when it cannot prompt', async () => { + const fetchMock = bypassFetch(goingPublic); + const root = setup(fetchMock); + capture(); + await expect(runProjectZeroTrustCommand(root, args, { interactive: false })).rejects.toThrow( + 'Add --yes', + ); + await expect( + runProjectZeroTrustCommand(root, { ...args, json: true }, { interactive: true }), + ).rejects.toThrow('Add --yes'); + expect(fetchMock.mock.calls.some(([, init]) => init?.method === 'POST')).toBe(false); + }); + + it('skips the prompt with --yes and prints JSON', async () => { + const root = setup(bypassFetch(goingPublic)); + const out = capture(); + await runProjectZeroTrustCommand( + root, + { ...args, yes: true, json: true }, + { interactive: false }, + ); + const printed = JSON.parse(out.logged[0]!); + expect(printed.publicRequest.state).toBe('bypassed'); + expect(printed.skipped).toContain('did not finish'); + }); + + it('names the open urgent findings on a 409', async () => { + const root = setup( + bypassFetch( + () => + Response.json( + { + error: 'security public request has urgent findings', + message: 'platform copy', + blockers: { count: 2, ids: ['F-12', 'F-15'] }, + }, + { status: 409 }, + ), + request('held_findings', { blockers: { count: 2, ids: ['F-12', 'F-15'] } }), + ), + ); + capture(); + const failure = await runProjectZeroTrustCommand(root, { ...args, yes: true }).catch( + (error: Error) => error, + ); + expect((failure as Error).message).toContain( + 'linked-app has 2 urgent findings open (F-12, F-15). A bypass skips only the scan, not open findings.', + ); + expect((failure as Error).message).toContain('→ void project security list --urgent'); + }); + + it('says there is no request to bypass', async () => { + const root = setup(bypassFetch(goingPublic, null as never)); + capture(); + await expect(runProjectZeroTrustCommand(root, { ...args, yes: true })).rejects.toThrow( + 'linked-app has no public request to bypass. Run: void project zero-trust public', + ); + }); + + it('uses the platform message for a closed request', async () => { + const root = setup( + bypassFetch(() => + Response.json( + { + error: 'public request closed', + message: 'The public request is passed.', + state: 'passed', + }, + { status: 409 }, + ), + ), + ); + capture(); + await expect(runProjectZeroTrustCommand(root, { ...args, yes: true })).rejects.toThrow( + 'The public request is passed.', + ); + }); + + it('names an old platform that has no bypass route', async () => { + const fetchMock = vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => + init?.method === 'POST' + ? new Response('Not Found', { status: 404 }) + : Response.json({ + available: true, + platformStatus: 'ready', + protectNewProjects: true, + project, + }), + ); + const root = setup(fetchMock); + capture(); + await expect(runProjectZeroTrustCommand(root, { ...args, yes: true })).rejects.toThrow( + 'does not support security audits', + ); + }); +}); diff --git a/packages/void/test/unit/security-sarif.test.ts b/packages/void/test/unit/security-sarif.test.ts new file mode 100644 index 000000000..3ef076ac0 --- /dev/null +++ b/packages/void/test/unit/security-sarif.test.ts @@ -0,0 +1,205 @@ +import { describe, expect, it } from 'vite-plus/test'; +import { SARIF_SCHEMA_URI, securityFindingsSarif } from '../../src/cli/security-sarif.ts'; + +type SarifResult = { + ruleId: string; + level: string; + message: { text: string }; + locations?: unknown; + partialFingerprints: Record; + suppressions?: unknown; + properties: Record; +}; + +type Log = { + $schema: string; + version: string; + runs: Array<{ + tool: { driver: { name: string; version?: string; rules: Array> } }; + results: Array; + }>; +}; + +const sarif = (findings: Parameters[0], version = '1.10.0') => + securityFindingsSarif(findings, { version }) as unknown as Log; + +describe('securityFindingsSarif (M31)', () => { + it('writes a SARIF 2.1.0 log with one run and the CLI version', () => { + const log = sarif([]); + expect(log.$schema).toBe(SARIF_SCHEMA_URI); + expect(log.version).toBe('2.1.0'); + expect(log.runs).toHaveLength(1); + expect(log.runs[0]!.tool.driver).toMatchObject({ + name: 'Void Security Audit', + version: '1.10.0', + rules: [], + }); + expect(log.runs[0]!.results).toEqual([]); + const noVersion = securityFindingsSarif([], { version: null }) as unknown as Log; + expect(noVersion.runs[0]!.tool.driver.version).toBeUndefined(); + }); + + it('maps severity to level, file and lines to a location, and keys a result by finding id', () => { + const log = sarif([ + { + id: 'F-12', + verdict: 'confirmed', + severity: 'critical', + state: 'open', + urgent: true, + title: 'SQL injection in /api/users', + category: 'sql-injection', + cwe: 'CWE-89', + file: 'src/routes/users.ts', + line: 41, + lineEnd: 44, + verdictSource: 'runtime', + }, + { + id: 'F-13', + verdict: 'confirmed', + severity: 'medium', + state: 'open', + title: 'Open redirect', + category: 'open-redirect', + file: 'src/a b.ts', + line: 0, + }, + { + id: 'F-14', + verdict: 'needs_validation', + severity: null, + state: 'open', + title: 'Possible SSRF', + category: 'ssrf', + file: null, + }, + ]); + const [critical, medium, lead] = log.runs[0]!.results; + expect(critical).toEqual({ + ruleId: 'sql-injection', + level: 'error', + message: { text: 'F-12: SQL injection in /api/users' }, + locations: [ + { + physicalLocation: { + artifactLocation: { uri: 'src/routes/users.ts', uriBaseId: '%SRCROOT%' }, + region: { startLine: 41, endLine: 44 }, + }, + }, + ], + partialFingerprints: { 'voidFinding/v1': 'F-12' }, + properties: { + id: 'F-12', + severity: 'critical', + verdict: 'confirmed (runtime)', + state: 'open', + urgent: true, + cwe: 'CWE-89', + }, + }); + // No line: a file location only. Path segments are URI-encoded. + expect(medium!.level).toBe('warning'); + expect(medium!.locations).toEqual([ + { physicalLocation: { artifactLocation: { uri: 'src/a%20b.ts', uriBaseId: '%SRCROOT%' } } }, + ]); + expect(lead).toMatchObject({ level: 'note', properties: { verdict: 'lead' } }); + expect(lead!.locations).toBeUndefined(); + }); + + it('marks a resolved finding as suppressed with its reason', () => { + const [result] = sarif([ + { + id: 'F-3', + verdict: 'confirmed', + severity: 'high', + state: 'resolved', + resolution: 'accepted_risk', + title: 'Weak hash', + category: 'crypto', + }, + ]).runs[0]!.results; + expect(result!.suppressions).toEqual([ + { kind: 'external', status: 'accepted', justification: 'accepted risk' }, + ]); + }); + + it('gives a reader finding a generic rule and message, with no details', () => { + const [result] = sarif([{ id: 'F-7', verdict: 'confirmed', severity: 'high', state: 'open' }]) + .runs[0]!.results; + expect(result).toMatchObject({ + ruleId: 'finding', + level: 'error', + message: { text: 'F-7: high finding. Ask a project collaborator for the details.' }, + }); + }); + + it('lists each category once with its highest security-severity and CWEs', () => { + const log = sarif([ + { + id: 'F-1', + verdict: 'confirmed', + severity: 'medium', + state: 'open', + title: 'a', + category: 'secret-in-output', + cwe: 'CWE-798', + }, + { + id: 'F-2', + verdict: 'confirmed', + severity: 'high', + state: 'open', + title: 'b', + category: 'secret-in-output', + cwe: 'CWE-200', + }, + { + id: 'F-3', + verdict: 'needs_validation', + severity: null, + state: 'open', + title: 'c', + category: 'ai-reviewer-text', + }, + ]); + expect(log.runs[0]!.tool.driver.rules).toEqual([ + { + id: 'secret-in-output', + shortDescription: { text: 'secret in output' }, + properties: { tags: ['security', 'CWE-798', 'CWE-200'], 'security-severity': '8.0' }, + }, + { + id: 'ai-reviewer-text', + shortDescription: { text: 'ai reviewer text' }, + properties: { tags: ['security'] }, + }, + ]); + }); + + it('keys findings of several projects apart, and strips control characters', () => { + const log = sarif([ + { + id: 'F-1', + project: 'acme-web', + verdict: 'confirmed', + severity: 'low', + state: 'open', + title: 'x\u001b[31m\ny', + }, + { + id: 'F-1', + project: 'acme-api', + verdict: 'confirmed', + severity: 'low', + state: 'open', + title: 'z', + }, + ]); + const [web, api] = log.runs[0]!.results; + expect(web!.partialFingerprints).toEqual({ 'voidFinding/v1': 'acme-web/F-1' }); + expect(api!.partialFingerprints).toEqual({ 'voidFinding/v1': 'acme-api/F-1' }); + expect(web!.properties.project).toBe('acme-web'); + expect(web!.message.text).toBe('F-1: x y'); + }); +}); diff --git a/platform/meta/design-docs/0095-security-audits.md b/platform/meta/design-docs/0095-security-audits.md new file mode 100644 index 000000000..d4130e6d3 --- /dev/null +++ b/platform/meta/design-docs/0095-security-audits.md @@ -0,0 +1,2724 @@ +--- +title: Security audits on deploy +status: implemented +created: 2026-11-18 +--- + +# Security audits on deploy + +Plan for building the approved PRD, all three phases, in one PR with one commit +per milestone. Product rules, copy and the 94 edge cases stay in the PRD and spec; +this file says where the code goes, in what order, and how we test it. + +- PRD: `void-prds/security-audits-prd.md` (short), spec: `void-prds/security-audits-spec.md`. + Decision numbers D1–D52 and Q1–Q15 come from there. +- Background: [project Zero Trust](./0083-project-zero-trust.md), + [managed Sandbox restoration](./0082-managed-sandbox-restoration.md), + [operator CLI](./0078-platform-operator-cli.md), + [permission errors](./0081-project-permission-errors.md), + [installation plans](./0090-installation-plans.md), + [AI Gateway logging policy](./0094-ai-gateway-logging-policy.md). +- The spec calls this doc `0094-security-audits.md`; 0094 is taken, so it is 0095. + +## Contract (short) + +- A deploy that reaches `live` writes a scan row in the same transaction. The scan + runs later, in a container with no internet. Scans never block, slow or fail a + deploy (D45). +- Open `confirmed` + `critical`/`high` findings are urgent. Only humans resolve. +- With "Scan before a project goes public" on, a protected project asked to go + public stays protected until a scan of its live deployment passes, or someone + bypasses the scan while no urgent finding is open (D46). +- Capability off: the install is the same as today, except the idle + `SecurityScanScheduler` DO class in the API Worker. +- Native `void deploy --platform cloudflare` does not change at all. + +## Scanner invariants + +Every change to the scanner, the controller, the model proxy or the gate must keep these. +Each one has tests (named) or a spike that checks it. + +| # | Invariant | Held by | Checked by | +| --- | ---------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| I1 | A scan never blocks, slows or fails a deploy, rollback, build or GitHub check (D45) | go-live tx writes a row only; all scan work runs after commit; the GitHub check is `neutral` | `security-enqueue.test.ts`, `security-github-check.test.ts` | +| I2 | The container has no internet. It reaches only `model.void.internal` and `copy.void.internal`, and the input comes in over `exec` stdin | `start({ enableInternet: false, env: {} })`, outbound intercepts in the controller | S11 (egress 19/19); S1 not recorded | +| I3 | No credential enters the container: no token in env or files; identity is in service-binding props; own provider keys stay in the API (M33) | `ScanModelOutbound` / `CopyOutbound` props, proxy adds headers | S11, `security-byok.test.ts`; S1 not recorded | +| I4 | Every controller write carries `(scan, attempt)`; a write from an ended or reaped attempt is refused | lease + attempt fence in `control.ts` | `security-scan-control.test.ts` | +| I5 | Only a human closes a finding; a scan adds, confirms or reopens. A human severity is never changed by a scan | `findings.ts` `decideSeenFinding` | `security-findings-rules.test.ts` | +| I6 | No project goes public through a gated request without a gate pass or a recorded bypass; no bypass while an urgent finding is open (D46, D50) | `public-gate-judge.ts`, bypass under the project lock | `security-gate-bypass.test.ts` ("public gate bypass races", #94), `security-public-gate.test.ts` (bypass refused while urgent open), `security-gate-judge.test.ts`, `security-gate-zero-trust.test.ts` | +| I7 | A scan starts only when its worst case fits every cap; each model call is metered against the hold; own-key spend counts too (R14) | scheduler reserve, proxy `UPDATE … RETURNING` | `security-budget.test.ts`, S11 (caps 12/12) | +| I8 | No code goes to a third-party model before its provider notice is accepted; a fallback never moves a `@cf` scan to a third party | model resolve, `fallback.ts` | `security-fallback.test.ts`, `api-project-security.test.ts` | +| I9 | Stored secret values are replaced before any model sees code; a secret finding never stores the value; no runtime copy when a value is in the bundle | `input/redact.ts`, `runtime-copy-plan.ts` | `security-redact.test.ts`, `security-runtime-copy.test.ts` | +| I10 | A refused, timed-out, failed or incomplete scan is never "clean" for the gate, the page or the GitHub check | `ingest.ts` outcome table | S9 (24/24), `security-ingest.test.ts` | +| I11 | Files from the scanned code (`AGENTS.md`, `.claude/`, `.codex/`, `.agents/skills`, `.mcp.json`) are input only, never engine config | Engine A `settingSources: []`, Engine C empty cwd and own `CODEX_HOME` | S2, S3, S11 | +| I12 | A local check never opens, reopens, proves or holds anything (R13) | `storeLocalOutcome` | `security-local-check.test.ts` | +| I13 | Capability off: only the idle `SecurityScanScheduler` class is new; native Cloudflare deploys are unchanged | runtime manifest, CLI target checks | capability-off cases in `security-enqueue.test.ts` and `api-project-security.test.ts`; `cloudflare-deploy.test.ts`, `cf-version-runner.test.ts`, `worker-config.test.ts` | + +## Architecture + +``` + ┌──────────────────────────── API Worker (trusted) ─────────────────────────────┐ + void deploy ──► admit ─►│ pipeline ─► commitCutoverLive tx ──► security_scans(pending_input) [outbox] │ + (CLI / CI / build) │ │ after commit: copy inline files to R2, row → queued, poke │ + │ ▼ │ + │ SecurityScanScheduler DO (singleton 'global') │ + │ round-robin by owner · concurrency · @cf token bucket │ + │ reserve budget (spend rows) · lease + attempt · notifications outbox sender │ + │ │ start(scanId, attempt, engine, image) │ + │ ▼ │ + │ SecurityScanControl (WorkerEntrypoint, RPC only, no HTTP route) │ + │ input(scan, attempt) → tar stream (tier, filters, redaction, memory) │ + │ model(scan, attempt, request) → model proxy │ + │ heartbeat / result(scan, attempt, findings.json) → ingest (one tx) │ + │ │ + │ model proxy: allowlist · caps (UPDATE…RETURNING) · fixed gateway headers ─────┼──► AI Gateway + │ signed {"securityScan":tag} · access_programs for openai/* │ (installation gateway) + │ │ @cf: env.AI binding + │ policy (platform_settings) · public gate (ZT checkpoint) · findings · budget │ 3rd party: REST /ai/v1/* + │ routes: /projects/:id/security* · /operator/v1/security* · /admin/security │ + │ /security/projects/:slug (signed page) · hourly cron jobs │ + └───────────────▲───────────────────────────────┬───────────────────────────────┘ + │ service binding (props = identity) ▲ email (env.EMAIL) + ┌──────── void-security-scanner controller Worker (ours) ────────┐ │ │ + │ ScannerController DO, one instance per scan id │─────┘ └── owner, admins, deploy authors, + │ interceptOutboundHttp('model.void.internal', ScanModelOutbound)│ installation admins + │ interceptAllOutboundHttp(DenyAll) │ + │ start({enableInternet:false, env: no tokens}) │ + │ write input · exec runner (non-root) · poll /scan/out · alarm │ + └──────────────┬──────────────────────────────────────────────────┘ + ▼ + ┌──────── scanner container (untrusted) ─────────┐ PostgreSQL (Hyperdrive) + │ Void runner: hunt → verify (≤10) → findings │ platform_settings['securityAudits.policy'] + │ A anthropic/* Claude Agent SDK │ project_security_settings, security_scans, + │ C openai/* Codex SDK + void-scan MCP │ security_findings, security_finding_events, + │ B @cf/* Void tool loop │ security_public_requests, security_scan_bypasses, + │ http://model.void.internal/* only │ security_*_spend, security_notifications, … + └────────────────────────────────────────────────┘ + R2 STATIC_ASSETS_R2 (existing bucket) + CLI: void project security · zero-trust bypass · security-scans/{project}/{deployment}/ inputs + deploy notice · void platform security security-scans/{project}/backlog.json + Admin: /admin/security · Project detail · Zero Trust page security-scans/{project}/scans/{scan}/ raw, 30 d +``` + +Main choices (spec text says the same promise another way; flagged in Risks): + +| Choice | Why | +| ------------------------------------------------------------------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `SecurityScanControl` RPC entrypoint, not `/internal/security-scans/*` HTTP | Same as `SandboxControl`: identity comes from immutable binding `props`, nothing on the API hostname, no Access allowlist entry | +| API builds the input and streams it to the controller | Redaction needs project secrets; the controller and container get no R2, DB or secret | +| `@cf/*` through `env.AI.run`, third-party through REST `/ai/v1/*` with `cf-aig-gateway-id` | No new token permission for the default model; REST only when a third-party host is used (probe check 5 reports a missing permission). S10 can move `@cf` to REST if the binding ignores the payload header | +| Scheduler DO in the API Worker, scanner in a separate controller Worker | Losing Containers never breaks API upgrades (spec §5.1) | +| One installation-wide controller Worker + container app | Created at first move away from `disabled`, verified by the probe | + +## Package and file layout + +New code (paths from repo root): + +``` +packages/platform/src/ + security-models.ts model list, engines, hosts, badges, prices, reserves → @void/platform/security-models + security-policy.ts policy type, defaults, parser, limits ranges, copy keys → @void/platform/security-policy +platform/packages/security-scanner/ @voidcloud/security-scanner (private, new workspace package) + src/runner/{main,phases,extract,status,validate-findings}.ts + src/runner/engines/{void-loop,claude,codex}.ts + src/runner/tools/fs.ts read_file / list_files / grep, realpath under /scan, no symlinks + src/runner/mcp/void-scan.ts stdio MCP server, 4 tools (Engine C) + src/self-test.ts probe checks 2–3 inside the container + skill/ vendored skill + LICENSE, Void Workers companion, deploy-diff profile, report-schema.json + config/codex/{config.toml,requirements.toml,model_catalog.json}, config/claude/managed-settings.json + image/{Dockerfile.claude,Dockerfile.codex,package.json,pnpm-lock.yaml,codex-wrapper.sh,NOTICE} + test/fake-model/server.ts scripted Anthropic SSE, Responses SSE, chat completions + test/unit/*.test.ts + vite.config.ts / package.json (vp pack → dist/runner.mjs) +platform/packages/api/src/security/ + schema.ts drizzle tables, re-exported from src/schema.ts + policy.ts lenient + strict readers, CAS write, preview builders + models.ts "which model runs" resolver, notice checks + enqueue.ts enqueueSecurityScanInTx, coalesce, after-commit copy + poke, input hold check + scheduler.ts SecurityScanScheduler DO + control.ts SecurityScanControl WorkerEntrypoint (input / model / heartbeat / result) + input/{tier,t2,t1,filters,third-party,redact,phrase-check,memory,backlog,tar}.ts + model-proxy.ts allowlist, caps, headers, SSE metering, failure reasons + budget.ts ceilings, reserve, per-call check, month math, alerts + ingest.ts, findings.ts validate (zod), fingerprint, state machine, reopen, F-numbers + public-gate.ts request store, judge, re-check, bypass, cancel, backstop + notifications.ts, recipients.ts + page-token.ts 15-min signed page link + maintenance.ts hourly jobs (re-poke, reaper, backlog skip, sweeps, probe, exposure) + probe.ts checks 1–6 + errors.ts typed errors → status + code +platform/packages/api/src/ + provisioning/security-scanner.ts provision / verify / delete controller Worker + container app + security-scanner-controller-runtime.ts controller Worker source (DO, outbound entrypoints) + security-scanner-controller-source.ts reads the alias + scripts/build-security-scanner-controller.mjs (under platform/packages/api/scripts/) + routes/project-security.ts, routes/security-page.ts + operator/security-routes.ts + admin/routes/security.tsx + admin/react/views/{SecurityPage,SecurityFindingsPage,SecurityScansPage,SecurityPublicRequestsPage,ProjectSecuritySection,AdminBanner}.tsx +packages/void/src/cli/ + project-security.ts, deploy-security-notice.ts, platform-security-audits.ts (runtime guard) +platform/scripts/ + security-spike-*.ts + fixtures/security-seeded-apps/ (Phase 0, below) +``` + +Edited (main touch points; file:line refs are in the four maps kept with the PRD): + +- Capability: `packages/platform/src/{manifest,discovery,worker-config,installer}.ts`, + `packages/platform/scripts/build-runtime.mjs`, `platform/packages/api/src/capabilities.ts`, + `platform/packages/proxy/src/capabilities.ts`, `platform/packages/api/wrangler.jsonc`, + `platform/packages/api/src/{env,index}.ts`, `src/worker/index.ts`. +- Deploy: `deploy/{recovery,execute,compensate,publish-worker,publish-static}.ts`, + `deployment-execution.ts`, `assets.ts`, `provisioning/cleanup.ts`, `routes/projects.ts` (rollback). +- Zero Trust: `zero-trust/{project,operation,installation,maintenance}.ts`, + `routes/project-zero-trust.ts`, `operator/zero-trust-routes.ts`, `admin/routes/{zero-trust,projects}.tsx`. +- Shared: `email.ts`, `operator/{index,audit}.ts`, `admin/react/views/{Layout,ProjectDetailPage,ProjectZeroTrustSection,ZeroTrustPage}.tsx`, + `admin/react/{pages,server}.ts`, `admin/fate/{page-server,page-data,render,views}.ts` (+ regenerated `client.generated.ts`), + `api.ts` (typed routes for the dashboard), `test/integration/helpers.ts`, `vite.config.ts`, root `.dockerignore`, + `.github/workflows/platform-ci.yml`, `pnpm-workspace.yaml` (nothing: `platform/packages/*` is already a glob). +- CLI: `project-{args,cmd,zero-trust}.ts`, `list.ts`, `client.ts`, `platform-errors.ts`, `help.ts`, `cli-main.ts`, + `deploy-managed-{full,static,framework}.ts`, `operator-{args,cmd}.ts`, `platform-{args,lifecycle,setup,management,plan,teardown}.ts`. + +## Milestones + +One PR, one commit per milestone, in this order. Each commit passes +`vp check` and the exact test files it adds. "Exit" is the check that ends it. + +``` +P1 M1 cap+DO ─► M2 shared types ─► M3 schema ─► M4 policy ─► M6 controller+probe ─► M7 model proxy+budget + │ └────────────► M5 runner (no deps) ─┘ │ + ├─► M8 outbox+hold ─► M9 scheduler+cron ─► M10 input ─► M11 T1 + │ └─► M12 ingest ─► M13 engines A/C + └─► M14 project API ─► M15 email ─► M16 public gate ─► M17 operator + M18 admin ─► M19 page ─► M20–M23 CLI ─► M24 docs +P2 M25 rescan/backfill/sweeps · M26 fallback+streaks+digest · M27 plan caps · M28 GitHub check + M29 page forms + dashboard · M30 runtime copy · M31 secret findings, client assets, SARIF, webhooks +P3 M32 local check · M33 BYOK · M34 per-project policy · M35 severity edits · M36 final docs + full suite +``` + +### Phase 1 (MVP) + +**M1 Capability, scheduler DO class, config.** + +- Scope: optional `securityAudits` in all parsers (missing = false, non-boolean = error); + `HOSTED_CAPABILITIES.securityAudits = false`; manifest writes `schemaVersion: 7` when true + (v7 allows `storageLocationHint`/`runtimeLogs` absent) so an old CLI refuses instead of + dropping it; `PlatformRuntimeManifest.securityAudits: 1`. `SecurityScanScheduler` stub + (answers `/poke`, alarm no-op) exported from `src/worker/index.ts` and `src/index.ts`. + `worker-config.ts`: DO binding + `{tag:'security-audits-v1', new_sqlite_classes:['SecurityScanScheduler']}` + always; `ai:{binding:'AI'}` on the API Worker only when the capability is on. Hosted + `wrangler.jsonc`: binding ×3 blocks, tag after v6 (sqlite). `env.ts`: `SECURITY_SCAN_SCHEDULER`, `AI?`. +- Tests (unit): `platform/packages/api/test/unit/capabilities.test.ts`, + `packages/platform/test/unit/{worker-config,auth-discovery,auth-manifest}.test.ts` + (old documents parse, v7 round-trip, v6 parser refuses v7), + `platform/packages/api/test/unit/{platform-worker-config,hosted-config}.test.ts`, + `platform/packages/api/test/unit/security-scheduler-stub.test.ts`. +- Exit: capability off → config diff is exactly the DO binding + tag; worker keys still + `[api, dispatch, emailGateway, proxy, tail]`. +- As built: the DO binding + tag follow the runtime manifest (`securityAudits: 1`, + input `securityScanScheduler`), not the capability, so a new CLI can still deploy an + older runtime that has no such class. `PLATFORM_CAPABILITIES` leaves out + `securityAudits` while it is off (`serializePlatformCapabilities`), so the vars are + unchanged. The proxy never reads this capability, so `proxy/src/capabilities.ts` is + unchanged. + `assertPlatformRollbackCompatibility` refuses a rollback to a runtime without + `securityAudits: 1` when the installed runtime has it or the capability is on, and says + to roll forward (R2). `readPlatformCapability` in `@void/platform` is the one place that + reads a missing optional capability as `false` (manifest, discovery, API). Deployment + schema version 7 and the capability must go together; later versions may carry it too. + Extra tests: `packages/void/test/unit/{platform-rollback,platform-installer}.test.ts`. + +**M2 Shared model list and policy types.** + +- Scope: `security-models.ts` (6 models, engine, host, badges, $/M, reserve = + 1.2M×in + 120k×out, notice version, provider names); `security-policy.ts` (type, + defaults, strict parser, ranges, error code strings shared by API and CLI). Sonnet + price: see Risks R6. New package exports in `packages/platform/package.json`. +- Tests (unit): `packages/platform/test/unit/security-models.test.ts` (every model has a + price; reserves match spec §16.1 table; ids use catalog spelling), + `packages/platform/test/unit/security-policy.test.ts`. +- Exit: API and CLI import one list. +- As built: Sonnet has `price: null`. "Every model has a price" holds for the five + priced models; the policy parser refuses an unpriced default, and the M4/M14 pickers + treat `isSecurityModelPriced() === false` as blocked (R6). Costs are kept in whole + nano-dollars per token so metered sums do not drift. The spec gives ranges only for + concurrency (1–10) and timeout (5–60); ours for the rest: `maxInputTokens` + 50k–2M, `maxOutputTokens` 5k–200k, `modelCallsPerScan` 10–200, caps $0–$1,000,000 in + whole cents. The strict parser needs every known field, checks cross-field rules + (default not blocked, priced, third-party default needs the notice, gate needs mode + `public`/`all`) and ignores unknown fields; probe check names in + `entitlement.missing` stay open text so a later probe still reads. The strict + `parseSecurityPolicy` guards writes; the stored row is read with `readSecurityPolicy`, + which survives an upgrade or rollback: unknown blocked ids are dropped, an unknown, + unpriced or blocked default becomes the first non-blocked priced `@cf` model (spec + edge case 23), limits are clamped into range. Otherwise one model change would make + the whole policy unreadable (Off, or 503 with the public gate on). Runtime + conditions (fresh probe, Zero Trust state) stay with the API writes (M4, M16). The + provider notice text lives next to `SECURITY_PROVIDER_NOTICE_VERSION`. Exports + also go in the `vp pack` entry list (`packages/platform/vite.config.ts`). + +**M3 Schema and migration 0065.** + +- Scope: all Phase 1 tables in `src/security/schema.ts` (spec §14). Project FKs cascade; + no FK to deployments; `actor_user_id` no FK. Partial uniques: running scan per project, + open request per project. F-numbers from `project_security_settings.next_finding_number` + under the project lock. `security_notifications` gets `attempts`, `next_attempt_at`. + Phase 2/3 columns that are cheap to add now are added now (one migration, see M25+): + `security_scans.deployment_id` nullable + `trigger` incl. `local`/`sweep`/`backfill`/`fallback`, + `security_findings.verdict_source static|runtime`, `severity_override`, + `project_security_settings.policy_override`. Generate with `vp run --filter @voidcloud/api db:generate`. +- Data: `drizzle/0065_security_audits.sql`, `meta/0065_snapshot.json`, journal entry. + `compatibility.json` edge added only after the old-runtime check (schema-ci guide). +- Tests: `platform/packages/api/test/unit/security-migration.test.ts` (PGlite; add to + `pgliteUnitTests` in `vite.config.ts`); `test/integration/api-delete.test.ts` gains a + case: project with scans, findings, requests, spend deletes cleanly; `clearTables` + adds `security_platform_spend`, `security_notifications`. +- Exit: template DB rebuilds; project delete cascade test passes. +- As built: 11 tables, re-exported from `src/schema.ts`. Money is in whole units, not + `numeric` USD, to match M2: spend, reserves and costs in nano-dollars (`*_nano_usd`, + `bigint`), caps in cents (`*_cents`, `integer`, 0–100,000,000). `month` is a `date` + with a first-of-month check (`EXTRACT(DAY …) = 1`, which does not depend on the session + time zone). Status, trigger, state and kind lists are `CHECK`s built from exported TS + lists in the same file; the migration test checks that the mode list, the engine list + and the max cap match M2's `SECURITY_MODES`, `SecurityEngine` and + `SECURITY_MAX_MONTHLY_USD`. A bypass row's `request_state` is limited to + `waiting_scan`, `held_no_result` and `needs_deploy` (D50). The urgent index uses + `COALESCE(severity_override, severity)` so M35 needs no new index. Extra, not in + spec §14: `next_finding_number`, `policy_override` (default `inherit`), `created_at` + on scans, a waiting-scan index and an input-hold index (M8/M9), `severity_edited` in + the event actions (M35), `project_id` FK on finding events, PK + `(project_id, fingerprint_key)` on `security_memory_rejected`. The bypass → request + FK is `NO ACTION`: retention cannot delete a request a bypass points to, while a + project delete still removes both. `security_notifications.project_id` cascades and + is `NULL` only for `cap_platform`. `compatibility.json` is unchanged (old-runtime + check first). + +**M4 Policy store and operator policy routes.** + +- Scope: `security/policy.ts` lenient reader (bad data → `disabled` + `console.error`), + strict reader (`SecurityPolicyUnreadableError` → 503), CAS by `revision`. Operator + `GET/POST /operator/v1/security/policy` (mode, default model, blocked models, notice, + limits) with dryRun preview text (spec §5.4); `GET /security/status`. Mode change to + Off also cancels queued scans (after M9) and turns the gate off (after M16). Audit + targets for every path (ids + new state only). +- Tests: unit `security-policy-store.test.ts`; integration `operator-security-policy.test.ts` + (CAS 409, preview counts, 501 when capability off, entitlement missing 409), + `operator-audit.test.ts` (new targets). +- Exit: policy round-trips; nothing turns on without a fresh probe. +- As built: `security/policy.ts` + `security/errors.ts` (`SecurityApiError`, mapped to + `OperatorError` by `operator/security-routes.ts`). The routes are + `/operator/v1/security/{policy,status}`. Every policy writer takes the advisory lock + `void:platform:security-policy`, then checks `expectedRevision` (409 + `revision_conflict`, like plans) and writes `revision + 1`. A preview takes the + revision optionally and returns the one to send. Extra fields such as `missing[]` sit in + `details`, the way every operator error does. Bad stored data reads as Off and keeps its + revision, so an operator write can replace it (the preview says so). Body: + `mode`, `defaultModel`, `blockedModels` (full list, admin panel) or `block`/`unblock` + (CLI), `acceptProviderNoticeVersion` (must equal the current notice version), `limits` + (patch). Unknown fields get a 400. A third-party default needs its host to pass probe check 5 + and the current notice; blocking the default and unpriced models get 422 `security model + not allowed`. `publicGate: true` gets a 400 until M16. Off cancels `pending_input` and + `queued` scans in the same transaction (`status_reason 'policy_off'`); the tables exist + since M3, so this did not wait for M9. All → Public does not cancel queued protected + scans: the scheduler (M9 scope) checks protection when it claims a scan. The "re-run the probe in + set mode" step (spec §5.2) comes with the probe (M6 scope); until then a stored pass less than + 24 h old is required. GET policy and status work with the capability off; only POST + answers 501. Status failure rate = `failed|refused|timed_out|incomplete` out of those plus + `succeeded`, finished in the last 24 h. + +**M5 Scanner runner package (Engine B first).** + +- Scope: new `platform/packages/security-scanner`. `task.json` → phases (1 hunt, ≤10 + verify, 1 repair turn) → `/scan/out/findings.json` + `status.json`. Engine B loop + (chat-completions messages, 4 tools, 40 turns). Safe tar extract (regular files only, + reject symlink, `..`, absolute). Hand-written validator (≤5 MiB, ≤1000 records, no + regex). Status mapping per engine. Base URL `http://model.void.internal`. Engine + interface so A/C plug in at M13. Real SDKs are **not** workspace deps (see Test strategy). +- Tests (unit, `platform/packages/security-scanner/test/unit/`): `void-loop.test.ts` + (fake model server), `fs-tools.test.ts` (temp dirs: symlink, `..`, big file), + `extract.test.ts`, `validate-findings.test.ts`, `status.test.ts`, `phases.test.ts`. +- Exit: `dist/runner.mjs` built by `vp pack`; Engine B passes on the fake model. +- As built: the runner has no runtime dependency (63 kB, Node built-ins only). The + controller (M6) starts `node runner.mjs --stdin-tar [--root /scan]` and streams the + input tar on stdin (S1: short argv). The tar may hold only `task.json`, `input/**` + and `memory/**`; any symlink, link, device, `..`, absolute path or duplicate refuses + the whole input (`failed`, `error_class: input_invalid`). Of pax records only + `path` and `size` are decoded; others (binary `SCHILY.xattr.*`) are skipped. Paths + with a control character are refused in the tar, `changed_files` and the report, + and the hunt prompt lists changed files as JSON strings. Files are written with + `O_EXCL|O_NOFOLLOW`, mode 0444. `findings.json` is written first, then + `status.json` is renamed into place whole, so the controller polls one file. Exit + 0 means `status.json` exists; SIGTERM writes `timed_out (wall_clock)`, also while + the tar is still coming in (stdin is closed then, and after the tar). Model calls + go to `POST http://model.void.internal/v1/chat/completions` with no credentials; + M7 must answer a stop with a non-2xx status and `x-void-scan-stop: + session_calls|scan_calls|tokens|budget|credits` (a bare 402 = credits); any other + failure (other non-2xx, network error, unreadable body) is retried once, then + `failed (infrastructure)`. The last allowed turn tells the model to submit now. Tools read only + `/scan/input` and `/scan/memory`; relative paths mean `/scan/input`; `grep` is + plain text (no regex). The verify phase keeps the hunt fingerprint, an empty + verify answer rejects the candidate, and candidates past `max_verify` stay leads + (confirmed needs the second session). The one repair turn is shared by a bad + report and a plain-text answer. `status.ts` also maps Engine A/C signals (§8.4) + so M13 only feeds them; S2/S3 confirm the wording. Deviations: the upstream + skill at `c1c8a8c` is not in the repo, so the prompts are Void's own + (`prompts.ts`: trust rule, verdicts, severity scale, Workers checks) and the + report schema is ours (`report.ts`); vendoring the skill and its + `report-schema.json` contract test move to M13 with `skill/`. `task.json` is + defined here (M10 builds it): `version`, `scan_id`, `attempt`, `engine`, `model`, + `tier`, `changed_files`, optional `limits`. Extra test file: none; `task.json` + cases live in `phases.test.ts`, the CLI tar path in `void-loop.test.ts`. + +**M6 Controller Worker, provisioning, probe.** + +- Scope: `security-scanner-controller-runtime.ts` (DO per scan id; register model + intercept then `DenyAll`; `start({enableInternet:false})`; stream input tar into the + container; exec runner as `scanner`; poll result files; alarm at wall clock and hard + cap; destroy after result). Build script + alias `void:security-scanner-controller-source` + in `wrangler.jsonc`, `scripts/build-worker.mjs`, `packages/platform/scripts/build-runtime.mjs`, + `vite.config.ts` mock. Runner bundle embedded for the managed image (Engine B, image + option C). `provisioning/security-scanner.ts` (copy of `sandbox-controller.ts`: upload + with `If-None-Match:*`, ownership marker, service binding to `SecurityScanControl` + with props, `containers[]`, workers.dev off, container app create/find/verify, delete + app then Worker). Name derived per installation. `SecurityScanControl` entrypoint + with `heartbeat` (fenced). `security/probe.ts` checks 1–6 + operator `POST /security/probe`. + Re-run the probe inside the policy change that leaves `disabled` (spec §5.2); this + replaces the 24 h stored-pass check in `assertEntitlement` (`security/policy.ts`). + Daily probe hook comes in M9. +- Tests: unit `security-scanner-controller-runtime.test.ts` (mocked `ctx.container` + with `interceptOutbound*`: order, `enableInternet:false`, env has no token, alarm kill, + stale attempt refused, two scans never share an instance id — edge #42), + `security-scan-control.test.ts`; integration `api-security-provisioning.test.ts` + (`mockCfApi` containers state: create, reuse, ownership mismatch, delete order), + `operator-security-probe.test.ts` (each failing check copy; Off → on runs the probe + and a failing check refuses the change). +- Exit: probe reports all six checks against fakes. +- As built: the plan did not say how the API calls the controller. A service binding + from the API Worker cannot point at a Worker that does not exist yet (the deploy + fails), and the controller is created only at turn-on. So `provisionSecurityScanner` + also uploads a gate script into the platform dispatch namespace + (`void-security-scanner-gate-`, one service binding `SCANNER` → the + controller, no logic, no secret). The API calls `env.DISPATCH.get(gate).fetch(…)`: + `POST /v1/scans/start | /v1/scans/cancel | /v1/self-test`. The controller keeps + workers.dev off; nothing is on a public hostname and the installer config is + unchanged. Names are `void-security-scanner[-gate]-<12 hex of sha256(installation + id)>` (Worker and container app share one name). Unlike Sandbox controllers, this one + is shared and is re-uploaded (no `If-None-Match`, no repeated migration) when a + platform release ships a new bundle (`__VOID_SECURITY_SCANNER_SOURCE` digest). + The control binding's props are `{protocol: 1, installation}`; `SecurityScanControl` + refuses any other caller and everything while the capability is off. + `heartbeat` is the fence (current attempt, `running`, lease not past, project not + `deleting` → `ok`, else `stale` or `canceled`); `input`, `model` and `result` are + present but refuse until M10, M7 and M12. One Durable Object per attempt + (`scan::`) or probe (`probe:`), so an instance is never reused, + and a start is accepted once. The start runs in the alarm: fence check first (a + stale attempt never starts a container), then the S1 egress lock (model host + intercept → all HTTP deny → all HTTPS deny), `start({image: + 'cloudflare/debian-trixie', enableInternet: false, env: {}})`, a root setup step + (`useradd scanner`, `/scan` 0700, runner from stdin to + `/opt/void-scanner/runner.mjs` 0555), then the runner as `user: 'scanner'` with + the input tar piped to stdin. Alarms every 10 s: fence, read + `/scan/out/status.json` (then `findings.json`, at most 5 MiB + 1 byte) as + `scanner` with a 30 s limit (a short `node -e` reader: `/scan/out` must be a real + directory, the file is opened `O_NOFOLLOW|O_NONBLOCK` and must be a regular file; a + refused `status.json` reports `failed (bad_output)` with no findings), hand both to + `result`, destroy. Every exec gets `env: {PATH, HOME=/scan}` and nothing else. At the wall clock: `kill -TERM`, 60 s + grace, then `timed_out (wall_clock)`; at the hard cap: `timed_out (hard_cap)`. The + container stays until `result` accepts, so nothing large is kept in DO storage. + Engines A/C answer `engine_unavailable` until M13. The runner gained + `--self-test` (`src/runner/self-test.ts`, not `src/self-test.ts`, so it ships in the + one bundle): uid, model route answers with the probe id from the outbound props, the + four egress targets fail or end in `DenyAll`, no credential-like env name; no file + system walk (S1). The runner bundle is built by + `build-security-scanner-controller.mjs` with Vite (SSR, Node built-ins external) and + embedded through `void:security-scanner-runner-source`; `build-runtime.mjs` and + `build-worker.mjs` build it. Probe: checks run in parallel (2+3 share one + self-test); a skipped required check counts as missing (`container` failing gives + `missing: ['container', 'egress']`). Check 4 calls `env.AI.run` with + `skipCache` and `cf-aig-collect-log-payload: false`; "no cached entry after" is not + read back (no gateway log read yet, S10). Check 5 calls REST `/ai/v1/messages` and + `/ai/v1/responses` (with `access_programs`) on the first priced model of each host; + 401/403 names the token permission instead of credits. Probe calls carry + `cf-aig-metadata {"securityScan":"probe"}`. `POST /operator/v1/security/probe` has no + 501 guard: with the capability off it returns check 1's copy and makes no other call + and stores nothing. A stored row that cannot be read is not overwritten by a probe. + Turning the policy on (`changeSecurityPolicy` with `probe`) runs the probe outside + the transaction when the revision still matches, stores a failing result and + answers 409, or writes the passing result with the mode in one write; a preview + does not check the stored probe and says the probe runs on apply. Without `probe` + (direct callers) the stored < 24 h check stays. `deleteSecurityScanner` (gate → + container app → Worker) exists for uninstall; wiring it into `void platform + uninstall` is left to the CLI milestone. + Review fixes: turn-on first runs the full proposal (`probeOnApply`) so a change + refused anyway (public gate, blocked or unpriced default, no provider notice) never + provisions or calls a model; a third-party default is checked against the fresh + probe, not the stored hosts. A failed turn-on probe answers 409 with `probeId` and + each refusing check (`name`, `message`, `link`) in `details`. A gate with no marker + or another installation's marker is refused. Timing: probe ready wait 90 s + setup + 30 s + self-test 90 s < the API's 240 s wait. Check 2 keeps the Workers Paid / + permissions copy for plan and token errors and shows the provisioning error's own + copy for `ownership`, `outdated`, `missing` and `gate`. + +**M7 Model proxy and budget.** + +- Scope: `SecurityScanControl.model()` → `security/model-proxy.ts`: scan id + attempt + + lease; `model == scan.model_used`; allowlist minus blocked, host passed check 5, notice; + per-session (40) and per-scan (80) call counts; token caps; pre-call worst case and + post-call spend in one `UPDATE … RETURNING` on both spend rows; fixed headers + (`cf-aig-gateway-id`, `cf-aig-metadata {"securityScan":tag}`, collect-log true, + payload false, skip-cache true); `access_programs` for `openai/*`; SSE pass-through + with usage read; failure reason store so the runner can ask why (Engine C). `@cf` rate + token asked from the scheduler DO. `deriveSecurityScanTag` (own HMAC label). + `security/budget.ts`: ceilings (spec §16.2), reserve, month math (UTC, cross-midnight), + 80/100% thresholds (alerts queued in M15). +- Tests (unit): `security-model-proxy.test.ts` (mock `fetch` + `AI`: headers, strips + caller `cf-aig-*`, 402 → credits, cap stop → `incomplete (budget)`, wrong model 422), + `security-budget.test.ts` (ceiling table, edges #49–#52); integration + `security-spend.test.ts` (two reserves near the cap: one wins — edge #51, real SQL). +- Exit: metered spend equals tokens × list price in tests. +- As built: `SecurityScanControl.model()` calls `handleSecurityModelRequest` + (`security/model-proxy.ts`). One route per host: `POST /v1/chat/completions` + (`@cf`, `env.AI.run`), `/v1/messages` (`anthropic/*`), `/v1/responses` (`openai/*`) + (REST `/ai/v1/*`); a route that does not match the model's host is a 422. Policy Off + refuses every call (409). Check 5 uses the stored `entitlement.hosts` (no 24 h + freshness: the daily probe in M9 keeps it current). A third-party call needs the + project's own notice at the current version. REST headers are built from nothing + (only `anthropic-version`/`anthropic-beta` pass on Messages), so no caller credential + or `cf-aig-*` header passes. The binding answer is turned into chat-completions shape + when it is the legacy `{response, tool_calls}` form (Engine B reads `choices`). + Money: a call's worst case (request bytes as input tokens, since a token is at least + one byte, plus its output limit) is held on `spent_nano_usd` of both month rows in + the `UPDATE … WHERE spent + worst ≤ cap RETURNING` that checks the cap, after the + scan row `UPDATE` that checks attempt, `running`, lease, call cap and token caps. One + transaction, always scan → project → platform row (also for reserve, settle, + release, so no lock cycle). After the answer the hold is replaced by tokens × list + price; a failed upstream call costs 0; a paid answer with no usage, a dropped stream + or a failed settle keeps the worst case (the meter errs high). The proxy clamps the + output limit to what the scan has left (`max_tokens` / `max_output_tokens`; 16,384 + when the caller sets none) so the worst case is bounded. Stops answer 429 (402 for + credits) with `x-void-scan-stop`; other failures carry no header (runner retries once). + `budget.ts` also has `reserveSecurityScanBudget` (scan start, for M9: sets + `started_at`, refuses a scan that already holds a reserve) and + `releaseSecurityScanReserve` (month of `started_at`, edge #52), the §16.2 ceiling + rules, the edge #49 refusal copy, 80/100 % thresholds (alerts stay M15) and the + `Dec 1` reset label. Deviation: per-session counts (40), the `@cf` token bucket + (10/min/model) and the last refused call live in the `SecurityScanScheduler` DO + storage (`security/call-ledger.ts`, RPC `admitModelCall`, `recordModelCallFailure`, + `modelCallFailure`, `forgetModelCalls`): Postgres has no column for them and M3 is + done. The session comes from an optional `x-void-scan-session: 0–63` header (Engine C + config in M13; Engine B sends none and counts its own turns); the per-scan cap in + Postgres stays the hard bound. M9 adds 429 back-off to the bucket and calls + `forgetModelCalls` when an attempt ends. `GET /v1/void/last-failure` answers the last + refused or failed call of the attempt (Engine C). Waiting for a rate token (≤ 120 s) + does not use a model call. `deriveSecurityScanTag` sits in `proxy-token.ts` + (`.<22-char MAC>`, HKDF label `void-security-scan`). Extra test cases: the + call ledger in `security-budget.test.ts`; the proxy on real SQL in + `security-spend.test.ts`. + Review fixes: the proxy refuses (422 `tool_not_allowed`, failure `not_allowed`) + any tool the provider runs (Messages: any typed tool except `custom`; Responses: + anything but `function`/`custom`, also inside a `namespace` or an `additional_tools` + input item) and `mcp_servers`, `container`, `background`; the container's tool + lockdown is untrusted (spec T2). `anthropic-beta` keeps only an allowlist + (`SECURITY_ALLOWED_ANTHROPIC_BETAS`, no `context-1m-*`); S2 recorded header names, + not values, so M13 confirms the list and the Codex namespace type. When the output + left is below the route minimum (16 on Responses) or a `budget_tokens` thinking + budget cannot drop to ≥ 1,024 under it, the call answers the `tokens` stop before + the hold; otherwise the budget is lowered to `max_tokens − 1`. A 2xx answer that is + not JSON keeps the worst case (502 to the runner). Cache writes are priced 1.25× + (5 min) / 2× (1 h) input and a Messages hold counts input at 2×; cache reads stay + at 1× (over). On the binding only a 402 is a credits stop. + +**M8 Outbox enqueue and input hold.** + +- Scope: `enqueueSecurityScanInTx(tx, …)` called in `commitCutoverLive` after + `setActiveDeployment` (pass `env`), in `promoteProtectedDeployment` (`trigger=recovery`), + and in the compensate `post_routing_recovery` branch in its own short tx (best effort, + logged; see Risks R8). Rules: policy lenient read; public state fresh (strict ZT read, + any error = public); `preview-*`, owner suspended, deleting → no row; protected under + `public` → `skipped:protected`; open request → `trigger=gate`; coalesce (old queued → + `superseded`, keep `first_queued_at`). After commit: copy inline modules + (`publish-worker.ts`, ≤50 MB / 30 s), then move the row with a compare-and-set + (`UPDATE … SET status = 'queued' WHERE id = :id AND status = 'pending_input'`), so a + scan canceled meanwhile (policy Off, `policy_off`) stays canceled; poke only when the + row moved. Hold in + `deleteDeploymentInputs` and `sweepStaleDeploymentInputs` (check `security_scans.input_prefix`). + `deleteProjectAssets` adds `security-scans/{project}/`. +- Tests: integration `security-enqueue.test.ts` (row in same tx; rollback of the tx + leaves none; skip table spec §6.1; coalesce keeps `first_queued_at` — edges #2, #37; + recovery row — #41; unchanged static redeploy no row; policy Off between commit and + the input copy leaves the row `canceled`), `deployment-execution.test.ts` + (hold + release), `unread-deploy-cleanup.test.ts` unchanged pass. +- Exit: no live deploy path (except R8) can go live without a row while policy is on. +- As built: `security/enqueue.ts`. `enqueueSecurityScanInTx(tx, env, …)` runs in a + savepoint, so a failed statement is logged and the deploy commits with no row (D45). + Capability off → no row and no read. It takes the policy advisory lock in shared mode + (lock order: project row, then policy), so an Off write waits for the deploy commit + and cancels the new row instead of missing it. Owner suspended = any + `users.suspended_reason`. Protection is spec §4 read in the transaction (the + installation check is `installationZeroTrustProtects`, now exported from + `policy.ts`). One row per live deployment: a second call (compensation after a + committed cutover, R8) gets the same row back while it is still `pending_input` + (or `skipped:protected` with no module copy yet). + An open public request sets `trigger=gate` and `public_request_id` only; the + request state (`needs_deploy` → `waiting_scan`, `gate_scan_id`) is M16. Coalescing + supersedes `pending_input` and `queued` rows (not only `queued`), so an earlier + deploy's after-commit step cannot queue a replaced row; a `skipped:protected` row + supersedes them too (the old deployment is no longer live and the project is out of + scope), without taking a `first_queued_at`. The hold is `input_prefix` = the + deployment operation's prefix (operation id = deployment id) while `inputs_deleted` + is false. Copy: when the row + holds no staged input (inline `workerFiles`, no Queue) the modules go to + `security-scans/{project}/{deployment}/modules/{i}`, then `modules.json` last (a + copy without it is incomplete), and `input_r2_key` is that prefix. A + `skipped:protected` row holds nothing, so its modules are copied too (staged or + inline) for the exposure catch-up (spec §7.2). Over 50 MB, not done in 30 s, or a + read error → `failed`, `status_reason`/`error_class` `input_missing`, `failure_cause + project`. A copy whose compare-and-set misses (row canceled or superseded + meanwhile) is deleted unless a row points at it; a timed-out copy is deleted again + once its last `put` settles. `finishSecurityScanEnqueue` runs after `done` in both + publish paths (so the copy never delays the result), right after the admission + commit for `trigger=recovery`, and in compensation whenever a failed deploy is + still live: an unclear cutover that did commit, or a step after the cutover commit + that threw. There the pipeline hands over its `workerFiles`, and the short + transaction gets the row the cutover wrote back (still `pending_input`) or, when + live was written outside any transaction, writes one (R8). A `trigger=recovery` + row of an inline deploy is queued with no input (the modules left with the request + that died): M10 has to read it from the stored Worker bundle (`bundle_stored`), else + it ends `input_missing`. A row left in `pending_input` by a lost after-commit step is + for the M9 re-poke. + `dispatchPendingDeployments` leaves held operations out of its page so they cannot + starve the others. Unchanged static redeploy: the API has no such path (the CLI + skips unchanged assets, but a deploy still makes a deployment); the test covers an + idempotent replay, which makes no new deployment and no row. + +**M9 Scheduler and hourly jobs.** + +- Scope: real `SecurityScanScheduler`: claim queued rows round-robin by owner, oldest + first; installation concurrency (policy) and 1 per project; `@cf` token bucket in DO + storage (10/min/model, back off on 429); reserve at start (`skipped:budget`); set + `attempt`, `lease_until`; call the controller; retry once on infra error; re-arm while + work remains. At claim, a non-gate queued scan of a project that is now protected + under `public` becomes `skipped:protected` (spec §5.4 All → Public). Cancel API for + teardown and operator cancel. `security/maintenance.ts` + in the hourly branch only (after `index.ts:768`, gated by capability and policy): + re-poke, reaper (`timed_out`), 24 h → `skipped:backlog`, raw output sweep (cursor in + ROUTING, capped deletes), scan row and closed request retention, daily probe + (`entitlement.checkedAt` > 24 h, mode ≠ disabled). `teardownProject` cancels scans. +- Tests: unit `security-scheduler.test.ts` (round-robin, bucket, re-arm, back-off); + integration `security-scheduler-claim.test.ts` (running unique index, lease fencing — + edge #33; under `public` a queued non-gate scan of a now-protected project becomes + `skipped:protected` at claim, a gate scan still runs), `scheduled.test.ts` (hourly jobs run only when on; fast tier untouched), + `api-delete.test.ts` (mid-scan delete cancels — #26). +- Exit: fake controller drives queued → running → result. +- As built: the queue's Postgres side is a new `security/queue.ts` (read, claim, end, + requeue, cancel, reaper, backlog skip, re-poke); `scheduler.ts` keeps the DO and + `runSecurityScanQueue(deps)`, which tests drive with a fake store and controller. + The "which model runs" resolver (`security/models.ts`, from the layout) landed here + because the claim stores `model_requested`, `model_used` and `engine`: project model, + else the default; unknown/blocked/unpriced → default (#23); third-party without a + passing check 5 host, the current installation notice or the project's own notice → + first non-blocked priced `@cf` model (#44, #84); none → `failed (infrastructure, + no_model)`. A pass, per candidate in round-robin order (owners never served first, + then least recently served, kept in DO storage, ≤ 1,000 owners): claim under the + project lock + shared policy lock (attempt + 1, lease = 2× wall clock + 5 min); the + claim re-checks what may have changed while the row waited: project `deleting` / + owner suspended → `canceled` (`project_deleted` / `owner_suspended`), 24 h → + `skipped:backlog`, `public` + protected + not `gate` → `skipped:protected`; a unique + index hit is `busy` (row stays queued). Then reserve (refusal → `skipped`, reason + `budget`, `error_class` `project_cap|platform_cap`), then `POST /v1/scans/start` + through the gate. A failed start (throw, non-2xx, `ok:false`) cancels that attempt at + the controller, forgets its ledger, gives the reserve back and requeues it with a + 60 s back-off; the second failure is `failed (infrastructure, start_failed)`. A + container that started and then failed is M12's to retry (`requeueSecurityScan`, + `endSecurityScanAttempt` are there). At most `floor(10 / 10) = 1` running scan per + `@cf` model. A Workers AI 429 now reaches the scheduler (`rateLimited` proxy dep → + RPC `backOffModelRate`): the bucket goes 5 tokens (30 s) into debt per 429, at most + one minute; calls wait for the refill and no new scan starts on that model until it + is paid. Re-arm 30 s while queued rows remain, sooner for a retry or back-off end, no + alarm when empty; ingest (M12) should poke on completion. With the capability off + the alarm does nothing. Cancel: `cancelSecurityScans` writes the rows first (that is + the fence), then controller cancel + ledger forget, best effort; `teardownProject` + calls it right after `lockAndMarkDeleting` (direct, not through the DO: the rows + are the fence, and the running scan's reserve must go back to the platform month + before the cascade); DO RPC `cancelScans(scanIds, reason)` is for M17. Hourly + (`maintenance.ts`, after the "Hourly tier" line): the capability gates everything; + policy Off skips re-poke, backlog and probe, but the reaper, the raw output sweep and + retention still run (Off does not end running scans, and stored data still ages). + Reaper: `timed_out` / `lease_expired` / `installation`, reserve back, controller + cancel, ledger forget. Re-poke: `pending_input` older than 10 min → `queued`, then a + poke if anything is queued. Raw output: `securityRawOutputPrefix` = + `security-scans/{project}/scans/{scan}/` (M12 writes there), cursor `(finished_at, + id)` in ROUTING `security-audits:raw-output-sweep`, 50 scans a run. Scan rows: deleted + outside the newest 200 or past 180 days, never active, a current base (latest + `succeeded`), an open request's gate scan, or a row the raw sweep has not passed; + 500 a run. Closed requests: newest 50 per project, never one a bypass names. Daily + probe: `probeAndRecord` when the mode is on and the stored result is missing or + ≥ 24 h old. The exit test ends with the reaper (`timed_out`), since `result()` + refuses until M12. The M1 stub test now checks that the alarm does nothing with the + capability off. Extra tests: the 429 back-off case in `security-model-proxy.test.ts`. + Review fixes: the reserve is fenced on `running` + `attempt` (a cancel after the + claim gives `gone`: no start, no end), and a start that worked re-reads the row and + cancels at the controller if it moved; every end, requeue and cancel releases the + reserve in the same transaction, and an hourly step releases any ended row that still + holds one. The first failed start ends the pass and the alarm waits for the retry + back-off (an outage costs one scan its retry, not the queue); an error on one + candidate ends only it (`failed (infrastructure, scheduler_error)` once claimed). + Cancel locks its rows in one `SELECT … FOR UPDATE` over every active status, so a + claim in flight is waited for and still canceled. A pass keeps an earlier alarm (a + poke). Teardown lets a failed cancel throw (retried before the cascade). The binding + often throws only `3040: …` with no status: the proxy reads that leading code (3036 + and 3040 → 429). The month's `scans` count only goes up on the first attempt. The + hourly security step stays first in the hourly tier, as planned; a due daily probe + can add about 3 minutes before the jobs after it. + +**M10 Input builder (T2, T3, filters, memory).** + +- Scope: base selection at scan start; T2 from changed Worker modules by sha256 + + source-map `sourcesContent`, changed text assets by hash; T3 full; claimed-commit + check (sha256 of `sourcesContent` vs file at commit when T1 is possible); filters and + secret-like file drop; third-party by lockfile registry identity (else keep, rank last, + `third-party-unverified`); caps 400 files / 2 MB / 256 KB; priority by import graph; + `backlog.json`; redaction (8+ mixed chars, 4 forms); phrase check (plain substring, + no regex) → server lead; memory index (64 KB, 200 records, role only) + history files; + copy staged inputs to `security-scans/…` at start and release the hold; + `SecurityScanControl.input()` streams a tar. +- Tests (unit, pure): `security-input-tier.test.ts`, `security-input-t2.test.ts` + (fixture bundles with source maps for React/Vue/Svelte/Solid), `security-filters.test.ts`, + `security-third-party.test.ts`, `security-redact.test.ts` (4 forms, short values kept — + #30), `security-phrase-check.test.ts`, `security-memory.test.ts` (order, caps, no model + rejections — #40), `security-backlog.test.ts` (#13, #36); integration + `security-input-capture.test.ts` (R2 copy, hold release, input_missing — #12). +- Exit: a fixture deploy produces the expected tar and coverage label. +- As built: `security/input/{tier,t2,filters,third-party,redact,phrase-check,memory,backlog,tar,build,prepare}.ts`. + The pure parts take data already read; `build.ts` puts them together and + `prepare.ts` does the I/O. `SecurityScanControl.input()` checks the fence, then + `prepareSecurityScanInput` builds and checks every entry before it answers (the + controller now waits 120 s for it, `INPUT_TIMEOUT_MS`), so a failure gives `null`, never + half a tar; the tar is then encoded entry by entry as the controller reads it. + Tar: own ustar writer, regular files only, pax `path` for long or non-ASCII names, same + name rules as the runner's reader. Head modules, first match: the scan snapshot + (`input_r2_key`), the staged deploy input (`input_prefix`), the stored Worker bundle + (`bundle_stored`, new `loadStoredWorkerModules` in `durable-objects.ts`, for M8's + recovered inline deploys); staged and stored modules are copied to + `security-scans/{project}/{deployment}/` and the hold is released with a fenced write + (`input_r2_key = prefix, input_prefix = NULL`). Modules are read one at a time (hashed, + copied, decoded, a map cut to its `sourcesContent`), so the API isolate never holds the + bundle's bytes. None, an incomplete snapshot, a missing object or > 50 MB counted as + read (not as recorded) → `failed (input_missing)`, project cause, reserve back, poke (#12). + Deviation: the claim moves the row to `running`, which used to drop the hold before the + copy, so `SECURITY_SCAN_INPUT_HOLD_STATUSES` now includes `running` (a running row holds + its prefix until the copy clears it); coalescing uses the new + `SECURITY_SCAN_WAITING_STATUSES`. The `idx_security_scans_input_hold` partial index + still names only the two waiting states (no migration change); the hold check is a + small lookup either way. The snapshot gains `sha256` in `modules.json` (an inline copy + from M8 has none: the first scan fills it in), `sources.json` (path → sha256 of the + unredacted text) and `assets.json` (path → hash), so it can be the next scan's base + without the deployment row. Base = last `succeeded` scan; tier: rescan → full (#43), no + base → `first-scan`, snapshot gone → `no-usable-base`, else T2 (T1 is M11). T2: a source + changed when its module or that module's map changed and its text hash differs from the + base index (no index: every source of a changed module); modules with no map are read as + built code under `input/_worker/` (`no-source-maps`); changed text assets (≤ 256 KB) + under `input/_assets/`, read from R2 then KV. Priority: breadth-first over relative + imports from `workerMain` (plain text scan), then assets, then `third-party-unverified`. + Source paths: scheme and query cut, resolved against the map folder and `sourceRoot`, + `..` above the root dropped, duplicates with other text get `~2`. Focus: backlog first, + 400 files / 2 MB, a file over 256 KB counts as 256 KB (T2 has no hunks); T3 sends no + focus list; its backlog is only what it could not read. The backlog a scan leaves is written to + `security-scans/{project}/scans/{scan}/backlog.json`, not the project's `backlog.json`: + M12 must promote it only on `succeeded`, so a failed scan loses no file. Server leads + (phrase check) go to `…/scans/{scan}/server-leads.json` for M12 to store. Empty diff: + note `no-changes` and `no_changes: true` in `task.json` (the runner ignores the field + today); M12 must take the "no changes" path (no model call, #14). A gate scan with no + diff re-checks the files of `fixed` findings resolved since the base; with none it runs + in full (`gate-recheck`, #85). Filters: `id_*` matches only key files (no extension or + `.pub`) so `id_utils.ts` stays; binary = NUL or U+FFFD in the first 8 KiB. Third-party: + `package-lock.json` and `pnpm-lock.yaml` readers (completeness review: now in + `@void/platform/security-lockfile`, and `pnpm-lock.yaml` also reads `packages`, so + transitive packages are placed). T1 reads the repo lockfile nearest the project folder + from the same tarball pass; a CLI deploy sends `securityPackages` (`{registry, local}` + for the packages its source maps name, read from the nearest lockfile up to the repo + root), kept as `packages.json` next to the head snapshot for retries. With neither (old + CLI, yarn or bun lockfile, recovered inline deploy) `node_modules/…` sources stay as + unverified. Read set: 32 MB, and the runner's 16 MB a file (after redaction) and 20,000 + entries with memory (`security-scanner/src/runner/limits.ts`, shared by both sides); + assets: 400 files / 16 MB. A changed or backlogged file left out (`input-capped`), and + an asset not read (`assets-unread`, over the limits or gone from storage), goes to the + backlog and stays out of `sources.json` / `assets.json`, so no later scan counts it as + seen. A path over 960 characters becomes `_long//`; a path the runner still + refuses is dropped (`dropped-bad-path`, partial), not the whole tar. Inline source maps + are found at any length. `partial` = backlog left, a cut or bad-path file, or > 5 % of + source bytes lost to registry drops or the cap; secret-like files are dropped and + counted in `dropped_files` but do not make a scan partial; a partial from registry + drops alone adds `partial-third-party-only` (#92). Redaction covers every file in the + tar, memory included; a secret that cannot be decrypted fails the build (the + controller reports `input_unavailable`). Phrase check: whole-word, case-insensitive, + `LLM` upper case only (lower `llm` is common in identifiers); a full scan checks the + project's own files. Memory: no `security_memory_rejected` read; history files capped + at 8 MB and 2,000 files (oldest resolved first). The row gets tier, coverage, notes, counts and + `base_scan_id`/`base_deployment_id` (fenced on `running` + attempt). + `securityCoverageLabel` (tier.ts) builds the label from the row for M14+. + +**M11 T1 source diff (hosted, `managedBuilds`).** + +- Scope: `compareCommits` in `github/installation-token.ts` (files, patch, truncation); + head tarball to R2; project root + source-map-listed shared files; OIDC `sha` match. +- Tests: unit `security-input-t1.test.ts` (truncated → T2, force push → T2/T3 — #9, + monorepo — #32, mismatch → `commit-mismatch` — #38); integration + `security-t1-github.test.ts` with mocked GitHub. +- Exit: self-hosted never takes T1. +- As built: `security/input/{t1,t1-github,source-tar}.ts`; `prepare.ts` tries T1 when the + tier would be T2 (a base snapshot exists, not a rescan), after assets are read, and + passes the files to `build.ts` as `sourceDiff` (or a fallback note as `notes`). + `compareCommits(token, repo, base, head)` asks for one page of one commit (the file list + is on page 1 only); ≥ 300 files or no list = truncated. Start: `managedBuilds`, a + `github_connections` row, hex base and head commits; the bundle is parsed only past this + point and handed to `build.ts`, so T2 parses it once. Before the token, the connection must + pass `installationCoversRepo` (active installation, repo still selected, owner/admin + authorizer), as a managed build does; else `source-diff-unavailable`. The head's build comes from + `deployment_operations.build_id` (or `builds.deployment_id`): `container` = managed (no + content check), `github_actions` = its `commit_sha` (the OIDC `sha` claim) must equal + the claimed commit; a build whose commit differs → `commit-mismatch`. One scoped token + (this repository, `contents: read`) for the compare and the tarball. Compare: only + `ahead` / `identical` (`behind` / `diverged` = force push → `base-not-ancestor`; a 404 or + error → `source-diff-unavailable`; truncated → `compare-truncated`), each T2 with that + note. The tarball goes to R2 by multipart (100 MB compressed, 512 MB / 100,000 files + unpacked, else `source-too-large`) at `…/scans/{scan}/source-{attempt}-{uuid}.tar.gz` (one key per call, so + overlapping runs never delete each other's) in parts of exactly 8 MiB (R2 wants equal + non-last parts) and is deleted as + soon as the input is built (a retry fetches it again), so the whole repository is never + kept. Pass 1 hashes every file, pass 2 reads the planned ones. Own streaming ustar/pax + reader: regular files only, top folder cut, unsafe names and links skipped (but every + entry counts toward the limits). + Root: a source-map path is the map's path with `..` above the output folder dropped, so + it ends a repo path; each source whose text is at exactly one such path votes for the + folder in front. The folders must form one line (deepest = project root, the rest hold + shared packages), else `monorepo-shared-code`; no vote → `commit-mismatch`. A managed + build's root is `''` (it ran at the repo root). Content check (not managed): no source + maps, or a mapped source whose text differs from the commit while it changed (in the + compare or in the built output) → `commit-mismatch`. A file that differs but did not + change is read from the bundle (its live text). Scope: the root (no `node_modules/`) plus + repo files the maps list; secret-like files noted, filters as M10. Changed = compare + files in scope ∪ T2's changed sources. Deviation (safer than the spec): the T2 changes + are part of T1, so code that went live is scanned even when the base's claimed commit + did not match what it shipped. Bundle sources with no repo file (packages, generated + code) stay in the input under their own path. Input paths match T2 (a mapped file keeps + its source-map path, others are relative to the root), so findings keep their file when + a project moves between T1 and T2. Order: changed first; server code (bundle order), + config, other code, tests and docs. Changed repo files may use the whole read budget, + unchanged ones what bundle-only sources leave; the rest is unread. An unread file that changed + (or waits in the backlog) is cut: capped, lost, back to the backlog. An unchanged one is + read access only (§7.4): dropped, not capped, so a big repo is not `partial` on every + scan (a gate scan that turns full caps it, as in T2). Deviation: no hunks for files over 256 KB: the runner takes only + `changed_files` and reads whole files, so a big file counts as 256 KB in the focus, as in + T2. `MemoryR2Bucket` gained `createMultipartUpload`. New note names beyond the spec: + `compare-truncated`, `base-not-ancestor`, `source-diff-unavailable`, `source-too-large`. + +**M12 Ingest and findings.** + +- Scope: `SecurityScanControl.result()` → zod check → one tx: fingerprint key + (project + skill fingerprint + sink path), dedupe, F-number, 50+50 cap + (`findings_capped`), promote, `not_seen` hint, reopen rules and stale-scan rule, + `fix_checked_scan_id`, `rejected` store (never fed), events only on change, base + moves only on `succeeded`, `no changes` path for empty Worker diff, raw output to R2, + `ledger_summary`. Late or reaped attempt rejected. Then (after commit) gate re-check + (M16) and notification rows (M15). +- Tests: unit `security-findings-rules.test.ts` (reopen table, "new" rules spec §9.4, + possible duplicate), `security-ingest-schema.test.ts`; integration + `security-ingest.test.ts` (one tx; concurrent same key — #20; stale scan — #35; + incomplete keeps confirmed only; refused stores none; #3, #4, #14, #18, #19). +- Exit: full fake path deploy → findings rows with the fake controller. +- As built: `security/ingest.ts` (status and report parsing, the outcome table, the one + transaction), `security/findings.ts` (pure rules) and `security/fence.ts` (the fence, + moved out of `control.ts`, which re-exports it). `result()` answers `ok: true` once the + result is taken (stored, or requeued), `false` when fenced off or when the store threw + (the controller keeps polling until the hard cap; the reaper ends a scan nobody + stored). Deviation: no Zod in the API Worker; `findings.json` goes through the runner's + own hand-written validator (`validate-findings.ts`, one copy of the rules on both + sides) and must carry `schema_version: 1`. `status.json` is read by a small parser: + unknown status, a reason that does not go with it, or another scan id / attempt → + `failed (bad_output)` (`status_unreadable` / `status_mismatch`). Outcome: `succeeded` + stores all; a report with `run_status: incomplete` makes the scan `incomplete + (run_incomplete)`; `incomplete` stores validated confirmed only; the rest store none. + Cause: `infrastructure`/`credits` installation, every other failure project. The + first `failed (infrastructure)` attempt is requeued (`requeueSecurityScan`), the second + ends. The transaction locks the project row (serializes ingests and F-numbers), then + the scan row, re-checks the fence (attempt, `running`, lease, project not `deleting`), + writes findings, events, scan status and gives the reserve back. After commit: the + scan's `backlog.json` becomes the project's (only on `succeeded`, and only when the + scan file exists), `status.json` + `findings.json` go to `…/scans/{scan}/`, the call + ledger forgets the attempt, poke. Key = sha256(source, project, skill fingerprint, sink + path or file): the source (`scanner` / `server`) comes first, so a model fingerprint + such as `server:reviewer_text` never takes over a server lead's row (§10.3). The + per-scan cap counts new keys only (a key the project has adds no row, so a capped scan + still re-sees, reopens and promotes all it reported); of those it keeps the most + severe confirmed and puts server leads first in the 50 leads; note `findings-capped`. + Finding rows are locked in id order (`SELECT … ORDER BY id FOR UPDATE`); bulk resolve + (later milestone) must take them in the same order. Severity only rises and a confirmed finding + is never demoted (a scan cannot downgrade, §10.3). `revision` moves only on + `reopened`, `promoted`, `severity_changed` (a re-see never makes a resolve in flight + answer 409). Stale-scan rule: unknown admission time = stale; `rescan` uses + `started_at`. A sink hash unknown on either side is not a change. One `seen_again` / + `seen_again_stale` per resolve. `possible_duplicate_of` = id of the newest resolved + finding with the same file + category. Server leads and `rejected` records are stored + on `succeeded` only (otherwise the base does not move and the next scan finds them + again). `prepare.ts` now also writes `…/scans/{scan}/scope.json` (diff focus, or every + input file of a full scan, plus each input file's hash: a source's unredacted hash, + else the hash of the text sent), used for `sink_content_hash` and the not-seen hint: + set on `succeeded` scans for open findings not reported whose file the scan looked at + (diff: focus; full: the files in its input, so a file the filters dropped, a backlog + file or a file gone from the deployment never gets it), one `not_seen` event. + `fix_checked_scan_id` is set by a `succeeded`, uncapped scan with no backlog, model + calls on the row (proxy count, not the container's) and a model run, of a deployment + admitted after the `fixed` resolve (compared in SQL). `ledger_summary` (succeeded + only) is server-built from paths + `finding|scanned|backlog`, ≤ 6 KB of JSON; a diff + scan (and a scan with no model run) merges the base scan's ledger (this scan wins a + path; base `backlog` entries drop, this scan's backlog is the whole one), a full scan + replaces it. Deviation: the server-side path (#14) is in `prepareSecurityScanInput`: + a diff scan with an empty focus is stored as `succeeded` with no model call and + `input()` answers `null`, so the runner never starts. `status_reason` is `no_changes` + (and the `no-changes` note) only when nothing was cut; when changed files were all cut + to the backlog the scan is a plain partial `succeeded`; the controller's `input_unavailable` report + that follows is fenced off. Not yet: ingest returns `news` / `reopened` / `capped` for + M15 (notification rows) and M16 (gate re-check); neither is written here. + +**M13 Engines A and C, images, drift test.** (Code lands; turning models on depends on S2/S3.) + +- Scope: `engines/claude.ts` (locked options spec §15.3, `ANTHROPIC_BASE_URL`, placeholder + key, managed settings), `engines/codex.ts` (SDK with `codexPathOverride` → `codex-wrapper.sh` + adding `--ephemeral --ignore-user-config --ignore-rules --strict-config --skip-git-repo-check`, + empty `/work`, own `CODEX_HOME`, config/requirements/model catalog), `mcp/void-scan.ts`. + Two images (`Dockerfile.claude`, `Dockerfile.codex`), exact pins in `image/package.json` + with its own lockfile, `--ignore-scripts`, linux-x64 only, non-root, `LICENSE`/`NOTICE`. + Image distribution per R1. CI job `build-security-scanner-images` next to + `build-api-container` in `platform-ci.yml`; root `.dockerignore` allowlist. +- Tests: unit `claude-engine.test.ts`, `codex-engine.test.ts` (option shapes, env has no + key, wrapper args), `void-scan-mcp.test.ts`, `image-pins.test.ts` (Dockerfile ↔ + `image/package.json` ↔ wrapper versions match; like `build-container-package.test.ts`); + opt-in `recorded-run.e2e.test.ts` (`VOID_SCANNER_E2E=1`, Docker, `--network none`, + fake model: tools list only Read/Glob/Grep(/Skill) or the 4 MCP tools; planted + `AGENTS.md`, `.codex/`, `CLAUDE.md`, `.mcp.json` never load; `codex --version` matches). +- Exit: drift test green; models whose engine spike failed stay out of the list (blocked by default). +- As built: `engines/{claude,codex,proxy-failure}.ts`, `mcp/{server,void-scan}.ts`, + `coerce.ts`, `image/{Dockerfile.claude,Dockerfile.codex,claude/,codex/,codex-wrapper.sh,NOTICE}`, + CI job `build-security-scanner-images`, one `Dockerfile..dockerignore` allowlist each + (the root `.dockerignore` is pinned to the API build container by its own test). The SDKs are loaded + by a variable specifier when the first session starts, so the runner bundle stays + dependency-free and a managed (Engine B) image that gets an A/C task ends `failed + (engine_unavailable)`. `vp pack` now writes `runner.mjs` and `void-scan-mcp.mjs`. + Each image has its own exact-pin `package.json` and an npm `package-lock.json` (plan + said one pnpm lockfile; two images need two sets, and the base image has npm), installed + with `npm ci --ignore-scripts`; everything under `/opt/void-scanner` (the controller's + `RUNNER_PATH` folder). The wrapper also refuses a `codex` that is not the pinned version. + Engine A: `systemPrompt` is Void's own prompt (skill vendoring is still R5) plus a note + that the tools are Read/Glob/Grep and the end is the structured output (size keywords + stripped from the schema, `validate-findings` still enforces them); no plugin, no + `Skill` tool; cwd `/scan/input` plus `/scan/memory`; the PreToolUse hook checks realpath. + Both engines send `x-void-scan-session` (the proxy's per-session call cap), set the CLI + retry caps from spikes S2/S3 (Codex 0 and 0; Claude Code 2, since a 401 retried for + 120 s), and after a session with no report ask the proxy `GET /v1/void/last-failure`; + a failure that is new since the session started decides credits or a cap stop. + `classifyClaudeResult` reads `is_error` + `API Error: 402` as credits (S2). + The proxy (M7) now takes the gateway name (`claude-sonnet-5.5`, `gpt-6.1-terra`) as the + scan's model and sends that name on, the form S2/S3 verified, and never passes an + upstream 401 on to an engine. Engine B (and the other engines) read a report sent as JSON + text, repair harmless slips (`coerce.ts`) and retry once with "your last output was + invalid: …". Not built here: the controller dispatch for A/C, the image copy into the + operator registry, the publish script and the `recorded-run.e2e` Docker test (all in + M13b below), and the upstream skill (R5). Live quality numbers for A/C are blocked on + credits (S2/S3). + Checked locally on an arm64 colima build of both images: they build, `import()` of the SDK + works, the wrapper refuses other subcommands and a missing version match, the catalog + holds only `gpt-6.1-terra`/`gpt-6.1-sol` with `shell_type: disabled`, and the Codex SDK + accepts our whole config under `--strict-config` (`http_headers` and the MCP server + included) and reaches the model URL. Codex still prints "Reconnecting…" on a dropped + connection after the retry caps are 0 (those caps cover HTTP statuses such as 402), so + the wall clock ends such a session. `vp pack` runs two builds: one shared chunk would + break the single-file `runner.mjs` the controller embeds. The Codex image keeps only the + `codex` binary (the platform package also carries `bwrap`, `codex-code-mode-host` and + LGPL voice libraries) and the Apache-2.0 `LICENSE` from the SDK package. + +**M13b Engine A/C images in the operator account, controller dispatch, recorded run.** + +- Scope: what M13 left out so A/C can run a real scan: copy the digest-pinned images into + the operator registry (S1b option A), one container app per engine, controller dispatch + by engine, a probe check for the images, uninstall, a release script (no push here), + and the Docker recorded run with the fake model. +- As built: + + ``` + release: publish-security-scanner-images.ts --push (manual workflow) + └─► ghcr.io/voidzero-dev/void-security-scanner-engine-{a,c}@sha256 (public) + └─► api/src/security/scanner-images.json { digest | null } + probe (per host, right after its credits call passes, unless all its models are + blocked; calls + copy end 45 s after the probe start): + registry credentials (push, pull; 15 min) ─► HEAD dest manifest ─► skip if there + └─► ghcr manifest (sha256 = pin, not an index) ─► config (linux/amd64) + ─► layers missing in the account, deadline checked before each (resumable) + ─► PUT manifest by tag sha256- ─► /containers/image-preparations + provision: one Worker, classes ScannerController (B, managed image) + + ScannerControllerEngineA / ScannerControllerEngineC + one container app per deployed engine: void-security-scanner-engine-{a,c}- + deployed = images it already runs at the current pin + images ready now + scheduler start ─► SCANNER / SCANNER_ENGINE_A / SCANNER_ENGINE_C by task engine + ``` + + - Files: `security/scanner-images.{json,ts}` (pins; parse refuses a bad pin), + `provisioning/security-scanner-images.ts` (copy, prepare, delete + `/v2/gc/layers`), + `provisioning/security-scanner.ts` (engine classes, bindings, apps, images text + `__VOID_SECURITY_SCANNER_IMAGES`, `assertSecurityScannerContainers`), + `security-scanner-controller-runtime.ts` (dispatch, engine subclasses), + `security/probe.ts`, CLI `platform-security-audits.ts` (uninstall), + `platform/scripts/publish-security-scanner-images.ts`, + `.github/workflows/platform-security-scanner-images.yml` (manual, main or a tag only, + no cache, `packages: write`; images carry `org.opencontainers.image.revision`, which + the script checks equals HEAD, and `--push` refuses a dirty tree), + `security-scanner/test/e2e/{recorded-run.e2e.test.ts,fake-sdk-model.mjs}`, and a new step + in `build-security-scanner-images` that runs the recorded run with `VOID_SCANNER_E2E=1`. + - Deviations from the plan, with reasons: + - The image check is a new row `image` per third-party host in check 5, after the + credits row. A host can be picked only when credits, the image copy and that engine's + self-test all pass. Checks 1–4 (the probe's pass) do not depend on it, so a missing + image never blocks the `@cf` engine. No credits for a host, or every model of it + blocked: no copy and no self-test for it (row `skipped`). + - What is deployed never depends on one probe's results. The controller keeps every + engine image it already runs whose ref matches the current release pin, and adds the + ones made ready now; an image leaves only when its pin changes, or on uninstall. A + failed credits call, registry call or `pending` prepare therefore never re-uploads + the controller (an upload is a code deploy that restarts every scan). A deployed image + of a callable, unblocked host is judged by its self-test even when this run's copy + step failed. Two probes at once converge without a lock: each re-reads after its + upload and uploads again (at most 3 times) until the controller runs at least its + own images; only different code ends `outdated`. + - The pins live in the API package (it does the copy), not in the scanner package. + Both digests are `null` until the first release push; `null` reads as "this + release has no image" (`unpublished`) and keeps those models unpickable. + - The copy runs in the API Worker on each probe and goes on from the layers already + copied, since a full image is too large for one request. The model calls and the copy + end 45 s after the probe start; every registry request gets what is left (a layer + still in flight is cut off and copied again next time), so with provisioning and the + self-test (≤ 240 s) a probe stays under the CLI's 5-minute timeout. A layer must fit + one window. Once copied, a probe does credentials, one HEAD and the prepare call. + - A cancel without an engine goes to all three classes at once (`allSettled`); one + class that fails answers 500 but never keeps the cancel from the others. + - The engine images keep their baked `runner.mjs`; the controller does not stream it. + As root it checks the `scanner` user and the runner file (exit 2 → + `controller_error`), then makes `/scan` owned by `scanner`, mode 0700. The + Dockerfiles now create `/scan` the same way: a root-owned `/scan` broke extraction. + The egress lock and `EXEC_ENV` are the same as Engine B. + - Each engine needs its own Durable Object class (one namespace binds one container + app). A controller provisioned before M13b gets migration `v1 → v2` adding both + classes; a new one gets all three in `v1`. Cancel without an engine goes to all three + namespaces (the scheduler does not send the engine on cancel). + - Names use `engine-a` / `engine-c`, never a vendor name (branding rule). + - Uninstall also deletes the engine apps (namespace checked like the B app) and the + copied images, then runs layer cleanup. A manifest the registry cannot read (not 200 + or 404) or a failed cleanup fails the uninstall instead of reporting it done; the API + version also deletes the images when the controller is already gone, so a retry after + a failed image delete finishes the job. + - The recorded run builds for the host arch (arm64 locally, amd64 in CI). It is opt-in + everywhere: only `VOID_SCANNER_E2E=1` with Docker present (the CI image job sets it), + so the normal test suite never builds the images. Claude Code offers + `DeferredToolPlaceholder` next to Read/Glob/Grep/StructuredOutput (S2), so the test + allows it. The fake model also answers `/v1/void/last-failure`. + - Admin and project copy for a host that cannot be picked now says "not ready (probe + check 5: credits or scanner image)" instead of blaming credits only. + - Not run here: the ghcr push (release step), a live A/C scan on Cloudflare (needs the + push and credits, S2/S3), and the upstream skill (R5). + - **Needs the user's OK (R1):** this builds option A (copy into the operator registry) + with Void publishing public images at `ghcr.io/voidzero-dev/void-security-scanner-engine-{a,c}`. + Both pins stay `null` (A/C models off) until the user agrees and a release pushes. + +**M14 Project API routes.** + +- Scope: `routes/project-security.ts` mounted with `/projects/*` auth: `GET /security` + (spec §13.5 shape, role filtering, `detail:'counts'` for CI tokens and OIDC), findings + list/show (scoped `WHERE project_id`, cursor paging), comment (`configure`), + resolve/reopen (`settings`, `expectedRevision`, capability re-checked in tx — #21, + #22), scans (`deploy`), model (notice version, 422s), budget (422 above ceiling), + page-link. Capability off: write and scan routes 501, read/comment/resolve open. + Add to `api.ts` typed routes. +- Tests: integration `api-project-security.test.ts` (role matrix PRD §3, 404 vs 403, + cross-project id 404, readers get no titles or dollars, CI detail). +- Exit: role matrix test covers every row of PRD §3. +- As built: `routes/project-security.ts` (mounted after the zero-trust routes; in `api.ts`), + with `security/project-view.ts` (status, policy reason, model and budget views, scan list, + cursor and role filter), `project-findings.ts` (list, show, comment, resolve, reopen) and + `project-settings.ts` (model, budget). Routes: status, findings list and show, comments, + resolve, reopen, scans, `PUT model`, `PUT budget`, `POST page-link`. There is no project + route that starts a scan: a manual rescan is operator only (spec §3), so "scans (`deploy`)" + is the history list. Role filter: `full` = user session with `deploy`; `counts` = readers and + any deploy token (`deployScope` set: CI, remote build, OIDC). `GET /projects/:id/security` is + on the deploy-token allowlist (`middleware/auth.ts`); nothing else under `/security` is. + Counts level shows F-id, severity, verdict and state of open findings; a resolved finding also + shows its title (spec §3). `budget` is `null` unless `full`. Severity everywhere is + `COALESCE(severity_override, severity)`. Finding lists page by `number` ascending (cursor = + the last number); the scan list pages by `(created_at, id)` descending (opaque cursor). + `limit` 1–100 (default 25), a bad limit, cursor, `state` or `severity` is a 400. A finding is + addressed by `F-12`, `12` or its id, always scoped to the project. Resolve and reopen lock the + project row (as ingest does), re-check `settings` with the same lock held (#22), lock the + finding, then compare `expectedRevision` (#21); a resolved finding cannot be resolved again and + an open one cannot be reopened (both 409 `finding changed`, with `state`, `resolution`, + `revision`, `changedAt`, `byRole`). Resolve stores `resolved_sink_hash` and + `resolved_severity`, clears `fix_checked_scan_id` and bumps the revision; reopen clears the + resolved columns, bumps `reopen_count` and the revision. Comments need `configure`, 1–4,000 + characters, change no revision, and are events only. The route takes one finding per call: + bulk resolve is the CLI looping (M20). Capability off: `PUT model` and `PUT budget` answer + 501 (after the access check, so a private project still 404s / 403s first); status, findings, + comments, resolve, reopen, scans and page-link stay open. Model: a pick must be a listed, + unblocked, priced model (422 `security model not allowed`); a third-party pick also needs the + host's probe check 5 (same 422, as the policy picker does) and the notice + (`acceptProviderNoticeVersion` = current, or accepted before; else 422 `provider notice not + accepted` with the notice lines). `model:null` is always allowed; with a third-party + default, `acceptProviderNoticeVersion` accepts it for the project. A wrong notice version is + refused. Without the installation notice a third-party pick is stored but the next scan + still falls back to `@cf` (`model.source: 'fallback'`). `model` in the status is + `{id, requested, source: project|default|fallback, thirdParty, noticeAccepted, pendingDefault}` + (`pendingDefault` is the model id or `null`). Budget: `monthlyUsd` whole cents, 0 to + 1,000,000 or `null`; above the ceiling is 422 with `ceilingUsd` and the operator command; a + `cap_changed` project event is written only when the cap moves. `budget` in the status is + `{capUsd, capSource: own|limit|none, ceilingUsd, spentUsd, month, resetsAt}`. Policy reason + copy follows §11.4; a protected project in `public` mode with no open request reads + `applies:false`. **Deviations:** (1) `publicRequest` is `null` and the status gains no + request text until M16 (the table exists; the shape belongs to the gate). (2) `security/page-token.ts` + (mint and verify, own HMAC label, 15 minutes, user + project, key `JWT_SECRET`) was added + here because `page-link` needs it; M19 only adds the page route that calls + `verifySecurityPageToken`. The link points at the request origin + (`/security/projects/:slug?t=…`) and is a dead link until M19. (3) A human reopen + does not enqueue the "reopened" email and resolve/reopen do not re-check a public request: + both hook in at M15 and M16. (4) `packages/platform/dist` was stale (old model order); run + `vp run --filter ./packages/platform build` before the tests. (5) `GET /security/scans` answers 501 + while the capability is off (spec §13.5); status, findings, comment and resolve stay open. + A comment re-checks no role inside a transaction (it never changes state); the model PUT takes + no lock (scan time re-checks the model). + +**M15 Notifications.** + +- Scope: senders in `email.ts` (findings, reopen, project and platform cap, public held / + now public / canceled, bypass) with escaping and 120/300 char cuts; footer reason; + `recipients.ts` worked out at send time (owner, project admins, deploy authors with + `deploy`, requester while `settings`, installation admins); outbox in the scheduler + alarm: dedupe key, 30-min findings cooldown per project, merged scan authors, attempts + ×3 with backoff, skip quietly when `EMAIL` unbound. +- Tests: unit `email.test.ts` (new templates; never a bypass line in the held-urgent + email), `security-notifications.test.ts`; integration `security-recipients.test.ts` + (#25, #27, #46–#48, #69, #70). +- Exit: one email per scan; bypass email to every installation admin. +- As built: copy is pure in `security/notification-copy.ts`; the senders are in `email.ts` + (`sendSecurity*Email`, subject prefix is `[]`, so `[Void Cloud]` on + the hosted platform, not a fixed `[Void]`); `security/recipients.ts` works out who gets + what at send time (suspended or email-less users skipped, one email per person and per + address, reason order requester, owner/admin, author); `security/notifications.ts` has + `enqueueSecurityNotification` (dedupe key per spec §12), the cap helpers and + `runSecurityNotifications`, which the scheduler alarm runs after each queue pass and + re-arms for the next due row. Rows are queued in the same transaction as the change: findings + at ingest (`news` non-empty), human reopen of an urgent finding (`reopenSecurityFinding`, + route pokes the scheduler), 80/100% after a model call settles (`notifyCaps` dep in the proxy) + and 100% when a scan is `skipped:budget` (`onBudgetRefused` dep of the queue pass: a hold + keeps `spent + hold ≤ cap`, so spend alone may never reach 100%). Public and bypass kinds + have senders, builders and `enqueueSecurityNotification` inputs; **M16 calls them**. + Deviations: (1) the table has no column for the new-finding ids, so the findings email + rebuilds them at send time from the scan's `created` / `promoted` / `reopened` / + `severity_changed` events (open, confirmed, not informational; reopened and raised ones only + while urgent). A raise to critical counts as new there even when the finding was already high (ingest's own `news` is stricter). **Decision:** keep it. The event stores no old severity, so the email cannot tell high→critical from medium→critical, and a schema change is not worth it for a rare second email that reports a worse finding. A test pins it (`security-recipients`). + (2) Cap, reopen and public rows keep their parameters in the dedupe key (no schema change); + a held row whose request left that state, a cap-80 row whose cap was raised, a finding + resolved since, and rows older than 7 days are dropped unsent. (3) Retries: 1 min, then 5 + min, third failure is `failed`; a recipient that failed while another got the email is + logged and not retried (no double send). (4) `EMAIL` unbound marks every pending row + `skipped` (a later "on" does not replay old news). (5) The hourly maintenance pokes the + scheduler while any row is pending, also with the policy Off. (6) Unit + `security-notifications.test.ts` covers keys, retry constants and the copy helpers; the + database cases (recipients #25 #27 #46–#48 #69 #70, cooldown, merge, retry, email off, bypass + to every installation admin) are in integration `security-recipients.test.ts`. (7) Tests that expected the old default model and scan limits (commits 9727781b8 and + 8d3a1a067) now name the new default, or pin glm where they price a glm reserve. (8) A crash + between the send and the row update leaves the row pending, so the email goes out twice + on the retry. Accepted: an email twice beats an email never, and no test covers it. (9) + Test clocks: a row is due from the database clock at its insert, so tests that pass a + time start it a few seconds ahead. + +**M16 Scan before public (gate).** + +- Scope: `publicGate` turn-on/off in the policy POST (conditions + copy spec §5.5; + holds `lockZeroTrustConfiguration(shared)` and re-reads ZT); strict `publicGate` + read inside `claimConfiguration` → 409 `security public gate on` / 503 for disable + and public-only; `security/public-gate.ts` (`requestPublic`, `judge`, `recheck`, + `bypass`, `cancelOpen`, `cancelAll`); `checkpointProjectReconciliation` hook with the + new `publicRequestId` option; `setProjectZeroTrustProtection` returns + `{row, publicRequest, held}` and `protect` with an open request only cancels (no + reconcile). Re-check triggers: request, ingest, resolve/reopen, after + `commitCutoverLive` commit (moves `target_deployment_id`), rollback tx in + `routes/projects.ts` (moves target, re-check after commit), bypass, hourly backstop + after `reconcilePendingProjectZeroTrust` (own query on open requests, flips only when + the full reconcile fits the routing budget; on roll-forward cancels requests whose ZT + row changed after creation). Exposure catch-up in `maintenance.ts`. Gate errors as a + new error type (not `ZeroTrustUnavailableError`). Project routes: GET adds + `publicRequest`/`publicGate`; PUT answers 202 with the old-CLI-safe `state:'reconciling'` + - held line; new `POST …/public-request/bypass`. Operator `zero-trust/projects/:id` + and admin form go through the same path with `requested_via` and actor. +- Tests (integration, nearest suites copied): `security-public-gate.test.ts` (states + and transitions; #54–#62, #65–#68, #79–#85, #88, #91–#92), `security-gate-bypass.test.ts` + (#72, #89, #93, #94: bypass races under the lock), `security-gate-zero-trust.test.ts` + (disable / public-only refused, turn-on race — #64, #90; strict reader 503), + extend `zero-trust-surface.test.ts`, `zero-trust-deploy-admission.test.ts` (deploys + keep working while held — D45), `zero-trust-disable-bypass.test.ts`; unit + `security-gate-judge.test.ts` (pure judge function over scan + findings + deployment). +- Exit: invariant tests: no flip without pass or bypass; no bypass with urgent open; + no deploy ever refused because of a request. +- As built: pure judge in `security/public-gate-judge.ts` and copy in `public-gate-copy.ts`; + tx-level code in `public-gate.ts`; drivers (re-check, bypass, hourly backstop) in + `public-gate-flow.ts`, split so `zero-trust/project.ts` has no import cycle. The checkpoint + takes `gate: ask | flip | bypass` and `requester`; `reconcileProjectZeroTrustGated` returns + `{row, publicRequest, held, skipped}`. Lock order is project row, ZT shared, policy shared; + the policy writer takes ZT shared first when turning the gate on. `security/exposure.ts` + holds the exposure catch-up, run by `maintenance.ts` under `public` mode. + Deviations: tests are fewer than listed. Built: `security-gate-judge.test.ts` (unit), + `security-public-gate.test.ts` (ask, hold, pass, bypass, protect-cancel, ZT disable + refused), `security-exposure.test.ts`; existing suites updated for the new + `setProjectZeroTrustProtection` result and GET fields. Not built yet: + `security-gate-bypass.test.ts`, `security-gate-zero-trust.test.ts` (race cases #64, #72, + #89, #90, #93, #94, strict reader 503), and the `zero-trust-deploy-admission` and + `zero-trust-disable-bypass` extensions. Review round: the hourly backstop judges every + picked request (holds need no budget), rotates by touching `updated_at`, and shares the + cron run's routing budget with `reconcilePendingProjectZeroTrust` (passed from `scheduled`); + a pass with too little budget commits its checkpoint and the project stays reconciling, + as the checkpoint already does. Any `trigger=exposure` scan of the live deployment stops + further catch-up scans. `held_reason` for a failed gate scan is `failed_installation` or + `failed_project`; copy varies on it. Added afterwards (commit 3fddc9dba): the race tests (#64, #72, #89, #90, #93, #94) in + `security-gate-bypass.test.ts` and `security-gate-zero-trust.test.ts`, the strict-reader + 503, the deploy and rollback admission cases and the operator 202 and dry-run shapes. + Completeness review: `security-gate-resolve.test.ts` runs Q13 end to end (real resolve, + ingest and flip). A rollback to a deployment with no past scan queues a gate scan when its + code is kept, else `needs_deploy` (recorded deviation from §12.4, which says + `needs_deploy`: the scan can only hold or pass on a clean result, so nothing goes public + sooner). A succeeded scan with a backlog and no kept input is `needs_deploy` (`no_input`), + not a `waiting_scan` with no scan queued. + The scheduler poke after the hourly backstop runs only when a request was judged. + +**M17 Operator security routes (rest).** + +- Scope: `operator/security-routes.ts`: budget GET/POST, findings, scans, rescan (T3, + never `no changes`, cost preview — #43), cancel, public-requests, bypasses, project + findings resolve/reopen/comments, model, budget, public-request bypass. Paging with + the existing `pagination()` (page/limit). All writes POST + dryRun; audit targets. +- Tests: integration `operator-security.test.ts`, `operator-audit.test.ts`. +- Exit: every route in spec §13.5 operator row exists and is audited. +- As built: routes in `operator/security-routes.ts`, logic in `security/operator.ts` (so the + admin panel can call it). Added to the M4 routes: `GET/POST /security/budget`, `GET + /security/{findings,scans,public-requests,bypasses}`, `POST /security/scans/:sid/cancel` + (DO RPC `cancelScans`, reason `operator_canceled`), and under `/projects/:id/security`: + `GET findings/:fid` (added for the CLI `show`), `POST findings/:fid/{resolve,reopen,comments}`, + `POST scans` (rescan), `POST model`, `POST budget`, `POST public-request/bypass`. Reads stay + open with the capability off; scans, cancel, model, budget and rescan answer 501. Lists use + `page`/`limit`; findings and public requests list oldest first, scans and bypasses newest + first. The scans list carries the month totals (metered, gateway, refused, failed, skipped + for budget). Budget body: `platformMonthlyUsd` and `projectDefaultMonthlyUsd`, a number + (cap on at that amount) or `null` (cap off), by `expectedRevision` under the policy lock + (same revision as the policy, so the two writers never overwrite). The project budget route + sets the per-project ceiling (`cap_ceiling_cents`, event `cap_kind=ceiling`, actor + `installation_admin`). Previews of finding, model and ceiling writes run the real write in a + transaction and roll it back (`previewInRollback`), so they fail wherever the write fails. + Finding writers take `actor: 'installation_admin'` (no project role checked or recorded). + Rescan: a `trigger=rescan` row, `queued`, reading the live deployment's snapshot + (`findLiveInput`); refuses when the capability, policy or scope is off, nothing is live, the + code is gone, or a scan already waits or runs (409, own codes). The preview is the cost check: + `alreadyScanned`, `tier: full`, the model, `worstCaseUsd` (the reserve at list price) and the + budget view; the CLI confirms from it. Deviation: spec §13.3 says a live deployment with no + succeeded scan diffs from the base as usual; `chooseSecurityTier` makes every `rescan` a full + scan (as the plan says), so that case also runs T3. Bypass: `gateBypass` writes its own + `operator_events` row only for project members now; an installation admin's bypass is audited + by the operator API (or the admin panel), so there is one row, not two. A Zero Trust not + ready refusal maps to 409 `zero trust not ready`. Audit targets (`operator/audit.ts`) are ids, + known values and numbers only: no comment, reason or note text; `security/probe` now records + `{installation:'platform'}`. + +**M18 Admin panel.** + +- Scope: Security nav item with unseen-bypass badge; banner slot in `Layout` through + `renderAdminPage` and fate renders (probe failing, platform cap); screens Settings + (with previews), Findings (Urgent filter, oldest first), Scans (metered + gateway + cost, top 5 spenders, silent-gap flags), Public requests (+ bypass list); Project + detail Security section; Zero Trust page greys Disable/public-only; + `ProjectZeroTrustSection` request state, Cancel, Bypass form. All writes through + `executeAuditedMutation`. Regenerate `client.generated.ts`. +- Tests: integration `admin-security.test.ts`, extend `admin-zero-trust-actions.test.ts`; + unit view snapshots where the admin suite already has them. +- Exit: every PRD §10.6 item reachable; no comment or reason text in audit rows. +- As built: data in `admin/security-data.ts` (one Fate source `AdminSecurity` with a + `section` for the four pages, so the pages are `/admin/security`, `/findings`, `/scans`, + `/requests`); writes in `admin/routes/security.ts` (`/admin/security/*` and + `/admin/projects/:id/security/*`, the latter mounted beside the project routes with a guard scoped + to its own paths). Every write calls the operator function (`changeSecurityPolicy`, + `changeSecurityBudgets`, `setProjectSecurityModel`, `setProjectSecurityCeiling`, + `queueSecurityRescan`, `bypassPublicRequest`) inside `executeAuditedMutation`; policy and + budget forms post twice (`step=preview` renders the `securityPreview` page from the real + `dryRun`, `step=apply` writes). Banner and badge: `renderAdminPage` puts `securityChrome` + into the shared page data (read only while the capability is on, never throws) and `Layout` + reads it with `useShared` (guarded, because the navigation fallback renders the shell outside a + Void page). "Unseen" bypasses use a per-admin `platform_settings` row + (`security.bypasses-seen.`) and an explicit "Mark all as seen" button, audited as + `security/bypasses-seen`; no new table. "Cancel request" is the existing `protected=true` form. + Deviations: (1) no finding detail page, resolve, reopen or comment forms in the panel (the plan's + M18 scope lists none; the operator API has them); (2) the probe banner says "failing (checked +