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 af2f1a1aa..4f81cf71f 100644 --- a/docs/.vitepress/config.ts +++ b/docs/.vitepress/config.ts @@ -110,6 +110,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' }, ], @@ -196,6 +197,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..fe0605c0d --- /dev/null +++ b/docs/guide/platform/administration/security-audits.md @@ -0,0 +1,213 @@ +--- +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 and reaches models only through the platform. Uninstalling the platform removes it. 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. + +| Mode | Scans | +| -------------------- | --------------------------------------------------------------- | +| Off (default) | Nothing | +| Public projects only | Projects that are public, or that have no Zero Trust protection | +| All projects | Every project | + +A mode change scans nothing right away. Each project is scanned at its next deploy: the first scan reviews the whole deployment, later scans 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 give one project its own rule, from the project's **Security** section in the administrator UI or with `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 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 code by the project's `pnpm-lock.yaml` or `package-lock.json`; without one, package code is reviewed too and the result notes `third-party-unverified`. 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 first with `void project security check`. It sends the git-tracked files of the current folder, as they are on disk; untracked files, secret-like files, lockfiles, and binaries stay on the machine. It shows what it sends, which model reviews it, and the most it can cost, then asks before it uploads. It needs the policy to apply to the project (not the `never` rule), waits in the queue like any scan, and counts toward the caps. The result shows in the terminal and is 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. So code does not go to a third party until someone accepts the notice: you once for a third-party platform default, and a project owner or administrator once per project. Until then the project uses a Cloudflare model. To keep all code in Cloudflare, block the third-party models. + +A third-party model also needs an AI permission on the platform's runtime token, unless you [saved your own key](#own-provider-key). 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, which can take more than one probe run; a provider whose models are all blocked gets no copy. + +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 account's [AI Gateway Unified Billing](https://developers.cloudflare.com/ai-gateway/features/unified-billing/) credits. To bill your own key and agreement with the provider instead: + +```sh +printf "%s" "$ANTHROPIC_API_KEY" | void platform security models --provider anthropic --key-stdin --yes +void platform security probe +``` + +Void saves the key, encrypted, only if a 1-token test call with it works. Calls still go through AI Gateway, are metered at list price, and count toward the [spending caps](#spending-caps). Run the probe after saving if that provider's models could not be picked before. Saving a new key replaces the old one. `--remove-key` deletes it: scans go back to Unified Billing, and the models cannot be picked until the probe passes again. `void platform security status` shows which keys are saved, never the key. + +## Findings + +Only a human closes a finding. A scan can add one, confirm it again, or reopen it, 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 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. Leads and lower severities 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. + +When a project secret's value appears, as is or encoded, in the deployed Worker code or a static text file (`.js`, `.html`, `.json`, `.css`, `.txt`, up to 8 MB), the platform reports a `secret-in-output` finding that names the secret but never shows its value, one per secret for static files and one for Worker code. In a static file it is high and urgent, since anyone can download it 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. A value meant to be public, such as a publishable key, can be resolved as accepted risk; it stays resolved when later deploys change the bundle. + +With a Cloudflare model, a scan can test a possible finding on a throwaway copy of the deployment: the same code with empty databases, fake secrets, and no internet access, reachable only by the scanner and deleted when the scan ends. Such a finding 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 (`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. + +Export findings as SARIF with `void project security list --format sarif` (or `void platform security findings --format sarif` for every project). + +A 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} + +These scans review more than a deploy scan. Each 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. Add `--client-assets` to also review the client bundles' sources, from the source maps deployed with them. Backfill handles up to 50 projects at a time; run it again for the rest. Only a few sweeps 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 unreadable output; 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` (either executor) adds a `Void Security Audit` check to the commit. A `void deploy` from a terminal or an unconnected CI job gets none. The check is always **neutral**, so it never blocks a merge, and shows only the urgent count and a link to the project's security page, because anyone who can see the repository can read it. A scan that did not finish says so. + +While an urgent finding is open, each open pull request for that commit (up to five) gets one comment with the same counts, updated in place by later scans. 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. Otherwise, or on a check of an older deployment, it does nothing. **Re-run all** reruns the build. + +## Spending caps + +The platform pays for scans; they do not count against the plan's AI limits. Two monthly caps (calendar month, UTC) are off by default: + +- A **platform cap** that stops all scans when it is used up. +- A **project cap**, with a default for every project. A project owner or administrator can set a lower cap for their project, up to the limit you give that project, else the owner's plan cap, else the default when project caps are on. + +A scan starts only if its worst case fits under both caps. 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. The Scans page in the administrator UI shows the metered cost next to what AI Gateway reports about an hour later. 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` removes it and `inherit` returns 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 mode was set to Off sends no email. Without an [email domain](./email.md) the same information is in the CLI and on the project page, and bypasses still show in the admin pages. To send these events to your own system, set `void platform security webhook `: a signed body with ids and counts only, 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. Turning the gate off, or setting the 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. + +| 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 | +| Files not read | The scan could not read some project files (too large, not text, or a path it cannot send) | Fix them and 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. One resolved as **fixed** counts only after a clean scan of a newer deploy (an unchanged Worker redeploy is enough; a static site needs a changed deploy). A rescan of the same deployment proves nothing. + +The gate covers only the change from protected to public for an existing project. Projects that start public, and `preview-*` projects, are not covered. A later finding never makes a public project private again. + +### Bypass the scan + +An owner or a project administrator can skip the scan with a reason; platform administrators use the platform command with the project ID: + +```sh +void project zero-trust bypass --reason "Scanner down since 09:00; launch today." +void platform security bypass --reason "Scanner down since 09:00; launch today." +``` + +A bypass never skips an open urgent finding: it is refused and nothing is recorded. Every bypass is recorded with its reason and emailed to every platform administrator; list them with `void platform security bypasses`. Later findings follow the normal flow. + +## What users see + +Project members use `void project security status`, `list --urgent`, `check`, and `void project zero-trust status`. See [Projects](/reference/cli/project#void-project-security). A new CLI talking to a platform without security audits says so. Older CLIs print nothing extra after a deploy, and 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 708f75815..1f5d812e8 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. Confirm **Workers → Admin** for the account on both forms. The installer creates platform Workers, and the runtime token deploys apps into the platform's dispatch namespace. 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 | Admin | Admin | -| 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 | Write | — | -| Zone | Cache Purge | — | Purge | +| Scope | Permission | Management | Runtime | +| ------- | ------------------ | ---------- | ------------------------------------------------------------------------------------------------------------------------------------- | +| Account | Account Settings | Read | Read | +| Account | Workers | Admin | Admin | +| 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 | Write | — | +| 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 e14005c89..9d889eb37 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..d6d0dd7eb --- /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] +``` + +`limits --concurrency` sets how many scans run at once on the platform, and `--scan-timeout` how long one scan may run. Each Cloudflare (`@cf`) model runs one scan at a time, so more scans run at once only on different models. 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..7436ddea0 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,61 @@ 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 and the last bypass: + +```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. +Last bypass: Nov 17, by a project admin ("Launch today; scanner is down.") +``` + +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. With `--json`, a refusal prints the platform error code, such as `security public request has urgent findings` with the findings under `blockers`, or `public request closed` when someone protected the project or the request finished 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 3e0394c69..60e7229e5 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(import.meta.dirname, '..'); 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 62c14b87b..057a20fce 100644 --- a/packages/platform/src/discovery.ts +++ b/packages/platform/src/discovery.ts @@ -3,7 +3,11 @@ import type { PlatformApplication } from './application.ts'; import { parsePlatformLoginDescriptor, parsePlatformLoginId } from './authentication.ts'; import type { PlatformLoginDescriptor } from './authentication.ts'; import { parseUsageProtocolVersion } from './installation.ts'; -import { normalizeApplicationDomain, normalizePlatformDashboardUrl } from './manifest.ts'; +import { + normalizeApplicationDomain, + normalizePlatformDashboardUrl, + readPlatformCapability, +} from './manifest.ts'; import type { PlatformCapabilities } from './manifest.ts'; import { assertRecord, record } from './validate.ts'; @@ -163,7 +167,7 @@ export function parsePlatformDiscoveryDocument(value: unknown): PlatformDiscover } assertRecord(capabilities, 'capabilities'); const readCapability = (name: keyof PlatformCapabilities): boolean => { - const enabled = capabilities[name]; + const enabled = readPlatformCapability(capabilities, name); if (typeof enabled !== 'boolean') { throw new Error(`capabilities.${name} must be a boolean.`); } @@ -178,6 +182,7 @@ export function parsePlatformDiscoveryDocument(value: unknown): PlatformDiscover googleOAuth: readCapability('googleOAuth'), managedBuilds: readCapability('managedBuilds'), sandbox: readCapability('sandbox'), + securityAudits: readCapability('securityAudits'), }; const providers = document.authenticationProviders; if ( 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 2b186a451..d6ca6358a 100644 --- a/packages/platform/src/installer.ts +++ b/packages/platform/src/installer.ts @@ -44,6 +44,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; @@ -113,6 +115,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.'); } @@ -233,6 +238,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 0c4221c21..764ee17c0 100644 --- a/packages/platform/src/manifest.ts +++ b/packages/platform/src/manifest.ts @@ -16,6 +16,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<{ @@ -81,7 +86,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<{ @@ -123,8 +132,42 @@ 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 = new Set(['securityAudits'] satisfies ReadonlyArray< + keyof PlatformCapabilities +>); + +/** + * 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: string, + // oxlint-disable-next-line quality/no-unknown-returns -- The raw value stays unvalidated for the caller's own capability checks. +): 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), + ), + ), + ); +} + const CONTROL_PLANE_DEFAULTS: PlatformControlPlane = { apiHostname: null, dashboardHostname: null, @@ -380,17 +423,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)) { @@ -421,7 +466,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)}.`, @@ -455,13 +501,19 @@ export function parsePlatformDeploymentManifest(value: unknown): PlatformDeploym assertRecord(rawResources, 'resources'); const capabilities = Object.fromEntries( Object.keys(CORE_CAPABILITIES).map((key) => { - const entry = rawCapabilities[key]; + const entry = readPlatformCapability(rawCapabilities, key); if (typeof entry !== 'boolean') { throw new Error(`capabilities.${key} must be a boolean.`); } return [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) || @@ -500,7 +552,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 ) { @@ -512,7 +564,9 @@ export function parsePlatformDeploymentManifest(value: unknown): PlatformDeploym if ( value.schemaVersion === 6 ? storageLocationHint === undefined - : value.storageLocationHint !== undefined + : value.schemaVersion === 7 + ? value.storageLocationHint !== undefined && storageLocationHint === undefined + : value.storageLocationHint !== undefined ) { throw new Error( 'storageLocationHint requires deployment schema version 6 and a valid R2 location hint.', diff --git a/packages/platform/src/security-local-check.ts b/packages/platform/src/security-local-check.ts new file mode 100644 index 000000000..5fff9048f --- /dev/null +++ b/packages/platform/src/security-local-check.ts @@ -0,0 +1,193 @@ +/** + * Local tree checks (design doc 0095 M32), shared by the CLI that packs the tree and the + * API that reads it. The same filter runs on every scan input on the platform side. + */ + +/** + * `secret`: always dropped and listed in the coverage notes. `skipped`: lockfiles, + * generated files, `.d.ts`, binaries and media; out of scope, not counted as dropped. + */ +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', + 'png jpg jpeg gif webp avif ico bmp tif tiff heic', + 'woff woff2 ttf otf eot', + 'mp3 mp4 webm ogg wav mov', + ] + .join(' ') + .split(' '), +); + +const SECRET_EXTENSIONS = new Set(['pem', 'key', 'p12', 'pfx']); + +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 lower = path.slice(path.lastIndexOf('/') + 1).toLowerCase(); + if ( + segments.some((segment) => segment.startsWith('.git')) || + lower.startsWith('.env') || + lower === '.npmrc' || + SECRET_EXTENSIONS.has(extension(lower)) || + isKeyFileName(lower) + ) { + return 'secret'; + } + const skipped = + segments.includes('.void') || + LOCKFILES.has(lower) || + ['.d.ts', '.d.mts', '.d.cts'].some((suffix) => lower.endsWith(suffix)) || + SKIPPED_EXTENSIONS.has(extension(lower)); + return skipped ? 'skipped' : null; +} + +/** What one local check may send; the CLI checks before upload, the API again when it reads. */ +export const SECURITY_LOCAL_CHECK_LIMITS: Readonly< + Record<'maxFiles' | 'maxBytes' | '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; + } + if (path.split('/').some((segment) => segment === '' || segment === '.' || segment === '..')) { + return false; + } + return Array.from(path).every((char) => { + const code = char.charCodeAt(0); + return code >= 0x20 && code !== 0x7f && code !== 0x5c; + }); +} + +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}`); +} + +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 || + Array.from(name).some((char) => char.charCodeAt(0) > 0x7e) + ) { + 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..253c74c4c --- /dev/null +++ b/packages/platform/src/security-lockfile.ts @@ -0,0 +1,287 @@ +/** + * Third-party code by package identity (design doc 0095 M10), shared by the CLI at deploy + * and the API that drops registry packages from a scan input. A package seen as both + * local and registry is local: code that may be the owner's is never dropped. + */ + +import { isRecord } from './validate.ts'; + +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 = 5000; +/** 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('/'); + const last = segments.lastIndexOf('node_modules'); + 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 { + const local = + ['link:', 'file:', 'workspace:', 'git'].some((prefix) => version.startsWith(prefix)) || + version.includes('://'); + return local ? 'local' : '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 (!isRecord(value) || !isRecord(value.packages)) { + return null; + } + const index = new Map(); + for (const [key, entry] of Object.entries(value.packages)) { + const name = packageNameOfPath(key); + if (name === null || !isRecord(entry)) { + continue; + } + const { link, resolved } = entry; + // 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.at(-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` give each + * direct dependency's `version:`, `packages` each resolved package's `resolution`. + * 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 (!isRecord(value)) { + return null; + } + const { registry, local } = value; + if ( + !Array.isArray(registry) || + !Array.isArray(local) || + registry.length + local.length > SECURITY_PACKAGE_CLAIMS_MAX || + !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..bd91209fd --- /dev/null +++ b/packages/platform/src/security-models.ts @@ -0,0 +1,269 @@ +/** + * The only list of models a security scan can run on, shared by the platform API and the + * CLI. Prices are list prices in USD per million tokens; an unpriced model cannot be picked. + */ + +/** 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; + /** + * USD per million input tokens read from the prompt cache, when the model lists a + * cached-input price. Without it, cached input costs the plain input price. + */ + cachedInputUsdPerMillion?: 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', + // Workers AI catalog (ai/models/search), 2026-11-18. + price: { inputUsdPerMillion: 0.3, outputUsdPerMillion: 1.2, cachedInputUsdPerMillion: 0.006 }, + }, + { + id: '@cf/zai-org/glm-5.3', + host: 'workers-ai', + engine: 'void_loop', + zeroDataRetention: true, + refusalRisk: 'low', + // Workers AI catalog (ai/models/search), 2026-11-18. + price: { inputUsdPerMillion: 1.4, outputUsdPerMillion: 4.4, cachedInputUsdPerMillion: 0.26 }, + }, + { + 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 at the model's list price in whole nano-dollars; `cachedInputTokens` is the part of + * `inputTokens` read from the prompt cache. `null` when the model has no price. + */ +export function securityModelCostNanoUsd( + id: SecurityModelId, + inputTokens: number, + outputTokens: number, + cachedInputTokens = 0, +): number | null { + assertTokenCount(inputTokens, 'inputTokens'); + assertTokenCount(outputTokens, 'outputTokens'); + assertTokenCount(cachedInputTokens, 'cachedInputTokens'); + const price = getSecurityModel(id).price; + if (!price) { + return null; + } + const cached = Math.min(cachedInputTokens, inputTokens); + return ( + (inputTokens - cached) * nanoUsdPerToken(price.inputUsdPerMillion) + + cached * nanoUsdPerToken(price.cachedInputUsdPerMillion ?? 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 at start (spec §16.1). */ +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', + ]; +} + +/** Why a scan does not run on the project's own pick (the platform API sends it as `pickProblem`). */ +export type SecurityPickProblem = 'blocked' | 'unknown' | 'notice' | 'unavailable'; + +/** + * The model line note when the project's pick does not run (spec §8.2), shared by the + * project page and the CLI: `your pick openai/gpt-6.1-sol is blocked by the platform admin`. + */ +export function securityPickProblemNote(pick: string, problem: SecurityPickProblem): string { + switch (problem) { + case 'blocked': + return `your pick ${pick} is blocked by the platform admin`; + case 'unknown': + return `your pick ${pick} is not offered on this platform any more`; + case 'notice': + return `your pick ${pick} waits for the provider notice: void project security model ${pick} --accept-provider-notice`; + case 'unavailable': + return `your pick ${pick} cannot run on this platform now`; + } +} diff --git a/packages/platform/src/security-policy.ts b/packages/platform/src/security-policy.ts new file mode 100644 index 000000000..5516969b6 --- /dev/null +++ b/packages/platform/src/security-policy.ts @@ -0,0 +1,705 @@ +/** + * The installation security audit policy (spec §5.3), shared by the platform API and the + * CLI. The API checks a new policy with the strict `parseSecurityPolicy` and reads the + * stored row with the lenient `readSecurityPolicy`. + */ +import { + DEFAULT_SECURITY_MODEL, + isSecurityModelId, + isSecurityModelPriced, + isThirdPartySecurityModel, + SECURITY_MODEL_IDS, +} from './security-models.ts'; +import type { SecurityModelId } from './security-models.ts'; +import { isPrintableText, isRecord, 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 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 = { + /** Running scans per installation. */ + concurrency: { min: 1, max: 10, default: 2 }, + /** Wall clock per scan, the only timeout setting. */ + timeoutMinutes: { min: 5, max: 60, default: 20 }, + maxInputTokens: { min: 50_000, max: 2_000_000, default: 1_200_000 }, + maxOutputTokens: { min: 5000, max: 200_000, default: 120_000 }, + modelCallsPerScan: { min: 10, max: 200, default: 80 }, +} as const; + +export type SecurityLimitKey = keyof typeof SECURITY_LIMIT_RANGES; +export type SecurityPolicyLimits = Readonly>; + +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). Off by default: they cost money. */ +export type SecuritySweeps = Readonly<{ on: boolean; everyDays: number }>; + +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 }>; + /** While failing: when the probe first failed in this run of failures. */ + failingSince?: string; +}>; + +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; + /** Spec §8.5: re-scan once on the `@cf` default after a third-party scan fails. */ + fallbackToCf: boolean; + /** Spec §20: a weekly summary email to installation admins. */ + 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. + */ +export const SECURITY_ERRORS = { + 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 }, +} as const; + +export type SecurityErrorName = keyof typeof SECURITY_ERRORS; +export type SecurityError = (typeof SECURITY_ERRORS)[SecurityErrorName]; + +export function defaultSecurityBudgets(): SecurityPolicyBudgets { + return { + platformCapOn: false, + platformMonthlyUsd: 1000, + projectCapsOn: false, + projectDefaultMonthlyUsd: 100, + }; +} + +function wholeInRange(value: unknown, range: SecurityLimitRange, label: string): number { + if ( + typeof value !== 'number' || + !Number.isSafeInteger(value) || + value < range.min || + value > range.max + ) { + throw new Error(`${label} must be a whole number from ${range.min} to ${range.max}.`); + } + return value; +} + +/** `sweeps.everyDays`: a whole number of days in `SECURITY_SWEEP_DAYS_RANGE`. */ +export function parseSecuritySweepDays(value: unknown): number { + return wholeInRange(value, SECURITY_SWEEP_DAYS_RANGE, 'sweeps.everyDays'); +} + +/** + * The sweep setting; a row saved before sweeps existed reads as Off. The lenient reader + * clamps the days and reads anything else as Off, so bad data never starts paid scans. + */ +function parseSweeps(value: unknown, strict: boolean): SecuritySweeps { + const off = { on: false, everyDays: SECURITY_SWEEP_DAYS_RANGE.default }; + if (value === undefined) { + return off; + } + if (strict) { + const input = record(value, 'sweeps'); + return { + on: parseBoolean(input.on, 'sweeps.on'), + everyDays: parseSecuritySweepDays(input.everyDays), + }; + } + const input: Record = isRecord(value) ? value : {}; + const days = input.everyDays; + if (typeof input.on !== 'boolean' || typeof days !== 'number' || !Number.isSafeInteger(days)) { + return off; + } + 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 missing one reads as Off. The + * lenient reader reads a bad value as Off, so bad data never starts paid scans or mail. + */ +function parseAddedFlag(value: unknown, label: string, strict: boolean): boolean { + if (value === undefined || (!strict && typeof value !== 'boolean')) { + return false; + } + return parseBoolean(value, label); +} + +/** + * The security webhook URL (spec §20): `https` only, no user name or password (the body + * is signed instead), at most 2048 characters. Returns the normalized URL. + */ +export function parseSecurityWebhookUrl(value: unknown): string { + const max = 2048; + if (typeof value !== 'string' || value.length === 0 || value.length > max) { + throw new Error(`The webhook URL must be an https URL of at most ${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: limitsFrom({}, false), + budgets: defaultSecurityBudgets(), + entitlement: null, + publicGate: false, + sweeps: parseSweeps(undefined, true), + fallbackToCf: false, + digest: false, + revision: 0, + }; +} + +export function isSecurityMode(value: unknown): value is SecurityMode { + return SECURITY_MODES.some((mode) => mode === value); +} + +function parseModelId(value: unknown, label: string): SecurityModelId { + if (!isSecurityModelId(value)) { + throw new Error(`${label} must be one of: ${SECURITY_MODEL_IDS.join(', ')}.`); + } + return value; +} + +/** + * Every limit, each in range. The lenient reader clamps a limit into today's range and + * gives a limit the row lacks its default. + */ +function limitsFrom(value: unknown, strict: boolean): SecurityPolicyLimits { + const input = record(value, 'Security limits'); + const read = (key: SecurityLimitKey): number => { + const range = SECURITY_LIMIT_RANGES[key]; + const limit = input[key]; + if (strict) { + return wholeInRange(limit, range, 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'), + }; +} + +/** 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] = wholeInRange(limit, SECURITY_LIMIT_RANGES[known], known); + } + 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; +} + +function parseBudgets(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 { + const time = typeof value === 'string' ? Date.parse(value) : Number.NaN; + if (!Number.isFinite(time) || new Date(time).toISOString() !== value) { + throw new Error(`${label} must be an ISO 8601 timestamp.`); + } + return String(value); +} + +function parseNotice(value: unknown): SecurityThirdPartyNotice | null { + if (value === null) { + return null; + } + const input = record(value, 'thirdPartyNotice'); + if (!isPrintableText(input.acceptedByUserId, 200)) { + throw new Error('thirdPartyNotice.acceptedByUserId must be a user ID.'); + } + const acceptedAt = parseIsoTimestamp(input.acceptedAt, 'thirdPartyNotice.acceptedAt'); + const version = input.version; + if (typeof version !== 'number' || !Number.isSafeInteger(version) || version < 1) { + throw new Error('thirdPartyNotice.version must be a positive whole number.'); + } + return { acceptedByUserId: input.acceptedByUserId, acceptedAt, version }; +} + +function parseEntitlement(value: unknown): SecurityEntitlement | null { + if (value === null) { + return null; + } + 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'), + }, + // Added later, so a row without it still reads; a passing probe has none. + ...(!ok && input.failingSince !== undefined + ? { failingSince: parseIsoTimestamp(input.failingSince, 'entitlement.failingSince') } + : {}), + }; +} + +/** Each id once. The lenient reader drops ids a later release added. */ +function blockedModelsFrom(value: unknown, strict: boolean): 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 (strict) { + const id = parseModelId(entry, 'Each blocked model'); + if (blocked.includes(id)) { + throw new Error(`Blocked model listed twice: ${id}.`); + } + blocked.push(id); + } else if (isSecurityModelId(entry) && !blocked.includes(entry)) { + blocked.push(entry); + } + } + return blocked; +} + +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 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. + */ +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; +} + +/** The rules that tie policy fields together; the API checks runtime conditions itself. */ +function assertConsistent(policy: SecurityPolicy): SecurityPolicy { + 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.'); + } + return policy; +} + +function policyFrom(value: unknown, strict: boolean): SecurityPolicy { + const input = record(value, 'Security policy'); + const revision = input.revision; + if (typeof revision !== 'number' || !Number.isSafeInteger(revision) || revision < 0) { + throw new Error('Security policy revision must be a nonnegative whole number.'); + } + if (!isSecurityMode(input.mode)) { + throw new Error('Security audit mode must be disabled, public or all.'); + } + const asked = strict ? parseModelId(input.defaultModel, 'defaultModel') : null; + const blockedModels = blockedModelsFrom(input.blockedModels, strict); + const thirdPartyNotice = parseNotice(input.thirdPartyNotice); + return assertConsistent({ + mode: input.mode, + defaultModel: asked ?? readDefaultModel(input.defaultModel, blockedModels, thirdPartyNotice), + blockedModels, + thirdPartyNotice, + limits: limitsFrom(input.limits, strict), + budgets: parseBudgets(input.budgets), + entitlement: parseEntitlement(input.entitlement), + publicGate: parseBoolean(input.publicGate, 'publicGate'), + sweeps: parseSweeps(input.sweeps, strict), + fallbackToCf: parseAddedFlag(input.fallbackToCf, 'fallbackToCf', strict), + digest: parseAddedFlag(input.digest, 'digest', strict), + revision, + }); +} + +/** + * Strict check of a policy about to be written: every known field present and valid, + * and the fields agree. Unknown fields are ignored. + */ +export function parseSecurityPolicy(value: unknown): SecurityPolicy { + return policyFrom(value, true); +} + +/** + * Reader of the stored policy row. Data another release could have written still reads: + * unknown blocked models are dropped, a default this release cannot run falls back, + * limits are clamped. Anything else the strict parser refuses throws here too. + */ +export function readSecurityPolicy(value: unknown): SecurityPolicy { + return policyFrom(value, false); +} + +/** 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; +} + +/** + * `platform_settings` key of the per-plan monthly scan caps (M27). Kept out of + * `plans:catalog`: an older API rebuilds the catalog from known keys on every write, so + * a cap stored there would 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 interface PlanSecurityCaps { + readonly [planId: string]: number | null; +} + +/** A read caps row and how many entries it left out. */ +export interface PlanSecurityCapsRead { + readonly caps: PlanSecurityCaps; + readonly dropped: number; +} + +/** + * 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'; + +function isPlanSecurityCapCents(value: unknown): value is number { + return ( + typeof value === 'number' && + Number.isSafeInteger(value) && + value >= 0 && + value <= SECURITY_MAX_MONTHLY_USD * 100 + ); +} + +/** 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 > 64 || key[0] < 'a' || key[0] > 'z') { + return false; + } + return Array.from(key).every( + (char) => (char >= 'a' && char <= 'z') || (char >= '0' && char <= '9') || char === '-', + ); +} + +/** + * 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): PlanSecurityCapsRead { + if (value === null || value === undefined) { + return { caps: {}, dropped: 0 }; + } + if (!isRecord(value)) { + return { caps: {}, dropped: 1 }; + } + const caps: Record = {}; + let dropped = 0; + for (const [key, entry] of Object.entries(value)) { + if (isPlanKey(key) && (entry === null || isPlanSecurityCapCents(entry))) { + caps[key] = entry; + } else { + dropped++; + } + } + return { caps, dropped }; +} + +/** The cap of one plan in a caps row. */ +export function planSecurityCap(caps: PlanSecurityCaps, planId: string): SecurityPlanCap { + if (!Object.hasOwn(caps, planId)) { + return 'inherit'; + } + return caps[planId] ?? 'none'; +} + +/** + * Reads a plan change's `securityCap` field: a USD amount (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 || 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 cents = String(cap % 100).padStart(2, '0'); + return `$${Math.floor(cap / 100).toLocaleString('en-US')}.${cents} / month`; +} + +/** `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; + } + return Array.from(text).every((char) => char >= '0' && char <= '9') ? Number(text) : null; +} + +/** 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 finding trace of `{ file, line, note }` steps as `file:line note` lines, as the CLI + * and the project page print it; `null` for another shape. Callers clean the text. + */ +export function securityTraceLines(value: unknown): Array | null { + if (!Array.isArray(value) || value.length === 0) { + return null; + } + const lines: Array = []; + for (const step of value) { + if (!isRecord(step) || typeof step.file !== 'string' || typeof step.note !== 'string') { + return null; + } + lines.push(`${step.file}${typeof step.line === 'number' ? `:${step.line}` : ''} ${step.note}`); + } + return lines; +} + +/** + * 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`. + */ +export function parseSecurityUsdText(text: string): number | null | undefined { + let amount = text.trim(); + if (amount === '') { + return null; + } + if (amount.startsWith('$')) { + amount = amount.slice(1); + } + const [whole = '', fraction, ...extra] = amount.split('.'); + if ( + extra.length > 0 || + parseSecurityDigits(whole, 7) === null || + (fraction !== undefined && parseSecurityDigits(fraction, 2) === null) + ) { + return undefined; + } + return Number(amount); +} diff --git a/packages/platform/src/worker-config.ts b/packages/platform/src/worker-config.ts index 0f5d83f0c..b1deb703a 100644 --- a/packages/platform/src/worker-config.ts +++ b/packages/platform/src/worker-config.ts @@ -1,5 +1,9 @@ import { createPlatformResourceOwnershipMarker } from './installation.ts'; -import { createApplicationRoutes, platformDashboardUrl } from './manifest.ts'; +import { + createApplicationRoutes, + platformDashboardUrl, + serializePlatformCapabilities, +} from './manifest.ts'; import type { PlatformDeploymentManifest } from './manifest.ts'; export type PlatformProvisionedResourceIds = Readonly<{ @@ -30,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> >; @@ -76,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 } @@ -144,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: { @@ -152,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: [ @@ -159,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: [ @@ -196,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', @@ -246,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, @@ -273,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..235e6b45d 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,11 @@ describe('direct Worker upload discovery', () => { ); }); }); + +it('reads a discovery document from before security audits as off', () => { + const discovery = createPlatformDiscoveryDocument(base); + const { securityAudits: _, ...olderCapabilities } = discovery.capabilities; + const parsed = parsePlatformDiscoveryDocument({ ...discovery, capabilities: olderCapabilities }); + expect(parsed).toEqual(discovery); + expect(parsed.capabilities.securityAudits).toBe(false); +}); diff --git a/packages/platform/test/unit/auth-manifest.test.ts b/packages/platform/test/unit/auth-manifest.test.ts index 9366aafa5..247f75fee 100644 --- a/packages/platform/test/unit/auth-manifest.test.ts +++ b/packages/platform/test/unit/auth-manifest.test.ts @@ -50,3 +50,30 @@ 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) => + // oxlint-disable-next-line unicorn/prefer-structured-clone -- Exercise the JSON representation read by the parser. + parsePlatformDeploymentManifest(JSON.parse(JSON.stringify(manifest))); + + it('reads a missing capability as off and needs schema version 7 to turn it on', () => { + const off = createPlatformDeploymentManifest(input); + expect(off.schemaVersion).toBe(1); + const { securityAudits: _, ...olderCapabilities } = off.capabilities; + expect(roundTrip({ ...off, capabilities: olderCapabilities })).toEqual(off); + + const on = createPlatformDeploymentManifest({ + ...input, + capabilities: { securityAudits: true }, + }); + expect(on.schemaVersion).toBe(7); + expect(roundTrip(on)).toEqual(on); + expect(() => roundTrip({ ...on, schemaVersion: 1 })).toThrow('schema version 7'); + expect(() => roundTrip({ ...off, schemaVersion: 7 })).toThrow('schema version 7'); + }); +}); 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..edbd17a7e --- /dev/null +++ b/packages/platform/test/unit/security-models.test.ts @@ -0,0 +1,24 @@ +import { expect, it } from 'vite-plus/test'; +import { + securityModelCostNanoUsd, + securityModelCostUsd, + securityScanReserveUsd, +} from '../../src/security-models.ts'; + +// I7: a scan reserves its worst case at list price; calls add up in whole nano-dollars. +it('reserves the worst case of a scan and prices calls without drift', () => { + expect(securityScanReserveUsd('@cf/zai-org/glm-5.3')).toBe(2.208); + expect(securityScanReserveUsd('anthropic/claude-sonnet-5.5')).toBeNull(); + const limits = { maxInputTokens: 100_000, maxOutputTokens: 10_000 }; + expect(securityScanReserveUsd('anthropic/claude-opus-5.5', limits)).toBe(0.6); + 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)); + // Cached input at the cached rate; a model with no cached price pays the plain price. + expect(securityModelCostNanoUsd('@cf/zai-org/glm-5.3', 100, 0, 60)).toBe(40 * 1400 + 60 * 260); + expect(securityModelCostNanoUsd('openai/gpt-6.1-sol', 100, 0, 60)).toBe(100 * 2000); + expect(securityModelCostUsd('anthropic/claude-sonnet-5.5', 10, 10)).toBeNull(); + expect(() => securityModelCostNanoUsd('@cf/zai-org/glm-5.3', -1, 0)).toThrow('inputTokens'); +}); 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..75900586d --- /dev/null +++ b/packages/platform/test/unit/security-policy.test.ts @@ -0,0 +1,72 @@ +import { describe, expect, it } from 'vite-plus/test'; +import { + defaultSecurityPolicy, + isSecurityEntitlementFresh, + parseSecurityPolicy, + readSecurityPolicy, + SECURITY_ENTITLEMENT_MAX_AGE_MS, + SECURITY_LIMIT_RANGES, +} from '../../src/security-policy.ts'; +import type { SecurityPolicy } from '../../src/security-policy.ts'; + +const CHECKED_AT = '2026-11-18T03:00:00.000Z'; +const CF_DEFAULT = '@cf/deepseek-ai/deepseek-v4.1-flash-1017'; + +// oxlint-disable-next-line quality/no-unknown-returns -- The test feeds the parser untrusted stored JSON. +function stored(overrides: Partial> = {}): unknown { + // oxlint-disable-next-line unicorn/prefer-structured-clone -- Exercise the JSON representation read by the parser, which drops undefined keys. + return JSON.parse(JSON.stringify({ ...defaultSecurityPolicy(), ...overrides })); +} + +describe('security policy', () => { + it('starts Off, with no gate, no budgets on and the @cf default', () => { + const policy = defaultSecurityPolicy(); + expect(policy).toMatchObject({ + mode: 'disabled', + defaultModel: CF_DEFAULT, + thirdPartyNotice: null, + publicGate: false, + budgets: { platformCapOn: false, projectCapsOn: false }, + }); + expect(parseSecurityPolicy(stored())).toEqual(policy); + }); + + it('repairs a row another release wrote, which the write path refuses', () => { + const retired = stored({ + mode: 'public', + defaultModel: 'openai/gpt-5-retired', + blockedModels: ['openai/gpt-5-retired', '@cf/zai-org/glm-5.3'], + }); + expect(() => parseSecurityPolicy(retired)).toThrow('defaultModel must be one of'); + expect(readSecurityPolicy(retired)).toMatchObject({ + mode: 'public', + defaultModel: CF_DEFAULT, + blockedModels: ['@cf/zai-org/glm-5.3'], + }); + // I8: a third-party default needs the accepted provider notice. + const noNotice = stored({ defaultModel: 'openai/gpt-6.1-terra' }); + expect(() => parseSecurityPolicy(noNotice)).toThrow('needs the accepted provider notice'); + expect(readSecurityPolicy(noNotice).defaultModel).toBe(CF_DEFAULT); + const tooMany = stored({ limits: { ...defaultSecurityPolicy().limits, concurrency: 50 } }); + expect(() => parseSecurityPolicy(tooMany)).toThrow(); + expect(readSecurityPolicy(tooMany).limits.concurrency).toBe( + SECURITY_LIMIT_RANGES.concurrency.max, + ); + }); + + it('counts only a passing probe, for 24 hours', () => { + const now = Date.parse(CHECKED_AT); + const entitlement = { + checkedAt: CHECKED_AT, + ok: true, + missing: [], + hosts: { openai: true, anthropic: false }, + }; + expect(isSecurityEntitlementFresh(entitlement, now)).toBe(true); + expect(isSecurityEntitlementFresh(entitlement, now + SECURITY_ENTITLEMENT_MAX_AGE_MS)).toBe( + false, + ); + expect(isSecurityEntitlementFresh({ ...entitlement, ok: false }, now)).toBe(false); + expect(isSecurityEntitlementFresh(null, now)).toBe(false); + }); +}); diff --git a/packages/platform/test/unit/worker-config.test.ts b/packages/platform/test/unit/worker-config.test.ts index fe4fe618d..63196c772 100644 --- a/packages/platform/test/unit/worker-config.test.ts +++ b/packages/platform/test/unit/worker-config.test.ts @@ -203,11 +203,70 @@ 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 off = () => workerConfigs({ securityScanScheduler: true }); + const readVars = (value: unknown) => { + const { PLATFORM_CAPABILITIES: capabilities, ...other } = (value ?? {}) as Record< + string, + string + >; + return { capabilities: capabilities ? JSON.parse(capabilities) : undefined, other }; + }; + + it('adds only the scheduler binding and its migration when the capability is off', () => { + const configs = off(); + const older = workerConfigs(); + const { durable_objects: bindings, migrations: _, ...rest } = configs.api; + const { durable_objects: olderBindings, migrations: __, ...olderRest } = older.api; + expect(rest).toEqual(olderRest); + expect((bindings as { bindings: Array }).bindings).toEqual([ + ...(olderBindings as { bindings: Array }).bindings, + { name: 'SECURITY_SCAN_SCHEDULER', class_name: 'SecurityScanScheduler' }, + ]); + const { api: _api, ...others } = configs; + const { api: _olderApi, ...olderOthers } = older; + expect(others).toEqual(olderOthers); + expect(Object.keys(configs).sort()).toEqual([...workers]); + expect(JSON.stringify(configs)).not.toContain('securityAudits'); + }); + + it('adds only the AI binding on the API Worker when the capability is on', () => { + const on = workerConfigs({ + securityScanScheduler: true, + deployment: createPlatformDeploymentManifest({ + ...deploymentInput, + capabilities: { securityAudits: true }, + }), + }); + const before = off(); + expect(Object.keys(on).sort()).toEqual([...workers]); + for (const worker of workers) { + const { ai, vars, ...rest } = on[worker]; + const { ai: offAi, vars: offVars, ...offRest } = before[worker]; + expect(rest).toEqual(offRest); + expect(ai).toEqual(worker === 'api' ? { binding: 'AI' } : offAi); + const now = readVars(vars); + const was = readVars(offVars); + expect(now.other).toEqual(was.other); + expect(now.capabilities).toEqual( + was.capabilities && { ...was.capabilities, 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..b184b7be4 100644 --- a/packages/void/skills/void/SKILL.md +++ b/packages/void/skills/void/SKILL.md @@ -64,6 +64,9 @@ Use `void deploy --skip-migrations` when database migrations run separately; it | 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` | +| Security audit admin commands | `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` | @@ -101,6 +104,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 bd08dbc28..bd36c8d6b 100644 --- a/packages/void/src/cli/cli-main.ts +++ b/packages/void/src/cli/cli-main.ts @@ -97,6 +97,27 @@ 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; + // A refusal's details (urgent blockers, a closed request's state) stay in the JSON. + const details = (err as { details?: unknown }).details; + console.error( + JSON.stringify({ + ...(details !== null && typeof details === 'object' && !Array.isArray(details) + ? details + : {}), + 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( @@ -319,7 +340,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 7f4bacff8..e42dbb750 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'; @@ -14,6 +15,23 @@ import { } from './platform-errors.ts'; 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, @@ -159,6 +177,25 @@ 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. + */ +function securityApiError(error: PlatformApiError): 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'; @@ -283,6 +320,11 @@ 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; + /** The newest bypass; `reason` only for callers with `deploy` and up. */ + lastBypass?: { id: string; at: string; byRole: string | null; reason?: string } | null; project: ProjectZeroTrustState | null; }; @@ -290,6 +332,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 & { @@ -577,7 +628,16 @@ export type GithubConnection = { updated_at: string; }; -export type ManifestOnlyDeployPayload = DeployUploadPayload; +type SecurityCheckTree = { files: number; bytes: number; size: number; md5: string }; + +/** + * `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 @@ -843,11 +903,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 } @@ -863,7 +929,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>(); } @@ -953,6 +1024,260 @@ export class PlatformClient { ); } + /** `tooOld`: what a platform without this route cannot do, for a 404 with no JSON body. */ + private async security( + path: string, + action: string, + options: { + method?: string; + body?: unknown; + permission: ProjectPermission; + signal?: AbortSignal; + tooOld?: string; + }, + ): Promise { + const { tooOld, ...request } = options; + try { + return await this.json(`${this.baseUrl}/projects/${path}`, action, request); + } catch (error) { + if (!(error instanceof PlatformApiError)) { + throw error; + } + if (tooOld && error.status === 404 && parsePlatformErrorBody(error.body) === null) { + throw new Error( + `project: This Void platform ${tooOld} yet. Ask its administrator to upgrade with \`void platform upgrade\`.`, + { cause: 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), + ...(query.urgent ? { urgent: '1' } : {}), + ...(query.severity ? { severity: query.severity } : {}), + ...(query.cursor ? { 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 { + // The finding was read just before, so a plain 404 is a platform without this route. + return this.security( + `${projectId}/security/findings/${encodeURIComponent(findingId)}/severity`, + 'Failed to change the severity of the security finding', + { method: 'POST', body, permission: 'settings', tooOld: 'cannot change finding severity' }, + ); + } + + 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 is named as too old. */ + private async securityCheck( + path: string, + action: string, + options: { method?: string; body?: unknown }, + ): Promise { + return this.security(path, action, { + ...options, + permission: 'deploy', + tooOld: 'cannot run local security checks', + }); + } + + /** What a local check would run (model, provider notice, most it can cost). Sends no code. */ + async previewProjectSecurityCheck( + projectId: string, + tree: SecurityCheckTree, + ): Promise { + const body = { dryRun: true, ...tree }; + return this.securityCheck( + `${projectId}/security/checks`, + 'Failed to prepare the security check', + { method: 'POST', body }, + ); + } + + /** Stores the check and returns the one presigned upload for its archive. */ + async createProjectSecurityCheck( + projectId: string, + tree: SecurityCheckTree, + ): 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', + }); + } + + /** `requestId`: the open request the caller saw; one closed meanwhile is a 409. */ + async bypassProjectPublicRequest( + projectId: string, + reason: string, + requestId?: string, + ): Promise { + return this.security( + `${projectId}/zero-trust/public-request/bypass`, + 'Failed to bypass the security scan', + { + method: 'POST', + body: requestId === undefined ? { reason } : { reason, requestId }, + 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 e5680be89..d2156ecae 100644 --- a/packages/void/src/cli/deploy-managed-events.ts +++ b/packages/void/src/cli/deploy-managed-events.ts @@ -12,6 +12,7 @@ import { formatStreamDeployError, } from './deploy-errors.ts'; import { log, DeployEventError } from './deploy-helpers.ts'; +import { readSecurityPackageClaims } from './deploy-security-packages.ts'; import type { ApplyDeployEventResult, StreamDeployResult } from './deploy-types.ts'; import { uploadAssetsToR2 } from './direct-r2-upload.ts'; import type { DirectR2PutItem } from './direct-r2-upload.ts'; @@ -290,6 +291,7 @@ export async function streamDirectR2Deploy({ gitMetadata, preflightUsed, workerFiles, + root, spinner: s, cliLog, }: { @@ -303,6 +305,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 { @@ -311,6 +315,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) @@ -443,6 +452,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 2d6920c74..77ed51fdd 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'; @@ -247,6 +248,7 @@ export async function runFrameworkDeploy( gitMetadata, preflightUsed: skipped > 0, workerFiles, + root, spinner: s, cliLog, }); @@ -271,4 +273,5 @@ export async function runFrameworkDeploy( warnUnpublishedRouting(result); printDeploySuccess(result.published !== false); + await printDeploySecurityNotice({ client, ...config, 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 0e1256092..b66f53818 100644 --- a/packages/void/src/cli/deploy-managed-full.ts +++ b/packages/void/src/cli/deploy-managed-full.ts @@ -48,6 +48,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'; @@ -490,6 +491,7 @@ export async function runFullDeploy( gitMetadata, preflightUsed: skipped > 0, workerFiles, + root, spinner: s, cliLog, }); @@ -512,4 +514,5 @@ export async function runFullDeploy( warnUnpublishedRouting(result); printDeploySuccess(result.published !== false); + await printDeploySecurityNotice({ client, ...config, 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 8a0f3a927..17740dd86 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'; @@ -173,4 +174,5 @@ export async function runStaticDeploy( warnUnpublishedRouting(result); printDeploySuccess(result.published !== false); + await printDeploySecurityNotice({ client, ...config, 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..076426b18 --- /dev/null +++ b/packages/void/src/cli/deploy-security-notice.ts @@ -0,0 +1,371 @@ +import { SECURITY_PROVIDER_NAMES } from '@void/platform/security-models'; +import { hasOwnKey } from '../shared/has-own-key.ts'; +import { PlatformApiError } from './client.ts'; +import type { PlatformClient } from './client.ts'; +import type { CliLogger } from './log-file.ts'; +import { cleanLine } from './output.ts'; +import { budgetAhead, budgetCause, budgetSkipCopy, urgentCounts } from './project-security.ts'; +import type { + ProjectSecurityStatus, + SecurityBudgetCause, + 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 = 5000; +const MAX_ROWS = 5; +const MAX_TITLE = 120; + +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]; + if (hasOwnKey(SECURITY_PROVIDER_NAMES, prefix)) { + return SECURITY_PROVIDER_NAMES[prefix]; + } + return prefix ? cleanLine(prefix) : 'a third-party provider'; +} + +/** `Not security-scanned: …` for a budget skip (spec §6.5, §16.3). */ +function budgetLines( + cause: SecurityBudgetCause, + status: ProjectSecurityStatus, + projectId: string | undefined, +): Array { + const copy = budgetSkipCopy(cause, status.budget, status.model.id, projectId); + if (copy.raised) { + return [` Not security-scanned: ${copy.why}. The next deploy is scanned.`]; + } + const first = ` Not security-scanned: ${copy.why}.${copy.resets ? ` ${copy.resets}` : ''}`; + if (copy.next === null) { + return [status.budget ? `${first} Ask your platform admin.` : first]; + } + return [first, ` ${copy.next}`]; +} + +function scanLines( + slug: string, + deploymentId: string, + status: ProjectSecurityStatus, + projectId: string | undefined, +): Array { + const { policy, lastScan, model, budget } = status; + if (!lastScan || lastScan.deploymentId !== deploymentId) { + return []; + } + const reason = lastScan.statusReason ?? ''; + // A protected project under `public` is out of scope, and its deploy says why. + const protectedSkip = lastScan.status === 'skipped' && reason === 'protected'; + if (!policy.applies && !protectedSkip) { + return []; + } + switch (lastScan.status) { + case 'queued': + case 'running': + case 'pending_input': { + // The cap is checked again when the scan starts; one used up now skips it then. + const ahead = lastScan.status === 'running' ? null : budgetAhead(budget); + if (ahead) { + return budgetLines(ahead, status, projectId); + } + 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') { + return budgetLines(budgetCause(lastScan, budget), status, projectId); + } + 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; + // The newest scan is usually this deploy's own, just queued: warn about the one before. + const prior = lastScan?.deploymentId === deploymentId ? (status.previousScan ?? null) : lastScan; + if (!policy.applies || !prior || prior.deploymentId === deploymentId) { + return []; + } + const why = failureWhy(prior); + if (!why) { + return []; + } + const lines = [ + ` Warning: the security scan of ${cleanLine(prior.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'); + case 'incomplete': + return (scan.statusReason ?? '').startsWith('budget') + ? 'the monthly scan budget ran out' + : `partial: ${cleanLine(scan.statusReason ?? 'stopped early')}`; + 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 = urgentCounts(urgent); + 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; projectId?: 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, input.projectId), + 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(input, 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..67325afd5 --- /dev/null +++ b/packages/void/src/cli/deploy-security-packages.ts @@ -0,0 +1,91 @@ +/** + * The package claims a deploy sends for security scans (design doc 0095 M10): which + * packages the Worker source maps name come from the registry, per the nearest lockfile. + * 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, +} from '@void/platform/security-lockfile'; +import 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 fd689f1a4..5ae1ce42c 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 = { }, { 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 = { }, { 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 = { 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 = { 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,113 @@ const HELP_TREE = { }, 'zero-trust': { summary: 'Inspect and manage Zero Trust protection for a Void platform project.', - 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: '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]`, - ), - ]), - ), + usage: ['void project zero-trust [options]'], + commands: helpRows([ + ['status', 'Show desired and effective protection state'], + ['protect', 'Protect the project'], + ['public', 'Make the project public (may wait for a security scan)'], + [ + 'bypass --reason ""', + 'Skip the security scan for a waiting request (admin or owner)', + ], + ['reconcile', 'Repair Cloudflare Access configuration drift'], + ]), + options: helpRows([ + ['--project ', 'Project name override'], + ['--json', 'Print machine-readable output'], + ['--reason ', 'bypass: why the scan is skipped (required)'], + ['--yes', 'bypass: skip the confirmation prompt'], + ]), + children: { + ...Object.fromEntries( + [ + [ + 'status', + 'Show desired and effective Zero Trust protection and any open public request.', + ], + ['protect', 'Protect the project with the platform Access policy.'], + [ + 'public', + '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.', + ], + ].map(([action, summary]) => [ + action, + withProjectOption(summary, `void project zero-trust ${action} [options]`, true), + ]), + ), + 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: helpRows([ + ['--reason ', 'Why the scan is skipped (required)'], + ['--yes', 'Skip the confirmation prompt (needed in CI)'], + ['--project ', 'Project name override'], + ['--json', 'Print machine-readable output'], + ]), + }, + reconcile: withProjectOption( + 'Repair Cloudflare Access configuration drift for the project.', + 'void project zero-trust reconcile [options]', + true, + ), + }, + }, + security: { + summary: + 'Review security audit findings, scans, model and budget for a Void platform project.', + usage: ['void project security [options]'], + commands: helpRows([ + ['status', 'Urgent findings, policy, model, budget and last scan'], + ['list', 'List findings (--urgent, --state, --severity, --leads, --format sarif)'], + ['show ', 'Show one finding with its history'], + ['comment ""', 'Add a comment (collaborator or higher)'], + ['resolve ...', 'Resolve findings with --reason and --comment'], + ['reopen ', 'Reopen a resolved finding with --comment'], + [ + 'severity ', + 'Set the severity of an open finding with --comment (scan: use the scan value)', + ], + ['scans', 'Show scan history (--limit, up to 100)'], + [ + 'scan', + 'Run a full scan of the live deployment (asks first; it costs money; --client-assets)', + ], + [ + 'check []', + 'Scan the git-tracked code in this folder before you deploy (asks first; uploads it), or show an earlier check', + ], + ['model [ | --default]', 'Show or set the scan model'], + ['budget [--usd N | --off]', 'Show or set this project monthly scan budget'], + ['open', 'Open the read-only security page (link works for 15 minutes)'], + ]), + options: helpRows([ + ['--project ', 'Project name override'], + ['--json', 'Print machine-readable output'], + ['--urgent', 'list: only urgent findings'], + ['--state ', 'list: open, resolved or all (default: open)'], + ['--severity ', 'list: critical, high, medium, low or informational'], + ['--leads', 'list: include leads that need a human look'], + ['--format sarif', 'list: print a SARIF 2.1.0 file for code scanning tools'], + ['--reason ', 'resolve: fixed, false-positive or accepted-risk'], + ['--comment ', 'resolve, reopen, severity: why (up to 4,000 characters)'], + ['--limit ', 'scans: how many scans, 1 to 100'], + ['--default', 'model: use the platform default model'], + ['--accept-provider-notice', 'model: accept the third-party provider notice'], + ['--usd ', 'budget: monthly cap in dollars'], + ['--off', 'budget: clear this project own cap'], + ['--yes', 'scan, check: start without the prompt'], + ['--no-wait', 'check: queue it and return without waiting'], + ['--client-assets', 'scan: also review client bundle sources from their source maps'], + ]), + examples: helpRows([ + ['void project security list --urgent', 'Show findings to fix first'], + [ + 'void project security resolve F-12 --reason fixed --comment "Bound params in 4e1b9a3"', + 'Resolve a finding', + ], + ['void project security check', 'Check the code in this folder before you deploy it'], + ]), }, logs: { summary: 'Show runtime logs from the deployed project.', @@ -1490,11 +1590,18 @@ function basicSubcommand(summary: string, usage: string, example?: string): Help }; } -function withProjectOption(summary: string, usage: string): HelpPage { +function helpRows(rows: Array<[command: string, description: string]>): Array { + return rows.map(([command, description]) => ({ command, description })); +} + +function withProjectOption(summary: string, usage: string, json = false): HelpPage { return { summary, usage: [usage], - options: [{ command: '--project ', description: 'Project name override' }], + options: [ + { command: '--project ', description: 'Project name override' }, + ...(json ? [{ command: '--json', description: 'Print machine-readable output' }] : []), + ], }; } @@ -1505,7 +1612,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 +1635,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 dd0b0022b..deba4fcf3 100644 --- a/packages/void/src/cli/list.ts +++ b/packages/void/src/cli/list.ts @@ -2,6 +2,10 @@ import { outro, log } from '@voidzero-dev/vite-plus-prompts'; import { getToken } from './auth.ts'; import { PlatformClient } from './client.ts'; import type { DeploymentResponse } from './client.ts'; +import { + formatProjectStatusSecurityLine, + readSecurityStatusQuietly, +} from './deploy-security-notice.ts'; import { dim, formatCount, @@ -108,6 +112,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 6edf971cd..3658b64bb 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]; @@ -696,6 +737,7 @@ export function parseOperatorArgs(args: Array): OperatorArgs { ); } const paged = + command.paged === true || action === 'list' || action === 'events' || action === 'logs' || @@ -716,7 +758,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) ) { @@ -804,7 +846,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 2e16e0d62..2517e07f2 100644 --- a/packages/void/src/cli/operator-cmd.ts +++ b/packages/void/src/cli/operator-cmd.ts @@ -20,6 +20,7 @@ import { import { OperatorClient, OperatorClientError } from './operator-client.ts'; import { dim, printSuccess, sanitizeTerminalText } from './output.ts'; import { MINIMAL_RUNTIME_LOGS_NOTE } from './platform-runtime-logs.ts'; +import { OPEN_PUBLIC_REQUEST_STATES } from './security-api-types.ts'; const MAX_RUNTIME_FOLLOW_ROWS = 10_000; export const BUILD_LOG_DRAIN_TIMEOUT_MS: number = 2 * 60_000; @@ -163,17 +164,20 @@ 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.has(publicRequest.state)) || result.ok === false || result.partial === true || result.complete === false || @@ -681,14 +685,29 @@ export async function runOperatorCommand(args: OperatorArgs): Promise { return runAuth(origin, args); } const client = new OperatorClient(origin, readOperatorToken(origin)); + // Fail before contacting the server when unattended mutation authorization is missing. + // The security probe is a check, not a change, so it needs no confirmation. + if ( + args.method === 'POST' && + !(args.group === 'security' && 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', + ); + } + if (args.group === 'security') { + 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)) { - throw new OperatorClientError( - 'Mutations in non-interactive mode require --yes or --plan.', - 'confirmation_required', - ); - } if (args.group === 'deployment' && args.action === 'migrate-assets') { return migrateDeploymentAssets(client, origin, args); } 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..8d07843f0 --- /dev/null +++ b/packages/void/src/cli/operator-security-args.ts @@ -0,0 +1,626 @@ +import { parseSecurityDigits } from '@void/platform/security-policy'; +import { hasOwnKey } from '../shared/has-own-key.ts'; +import type { OperatorCommand } from './operator-args.ts'; +import { isDollarAmount } from './project-security-args.ts'; + +/** `void platform security …` (spec §13.4): feeds the generic operator parser and the help. */ +const commands: Array> = [ + { + action: 'status', + description: + 'Inspect capability, last probe, policy, queue depth, running scans and month totals', + path: '/security/status', + }, + { + action: 'probe', + description: 'Run the entitlement probe (checks Containers, Workers AI and model hosts)', + path: '/security/probe', + method: 'POST', + noConfirm: true, + }, + { + 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', + }, + { + 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', + }, + { + 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', + }, + { + 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', + }, + { + 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, + }, + { + 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]'], + }, + { + 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', + }, + { + 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', + }, + { + 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', + }, + { + 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', + }, + { + 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, + }, + { + 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', + }, + { + action: 'backfill', + description: + 'Scan every live deployment that was never scanned (asks first; it can cost real money)', + path: '/security/backfill', + method: 'POST', + }, + { + 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', + }, + { + 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', + }, + { + 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', + }, + { + 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', + }, + { + action: 'cancel', + description: 'Cancel a waiting or running scan', + path: '/security/scans/:sid/cancel', + positional: ['sid'], + method: 'POST', + }, + { + 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', + }, + { + 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, + }, + { + 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', + }, + { + action: 'bypasses', + description: 'List bypass records, newest first', + path: '/security/bypasses', + values: { project: 'Project id or slug' }, + paged: true, + }, +]; + +export const securityOperatorCommands: Array = commands.map((command) => ({ + group: 'security', + ...command, +})); + +const MODES = new Set(['disabled', 'public', 'all']); +/** One project's own scan rule (M34). */ +const OVERRIDES = new Set(['inherit', 'always', 'never']); +const SEVERITIES = ['critical', 'high', 'medium', 'low', 'informational']; +const REASONS = { + fixed: 'fixed', + 'false-positive': 'false_positive', + false_positive: 'false_positive', + 'accepted-risk': 'accepted_risk', + accepted_risk: 'accepted_risk', +}; +const MAX_FINDING_IDS = 20; +const ON_OFF_FIELDS = { fallback: 'fallbackToCf', digest: 'digest', 'public-gate': 'publicGate' }; + +/** An id for a URL path segment. */ +function pathId(id: string): string { + if (id === '.' || id === '..') { + throw new Error('platform: An object ID cannot be a dot path segment.'); + } + return encodeURIComponent(id); +} + +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 { + const number = parseSecurityDigits(value, 16); + if (number === null || value.startsWith('0') || !Number.isSafeInteger(number)) { + throw new Error(`platform: --${name} must be a whole number.`); + } + return number; +} + +function dollars(value: string, name: string): number { + if (!isDollarAmount(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`: the runner sends one + * request per `findingIds` entry. The runner strips the internal body keys. + */ +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) { + parsed.path = parsed.path.replace(':id', pathId(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.has(mode)) { + throw new Error( + 'platform: Usage: void platform security policy --project .', + ); + } + parsed.action = 'project-policy'; + parsed.path = `/projects/${pathId(project)}/security/policy`; + parsed.body = { override: mode }; + return; + } + if (OVERRIDES.has(mode)) { + throw new Error( + `platform: ${mode} is a project rule; name the project: void platform security policy --project ${mode}.`, + ); + } + if (!MODES.has(mode)) { + throw new Error('platform: Usage: void platform security policy .'); + } + parsed.body = { mode }; + return; + } + case 'sweeps': + case 'fallback': + case 'digest': + case 'public-gate': { + const state = parameters[0]; + if (state !== 'on' && state !== 'off') { + throw new Error( + `platform: Usage: void platform security ${action} ${action === 'sweeps' ? ' [--every-days ]' : ''}.`, + ); + } + const on = state === 'on'; + const days = values['every-days']; + parsed.body = + action === 'sweeps' + ? { + sweeps: { + on, + ...(days === undefined ? {} : { everyDays: wholeNumber(days, 'every-days') }), + }, + } + : { [ON_OFF_FIELDS[action]]: 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 '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 platformChange = + ['platform-usd', 'project-default-usd', 'project-caps'].some( + (name) => values[name] !== undefined, + ) || flags.has('platform-off'); + if (project !== undefined) { + if (platformChange) { + 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).', + ); + } + parsed.path = `/projects/${pathId(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; + } + // Some cap flag is set here: with none the command is a read (above). + parsed.body = body; + return; + } + case 'resolve': { + const reason = + values.reason !== undefined && hasOwnKey(REASONS, values.reason) + ? REASONS[values.reason] + : undefined; + 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..8b6dc7d85 --- /dev/null +++ b/packages/void/src/cli/operator-security.ts @@ -0,0 +1,488 @@ +import type { OperatorArgs } from './operator-args.ts'; +import { OperatorClientError } from './operator-client.ts'; +import type { OperatorClient } from './operator-client.ts'; +import { dim, printSuccess } from './output.ts'; +import { sarifToolVersion, securityFindingsSarif } from './security-sarif.ts'; +import type { SarifFinding } from './security-sarif.ts'; + +interface Result { + [key: string]: unknown; +} + +/** 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') : []; +} + +async function previewOf( + client: OperatorClient, + args: OperatorArgs, + path: string, + body: Result, +): Promise { + const preview = await post(client, args, { ...body, dryRun: true }, path); + 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', + ); + } + return preview; +} + +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`, + ); + } +} + +function post( + client: OperatorClient, + args: OperatorArgs, + body: Result, + path = args.path, +): Promise { + return client.request(path, { method: 'POST', body, timeoutMs: args.timeoutMs }); +} + +/** Preview (unless given), confirm, then send the same body; `null` when not confirmed. */ +async function apply( + client: OperatorClient, + origin: string, + args: OperatorArgs, + io: SecurityIo, + body: Result, + preview?: Result, +): Promise { + const shownPreview = preview ?? (await previewOf(client, args, args.path, body)); + return (await io.confirm(origin, shownPreview, args)) ? post(client, args, body) : null; +} + +/** 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); + // The policy preview carries the whole policy; the change lines are what a person reads. + const { policy: _policy, ...shown } = preview; + if (!(await io.confirm(origin, shown, 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', + ); + } + io.outputMutation(await post(client, args, { ...body, expectedRevision: revision }), args); +} + +/** `--accept-provider-notice` becomes the notice version the platform asks for now. */ +async function withNoticeVersion(client: OperatorClient, args: OperatorArgs): Promise { + const { acceptProviderNotice, ...body } = args.body; + if (acceptProviderNotice !== true) { + return body; + } + 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 { ...body, acceptProviderNoticeVersion: 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 post(client, args, item.body, item.path)); + } 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 result = await apply(client, origin, args, io, body); + if (!result) { + return; + } + 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 id = + typeof preview.deploymentId === 'string' ? preview.deploymentId : String(preview.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`, + ); + } + const result = await apply(client, origin, args, io, args.body, preview); + if (!result) { + return; + } + io.output(result, args.json); + if (args.json) { + return; + } + // The scan is only queued here: it waits its turn like any scan. + const scanId = typeof result.scanId === 'string' ? ` (${result.scanId})` : ''; + // The path is `/projects//security/scans`. + const project = + typeof result.project === 'string' + ? result.project + : decodeURIComponent(args.path.split('/')[2] ?? ''); + printSuccess( + `Rescan queued${scanId}. Check it: void platform security scans --project ${project}`, + ); +} + +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 null; + } + return apply(client, origin, args, io, args.body, preview); +} + +/** Longest provider key read from stdin; the server takes at most 1,024 characters. */ +const MAX_PROVIDER_KEY_INPUT = 8192; + +/** Reads one provider API key piped on stdin. The key is never printed. */ +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 || Array.from(key).some((char) => char <= ' ')) { + throw new OperatorClientError( + 'Standard input must hold one API key on one line.', + 'invalid_key_input', + ); + } + return key; +} + +/** The body of a change with no revision. A piped provider key is read before any request. */ +async function plainBody(client: OperatorClient, args: OperatorArgs): Promise { + const { keyStdin, ...fields } = args.body; + return keyStdin === true + ? { ...fields, key: await readProviderKeyStdin() } + : withNoticeVersion(client, args); +} + +const WEBHOOK_SECRET_NOTE = + 'Save the signing secret above now; it is not shown again. Check each request: X-Void-Signature is t=,v1=.">.'; + +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 post(client, args, {}), 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 'models': + return changeWithRevision(client, origin, args, io, await withNoticeVersion(client, args)); + case 'budget-set': + return runBudget(client, origin, args, io); + case 'resolve': + case 'reopen': + case 'comment': + return runFindings(client, origin, args, io); + case 'rescan': + return runRescan(client, origin, args, io); + default: { + // model, webhook, provider-key, backfill, cancel, bypass: a preview, then the same body. + const result = + args.action === 'backfill' + ? await runBackfill(client, origin, args, io) + : await apply(client, origin, args, io, await plainBody(client, args)); + if (!result) { + return; + } + io.outputMutation(result, args); + const note = + args.action === 'webhook' && typeof result.secret === 'string' + ? WEBHOOK_SECRET_NOTE + : args.action === 'provider-key' && typeof result.message === 'string' + ? result.message + : null; + if (!args.json && note) { + process.stderr.write(`${dim(note)}\n`); + } + } + } +} + +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/output.ts b/packages/void/src/cli/output.ts index 40f35b4ca..d8cc5c81b 100644 --- a/packages/void/src/cli/output.ts +++ b/packages/void/src/cli/output.ts @@ -210,6 +210,20 @@ export function sanitizeTerminalText(value: string): string { return value.replaceAll(/[\u0000-\u001f\u007f-\u009f]/g, ' '); } +/** Text from a model or a user: no escape sequences, one line. */ +export function cleanLine(value: unknown): string { + return sanitizeTerminalText(stripVTControlCharacters(String(value ?? ''))); +} + +/** 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 stripVTControlCharacters(text ?? '') + .split('\n') + .map(sanitizeTerminalText) + .join('\n'); +} + export function helpLine(command: string, description: string): string { return `${pc.reset(command.padEnd(34))} ${pc.dim(description)}`; } diff --git a/packages/void/src/cli/platform-args.ts b/packages/void/src/cli/platform-args.ts index 6df1640fb..f02cb2990 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( 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') { @@ -205,6 +208,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); @@ -236,6 +244,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 } : {}), }; @@ -357,6 +366,7 @@ export function parsePlatformArgs(args: Array): PlatformArgs { authConfig, dashboardUrl, customDomains, + securityAudits, runtimeLogs, storageLocation, } = parseLifecycleSelector(rest, subcommand); @@ -371,6 +381,7 @@ export function parsePlatformArgs(args: Array): PlatformArgs { ...(authConfig !== undefined ? { authConfig } : {}), ...(dashboardUrl !== undefined ? { dashboardUrl } : {}), ...(customDomains ? { customDomains } : {}), + ...(securityAudits ? { securityAudits } : {}), ...(runtimeLogs !== undefined ? { runtimeLogs } : {}), ...(storageLocation !== undefined ? { storageLocation } : {}), }; @@ -418,6 +429,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)) { @@ -446,6 +458,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}'.`); } @@ -508,6 +522,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 } : {}), ...(hyperdrive !== undefined ? { 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 0e1fbfeb1..8adc61d3d 100644 --- a/packages/void/src/cli/platform-installer.ts +++ b/packages/void/src/cli/platform-installer.ts @@ -85,6 +85,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'; @@ -239,6 +240,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 ( @@ -605,6 +607,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 dd6f8dae9..4a238a07b 100644 --- a/packages/void/src/cli/platform-lifecycle.ts +++ b/packages/void/src/cli/platform-lifecycle.ts @@ -90,6 +90,7 @@ import { savePlatformInstallChoices, removeSavedPlatformInstallPlan, } from './platform-saved-plans.ts'; +import { assertPlatformSecurityAuditsSupported } from './platform-security-audits.ts'; import { completePlatformSetupDraft, isPlatformSetupDraft, @@ -261,6 +262,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( @@ -798,6 +800,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 } : {}), @@ -824,6 +827,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(), @@ -835,6 +839,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 3cf59d7af..f95e0aa7e 100644 --- a/packages/void/src/cli/platform-management.ts +++ b/packages/void/src/cli/platform-management.ts @@ -94,6 +94,11 @@ import { shouldUpdateProjectWorkerRuntimeLogs, updateProjectWorkerRuntimeLogs, } from './platform-runtime-logs.ts'; +import { + assertPlatformSecurityAuditsSupported, + deletePlatformSecurityScanner, +} from './platform-security-audits.ts'; +import type { SecurityScannerTeardown } from './platform-security-audits.ts'; import { assertPlatformStorageSupported } from './platform-storage.ts'; import { assertNoPlatformProjects, @@ -222,6 +227,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( @@ -267,6 +276,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); } @@ -391,6 +403,7 @@ export async function runInstalledPlatformCommand( ? databaseLock.readProjects : () => readPlatformProjectSlugs(databaseUrl, manifest.id, manifest.ownershipNonce), credential: { source: operatorCredential.source, aiGatewayToken: !!gatewayToken }, + deleteSecurityScanner: (current) => deletePlatformSecurityScanner(client, current), ...(apiUrl && appAccessSetupToken ? { turnOffProjectZeroTrust: async () => { @@ -474,6 +487,7 @@ export async function runInstalledPlatformCommand( ? { dashboardUrl: args.dashboardUrl } : {}), ...(args.subcommand !== 'rollback' && args.customDomains ? { customDomains: true } : {}), + ...(args.subcommand !== 'rollback' && args.securityAudits ? { securityAudits: true } : {}), ...(args.subcommand === 'upgrade' && args.storageLocation !== undefined ? { storageLocation: args.storageLocation } : {}), @@ -498,6 +512,7 @@ export async function runInstalledPlatformCommand( }), ); assertPlatformRuntimeLogsSupported(plan.deployment, runtime.manifest); + assertPlatformSecurityAuditsSupported(plan.deployment, runtime.manifest); assertPlatformStorageSupported(plan.deployment, runtime.manifest); markPhase('plan'); note( @@ -1052,6 +1067,17 @@ export function assertPlatformRollbackCompatibility( 'platform: The rollback target predates the installed sandbox-drain safety protocol.', ); } + // The API Worker keeps the SecurityScanScheduler Durable Object once its + // migration ran. Cloudflare refuses an upload that no longer exports the + // class, so a rollback across that release would stop half way. + if ( + target.manifest.securityAudits !== 1 && + (source.manifest.securityAudits === 1 || installation.deployment.capabilities.securityAudits) + ) { + throw new Error( + 'platform: The rollback target predates security audits and cannot replace this installation. Roll forward to a runtime with security audits instead.', + ); + } } export function resolvePlatformRuntimeTokenToPreflight( @@ -1248,6 +1274,12 @@ export async function uninstallPlatform( writeRemoteManifest(client, state, dependencies.checkpoint); const retainData = !args.purgeData; const purgeResources = args.purgeResources; + const securityAudits = manifest.deployment.capabilities.securityAudits === true; + if (securityAudits && !dependencies.deleteSecurityScanner) { + throw new Error( + 'platform: Refusing to uninstall because the security scanner cannot be removed from here.', + ); + } const routingKv = manifest.resources.find((resource) => resource.key === 'routing-kv'); // --purge-resources also uses routing KV that an uninstall which stopped before it // finished recorded as retained. @@ -1279,6 +1311,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) : [ @@ -1502,6 +1539,14 @@ export async function uninstallPlatform( } } } + if (securityAudits && dependencies.deleteSecurityScanner) { + // 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) { const { readProjects } = dependencies; if (!readProjects) { diff --git a/packages/void/src/cli/platform-plan.ts b/packages/void/src/cli/platform-plan.ts index 02d68b69e..674fd2dbf 100644 --- a/packages/void/src/cli/platform-plan.ts +++ b/packages/void/src/cli/platform-plan.ts @@ -81,6 +81,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; @@ -247,6 +249,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)) { @@ -355,6 +358,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 = ( @@ -375,7 +390,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 06bd4836b..8c712cca6 100644 --- a/packages/void/src/cli/platform-plans-config.ts +++ b/packages/void/src/cli/platform-plans-config.ts @@ -11,6 +11,14 @@ import { parsePlatformPlanId, } from '@void/platform/plans'; import type { PlatformPlanCatalog, PlatformPlanDefinition } from '@void/platform/plans'; +import { + formatPlanSecurityCap, + parsePlanSecurityCapInput, + planSecurityCap, + readPlanSecurityCaps, + readStoredPlanSecurityCap, +} from '@void/platform/security-policy'; +import type { PlanSecurityCaps, SecurityPlanCap } from '@void/platform/security-policy'; import { confirm, isCancel, select, text } from '@voidzero-dev/vite-plus-prompts'; import type { CANCEL_SYMBOL } from '@voidzero-dev/vite-plus-prompts'; import { utcTime } from './operator-ai-logging.ts'; @@ -32,8 +40,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); +} + +const PLAN_FILE_FIELDS = [ + 'name', + 'limits', + 'buildInstanceType', + 'allowShortSlugs', + 'aiLogging', + 'securityCap', +]; + const aiLoggingLabels: Record = { inherit: 'inherit (AI Gateway setting)', off: 'off', @@ -89,10 +113,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}`); } @@ -147,6 +177,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; @@ -173,6 +209,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) { @@ -181,7 +220,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)) { @@ -189,7 +234,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), + ); } } } @@ -243,6 +294,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)) { @@ -250,14 +302,15 @@ async function changesInput( } const object = input as Record; for (const key of Object.keys(object)) { - if (!['name', 'limits', 'buildInstanceType', 'allowShortSlugs', 'aiLogging'].includes(key)) { + if (!PLAN_FILE_FIELDS.includes(key)) { throw new Error( - `platform: Unknown plan field ${key}. Use name, limits, buildInstanceType, allowShortSlugs, or aiLogging.`, + `platform: Unknown plan field ${key}. Use ${PLAN_FILE_FIELDS.slice(0, -1).join(', ')}, or securityCap.`, ); } } try { parsePlanAiLoggingInput(object.aiLogging); + parsePlanSecurityCapInput(object.securityCap); } catch (error) { throw new Error(`platform: ${(error as Error).message}`, { cause: error }); } @@ -272,10 +325,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') { @@ -288,12 +345,14 @@ async function changesInput( if (args.action === 'add') { return { name: parsePlanName(value(await text({ message: 'Plan name:', initialValue: args.target }))), + ...cap, }; } if (!plan) { throw new Error('platform: No plan selected.'); } const aiLogging = listing?.aiLogging; + const securityCaps = listing?.securityCaps; const field = value( await select({ message: 'What would you like to change?', @@ -312,9 +371,23 @@ async function changesInput( }, ] : []), + ...(securityCaps + ? [ + { + value: 'securityCap', + label: `Security scan cap: ${formatPlanSecurityCap(securityCapOf(securityCaps, plan.id))}`, + }, + ] + : []), ], }), ); + if (field === 'securityCap') { + if (!securityCaps) { + throw new Error('platform: Security scan caps are unavailable.'); + } + return { securityCap: await chooseSecurityCap(securityCapOf(securityCaps, plan.id)) }; + } if (field === 'aiLogging') { if (!aiLogging) { throw new Error('platform: AI Gateway logging is unavailable.'); @@ -362,6 +435,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, @@ -371,6 +477,12 @@ async function apply( ): Promise { const { catalog } = listing; assertPlanAiLoggingSupported(listing, body); + // A platform whose API would refuse or drop a plan scan cap. + 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`.', + ); + } if (!args.plan && !args.yes && (!process.stdin.isTTY || args.json)) { throw new Error( 'platform: Configuration changes require --yes or --plan in non-interactive mode.', @@ -599,6 +711,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 interface SecurityScannerNames { + worker: string; + application: string; + gate: string; + engines: { 'engine-a': SecurityScannerEngineNames; 'engine-c': SecurityScannerEngineNames }; +} + +export function securityScannerNames(installationId: string): SecurityScannerNames { + 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; +} + +/** `undefined` when Cloudflare answers 404, or 403 too when `forbiddenOk`. */ +async function optional(read: () => Promise, forbiddenOk = false): Promise { + try { + return await read(); + } catch (error) { + if ( + error instanceof PlatformCloudflareApiError && + (error.status === 404 || (forbiddenOk && error.status === 403)) + ) { + 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 optional(read, true); + 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 = {}) => { + const headers = new Headers(init.headers); + if (!headers.has('Authorization')) { + headers.set('Authorization', auth); + } + if (!headers.has('Accept')) { + headers.set('Accept', MANIFEST_ACCEPT); + } + return registryFetch(url, { ...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<{ 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 container applications, the + * controller Worker and the engine images. Each must carry this installation's ownership + * marker; one that is not ours is left alone and reported. + */ +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 optional(listApplications, true)) ?? []); + 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 55a8634c5..b0f1980fa 100644 --- a/packages/void/src/cli/platform-setup.ts +++ b/packages/void/src/cli/platform-setup.ts @@ -114,6 +114,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' }, @@ -173,7 +180,8 @@ export function platformSetupPages(plan: PlatformInstallPlan): PlatformSetupPage ...(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' }, @@ -308,6 +316,7 @@ export type PlatformInstallCommandOptions = { controlPlaneDomain: string; dashboardUrl?: string; customDomains?: boolean; + securityAudits?: boolean; dedicatedZone: boolean; workersDev: boolean; authConfig?: string; @@ -368,6 +377,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 bd5cabee9..488db82c6 100644 --- a/packages/void/src/cli/project-args.ts +++ b/packages/void/src/cli/project-args.ts @@ -1,3 +1,5 @@ +import { parseSecurityArgs } from './project-security-args.ts'; +import 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 +27,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 +58,94 @@ 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 = new Set(['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.has(action)) { + throw new Error( + 'project: Usage: void project zero-trust [--project ] [--json].', + ); + } + let projectSlug = ''; + let reason: string | undefined; + const flags = new Set(); + for (let index = 0; index < args.length; index++) { + const arg = args[index]; + if ((arg === '--reason' || arg === '--yes') && action !== 'bypass') { + throw new Error(`project: ${arg} is not used with zero-trust ${action || ''}.`); + } + 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 === '--reason') { + if (reason !== undefined) { + throw new Error("project: Duplicate flag '--reason'."); + } + // A reason is free text and may start with a dash. + reason = args[++index]; + if (reason === undefined) { + throw new Error('project: --reason requires a value.'); + } + } else if (arg === '--json' || arg === '--yes') { + if (flags.has(arg)) { + throw new Error(`project: Duplicate flag '${arg}'.`); + } + flags.add(arg); + } else { + throw new Error(`project: Unexpected argument '${arg}'.`); + } + } + const json = flags.has('--json'); + 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 (Array.from(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: flags.has('--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..54bae83bb --- /dev/null +++ b/packages/void/src/cli/project-security-args.ts @@ -0,0 +1,366 @@ +/** Arguments of `void project security …` (spec §13.3). */ +import { parseSecurityDigits } from '@void/platform/security-policy'; +import { hasOwnKey } from '../shared/has-own-key.ts'; + +export const SECURITY_COMMENT_MAX_CHARS = 4000; +const SEVERITIES = ['critical', 'high', 'medium', 'low', 'informational']; +const STATES = new Set(['open', 'resolved', 'all']); +const REASONS = { + fixed: 'fixed', + 'false-positive': 'false_positive', + 'accepted-risk': 'accepted_risk', +} satisfies Record; +// 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'.split(' '), +); +const BOOLEAN_FLAGS = new Set( + '--json --urgent --leads --default --accept-provider-notice --off --yes --client-assets --no-wait'.split( + ' ', + ), +); +// Each action and the flags it accepts besides `--project` and `--json`, in usage order. +const ACTION_FLAGS = { + status: [], + 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'], + open: [], +}; + +/** `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); + } + } + return parseSecurityDigits(digits, 9) === null || digits.startsWith('0') ? null : `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; +} + +/** The first finding id in one positional. */ +function firstFindingId(value: string): string { + const id = parseFindingIds([value])[0]; + if (!id) { + throw new Error(`project: '${value}' is not a finding id. Use a form like F-12.`); + } + return id; +} + +/** `40` or `12.50`: digits, then at most two decimals. */ +export function isDollarAmount(value: string): boolean { + const [whole = '', cents, ...extra] = value.split('.'); + return ( + extra.length === 0 && + parseSecurityDigits(whole, value.length) !== null && + (cents === undefined || parseSecurityDigits(cents, 2) !== null) + ); +} + +function parseUsd(value: string): number { + if (!isDollarAmount(value)) { + 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 (Array.from(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 !== '' && !hasOwnKey(ACTION_FLAGS, action)) { + throw new Error( + `project: Usage: void project security <${Object.keys(ACTION_FLAGS).join('|')}> [--project ] [--json].`, + ); + } + const values = new Map(); + const flags = new Set(); + const positionals: Array = []; + const allowed = new Set([ + '--project', + '--json', + ...(action === '' ? [] : 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 === '' || action === 'status' || action === 'open') { + noPositionals(); + return { ...base, json, action }; + } + if (action === 'list') { + noPositionals(); + const state = values.get('--state') ?? 'open'; + if (!STATES.has(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 = firstFindingId(positionals[0]); + 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 = firstFindingId(positionals[0]); + 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 && hasOwnKey(REASONS, reasonText) ? REASONS[reasonText] : undefined; + 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 = firstFindingId(positionals[0]); + 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..2896f5003 --- /dev/null +++ b/packages/void/src/cli/project-security-check.ts @@ -0,0 +1,396 @@ +/** + * `void project security check` (design doc 0095 M32): only git-tracked files that pass + * the platform's input filter leave the machine (tar + gzip, one presigned upload). + */ +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, +} from '@void/platform/security-local-check'; +import type { SecurityLocalTreeFile } from '@void/platform/security-local-check'; +import { join } from 'pathslash'; +import { hasOwnKey } from '../shared/has-own-key.ts'; +import type { PlatformClient } from './client.ts'; +import { DirectR2PutError, uploadAssetsToR2 } from './direct-r2-upload.ts'; +import { cleanLine } from './output.ts'; +import type { 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 = 5000; +export const SECURITY_CHECK_WAIT_MS: number = 60 * 60_000; +const ENDED_WITH_RESULT = new Set(['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: 'utf8', + 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): 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(cleanLine).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 = { + critical: 'CRITICAL', + high: 'HIGH', + medium: 'MEDIUM', + low: 'LOW', + informational: 'INFO', +}; + +/** + * 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, + options: { fresh?: boolean } = {}, +): Array { + const { check, result } = view; + const head = [ + `${slug} · local check ${cleanLine(check.id)}`, + ` ${cleanLine(check.status)}${check.statusReason ? ` (${cleanLine(check.statusReason)})` : ''}${check.coverageLabel ? ` · ${cleanLine(check.coverageLabel)}` : ''} · ${plural(check.filesScanned, 'file')}${check.model ? ` · ${cleanLine(check.model)}` : ''}`, + ]; + if (!ENDED_WITH_RESULT.has(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, ...leads]) { + const severity = finding.severity; + const label = + finding.verdict !== 'confirmed' + ? 'LEAD' + : severity !== null && hasOwnKey(SEVERITY_LABEL, severity) + ? SEVERITY_LABEL[severity] + : 'INFO'; + const place = `${cleanLine(finding.file)}${finding.lineStart === null ? '' : `:${finding.lineStart}`}`; + lines.push(` ${label.padEnd(9)} ${cleanLine(finding.title)}`, ` ${' '.repeat(9)} ${place}`); + } + 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, + options: { fresh?: boolean } = {}, +): string { + const { check } = view; + const reason = cleanLine(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 ${cleanLine(check.model ?? 'the scan model')} (category: ${cleanLine(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.has(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..1bd8268d1 --- /dev/null +++ b/packages/void/src/cli/project-security.ts @@ -0,0 +1,1213 @@ +import { securityPickProblemNote } from '@void/platform/security-models'; +import { securityTraceLines } from '@void/platform/security-policy'; +import { confirm, isCancel } from '@voidzero-dev/vite-plus-prompts'; +import { isCI } from 'ci-info'; +import { hasOwnKey } from '../shared/has-own-key.ts'; +import { getToken, openBrowser } from './auth.ts'; +import { PlatformApiError, PlatformClient } from './client.ts'; +import { cleanBlock, cleanLine } from './output.ts'; +import type { ProjectSecurityArgs } from './project-security-args.ts'; +import { + checkEndedWithResult, + checkFailureMessage, + checkResultLines, + checkSummaryLines, + collectSecurityLocalTree, + packSecurityLocalTree, + sendSecurityLocalCheck, + waitForSecurityLocalCheck, +} from './project-security-check.ts'; +import type { SecurityCheckDeps } from './project-security-check.ts'; +import { readProjectConfig } from './project.ts'; +import { getRequestedProjectSlug, requireProjectBySlug } from './resolve-project.ts'; +import type { + ProjectSecurityStatus, + SecurityBudgetCause, + SecurityFinding, + SecurityFindingEvent, + SecurityPublicRequest, + SecurityRescanPreview, + SecurityScanSummary, +} from './security-api-types.ts'; +import { sarifToolVersion, securityFindingsSarif } from './security-sarif.ts'; + +type Args = ProjectSecurityArgs; + +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`; +} + +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`; +} + +type Budget = NonNullable; + +const BUDGET_CAUSES: ReadonlyArray = [ + 'project_cap', + 'platform_cap', + 'project_reserve', + 'platform_reserve', +]; + +/** + * Which cap skipped a scan. Older platforms send no cause: a project cap whose spend + * reached it is the project's, anything else the platform's. + */ +export function budgetCause( + scan: Pick | null | undefined, + budget: Budget | null | undefined, +): SecurityBudgetCause { + const sent = BUDGET_CAUSES.find((cause) => cause === scan?.budgetCause); + if (sent) { + return sent; + } + return budget && budget.capUsd !== null && budget.spentUsd >= budget.capUsd + ? 'project_cap' + : 'platform_cap'; +} + +/** What a used-up project cap will refuse at the next scan start, if anything (spec §6.5). */ +export function budgetAhead(budget: Budget | null | undefined): SecurityBudgetCause | null { + if (!budget || budget.capUsd === null) { + return null; + } + if (budget.spentUsd >= budget.capUsd) { + return 'project_cap'; + } + const reserve = budget.scanReserveUsd; + return typeof reserve === 'number' && budget.spentUsd + reserve > budget.capUsd + ? 'project_reserve' + : null; +} + +/** A CLI `--usd` value: `150`, or `150.50` with cents. */ +function usdArgument(value: number): string { + return Number.isInteger(value) ? String(value) : value.toFixed(2); +} + +/** The one §16.3 raise line that works now for this project's cap. */ +function projectRaiseLine(budget: Budget, projectId: string | undefined): string { + const cap = budget.capUsd ?? 0; + const ceiling = budget.ceilingUsd; + if (budget.capSource === 'own' && (ceiling === null || cap < ceiling)) { + return ceiling === null + ? 'A project admin can raise it: void project security budget --usd ' + : `A project admin can raise it (up to ${usd(ceiling)}): void project security budget --usd ${usdArgument(ceiling)}`; + } + // The operator route takes the project id, not the slug. + const id = projectId ? cleanLine(projectId) : ''; + return `Your platform admin can raise it: void platform security budget --project ${id} --usd ${usdArgument(Math.max(1, Math.ceil(cap * 1.5)))}`; +} + +/** The parts of the §11.4 / §16.3 copy for a scan the budget skipped. */ +export type BudgetSkipCopy = { + /** What happened, with no end stop: `this project's monthly scan budget is used up ($40.00 of $40.00)`. */ + why: string; + /** `Resets Dec 1.` while the cap is still used up. */ + resets: string | null; + /** The one way on that works now; `null` for the platform cap and for readers. */ + next: string | null; + /** The cap was raised or removed since, so the next scan can run. */ + raised: boolean; +}; + +export function budgetSkipCopy( + cause: SecurityBudgetCause, + budget: Budget | null | undefined, + model: string | null | undefined, + projectId?: string, +): BudgetSkipCopy { + const none = { resets: null, next: null, raised: false }; + if (!budget) { + // Readers see no amounts (spec §16.3). + return { ...none, why: 'the monthly scan budget is used up' }; + } + const resets = `Resets ${day(budget.resetsAt)}.`; + const reserve = typeof budget.scanReserveUsd === 'number' ? budget.scanReserveUsd : null; + // `one scan with can cost up to $2.04, more than is left of …` + const oneScan = `one scan with ${cleanLine(model ?? 'this model')} can cost${reserve === null ? '' : ` up to ${usd(reserve)},`}`; + const cheaper = 'pick a cheaper model: void project security model'; + if (cause === 'platform_cap') { + return { ...none, why: "the platform's monthly scan budget is used up", resets }; + } + if (cause === 'platform_reserve') { + return { + ...none, + why: `${oneScan} more than is left of the platform's monthly scan budget`, + next: `Ask your platform admin, or ${cheaper}`, + }; + } + const cap = budget.capUsd; + const usedUp = cause === 'project_cap' ? 'was used up' : 'had too little left for one scan'; + if (cap === null) { + return { + ...none, + why: `this project's monthly scan budget ${usedUp}; the cap was removed since`, + raised: true, + }; + } + const left = cap - budget.spentUsd; + const fits = cause === 'project_cap' ? left > 0 : reserve !== null && reserve <= left; + if (fits) { + return { + ...none, + why: `this project's monthly scan budget ${usedUp}; it was raised since (${usd(budget.spentUsd)} of ${usd(cap)} used)`, + raised: true, + }; + } + if (cause === 'project_reserve') { + return { + ...none, + why: `${oneScan} more than is left of this project's monthly scan budget (${usd(Math.max(0, left))} of ${usd(cap)})`, + next: `${projectRaiseLine(budget, projectId)}. Or ${cheaper}`, + }; + } + return { + ...none, + why: `this project's monthly scan budget is used up (${usd(budget.spentUsd)} of ${usd(cap)})`, + resets, + next: projectRaiseLine(budget, projectId), + }; +} + +/** `2 critical, 1 high`. */ +export function urgentCounts(urgent: ProjectSecurityStatus['urgent']): string { + const { critical, high } = urgent.counts; + return [critical ? `${critical} critical` : '', high ? `${high} high` : ''] + .filter(Boolean) + .join(', '); +} + +const row = (label: string, text: string) => ` ${label.padEnd(10)} ${text}`; +const cont = (text: string) => ` ${' '.repeat(10)} ${text}`; + +const MODEL_SOURCES = { + project: "your project's pick", + default: 'platform default', + fallback: 'fallback: the model you asked for cannot run now', +}; + +/** Where the model in use comes from; names the pick and why it does not run (spec §8.2). */ +function modelSource(model: ProjectSecurityStatus['model']): string { + if (model.pickProblem) { + return cleanLine(securityPickProblemNote(model.requested, model.pickProblem)); + } + // A source a newer platform added reads like none. + return model.source !== null && hasOwnKey(MODEL_SOURCES, model.source) + ? MODEL_SOURCES[model.source] + : 'no model can run now'; +} + +/** Spec §11.4 status copy for the last scan; `null` when the scan needs no explanation. */ +export function scanStatusCopy(status: ProjectSecurityStatus, projectId?: string): 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') { + const cause = budgetCause(lastScan, budget); + const copy = budgetSkipCopy(cause, budget, status.model?.id, projectId); + if (copy.raised) { + return `Not scanned: ${copy.why}. The next deploy is scanned.`; + } + const next = + cause === 'platform_cap' && budget ? 'Your platform admin can raise it.' : copy.next; + return [`Not scanned: ${copy.why}.`, copy.resets, next ? withStop(next) : null] + .filter(Boolean) + .join(' '); + } + 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; + } +} + +const HELD_CAUSES = { + refused: 'refused', + timed_out: 'timed out', + findings_capped: 'it hit the findings limit, so more findings may be hidden', + failed_project: 'the scan of this project failed', +}; + +function withStop(text: string): string { + return text.endsWith('.') ? text : `${text}.`; +} + +/** + * What the public request copy reads besides the request: the backlog, the budget, and + * (when known) the gate scan, the model and the project id for the raise line. + */ +export type RequestSecurity = Pick & + Partial> & { projectId?: string }; + +/** Spec §11.4 public request copy, with the command that moves it on. */ +export function publicRequestLines( + slug: string, + request: SecurityPublicRequest, + status: RequestSecurity, +): 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': + // Same rule as the platform copy: say what the request waits for. + lines.push( + reason === 'deployment_moving' + ? `Waiting for the new deployment to go live before ${slug} goes public. It stays protected by Zero Trust until the scan of that deployment passes.` + : reason === 'zero_trust_not_ready' + ? `Waiting for the Zero Trust protection of ${slug} to be ready before it goes public. It stays protected until then.` + : 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 === 'unread_files') { + // Asking again scans the same code: it does not help. + lines.push( + `Stays protected: the security scan could not read some project files (too large, not text, or a path the scanner cannot send). Fix them and deploy again, or bypass the scan: ${bypass}`, + ); + } else 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 gate = + status.lastScan && status.lastScan.id === request.gateScanId ? status.lastScan : null; + const cause = budgetCause(gate, status.budget); + const copy = budgetSkipCopy(cause, status.budget, status.model?.id, status.projectId); + const resets = copy.resets ? ` ${copy.resets}` : ''; + if (copy.raised) { + lines.push( + `Stays protected: ${copy.why}, so the scan could not run. Ask again with void project zero-trust public, or bypass the scan: ${bypass}`, + ); + } else if (copy.next === null) { + lines.push( + `Stays protected: ${copy.why}, so the scan could not run.${resets} Ask your platform admin, or bypass the scan: ${bypass}`, + ); + } else { + lines.push( + `Stays protected: ${copy.why}, so the scan could not run.${resets} ${withStop(copy.next)}`, + `Or bypass the scan: ${bypass}`, + ); + } + } else { + const cause = + reason !== null && hasOwnKey(HELD_CAUSES, reason) + ? HELD_CAUSES[reason] + : 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, + projectId?: string, +): 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 { + lines.push( + row( + 'Urgent', + `${urgent.count} open (${urgentCounts(urgent)}) · 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}`)); + } + lines.push(row('Model', `${cleanLine(model.id ?? 'none')} (${modelSource(model)})`)); + 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) { + // The "first scan runs after your next deploy" promise holds only when the policy applies. + lines.push( + row( + 'Last scan', + policy.applies && policy.mode !== 'disabled' + ? 'none yet. The first scan runs after your next deploy and reviews the whole app.' + : 'none', + ), + ); + } 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, projectId); + 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, + projectId, + }); + 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', securityTraceLines(finding.trace)?.map(cleanLine).join('\n') ?? 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; + // Spec #24: a removed commenter keeps the comment, shown as a former member. + const role = event.formerMember + ? 'former member' + : event.actorRole + ? cleanLine(event.actorRole) + : null; + 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)}${role ? ` (${role})` : ''}`, + ); + 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(), + ); +} + +export async function resolveTarget( + root: string, + args: { projectSlug: string }, +): Promise<{ client: PlatformClient; projectId: string; slug: string }> { + 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, projectId)); + 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; + } + + const revision = async (id: string) => + (await client.getProjectSecurityFinding(projectId, id)).finding.revision; + + if (args.action === 'reopen') { + const result = await client.reopenProjectSecurityFinding(projectId, args.id, { + comment: args.comment, + expectedRevision: await revision(args.id), + }); + print(args, result, [`✓ ${cleanLine(result.id)} reopened.`]); + return; + } + + if (args.action === 'severity') { + const result = await client.editProjectSecurityFindingSeverity(projectId, args.id, { + severity: args.severity, + comment: args.comment, + expectedRevision: await revision(args.id), + }); + const id = cleanLine(result.id); + const level = cleanLine(result.severity ?? '-'); + const lines = [severityChangeLine(id, level, result)]; + if (result.publicRequest) { + const status = await statusAfterChange(client, projectId); + const [first = '', ...rest] = publicRequestLines(slug, result.publicRequest, { + ...(status ?? { backlogFiles: 0, budget: null }), + projectId, + }); + 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 result = await client.resolveProjectSecurityFinding(projectId, id, { + reason: args.reason, + comment: args.comment, + expectedRevision: await revision(id), + }); + 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) { + const status = await statusAfterChange(client, projectId); + 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) { + if (args.json || !isInteractive(deps)) { + throw new Error('project: Add --yes to start the scan without a prompt.'); + } + const [question, ...rest] = rescanConfirmLines(preview); + console.log(['', ...rest].join('\n')); + if (!(await askYesNo(deps, 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')} (${modelSource(model)})`), + row('Asked for', cleanLine(model.requested)), + // The provider notice is only about third-party models. + model.thirdParty || model.pendingDefault || model.pickProblem === 'notice' + ? row( + 'Notice', + model.noticeAccepted ? 'provider notice accepted' : 'provider notice not accepted', + ) + : null, + 'Change: void project security model or void project security model --default', + ].filter((line) => line !== null); + print(args, { model }, lines); + return; + } + const target = args.change === 'default' ? null : args.model; + const lines: Array = []; + // A version the platform does not know (0) is refused with the current version and notice. + const set = (version?: number) => + client.setProjectSecurityModel(projectId, { + model: target, + ...(version === undefined ? {} : { acceptProviderNoticeVersion: version }), + }); + let result; + try { + result = await set(args.acceptNotice ? 0 : undefined); + } catch (error) { + const notice = noticeOf(error); + if (!notice) { + throw error; + } + const text = notice.notice.map(cleanLine); + if (!args.acceptNotice) { + if (!args.json) { + console.log(['', ...text, ''].join('\n')); + } + throw error; + } + lines.push(...text, ''); + result = await set(notice.version); + } + 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( + result.model.pickProblem + ? ` The next scan runs on ${cleanLine(result.model.id ?? 'no model')}: ${cleanLine(securityPickProblemNote(result.model.requested, result.model.pickProblem))}.` + : ' 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.slice(0, 7)}-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' : `platform limit for ${budget.ceilingSource === 'project' ? 'this project' : budget.ceilingSource === 'plan' ? 'this plan' : 'every project'}`})`; + 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: boolean; + 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)}).`, + ]); + if (isInteractive(deps) && !args.json) { + (deps.openUrl ?? openBrowser)(link.url); + } + return; + } +} + +export function isInteractive(deps: Pick): boolean { + return deps.interactive ?? (Boolean(process.stdout.isTTY) && !isCI); +} + +export async function askYesNo( + deps: Pick, + message: string, +): Promise { + if (deps.confirm) { + return deps.confirm(message); + } + const answer = await confirm({ message, initialValue: false }); + return !isCancel(answer) && answer; +} + +/** The status for lines added after a change; the change already happened, so errors are dropped. */ +async function statusAfterChange( + client: PlatformClient, + projectId: string, +): Promise { + try { + return await client.getProjectSecurity(projectId); + } catch { + return null; + } +} + +/** + * `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) { + if (!args.yes && (args.json || !isInteractive(deps))) { + 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)]; + 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.', + ); + log(lines); + if ( + !args.yes && + !(await askYesNo(deps, `Send these files for a security check with ${model}?`)) + ) { + console.log('Nothing was sent.'); + return; + } + 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; + } + let view: Awaited>; + try { + view = await waitForSecurityLocalCheck( + client, + projectId, + checkId, + (status) => log([status === 'running' ? ' Running…' : ' Waiting in the scan queue…']), + deps.check, + ); + } catch (error) { + // A lost session, a disabled platform or the network stops the wait, not the check. + if (!(error instanceof PlatformApiError && error.status === 404)) { + const hint = ` The check keeps running. See it later: void project security check ${cleanLine(checkId)}`; + if (args.json) { + console.error(hint.trim()); + } else { + log([hint]); + } + } + throw error; + } + 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, { fresh })); + if (!checkEndedWithResult(view)) { + throw new Error(checkFailureMessage(view, { fresh })); + } +} diff --git a/packages/void/src/cli/project-zero-trust.ts b/packages/void/src/cli/project-zero-trust.ts index 68049ca23..7f4ac8570 100644 --- a/packages/void/src/cli/project-zero-trust.ts +++ b/packages/void/src/cli/project-zero-trust.ts @@ -1,35 +1,95 @@ import { log, outro } from '@voidzero-dev/vite-plus-prompts'; -import { getToken } from './auth.ts'; -import { PlatformClient } from './client.ts'; -import type { ProjectZeroTrustResponse, ProjectZeroTrustUpdateResponse } from './client.ts'; -import { printSuccess, note, sanitizeTerminalText } from './output.ts'; -import type { ProjectArgs } from './project-args.ts'; -import { readProjectConfig } from './project.ts'; -import { getRequestedProjectSlug, requireProjectBySlug } from './resolve-project.ts'; - -type ZeroTrustArgs = Extract & { - action: 'status' | 'protect' | 'public' | 'reconcile'; +import { hasOwnKey } from '../shared/has-own-key.ts'; +import { PlatformApiError } from './client.ts'; +import type { + PlatformClient, + ProjectZeroTrustResponse, + ProjectZeroTrustUpdateResponse, +} from './client.ts'; +import { cleanLine, printSuccess, note, sanitizeTerminalText } from './output.ts'; +import type { ProjectZeroTrustArgs } from './project-args.ts'; +import { + askYesNo, + day, + isInteractive, + publicRequestLines, + resolveTarget, +} from './project-security.ts'; +import type { RequestSecurity } from './project-security.ts'; +import { OPEN_PUBLIC_REQUEST_STATES } from './security-api-types.ts'; +import type { SecurityPublicRequest } from './security-api-types.ts'; + +type ZeroTrustArgs = Exclude; + +export type ProjectZeroTrustDeps = { + interactive?: boolean; + confirm?: (message: string) => Promise; }; -async function resolveTarget(root: string, args: ZeroTrustArgs) { - 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.'); +function isOpenRequest( + request: SecurityPublicRequest | null | undefined, +): request is SecurityPublicRequest { + return Boolean(request && OPEN_PUBLIC_REQUEST_STATES.has(request.state)); +} + +/** + * A refusal that keeps the platform's error code, status and details (blockers, the + * closed request's state), so `--json` prints them (cli-main). + */ +class ZeroTrustRefusal extends Error { + readonly code: string; + readonly status?: number; + readonly details: Record; + constructor( + message: string, + code: string, + status: number | undefined, + details: Record = {}, + ) { + super(message); + this.code = code; + if (status !== undefined) { + this.status = status; + } + this.details = details; } - return { client, projectId: linked.projectId, slug: linked.slug }; } -function statusLines(result: ProjectZeroTrustResponse): string { +function noRequestRefusal(slug: string, status?: number): ZeroTrustRefusal { + return new ZeroTrustRefusal( + `project: ${slug} has no public request to bypass. Run: void project zero-trust public`, + 'no public request', + status, + ); +} + +const ROLE_LABELS = { + owner: 'the project owner', + admin: 'a project admin', + installation_admin: 'a platform admin', +}; + +function lastBypassLine(bypass: NonNullable): string { + const reason = bypass.reason === undefined ? '' : ` ("${cleanLine(bypass.reason)}")`; + const role = bypass.byRole; + const by = role !== null && hasOwnKey(ROLE_LABELS, role) ? ROLE_LABELS[role] : 'a project member'; + return `Last bypass: ${day(bypass.at)}, by ${by}${reason}`; +} + +function requestBlock( + slug: string, + request: SecurityPublicRequest, + security: RequestSecurity, +): Array { + const [first = '', ...rest] = publicRequestLines(slug, request, security); + return [`Public request: ${first}`, ...rest.map((line) => ` ${line}`)]; +} + +function statusLines( + result: ProjectZeroTrustResponse, + security: RequestSecurity, + slug: string, +): string { const project = result.project; const platformStatus = sanitizeTerminalText(result.platformStatus); const unavailableMessage = @@ -56,14 +116,197 @@ 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) + : []), + ...(result.lastBypass ? [lastBypassLine(result.lastBypass)] : []), ].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 closedRefusalText(slug: string, state: string, fallback: string): string { + switch (state) { + case 'canceled': + return `project: Public request canceled, so nothing was bypassed. ${slug} stays protected.`; + case 'passed': + return `project: The security scan already passed, so nothing was bypassed. ${slug} is going public.`; + case 'bypassed': + return `project: The scan was already bypassed. ${slug} is going public.`; + default: + return fallback; + } +} + +/** The CLI copy of a 409 from the bypass route, keeping its code; else `null`. */ +function bypassRefusal(slug: string, error: PlatformApiError): ZeroTrustRefusal | null { + let body: { error?: unknown; state?: unknown; blockers?: { count?: unknown; ids?: unknown } }; + try { + body = JSON.parse(error.body) as typeof body; + } catch { + return null; + } + if (body.error === 'no public request') { + return noRequestRefusal(slug, error.status); + } + if (body.error === 'public request closed') { + // A protect, a pass or another bypass closed the request this bypass saw (edge #72). + const state = typeof body.state === 'string' ? body.state : ''; + return new ZeroTrustRefusal( + closedRefusalText(slug, state, error.message), + body.error, + error.status, + { state }, + ); + } + 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 ZeroTrustRefusal( + `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`, + body.error, + error.status, + { blockers: { count, ids } }, + ); +} + +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.`; + } + if (request.heldReason === 'unread_files') { + return `The scan of ${target} could not read some project files.`; + } + const why = request.heldReason ? cleanLine(request.heldReason.split('_').join(' ')) : ''; + return `The scan of ${target} did not finish${why ? ` (${why})` : ''}.`; +} + +const NO_SECURITY: RequestSecurity = { + backlogFiles: 0, + budget: null, +}; + +/** + * The backlog, budget, gate scan and model the request copy names; without them it + * still reads right. + */ +async function requestSecurity( + client: PlatformClient, + projectId: string, +): Promise { + try { + const status = await client.getProjectSecurity(projectId); + return { + backlogFiles: typeof status.backlogFiles === 'number' ? status.backlogFiles : 0, + budget: status.budget ?? null, + lastScan: status.lastScan ?? null, + model: status.model, + projectId, + }; + } catch { + return { ...NO_SECURITY, projectId }; + } +} + +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 noRequestRefusal(slug); + } + const request = state.publicRequest; + if (request && !args.yes && request.state !== 'held_findings') { + if (args.json || !isInteractive(deps)) { + throw new Error('project: Add --yes to bypass the scan without a prompt.'); + } + 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 askYesNo(deps, `Bypass the scan and make ${slug} public?`))) { + outro('Nothing was changed.'); + return; + } + } + let result; + try { + result = await client.bypassProjectPublicRequest(projectId, args.reason, request?.id); + } catch (error) { + if (error instanceof PlatformApiError && error.status === 409) { + throw bypassRefusal(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; + } + const security = isOpenRequest(result.publicRequest) + ? await requestSecurity(client, projectId) + : NO_SECURITY; + note(statusLines(result, security, slug), slug); outro(`${slug} Zero Trust status`); return; } @@ -71,9 +314,33 @@ export async function runProjectZeroTrustCommand(root: string, args: ZeroTrustAr args.action === 'reconcile' ? await client.reconcileProjectZeroTrust(projectId) : await client.setProjectZeroTrust(projectId, args.action === 'protect'); + const publicRequest = result.publicRequest; + const held = args.action === 'public' && isOpenRequest(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". The + // local copy adds the command lines (spec §13.3) the platform message leaves out. + const security = await requestSecurity(client, projectId); + log.warn(publicRequestLines(slug, publicRequest, security).join('\n')); + outro('Check it: void project zero-trust status'); + return; + } + // Protect closed an open request (edge #80): say so (spec §11.4). + const canceled = args.action === 'protect' && result.publicRequest?.state === 'canceled'; + const canceledLine = `Public request canceled. ${slug} stays protected.`; if (result.project.last_error) { log.warn(sanitizeTerminalText(result.project.last_error)); } + const settledProtect = + result.project.state !== 'reconciling' && + result.project.state !== 'error' && + !result.project.last_error; + if (canceled && !settledProtect) { + log.info(canceledLine); + } if (result.project.state === 'reconciling') { outro( `${slug} Zero Trust update is still in progress. Run \`void project zero-trust reconcile\` to continue, or wait for scheduled maintenance.`, @@ -85,10 +352,12 @@ export async function runProjectZeroTrustCommand(root: string, args: ZeroTrustAr return; } printSuccess( - args.action === 'protect' - ? `${slug} is protected by Zero Trust.` - : args.action === 'public' - ? `${slug} is public.` - : `${slug} Zero Trust reconciled (${result.project.state}).`, + canceled + ? canceledLine + : args.action === 'protect' + ? `${slug} is protected by Zero Trust.` + : args.action === 'public' + ? `${slug} is public.` + : `${slug} Zero Trust reconciled (${result.project.state}).`, ); } 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..3ab299f2b --- /dev/null +++ b/packages/void/src/cli/security-api-types.ts @@ -0,0 +1,242 @@ +import type { SecurityPickProblem } from '@void/platform/security-models'; +/** Replies of the project security routes (spec §13.5), as the CLI reads them. */ + +/** `*_cap`: that cap is used up; `*_reserve`: one scan's worst case does not fit in what is left. */ +export type SecurityBudgetCause = + | 'project_cap' + | 'platform_cap' + | 'project_reserve' + | 'platform_reserve'; + +export type SecurityScanSummary = { + id: string; + status: string; + statusReason: string | null; + failureCause: string | null; + /** Which cap skipped a `skipped:budget` scan; older platforms do not send it. */ + budgetCause?: SecurityBudgetCause | 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; +}; + +/** Public request states that still hold the project protected. */ +export const OPEN_PUBLIC_REQUEST_STATES: ReadonlySet = new Set([ + 'waiting_scan', + 'held_findings', + 'held_no_result', + 'needs_deploy', +]); + +export type SecurityPublicRequest = { + id: string; + state: string; + heldReason: string | null; + targetDeploymentId: string; + gateScanId: string | null; + blockers: { count: number; ids: Array }; +}; + +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; + /** Why the project's own pick does not run; older platforms do not send it. */ + pickProblem?: SecurityPickProblem | 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; + /** The most one scan with the current model can cost; older platforms do not send it. */ + scanReserveUsd?: number | null; + } | null; + lastScan: SecurityScanSummary | null; + /** + * The newest scan of another deployment than `lastScan`'s, not replaced by a newer + * deploy; older platforms do not send it. + */ + previousScan?: 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; + /** `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; + 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; + /** The person is no longer the owner or a member of the project (older platforms omit it). */ + formerMember?: boolean; + 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 = { + id: string; + resolution: string | null; + publicRequest?: SecurityPublicRequest; +}; + +/** `POST …/findings/:fid/severity`: the finding after a severity edit. */ +export type SecuritySeverityChange = { + id: string; + severity: string | null; + scanSeverity: string | null; + severityEdited: boolean; + changed: boolean; + publicRequest?: SecurityPublicRequest; +}; + +export type SecurityScanList = { scans: Array; nextCursor: string | null }; + +export type SecurityModelChange = { model: ProjectSecurityStatus['model'] }; + +/** `POST /projects/:id/security/scans` with `dryRun: true`: what a rescan would run. */ +export type SecurityRescanPreview = { + deploymentId: string; + alreadyScanned: boolean; + /** M31: the scan also reads client bundle sources; older platforms omit it. */ + clientAssets?: boolean; + model: string | null; + worstCaseUsd: number | null; + budget: ProjectSecurityStatus['budget']; +}; + +export type SecurityRescanQueued = { scanId: string; deploymentId: string; clientAssets?: boolean }; + +export type SecurityBudgetChange = { 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 = { + model: string; + /** The provider notice, for a third-party model; `null` for a Cloudflare model. */ + notice: Array | null; + worstCaseUsd: number | null; +}; + +export type SecurityCheckCreated = { + checkId: string; + upload: { url: string; headers: Record }; +}; + +export type SecurityCheckFinding = { + verdict: 'confirmed' | 'needs_validation'; + severity: string | null; + title: string; + file: string; + lineStart: number | null; +}; + +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..5ef651e51 --- /dev/null +++ b/packages/void/src/cli/security-sarif.ts @@ -0,0 +1,227 @@ +/** + * SARIF 2.1.0 export of security audit findings (design doc 0095, M31). Paths are as the + * scan saw them. + */ +import { hasOwnKey } from '../shared/has-own-key.ts'; +import { getOwnVersion } from './agents.ts'; +import { cleanLine } from './output.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; + } +} + +/** 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 = { + 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('/'); +} + +interface SarifLocation { + physicalLocation: { + artifactLocation: { uri: string; uriBaseId: string }; + region?: { startLine: number; endLine?: number }; + }; +} + +interface SarifResult { + ruleId: string; + level: 'error' | 'warning' | 'note'; + message: { text: string }; + locations?: Array; + partialFingerprints?: { 'voidFinding/v1': string }; + suppressions?: Array<{ kind: 'external'; status: 'accepted'; justification: string }>; + properties?: { + id: string; + project?: string; + severity: string | null; + verdict: string; + state: string; + urgent?: boolean; + cwe?: string; + }; +} + +interface SarifRule { + id: string; + shortDescription: { text: string }; + properties: { tags: Array; 'security-severity'?: string }; +} + +/** One SARIF 2.1.0 log. */ +export interface SarifLog { + $schema: string; + version: '2.1.0'; + runs: Array<{ + tool: { + driver: { name: string; version?: string; informationUri: string; rules: Array }; + }; + results: Array; + }>; +} + +function result(finding: SarifFinding): SarifResult { + 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: SarifResult = { + 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 }>, +): SarifLog { + const results = findings.map(result); + const rules = new Map }>(); + for (const [index, finding] of findings.entries()) { + const ruleId = results[index].ruleId; + const rule = rules.get(ruleId) ?? { id: ruleId, score: 0, cwes: new Set() }; + const severity = finding.severity; + rule.score = Math.max( + rule.score, + severity !== null && hasOwnKey(SECURITY_SEVERITY, severity) ? SECURITY_SEVERITY[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/helpers/cli-command.ts b/packages/void/test/helpers/cli-command.ts index ccdfadf5a..6a552e7aa 100644 --- a/packages/void/test/helpers/cli-command.ts +++ b/packages/void/test/helpers/cli-command.ts @@ -1,12 +1,12 @@ -import { mkdtempSync } from 'node:fs'; +import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; -import { vi } from 'vite-plus/test'; +import { onTestFinished, vi } from 'vite-plus/test'; import { Buffer } from '../../src/cli/node-buffer.ts'; import { savePlatformConnection } from '../../src/cli/platform-registry.ts'; -/** Collects stdout writes and `console.log` lines until `restore()` is called. */ -export function captureOutput(): { output: () => string; restore: () => void } { +/** Collects stdout writes and `console.log` lines until `restore()` is called; `clear()` starts over. */ +export function captureOutput(): { output: () => string; clear: () => void; restore: () => void } { const chunks: Array = []; const writeMock = vi .spyOn(process.stdout, 'write') @@ -24,6 +24,9 @@ export function captureOutput(): { output: () => string; restore: () => void } { }); return { output: () => chunks.join(''), + clear: () => { + chunks.length = 0; + }, restore: () => { writeMock.mockRestore(); logMock.mockRestore(); @@ -40,6 +43,11 @@ export function setIsolatedHome(): string { process.env.HOME = dir; process.env.USERPROFILE = dir; process.env.VOID_PLATFORM_REGISTRY_DIR = join(dir, 'registry'); + saveTestConnection(); + return dir; +} + +function saveTestConnection(): void { savePlatformConnection({ accountId: null, apiUrl: 'https://api.example.test', @@ -49,5 +57,28 @@ export function setIsolatedHome(): string { kind: 'connected', proxyUrl: 'https://proxy.example.test', }); - return dir; +} + +/** + * A temp project folder linked to `project_1` on the test platform, with a + * token in the env. The registry lives inside it; both go when the test ends. + */ +export function linkedProject({ slug }: { slug: string }): string { + const root = mkdtempSync(join(tmpdir(), 'void-linked-')); + onTestFinished(() => rmSync(root, { recursive: true, force: true })); + vi.stubEnv('VOID_PLATFORM_REGISTRY_DIR', join(root, '.registry')); + vi.stubEnv('VOID_TOKEN', 'test-token'); + vi.stubEnv('VOID_API_URL', 'https://api.example.test'); + saveTestConnection(); + mkdirSync(join(root, '.void')); + writeFileSync( + join(root, '.void', 'project.json'), + JSON.stringify({ + platform: 'void', + platformUrl: 'https://api.example.test', + projectId: 'project_1', + slug, + }), + ); + return root; } diff --git a/packages/void/test/helpers/security-status.ts b/packages/void/test/helpers/security-status.ts new file mode 100644 index 000000000..e190f80e8 --- /dev/null +++ b/packages/void/test/helpers/security-status.ts @@ -0,0 +1,65 @@ +import type { + ProjectSecurityStatus, + SecurityScanSummary, +} from '../../src/cli/security-api-types.ts'; + +/** A queued deploy scan of `dpl_9a1d`; pass what the test is about. */ +export function scanSummary(overrides: Partial = {}): SecurityScanSummary { + return { + 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, + }; +} + +/** A project the platform scans, with nothing urgent, no budget and a queued scan. */ +export function securityStatus( + 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: scanSummary(), + lastSuccessfulScan: null, + deploysSinceLastSuccess: null, + backlogFiles: 0, + counts: { open: {}, leads: 3, resolved: 0, urgent: 0 }, + publicRequest: null, + ...overrides, + }; +} diff --git a/packages/void/test/unit/cloudflare-deploy.test.ts b/packages/void/test/unit/cloudflare-deploy.test.ts index 4c459afd6..94c21af96 100644 --- a/packages/void/test/unit/cloudflare-deploy.test.ts +++ b/packages/void/test/unit/cloudflare-deploy.test.ts @@ -1421,6 +1421,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..698945076 --- /dev/null +++ b/packages/void/test/unit/deploy-security-notice.test.ts @@ -0,0 +1,65 @@ +import { describe, expect, it, vi } from 'vite-plus/test'; +import { PlatformApiError } from '../../src/cli/client.ts'; +import type { PlatformClient } from '../../src/cli/client.ts'; +import { printDeploySecurityNotice } from '../../src/cli/deploy-security-notice.ts'; +import type { ProjectSecurityStatus } from '../../src/cli/security-api-types.ts'; +import { securityStatus as status } from '../helpers/security-status.ts'; + +const urgent = (n: number): 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: 'full', + findings: Array.from({ length: n }, (_, index) => ({ + id: `F-${index + 1}`, + severity: index === 1 ? 'critical' : 'high', + title: `Title ${index + 1}\u001b[31m red`, + file: 'src/a.ts', + line: 4, + })), +}); + +async function run(reply: () => Promise, env: NodeJS.ProcessEnv = {}) { + const lines: Array = []; + await printDeploySecurityNotice({ + client: { getProjectSecurity: vi.fn(reply) } as unknown as PlatformClient, + projectId: 'project_1', + slug: 'acme-web', + deploymentId: 'dpl_9a1d', + env, + write: (line) => lines.push(line), + }); + return { lines }; +} + +describe('deploy security notice', () => { + it('prints the queued scan and urgent rows for a user session, with ANSI stripped', async () => { + const text = (await run(async () => status({ urgent: urgent(2) }))).lines.join('\n'); + expect(text).toContain('Security scan queued · model @cf/deepseek-ai/deepseek-v4.1-flash-1017'); + expect(text).toContain( + '⚠ 2 urgent security findings are open in acme-web (1 critical, 1 high):', + ); + expect(text).toContain('Title 2 red'); + expect(text).not.toContain('\u001b'); + expect(text).toContain('void project security show F-2'); + }); + + it('drops to counts and ids in CI even when the server sent titles', async () => { + const env = { CI: 'true' }; + const text = (await run(async () => status({ urgent: urgent(2) }), env)).lines.join('\n'); + expect(text).toContain('2 urgent security findings are open (1 critical, 1 high): F-2, F-1'); + expect(text).toContain('Details are not printed in CI logs.'); + expect(text).not.toContain('Title'); + expect(text).not.toContain('src/a.ts'); + }); + + it.each([ + ['500', () => Promise.reject(new PlatformApiError('boom', 500, ''))], + ['network error', () => Promise.reject(new TypeError('fetch failed'))], + ])('prints nothing and keeps the exit code on a %s', async (_name, reply) => { + const before = process.exitCode; + expect((await run(reply)).lines).toEqual([]); + expect(process.exitCode).toBe(before); + }); +}); diff --git a/packages/void/test/unit/init.test.ts b/packages/void/test/unit/init.test.ts index d032443cc..c66566889 100644 --- a/packages/void/test/unit/init.test.ts +++ b/packages/void/test/unit/init.test.ts @@ -1535,6 +1535,7 @@ beforeEach(() => { googleOAuth: true, managedBuilds: true, sandbox: true, + securityAudits: true, }, displayName: 'Void Cloud', installationId: null, @@ -1565,6 +1566,7 @@ describe('Void platform deployment setup', () => { googleOAuth: false, managedBuilds: false, sandbox: false, + securityAudits: false, }, displayName: 'Company Void', installationId: 'company-a1b2c3d4', @@ -1605,6 +1607,7 @@ describe('Void platform deployment setup', () => { googleOAuth: false, managedBuilds: false, sandbox: false, + securityAudits: false, }, displayName: 'Company Void', installationId: 'company-a1b2c3d4', diff --git a/packages/void/test/unit/operator-cli.test.ts b/packages/void/test/unit/operator-cli.test.ts index 9fd7a8654..742a5b1d8 100644 --- a/packages/void/test/unit/operator-cli.test.ts +++ b/packages/void/test/unit/operator-cli.test.ts @@ -142,13 +142,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' ? [ @@ -1971,3 +2003,99 @@ describe('project AI logging commands', () => { }, ); }); + +describe('platform security commands', () => { + type Call = { method: string; path: 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) => { + calls.push({ + method: init?.method ?? 'GET', + path: new URL(String(input)).pathname.replace('/operator/v1', ''), + 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.mock.calls, ...stderr.mock.calls, ...stdout.mock.calls] + .map(([chunk]) => String(chunk)) + .join('\n'); + } + + const run = (...args: Array) => + runOperatorCommand(parseOperatorArgs(['security', ...args])); + + it('previews a mode change, then applies it at the previewed revision; refuses a bad mode', async () => { + const out = quiet(); + const calls = serve([ + { dryRun: true, action: 'security.policy', target: 'platform', expectedRevision: 7 }, + { ok: true, policy: { mode: 'public' } }, + ]); + await run('policy', 'public', '--yes'); + expect(calls.map((call) => [call.path, call.body])).toEqual([ + ['/security/policy', { mode: 'public', dryRun: true }], + ['/security/policy', { mode: 'public', expectedRevision: 7 }], + ]); + expect(stripVTControlCharacters(out())).toContain('Platform security policy completed.'); + expect(() => parseOperatorArgs(['security', 'policy', 'everything'])).toThrow( + 'disabled|public|all', + ); + }); + + it('reads a provider key from stdin once and never prints it', async () => { + const out = quiet(); + 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' }, + { ok: true, host: 'anthropic', message: 'Saved your own Anthropic key.' }, + ]); + await run('models', '--provider', 'anthropic', '--key-stdin', '--yes'); + expect(calls[1]).toMatchObject({ + path: '/security/provider-keys', + body: { host: 'anthropic', key: 'sk-ant-secret-value-123' }, + }); + expect(out()).toContain('Saved your own Anthropic key.'); + expect(out()).not.toContain('sk-ant-secret-value-123'); + }); + + it('bypasses a public request with a preview first', async () => { + quiet(); + const calls = serve([ + { dryRun: true, action: 'security.public-request-bypass', target: 'p1' }, + { ok: true, project: { state: 'ready' } }, + ]); + await run('bypass', 'p1', '--reason', 'launch today', '--yes'); + expect(calls[1]).toMatchObject({ + path: '/projects/p1/security/public-request/bypass', + body: { reason: 'launch today' }, + }); + }); + + it('names the upgrade command when security audits are not installed', async () => { + quiet(); + const body = { error: 'platform capability unavailable', capability: 'securityAudits' }; + serve([Response.json(body, { 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-database-migrations.test.ts b/packages/void/test/unit/platform-database-migrations.test.ts index 9801dabf2..1dae1cde5 100644 --- a/packages/void/test/unit/platform-database-migrations.test.ts +++ b/packages/void/test/unit/platform-database-migrations.test.ts @@ -18,7 +18,9 @@ afterEach(async () => { database = undefined; }); -describe('platform database migrations', () => { +// Each case applies the whole packaged schema in PGlite (under a second alone). Under a +// full `vp run test`, with every PGlite worker busy, the first case passed 5 seconds. +describe('platform database migrations', { timeout: 20_000 }, () => { it.each(['1.6.0', '1.7.0'])( 'upgrades a released %s database before applying project AI logging policies', async (version) => { diff --git a/packages/void/test/unit/project-args.test.ts b/packages/void/test/unit/project-args.test.ts index f7ddaed50..b1fa04144 100644 --- a/packages/void/test/unit/project-args.test.ts +++ b/packages/void/test/unit/project-args.test.ts @@ -126,20 +126,30 @@ 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, }); } + expect( + parseProjectArgs(['zero-trust', 'bypass', '--reason', ' Down ', '--yes']), + ).toMatchObject({ + action: 'bypass', + reason: 'Down', + yes: true, + }); + expect(() => parseProjectArgs(['zero-trust', 'bypass'])).toThrow('A reason is required'); }); 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 +386,22 @@ describe('parseProjectArgs', () => { }); }); }); + +describe('security', () => { + it('parses an action and refuses a resolve without a comment', () => { + expect( + parseProjectArgs([ + 'security', + 'resolve', + 'F-12,13', + '--reason', + 'false-positive', + '--comment', + 'ok', + ]), + ).toMatchObject({ ids: ['F-12', 'F-13'], reason: 'false_positive', comment: 'ok' }); + expect(() => parseProjectArgs(['security', 'resolve', 'F-1', '--reason', 'fixed'])).toThrow( + 'comment is required', + ); + }); +}); 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..edd1cba7e --- /dev/null +++ b/packages/void/test/unit/project-security-check-command.test.ts @@ -0,0 +1,212 @@ +import { mkdirSync, symlinkSync, writeFileSync } from 'node:fs'; +import { join } from 'node:path'; +import { gunzipSync } from 'node:zlib'; +import { afterEach, describe, expect, it, vi } from 'vite-plus/test'; +import type { Buffer } from '../../src/cli/node-buffer.ts'; +import type { SecurityCheckDeps } from '../../src/cli/project-security-check.ts'; +import { runProjectSecurityCommand } from '../../src/cli/project-security.ts'; +import { captureOutput, linkedProject } from '../helpers/cli-command.ts'; +import { withPlatformDiscovery } from '../helpers/platform-discovery.ts'; +import { scanSummary } from '../helpers/security-status.ts'; + +const linked = () => linkedProject({ slug: 'acme-web' }); + +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(() => { + vi.unstubAllEnvs(); + vi.unstubAllGlobals(); + vi.restoreAllMocks(); +}); + +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 = { + ...scanSummary({ + id: 'scan_9', + trigger: 'local', + deploymentId: null, + baseDeploymentId: null, + model: null, + meteredUsd: 0, + 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 }; + +/** The platform and storage: handlers by `METHOD path` (the upload by its full URL). */ +function route(handlers: Record Response>) { + const calls: Array = []; + const impl = withPlatformDiscovery(async (input: string | URL | Request, init?: RequestInit) => { + const url = new URL(String(input instanceof Request ? input.url : input)); + const method = init?.method ?? 'GET'; + const upload = url.href === UPLOAD; + calls.push({ + method, + url: upload ? 'UPLOAD' : url.pathname, + body: upload ? init?.body : init?.body ? JSON.parse(String(init.body)) : undefined, + }); + 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 }; +} + +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('void project security check', () => { + it('keeps secret-like files and links out, previews, uploads, starts, waits and prints', async () => { + const root = linked(); + write(root, { ...APP, '.env': 'SECRET=1', 'pnpm-lock.yaml': 'lockfileVersion: 9' }); + symlinkSync(join(root, 'src/app.tsx'), join(root, 'link.ts')); + let gets = 0; + const { calls, fetch } = route( + platform(() => (++gets === 1 ? { check, ended: false, result: null } : ended)), + ); + const out = captureOutput(); + const files = [...Object.keys(APP), '.env', 'pnpm-lock.yaml', 'link.ts']; + await runProjectSecurityCommand(root, args(), deps(files, { 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`, + ]); + expect(calls[0]?.body).toMatchObject({ dryRun: true, files: 2 }); + const tar = gunzipSync(calls[2]?.body as Buffer).toString('latin1'); + expect(tar).toContain('tree/src/routes/users.ts'); + expect(tar).not.toContain('SECRET=1'); + expect(tar).not.toContain('lockfileVersion'); + expect(tar).not.toContain('link.ts'); + expect(out.output()).toContain('Not sent: 1 secret-like file (.env).'); + expect(out.output()).toContain('1 finding (1 high) · 1 lead'); + expect(out.output()).not.toContain('\u001b[31m'); + }); + + it('needs --yes without a terminal, 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.'); + expect(calls).toHaveLength(0); + }); +}); 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..fc453209f --- /dev/null +++ b/packages/void/test/unit/project-security-command.test.ts @@ -0,0 +1,182 @@ +import { afterEach, describe, expect, it, vi } from 'vite-plus/test'; +import { parseProjectArgs } from '../../src/cli/project-args.ts'; +import { runProjectCommand } from '../../src/cli/project-cmd.ts'; +import { captureOutput, linkedProject } from '../helpers/cli-command.ts'; +import { withPlatformDiscovery } from '../helpers/platform-discovery.ts'; +import { securityStatus } from '../helpers/security-status.ts'; + +const linked = () => linkedProject({ slug: 'acme-web' }); + +afterEach(() => { + vi.unstubAllEnvs(); + vi.unstubAllGlobals(); + vi.restoreAllMocks(); +}); + +const status = securityStatus({ + urgent: { + count: 1, + counts: { critical: 1, high: 0 }, + oldestFirstSeenAt: '2026-11-10T00:00:00.000Z', + findings: [{ id: 'F-12', severity: 'critical' }], + more: 0, + detail: 'full', + }, + budget: { + capUsd: 100, + capSource: 'own', + ceilingUsd: 100, + spentUsd: 12.4, + month: '2026-11-01', + resetsAt: '2026-12-01T00:00:00.000Z', + }, +}); + +function route(handlers: Record Response>) { + const calls: Array<{ method: string; path: string; body: unknown }> = []; + vi.stubGlobal( + 'fetch', + withPlatformDiscovery(async (input: string | URL | Request, init?: RequestInit) => { + const url = new URL(String(input instanceof Request ? input.url : input)); + const method = init?.method ?? 'GET'; + const body = init?.body ? JSON.parse(String(init.body)) : undefined; + calls.push({ method, path: url.pathname + url.search, body }); + 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)); +const S = '/projects/project_1/security'; +const F = `${S}/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('void project security', () => { + it('prints the status, one JSON document with --json, and names an old platform', async () => { + const root = linked(); + route({ [`GET ${S}`]: () => Response.json(status) }); + const out = captureOutput(); + await run(root, ['security', 'status']); + expect(out.output()).toContain('1 open (1 critical) · oldest Nov 10'); + expect(out.output()).toContain('$12.40 of $100.00 this month (project cap) · resets Dec 1'); + out.clear(); + await run(root, ['security', 'status', '--json']); + expect(JSON.parse(out.output())).toMatchObject({ + policy: { mode: 'all' }, + counts: { leads: 3 }, + }); + route({}); + await expect(run(root, ['security', 'status'])).rejects.toThrow( + 'does not support security audits', + ); + }); + + it('lists findings without leads and shows one in full', async () => { + const root = linked(); + route({ + [`GET ${F}`]: () => + Response.json({ + findings: [finding('F-1'), finding('F-2', { verdict: 'needs_validation' })], + nextCursor: null, + }), + [`GET ${F}/F-1`]: () => + Response.json({ finding: finding('F-1', { evidence: 'EVID', fix: 'FIXTEXT' }) }), + }); + const out = captureOutput(); + await run(root, ['security', 'list']); + expect(out.output()).toContain('F-1'); + expect(out.output()).toContain('1 lead is hidden. Show them with --leads.'); + out.clear(); + await run(root, ['security', 'show', 'F-1']); + expect(out.output()).toContain('EVID'); + expect(out.output()).toContain('FIXTEXT'); + }); + + it('resolves with the revision it read, keeps going after a refusal, then fails', async () => { + const root = linked(); + const calls = route({ + [`GET ${F}/F-1`]: () => Response.json({ finding: finding('F-1', { revision: 4 }) }), + [`GET ${F}/F-2`]: () => Response.json({ finding: finding('F-2') }), + [`POST ${F}/F-1/resolve`]: () => + Response.json({ ok: true, id: 'F-1', state: 'resolved', resolution: 'fixed' }), + [`POST ${F}/F-2/resolve`]: () => + Response.json({ error: 'finding changed', message: 'F-2 changed.' }, { status: 409 }), + [`GET ${S}`]: () => Response.json(status), + }); + const out = captureOutput(); + await expect( + run(root, ['security', 'resolve', 'F-1,F-2', '--reason', 'fixed', '--comment', 'Bound']), + ).rejects.toThrow('1 of 2 findings were not resolved'); + expect(out.output()).toContain('F-1 resolved (fixed)'); + expect(out.output()).toContain('F-2: F-2 changed.'); + expect(calls.find((c) => c.path === `${F}/F-1/resolve`)?.body).toEqual({ + reason: 'fixed', + comment: 'Bound', + expectedRevision: 4, + }); + }); + + it('sets the budget and accepts a provider notice only with the version the platform names', async () => { + const root = linked(); + let puts = 0; + const calls = route({ + [`PUT ${S}/budget`]: () => Response.json({ ok: true, budget: status.budget }), + [`PUT ${S}/model`]: () => + ++puts === 1 + ? Response.json( + { error: 'provider notice not accepted', version: 3, notice: ['Run by Anthropic.'] }, + { status: 422 }, + ) + : Response.json({ ok: true, model: { ...status.model, id: 'anthropic/claude-x' } }), + }); + const out = captureOutput(); + await run(root, ['security', 'budget', '--usd', '40']); + expect(out.output()).toContain('scan budget set to $40.00 / month'); + expect(calls[0]?.body).toEqual({ monthlyUsd: 40 }); + await run(root, ['security', 'model', 'anthropic/claude-x', '--accept-provider-notice']); + expect(out.output()).toContain('Run by Anthropic.'); + const versions = calls + .slice(1) + .map((c) => (c.body as { acceptProviderNoticeVersion?: number }).acceptProviderNoticeVersion); + expect(versions).toEqual([0, 3]); + }); + + it('previews a scan, needs --yes without a terminal, then queues it', async () => { + const root = linked(); + let posts = 0; + const calls = route({ + [`POST ${S}/scans`]: () => + ++posts === 1 + ? Response.json({ dryRun: true, deploymentId: 'dpl_9a1d', tier: 'full', model: '@cf/x' }) + : Response.json( + { + ok: true, + scanId: 'ss_new', + deploymentId: 'dpl_9a1d', + tier: 'full', + model: '@cf/x', + }, + { status: 202 }, + ), + }); + await expect(run(root, ['security', 'scan', '--json'])).rejects.toThrow('Add --yes'); + posts = 0; + const out = captureOutput(); + await run(root, ['security', 'scan', '--yes']); + expect(calls.map((c) => c.body)).toEqual([{ dryRun: true }, { dryRun: true }, {}]); + expect(out.output()).toContain('✓ Full scan ss_new of dpl_9a1d queued.'); + }); +}); 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..f6add69f2 100644 --- a/packages/void/test/unit/project-zero-trust-command.test.ts +++ b/packages/void/test/unit/project-zero-trust-command.test.ts @@ -4,6 +4,8 @@ import { join } from 'node:path'; 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 { captureOutput } from '../helpers/cli-command.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,76 @@ describe('project Zero Trust command', () => { expect(rendered).not.toContain('\u009d'); }); }); + +describe('project Zero Trust with a public request', () => { + const project = { project_id: 'project_1', desired_protected: true, state: 'protected' }; + const request = (state: string) => ({ + id: 'spr_1', + state, + heldReason: 'timed_out', + targetDeploymentId: 'dpl_9a1d', + blockers: { count: 0, ids: [] }, + }); + 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 = { projectSlug: '', json: false } as const; + const bypass = { ...base, subcommand: 'zero-trust', action: 'bypass' } as const; + const args = { ...bypass, reason: 'Scanner down', yes: true }; + + it('prints a held public as protected, never as public', async () => { + const reply = { ok: true, project, publicRequest: request('waiting_scan') }; + const root = setup(vi.fn(async () => Response.json(reply, { status: 202 }))); + const out = captureOutput(); + await runProjectCommand(root, { ...bypass, action: 'public' }); + expect(out.output()).toContain('Waiting for a security scan of dpl_9a1d'); + expect(out.output()).not.toContain('is public'); + }); + + it('bypasses with the reason and the request it saw, and refuses while urgent findings are open', async () => { + let post = () => Response.json({ ok: true, project, publicRequest: request('bypassed') }); + const fetchMock = vi.fn(async (_input: RequestInfo | URL, init?: RequestInit) => + init?.method === 'POST' + ? post() + : Response.json({ + available: true, + platformStatus: 'ready', + project, + publicRequest: request('held_no_result'), + }), + ); + const root = setup(fetchMock); + const out = captureOutput(); + await runProjectZeroTrustCommand(root, args, { interactive: false }); + const sent = fetchMock.mock.calls.find(([, init]) => init?.method === 'POST')?.[1]?.body; + expect(JSON.parse(String(sent))).toEqual({ reason: 'Scanner down', requestId: 'spr_1' }); + expect(out.output()).toContain('Scan bypassed.'); + const blockers = { count: 1, ids: ['F-12'] }; + post = () => + Response.json( + { error: 'security public request has urgent findings', blockers }, + { status: 409 }, + ); + await expect(runProjectZeroTrustCommand(root, args, { interactive: false })).rejects.toThrow( + 'A bypass skips only the scan, not open findings.', + ); + }); + + it('refuses security and bypass on a direct Cloudflare target before any request', async () => { + const root = linkedProject(); + writeFileSync(join(root, '.void', 'project.json'), JSON.stringify({ platform: 'cloudflare' })); + const fetchMock = vi.fn(); + vi.stubGlobal('fetch', fetchMock); + await expect(runProjectCommand(root, args)).rejects.toThrow( + 'only for projects hosted on a Void platform', + ); + await expect( + runProjectCommand(root, { ...base, subcommand: 'security', action: 'status' }), + ).rejects.toThrow('Security audits are available only for projects hosted on a Void platform'); + expect(fetchMock).not.toHaveBeenCalled(); + }); +}); 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..08019a30d --- /dev/null +++ b/platform/meta/design-docs/0095-security-audits.md @@ -0,0 +1,677 @@ +--- +title: Security audits on deploy +status: implemented +created: 2026-11-18 +--- + +# Security audits on deploy + +The design as built for the approved PRD, all three phases. Product rules, copy and the +94 edge cases stay in the PRD and spec; this file says where the code is, how the parts +fit, which rules every change must keep, and what is still open. + +- PRD: `void-prds/security-audits-prd.md` (short), spec: `void-prds/security-audits-spec.md`. + Decision numbers D1–D52, Q1–Q15 and edge case numbers (#1–#94) 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. +- Code comments name milestones (M1–M36) and risks (R1–R20); the + [milestone index](#milestone-index) and [risks](#risks-and-items-for-the-user) map them. + +## 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 attempt │─────┘ └── 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 (the spec 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 names a missing permission) | +| 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 per engine | Created at first move away from `disabled`, verified by the probe | +| API reaches the controller through a gate script in the platform dispatch namespace | A service binding from the API cannot point at a Worker created later; the gate (`void-security-scanner-gate-`) holds one binding `SCANNER` and no logic or secret | + +## Package and file layout + +``` +packages/platform/src/ + security-models.ts model list, engines, hosts, badges, prices, reserves → @void/platform/security-models + security-policy.ts policy type, defaults, strict + lenient parser, ranges, plan caps, form parsers + security-lockfile.ts package-lock / pnpm-lock readers (third-party identity) + security-local-check.ts local check path filter, limits, small ustar writer +platform/packages/security-scanner/ @voidcloud/security-scanner (private) + src/runner/{main,phases,extract,status,validate-findings,coerce,prompts,report,limits}.ts + src/runner/engines/{void-loop,claude,codex,proxy-failure}.ts, src/runner/mcp/{server,void-scan}.ts + src/runner/tools/fs.ts read_file / list_files / grep, realpath under /scan, no symlinks + src/runner/runtime/copy.ts copy_request tool (Engine B) + src/runner/self-test.ts probe checks 2–3 inside the container + image/{Dockerfile.claude,Dockerfile.codex,claude/,codex/,codex-wrapper.sh,NOTICE} + test/fake-model/server.ts, test/unit/*, test/e2e/recorded-run.e2e.test.ts (VOID_SCANNER_E2E=1) +platform/packages/api/src/security/ + schema.ts drizzle tables, re-exported from src/schema.ts + policy.ts, project-policy.ts, models.ts, errors.ts + enqueue.ts, queue.ts, scheduler.ts, call-ledger.ts, fence.ts, control.ts + input/{tier,t1,t1-github,t2,filters,third-party,redact,phrase-check,memory,backlog,tar,source-tar,build,prepare,local,project-data}.ts + model-proxy.ts, budget.ts, plan-caps.ts, provider-keys.ts, gateway-cost.ts + ingest.ts, findings.ts, project-findings.ts, project-view.ts, project-settings.ts, project-page.ts + public-gate{,-judge,-copy,-flow}.ts, exposure.ts + notifications.ts, notification-copy.ts, recipients.ts, alerts.ts, streaks.ts, digest.ts, webhook.ts + operator.ts, sweeps.ts, scan-candidates.ts, fallback.ts, local-check.ts, github-check.ts + runtime-copy{,-names,-plan,-sources,-sweep}.ts, scanner-images.{json,ts} + page-token.ts, probe.ts, maintenance.ts +platform/packages/api/src/ + provisioning/security-scanner{,-images}.ts controller Worker, gate, apps, image copy + security-scanner-controller-runtime.ts controller Worker source (DOs, outbound entrypoints) + routes/project-security.ts, routes/security-page.ts, operator/security-routes.ts + admin/security-data.ts, admin/routes/security.ts, admin/react/views/{Security,ProjectSecuritySection}*.tsx +platform/packages/dashboard/pages/projects/{index,[slug]/security}.{tsx,server.ts} +packages/void/src/cli/ + project-security{,-args,-check}.ts, deploy-security-{notice,packages}.ts, security-sarif.ts, + operator-security{,-args}.ts, platform-security-audits.ts +platform/scripts/publish-security-scanner-images.ts release: publish the Engine A / C images +``` + +Main edits outside these files: capability parsing and worker config in `packages/platform`; +the deploy pipeline (`deploy/*`, `deployment-execution.ts`, rollback in `routes/projects.ts`); +the Zero Trust write paths (`zero-trust/*`, `routes/project-zero-trust.ts`, +`operator/zero-trust-routes.ts`, admin Zero Trust views); `email.ts`; the admin shell +(`Layout`, `renderAdminPage`, fate renders); `api.ts` typed routes; the CLI managed deploy +paths, `list.ts`, the operator and installer arguments; `platform-ci.yml`. + +## Data model + +Migration `0065_security_audits.sql`, 11 tables in `security/schema.ts`: + +| Table | Holds | +| ---------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------- | +| `project_security_settings` | per project: model pick, notice version, own cap, admin ceiling (`cap_ceiling_cents`), `policy_override`, `next_finding_number` | +| `security_scans` | one row per scan: trigger, status/reason/error class/cause, attempt, lease, model, engine, tier, coverage, input keys, counts | +| `security_findings` | F-number, fingerprint key, state, severity + `severity_override`, verdict + `verdict_source`, revision, resolve columns | +| `security_finding_events` | finding history (actions, comments, `severity_from/to`) | +| `security_project_events` | cap changes, `protection_on/off` | +| `security_public_requests`, `security_scan_bypasses` | gate requests (one open per project) and recorded bypasses | +| `security_project_spend`, `security_platform_spend` | month rows: spent, scans, holds | +| `security_memory_rejected` | rejected records, kept so they are never fed back (PK `(project_id, fingerprint_key)`) | +| `security_notifications` | outbox: kind, dedupe key, attempts, `next_attempt_at` (email and webhook twins) | + +- Project FKs cascade; no FK to deployments; `actor_user_id` has no FK. The bypass → request + FK is `NO ACTION`, so retention cannot delete a request a bypass points to. +- Partial uniques: one running scan per project, one open request per project. The urgent + index uses `COALESCE(severity_override, severity)`. +- Money is in whole units: spend, holds and costs in nano-dollars (`*_nano_usd`, `bigint`), + caps in cents (`*_cents`, 0–100,000,000). `month` is a `date` with a first-of-month check. +- Status, trigger, state and kind lists are `CHECK`s built from TS lists; the migration test + checks them against `@void/platform` (`SECURITY_MODES`, engines, max cap). +- Settings keys (`platform_settings`): `securityAudits.policy` (with `revision`), + `securityAudits.providerKeys` (encrypted, M33), `securityAudits.webhook` (M26), + `plans:security-caps` (M27), `security.bypasses-seen.` (admin badge). +- R2 (platform bucket): `security-scans/{project}/{deployment}/` head snapshot + (`modules/`, `modules.json`, `sources.json`, `assets.json`, `packages.json`, + `never-sent.json`), `security-scans/{project}/backlog.json`, and per scan + `…/scans/{scan}/` (`backlog.json`, `server-leads.json`, `scope.json`, `status.json`, + `findings.json`, `local-result.{attempt}.json`; raw output swept after 30 days). + +## Flows + +### Capability and policy + +- `securityAudits` capability: optional in every parser (missing = false). The manifest + writes schema 7 when it is on, so an old CLI refuses instead of dropping it (R17). The DO + binding and the `security-audits-v1` migration tag follow the runtime manifest, not the + capability; `ai` binding only when on. A rollback to a runtime without the class is + refused (roll forward, R2). +- Policy in `security/policy.ts`: the strict parser guards writes; `readSecurityPolicy` is + lenient (unknown blocked ids dropped, a bad default becomes the first priced `@cf` model, + limits clamped; bad data reads as Off and keeps its revision). Every writer takes the + advisory lock `void:platform:security-policy` and checks `expectedRevision` (409). +- Turning on from `disabled` first checks the whole proposal, then provisions and runs the + probe outside the transaction; a failing check stores the result and answers 409 with each + check's copy. Off cancels `pending_input` and `queued` scans (`policy_off`) and turns the + gate off. +- Probe checks 1–6 (`probe.ts`): capability, container (provisioning), egress and self-test, + `@cf` call, per third-party host credits + image + engine self-test (check 5), gateway. A + daily re-probe runs while the mode is on. + +### Deploy → scan row (outbox) + +- `enqueueSecurityScanInTx` runs in a savepoint inside `commitCutoverLive`, + `promoteProtectedDeployment` (`trigger=recovery`) and compensation's post-routing recovery + (own short tx, R8). A failed statement is logged and the deploy commits with no row (D45). +- Lock order: project row, then the policy lock in shared mode, so an Off write cancels the + new row instead of missing it. +- Skips (spec §6.1): `preview-*`, owner suspended, project deleting → no row; protected + under `public` → `skipped:protected`; project rule `never` → `skipped:project_policy`. + Both skip rows keep a copy of inline modules so a later public request can still scan + that deployment. An open public request → `trigger=gate`. +- Coalescing supersedes waiting (`pending_input`, `queued`) rows and keeps `first_queued_at`. +- After commit (`finishSecurityScanEnqueue`): inline modules go to the head snapshot + (≤ 50 MB / 30 s, `modules.json` last), then a compare-and-set moves the row to `queued` + and pokes the scheduler. A staged deploy input is held (`input_prefix`) until the scan + copies it. + +### Scheduler, queue and hourly jobs + +- `SecurityScanScheduler` DO, one instance. A pass claims queued rows round-robin by owner, + oldest first, under the installation concurrency and one running scan per project. +- The claim (project lock + shared policy lock) resolves the model (`models.ts`: project + pick, else default; unknown/blocked/unpriced → default; third-party without check 5, the + installation notice or the project notice → first priced `@cf` model), bumps `attempt`, + sets the lease (2× wall clock + 5 min) and re-checks deleting, suspended, 24 h backlog, + protected under `public`, and the project rule. +- Then reserve the worst case on both month rows (`skipped:budget` on refusal), then start + through the gate. A failed start is retried once after 60 s, then `failed + (infrastructure, start_failed)`. +- `@cf` token bucket (10/min/model) and per-session call counts live in DO storage + (`call-ledger.ts`); a Workers AI 429 puts the bucket into debt. +- Cancel writes the rows first (that is the fence), then cancels at the controller. + `teardownProject` cancels before the cascade. +- Hourly (`maintenance.ts`, hourly tier only, R18): re-poke stale `pending_input`, reaper + (`timed_out`, reserve back), 24 h backlog skip, raw output sweep, scan and request + retention, daily probe, gateway cost, fallback, streak and digest alerts, sweeps, public + gate backstop, exposure catch-up, runtime copy sweep, local check sweep. Policy Off stops + the jobs that start work; cleanup jobs still run. + +### Controller and container + +- Names: `void-security-scanner[-gate]-<12 hex of sha256(installation id)>`; engine apps + `void-security-scanner-engine-{a,c}-`. Ownership marker on every object. +- One DO per attempt (`scan::`) or probe; a start is accepted once. The alarm + checks the fence, sets the egress lock (model host intercept, then deny all HTTP and + HTTPS), starts with `enableInternet: false, env: {}`, creates the `scanner` user and + `/scan` (0700), then runs the runner as `scanner` with the input tar on stdin. +- Engine B uses the managed `cloudflare/debian-trixie` image with the runner streamed in; + Engines A/C use digest-pinned images copied into the operator registry by the probe (R1). +- Every 10 s: fence, read `/scan/out/status.json` then `findings.json` (≤ 5 MiB) with + `O_NOFOLLOW`, hand both to `result`, destroy. Wall clock: `SIGTERM`, 60 s grace, + `timed_out (wall_clock)`; hard cap: `timed_out (hard_cap)`. +- The runner (dependency-free `runner.mjs`): safe tar extract (regular files only), hunt → + verify (≤ 10) → one repair turn → `findings.json` then `status.json` renamed into place. + Tools read only `/scan/input` and `/scan/memory`; `grep` is plain text. + +### Input + +- Tier at scan start: rescan, sweep, local → full (T3); no base → `first-scan`; base + snapshot gone → `no-usable-base`; else T1 when possible, else T2. +- T2: changed Worker modules by sha256 plus their source maps' `sourcesContent`; modules + with no map as built code; changed text assets (≤ 256 KB). T1 (hosted, `managedBuilds`): + GitHub compare of base and head commits plus the T2 changes, from one scoped + `contents: read` token; truncated, force-pushed or mismatched commits fall back to T2 with a + note. +- Filters (§7.4), secret-like files dropped, third-party code by lockfile identity (else + kept, ranked last, `third-party-unverified`), caps 400 files / 2 MB focus, 32 MB read set. + What does not fit goes to the backlog (`partial`); a project file the runner cannot read + (bad path, oversize, binary) holds a public request (`held_no_result`). +- Redaction replaces stored secret values (4 forms) in every file, memory included. The + phrase check (plain whole-word match) turns reviewer text into server leads. Redaction + hits become `secret_in_output` server findings (M31). +- Memory: index (64 KB, 200 records) plus history files; rejected records are never fed. +- An empty diff scan is stored `succeeded` with no model call (`no_changes`, #14). + +### Model proxy and budget + +- `SecurityScanControl.model()` → `model-proxy.ts`. One route per host: + `/v1/chat/completions` (`@cf`, `env.AI.run`), `/v1/messages` (`anthropic/*`), + `/v1/responses` (`openai/*`). The model must equal `scan.model_used`. +- Checks per call: fence and lease, policy on, host passed check 5, notices, session (40) + and scan call caps, token caps, provider-run tools refused (`tool_not_allowed`). +- Money: the call's worst case is held on both month rows in one `UPDATE … WHERE spent + + worst ≤ cap RETURNING`, always scan → project → platform row. After the answer the hold + becomes tokens × list price; an unreadable or lost answer keeps the worst case (the meter + errs high). Stops answer 429 (402 for credits) with `x-void-scan-stop`. +- Headers are built from nothing: `cf-aig-gateway-id`, signed `cf-aig-metadata + {"securityScan":tag}`, payload logging off, cache skipped; `access_programs` for `openai/*`. +- Caps (§16.2): ceiling = project ceiling → plan cap (`plans:security-caps`) → policy + default; effective = lower of the ceiling and the project's own cap. 80/100 % alerts are + queued after a settle and on `skipped:budget`. +- BYOK (M33): a saved provider key sends that host's calls through the AI binding's gateway + `run` on the provider-native route with `cf-aig-no-wholesale: true`. Keys are tested with a + 1-token call before saving and are metered like any call. + +### Ingest and findings + +- `result()` → `ingest.ts`. `status.json` goes through a small parser and `findings.json` + through the runner's own validator (`schema_version: 1`). Outcome table: `succeeded` + stores all; `incomplete` stores confirmed only; the rest store none (I10). The first + `failed (infrastructure)` attempt is requeued. +- One transaction: lock the project row, then the scan row, re-check the fence, write + findings and events, end the scan, release the reserve. +- Key = sha256(source, project, skill fingerprint, sink path or file). Severity only rises; + a confirmed finding is never demoted; a human severity is sticky (I5). 50 + 50 new keys + per scan (`findings-capped`). Reopen and stale-scan rules per spec §9.3. +- After commit: promote the scan's backlog (only on `succeeded`), store raw output, forget + the call ledger, queue notifications, re-check the public request, queue a fallback, send + the GitHub check, poke. + +### Notifications + +- Outbox rows are queued in the same transaction as the change (findings at ingest, human + reopen of an urgent finding, caps, public request states, bypass, streaks, digest). The + scheduler alarm sends them: dedupe key, 30-min findings cooldown, retries at 1 and 5 min, + third failure `failed`. `EMAIL` unbound marks rows `skipped`. +- Recipients are worked out at send time (`recipients.ts`); one email per person. +- The findings email rebuilds the new ids from the scan's events. A raise to critical counts + as new even when it was already high. **Decision:** kept; the event stores no old severity + and a schema change is not worth it. +- Webhook (M26): its own settings key and secret; every outbox event gets a `webhook` twin + row. Body has ids and counts only, signed `X-Void-Signature: t=…,v1=HMAC-SHA256`. + +### Scan before public (gate) + +- Turning `publicGate` on holds the Zero Trust lock (shared) and re-reads Zero Trust. + While on, disable and public-only are refused (409 `security public gate on`, 503 when the + policy cannot be read). +- Asking to go public goes through `checkpointProjectReconciliation` with `gate: ask`. The + pure judge (`public-gate-judge.ts`) reads the live deployment's newest scan and the open + findings: pass → flip; else hold (`waiting_scan`, `held_findings`, `held_no_result`, + `needs_deploy`). The project route answers 202 with an old-CLI-safe `state:'reconciling'`. +- Re-checks: ingest, resolve/reopen/severity edit, after a cutover commit, rollback, bypass, + and the hourly backstop (shares the cron's routing budget). +- Bypass (D50): under the project lock, only while no urgent finding is open and the + request waits for a scan or has no result. Installation admins get an email. +- Lock order: project row, Zero Trust shared, policy shared. +- Exposure catch-up (`exposure.ts`) scans a project that went public while out of scope. + +### Surfaces + +- Project API (`routes/project-security.ts`): status, findings list/show, comments + (`configure`), resolve/reopen/severity (`settings`, `expectedRevision`), scans history, + model and budget PUTs, page link, rescan, local checks. Role filter: `full` for a user + session with `deploy`; `counts` for readers and deploy tokens (only `GET …/security` is on + the deploy-token allowlist). Capability off: model, budget, scans and rescan answer 501; + reads, comments, resolve and the bypass stay open. +- Operator API (`operator/security-routes.ts`, logic in `security/operator.ts`): policy, + status, probe, budget, lists (page/limit, R16), cancel, rescan, backfill, sweeps, fallback, + digest, webhook, provider keys, per-project model/ceiling/policy/finding writes, bypass. + Every write takes `dryRun`; previews of finding, model and ceiling writes run the real + write and roll back. Audit targets hold ids and known values only. +- Admin panel (`admin/security-data.ts`, `admin/routes/security.ts`): Settings, Findings, + Scans, Public requests, Project detail section, Zero Trust page; banner and unseen-bypass + badge through `renderAdminPage`. Writes call the operator functions inside + `executeAuditedMutation`; policy and budget post twice (preview, apply). +- Signed page (`/security/projects/:slug`): 15-min HMAC token (`page-token.ts`) → HttpOnly + path cookie → 303. Access is re-checked on every load; platform Access is not relaxed. + Forms (resolve, comment, model, budget, bypass) check Origin/Referer, then call the same + operations. `Referrer-Policy: same-origin` (not `no-referrer`: that sends `Origin: null` + on the page's own posts). +- Dashboard: `/projects` and `/projects/:slug/security` through `apiClient` (`hc` for paths, + `ProjectSecurity*Body` types from `api.ts` for bodies). +- CLI: `void project security …` (status, list, show, resolve, reopen, comment, severity, + model, budget, scans, scan, check, open, `--format sarif`), `void project zero-trust + bypass`, the deploy notice (one GET, 5 s, prints nothing on any error), the `Security` + line in `void project status`, `void platform security …`, and `--security-audits` on + install, upgrade and repair. Uninstall deletes the scanner (R11). + +### Phase 2 and 3 additions + +- Rescan, backfill, sweeps (M25): rescan is a full `trigger=rescan` scan after a cost + preview; backfill queues up to 50 in-scope projects whose live deployment has no succeeded + scan; sweeps (`sweeps: {on, everyDays}`, off by default) queue `standard`-profile full scans + hourly. Candidates need stored code. +- Fallback (M26): opt-in `fallbackToCf`, one `@cf` scan after a third-party scan ended + `refused`, `timed_out` or `failed (bad_output)`; never `@cf` → third party, never a + fallback of a fallback or of a local check. +- GitHub check (M28, hosted): `Void Security Audit` check run, always `neutral`, counts and + the page link only; a PR comment only while something is urgent; Re-run queues a rescan + only for a sender who could rescan. +- Runtime copy (M30, Engine B): a copy of the live bundle in a separate dispatch namespace + with empty stores, the live D1 schema, fake secrets and stubbed services, reachable only as + `copy.void.internal`. A guard module blocks `fetch` and `WebSocket` from Durable Objects + (S13). `confirmed (runtime)` only when the named request reached the copy. No copy when a + secret value is in the bundle or schema. Deleted after the result and by the hourly sweep. +- Client assets and SARIF (M31): opt-in `--client-assets` rescan reads client source maps + under `_client/`; SARIF 2.1.0 is built in the CLI from the list routes. +- Local check (M32): the CLI uploads git-tracked files (filtered) to a presigned R2 URL; + `trigger=local`, no deployment, full scan; `storeLocalOutcome` writes a short-lived result + file and ends the row only (I12). +- Per-project policy (M34): `inherit | always | never`; `never` never skips a gate scan (D46). +- Severity edits (M35): `severity_override`, event `severity_edited`, revision check; the + reopen rule uses the human value. + +## Milestone index + +| M | What | Main code | +| ------ | ------------------------------------------------ | ------------------------------------------------------------------- | +| M1 | capability, scheduler DO class, config | `packages/platform` manifest / worker config, `scheduler.ts` | +| M2 | shared model list and policy types | `security-models.ts`, `security-policy.ts` | +| M3 | schema and migration 0065 | `security/schema.ts` | +| M4 | policy store and operator policy routes | `policy.ts`, `operator/security-routes.ts` | +| M5 | scanner runner (Engine B) | `security-scanner/src/runner` | +| M6 | controller Worker, provisioning, probe | `security-scanner-controller-runtime.ts`, `probe.ts` | +| M7 | model proxy and budget | `model-proxy.ts`, `budget.ts`, `call-ledger.ts` | +| M8 | outbox enqueue and input hold | `enqueue.ts` | +| M9 | scheduler and hourly jobs | `scheduler.ts`, `queue.ts`, `maintenance.ts`, `models.ts` | +| M10 | input builder (T2, T3, filters, memory) | `security/input/*` | +| M11 | T1 source diff | `input/{t1,t1-github,source-tar}.ts` | +| M12 | ingest and findings | `ingest.ts`, `findings.ts`, `fence.ts` | +| M13 | Engines A and C, images, drift test | `engines/{claude,codex}.ts`, `image/` | +| M13b | engine images in the operator account, dispatch | `provisioning/security-scanner-images.ts`, `scanner-images.json` | +| M14 | project API routes | `routes/project-security.ts`, `project-{view,findings,settings}.ts` | +| M15 | notifications | `notifications.ts`, `recipients.ts`, `email.ts` | +| M16 | scan before public (gate) | `public-gate*.ts`, `exposure.ts`, Zero Trust paths | +| M17 | operator security routes | `operator/security-routes.ts`, `security/operator.ts` | +| M18 | admin panel | `admin/security-data.ts`, `admin/routes/security.ts` | +| M19 | signed project page | `routes/security-page.ts`, `project-page.ts` | +| M20–23 | CLI project, zero-trust, deploy notice, operator | `packages/void/src/cli/*security*` | +| M24 | Phase 1 docs | `docs/` | +| M25 | rescan, backfill, sweeps | `sweeps.ts`, `scan-candidates.ts` | +| M26 | fallback, streak emails, digest, webhooks | `fallback.ts`, `alerts.ts`, `webhook.ts` | +| M27 | per-plan caps | `plan-caps.ts`, plans routes | +| M28 | GitHub check | `github-check.ts`, `routes/webhooks.ts` | +| M29 | page forms and dashboard pages | `routes/security-page.ts`, `platform/packages/dashboard` | +| M30 | runtime checks on a throwaway copy | `runtime-copy*.ts` | +| M31 | secret findings, client assets, SARIF | `input/redact.ts`, `security-sarif.ts` | +| M32 | local check | `local-check.ts`, `input/local.ts` | +| M33 | BYOK | `provider-keys.ts` | +| M34 | per-project policy override | `project-policy.ts` | +| M35 | severity edits | `project-findings.ts` | +| M36 | final docs and full verification | `docs/` | + +## Decisions and known gaps that still matter + +- Admin bypass with the capability off: the route is outside the capability guard. Held + requests are no longer re-checked while off, so the bypass is how an admin releases one. +- A rollback to a deployment with no past scan queues a gate scan when its code is kept, + else `needs_deploy` (safer than spec §12.4). +- Rescan is always a full scan, also for a live deployment with no succeeded scan + (spec §13.3 says diff). +- Gateway cost needs `CF_API_TOKEN` with Analytics read; a failed query leaves the rows + unknown, and after 7 days they stay `NULL`. +- A crash between an email send and the row update sends it twice on retry. Accepted. +- Not built: admin finding detail and resolve forms (spec §13.1; use the CLI or operator API), + deploy `--json` `security` field (R4), the release smoke script. +- Codex `bio policy`, `misalignment policy violation`, `invalid prompt` and `content_filter` + end `failed (infrastructure)` and are retried (product call; none of them opens the gate). + +## Live check status + +| Check | Status | +| ---------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| S1 egress, S1b image copy | S1 results are not recorded here; its egress lock is in M6 and S2 / S3 / S11 check egress again. S1b ran with a small image only (R1); a full engine image copy is unmeasured | +| S2 / S3 lockdown (Engines A / C) | PASS locally through the gateway; live quality BLOCKED (scratch account had no Unified Billing credits) | +| S4 / S8 Engine B quality, cost, time | PASS on the default `@cf/deepseek-ai/deepseek-v4.1-flash-1017` (10/10, 0 false, 8/8 valid); glm-5.3 FAILS | +| S5 static confirmations | PASS (20/20 planted bugs confirmed with a trace) | +| S6 engine parity | Not run (needs Engines A / C live) | +| S7 inputs, S9 refusals, S11 red team | PASS locally after fixes (S7 26/26, S9 24/24, S11 160/160); S9 live refusal rates not run | +| S10 gateway | PASS for no bodies and no cache on REST; binding path and meter vs gateway not run (0094 check A pending) | +| S12 legal | Open for the user (checklist below) | +| S13 runtime copy | PASS (guard added); the M30 copy code itself is not run live | +| BYOK (M33) | Not run live; needs a real provider key. The first live probe with a saved key is the check | +| Engine A / C images | Digests stay `null` until the images are published at release (ghcr, then copied by the probe); until then probe check 5 keeps `openai/*` and `anthropic/*` unpickable | +| Release smoke (`security-smoke-test.ts`) | Not written; to do before release | + +## Phase 0 spike conclusions + +The Phase 0 spikes were one-off scripts. They ran from 2026-11-18 to 2026-11-20 on +scratch accounts (never production) against five seeded apps with planted bugs +(React+D1, Vue+KV, Svelte+auth, Solid+R2, plain Void API). Once their results were +built into the code, the scripts, images and seeded apps were removed. This section +keeps only what they settled. "Live check status" above lists what is still open. + +| Spike | Result | What it settled | +| ---------------------- | ------------------------------------------ | --------------------------------------------------------------------------------------------------- | +| S1 egress, cold start | not recorded | the egress lock is in M6; S2, S3 and S11 check egress again | +| S1b image source | works with a ~2 MB image only | option A of R1 (copy a digest-pinned image into the operator registry); full-size copy time unknown | +| S2 Engine A lockdown | PASS locally through a real gateway | live quality, cost and time BLOCKED (no Unified Billing credits) | +| S3 Engine C lockdown | PASS locally through a real gateway | same block; Codex retries set to 0 | +| S4 Engine B quality | PASS on deepseek, FAIL on glm-5.3 | `@cf/deepseek-ai/deepseek-v4.1-flash-1017` is the default model everywhere | +| S5 static confirmation | PASS (20/20 planted bugs, with a trace) | "confirmed (static)" stays; not every result is a lead | +| S6 engine parity | not run | needs Engines A / C live | +| S7 scan input | PASS (26/26) | source maps cover every first-party server file; M8 covers every go-live path | +| S8 cost and time | PASS (median $0.18, p95 15.7 min, default) | caps 1.2M input / 120k output tokens | +| S9 refusals | PASS after fixes (24/24) | refusal mapping rules below; live refusal rates not run | +| S10 gateway | PASS for no bodies, no cache | cost by `securityScan` tag cannot be read back, so the spend meter is the only cost source | +| S11 red team | PASS after fixes (160/160) | no escape, no egress, no token; caps and server rules hold | +| S12 legal | open | checklist below | +| S13 runtime copy | PASS with a copy guard | a copy is ready in ~9 s and costs ~$0.00001; Durable Objects need the guard | + +### Engines A and C (S2, S3) + +- The engines cannot reach `gateway.ai.cloudflare.com`, `api.cloudflare.com` or + `1.1.1.1`. The token is in no process env and in no file of the container. +- Model names route as planned (`claude-sonnet-5.5` → `anthropic/…`, `gpt-6.1-terra` → + `openai/…`). `@cf` models do not work on `/ai/v1/*`, so there is no free stand-in for + a quality run. +- Engine A on a 402 returns `subtype: "success"` with `is_error: true`, so it is mapped by + `is_error` and the status, not by `subtype`. On a 401 it retries until the wall clock + stops it, so the proxy never passes a 401 through. +- Engine C retries a 402 or 401 five times; `request_max_retries = 0` and + `stream_max_retries = 0`, and the proxy answers repeats after a credits stop itself. + +### Gateway (S10) + +- With logs off and the cache skipped, no request or response body is stored and no + call is cached (also with a caller cache header). +- Third-party calls are always logged (Unified Billing), with metadata only. +- Not run: the binding path, and meter vs gateway cost (needs credits). + +### Engine B quality and cost (S4, S5, S8) + +T2 input, 5 seeded and 3 clean apps, 8 scans per model, runner at the final code: + +| | glm-5.3 | deepseek-v4.1-flash-1017 (default) | +| ---------------------------------- | ----------------------- | ---------------------------------- | +| Planted crit/high found (bar 7/10) | 4/10 | 10/10 | +| False confirmed crit/high (bar 2) | 0 | 0 | +| Valid runs (bar 95%) | 4/8 | 8/8 | +| Calls per scan (bar 80) | median 28, max 78 | median 54, max 72 | +| Cost per scan at list price | median $0.74, max $1.34 | median $0.18, max $0.29 | +| Wall time (bar p95 < 20 min) | p95 19.2 min | p95 15.7 min | + +- One unreadable verify session keeps that candidate as a lead and ends the scan + `incomplete`; Engine B repairs harmless output slips (`coerce.ts`) and gets one retry for + a bad report. +- glm-5.3 still fails the hunt session in half of its scans. It stays in the list and + can be picked. +- `sink_path` is sometimes an expression (`fetch(url)`), not a file path, so ingest and + the UI do not treat it as one. + +### Scan input (S7) + +- Every map entry has `sourcesContent`, and 100% of first-party server files are + readable. Modules with no map go in as built code. +- Workspace packages count as first-party. Registry code matches the installed package + byte for byte. With no lockfile all registry code is sent (input about 2× larger). +- A snapshot is 67–106 R2 objects per deployment, plus 3 per scan. +- GitHub compare lists at most 300 files. At that limit the scan falls back to T2. +- Go-live paths: cutover, protected promotion and post-routing recovery all enqueue a + scan. Rollback and operator repair are not scanned (no new code). + +### Refusals (S9) + +- Codex prints `cyber policy: ` with no code; `classifyCodexRun` compares letters and + digits only, so every spelling ends `refused`. +- The proxy passes the provider's `cyber_policy` 400 on and records a refusal. A 402 stays + a credits stop. +- A refused turn with no report ends `refused`, and fallback to another model is off. +- A session that read no code cannot clear the scan (`bad_output (nothing_read)`). Only + reads that returned non-blank code under `/scan/input` count. +- Remaining risk: a model that reads one file and then declines still looks clean. + +### Red team (S11) + +160 checks with a hostile fake model: tool paths, tar input, MCP, engines, output, +reviewer phrases, egress, caps and ingest. Known risks, recorded and accepted: + +- The reviewer-text check misses split, spaced, homoglyph and zero-width forms. +- A hard link in `/scan/input` would be readable, but the tar input refuses links. +- After two refused reports the MCP server still takes a third (bounded by the 40-call + session cap). +- With a lockfile, app code placed under a registry package path is dropped (a + malicious owner is a non-goal). + +### Runtime copy (S13) + +- 17/17 route checks pass. Ready in about 9 s, deleted in 2–4 s, about $0.00001 per copy. + The copy is not reachable from the internet. +- Durable Objects bypass the outbound Worker, so the copy guard replaces `fetch` and + `WebSocket`. It is not a boundary against code written to escape it; the outbound Worker + stays as the second layer. +- The planted SQL injection and IDOR returned another owner's rows on a copy. A real + outbound call carried the fake key, never the real one. + +The release smoke check still needs one scratch account with Workers Paid, Containers, +Workers AI or AI Gateway credits, Unified Billing, and a token with Containers, +Cloudchamber and AI Gateway / Workers AI permissions. + +### S12 legal checklist (open questions for the user) + +Not decided here. Each needs a written answer before MVP. + +1. Anthropic terms for operators. A self-hosted operator runs Engine A with their own + Cloudflare account and Unified Billing. Who is the "Customer" under the Anthropic + Commercial Terms / Agent SDK terms: the operator, Cloudflare, or VoidZero? Do the + Agent SDK terms allow it inside a product that other people install? +2. Redistributing Claude Code. The Engine A image ships the Claude Code native binary + (via the Agent SDK package) and Void publishes that image on ghcr. Is publishing that + image allowed, or must each operator build or pull it from Anthropic? +3. Codex licence. The Engine C image ships the `codex` binary and the SDK (Apache-2.0, + plus `bwrap`, `codex-code-mode-host` and LGPL voice libraries in the platform + package). Is shipping `LICENSE` enough, or do we need a `NOTICE` and the LGPL texts + (and the source offer for LGPL parts)? +4. OpenAI usage policies. Is automated vulnerability scanning of a customer's own code + allowed for `openai/*` models through Cloudflare? Does `access_programs.cyber: + standard` (sent by the proxy) need an agreement, and is the trusted-access-for-cyber + program needed for scan prompts? +5. Naming. Can docs, UI and CLI say "Claude", "Claude Code", "Codex" or "GPT" (as model + or engine names)? Proposal to check: Void names only ("Engine A / C", "security + audits") and plain model ids, with no third-party names in product names, badges or + the image names. +6. Data terms. Unified Billing sends customer source code to Anthropic / OpenAI through + Cloudflare. Does the provider notice (`SECURITY_PROVIDER_NOTICE_VERSION`) cover what + each provider's terms require (retention, training, zero-data-retention)? + +## Test strategy + +| Fake | Where | +| ---------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------- | +| Fake model server (scripted SSE for Messages, Responses, chat; records requests) | `platform/packages/security-scanner/test/fake-model/server.ts` | +| Fake container (`ctx.container` with `start`, `exec`, `interceptOutboundHttp`, `interceptAllOutboundHttp`) | `platform/packages/api/test/__mocks__/container.ts` | +| Fake scanner controller binding (canned `findings.json`, status, delays, late results) | `test/integration/helpers.ts` (`createFakeSecurityScanner`) | +| Fake AI (`fetch` for `/ai/v1/*`, `env.AI.run`) and `mockCfApi` containers / scanner state | `test/integration/helpers.ts` | + +- Business rules are pure functions with unit tests (tier, filters, redaction, memory, + fingerprint, reopen, budget math, gate judge). Integration tests cover transactions, locks + and route contracts, on the shared PGlite template. +- The real SDKs are not workspace dependencies (about 800 MB of native binaries); they + install only in `image/`. The Docker recorded run is opt-in (`VOID_SCANNER_E2E=1`, CI image + job). +- No live Cloudflare call in `vp test run`. +- Native and Workers Free regression: `cloudflare-deploy.test.ts` (no `/security`, no + `/containers/` request, no AI binding), `cf-version-runner.test.ts` (`body.containers` + undefined), `worker-config.test.ts` (capability off adds only the DO binding and tag), + `project-zero-trust-command.test.ts` (`project security` and `zero-trust bypass` on a + `cloudflare` target throw before any network call). +- The PR keeps its new tests under 10k lines. Each invariant keeps one strong test. + +## Risks and items for the user + +Items that need a user call are marked **(user)**. + +| # | Item | Plan | +| --- | ------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| R1 | **(user)** Image source. A `durable_object` container app only runs `registry.cloudflare.com//…` images. | Engine B uses the managed image plus the streamed runner. Engines A/C: the probe copies a digest-pinned public image from `ghcr.io/voidzero-dev/void-security-scanner-engine-{a,c}` (option A). Pins stay `null` until the user agrees. | +| R2 | One PR vs spec "DO migration one release before the feature". **Decided: single PR.** | The class and its `security-audits-v1` tag ship with the feature, idle while off. A Worker rollback cannot cross that release; roll forward. | +| R3 | **(user)** All three phases in one PR. | Very large review; the user chose one PR. | +| R4 | Deploy `--json` does not exist, so spec "deploy result gains `security`" has nothing to attach to. | Not built. | +| R5 | **(user)** Skill upstream repo URL for "security-audit-skill @ c1c8a8c" is not in the spec or repo. | Prompts and report schema are Void's own until the skill is vendored. | +| R6 | **(user)** Sonnet 5.5 price is missing; the meter needs a price for every model. | Listed but not pickable (`price: null`) until a price is filled in. | +| R7 | **(user)** Legal (S12). | A/C models stay unpickable until S12 is OK; `@cf` + Engine B ship first. | +| R8 | Compensate `post_routing_recovery` writes `live` outside any transaction. | Enqueue there in its own short tx, logged on failure. Gap accepted. | +| R9 | Codex SDK cannot pass the lockdown flags. | Wrapper script via `codexPathOverride`, version checked by the drift test. | +| R10 | REST `/ai/v1/*` needs an AI permission and `cf-aig-gateway-id`; binding calls may ignore the payload-off header (0094 check A). | `@cf` on the binding, third party on REST; probe check 5 names a missing permission; `credentials.md` has the row. | +| R11 | Uninstall keeps platform Workers unless `--purge-resources`; the PRD says uninstall removes the scanner. | Uninstall always deletes the scanner Worker, gate, apps and copied images, found by name and ownership marker. R2 data follows the bucket rule. | +| R12 | Input build runs in the API Worker; large T3 inputs may hit CPU limits. | Modules are read one at a time; S7/S8 stayed in limits. | +| R13 | Local check findings would break reopen and gate rules. | Separate short-lived result (I12). | +| R14 | Does BYOK spend count toward caps? | Yes, metered and counted. | +| R15 | Per-plan caps in `PlanLimits` need the exact key set; the two-release rule cannot fit one PR. | Separate settings key `plans:security-caps` (0094 precedent). | +| R16 | Paging: spec asks for cursors; operator API uses page/limit. | Operator routes keep page/limit; project routes use a cursor. | +| R17 | Old CLI on `void platform upgrade` drops the flag. | Manifest v7 when on (old CLIs refuse). | +| R18 | Cron fast tier is missing on some self-hosted installs. | All security jobs in the hourly tier. | +| R19 | Admin shell has no banner or badge slot. | New shared page data through `renderAdminPage` and fate renders. | +| R20 | Model ids and prices may change before release. | One list in `@void/platform/security-models`, updated per release. | + +Hard or impossible as written in the PRD (flagged, not silently changed): R1, R2, R4, R8, +R15, and the `/internal/security-scans/*` HTTP routes (replaced by RPC with the same +promise: not on the public hostname). diff --git a/platform/meta/design-docs/README.md b/platform/meta/design-docs/README.md index 4c62fb575..0cdc2df6f 100644 --- a/platform/meta/design-docs/README.md +++ b/platform/meta/design-docs/README.md @@ -20,7 +20,7 @@ Public packages are under packages/ and platform implementations are under platf | Builds and GitHub | [Build service](./0010-builds.md), [identity linking](./0074-github-deploy-identity-linking.md), [build logs](./0076-build-logs.md) | | Serving and routing | [Asset fallback](./0066-wfp-asset-r2-fallback.md), [direct R2 uploads](./0068-direct-r2-asset-upload.md), [scoped R2 migration](./0084-scoped-r2-asset-migration.md), [route-aware ISR](./0077-route-aware-isr-ttl.md), [Pages error boundaries](./0093-pages-error-boundaries.md) | | Custom domains | [HTTP certificate validation](./0073-custom-domain-http-dcv-migration.md) | -| Administration | [Operator CLI](./0078-platform-operator-cli.md), [project teams and ownership transfer](./0080-project-teams.md), [project Zero Trust](./0083-project-zero-trust.md), [installation plans](./0090-installation-plans.md) | +| Administration | [Operator CLI](./0078-platform-operator-cli.md), [project teams and ownership transfer](./0080-project-teams.md), [project Zero Trust](./0083-project-zero-trust.md), [installation plans](./0090-installation-plans.md), [security audits](./0095-security-audits.md) | | AI | [Workers AI](./0019-workers-ai.md), [multi-provider AI](./0049-multi-provider-ai.md), [AI Gateway logging policy](./0094-ai-gateway-logging-policy.md) | | Email | [Routing, recovery and delivery](./0078-email-cf-native.md) | | Sandboxes | [Managed Sandbox restoration](./0082-managed-sandbox-restoration.md) | diff --git a/platform/meta/operations.md b/platform/meta/operations.md index 6e39d674e..541b9b8eb 100644 --- a/platform/meta/operations.md +++ b/platform/meta/operations.md @@ -136,7 +136,7 @@ The API and proxy share their JWT signing configuration. Change it as a coordina ## GitHub Deployment Integration -The GitHub App used to build connected repositories is separate from the OAuth application used for platform sign-in. Its repository permissions are Contents read, Metadata read, Pull requests read, and Checks write. +The GitHub App used to build connected repositories is separate from the OAuth application used for platform sign-in. Its repository permissions are Contents read, Metadata read, Pull requests read, and Checks write. With security audits on, the API also publishes a `Void Security Audit` check run (always `neutral`, counts only). Its pull request comment needs Pull requests write; with read only, the API skips the comment and still publishes the check. Subscribe to `push`, `installation`, `installation_repositories`, `pull_request`, `workflow_run`, `check_run`, and `check_suite`. The last two subscriptions deliver requests from GitHub's rerun buttons; granting Checks write alone does not enable those events. An API hostname protected by Access cannot receive these deliveries. Deploy the optional ingress described in [Platform Development](../../docs/guide/platform/development/runtime.md#optional-github-webhook-ingress-for-access-protected-apis) and set the App webhook URL to that environment's isolated `/github` endpoint. Keep `/webhooks/github` only for an API origin that is not Access-protected. diff --git a/platform/packages/api/drizzle/0065_security_audits.sql b/platform/packages/api/drizzle/0065_security_audits.sql new file mode 100644 index 000000000..9192c30bb --- /dev/null +++ b/platform/packages/api/drizzle/0065_security_audits.sql @@ -0,0 +1,313 @@ +CREATE TABLE "project_security_settings" ( + "project_id" text PRIMARY KEY NOT NULL, + "model" text, + "provider_notice_version" integer, + "provider_notice_by_user_id" text, + "provider_notice_at" timestamp with time zone, + "monthly_cap_cents" integer, + "cap_ceiling_cents" integer, + "cap_updated_by_user_id" text, + "cap_updated_at" timestamp with time zone, + "next_finding_number" integer DEFAULT 1 NOT NULL, + "policy_override" text DEFAULT 'inherit' NOT NULL, + "updated_by_user_id" text, + "updated_at" timestamp with time zone DEFAULT now() NOT NULL, + CONSTRAINT "project_security_settings_monthly_cap" CHECK (("project_security_settings"."monthly_cap_cents" IS NULL OR "project_security_settings"."monthly_cap_cents" BETWEEN 0 AND 100000000)), + CONSTRAINT "project_security_settings_cap_ceiling" CHECK (("project_security_settings"."cap_ceiling_cents" IS NULL OR "project_security_settings"."cap_ceiling_cents" BETWEEN 0 AND 100000000)), + CONSTRAINT "project_security_settings_next_finding" CHECK ("project_security_settings"."next_finding_number" > 0), + CONSTRAINT "project_security_settings_policy_override" CHECK (("project_security_settings"."policy_override" IN ('inherit', 'always', 'never'))), + CONSTRAINT "project_security_settings_notice" CHECK (("project_security_settings"."provider_notice_version" IS NULL) = ("project_security_settings"."provider_notice_at" IS NULL)) +); +--> statement-breakpoint +CREATE TABLE "security_finding_events" ( + "id" text PRIMARY KEY NOT NULL, + "finding_id" text NOT NULL, + "project_id" text NOT NULL, + "scan_id" text, + "actor_kind" text NOT NULL, + "actor_user_id" text, + "actor_role" text, + "action" text NOT NULL, + "resolution" text, + "comment" text, + "severity_from" text, + "severity_to" text, + "created_at" timestamp with time zone DEFAULT now() NOT NULL, + CONSTRAINT "security_finding_events_actor_kind" CHECK (("security_finding_events"."actor_kind" IN ('user', 'installation_admin', 'scanner', 'system'))), + CONSTRAINT "security_finding_events_action" CHECK (("security_finding_events"."action" IN ('created', 'seen_again', 'seen_again_stale', 'severity_changed', 'promoted', 'not_seen', 'resolved', 'reopened', 'commented', 'severity_edited'))), + CONSTRAINT "security_finding_events_resolution" CHECK (("security_finding_events"."resolution" IS NULL OR ("security_finding_events"."resolution" IN ('fixed', 'false_positive', 'accepted_risk')))), + CONSTRAINT "security_finding_events_severity_from" CHECK (("security_finding_events"."severity_from" IS NULL OR ("security_finding_events"."severity_from" IN ('critical', 'high', 'medium', 'low', 'informational')))), + CONSTRAINT "security_finding_events_severity_to" CHECK (("security_finding_events"."severity_to" IS NULL OR ("security_finding_events"."severity_to" IN ('critical', 'high', 'medium', 'low', 'informational')))), + CONSTRAINT "security_finding_events_comment" CHECK ("security_finding_events"."comment" IS NULL OR char_length("security_finding_events"."comment") BETWEEN 1 AND 4000) +); +--> statement-breakpoint +CREATE TABLE "security_findings" ( + "id" text PRIMARY KEY NOT NULL, + "project_id" text NOT NULL, + "number" integer NOT NULL, + "fingerprint_key" text NOT NULL, + "model_fingerprint" text, + "verdict" text NOT NULL, + "verdict_source" text DEFAULT 'static' NOT NULL, + "severity" text, + "severity_override" text, + "confidence" text, + "title" text NOT NULL, + "category" text NOT NULL, + "cwe" text, + "file" text, + "line_start" integer, + "line_end" integer, + "detail" jsonb DEFAULT '{}'::jsonb NOT NULL, + "sink_path" text, + "sink_content_hash" text, + "outside_diff" boolean DEFAULT false NOT NULL, + "source" text DEFAULT 'scanner' NOT NULL, + "state" text DEFAULT 'open' NOT NULL, + "resolution" text, + "resolved_by_user_id" text, + "resolved_at" timestamp with time zone, + "resolved_sink_hash" text, + "resolved_severity" text, + "not_seen_in_latest" boolean DEFAULT false NOT NULL, + "possible_duplicate_of" text, + "reopen_count" integer DEFAULT 0 NOT NULL, + "revision" integer DEFAULT 1 NOT NULL, + "fix_checked_scan_id" text, + "first_scan_id" text NOT NULL, + "last_seen_scan_id" text NOT NULL, + "first_deployment_id" text, + "created_at" timestamp with time zone DEFAULT now() NOT NULL, + "updated_at" timestamp with time zone DEFAULT now() NOT NULL, + CONSTRAINT "security_findings_project_number" UNIQUE("project_id","number"), + CONSTRAINT "security_findings_project_fingerprint" UNIQUE("project_id","fingerprint_key"), + CONSTRAINT "security_findings_number" CHECK ("security_findings"."number" > 0), + CONSTRAINT "security_findings_verdict" CHECK (("security_findings"."verdict" IN ('confirmed', 'needs_validation'))), + CONSTRAINT "security_findings_verdict_source" CHECK (("security_findings"."verdict_source" IN ('static', 'runtime'))), + CONSTRAINT "security_findings_severity" CHECK (("security_findings"."severity" IS NULL OR ("security_findings"."severity" IN ('critical', 'high', 'medium', 'low', 'informational')))), + CONSTRAINT "security_findings_severity_override" CHECK (("security_findings"."severity_override" IS NULL OR ("security_findings"."severity_override" IN ('critical', 'high', 'medium', 'low', 'informational')))), + CONSTRAINT "security_findings_resolved_severity" CHECK (("security_findings"."resolved_severity" IS NULL OR ("security_findings"."resolved_severity" IN ('critical', 'high', 'medium', 'low', 'informational')))), + CONSTRAINT "security_findings_source" CHECK (("security_findings"."source" IN ('scanner', 'server'))), + CONSTRAINT "security_findings_state" CHECK (("security_findings"."state" IN ('open', 'resolved'))), + CONSTRAINT "security_findings_resolution" CHECK (("security_findings"."resolution" IS NULL) = ("security_findings"."state" = 'open') AND ("security_findings"."resolution" IS NULL OR ("security_findings"."resolution" IN ('fixed', 'false_positive', 'accepted_risk')))), + CONSTRAINT "security_findings_resolved_at" CHECK ("security_findings"."state" = 'open' OR "security_findings"."resolved_at" IS NOT NULL), + CONSTRAINT "security_findings_counts" CHECK ("security_findings"."reopen_count" >= 0 AND "security_findings"."revision" > 0), + CONSTRAINT "security_findings_lines" CHECK ("security_findings"."line_start" IS NULL OR "security_findings"."line_end" IS NULL OR "security_findings"."line_end" >= "security_findings"."line_start"), + CONSTRAINT "security_findings_detail_size" CHECK (octet_length("security_findings"."detail"::text) <= 32768) +); +--> statement-breakpoint +CREATE TABLE "security_memory_rejected" ( + "project_id" text NOT NULL, + "fingerprint_key" text NOT NULL, + "reason" text NOT NULL, + "scan_id" text NOT NULL, + "created_at" timestamp with time zone DEFAULT now() NOT NULL, + CONSTRAINT "security_memory_rejected_project_id_fingerprint_key_pk" PRIMARY KEY("project_id","fingerprint_key"), + CONSTRAINT "security_memory_rejected_reason" CHECK (octet_length("security_memory_rejected"."reason") <= 1024) +); +--> statement-breakpoint +CREATE TABLE "security_notifications" ( + "id" text PRIMARY KEY NOT NULL, + "kind" text NOT NULL, + "project_id" text, + "scan_ids" text[] DEFAULT '{}'::text[] NOT NULL, + "request_id" text, + "scan_bypass_id" text, + "dedupe_key" text NOT NULL, + "status" text DEFAULT 'pending' NOT NULL, + "attempts" integer DEFAULT 0 NOT NULL, + "next_attempt_at" timestamp with time zone DEFAULT now() NOT NULL, + "created_at" timestamp with time zone DEFAULT now() NOT NULL, + "sent_at" timestamp with time zone, + CONSTRAINT "security_notifications_dedupe_key" UNIQUE("dedupe_key"), + CONSTRAINT "security_notifications_kind" CHECK (("security_notifications"."kind" IN ('findings', 'reopen', 'cap_project', 'cap_platform', 'public_held', 'public_now_public', 'public_canceled', 'scan_bypass', 'streak_project', 'streak_installation', 'digest', 'webhook'))), + CONSTRAINT "security_notifications_status" CHECK (("security_notifications"."status" IN ('pending', 'sent', 'failed', 'skipped'))), + CONSTRAINT "security_notifications_project" CHECK ("security_notifications"."kind" = 'webhook' OR ("security_notifications"."project_id" IS NULL) = ("security_notifications"."kind" IN ('cap_platform', 'streak_installation', 'digest'))), + CONSTRAINT "security_notifications_attempts" CHECK ("security_notifications"."attempts" >= 0) +); +--> statement-breakpoint +CREATE TABLE "security_platform_spend" ( + "month" date PRIMARY KEY NOT NULL, + "spent_nano_usd" bigint DEFAULT 0 NOT NULL, + "reserved_nano_usd" bigint DEFAULT 0 NOT NULL, + "alerted_80_at" timestamp with time zone, + "alerted_100_at" timestamp with time zone, + "updated_at" timestamp with time zone DEFAULT now() NOT NULL, + CONSTRAINT "security_platform_spend_month" CHECK (EXTRACT(DAY FROM "security_platform_spend"."month") = 1), + CONSTRAINT "security_platform_spend_nonnegative" CHECK ("security_platform_spend"."spent_nano_usd" >= 0 AND "security_platform_spend"."reserved_nano_usd" >= 0) +); +--> statement-breakpoint +CREATE TABLE "security_project_events" ( + "id" text PRIMARY KEY NOT NULL, + "project_id" text NOT NULL, + "actor_kind" text NOT NULL, + "actor_user_id" text, + "actor_role" text, + "action" text NOT NULL, + "cap_kind" text, + "old_cents" integer, + "new_cents" integer, + "request_id" text, + "request_state" text, + "created_at" timestamp with time zone DEFAULT now() NOT NULL, + CONSTRAINT "security_project_events_actor_kind" CHECK (("security_project_events"."actor_kind" IN ('user', 'installation_admin', 'system'))), + CONSTRAINT "security_project_events_action" CHECK (("security_project_events"."action" IN ('cap_changed', 'public_requested', 'public_held', 'public_passed', 'public_canceled', 'scan_bypassed', 'protection_on', 'protection_off'))), + CONSTRAINT "security_project_events_cap_kind" CHECK (("security_project_events"."cap_kind" IS NULL OR ("security_project_events"."cap_kind" IN ('own', 'ceiling')))), + CONSTRAINT "security_project_events_old_cents" CHECK (("security_project_events"."old_cents" IS NULL OR "security_project_events"."old_cents" BETWEEN 0 AND 100000000)), + CONSTRAINT "security_project_events_new_cents" CHECK (("security_project_events"."new_cents" IS NULL OR "security_project_events"."new_cents" BETWEEN 0 AND 100000000)), + CONSTRAINT "security_project_events_request_state" CHECK (("security_project_events"."request_state" IS NULL OR ("security_project_events"."request_state" IN ('waiting_scan', 'held_findings', 'held_no_result', 'needs_deploy', 'passed', 'bypassed', 'canceled')))) +); +--> statement-breakpoint +CREATE TABLE "security_project_spend" ( + "project_id" text NOT NULL, + "month" date NOT NULL, + "spent_nano_usd" bigint DEFAULT 0 NOT NULL, + "reserved_nano_usd" bigint DEFAULT 0 NOT NULL, + "scans" integer DEFAULT 0 NOT NULL, + "alerted_80_at" timestamp with time zone, + "alerted_100_at" timestamp with time zone, + "updated_at" timestamp with time zone DEFAULT now() NOT NULL, + CONSTRAINT "security_project_spend_project_id_month_pk" PRIMARY KEY("project_id","month"), + CONSTRAINT "security_project_spend_month" CHECK (EXTRACT(DAY FROM "security_project_spend"."month") = 1), + CONSTRAINT "security_project_spend_nonnegative" CHECK ("security_project_spend"."spent_nano_usd" >= 0 AND "security_project_spend"."reserved_nano_usd" >= 0 AND "security_project_spend"."scans" >= 0) +); +--> statement-breakpoint +CREATE TABLE "security_public_requests" ( + "id" text PRIMARY KEY NOT NULL, + "project_id" text NOT NULL, + "state" text NOT NULL, + "held_reason" text, + "requested_by_user_id" text, + "requested_via" text NOT NULL, + "target_deployment_id" text NOT NULL, + "gate_scan_id" text, + "blockers" integer DEFAULT 0 NOT NULL, + "blocker_ids" text[] DEFAULT '{}'::text[] NOT NULL, + "cancel_cause" text, + "closed_by_user_id" text, + "closed_at" timestamp with time zone, + "revision" integer DEFAULT 1 NOT NULL, + "created_at" timestamp with time zone DEFAULT now() NOT NULL, + "updated_at" timestamp with time zone DEFAULT now() NOT NULL, + CONSTRAINT "security_public_requests_state" CHECK (("security_public_requests"."state" IN ('waiting_scan', 'held_findings', 'held_no_result', 'needs_deploy', 'passed', 'bypassed', 'canceled'))), + CONSTRAINT "security_public_requests_requested_via" CHECK (("security_public_requests"."requested_via" IN ('project', 'admin', 'operator'))), + CONSTRAINT "security_public_requests_cancel_cause" CHECK (("security_public_requests"."cancel_cause" IS NULL) = ("security_public_requests"."state" <> 'canceled') AND ("security_public_requests"."cancel_cause" IS NULL OR ("security_public_requests"."cancel_cause" IN ('protect', 'gate_off', 'policy_off')))), + CONSTRAINT "security_public_requests_closed" CHECK (("security_public_requests"."closed_at" IS NULL) = ("security_public_requests"."state" IN ('waiting_scan', 'held_findings', 'held_no_result', 'needs_deploy'))), + CONSTRAINT "security_public_requests_blockers" CHECK ("security_public_requests"."blockers" >= 0), + CONSTRAINT "security_public_requests_revision" CHECK ("security_public_requests"."revision" > 0) +); +--> statement-breakpoint +CREATE TABLE "security_scan_bypasses" ( + "id" text PRIMARY KEY NOT NULL, + "project_id" text NOT NULL, + "request_id" text NOT NULL, + "deployment_id" text NOT NULL, + "actor_kind" text NOT NULL, + "actor_user_id" text NOT NULL, + "actor_role" text, + "reason" text NOT NULL, + "request_state" text NOT NULL, + "held_reason" text, + "gate_scan_id" text, + "blockers" integer DEFAULT 0 NOT NULL, + "blocker_ids" text[] DEFAULT '{}'::text[] NOT NULL, + "notified_at" timestamp with time zone, + "created_at" timestamp with time zone DEFAULT now() NOT NULL, + CONSTRAINT "security_scan_bypasses_actor_kind" CHECK (("security_scan_bypasses"."actor_kind" IN ('user', 'installation_admin'))), + CONSTRAINT "security_scan_bypasses_reason" CHECK (char_length("security_scan_bypasses"."reason") BETWEEN 1 AND 4000), + CONSTRAINT "security_scan_bypasses_request_state" CHECK (("security_scan_bypasses"."request_state" IN ('waiting_scan', 'held_no_result', 'needs_deploy'))), + CONSTRAINT "security_scan_bypasses_blockers" CHECK ("security_scan_bypasses"."blockers" >= 0) +); +--> statement-breakpoint +CREATE TABLE "security_scans" ( + "id" text PRIMARY KEY NOT NULL, + "project_id" text NOT NULL, + "deployment_id" text, + "base_deployment_id" text, + "base_scan_id" text, + "status" text NOT NULL, + "status_reason" text, + "failure_cause" text, + "error_class" text, + "refusal_category" text, + "superseded_by_scan_id" text, + "trigger" text NOT NULL, + "public_request_id" text, + "tier" text, + "coverage" text, + "coverage_notes" text[] DEFAULT '{}'::text[] NOT NULL, + "backlog_files" integer DEFAULT 0 NOT NULL, + "dropped_files" integer DEFAULT 0 NOT NULL, + "dropped_bytes" bigint DEFAULT 0 NOT NULL, + "files_scanned" integer DEFAULT 0 NOT NULL, + "input_bytes" bigint DEFAULT 0 NOT NULL, + "input_prefix" text, + "input_r2_key" text, + "ledger_summary" jsonb, + "model_requested" text, + "model_used" text, + "engine" text, + "engine_version" text, + "skill_commit" text, + "policy_mode_at_enqueue" text, + "public_at_enqueue" boolean, + "attempt" integer DEFAULT 0 NOT NULL, + "lease_until" timestamp with time zone, + "model_calls" integer DEFAULT 0 NOT NULL, + "tokens_in" bigint DEFAULT 0 NOT NULL, + "tokens_out" bigint DEFAULT 0 NOT NULL, + "cost_nano_usd" bigint, + "metered_nano_usd" bigint DEFAULT 0 NOT NULL, + "reserved_nano_usd" bigint DEFAULT 0 NOT NULL, + "summary" text, + "first_queued_at" timestamp with time zone, + "queued_at" timestamp with time zone, + "started_at" timestamp with time zone, + "finished_at" timestamp with time zone, + "notified_at" timestamp with time zone, + "created_at" timestamp with time zone DEFAULT now() NOT NULL, + CONSTRAINT "security_scans_status" CHECK (("security_scans"."status" IN ('pending_input', 'queued', 'running', 'succeeded', 'incomplete', 'failed', 'refused', 'timed_out', 'superseded', 'skipped', 'canceled'))), + CONSTRAINT "security_scans_trigger" CHECK (("security_scans"."trigger" IN ('deploy', 'recovery', 'exposure', 'rescan', 'gate', 'local', 'sweep', 'backfill', 'fallback'))), + CONSTRAINT "security_scans_deployment" CHECK ("security_scans"."deployment_id" IS NOT NULL OR "security_scans"."trigger" = 'local'), + CONSTRAINT "security_scans_failure_cause" CHECK (("security_scans"."failure_cause" IS NULL OR ("security_scans"."failure_cause" IN ('installation', 'project')))), + CONSTRAINT "security_scans_tier" CHECK (("security_scans"."tier" IS NULL OR ("security_scans"."tier" IN ('source_diff', 'built_diff', 'full')))), + CONSTRAINT "security_scans_coverage" CHECK (("security_scans"."coverage" IS NULL OR ("security_scans"."coverage" IN ('complete', 'partial')))), + CONSTRAINT "security_scans_engine" CHECK (("security_scans"."engine" IS NULL OR ("security_scans"."engine" IN ('void_loop', 'agent_sdk', 'codex_sdk')))), + CONSTRAINT "security_scans_policy_mode" CHECK (("security_scans"."policy_mode_at_enqueue" IS NULL OR ("security_scans"."policy_mode_at_enqueue" IN ('disabled', 'public', 'all')))), + CONSTRAINT "security_scans_running_lease" CHECK ("security_scans"."status" <> 'running' OR "security_scans"."lease_until" IS NOT NULL), + CONSTRAINT "security_scans_counts" CHECK ("security_scans"."attempt" >= 0 AND "security_scans"."backlog_files" >= 0 AND "security_scans"."dropped_files" >= 0 AND "security_scans"."dropped_bytes" >= 0 AND "security_scans"."files_scanned" >= 0 AND "security_scans"."input_bytes" >= 0 AND "security_scans"."model_calls" >= 0 AND "security_scans"."tokens_in" >= 0 AND "security_scans"."tokens_out" >= 0 AND "security_scans"."metered_nano_usd" >= 0 AND "security_scans"."reserved_nano_usd" >= 0 AND ("security_scans"."cost_nano_usd" IS NULL OR "security_scans"."cost_nano_usd" >= 0)), + CONSTRAINT "security_scans_ledger_size" CHECK ("security_scans"."ledger_summary" IS NULL OR octet_length("security_scans"."ledger_summary"::text) <= 8192), + CONSTRAINT "security_scans_summary_size" CHECK ("security_scans"."summary" IS NULL OR octet_length("security_scans"."summary") <= 16384) +); +--> statement-breakpoint +ALTER TABLE "project_security_settings" ADD CONSTRAINT "project_security_settings_project_id_projects_id_fk" FOREIGN KEY ("project_id") REFERENCES "public"."projects"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint +ALTER TABLE "security_finding_events" ADD CONSTRAINT "security_finding_events_finding_id_security_findings_id_fk" FOREIGN KEY ("finding_id") REFERENCES "public"."security_findings"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint +ALTER TABLE "security_finding_events" ADD CONSTRAINT "security_finding_events_project_id_projects_id_fk" FOREIGN KEY ("project_id") REFERENCES "public"."projects"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint +ALTER TABLE "security_findings" ADD CONSTRAINT "security_findings_project_id_projects_id_fk" FOREIGN KEY ("project_id") REFERENCES "public"."projects"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint +ALTER TABLE "security_memory_rejected" ADD CONSTRAINT "security_memory_rejected_project_id_projects_id_fk" FOREIGN KEY ("project_id") REFERENCES "public"."projects"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint +ALTER TABLE "security_notifications" ADD CONSTRAINT "security_notifications_project_id_projects_id_fk" FOREIGN KEY ("project_id") REFERENCES "public"."projects"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint +ALTER TABLE "security_project_events" ADD CONSTRAINT "security_project_events_project_id_projects_id_fk" FOREIGN KEY ("project_id") REFERENCES "public"."projects"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint +ALTER TABLE "security_project_spend" ADD CONSTRAINT "security_project_spend_project_id_projects_id_fk" FOREIGN KEY ("project_id") REFERENCES "public"."projects"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint +ALTER TABLE "security_public_requests" ADD CONSTRAINT "security_public_requests_project_id_projects_id_fk" FOREIGN KEY ("project_id") REFERENCES "public"."projects"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint +ALTER TABLE "security_scan_bypasses" ADD CONSTRAINT "security_scan_bypasses_project_id_projects_id_fk" FOREIGN KEY ("project_id") REFERENCES "public"."projects"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint +ALTER TABLE "security_scan_bypasses" ADD CONSTRAINT "security_scan_bypasses_request_fk" FOREIGN KEY ("request_id") REFERENCES "public"."security_public_requests"("id") ON DELETE no action ON UPDATE no action;--> statement-breakpoint +ALTER TABLE "security_scans" ADD CONSTRAINT "security_scans_project_id_projects_id_fk" FOREIGN KEY ("project_id") REFERENCES "public"."projects"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint +CREATE INDEX "idx_security_finding_events_project_created" ON "security_finding_events" USING btree ("project_id","created_at");--> statement-breakpoint +CREATE INDEX "idx_security_finding_events_finding_created" ON "security_finding_events" USING btree ("finding_id","created_at");--> statement-breakpoint +CREATE INDEX "idx_security_findings_urgent" ON "security_findings" USING btree ("project_id") WHERE "security_findings"."verdict" = 'confirmed' AND COALESCE("security_findings"."severity_override", "security_findings"."severity") IN ('critical', 'high') AND "security_findings"."state" = 'open';--> statement-breakpoint +CREATE INDEX "idx_security_findings_project_state" ON "security_findings" USING btree ("project_id","state","number");--> statement-breakpoint +CREATE INDEX "idx_security_memory_rejected_project_created" ON "security_memory_rejected" USING btree ("project_id","created_at");--> statement-breakpoint +CREATE INDEX "idx_security_notifications_due" ON "security_notifications" USING btree ("next_attempt_at") WHERE "security_notifications"."status" = 'pending';--> statement-breakpoint +CREATE INDEX "idx_security_notifications_project_created" ON "security_notifications" USING btree ("project_id","created_at");--> statement-breakpoint +CREATE INDEX "idx_security_project_events_project_created" ON "security_project_events" USING btree ("project_id","created_at");--> statement-breakpoint +CREATE UNIQUE INDEX "security_public_requests_open_project" ON "security_public_requests" USING btree ("project_id") WHERE ("security_public_requests"."state" IN ('waiting_scan', 'held_findings', 'held_no_result', 'needs_deploy'));--> statement-breakpoint +CREATE INDEX "idx_security_public_requests_state_updated" ON "security_public_requests" USING btree ("state","updated_at");--> statement-breakpoint +CREATE INDEX "idx_security_public_requests_project_created" ON "security_public_requests" USING btree ("project_id","created_at");--> statement-breakpoint +CREATE INDEX "idx_security_scan_bypasses_created" ON "security_scan_bypasses" USING btree ("created_at");--> statement-breakpoint +CREATE INDEX "idx_security_scan_bypasses_project_created" ON "security_scan_bypasses" USING btree ("project_id","created_at");--> statement-breakpoint +CREATE INDEX "idx_security_scan_bypasses_request" ON "security_scan_bypasses" USING btree ("request_id");--> statement-breakpoint +CREATE INDEX "idx_security_scans_project_status_finished" ON "security_scans" USING btree ("project_id","status","finished_at");--> statement-breakpoint +CREATE UNIQUE INDEX "security_scans_running_project" ON "security_scans" USING btree ("project_id") WHERE "security_scans"."status" = 'running';--> statement-breakpoint +CREATE INDEX "idx_security_scans_waiting" ON "security_scans" USING btree ("status","first_queued_at") WHERE ("security_scans"."status" IN ('pending_input', 'queued', 'running'));--> statement-breakpoint +CREATE INDEX "idx_security_scans_input_hold" ON "security_scans" USING btree ("input_prefix") WHERE "security_scans"."input_prefix" IS NOT NULL AND ("security_scans"."status" IN ('pending_input', 'queued'));--> statement-breakpoint +CREATE INDEX "idx_security_scans_deployment" ON "security_scans" USING btree ("project_id","deployment_id"); \ No newline at end of file diff --git a/platform/packages/api/drizzle/meta/0065_snapshot.json b/platform/packages/api/drizzle/meta/0065_snapshot.json new file mode 100644 index 000000000..184ae2daf --- /dev/null +++ b/platform/packages/api/drizzle/meta/0065_snapshot.json @@ -0,0 +1,9218 @@ +{ + "id": "77c6fbc3-2ba1-493c-8951-aee22de2ec14", + "prevId": "d44eb65a-5b9e-451f-95ed-5ed78f2aee35", + "version": "7", + "dialect": "postgresql", + "tables": { + "public.auth_codes": { + "name": "auth_codes", + "schema": "", + "columns": { + "code": { + "name": "code", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "jwt": { + "name": "jwt", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "cli_state": { + "name": "cli_state", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "code_challenge": { + "name": "code_challenge", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "code_challenge_method": { + "name": "code_challenge_method", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "expires_at": { + "name": "expires_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.builds": { + "name": "builds", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "project_id": { + "name": "project_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "executor": { + "name": "executor", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'container'" + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'queued'" + }, + "commit_sha": { + "name": "commit_sha", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "branch": { + "name": "branch", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "deployment_id": { + "name": "deployment_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "github_run_id": { + "name": "github_run_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "github_run_attempt": { + "name": "github_run_attempt", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "logs_url": { + "name": "logs_url", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "check_run_id": { + "name": "check_run_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "error": { + "name": "error", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "exit_code": { + "name": "exit_code", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "instance_type": { + "name": "instance_type", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "started_at": { + "name": "started_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "completed_at": { + "name": "completed_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "idx_builds_project_created": { + "name": "idx_builds_project_created", + "columns": [ + { + "expression": "project_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "idx_builds_status": { + "name": "idx_builds_status", + "columns": [ + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "idx_builds_user_status": { + "name": "idx_builds_user_status", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "idx_builds_project_github_run_id": { + "name": "idx_builds_project_github_run_id", + "columns": [ + { + "expression": "project_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "github_run_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "github_run_attempt", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "\"builds\".\"github_run_id\" IS NOT NULL AND \"builds\".\"github_run_attempt\" IS NOT NULL AND \"builds\".\"status\" IN ('starting', 'building', 'deploying')", + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "builds_project_id_projects_id_fk": { + "name": "builds_project_id_projects_id_fk", + "tableFrom": "builds", + "tableTo": "projects", + "columnsFrom": ["project_id"], + "columnsTo": ["id"], + "onDelete": "no action", + "onUpdate": "no action" + }, + "builds_user_id_users_id_fk": { + "name": "builds_user_id_users_id_fk", + "tableFrom": "builds", + "tableTo": "users", + "columnsFrom": ["user_id"], + "columnsTo": ["id"], + "onDelete": "no action", + "onUpdate": "no action" + }, + "builds_deployment_id_deployments_id_fk": { + "name": "builds_deployment_id_deployments_id_fk", + "tableFrom": "builds", + "tableTo": "deployments", + "columnsFrom": ["deployment_id"], + "columnsTo": ["id"], + "onDelete": "no action", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.deployment_operations": { + "name": "deployment_operations", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "project_id": { + "name": "project_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "actor_id": { + "name": "actor_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "build_id": { + "name": "build_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "original_active_id": { + "name": "original_active_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "cli_version": { + "name": "cli_version", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "idempotency_key": { + "name": "idempotency_key", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "input_digest": { + "name": "input_digest", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "input_prefix": { + "name": "input_prefix", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "payload": { + "name": "payload", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'queued'" + }, + "owner_id": { + "name": "owner_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "lease_expires_at": { + "name": "lease_expires_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "next_dispatch_at": { + "name": "next_dispatch_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "events": { + "name": "events", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'[]'::jsonb" + }, + "last_seq": { + "name": "last_seq", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "inputs_deleted": { + "name": "inputs_deleted", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "idx_deployment_operations_key": { + "name": "idx_deployment_operations_key", + "columns": [ + { + "expression": "project_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "actor_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "idempotency_key", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "idx_deployment_operations_dispatch": { + "name": "idx_deployment_operations_dispatch", + "columns": [ + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "next_dispatch_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "deployment_operations_project_id_projects_id_fk": { + "name": "deployment_operations_project_id_projects_id_fk", + "tableFrom": "deployment_operations", + "tableTo": "projects", + "columnsFrom": ["project_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.deployments": { + "name": "deployments", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "project_id": { + "name": "project_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'pending'" + }, + "manifest": { + "name": "manifest", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "source": { + "name": "source", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "commit": { + "name": "commit", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "repository_url": { + "name": "repository_url", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "commit_url": { + "name": "commit_url", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "git_ref": { + "name": "git_ref", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "cli_version": { + "name": "cli_version", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "admission_protocol": { + "name": "admission_protocol", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "error_message": { + "name": "error_message", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "asset_hashes": { + "name": "asset_hashes", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "deployed_at": { + "name": "deployed_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "retained": { + "name": "retained", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "applied_migrations": { + "name": "applied_migrations", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "bundle_stored": { + "name": "bundle_stored", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "billing_user_id": { + "name": "billing_user_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "initiated_by_user_id": { + "name": "initiated_by_user_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "proxy_token_gen": { + "name": "proxy_token_gen", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + } + }, + "indexes": { + "idx_deployments_project_id": { + "name": "idx_deployments_project_id", + "columns": [ + { + "expression": "project_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "idx_deployments_project_status": { + "name": "idx_deployments_project_status", + "columns": [ + { + "expression": "project_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "idx_deployments_created_id": { + "name": "idx_deployments_created_id", + "columns": [ + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "deployments_project_id_projects_id_fk": { + "name": "deployments_project_id_projects_id_fk", + "tableFrom": "deployments", + "tableTo": "projects", + "columnsFrom": ["project_id"], + "columnsTo": ["id"], + "onDelete": "no action", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.domains": { + "name": "domains", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "project_id": { + "name": "project_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "hostname": { + "name": "hostname", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "cf_hostname_id": { + "name": "cf_hostname_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'pending'" + }, + "verification_data": { + "name": "verification_data", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "idx_domains_project_id": { + "name": "idx_domains_project_id", + "columns": [ + { + "expression": "project_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "domains_project_id_projects_id_fk": { + "name": "domains_project_id_projects_id_fk", + "tableFrom": "domains", + "tableTo": "projects", + "columnsFrom": ["project_id"], + "columnsTo": ["id"], + "onDelete": "no action", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "domains_hostname_unique": { + "name": "domains_hostname_unique", + "nullsNotDistinct": false, + "columns": ["hostname"] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.email_destination_cleanups": { + "name": "email_destination_cleanups", + "schema": "", + "columns": { + "cf_destination_id": { + "name": "cf_destination_id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'pending'" + }, + "attempts": { + "name": "attempts", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "next_attempt_at": { + "name": "next_attempt_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "lease_started_at": { + "name": "lease_started_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "idx_email_destination_cleanups_due": { + "name": "idx_email_destination_cleanups_due", + "columns": [ + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "next_attempt_at", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "updated_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "email_destination_cleanups_status_check": { + "name": "email_destination_cleanups_status_check", + "value": "\"email_destination_cleanups\".\"status\" IN ('pending', 'deleting', 'completed')" + }, + "email_destination_cleanups_attempts_check": { + "name": "email_destination_cleanups_attempts_check", + "value": "\"email_destination_cleanups\".\"attempts\" >= 0" + } + }, + "isRLSEnabled": false + }, + "public.email_destinations": { + "name": "email_destinations", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "project_id": { + "name": "project_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "address": { + "name": "address", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'pending'" + }, + "cf_destination_id": { + "name": "cf_destination_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "verified_at": { + "name": "verified_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "verification_source": { + "name": "verification_source", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'cf'" + }, + "verified_by_user_id": { + "name": "verified_by_user_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "verified_by_email_snapshot": { + "name": "verified_by_email_snapshot", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "idx_email_destinations_project_id": { + "name": "idx_email_destinations_project_id", + "columns": [ + { + "expression": "project_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "idx_email_destinations_cf_destination_id": { + "name": "idx_email_destinations_cf_destination_id", + "columns": [ + { + "expression": "cf_destination_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "idx_email_destinations_verified_by_user_id": { + "name": "idx_email_destinations_verified_by_user_id", + "columns": [ + { + "expression": "verified_by_user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "verified_by_email_snapshot", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "email_destinations_project_id_projects_id_fk": { + "name": "email_destinations_project_id_projects_id_fk", + "tableFrom": "email_destinations", + "tableTo": "projects", + "columnsFrom": ["project_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "email_destinations_verified_by_user_id_users_id_fk": { + "name": "email_destinations_verified_by_user_id_users_id_fk", + "tableFrom": "email_destinations", + "tableTo": "users", + "columnsFrom": ["verified_by_user_id"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "email_destinations_project_address_uq": { + "name": "email_destinations_project_address_uq", + "nullsNotDistinct": false, + "columns": ["project_id", "address"] + } + }, + "policies": {}, + "checkConstraints": { + "email_destinations_status_check": { + "name": "email_destinations_status_check", + "value": "\"email_destinations\".\"status\" IN ('pending', 'verified')" + }, + "email_destinations_verification_source_check": { + "name": "email_destinations_verification_source_check", + "value": "\"email_destinations\".\"verification_source\" IN ('cf', 'platform')" + } + }, + "isRLSEnabled": false + }, + "public.email_domains": { + "name": "email_domains", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "project_id": { + "name": "project_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "domain": { + "name": "domain", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "zone_id": { + "name": "zone_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "account_id": { + "name": "account_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "mode": { + "name": "mode", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'pending'" + }, + "credential_kind": { + "name": "credential_kind", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "token_ciphertext": { + "name": "token_ciphertext", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "token_iv": { + "name": "token_iv", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "token_key_version": { + "name": "token_key_version", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "managed_by": { + "name": "managed_by", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'owner'" + }, + "relay_ciphertext": { + "name": "relay_ciphertext", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "relay_iv": { + "name": "relay_iv", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "relay_key_version": { + "name": "relay_key_version", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "relay_worker_name": { + "name": "relay_worker_name", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "relay_version": { + "name": "relay_version", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "token_id": { + "name": "token_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "token_expires_on": { + "name": "token_expires_on", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "attempt_id": { + "name": "attempt_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "setup_state": { + "name": "setup_state", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "idx_email_domains_project_id": { + "name": "idx_email_domains_project_id", + "columns": [ + { + "expression": "project_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "email_domains_zone_uq": { + "name": "email_domains_zone_uq", + "columns": [ + { + "expression": "zone_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "\"email_domains\".\"zone_id\" IS NOT NULL AND \"email_domains\".\"status\" IN ('active', 'pending')", + "concurrently": false, + "method": "btree", + "with": {} + }, + "email_domains_relay_uq": { + "name": "email_domains_relay_uq", + "columns": [ + { + "expression": "account_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "relay_worker_name", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "\"email_domains\".\"relay_worker_name\" IS NOT NULL", + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "email_domains_project_id_projects_id_fk": { + "name": "email_domains_project_id_projects_id_fk", + "tableFrom": "email_domains", + "tableTo": "projects", + "columnsFrom": ["project_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "email_domains_domain_uq": { + "name": "email_domains_domain_uq", + "nullsNotDistinct": false, + "columns": ["domain"] + } + }, + "policies": {}, + "checkConstraints": { + "email_domains_mode_check": { + "name": "email_domains_mode_check", + "value": "\"email_domains\".\"mode\" IN ('apex', 'subdomain')" + }, + "email_domains_status_check": { + "name": "email_domains_status_check", + "value": "\"email_domains\".\"status\" IN ('pending', 'active', 'token_revoked', 'token_expired', 'failed')" + }, + "email_domains_credential_kind_check": { + "name": "email_domains_credential_kind_check", + "value": "\"email_domains\".\"credential_kind\" IN ('oauth_grant', 'api_token', 'platform')" + }, + "email_domains_platform_token_check": { + "name": "email_domains_platform_token_check", + "value": "(\"email_domains\".\"credential_kind\" = 'platform' AND \"email_domains\".\"token_ciphertext\" IS NULL AND \"email_domains\".\"token_iv\" IS NULL AND \"email_domains\".\"token_key_version\" IS NULL) OR (\"email_domains\".\"credential_kind\" <> 'platform' AND \"email_domains\".\"token_ciphertext\" IS NOT NULL AND \"email_domains\".\"token_iv\" IS NOT NULL AND \"email_domains\".\"token_key_version\" IS NOT NULL)" + }, + "email_domains_managed_by_check": { + "name": "email_domains_managed_by_check", + "value": "\"email_domains\".\"managed_by\" IN ('owner', 'admin')" + } + }, + "isRLSEnabled": false + }, + "public.github_connections": { + "name": "github_connections", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "project_id": { + "name": "project_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "installation_id": { + "name": "installation_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "repo_full_name": { + "name": "repo_full_name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "repository_id": { + "name": "repository_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "authorized_by_user_id": { + "name": "authorized_by_user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "branch": { + "name": "branch", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'main'" + }, + "build_executor": { + "name": "build_executor", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'container'" + }, + "workflow_path": { + "name": "workflow_path", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'.github/workflows/void-deploy.yml'" + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "idx_github_connections_installation_id": { + "name": "idx_github_connections_installation_id", + "columns": [ + { + "expression": "installation_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "idx_github_connections_repo_full_name": { + "name": "idx_github_connections_repo_full_name", + "columns": [ + { + "expression": "repo_full_name", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "idx_github_connections_installation_repo_id": { + "name": "idx_github_connections_installation_repo_id", + "columns": [ + { + "expression": "installation_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "repository_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "github_connections_project_id_projects_id_fk": { + "name": "github_connections_project_id_projects_id_fk", + "tableFrom": "github_connections", + "tableTo": "projects", + "columnsFrom": ["project_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "github_connections_authorized_by_user_id_users_id_fk": { + "name": "github_connections_authorized_by_user_id_users_id_fk", + "tableFrom": "github_connections", + "tableTo": "users", + "columnsFrom": ["authorized_by_user_id"], + "columnsTo": ["id"], + "onDelete": "no action", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "github_connections_project_id_unique": { + "name": "github_connections_project_id_unique", + "nullsNotDistinct": false, + "columns": ["project_id"] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.github_installation_members": { + "name": "github_installation_members", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "installation_id": { + "name": "installation_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "github_account_id": { + "name": "github_account_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "verified_at": { + "name": "verified_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "expires_at": { + "name": "expires_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "idx_github_installation_members_install_user": { + "name": "idx_github_installation_members_install_user", + "columns": [ + { + "expression": "installation_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "idx_github_installation_members_user_id": { + "name": "idx_github_installation_members_user_id", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "github_installation_members_user_id_users_id_fk": { + "name": "github_installation_members_user_id_users_id_fk", + "tableFrom": "github_installation_members", + "tableTo": "users", + "columnsFrom": ["user_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.github_installation_revocations": { + "name": "github_installation_revocations", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "installation_id": { + "name": "installation_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "github_account_id": { + "name": "github_account_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "revoked_at": { + "name": "revoked_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "idx_github_installation_revocations_install_account": { + "name": "idx_github_installation_revocations_install_account", + "columns": [ + { + "expression": "installation_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "github_account_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.github_installations": { + "name": "github_installations", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "installation_id": { + "name": "installation_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "account_login": { + "name": "account_login", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "account_id": { + "name": "account_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "account_type": { + "name": "account_type", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "repositories": { + "name": "repositories", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'[]'::jsonb" + }, + "repository_selection": { + "name": "repository_selection", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'selected'" + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'active'" + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "idx_github_installations_user_id": { + "name": "idx_github_installations_user_id", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "idx_github_installations_account_id": { + "name": "idx_github_installations_account_id", + "columns": [ + { + "expression": "account_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "github_installations_user_id_users_id_fk": { + "name": "github_installations_user_id_users_id_fk", + "tableFrom": "github_installations", + "tableTo": "users", + "columnsFrom": ["user_id"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "github_installations_installation_id_unique": { + "name": "github_installations_installation_id_unique", + "nullsNotDistinct": false, + "columns": ["installation_id"] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.github_webhook_redeliveries": { + "name": "github_webhook_redeliveries", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "guid": { + "name": "guid", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "delivery_id": { + "name": "delivery_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "event": { + "name": "event", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "status_code": { + "name": "status_code", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "redelivered_at": { + "name": "redelivered_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "idx_github_webhook_redeliveries_guid": { + "name": "idx_github_webhook_redeliveries_guid", + "columns": [ + { + "expression": "guid", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.invitations": { + "name": "invitations", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "email": { + "name": "email", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'pending'" + }, + "email_delivery_status": { + "name": "email_delivery_status", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "invited_by": { + "name": "invited_by", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "accepted_by": { + "name": "accepted_by", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "revoked_at": { + "name": "revoked_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "revoked_by": { + "name": "revoked_by", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "accepted_at": { + "name": "accepted_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "idx_invitations_email": { + "name": "idx_invitations_email", + "columns": [ + { + "expression": "email", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "idx_invitations_status": { + "name": "idx_invitations_status", + "columns": [ + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "invitations_email_delivery_status_check": { + "name": "invitations_email_delivery_status_check", + "value": "\"invitations\".\"email_delivery_status\" IS NULL OR \"invitations\".\"email_delivery_status\" IN ('sent', 'failed', 'unavailable')" + } + }, + "isRLSEnabled": false + }, + "public.migration_renames": { + "name": "migration_renames", + "schema": "", + "columns": { + "project_id": { + "name": "project_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "from_name": { + "name": "from_name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "to_name": { + "name": "to_name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "idx_migration_renames_project_id": { + "name": "idx_migration_renames_project_id", + "columns": [ + { + "expression": "project_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "migration_renames_project_id_projects_id_fk": { + "name": "migration_renames_project_id_projects_id_fk", + "tableFrom": "migration_renames", + "tableTo": "projects", + "columnsFrom": ["project_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "migration_renames_project_id_from_name_to_name_pk": { + "name": "migration_renames_project_id_from_name_to_name_pk", + "columns": ["project_id", "from_name", "to_name"] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.oauth_accounts": { + "name": "oauth_accounts", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "provider": { + "name": "provider", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "provider_id": { + "name": "provider_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "idx_oauth_accounts_provider_id": { + "name": "idx_oauth_accounts_provider_id", + "columns": [ + { + "expression": "provider", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "provider_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "idx_oauth_accounts_user_id": { + "name": "idx_oauth_accounts_user_id", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "oauth_accounts_user_id_users_id_fk": { + "name": "oauth_accounts_user_id_users_id_fk", + "tableFrom": "oauth_accounts", + "tableTo": "users", + "columnsFrom": ["user_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.oauth_clients": { + "name": "oauth_clients", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "operator": { + "name": "operator", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "redirect_uris": { + "name": "redirect_uris", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "scopes": { + "name": "scopes", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "secret_hash": { + "name": "secret_hash", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "enabled": { + "name": "enabled", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.oauth_grants": { + "name": "oauth_grants", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "client_id": { + "name": "client_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "session": { + "name": "session", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "scopes": { + "name": "scopes", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'[\"profile\"]'::jsonb" + }, + "token_hash": { + "name": "token_hash", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "expires_at": { + "name": "expires_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true + }, + "revoked_at": { + "name": "revoked_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "oauth_grants_token": { + "name": "oauth_grants_token", + "columns": [ + { + "expression": "token_hash", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "oauth_grants_user": { + "name": "oauth_grants_user", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "oauth_grants_expiry": { + "name": "oauth_grants_expiry", + "columns": [ + { + "expression": "expires_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "oauth_grants_client_id_oauth_clients_id_fk": { + "name": "oauth_grants_client_id_oauth_clients_id_fk", + "tableFrom": "oauth_grants", + "tableTo": "oauth_clients", + "columnsFrom": ["client_id"], + "columnsTo": ["id"], + "onDelete": "no action", + "onUpdate": "no action" + }, + "oauth_grants_user_id_users_id_fk": { + "name": "oauth_grants_user_id_users_id_fk", + "tableFrom": "oauth_grants", + "tableTo": "users", + "columnsFrom": ["user_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.oauth_nonces": { + "name": "oauth_nonces", + "schema": "", + "columns": { + "nonce": { + "name": "nonce", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "expires_at": { + "name": "expires_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.oauth_refresh_tokens": { + "name": "oauth_refresh_tokens", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "grant_id": { + "name": "grant_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "token_hash": { + "name": "token_hash", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "expires_at": { + "name": "expires_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true + }, + "used_at": { + "name": "used_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "oauth_refresh_tokens_token": { + "name": "oauth_refresh_tokens_token", + "columns": [ + { + "expression": "token_hash", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "oauth_refresh_tokens_grant": { + "name": "oauth_refresh_tokens_grant", + "columns": [ + { + "expression": "grant_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "oauth_refresh_tokens_expiry": { + "name": "oauth_refresh_tokens_expiry", + "columns": [ + { + "expression": "expires_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "oauth_refresh_tokens_grant_id_oauth_grants_id_fk": { + "name": "oauth_refresh_tokens_grant_id_oauth_grants_id_fk", + "tableFrom": "oauth_refresh_tokens", + "tableTo": "oauth_grants", + "columnsFrom": ["grant_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.oauth_requests": { + "name": "oauth_requests", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "client_id": { + "name": "client_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "browser_hash": { + "name": "browser_hash", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "data": { + "name": "data", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "code_hash": { + "name": "code_hash", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "code_expires_at": { + "name": "code_expires_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "approved_at": { + "name": "approved_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "consumed_at": { + "name": "consumed_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "expires_at": { + "name": "expires_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true + } + }, + "indexes": { + "oauth_requests_code": { + "name": "oauth_requests_code", + "columns": [ + { + "expression": "code_hash", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "oauth_requests_expiry": { + "name": "oauth_requests_expiry", + "columns": [ + { + "expression": "expires_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "oauth_requests_client_id_oauth_clients_id_fk": { + "name": "oauth_requests_client_id_oauth_clients_id_fk", + "tableFrom": "oauth_requests", + "tableTo": "oauth_clients", + "columnsFrom": ["client_id"], + "columnsTo": ["id"], + "onDelete": "no action", + "onUpdate": "no action" + }, + "oauth_requests_user_id_users_id_fk": { + "name": "oauth_requests_user_id_users_id_fk", + "tableFrom": "oauth_requests", + "tableTo": "users", + "columnsFrom": ["user_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.operator_events": { + "name": "operator_events", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "login": { + "name": "login", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "action": { + "name": "action", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "target": { + "name": "target", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "http_status": { + "name": "http_status", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "idx_operator_events_created": { + "name": "idx_operator_events_created", + "columns": [ + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.operator_sessions": { + "name": "operator_sessions", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "human_session_id": { + "name": "human_session_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "expires_at": { + "name": "expires_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "idx_operator_sessions_expiry": { + "name": "idx_operator_sessions_expiry", + "columns": [ + { + "expression": "expires_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "operator_sessions_user_id_users_id_fk": { + "name": "operator_sessions_user_id_users_id_fk", + "tableFrom": "operator_sessions", + "tableTo": "users", + "columnsFrom": ["user_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "operator_sessions_human_session_id_platform_human_sessions_id_fk": { + "name": "operator_sessions_human_session_id_platform_human_sessions_id_fk", + "tableFrom": "operator_sessions", + "tableTo": "platform_human_sessions", + "columnsFrom": ["human_session_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.platform_auth_attempts": { + "name": "platform_auth_attempts", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "connection_id": { + "name": "connection_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "revision": { + "name": "revision", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "generation": { + "name": "generation", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "purpose": { + "name": "purpose", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "browser_hash": { + "name": "browser_hash", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "context": { + "name": "context", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "expires_at": { + "name": "expires_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true + } + }, + "indexes": { + "platform_auth_attempts_expiry": { + "name": "platform_auth_attempts_expiry", + "columns": [ + { + "expression": "expires_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "platform_auth_attempts_connection_id_platform_login_connections_id_fk": { + "name": "platform_auth_attempts_connection_id_platform_login_connections_id_fk", + "tableFrom": "platform_auth_attempts", + "tableTo": "platform_login_connections", + "columnsFrom": ["connection_id"], + "columnsTo": ["id"], + "onDelete": "no action", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.platform_auth_bootstrap": { + "name": "platform_auth_bootstrap", + "schema": "", + "columns": { + "singleton": { + "name": "singleton", + "type": "boolean", + "primaryKey": true, + "notNull": true, + "default": true + }, + "installation_id": { + "name": "installation_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "credential_hash": { + "name": "credential_hash", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "request_hash": { + "name": "request_hash", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "''" + }, + "claim_hash": { + "name": "claim_hash", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "pending_identity": { + "name": "pending_identity", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "connection_id": { + "name": "connection_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "expires_at": { + "name": "expires_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true + }, + "consumed_at": { + "name": "consumed_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + } + }, + "indexes": {}, + "foreignKeys": { + "platform_auth_bootstrap_connection_id_platform_login_connections_id_fk": { + "name": "platform_auth_bootstrap_connection_id_platform_login_connections_id_fk", + "tableFrom": "platform_auth_bootstrap", + "tableTo": "platform_login_connections", + "columnsFrom": ["connection_id"], + "columnsTo": ["id"], + "onDelete": "no action", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "platform_auth_bootstrap_singleton": { + "name": "platform_auth_bootstrap_singleton", + "value": "\"platform_auth_bootstrap\".\"singleton\" = true" + } + }, + "isRLSEnabled": false + }, + "public.platform_auth_settings": { + "name": "platform_auth_settings", + "schema": "", + "columns": { + "singleton": { + "name": "singleton", + "type": "boolean", + "primaryKey": true, + "notNull": true, + "default": true + }, + "revision": { + "name": "revision", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 1 + }, + "admission": { + "name": "admission", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "protection": { + "name": "protection", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "session_seconds": { + "name": "session_seconds", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 2592000 + }, + "sessions_required": { + "name": "sessions_required", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "platform_auth_settings_singleton": { + "name": "platform_auth_settings_singleton", + "value": "\"platform_auth_settings\".\"singleton\" = true" + }, + "platform_auth_settings_revision": { + "name": "platform_auth_settings_revision", + "value": "\"platform_auth_settings\".\"revision\" > 0" + }, + "platform_auth_settings_session_seconds": { + "name": "platform_auth_settings_session_seconds", + "value": "\"platform_auth_settings\".\"session_seconds\" BETWEEN 300 AND 2592000" + } + }, + "isRLSEnabled": false + }, + "public.platform_company_identities": { + "name": "platform_company_identities", + "schema": "", + "columns": { + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "issuer": { + "name": "issuer", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "subject": { + "name": "subject", + "type": "text", + "primaryKey": false, + "notNull": true + } + }, + "indexes": { + "platform_company_identity_user": { + "name": "platform_company_identity_user", + "columns": [ + { + "expression": "issuer", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "platform_company_identities_user_id_users_id_fk": { + "name": "platform_company_identities_user_id_users_id_fk", + "tableFrom": "platform_company_identities", + "tableTo": "users", + "columnsFrom": ["user_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "platform_company_identities_issuer_subject_pk": { + "name": "platform_company_identities_issuer_subject_pk", + "columns": ["issuer", "subject"] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.platform_events": { + "name": "platform_events", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "batch_id": { + "name": "batch_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "action": { + "name": "action", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "worker_name": { + "name": "worker_name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "environment": { + "name": "environment", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "version_id": { + "name": "version_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "script_name": { + "name": "script_name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'pending'" + }, + "error_message": { + "name": "error_message", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "admin_user_id": { + "name": "admin_user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "admin_login": { + "name": "admin_login", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "idx_platform_events_batch_id": { + "name": "idx_platform_events_batch_id", + "columns": [ + { + "expression": "batch_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "idx_platform_events_env_created": { + "name": "idx_platform_events_env_created", + "columns": [ + { + "expression": "environment", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.platform_human_sessions": { + "name": "platform_human_sessions", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "connection_id": { + "name": "connection_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "generation": { + "name": "generation", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "audience": { + "name": "audience", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "access_issuer": { + "name": "access_issuer", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "access_subject": { + "name": "access_subject", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "expires_at": { + "name": "expires_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true + }, + "revoked_at": { + "name": "revoked_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "platform_human_sessions_connection": { + "name": "platform_human_sessions_connection", + "columns": [ + { + "expression": "connection_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "platform_human_sessions_user": { + "name": "platform_human_sessions_user", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "platform_human_sessions_expiry": { + "name": "platform_human_sessions_expiry", + "columns": [ + { + "expression": "expires_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "platform_human_sessions_user_id_users_id_fk": { + "name": "platform_human_sessions_user_id_users_id_fk", + "tableFrom": "platform_human_sessions", + "tableTo": "users", + "columnsFrom": ["user_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "platform_human_sessions_connection_id_platform_login_connections_id_fk": { + "name": "platform_human_sessions_connection_id_platform_login_connections_id_fk", + "tableFrom": "platform_human_sessions", + "tableTo": "platform_login_connections", + "columnsFrom": ["connection_id"], + "columnsTo": ["id"], + "onDelete": "no action", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "platform_human_sessions_audience": { + "name": "platform_human_sessions_audience", + "value": "\"platform_human_sessions\".\"audience\" IN ('api', 'admin')" + }, + "platform_human_sessions_access_identity": { + "name": "platform_human_sessions_access_identity", + "value": "(\"platform_human_sessions\".\"access_issuer\" IS NULL) = (\"platform_human_sessions\".\"access_subject\" IS NULL)" + } + }, + "isRLSEnabled": false + }, + "public.platform_login_connections": { + "name": "platform_login_connections", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "kind": { + "name": "kind", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "enabled": { + "name": "enabled", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "active_revision": { + "name": "active_revision", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "revision": { + "name": "revision", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 1 + }, + "generation": { + "name": "generation", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 1 + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "platform_login_connections_kind": { + "name": "platform_login_connections_kind", + "value": "\"platform_login_connections\".\"kind\" IN ('github', 'google', 'oidc', 'cloudflare-access')" + }, + "platform_login_connections_revision": { + "name": "platform_login_connections_revision", + "value": "\"platform_login_connections\".\"revision\" > 0 AND \"platform_login_connections\".\"generation\" > 0" + }, + "platform_login_connections_active_revision": { + "name": "platform_login_connections_active_revision", + "value": "\"platform_login_connections\".\"active_revision\" IS NULL OR \"platform_login_connections\".\"active_revision\" BETWEEN 1 AND \"platform_login_connections\".\"revision\"" + }, + "platform_login_connections_enabled": { + "name": "platform_login_connections_enabled", + "value": "NOT \"platform_login_connections\".\"enabled\" OR \"platform_login_connections\".\"active_revision\" IS NOT NULL" + } + }, + "isRLSEnabled": false + }, + "public.platform_login_identities": { + "name": "platform_login_identities", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "connection_id": { + "name": "connection_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "issuer": { + "name": "issuer", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "subject": { + "name": "subject", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "last_authenticated_at": { + "name": "last_authenticated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "platform_login_identity_subject": { + "name": "platform_login_identity_subject", + "columns": [ + { + "expression": "connection_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "issuer", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "subject", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "platform_login_identity_user": { + "name": "platform_login_identity_user", + "columns": [ + { + "expression": "connection_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "platform_login_identities_user_id_users_id_fk": { + "name": "platform_login_identities_user_id_users_id_fk", + "tableFrom": "platform_login_identities", + "tableTo": "users", + "columnsFrom": ["user_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "platform_login_identities_connection_id_platform_login_connections_id_fk": { + "name": "platform_login_identities_connection_id_platform_login_connections_id_fk", + "tableFrom": "platform_login_identities", + "tableTo": "platform_login_connections", + "columnsFrom": ["connection_id"], + "columnsTo": ["id"], + "onDelete": "no action", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.platform_login_revisions": { + "name": "platform_login_revisions", + "schema": "", + "columns": { + "connection_id": { + "name": "connection_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "revision": { + "name": "revision", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "configuration": { + "name": "configuration", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "secret": { + "name": "secret", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": { + "platform_login_revisions_connection_id_platform_login_connections_id_fk": { + "name": "platform_login_revisions_connection_id_platform_login_connections_id_fk", + "tableFrom": "platform_login_revisions", + "tableTo": "platform_login_connections", + "columnsFrom": ["connection_id"], + "columnsTo": ["id"], + "onDelete": "no action", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "platform_login_revisions_connection_id_revision_pk": { + "name": "platform_login_revisions_connection_id_revision_pk", + "columns": ["connection_id", "revision"] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.platform_login_tests": { + "name": "platform_login_tests", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "connection_id": { + "name": "connection_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "revision": { + "name": "revision", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "issuer": { + "name": "issuer", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "subject": { + "name": "subject", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "login": { + "name": "login", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "''" + }, + "expires_at": { + "name": "expires_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true + } + }, + "indexes": { + "platform_login_tests_expiry": { + "name": "platform_login_tests_expiry", + "columns": [ + { + "expression": "expires_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "platform_login_tests_user_id_users_id_fk": { + "name": "platform_login_tests_user_id_users_id_fk", + "tableFrom": "platform_login_tests", + "tableTo": "users", + "columnsFrom": ["user_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "platform_login_tests_connection_id_platform_login_connections_id_fk": { + "name": "platform_login_tests_connection_id_platform_login_connections_id_fk", + "tableFrom": "platform_login_tests", + "tableTo": "platform_login_connections", + "columnsFrom": ["connection_id"], + "columnsTo": ["id"], + "onDelete": "no action", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.platform_settings": { + "name": "platform_settings", + "schema": "", + "columns": { + "key": { + "name": "key", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "value": { + "name": "value", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.preview_tickets": { + "name": "preview_tickets", + "schema": "", + "columns": { + "token_hash": { + "name": "token_hash", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "project_id": { + "name": "project_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "grant_id": { + "name": "grant_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "expires_at": { + "name": "expires_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true + } + }, + "indexes": {}, + "foreignKeys": { + "preview_tickets_project_id_projects_id_fk": { + "name": "preview_tickets_project_id_projects_id_fk", + "tableFrom": "preview_tickets", + "tableTo": "projects", + "columnsFrom": ["project_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "preview_tickets_grant_id_oauth_grants_id_fk": { + "name": "preview_tickets_grant_id_oauth_grants_id_fk", + "tableFrom": "preview_tickets", + "tableTo": "oauth_grants", + "columnsFrom": ["grant_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.project_access_events": { + "name": "project_access_events", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "project_id": { + "name": "project_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "actor_user_id": { + "name": "actor_user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "subject_user_id": { + "name": "subject_user_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "invitation_email_snapshot": { + "name": "invitation_email_snapshot", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "previous_role": { + "name": "previous_role", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "new_role": { + "name": "new_role", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "action": { + "name": "action", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "idx_project_access_events_project_created": { + "name": "idx_project_access_events_project_created", + "columns": [ + { + "expression": "project_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "idx_project_access_events_subject_created": { + "name": "idx_project_access_events_subject_created", + "columns": [ + { + "expression": "subject_user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "project_access_events_project_id_projects_id_fk": { + "name": "project_access_events_project_id_projects_id_fk", + "tableFrom": "project_access_events", + "tableTo": "projects", + "columnsFrom": ["project_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "project_access_events_previous_role_check": { + "name": "project_access_events_previous_role_check", + "value": "\"project_access_events\".\"previous_role\" IS NULL OR \"project_access_events\".\"previous_role\" IN ('reader', 'collaborator', 'admin')" + }, + "project_access_events_new_role_check": { + "name": "project_access_events_new_role_check", + "value": "\"project_access_events\".\"new_role\" IS NULL OR \"project_access_events\".\"new_role\" IN ('reader', 'collaborator', 'admin')" + }, + "project_access_events_action_check": { + "name": "project_access_events_action_check", + "value": "\"project_access_events\".\"action\" IN ('invited', 'invitation_resent', 'member_added', 'accepted', 'declined', 'invitation_revoked', 'role_changed', 'member_removed', 'left')" + } + }, + "isRLSEnabled": false + }, + "public.project_ai_logging": { + "name": "project_ai_logging", + "schema": "", + "columns": { + "project_id": { + "name": "project_id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "mode": { + "name": "mode", + "type": "text", + "primaryKey": false, + "notNull": true + } + }, + "indexes": {}, + "foreignKeys": { + "project_ai_logging_project_id_projects_id_fk": { + "name": "project_ai_logging_project_id_projects_id_fk", + "tableFrom": "project_ai_logging", + "tableTo": "projects", + "columnsFrom": ["project_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "project_ai_logging_mode": { + "name": "project_ai_logging_mode", + "value": "\"project_ai_logging\".\"mode\" IN ('off', 'metadata', 'full')" + } + }, + "isRLSEnabled": false + }, + "public.project_cleanup_jobs": { + "name": "project_cleanup_jobs", + "schema": "", + "columns": { + "target": { + "name": "target", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "project_id": { + "name": "project_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "kind": { + "name": "kind", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "payload": { + "name": "payload", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "attempts": { + "name": "attempts", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "last_error": { + "name": "last_error", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "next_attempt_at": { + "name": "next_attempt_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "project_cleanup_jobs_due": { + "name": "project_cleanup_jobs_due", + "columns": [ + { + "expression": "next_attempt_at", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.project_database_credentials": { + "name": "project_database_credentials", + "schema": "", + "columns": { + "project_id": { + "name": "project_id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "ciphertext": { + "name": "ciphertext", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "iv": { + "name": "iv", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "key_version": { + "name": "key_version", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": { + "project_database_credentials_project_id_projects_id_fk": { + "name": "project_database_credentials_project_id_projects_id_fk", + "tableFrom": "project_database_credentials", + "tableTo": "projects", + "columnsFrom": ["project_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.project_deploy_credentials": { + "name": "project_deploy_credentials", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "project_id": { + "name": "project_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "issued_by": { + "name": "issued_by", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "expires_at": { + "name": "expires_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true + }, + "revoked_at": { + "name": "revoked_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "project_deploy_credentials_project": { + "name": "project_deploy_credentials_project", + "columns": [ + { + "expression": "project_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "project_deploy_credentials_expiry": { + "name": "project_deploy_credentials_expiry", + "columns": [ + { + "expression": "expires_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "project_deploy_credentials_project_id_projects_id_fk": { + "name": "project_deploy_credentials_project_id_projects_id_fk", + "tableFrom": "project_deploy_credentials", + "tableTo": "projects", + "columnsFrom": ["project_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "project_deploy_credentials_issued_by_users_id_fk": { + "name": "project_deploy_credentials_issued_by_users_id_fk", + "tableFrom": "project_deploy_credentials", + "tableTo": "users", + "columnsFrom": ["issued_by"], + "columnsTo": ["id"], + "onDelete": "no action", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "project_deploy_credentials_name": { + "name": "project_deploy_credentials_name", + "value": "length(\"project_deploy_credentials\".\"name\") BETWEEN 1 AND 80" + } + }, + "isRLSEnabled": false + }, + "public.project_invitations": { + "name": "project_invitations", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "project_id": { + "name": "project_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "target_user_id": { + "name": "target_user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "target_email_snapshot": { + "name": "target_email_snapshot", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "role": { + "name": "role", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'pending'" + }, + "invited_by_user_id": { + "name": "invited_by_user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "accepted_by_user_id": { + "name": "accepted_by_user_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "expires_at": { + "name": "expires_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true + }, + "accepted_at": { + "name": "accepted_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "revoked_at": { + "name": "revoked_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "revoked_by_user_id": { + "name": "revoked_by_user_id", + "type": "text", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "idx_project_invitations_project_status": { + "name": "idx_project_invitations_project_status", + "columns": [ + { + "expression": "project_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "idx_project_invitations_target_status": { + "name": "idx_project_invitations_target_status", + "columns": [ + { + "expression": "target_user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "idx_project_invitations_pending_target": { + "name": "idx_project_invitations_pending_target", + "columns": [ + { + "expression": "project_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "target_user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "\"project_invitations\".\"status\" = 'pending'", + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "project_invitations_project_id_projects_id_fk": { + "name": "project_invitations_project_id_projects_id_fk", + "tableFrom": "project_invitations", + "tableTo": "projects", + "columnsFrom": ["project_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "project_invitations_target_user_id_users_id_fk": { + "name": "project_invitations_target_user_id_users_id_fk", + "tableFrom": "project_invitations", + "tableTo": "users", + "columnsFrom": ["target_user_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "project_invitations_role_check": { + "name": "project_invitations_role_check", + "value": "\"project_invitations\".\"role\" IN ('reader', 'collaborator', 'admin')" + }, + "project_invitations_status_check": { + "name": "project_invitations_status_check", + "value": "\"project_invitations\".\"status\" IN ('pending', 'accepted', 'declined', 'revoked', 'expired')" + } + }, + "isRLSEnabled": false + }, + "public.project_members": { + "name": "project_members", + "schema": "", + "columns": { + "project_id": { + "name": "project_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "role": { + "name": "role", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "added_by_user_id": { + "name": "added_by_user_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "idx_project_members_user_project": { + "name": "idx_project_members_user_project", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "project_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "project_members_project_id_projects_id_fk": { + "name": "project_members_project_id_projects_id_fk", + "tableFrom": "project_members", + "tableTo": "projects", + "columnsFrom": ["project_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "project_members_user_id_users_id_fk": { + "name": "project_members_user_id_users_id_fk", + "tableFrom": "project_members", + "tableTo": "users", + "columnsFrom": ["user_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "project_members_project_id_user_id_pk": { + "name": "project_members_project_id_user_id_pk", + "columns": ["project_id", "user_id"] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "project_members_role_check": { + "name": "project_members_role_check", + "value": "\"project_members\".\"role\" IN ('reader', 'collaborator', 'admin')" + } + }, + "isRLSEnabled": false + }, + "public.project_migrations": { + "name": "project_migrations", + "schema": "", + "columns": { + "project_id": { + "name": "project_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "applied_at": { + "name": "applied_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "source_deployment_id": { + "name": "source_deployment_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "idx_project_migrations_project_id": { + "name": "idx_project_migrations_project_id", + "columns": [ + { + "expression": "project_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "applied_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "project_migrations_project_id_projects_id_fk": { + "name": "project_migrations_project_id_projects_id_fk", + "tableFrom": "project_migrations", + "tableTo": "projects", + "columnsFrom": ["project_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "project_migrations_source_deployment_id_deployments_id_fk": { + "name": "project_migrations_source_deployment_id_deployments_id_fk", + "tableFrom": "project_migrations", + "tableTo": "deployments", + "columnsFrom": ["source_deployment_id"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "project_migrations_project_id_name_pk": { + "name": "project_migrations_project_id_name_pk", + "columns": ["project_id", "name"] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.project_ownership_periods": { + "name": "project_ownership_periods", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "project_id": { + "name": "project_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "owner_user_id": { + "name": "owner_user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "starts_at": { + "name": "starts_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true + }, + "ends_at": { + "name": "ends_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "changed_by_user_id": { + "name": "changed_by_user_id", + "type": "text", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "idx_project_ownership_periods_owner_time": { + "name": "idx_project_ownership_periods_owner_time", + "columns": [ + { + "expression": "owner_user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "starts_at", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "ends_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "idx_project_ownership_periods_project_time": { + "name": "idx_project_ownership_periods_project_time", + "columns": [ + { + "expression": "project_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "starts_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "idx_project_ownership_periods_open": { + "name": "idx_project_ownership_periods_open", + "columns": [ + { + "expression": "project_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "\"project_ownership_periods\".\"ends_at\" IS NULL", + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "project_ownership_periods_project_id_projects_id_fk": { + "name": "project_ownership_periods_project_id_projects_id_fk", + "tableFrom": "project_ownership_periods", + "tableTo": "projects", + "columnsFrom": ["project_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "project_ownership_periods_time_check": { + "name": "project_ownership_periods_time_check", + "value": "\"project_ownership_periods\".\"ends_at\" IS NULL OR \"project_ownership_periods\".\"ends_at\" >= \"project_ownership_periods\".\"starts_at\"" + } + }, + "isRLSEnabled": false + }, + "public.project_secrets": { + "name": "project_secrets", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "project_id": { + "name": "project_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "ciphertext": { + "name": "ciphertext", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "iv": { + "name": "iv", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "key_version": { + "name": "key_version", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "managed_reason": { + "name": "managed_reason", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "idx_project_secrets_project_id": { + "name": "idx_project_secrets_project_id", + "columns": [ + { + "expression": "project_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "project_secrets_project_id_projects_id_fk": { + "name": "project_secrets_project_id_projects_id_fk", + "tableFrom": "project_secrets", + "tableTo": "projects", + "columnsFrom": ["project_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "project_secrets_project_id_name_unique": { + "name": "project_secrets_project_id_name_unique", + "nullsNotDistinct": false, + "columns": ["project_id", "name"] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.project_zero_trust": { + "name": "project_zero_trust", + "schema": "", + "columns": { + "project_id": { + "name": "project_id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "desired_protected": { + "name": "desired_protected", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "effective_protected": { + "name": "effective_protected", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'ready'" + }, + "bypass_application_id": { + "name": "bypass_application_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "bypass_application_name": { + "name": "bypass_application_name", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "protected_application_id": { + "name": "protected_application_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "protected_application_name": { + "name": "protected_application_name", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "protected_application_audience": { + "name": "protected_application_audience", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "routing_cursor": { + "name": "routing_cursor", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "reconciled_operation": { + "name": "reconciled_operation", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "last_error": { + "name": "last_error", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "idx_project_zero_trust_status": { + "name": "idx_project_zero_trust_status", + "columns": [ + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "updated_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "project_zero_trust_project_id_projects_id_fk": { + "name": "project_zero_trust_project_id_projects_id_fk", + "tableFrom": "project_zero_trust", + "tableTo": "projects", + "columnsFrom": ["project_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "project_zero_trust_status_check": { + "name": "project_zero_trust_status_check", + "value": "\"project_zero_trust\".\"status\" IN ('ready', 'reconciling', 'error')" + }, + "project_zero_trust_ready_check": { + "name": "project_zero_trust_ready_check", + "value": "\"project_zero_trust\".\"status\" <> 'ready' OR \"project_zero_trust\".\"desired_protected\" = \"project_zero_trust\".\"effective_protected\"" + } + }, + "isRLSEnabled": false + }, + "public.projects": { + "name": "projects", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "slug": { + "name": "slug", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "preview_client_id": { + "name": "preview_client_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "preview_workspace_id": { + "name": "preview_workspace_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "preview_expires_at": { + "name": "preview_expires_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "mode": { + "name": "mode", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'void'" + }, + "active_deployment_id": { + "name": "active_deployment_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "websocket_version": { + "name": "websocket_version", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "proxy_token_gen": { + "name": "proxy_token_gen", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'active'" + }, + "email_alias": { + "name": "email_alias", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "idx_projects_slug": { + "name": "idx_projects_slug", + "columns": [ + { + "expression": "slug", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "idx_projects_email_alias": { + "name": "idx_projects_email_alias", + "columns": [ + { + "expression": "email_alias", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "\"projects\".\"email_alias\" IS NOT NULL", + "concurrently": false, + "method": "btree", + "with": {} + }, + "idx_projects_user_id": { + "name": "idx_projects_user_id", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "projects_preview_workspace": { + "name": "projects_preview_workspace", + "columns": [ + { + "expression": "preview_client_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "preview_workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "projects_user_id_users_id_fk": { + "name": "projects_user_id_users_id_fk", + "tableFrom": "projects", + "tableTo": "users", + "columnsFrom": ["user_id"], + "columnsTo": ["id"], + "onDelete": "no action", + "onUpdate": "no action" + }, + "projects_preview_client_id_oauth_clients_id_fk": { + "name": "projects_preview_client_id_oauth_clients_id_fk", + "tableFrom": "projects", + "tableTo": "oauth_clients", + "columnsFrom": ["preview_client_id"], + "columnsTo": ["id"], + "onDelete": "no action", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "projects_user_id_slug_unique": { + "name": "projects_user_id_slug_unique", + "nullsNotDistinct": false, + "columns": ["user_id", "slug"] + } + }, + "policies": {}, + "checkConstraints": { + "projects_preview_identity": { + "name": "projects_preview_identity", + "value": "(\"projects\".\"preview_client_id\" IS NULL AND \"projects\".\"preview_workspace_id\" IS NULL AND \"projects\".\"preview_expires_at\" IS NULL) OR (\"projects\".\"preview_client_id\" IS NOT NULL AND \"projects\".\"preview_workspace_id\" IS NOT NULL AND \"projects\".\"preview_expires_at\" IS NOT NULL AND \"projects\".\"slug\" LIKE 'preview-%')" + } + }, + "isRLSEnabled": false + }, + "public.resources": { + "name": "resources", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "project_id": { + "name": "project_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "type": { + "name": "type", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "cf_id": { + "name": "cf_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "binding_name": { + "name": "binding_name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "metadata": { + "name": "metadata", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'{}'::jsonb" + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": { + "resources_project_id_projects_id_fk": { + "name": "resources_project_id_projects_id_fk", + "tableFrom": "resources", + "tableTo": "projects", + "columnsFrom": ["project_id"], + "columnsTo": ["id"], + "onDelete": "no action", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "resources_project_id_type_binding_name_unique": { + "name": "resources_project_id_type_binding_name_unique", + "nullsNotDistinct": false, + "columns": ["project_id", "type", "binding_name"] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.sandbox_drain_checkpoints": { + "name": "sandbox_drain_checkpoints", + "schema": "", + "columns": { + "singleton": { + "name": "singleton", + "type": "boolean", + "primaryKey": true, + "notNull": true + }, + "admission_protocol": { + "name": "admission_protocol", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "generation": { + "name": "generation", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "state": { + "name": "state", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "phase": { + "name": "phase", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "cursor": { + "name": "cursor", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "lease_owner": { + "name": "lease_owner", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "lease_expires_at": { + "name": "lease_expires_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "started_at": { + "name": "started_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "completed_at": { + "name": "completed_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.users": { + "name": "users", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "provider": { + "name": "provider", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'github'" + }, + "provider_id": { + "name": "provider_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "''" + }, + "login": { + "name": "login", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "''" + }, + "email": { + "name": "email", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "plan": { + "name": "plan", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'free'" + }, + "role": { + "name": "role", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'user'" + }, + "billing_cycle_start": { + "name": "billing_cycle_start", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "suspended_reason": { + "name": "suspended_reason", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "idx_users_provider_id": { + "name": "idx_users_provider_id", + "columns": [ + { + "expression": "provider", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "provider_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "idx_users_email": { + "name": "idx_users_email", + "columns": [ + { + "expression": "email", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.email_cache_outbox": { + "name": "email_cache_outbox", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "installation_id": { + "name": "installation_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "resource_kind": { + "name": "resource_kind", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "resource_id": { + "name": "resource_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "version": { + "name": "version", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "payload": { + "name": "payload", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "published_at": { + "name": "published_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "email_cache_outbox_version_uq": { + "name": "email_cache_outbox_version_uq", + "columns": [ + { + "expression": "resource_kind", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "resource_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "version", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "email_cache_outbox_pending_idx": { + "name": "email_cache_outbox_pending_idx", + "columns": [ + { + "expression": "published_at", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.email_credentials": { + "name": "email_credentials", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "installation_id": { + "name": "installation_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "managed_by": { + "name": "managed_by", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "manager_user_id": { + "name": "manager_user_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "kind": { + "name": "kind", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "account_id": { + "name": "account_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "zone_id": { + "name": "zone_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "ciphertext": { + "name": "ciphertext", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "iv": { + "name": "iv", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "key_version": { + "name": "key_version", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "token_id": { + "name": "token_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "expires_on": { + "name": "expires_on", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "generation": { + "name": "generation", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 1 + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'healthy'" + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "email_credentials_scope_idx": { + "name": "email_credentials_scope_idx", + "columns": [ + { + "expression": "installation_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "account_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "zone_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "email_credentials_material_check": { + "name": "email_credentials_material_check", + "value": "(\"email_credentials\".\"kind\" = 'platform' AND \"email_credentials\".\"ciphertext\" IS NULL AND \"email_credentials\".\"iv\" IS NULL AND \"email_credentials\".\"key_version\" IS NULL) OR (\"email_credentials\".\"kind\" = 'api_token' AND \"email_credentials\".\"ciphertext\" IS NOT NULL AND \"email_credentials\".\"iv\" IS NOT NULL AND \"email_credentials\".\"key_version\" IS NOT NULL)" + } + }, + "isRLSEnabled": false + }, + "public.email_domain_routes": { + "name": "email_domain_routes", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "domain": { + "name": "domain", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "connection_id": { + "name": "connection_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "project_id": { + "name": "project_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "addressing": { + "name": "addressing", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "managed_by": { + "name": "managed_by", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "assigned_by_user_id": { + "name": "assigned_by_user_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "desired_state": { + "name": "desired_state", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'active'" + }, + "inbound_mode": { + "name": "inbound_mode", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'managed'" + }, + "inbound_status": { + "name": "inbound_status", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'pending'" + }, + "inbound_reason": { + "name": "inbound_reason", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "inbound_observed_at": { + "name": "inbound_observed_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "outbound_status": { + "name": "outbound_status", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'pending'" + }, + "outbound_reason": { + "name": "outbound_reason", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "outbound_observed_at": { + "name": "outbound_observed_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "desired_generation": { + "name": "desired_generation", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 1 + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "email_domain_routes_domain_uq": { + "name": "email_domain_routes_domain_uq", + "columns": [ + { + "expression": "domain", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "email_domain_routes_connection_idx": { + "name": "email_domain_routes_connection_idx", + "columns": [ + { + "expression": "connection_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "email_domain_routes_project_idx": { + "name": "email_domain_routes_project_idx", + "columns": [ + { + "expression": "project_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "email_domain_routes_connection_id_email_zone_connections_id_fk": { + "name": "email_domain_routes_connection_id_email_zone_connections_id_fk", + "tableFrom": "email_domain_routes", + "tableTo": "email_zone_connections", + "columnsFrom": ["connection_id"], + "columnsTo": ["id"], + "onDelete": "no action", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "email_domain_routes_assignment_check": { + "name": "email_domain_routes_assignment_check", + "value": "(\"email_domain_routes\".\"addressing\" = 'custom' AND \"email_domain_routes\".\"project_id\" IS NOT NULL) OR (\"email_domain_routes\".\"addressing\" = 'shared' AND \"email_domain_routes\".\"project_id\" IS NULL)" + }, + "email_domain_routes_inbound_mode_check": { + "name": "email_domain_routes_inbound_mode_check", + "value": "\"email_domain_routes\".\"inbound_mode\" = 'managed' OR (\"email_domain_routes\".\"inbound_mode\" = 'none' AND \"email_domain_routes\".\"addressing\" = 'custom')" + } + }, + "isRLSEnabled": false + }, + "public.email_operation_steps": { + "name": "email_operation_steps", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "operation_id": { + "name": "operation_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "ordinal": { + "name": "ordinal", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "kind": { + "name": "kind", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "resource_identity": { + "name": "resource_identity", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "request_digest": { + "name": "request_digest", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "attempt": { + "name": "attempt", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'pending'" + }, + "outcome": { + "name": "outcome", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "failure_code": { + "name": "failure_code", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "failure_detail": { + "name": "failure_detail", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "started_at": { + "name": "started_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "finished_at": { + "name": "finished_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "email_operation_steps_order_uq": { + "name": "email_operation_steps_order_uq", + "columns": [ + { + "expression": "operation_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "ordinal", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "email_operation_steps_operation_id_email_operations_id_fk": { + "name": "email_operation_steps_operation_id_email_operations_id_fk", + "tableFrom": "email_operation_steps", + "tableTo": "email_operations", + "columnsFrom": ["operation_id"], + "columnsTo": ["id"], + "onDelete": "no action", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.email_operations": { + "name": "email_operations", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "installation_id": { + "name": "installation_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "connection_id": { + "name": "connection_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "route_id": { + "name": "route_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "route_generation": { + "name": "route_generation", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "actor_kind": { + "name": "actor_kind", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "actor_user_id": { + "name": "actor_user_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "actor_scope": { + "name": "actor_scope", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "kind": { + "name": "kind", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "idempotency_key": { + "name": "idempotency_key", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "request_digest": { + "name": "request_digest", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "desired_generation": { + "name": "desired_generation", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'pending'" + }, + "current_step": { + "name": "current_step", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "failure_code": { + "name": "failure_code", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "failure_detail": { + "name": "failure_detail", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "email_operations_key_uq": { + "name": "email_operations_key_uq", + "columns": [ + { + "expression": "installation_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "actor_scope", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "idempotency_key", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "email_operations_work_idx": { + "name": "email_operations_work_idx", + "columns": [ + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "updated_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "email_operations_connection_idx": { + "name": "email_operations_connection_idx", + "columns": [ + { + "expression": "connection_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "email_operations_connection_id_email_zone_connections_id_fk": { + "name": "email_operations_connection_id_email_zone_connections_id_fk", + "tableFrom": "email_operations", + "tableTo": "email_zone_connections", + "columnsFrom": ["connection_id"], + "columnsTo": ["id"], + "onDelete": "no action", + "onUpdate": "no action" + }, + "email_operations_route_id_email_domain_routes_id_fk": { + "name": "email_operations_route_id_email_domain_routes_id_fk", + "tableFrom": "email_operations", + "tableTo": "email_domain_routes", + "columnsFrom": ["route_id"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.email_shared_recipients": { + "name": "email_shared_recipients", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "installation_id": { + "name": "installation_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "project_id": { + "name": "project_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "route_id": { + "name": "route_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "recipient": { + "name": "recipient", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "rule_name": { + "name": "rule_name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "rule_id": { + "name": "rule_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "create_started_at": { + "name": "create_started_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "removing": { + "name": "removing", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'pending'" + }, + "reason": { + "name": "reason", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "attempt": { + "name": "attempt", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "lease_started_at": { + "name": "lease_started_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "observed_at": { + "name": "observed_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "email_shared_recipients_project_address_uq": { + "name": "email_shared_recipients_project_address_uq", + "columns": [ + { + "expression": "installation_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "project_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "recipient", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "email_shared_recipients_rule_name_uq": { + "name": "email_shared_recipients_rule_name_uq", + "columns": [ + { + "expression": "rule_name", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "email_shared_recipients_reconcile_idx": { + "name": "email_shared_recipients_reconcile_idx", + "columns": [ + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "updated_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.email_zone_connections": { + "name": "email_zone_connections", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "installation_id": { + "name": "installation_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "account_id": { + "name": "account_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "zone_id": { + "name": "zone_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "zone_name": { + "name": "zone_name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "managed_by": { + "name": "managed_by", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "manager_user_id": { + "name": "manager_user_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "credential_id": { + "name": "credential_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "ingress_worker_name": { + "name": "ingress_worker_name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "ingress_version": { + "name": "ingress_version", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "desired_generation": { + "name": "desired_generation", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 1 + }, + "active_secret_generation": { + "name": "active_secret_generation", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "staged_secret_generation": { + "name": "staged_secret_generation", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "secret_ciphertext": { + "name": "secret_ciphertext", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "secret_iv": { + "name": "secret_iv", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "secret_key_version": { + "name": "secret_key_version", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "staged_secret_ciphertext": { + "name": "staged_secret_ciphertext", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "staged_secret_iv": { + "name": "staged_secret_iv", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "staged_secret_key_version": { + "name": "staged_secret_key_version", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "previous_secret_hash": { + "name": "previous_secret_hash", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "previous_secret_until": { + "name": "previous_secret_until", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "inbound_status": { + "name": "inbound_status", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'pending'" + }, + "inbound_reason": { + "name": "inbound_reason", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "inbound_observed_at": { + "name": "inbound_observed_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "management_status": { + "name": "management_status", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'probe_failed'" + }, + "management_reason": { + "name": "management_reason", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "management_observed_at": { + "name": "management_observed_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "email_zone_connections_zone_uq": { + "name": "email_zone_connections_zone_uq", + "columns": [ + { + "expression": "installation_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "account_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "zone_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "email_zone_connections_ingress_uq": { + "name": "email_zone_connections_ingress_uq", + "columns": [ + { + "expression": "account_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "ingress_worker_name", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "email_zone_connections_manager_idx": { + "name": "email_zone_connections_manager_idx", + "columns": [ + { + "expression": "manager_user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "email_zone_connections_manager_check": { + "name": "email_zone_connections_manager_check", + "value": "(\"email_zone_connections\".\"managed_by\" = 'owner' AND \"email_zone_connections\".\"manager_user_id\" IS NOT NULL) OR (\"email_zone_connections\".\"managed_by\" = 'admin')" + } + }, + "isRLSEnabled": false + }, + "public.email_action_recipients": { + "name": "email_action_recipients", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "action_id": { + "name": "action_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "project_id": { + "name": "project_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "recipient": { + "name": "recipient", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "state": { + "name": "state", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "error_code": { + "name": "error_code", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "provider_reference": { + "name": "provider_reference", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "reserved_at": { + "name": "reserved_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "attempt_started_at": { + "name": "attempt_started_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "completed_at": { + "name": "completed_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "idx_email_action_recipients_project_reserved": { + "name": "idx_email_action_recipients_project_reserved", + "columns": [ + { + "expression": "project_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "reserved_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "idx_email_action_recipients_expiring": { + "name": "idx_email_action_recipients_expiring", + "columns": [ + { + "expression": "reserved_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"email_action_recipients\".\"state\" = 'reserved'", + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "email_action_recipients_action_id_email_actions_id_fk": { + "name": "email_action_recipients_action_id_email_actions_id_fk", + "tableFrom": "email_action_recipients", + "tableTo": "email_actions", + "columnsFrom": ["action_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "email_action_recipients_action_recipient_uq": { + "name": "email_action_recipients_action_recipient_uq", + "nullsNotDistinct": false, + "columns": ["action_id", "recipient"] + } + }, + "policies": {}, + "checkConstraints": { + "email_action_recipients_state_check": { + "name": "email_action_recipients_state_check", + "value": "\"email_action_recipients\".\"state\" IN ('rejected', 'reserved', 'attempt_started', 'provider_accepted', 'failed', 'outcome_unknown', 'cancelled')" + } + }, + "isRLSEnabled": false + }, + "public.email_actions": { + "name": "email_actions", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "project_id": { + "name": "project_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "sender_domain": { + "name": "sender_domain", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "receipt_id": { + "name": "receipt_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "kind": { + "name": "kind", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "idempotency_key": { + "name": "idempotency_key", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "payload_digest": { + "name": "payload_digest", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "transport": { + "name": "transport", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "policy_version": { + "name": "policy_version", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "idx_email_actions_project_created": { + "name": "idx_email_actions_project_created", + "columns": [ + { + "expression": "project_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "email_actions_receipt_id_email_receipts_id_fk": { + "name": "email_actions_receipt_id_email_receipts_id_fk", + "tableFrom": "email_actions", + "tableTo": "email_receipts", + "columnsFrom": ["receipt_id"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "email_actions_project_key_uq": { + "name": "email_actions_project_key_uq", + "nullsNotDistinct": false, + "columns": ["project_id", "idempotency_key"] + } + }, + "policies": {}, + "checkConstraints": { + "email_actions_kind_check": { + "name": "email_actions_kind_check", + "value": "\"email_actions\".\"kind\" IN ('direct', 'forward', 'reply')" + } + }, + "isRLSEnabled": false + }, + "public.email_monthly_usage": { + "name": "email_monthly_usage", + "schema": "", + "columns": { + "project_id": { + "name": "project_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "month": { + "name": "month", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "recipient_attempts": { + "name": "recipient_attempts", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "inbound_receipts": { + "name": "inbound_receipts", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "email_monthly_usage_project_month_uq": { + "name": "email_monthly_usage_project_month_uq", + "nullsNotDistinct": false, + "columns": ["project_id", "month"] + } + }, + "policies": {}, + "checkConstraints": { + "email_monthly_usage_nonnegative_check": { + "name": "email_monthly_usage_nonnegative_check", + "value": "\"email_monthly_usage\".\"recipient_attempts\" >= 0" + }, + "email_monthly_usage_inbound_nonnegative_check": { + "name": "email_monthly_usage_inbound_nonnegative_check", + "value": "\"email_monthly_usage\".\"inbound_receipts\" >= 0" + } + }, + "isRLSEnabled": false + }, + "public.email_project_controls": { + "name": "email_project_controls", + "schema": "", + "columns": { + "project_id": { + "name": "project_id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "monthly_limit": { + "name": "monthly_limit", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 200 + }, + "burst_limit": { + "name": "burst_limit", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 10 + }, + "suspended_at": { + "name": "suspended_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "version": { + "name": "version", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 1 + } + }, + "indexes": {}, + "foreignKeys": { + "email_project_controls_project_id_projects_id_fk": { + "name": "email_project_controls_project_id_projects_id_fk", + "tableFrom": "email_project_controls", + "tableTo": "projects", + "columnsFrom": ["project_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.email_receipts": { + "name": "email_receipts", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "project_id": { + "name": "project_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'received'" + }, + "payload_digest": { + "name": "payload_digest", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "final_reject": { + "name": "final_reject", + "type": "boolean", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "idx_email_receipts_project_created": { + "name": "idx_email_receipts_project_created", + "columns": [ + { + "expression": "project_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.email_unresolved_attempts": { + "name": "email_unresolved_attempts", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "project_id": { + "name": "project_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "sender_domain": { + "name": "sender_domain", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "started_at": { + "name": "started_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true + } + }, + "indexes": { + "idx_email_unresolved_attempts_project": { + "name": "idx_email_unresolved_attempts_project", + "columns": [ + { + "expression": "project_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "idx_email_unresolved_attempts_domain": { + "name": "idx_email_unresolved_attempts_domain", + "columns": [ + { + "expression": "sender_domain", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.project_security_settings": { + "name": "project_security_settings", + "schema": "", + "columns": { + "project_id": { + "name": "project_id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "model": { + "name": "model", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "provider_notice_version": { + "name": "provider_notice_version", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "provider_notice_by_user_id": { + "name": "provider_notice_by_user_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "provider_notice_at": { + "name": "provider_notice_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "monthly_cap_cents": { + "name": "monthly_cap_cents", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "cap_ceiling_cents": { + "name": "cap_ceiling_cents", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "cap_updated_by_user_id": { + "name": "cap_updated_by_user_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "cap_updated_at": { + "name": "cap_updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "next_finding_number": { + "name": "next_finding_number", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 1 + }, + "policy_override": { + "name": "policy_override", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'inherit'" + }, + "updated_by_user_id": { + "name": "updated_by_user_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": { + "project_security_settings_project_id_projects_id_fk": { + "name": "project_security_settings_project_id_projects_id_fk", + "tableFrom": "project_security_settings", + "tableTo": "projects", + "columnsFrom": ["project_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "project_security_settings_monthly_cap": { + "name": "project_security_settings_monthly_cap", + "value": "(\"project_security_settings\".\"monthly_cap_cents\" IS NULL OR \"project_security_settings\".\"monthly_cap_cents\" BETWEEN 0 AND 100000000)" + }, + "project_security_settings_cap_ceiling": { + "name": "project_security_settings_cap_ceiling", + "value": "(\"project_security_settings\".\"cap_ceiling_cents\" IS NULL OR \"project_security_settings\".\"cap_ceiling_cents\" BETWEEN 0 AND 100000000)" + }, + "project_security_settings_next_finding": { + "name": "project_security_settings_next_finding", + "value": "\"project_security_settings\".\"next_finding_number\" > 0" + }, + "project_security_settings_policy_override": { + "name": "project_security_settings_policy_override", + "value": "(\"project_security_settings\".\"policy_override\" IN ('inherit', 'always', 'never'))" + }, + "project_security_settings_notice": { + "name": "project_security_settings_notice", + "value": "(\"project_security_settings\".\"provider_notice_version\" IS NULL) = (\"project_security_settings\".\"provider_notice_at\" IS NULL)" + } + }, + "isRLSEnabled": false + }, + "public.security_finding_events": { + "name": "security_finding_events", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "finding_id": { + "name": "finding_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "project_id": { + "name": "project_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "scan_id": { + "name": "scan_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "actor_kind": { + "name": "actor_kind", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "actor_user_id": { + "name": "actor_user_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "actor_role": { + "name": "actor_role", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "action": { + "name": "action", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "resolution": { + "name": "resolution", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "comment": { + "name": "comment", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "severity_from": { + "name": "severity_from", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "severity_to": { + "name": "severity_to", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "idx_security_finding_events_project_created": { + "name": "idx_security_finding_events_project_created", + "columns": [ + { + "expression": "project_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "idx_security_finding_events_finding_created": { + "name": "idx_security_finding_events_finding_created", + "columns": [ + { + "expression": "finding_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "security_finding_events_finding_id_security_findings_id_fk": { + "name": "security_finding_events_finding_id_security_findings_id_fk", + "tableFrom": "security_finding_events", + "tableTo": "security_findings", + "columnsFrom": ["finding_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "security_finding_events_project_id_projects_id_fk": { + "name": "security_finding_events_project_id_projects_id_fk", + "tableFrom": "security_finding_events", + "tableTo": "projects", + "columnsFrom": ["project_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "security_finding_events_actor_kind": { + "name": "security_finding_events_actor_kind", + "value": "(\"security_finding_events\".\"actor_kind\" IN ('user', 'installation_admin', 'scanner', 'system'))" + }, + "security_finding_events_action": { + "name": "security_finding_events_action", + "value": "(\"security_finding_events\".\"action\" IN ('created', 'seen_again', 'seen_again_stale', 'severity_changed', 'promoted', 'not_seen', 'resolved', 'reopened', 'commented', 'severity_edited'))" + }, + "security_finding_events_resolution": { + "name": "security_finding_events_resolution", + "value": "(\"security_finding_events\".\"resolution\" IS NULL OR (\"security_finding_events\".\"resolution\" IN ('fixed', 'false_positive', 'accepted_risk')))" + }, + "security_finding_events_severity_from": { + "name": "security_finding_events_severity_from", + "value": "(\"security_finding_events\".\"severity_from\" IS NULL OR (\"security_finding_events\".\"severity_from\" IN ('critical', 'high', 'medium', 'low', 'informational')))" + }, + "security_finding_events_severity_to": { + "name": "security_finding_events_severity_to", + "value": "(\"security_finding_events\".\"severity_to\" IS NULL OR (\"security_finding_events\".\"severity_to\" IN ('critical', 'high', 'medium', 'low', 'informational')))" + }, + "security_finding_events_comment": { + "name": "security_finding_events_comment", + "value": "\"security_finding_events\".\"comment\" IS NULL OR char_length(\"security_finding_events\".\"comment\") BETWEEN 1 AND 4000" + } + }, + "isRLSEnabled": false + }, + "public.security_findings": { + "name": "security_findings", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "project_id": { + "name": "project_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "number": { + "name": "number", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "fingerprint_key": { + "name": "fingerprint_key", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "model_fingerprint": { + "name": "model_fingerprint", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "verdict": { + "name": "verdict", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "verdict_source": { + "name": "verdict_source", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'static'" + }, + "severity": { + "name": "severity", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "severity_override": { + "name": "severity_override", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "confidence": { + "name": "confidence", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "title": { + "name": "title", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "category": { + "name": "category", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "cwe": { + "name": "cwe", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "file": { + "name": "file", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "line_start": { + "name": "line_start", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "line_end": { + "name": "line_end", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "detail": { + "name": "detail", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'{}'::jsonb" + }, + "sink_path": { + "name": "sink_path", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "sink_content_hash": { + "name": "sink_content_hash", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "outside_diff": { + "name": "outside_diff", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "source": { + "name": "source", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'scanner'" + }, + "state": { + "name": "state", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'open'" + }, + "resolution": { + "name": "resolution", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "resolved_by_user_id": { + "name": "resolved_by_user_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "resolved_at": { + "name": "resolved_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "resolved_sink_hash": { + "name": "resolved_sink_hash", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "resolved_severity": { + "name": "resolved_severity", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "not_seen_in_latest": { + "name": "not_seen_in_latest", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "possible_duplicate_of": { + "name": "possible_duplicate_of", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "reopen_count": { + "name": "reopen_count", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "revision": { + "name": "revision", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 1 + }, + "fix_checked_scan_id": { + "name": "fix_checked_scan_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "first_scan_id": { + "name": "first_scan_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "last_seen_scan_id": { + "name": "last_seen_scan_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "first_deployment_id": { + "name": "first_deployment_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "idx_security_findings_urgent": { + "name": "idx_security_findings_urgent", + "columns": [ + { + "expression": "project_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"security_findings\".\"verdict\" = 'confirmed' AND COALESCE(\"security_findings\".\"severity_override\", \"security_findings\".\"severity\") IN ('critical', 'high') AND \"security_findings\".\"state\" = 'open'", + "concurrently": false, + "method": "btree", + "with": {} + }, + "idx_security_findings_project_state": { + "name": "idx_security_findings_project_state", + "columns": [ + { + "expression": "project_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "state", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "number", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "security_findings_project_id_projects_id_fk": { + "name": "security_findings_project_id_projects_id_fk", + "tableFrom": "security_findings", + "tableTo": "projects", + "columnsFrom": ["project_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "security_findings_project_number": { + "name": "security_findings_project_number", + "nullsNotDistinct": false, + "columns": ["project_id", "number"] + }, + "security_findings_project_fingerprint": { + "name": "security_findings_project_fingerprint", + "nullsNotDistinct": false, + "columns": ["project_id", "fingerprint_key"] + } + }, + "policies": {}, + "checkConstraints": { + "security_findings_number": { + "name": "security_findings_number", + "value": "\"security_findings\".\"number\" > 0" + }, + "security_findings_verdict": { + "name": "security_findings_verdict", + "value": "(\"security_findings\".\"verdict\" IN ('confirmed', 'needs_validation'))" + }, + "security_findings_verdict_source": { + "name": "security_findings_verdict_source", + "value": "(\"security_findings\".\"verdict_source\" IN ('static', 'runtime'))" + }, + "security_findings_severity": { + "name": "security_findings_severity", + "value": "(\"security_findings\".\"severity\" IS NULL OR (\"security_findings\".\"severity\" IN ('critical', 'high', 'medium', 'low', 'informational')))" + }, + "security_findings_severity_override": { + "name": "security_findings_severity_override", + "value": "(\"security_findings\".\"severity_override\" IS NULL OR (\"security_findings\".\"severity_override\" IN ('critical', 'high', 'medium', 'low', 'informational')))" + }, + "security_findings_resolved_severity": { + "name": "security_findings_resolved_severity", + "value": "(\"security_findings\".\"resolved_severity\" IS NULL OR (\"security_findings\".\"resolved_severity\" IN ('critical', 'high', 'medium', 'low', 'informational')))" + }, + "security_findings_source": { + "name": "security_findings_source", + "value": "(\"security_findings\".\"source\" IN ('scanner', 'server'))" + }, + "security_findings_state": { + "name": "security_findings_state", + "value": "(\"security_findings\".\"state\" IN ('open', 'resolved'))" + }, + "security_findings_resolution": { + "name": "security_findings_resolution", + "value": "(\"security_findings\".\"resolution\" IS NULL) = (\"security_findings\".\"state\" = 'open') AND (\"security_findings\".\"resolution\" IS NULL OR (\"security_findings\".\"resolution\" IN ('fixed', 'false_positive', 'accepted_risk')))" + }, + "security_findings_resolved_at": { + "name": "security_findings_resolved_at", + "value": "\"security_findings\".\"state\" = 'open' OR \"security_findings\".\"resolved_at\" IS NOT NULL" + }, + "security_findings_counts": { + "name": "security_findings_counts", + "value": "\"security_findings\".\"reopen_count\" >= 0 AND \"security_findings\".\"revision\" > 0" + }, + "security_findings_lines": { + "name": "security_findings_lines", + "value": "\"security_findings\".\"line_start\" IS NULL OR \"security_findings\".\"line_end\" IS NULL OR \"security_findings\".\"line_end\" >= \"security_findings\".\"line_start\"" + }, + "security_findings_detail_size": { + "name": "security_findings_detail_size", + "value": "octet_length(\"security_findings\".\"detail\"::text) <= 32768" + } + }, + "isRLSEnabled": false + }, + "public.security_memory_rejected": { + "name": "security_memory_rejected", + "schema": "", + "columns": { + "project_id": { + "name": "project_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "fingerprint_key": { + "name": "fingerprint_key", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "reason": { + "name": "reason", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "scan_id": { + "name": "scan_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "idx_security_memory_rejected_project_created": { + "name": "idx_security_memory_rejected_project_created", + "columns": [ + { + "expression": "project_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "security_memory_rejected_project_id_projects_id_fk": { + "name": "security_memory_rejected_project_id_projects_id_fk", + "tableFrom": "security_memory_rejected", + "tableTo": "projects", + "columnsFrom": ["project_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "security_memory_rejected_project_id_fingerprint_key_pk": { + "name": "security_memory_rejected_project_id_fingerprint_key_pk", + "columns": ["project_id", "fingerprint_key"] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "security_memory_rejected_reason": { + "name": "security_memory_rejected_reason", + "value": "octet_length(\"security_memory_rejected\".\"reason\") <= 1024" + } + }, + "isRLSEnabled": false + }, + "public.security_notifications": { + "name": "security_notifications", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "kind": { + "name": "kind", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "project_id": { + "name": "project_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "scan_ids": { + "name": "scan_ids", + "type": "text[]", + "primaryKey": false, + "notNull": true, + "default": "'{}'::text[]" + }, + "request_id": { + "name": "request_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "scan_bypass_id": { + "name": "scan_bypass_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "dedupe_key": { + "name": "dedupe_key", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'pending'" + }, + "attempts": { + "name": "attempts", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "next_attempt_at": { + "name": "next_attempt_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "sent_at": { + "name": "sent_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "idx_security_notifications_due": { + "name": "idx_security_notifications_due", + "columns": [ + { + "expression": "next_attempt_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"security_notifications\".\"status\" = 'pending'", + "concurrently": false, + "method": "btree", + "with": {} + }, + "idx_security_notifications_project_created": { + "name": "idx_security_notifications_project_created", + "columns": [ + { + "expression": "project_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "security_notifications_project_id_projects_id_fk": { + "name": "security_notifications_project_id_projects_id_fk", + "tableFrom": "security_notifications", + "tableTo": "projects", + "columnsFrom": ["project_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "security_notifications_dedupe_key": { + "name": "security_notifications_dedupe_key", + "nullsNotDistinct": false, + "columns": ["dedupe_key"] + } + }, + "policies": {}, + "checkConstraints": { + "security_notifications_kind": { + "name": "security_notifications_kind", + "value": "(\"security_notifications\".\"kind\" IN ('findings', 'reopen', 'cap_project', 'cap_platform', 'public_held', 'public_now_public', 'public_canceled', 'scan_bypass', 'streak_project', 'streak_installation', 'digest', 'webhook'))" + }, + "security_notifications_status": { + "name": "security_notifications_status", + "value": "(\"security_notifications\".\"status\" IN ('pending', 'sent', 'failed', 'skipped'))" + }, + "security_notifications_project": { + "name": "security_notifications_project", + "value": "\"security_notifications\".\"kind\" = 'webhook' OR (\"security_notifications\".\"project_id\" IS NULL) = (\"security_notifications\".\"kind\" IN ('cap_platform', 'streak_installation', 'digest'))" + }, + "security_notifications_attempts": { + "name": "security_notifications_attempts", + "value": "\"security_notifications\".\"attempts\" >= 0" + } + }, + "isRLSEnabled": false + }, + "public.security_platform_spend": { + "name": "security_platform_spend", + "schema": "", + "columns": { + "month": { + "name": "month", + "type": "date", + "primaryKey": true, + "notNull": true + }, + "spent_nano_usd": { + "name": "spent_nano_usd", + "type": "bigint", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "reserved_nano_usd": { + "name": "reserved_nano_usd", + "type": "bigint", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "alerted_80_at": { + "name": "alerted_80_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "alerted_100_at": { + "name": "alerted_100_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "security_platform_spend_month": { + "name": "security_platform_spend_month", + "value": "EXTRACT(DAY FROM \"security_platform_spend\".\"month\") = 1" + }, + "security_platform_spend_nonnegative": { + "name": "security_platform_spend_nonnegative", + "value": "\"security_platform_spend\".\"spent_nano_usd\" >= 0 AND \"security_platform_spend\".\"reserved_nano_usd\" >= 0" + } + }, + "isRLSEnabled": false + }, + "public.security_project_events": { + "name": "security_project_events", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "project_id": { + "name": "project_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "actor_kind": { + "name": "actor_kind", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "actor_user_id": { + "name": "actor_user_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "actor_role": { + "name": "actor_role", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "action": { + "name": "action", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "cap_kind": { + "name": "cap_kind", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "old_cents": { + "name": "old_cents", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "new_cents": { + "name": "new_cents", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "request_id": { + "name": "request_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "request_state": { + "name": "request_state", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "idx_security_project_events_project_created": { + "name": "idx_security_project_events_project_created", + "columns": [ + { + "expression": "project_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "security_project_events_project_id_projects_id_fk": { + "name": "security_project_events_project_id_projects_id_fk", + "tableFrom": "security_project_events", + "tableTo": "projects", + "columnsFrom": ["project_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "security_project_events_actor_kind": { + "name": "security_project_events_actor_kind", + "value": "(\"security_project_events\".\"actor_kind\" IN ('user', 'installation_admin', 'system'))" + }, + "security_project_events_action": { + "name": "security_project_events_action", + "value": "(\"security_project_events\".\"action\" IN ('cap_changed', 'public_requested', 'public_held', 'public_passed', 'public_canceled', 'scan_bypassed', 'protection_on', 'protection_off'))" + }, + "security_project_events_cap_kind": { + "name": "security_project_events_cap_kind", + "value": "(\"security_project_events\".\"cap_kind\" IS NULL OR (\"security_project_events\".\"cap_kind\" IN ('own', 'ceiling')))" + }, + "security_project_events_old_cents": { + "name": "security_project_events_old_cents", + "value": "(\"security_project_events\".\"old_cents\" IS NULL OR \"security_project_events\".\"old_cents\" BETWEEN 0 AND 100000000)" + }, + "security_project_events_new_cents": { + "name": "security_project_events_new_cents", + "value": "(\"security_project_events\".\"new_cents\" IS NULL OR \"security_project_events\".\"new_cents\" BETWEEN 0 AND 100000000)" + }, + "security_project_events_request_state": { + "name": "security_project_events_request_state", + "value": "(\"security_project_events\".\"request_state\" IS NULL OR (\"security_project_events\".\"request_state\" IN ('waiting_scan', 'held_findings', 'held_no_result', 'needs_deploy', 'passed', 'bypassed', 'canceled')))" + } + }, + "isRLSEnabled": false + }, + "public.security_project_spend": { + "name": "security_project_spend", + "schema": "", + "columns": { + "project_id": { + "name": "project_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "month": { + "name": "month", + "type": "date", + "primaryKey": false, + "notNull": true + }, + "spent_nano_usd": { + "name": "spent_nano_usd", + "type": "bigint", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "reserved_nano_usd": { + "name": "reserved_nano_usd", + "type": "bigint", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "scans": { + "name": "scans", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "alerted_80_at": { + "name": "alerted_80_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "alerted_100_at": { + "name": "alerted_100_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": { + "security_project_spend_project_id_projects_id_fk": { + "name": "security_project_spend_project_id_projects_id_fk", + "tableFrom": "security_project_spend", + "tableTo": "projects", + "columnsFrom": ["project_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "security_project_spend_project_id_month_pk": { + "name": "security_project_spend_project_id_month_pk", + "columns": ["project_id", "month"] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "security_project_spend_month": { + "name": "security_project_spend_month", + "value": "EXTRACT(DAY FROM \"security_project_spend\".\"month\") = 1" + }, + "security_project_spend_nonnegative": { + "name": "security_project_spend_nonnegative", + "value": "\"security_project_spend\".\"spent_nano_usd\" >= 0 AND \"security_project_spend\".\"reserved_nano_usd\" >= 0 AND \"security_project_spend\".\"scans\" >= 0" + } + }, + "isRLSEnabled": false + }, + "public.security_public_requests": { + "name": "security_public_requests", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "project_id": { + "name": "project_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "state": { + "name": "state", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "held_reason": { + "name": "held_reason", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "requested_by_user_id": { + "name": "requested_by_user_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "requested_via": { + "name": "requested_via", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "target_deployment_id": { + "name": "target_deployment_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "gate_scan_id": { + "name": "gate_scan_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "blockers": { + "name": "blockers", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "blocker_ids": { + "name": "blocker_ids", + "type": "text[]", + "primaryKey": false, + "notNull": true, + "default": "'{}'::text[]" + }, + "cancel_cause": { + "name": "cancel_cause", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "closed_by_user_id": { + "name": "closed_by_user_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "closed_at": { + "name": "closed_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "revision": { + "name": "revision", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 1 + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "security_public_requests_open_project": { + "name": "security_public_requests_open_project", + "columns": [ + { + "expression": "project_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "(\"security_public_requests\".\"state\" IN ('waiting_scan', 'held_findings', 'held_no_result', 'needs_deploy'))", + "concurrently": false, + "method": "btree", + "with": {} + }, + "idx_security_public_requests_state_updated": { + "name": "idx_security_public_requests_state_updated", + "columns": [ + { + "expression": "state", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "updated_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "idx_security_public_requests_project_created": { + "name": "idx_security_public_requests_project_created", + "columns": [ + { + "expression": "project_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "security_public_requests_project_id_projects_id_fk": { + "name": "security_public_requests_project_id_projects_id_fk", + "tableFrom": "security_public_requests", + "tableTo": "projects", + "columnsFrom": ["project_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "security_public_requests_state": { + "name": "security_public_requests_state", + "value": "(\"security_public_requests\".\"state\" IN ('waiting_scan', 'held_findings', 'held_no_result', 'needs_deploy', 'passed', 'bypassed', 'canceled'))" + }, + "security_public_requests_requested_via": { + "name": "security_public_requests_requested_via", + "value": "(\"security_public_requests\".\"requested_via\" IN ('project', 'admin', 'operator'))" + }, + "security_public_requests_cancel_cause": { + "name": "security_public_requests_cancel_cause", + "value": "(\"security_public_requests\".\"cancel_cause\" IS NULL) = (\"security_public_requests\".\"state\" <> 'canceled') AND (\"security_public_requests\".\"cancel_cause\" IS NULL OR (\"security_public_requests\".\"cancel_cause\" IN ('protect', 'gate_off', 'policy_off')))" + }, + "security_public_requests_closed": { + "name": "security_public_requests_closed", + "value": "(\"security_public_requests\".\"closed_at\" IS NULL) = (\"security_public_requests\".\"state\" IN ('waiting_scan', 'held_findings', 'held_no_result', 'needs_deploy'))" + }, + "security_public_requests_blockers": { + "name": "security_public_requests_blockers", + "value": "\"security_public_requests\".\"blockers\" >= 0" + }, + "security_public_requests_revision": { + "name": "security_public_requests_revision", + "value": "\"security_public_requests\".\"revision\" > 0" + } + }, + "isRLSEnabled": false + }, + "public.security_scan_bypasses": { + "name": "security_scan_bypasses", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "project_id": { + "name": "project_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "request_id": { + "name": "request_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "deployment_id": { + "name": "deployment_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "actor_kind": { + "name": "actor_kind", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "actor_user_id": { + "name": "actor_user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "actor_role": { + "name": "actor_role", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "reason": { + "name": "reason", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "request_state": { + "name": "request_state", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "held_reason": { + "name": "held_reason", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "gate_scan_id": { + "name": "gate_scan_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "blockers": { + "name": "blockers", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "blocker_ids": { + "name": "blocker_ids", + "type": "text[]", + "primaryKey": false, + "notNull": true, + "default": "'{}'::text[]" + }, + "notified_at": { + "name": "notified_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "idx_security_scan_bypasses_created": { + "name": "idx_security_scan_bypasses_created", + "columns": [ + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "idx_security_scan_bypasses_project_created": { + "name": "idx_security_scan_bypasses_project_created", + "columns": [ + { + "expression": "project_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "idx_security_scan_bypasses_request": { + "name": "idx_security_scan_bypasses_request", + "columns": [ + { + "expression": "request_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "security_scan_bypasses_project_id_projects_id_fk": { + "name": "security_scan_bypasses_project_id_projects_id_fk", + "tableFrom": "security_scan_bypasses", + "tableTo": "projects", + "columnsFrom": ["project_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "security_scan_bypasses_request_fk": { + "name": "security_scan_bypasses_request_fk", + "tableFrom": "security_scan_bypasses", + "tableTo": "security_public_requests", + "columnsFrom": ["request_id"], + "columnsTo": ["id"], + "onDelete": "no action", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "security_scan_bypasses_actor_kind": { + "name": "security_scan_bypasses_actor_kind", + "value": "(\"security_scan_bypasses\".\"actor_kind\" IN ('user', 'installation_admin'))" + }, + "security_scan_bypasses_reason": { + "name": "security_scan_bypasses_reason", + "value": "char_length(\"security_scan_bypasses\".\"reason\") BETWEEN 1 AND 4000" + }, + "security_scan_bypasses_request_state": { + "name": "security_scan_bypasses_request_state", + "value": "(\"security_scan_bypasses\".\"request_state\" IN ('waiting_scan', 'held_no_result', 'needs_deploy'))" + }, + "security_scan_bypasses_blockers": { + "name": "security_scan_bypasses_blockers", + "value": "\"security_scan_bypasses\".\"blockers\" >= 0" + } + }, + "isRLSEnabled": false + }, + "public.security_scans": { + "name": "security_scans", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "project_id": { + "name": "project_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "deployment_id": { + "name": "deployment_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "base_deployment_id": { + "name": "base_deployment_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "base_scan_id": { + "name": "base_scan_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "status_reason": { + "name": "status_reason", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "failure_cause": { + "name": "failure_cause", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "error_class": { + "name": "error_class", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "refusal_category": { + "name": "refusal_category", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "superseded_by_scan_id": { + "name": "superseded_by_scan_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "trigger": { + "name": "trigger", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "public_request_id": { + "name": "public_request_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "tier": { + "name": "tier", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "coverage": { + "name": "coverage", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "coverage_notes": { + "name": "coverage_notes", + "type": "text[]", + "primaryKey": false, + "notNull": true, + "default": "'{}'::text[]" + }, + "backlog_files": { + "name": "backlog_files", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "dropped_files": { + "name": "dropped_files", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "dropped_bytes": { + "name": "dropped_bytes", + "type": "bigint", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "files_scanned": { + "name": "files_scanned", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "input_bytes": { + "name": "input_bytes", + "type": "bigint", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "input_prefix": { + "name": "input_prefix", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "input_r2_key": { + "name": "input_r2_key", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "ledger_summary": { + "name": "ledger_summary", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "model_requested": { + "name": "model_requested", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "model_used": { + "name": "model_used", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "engine": { + "name": "engine", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "engine_version": { + "name": "engine_version", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "skill_commit": { + "name": "skill_commit", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "policy_mode_at_enqueue": { + "name": "policy_mode_at_enqueue", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "public_at_enqueue": { + "name": "public_at_enqueue", + "type": "boolean", + "primaryKey": false, + "notNull": false + }, + "attempt": { + "name": "attempt", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "lease_until": { + "name": "lease_until", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "model_calls": { + "name": "model_calls", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "tokens_in": { + "name": "tokens_in", + "type": "bigint", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "tokens_out": { + "name": "tokens_out", + "type": "bigint", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "cost_nano_usd": { + "name": "cost_nano_usd", + "type": "bigint", + "primaryKey": false, + "notNull": false + }, + "metered_nano_usd": { + "name": "metered_nano_usd", + "type": "bigint", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "reserved_nano_usd": { + "name": "reserved_nano_usd", + "type": "bigint", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "summary": { + "name": "summary", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "first_queued_at": { + "name": "first_queued_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "queued_at": { + "name": "queued_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "started_at": { + "name": "started_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "finished_at": { + "name": "finished_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "notified_at": { + "name": "notified_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "idx_security_scans_project_status_finished": { + "name": "idx_security_scans_project_status_finished", + "columns": [ + { + "expression": "project_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "finished_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "security_scans_running_project": { + "name": "security_scans_running_project", + "columns": [ + { + "expression": "project_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "\"security_scans\".\"status\" = 'running'", + "concurrently": false, + "method": "btree", + "with": {} + }, + "idx_security_scans_waiting": { + "name": "idx_security_scans_waiting", + "columns": [ + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "first_queued_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "(\"security_scans\".\"status\" IN ('pending_input', 'queued', 'running'))", + "concurrently": false, + "method": "btree", + "with": {} + }, + "idx_security_scans_input_hold": { + "name": "idx_security_scans_input_hold", + "columns": [ + { + "expression": "input_prefix", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"security_scans\".\"input_prefix\" IS NOT NULL AND (\"security_scans\".\"status\" IN ('pending_input', 'queued'))", + "concurrently": false, + "method": "btree", + "with": {} + }, + "idx_security_scans_deployment": { + "name": "idx_security_scans_deployment", + "columns": [ + { + "expression": "project_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "deployment_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "security_scans_project_id_projects_id_fk": { + "name": "security_scans_project_id_projects_id_fk", + "tableFrom": "security_scans", + "tableTo": "projects", + "columnsFrom": ["project_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "security_scans_status": { + "name": "security_scans_status", + "value": "(\"security_scans\".\"status\" IN ('pending_input', 'queued', 'running', 'succeeded', 'incomplete', 'failed', 'refused', 'timed_out', 'superseded', 'skipped', 'canceled'))" + }, + "security_scans_trigger": { + "name": "security_scans_trigger", + "value": "(\"security_scans\".\"trigger\" IN ('deploy', 'recovery', 'exposure', 'rescan', 'gate', 'local', 'sweep', 'backfill', 'fallback'))" + }, + "security_scans_deployment": { + "name": "security_scans_deployment", + "value": "\"security_scans\".\"deployment_id\" IS NOT NULL OR \"security_scans\".\"trigger\" = 'local'" + }, + "security_scans_failure_cause": { + "name": "security_scans_failure_cause", + "value": "(\"security_scans\".\"failure_cause\" IS NULL OR (\"security_scans\".\"failure_cause\" IN ('installation', 'project')))" + }, + "security_scans_tier": { + "name": "security_scans_tier", + "value": "(\"security_scans\".\"tier\" IS NULL OR (\"security_scans\".\"tier\" IN ('source_diff', 'built_diff', 'full')))" + }, + "security_scans_coverage": { + "name": "security_scans_coverage", + "value": "(\"security_scans\".\"coverage\" IS NULL OR (\"security_scans\".\"coverage\" IN ('complete', 'partial')))" + }, + "security_scans_engine": { + "name": "security_scans_engine", + "value": "(\"security_scans\".\"engine\" IS NULL OR (\"security_scans\".\"engine\" IN ('void_loop', 'agent_sdk', 'codex_sdk')))" + }, + "security_scans_policy_mode": { + "name": "security_scans_policy_mode", + "value": "(\"security_scans\".\"policy_mode_at_enqueue\" IS NULL OR (\"security_scans\".\"policy_mode_at_enqueue\" IN ('disabled', 'public', 'all')))" + }, + "security_scans_running_lease": { + "name": "security_scans_running_lease", + "value": "\"security_scans\".\"status\" <> 'running' OR \"security_scans\".\"lease_until\" IS NOT NULL" + }, + "security_scans_counts": { + "name": "security_scans_counts", + "value": "\"security_scans\".\"attempt\" >= 0 AND \"security_scans\".\"backlog_files\" >= 0 AND \"security_scans\".\"dropped_files\" >= 0 AND \"security_scans\".\"dropped_bytes\" >= 0 AND \"security_scans\".\"files_scanned\" >= 0 AND \"security_scans\".\"input_bytes\" >= 0 AND \"security_scans\".\"model_calls\" >= 0 AND \"security_scans\".\"tokens_in\" >= 0 AND \"security_scans\".\"tokens_out\" >= 0 AND \"security_scans\".\"metered_nano_usd\" >= 0 AND \"security_scans\".\"reserved_nano_usd\" >= 0 AND (\"security_scans\".\"cost_nano_usd\" IS NULL OR \"security_scans\".\"cost_nano_usd\" >= 0)" + }, + "security_scans_ledger_size": { + "name": "security_scans_ledger_size", + "value": "\"security_scans\".\"ledger_summary\" IS NULL OR octet_length(\"security_scans\".\"ledger_summary\"::text) <= 8192" + }, + "security_scans_summary_size": { + "name": "security_scans_summary_size", + "value": "\"security_scans\".\"summary\" IS NULL OR octet_length(\"security_scans\".\"summary\") <= 16384" + } + }, + "isRLSEnabled": false + } + }, + "enums": {}, + "schemas": {}, + "sequences": {}, + "roles": {}, + "policies": {}, + "views": {}, + "_meta": { + "columns": {}, + "schemas": {}, + "tables": {} + } +} diff --git a/platform/packages/api/drizzle/meta/_journal.json b/platform/packages/api/drizzle/meta/_journal.json index 0764d3fa8..a79753e54 100644 --- a/platform/packages/api/drizzle/meta/_journal.json +++ b/platform/packages/api/drizzle/meta/_journal.json @@ -407,6 +407,13 @@ "when": 1794435917244, "tag": "0064_project_ai_logging", "breakpoints": true + }, + { + "idx": 65, + "version": "7", + "when": 1794980793652, + "tag": "0065_security_audits", + "breakpoints": true } ] } diff --git a/platform/packages/api/scripts/build-security-scanner-controller.mjs b/platform/packages/api/scripts/build-security-scanner-controller.mjs new file mode 100644 index 000000000..89eaf1dcb --- /dev/null +++ b/platform/packages/api/scripts/build-security-scanner-controller.mjs @@ -0,0 +1,90 @@ +import { spawnSync } from 'node:child_process'; +import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { dirname, join, resolve } from 'node:path'; +import { fileURLToPath, pathToFileURL } from 'node:url'; +import { build } from 'vite'; + +const packageRoot = fileURLToPath(new URL('..', import.meta.url)); +const scannerRoot = join(packageRoot, '../security-scanner'); + +/** + * One Node file with no dependencies (node built-ins stay imports). The controller + * streams it into the managed scanner image at start (Engine B, design doc 0095 R1 + * option C); the Engine A/C images copy the same file in. + */ +export async function buildSecurityScannerRunner(outputDirectory) { + await build({ + configFile: false, + root: scannerRoot, + publicDir: false, + logLevel: 'warn', + build: { + ssr: join(scannerRoot, 'src/runner/main.ts'), + outDir: outputDirectory, + emptyOutDir: true, + minify: false, + sourcemap: false, + target: 'node22', + rollupOptions: { output: { format: 'es', entryFileNames: 'runner.mjs' } }, + }, + ssr: { target: 'node', noExternal: true }, + }); + return readFileSync(join(outputDirectory, 'runner.mjs'), 'utf8'); +} + +/** Bundle the scanner controller Worker (runner inside) so the API uploads fixed code. */ +export async function buildSecurityScannerController(outputDirectory = join(packageRoot, 'dist')) { + const temporary = mkdtempSync(join(tmpdir(), 'void-security-scanner-controller-')); + try { + const runner = await buildSecurityScannerRunner(join(temporary, 'runner')); + const runnerModule = join(temporary, 'runner-source.ts'); + writeFileSync(runnerModule, `export default ${JSON.stringify(runner)};\n`); + const config = join(temporary, 'wrangler.json'); + writeFileSync( + config, + JSON.stringify({ + name: 'void-security-scanner-controller-build', + main: join(packageRoot, 'src/security-scanner-controller-runtime.ts'), + compatibility_date: '2026-09-01', + alias: { 'void:security-scanner-runner-source': runnerModule }, + }), + ); + const result = spawnSync( + process.execPath, + [ + fileURLToPath(import.meta.resolve('wrangler')), + 'deploy', + '--dry-run', + '--config', + config, + '--outdir', + join(temporary, 'bundle'), + '--minify', + ], + { cwd: packageRoot, encoding: 'utf8' }, + ); + if (result.status !== 0) { + throw new Error( + `Security scanner controller build failed:\n${result.stdout}\n${result.stderr}`, + ); + } + const bundled = readFileSync( + join(temporary, 'bundle', 'security-scanner-controller-runtime.js'), + 'utf8', + ); + // The upload carries no source map, so drop the trailing reference to one. + const mapComment = bundled.lastIndexOf('\n//# sourceMappingURL='); + const source = mapComment === -1 ? bundled : `${bundled.slice(0, mapComment)}\n`; + const modulePath = join(outputDirectory, 'security-scanner-controller-source.ts'); + mkdirSync(dirname(modulePath), { recursive: true }); + writeFileSync(modulePath, `export default ${JSON.stringify(source)};\n`); + return { source, modulePath }; + } finally { + rmSync(temporary, { recursive: true, force: true }); + } +} + +if (process.argv[1] && import.meta.url === pathToFileURL(resolve(process.argv[1])).href) { + await buildSecurityScannerController(); +} diff --git a/platform/packages/api/scripts/build-worker.mjs b/platform/packages/api/scripts/build-worker.mjs index 537060f0f..44bee12c1 100644 --- a/platform/packages/api/scripts/build-worker.mjs +++ b/platform/packages/api/scripts/build-worker.mjs @@ -1,7 +1,11 @@ import { spawnSync } from 'node:child_process'; import { fileURLToPath } from 'node:url'; -for (const script of ['build-sandbox-controller.mjs', 'build-admin-client.mjs']) { +for (const script of [ + 'build-sandbox-controller.mjs', + 'build-security-scanner-controller.mjs', + 'build-admin-client.mjs', +]) { const result = spawnSync(process.execPath, [fileURLToPath(new URL(script, import.meta.url))], { stdio: 'inherit', }); diff --git a/platform/packages/api/src/admin/fate/client.generated.ts b/platform/packages/api/src/admin/fate/client.generated.ts index 0654e2d9c..ff778ede5 100644 --- a/platform/packages/api/src/admin/fate/client.generated.ts +++ b/platform/packages/api/src/admin/fate/client.generated.ts @@ -1,5 +1,5 @@ // @generated by @nkzw/fate/vite -import type { AdminAuthEdit, AdminAuthNew, AdminAuthSettings, AdminBuildDetail, AdminBuildLogs, AdminBuildStatus, AdminCliVersions, AdminDashboard, AdminDeploymentDetail, AdminDeploymentLogs, AdminDeploymentsPage, AdminEmailProject, AdminEmailSettings, AdminHealth, AdminInvitations, AdminPlans, AdminProjectDetail, AdminProjectsPage, AdminSignup, AdminTopProject, AdminUserDetail, AdminUsersPage, AdminZeroTrust, fateServer } from './server.ts'; +import type { AdminAuthEdit, AdminAuthNew, AdminAuthSettings, AdminBuildDetail, AdminBuildLogs, AdminBuildStatus, AdminCliVersions, AdminDashboard, AdminDeploymentDetail, AdminDeploymentLogs, AdminDeploymentsPage, AdminEmailProject, AdminEmailSettings, AdminHealth, AdminInvitations, AdminPlans, AdminProjectDetail, AdminProjectsPage, AdminSecurity, AdminSignup, AdminTopProject, AdminUserDetail, AdminUsersPage, AdminZeroTrust, fateServer } from './server.ts'; import { clientRoot, createClient, createHTTPTransport, mutation, type InferFateAPI } from 'react-fate'; @@ -28,6 +28,7 @@ const roots = { 'adminPlans': clientRoot, 'AdminPlans'>('AdminPlans'), 'adminProjectDetail': clientRoot, 'AdminProjectDetail'>('AdminProjectDetail'), 'adminProjectsPage': clientRoot, 'AdminProjectsPage'>('AdminProjectsPage'), + 'adminSecurity': clientRoot, 'AdminSecurity'>('AdminSecurity'), 'adminSignup': clientRoot, 'AdminSignup'>('AdminSignup'), 'adminTopProject': clientRoot, 'AdminTopProject'>('AdminTopProject'), 'adminUserDetail': clientRoot, 'AdminUserDetail'>('AdminUserDetail'), @@ -51,6 +52,7 @@ const roots = { 'plans': clientRoot('AdminPlans'), 'projectDetail': clientRoot('AdminProjectDetail'), 'projectsPage': clientRoot('AdminProjectsPage'), + 'security': clientRoot('AdminSecurity'), 'signupControl': clientRoot('AdminSignup'), 'userDetail': clientRoot('AdminUserDetail'), 'usersPage': clientRoot('AdminUsersPage'), @@ -59,7 +61,7 @@ const roots = { export type GeneratedClientMutations = typeof mutations; export type GeneratedClientRoots = typeof roots; -const hydrationScope = "{\"moduleName\":\"./server.ts\",\"roots\":{\"authEdit\":{\"kind\":\"query\",\"procedure\":\"authEdit\",\"router\":\"adminAuthEdit\",\"type\":\"AdminAuthEdit\"},\"authNew\":{\"kind\":\"query\",\"procedure\":\"authNew\",\"router\":\"adminAuthNew\",\"type\":\"AdminAuthNew\"},\"authSettings\":{\"kind\":\"query\",\"procedure\":\"authSettings\",\"router\":\"adminAuthSettings\",\"type\":\"AdminAuthSettings\"},\"buildDetail\":{\"kind\":\"query\",\"procedure\":\"buildDetail\",\"router\":\"adminBuildDetail\",\"type\":\"AdminBuildDetail\"},\"buildLogs\":{\"kind\":\"query\",\"procedure\":\"buildLogs\",\"router\":\"adminBuildLogs\",\"type\":\"AdminBuildLogs\"},\"buildStatus\":{\"kind\":\"query\",\"procedure\":\"buildStatus\",\"router\":\"adminBuildStatus\",\"type\":\"AdminBuildStatus\"},\"cliVersions\":{\"kind\":\"query\",\"procedure\":\"cliVersions\",\"router\":\"adminCliVersions\",\"type\":\"AdminCliVersions\"},\"dashboard\":{\"kind\":\"query\",\"procedure\":\"dashboard\",\"router\":\"adminDashboard\",\"type\":\"AdminDashboard\"},\"deploymentDetail\":{\"kind\":\"query\",\"procedure\":\"deploymentDetail\",\"router\":\"adminDeploymentDetail\",\"type\":\"AdminDeploymentDetail\"},\"deploymentLogs\":{\"kind\":\"query\",\"procedure\":\"deploymentLogs\",\"router\":\"adminDeploymentLogs\",\"type\":\"AdminDeploymentLogs\"},\"deploymentsPage\":{\"kind\":\"query\",\"procedure\":\"deploymentsPage\",\"router\":\"adminDeploymentsPage\",\"type\":\"AdminDeploymentsPage\"},\"emailProject\":{\"kind\":\"query\",\"procedure\":\"emailProject\",\"router\":\"adminEmailProject\",\"type\":\"AdminEmailProject\"},\"emailSettings\":{\"kind\":\"query\",\"procedure\":\"emailSettings\",\"router\":\"adminEmailSettings\",\"type\":\"AdminEmailSettings\"},\"health\":{\"kind\":\"query\",\"procedure\":\"health\",\"router\":\"adminHealth\",\"type\":\"AdminHealth\"},\"invitations\":{\"kind\":\"query\",\"procedure\":\"invitations\",\"router\":\"adminInvitations\",\"type\":\"AdminInvitations\"},\"plans\":{\"kind\":\"query\",\"procedure\":\"plans\",\"router\":\"adminPlans\",\"type\":\"AdminPlans\"},\"projectDetail\":{\"kind\":\"query\",\"procedure\":\"projectDetail\",\"router\":\"adminProjectDetail\",\"type\":\"AdminProjectDetail\"},\"projectsPage\":{\"kind\":\"query\",\"procedure\":\"projectsPage\",\"router\":\"adminProjectsPage\",\"type\":\"AdminProjectsPage\"},\"signupControl\":{\"kind\":\"query\",\"procedure\":\"signupControl\",\"router\":\"adminSignup\",\"type\":\"AdminSignup\"},\"userDetail\":{\"kind\":\"query\",\"procedure\":\"userDetail\",\"router\":\"adminUserDetail\",\"type\":\"AdminUserDetail\"},\"usersPage\":{\"kind\":\"query\",\"procedure\":\"usersPage\",\"router\":\"adminUsersPage\",\"type\":\"AdminUsersPage\"},\"zeroTrust\":{\"kind\":\"query\",\"procedure\":\"zeroTrust\",\"router\":\"adminZeroTrust\",\"type\":\"AdminZeroTrust\"}},\"types\":[{\"type\":\"AdminAuthEdit\"},{\"type\":\"AdminAuthNew\"},{\"type\":\"AdminAuthSettings\"},{\"type\":\"AdminBuildDetail\"},{\"type\":\"AdminBuildLogs\"},{\"type\":\"AdminBuildStatus\"},{\"type\":\"AdminCliVersions\"},{\"fields\":{\"topProjects\":{\"listOf\":\"AdminTopProject\"}},\"type\":\"AdminDashboard\"},{\"type\":\"AdminDeploymentDetail\"},{\"type\":\"AdminDeploymentLogs\"},{\"type\":\"AdminDeploymentsPage\"},{\"type\":\"AdminEmailProject\"},{\"type\":\"AdminEmailSettings\"},{\"type\":\"AdminHealth\"},{\"type\":\"AdminInvitations\"},{\"type\":\"AdminPlans\"},{\"type\":\"AdminProjectDetail\"},{\"type\":\"AdminProjectsPage\"},{\"type\":\"AdminSignup\"},{\"type\":\"AdminTopProject\"},{\"type\":\"AdminUserDetail\"},{\"type\":\"AdminUsersPage\"},{\"type\":\"AdminZeroTrust\"}]}" as const; +const hydrationScope = "{\"moduleName\":\"./server.ts\",\"roots\":{\"authEdit\":{\"kind\":\"query\",\"procedure\":\"authEdit\",\"router\":\"adminAuthEdit\",\"type\":\"AdminAuthEdit\"},\"authNew\":{\"kind\":\"query\",\"procedure\":\"authNew\",\"router\":\"adminAuthNew\",\"type\":\"AdminAuthNew\"},\"authSettings\":{\"kind\":\"query\",\"procedure\":\"authSettings\",\"router\":\"adminAuthSettings\",\"type\":\"AdminAuthSettings\"},\"buildDetail\":{\"kind\":\"query\",\"procedure\":\"buildDetail\",\"router\":\"adminBuildDetail\",\"type\":\"AdminBuildDetail\"},\"buildLogs\":{\"kind\":\"query\",\"procedure\":\"buildLogs\",\"router\":\"adminBuildLogs\",\"type\":\"AdminBuildLogs\"},\"buildStatus\":{\"kind\":\"query\",\"procedure\":\"buildStatus\",\"router\":\"adminBuildStatus\",\"type\":\"AdminBuildStatus\"},\"cliVersions\":{\"kind\":\"query\",\"procedure\":\"cliVersions\",\"router\":\"adminCliVersions\",\"type\":\"AdminCliVersions\"},\"dashboard\":{\"kind\":\"query\",\"procedure\":\"dashboard\",\"router\":\"adminDashboard\",\"type\":\"AdminDashboard\"},\"deploymentDetail\":{\"kind\":\"query\",\"procedure\":\"deploymentDetail\",\"router\":\"adminDeploymentDetail\",\"type\":\"AdminDeploymentDetail\"},\"deploymentLogs\":{\"kind\":\"query\",\"procedure\":\"deploymentLogs\",\"router\":\"adminDeploymentLogs\",\"type\":\"AdminDeploymentLogs\"},\"deploymentsPage\":{\"kind\":\"query\",\"procedure\":\"deploymentsPage\",\"router\":\"adminDeploymentsPage\",\"type\":\"AdminDeploymentsPage\"},\"emailProject\":{\"kind\":\"query\",\"procedure\":\"emailProject\",\"router\":\"adminEmailProject\",\"type\":\"AdminEmailProject\"},\"emailSettings\":{\"kind\":\"query\",\"procedure\":\"emailSettings\",\"router\":\"adminEmailSettings\",\"type\":\"AdminEmailSettings\"},\"health\":{\"kind\":\"query\",\"procedure\":\"health\",\"router\":\"adminHealth\",\"type\":\"AdminHealth\"},\"invitations\":{\"kind\":\"query\",\"procedure\":\"invitations\",\"router\":\"adminInvitations\",\"type\":\"AdminInvitations\"},\"plans\":{\"kind\":\"query\",\"procedure\":\"plans\",\"router\":\"adminPlans\",\"type\":\"AdminPlans\"},\"projectDetail\":{\"kind\":\"query\",\"procedure\":\"projectDetail\",\"router\":\"adminProjectDetail\",\"type\":\"AdminProjectDetail\"},\"projectsPage\":{\"kind\":\"query\",\"procedure\":\"projectsPage\",\"router\":\"adminProjectsPage\",\"type\":\"AdminProjectsPage\"},\"security\":{\"kind\":\"query\",\"procedure\":\"security\",\"router\":\"adminSecurity\",\"type\":\"AdminSecurity\"},\"signupControl\":{\"kind\":\"query\",\"procedure\":\"signupControl\",\"router\":\"adminSignup\",\"type\":\"AdminSignup\"},\"userDetail\":{\"kind\":\"query\",\"procedure\":\"userDetail\",\"router\":\"adminUserDetail\",\"type\":\"AdminUserDetail\"},\"usersPage\":{\"kind\":\"query\",\"procedure\":\"usersPage\",\"router\":\"adminUsersPage\",\"type\":\"AdminUsersPage\"},\"zeroTrust\":{\"kind\":\"query\",\"procedure\":\"zeroTrust\",\"router\":\"adminZeroTrust\",\"type\":\"AdminZeroTrust\"}},\"types\":[{\"type\":\"AdminAuthEdit\"},{\"type\":\"AdminAuthNew\"},{\"type\":\"AdminAuthSettings\"},{\"type\":\"AdminBuildDetail\"},{\"type\":\"AdminBuildLogs\"},{\"type\":\"AdminBuildStatus\"},{\"type\":\"AdminCliVersions\"},{\"fields\":{\"topProjects\":{\"listOf\":\"AdminTopProject\"}},\"type\":\"AdminDashboard\"},{\"type\":\"AdminDeploymentDetail\"},{\"type\":\"AdminDeploymentLogs\"},{\"type\":\"AdminDeploymentsPage\"},{\"type\":\"AdminEmailProject\"},{\"type\":\"AdminEmailSettings\"},{\"type\":\"AdminHealth\"},{\"type\":\"AdminInvitations\"},{\"type\":\"AdminPlans\"},{\"type\":\"AdminProjectDetail\"},{\"type\":\"AdminProjectsPage\"},{\"type\":\"AdminSecurity\"},{\"type\":\"AdminSignup\"},{\"type\":\"AdminTopProject\"},{\"type\":\"AdminUserDetail\"},{\"type\":\"AdminUsersPage\"},{\"type\":\"AdminZeroTrust\"}]}" as const; export const createFateClient = (options: { fetch?: typeof fetch; @@ -148,6 +150,9 @@ export const createFateClient = (options: { { type: 'AdminZeroTrust', }, + { + type: 'AdminSecurity', + }, { type: 'AdminBuildLogs', }, diff --git a/platform/packages/api/src/admin/fate/page-data.ts b/platform/packages/api/src/admin/fate/page-data.ts index e7c73624e..566682d0d 100644 --- a/platform/packages/api/src/admin/fate/page-data.ts +++ b/platform/packages/api/src/admin/fate/page-data.ts @@ -2,7 +2,7 @@ import { PLATFORM_LOGIN_KINDS, parsePlatformLoginConfiguration } from '@void/pla import type { PlatformLoginConfiguration } from '@void/platform'; import { and, eq, gt, inArray, ne } from 'drizzle-orm'; import type { Context } from 'hono'; -import { getPlatformCapabilities } from '../../capabilities.ts'; +import { getPlatformCapabilities, securityAuditsEnabled } from '../../capabilities.ts'; import { SITE_DOMAIN } from '../../constants.ts'; import { countDeployments, @@ -34,6 +34,7 @@ import { getPlatformApiUrl, platformConnectCommand } from '../../platform-identi import { projectUrl, projectWithUrl } from '../../project-url.ts'; import { invitations, platformLoginTests } from '../../schema.ts'; import type { DeployManifest } from '../../types.ts'; +import { loadProjectGate, loadProjectSecurity, loadPublicGateOn } from '../security-data.ts'; type AdminContext = Context; const PAGE_SIZE = 20; @@ -211,6 +212,10 @@ export async function loadProjectDetailPage(context: AdminContext, path: string) getPendingProjectInvitations(db, id), loadProjectZeroTrust(db, id), ]); + const [gate, security] = await Promise.all([ + loadProjectGate(context, detail.project), + loadProjectSecurity(context, detail.project), + ]); return { id: path, ...detail, @@ -226,7 +231,8 @@ export async function loadProjectDetailPage(context: AdminContext, path: string) role: invitation.role, expiresAt: invitation.expires_at, })), - zeroTrust, + zeroTrust: { ...zeroTrust, gate }, + security, cfAccountId: context.env.CF_ACCOUNT_ID, deployUrl: projectUrl(detail.project, context.env), tz: requestTimezone(context), @@ -468,6 +474,7 @@ export async function loadZeroTrustPage(context: AdminContext, path: string) { const saved = 'accountId' in status ? status : null; return { id: path, + publicGate: await loadPublicGateOn(context), configured: status.configured, enabled: status.enabled, status: 'status' in status ? status.status : null, @@ -507,13 +514,17 @@ export async function loadPlansPage(context: AdminContext, path: string) { } const initialPlanDefault = initialPlanDefaultFor(context.env); const { readPlanAiLoggingProgress } = await import('../../ai-logging-plans.ts'); - const [data, aiLogging] = await Promise.all([ + const { readSecurityPlanCaps } = await import('../../security/plan-caps.ts'); + const [data, aiLogging, securityCaps] = await Promise.all([ readPlanCatalogWithAccounts(context.get('db'), initialPlanDefault), readPlanAiLoggingProgress(context.get('db'), initialPlanDefault), + readSecurityPlanCaps(context.get('db')), ]); + // The scan cap column and field show only while security audits are on (M27). + const securityAudits = securityAuditsEnabled(context.env); const selectedPlanId = match?.[1] ?? null; if (selectedPlanId && !data.catalog.plans.some((plan) => plan.id === selectedPlanId)) { throw new OperatorError(404, 'Plan not found.'); } - return { id: path, ...data, aiLogging, selectedPlanId }; + return { id: path, ...data, aiLogging, securityCaps, securityAudits, selectedPlanId }; } diff --git a/platform/packages/api/src/admin/fate/page-server.ts b/platform/packages/api/src/admin/fate/page-server.ts index 0619de3c1..22e99b9c0 100644 --- a/platform/packages/api/src/admin/fate/page-server.ts +++ b/platform/packages/api/src/admin/fate/page-server.ts @@ -3,6 +3,7 @@ import type { Entity, SourceDefinition, SourceRegistry } from '@nkzw/fate/server import type { Context } from 'hono'; import type { ApiEnv } from '../../env.ts'; import { OperatorError } from '../../operator/common.ts'; +import { loadSecurityAdminPage as loadSecurityPage } from '../security-data.ts'; import { loadPlansPage, loadBuildDetailPage, @@ -29,6 +30,8 @@ export const plansDataView = dataView('AdminPlans')({ catalog: true, accounts: true, aiLogging: true, + securityCaps: true, + securityAudits: true, selectedPlanId: true, }); export type AdminPlans = Entity; @@ -51,6 +54,7 @@ type AuthEditRecord = Awaited>; type EmailSettingsRecord = Awaited>; type EmailProjectRecord = Awaited>; type ZeroTrustRecord = Awaited>; +type SecurityRecord = Awaited>; export const usersPageDataView = dataView('AdminUsersPage')({ id: true, @@ -99,6 +103,7 @@ export const projectDetailDataView = dataView('AdminProject domains: true, builds: true, zeroTrust: true, + security: true, aiLogging: true, cfAccountId: true, deployUrl: true, @@ -189,8 +194,27 @@ export const emailProjectDataView = dataView('AdminEmailProj senderDomain: true, tz: true, }); +export const securityDataView = dataView('AdminSecurity')({ + id: true, + section: true, + capability: true, + emailEnabled: true, + urgentTotal: true, + unseenBypasses: true, + seenAt: true, + revision: true, + tz: true, + page: true, + totalPages: true, + settings: true, + findings: true, + findingFilter: true, + scans: true, + requests: true, +}); export const zeroTrustDataView = dataView('AdminZeroTrust')({ id: true, + publicGate: true, configured: true, enabled: true, status: true, @@ -225,6 +249,7 @@ export type AdminAuthEdit = Entity; export type AdminEmailSettings = Entity; export type AdminEmailProject = Entity; export type AdminZeroTrust = Entity; +export type AdminSecurity = Entity; const usersSource: SourceDefinition = { id: 'id', view: usersPageDataView }; const projectsSource: SourceDefinition = { @@ -272,6 +297,7 @@ const emailProjectSource: SourceDefinition = { view: emailProjectDataView, }; const zeroTrustSource: SourceDefinition = { id: 'id', view: zeroTrustDataView }; +const securitySource: SourceDefinition = { id: 'id', view: securityDataView }; export const pageSourceByType = new Map([ ['AdminPlans', plansSource], @@ -291,6 +317,7 @@ export const pageSourceByType = new Map([ ['AdminEmailSettings', emailSettingsSource], ['AdminEmailProject', emailProjectSource], ['AdminZeroTrust', zeroTrustSource], + ['AdminSecurity', securitySource], ]); export const pageRegistry: SourceRegistry = new Map(); @@ -337,6 +364,7 @@ registerPage(authEditSource, loadAuthEditPage); registerPage(emailSettingsSource, loadEmailSettingsPage); registerPage(emailProjectSource, loadEmailProjectPage); registerPage(zeroTrustSource, loadZeroTrustPage); +registerPage(securitySource, loadSecurityPage); function pagePath(input: { args?: Record }) { const path = input.args?.path; @@ -364,6 +392,7 @@ export const PageRoot = { emailSettings: emailSettingsDataView, emailProject: emailProjectDataView, zeroTrust: zeroTrustDataView, + security: securityDataView, }; function pageQuery(source: SourceDefinition) { @@ -405,4 +434,5 @@ export const pageQueries = { emailSettings: pageQuery(emailSettingsSource), emailProject: pageQuery(emailProjectSource), zeroTrust: pageQuery(zeroTrustSource), + security: pageQuery(securitySource), }; diff --git a/platform/packages/api/src/admin/fate/render.ts b/platform/packages/api/src/admin/fate/render.ts index 10fe383d6..8785432f8 100644 --- a/platform/packages/api/src/admin/fate/render.ts +++ b/platform/packages/api/src/admin/fate/render.ts @@ -26,6 +26,7 @@ import { invitationsRequest, projectDetailRequest, projectsPageRequest, + securityRequest, signupRequest, userDetailRequest, usersPageRequest, @@ -73,6 +74,7 @@ export async function renderFateListPage( | 'authNew' | 'authEdit' | 'email' + | 'security' | 'zeroTrust', ): Promise { const title = { @@ -88,6 +90,7 @@ export async function renderFateListPage( authNew: 'Add login method', authEdit: 'Edit login method', email: 'Email', + security: 'Security', zeroTrust: 'Zero Trust', }[page]; const { pathname, search } = new URL(context.req.url); @@ -123,6 +126,8 @@ export async function renderFateListPage( await client.request(authNewRequest(path)); } else if (page === 'authEdit') { await client.request(authEditRequest(path)); + } else if (page === 'security') { + await client.request(securityRequest(path)); } else if (page === 'zeroTrust') { await client.request(zeroTrustRequest(path)); } else { diff --git a/platform/packages/api/src/admin/fate/server.ts b/platform/packages/api/src/admin/fate/server.ts index bd7c8af0f..e7d68790f 100644 --- a/platform/packages/api/src/admin/fate/server.ts +++ b/platform/packages/api/src/admin/fate/server.ts @@ -40,6 +40,7 @@ export type { AdminAuthEdit, AdminEmailSettings, AdminEmailProject, + AdminSecurity, AdminZeroTrust, } from './page-server.ts'; export type { AdminBuildLogs, AdminBuildStatus, AdminDeploymentLogs } from './telemetry.ts'; diff --git a/platform/packages/api/src/admin/fate/views.ts b/platform/packages/api/src/admin/fate/views.ts index 4aeb6a500..a41215c1c 100644 --- a/platform/packages/api/src/admin/fate/views.ts +++ b/platform/packages/api/src/admin/fate/views.ts @@ -22,6 +22,7 @@ import type { AdminEmailSettings, AdminEmailProject, AdminZeroTrust, + AdminSecurity, AdminBuildLogs, AdminDeploymentLogs, } from './server.ts'; @@ -141,6 +142,7 @@ export const ProjectDetailView = view()({ domains: true, builds: true, zeroTrust: true, + security: true, aiLogging: true, cfAccountId: true, deployUrl: true, @@ -298,6 +300,7 @@ export const emailProjectRequest = (path: string) => export const ZeroTrustView = view()({ id: true, + publicGate: true, configured: true, enabled: true, status: true, @@ -313,6 +316,30 @@ export const ZeroTrustView = view()({ projects: true, }); +export const SecurityView = view()({ + id: true, + section: true, + capability: true, + emailEnabled: true, + urgentTotal: true, + unseenBypasses: true, + seenAt: true, + revision: true, + tz: true, + page: true, + totalPages: true, + settings: true, + findings: true, + findingFilter: true, + scans: true, + requests: true, +}); + +export const securityRequest = (path: string) => + ({ + security: { view: SecurityView, args: { path } }, + }) as const; + export const zeroTrustRequest = (path: string) => ({ zeroTrust: { view: ZeroTrustView, args: { path } }, @@ -323,6 +350,8 @@ export const PlansView = view()({ catalog: true, accounts: true, aiLogging: true, + securityCaps: true, + securityAudits: true, selectedPlanId: true, }); export const plansRequest = (path: string) => diff --git a/platform/packages/api/src/admin/middleware/csrf.ts b/platform/packages/api/src/admin/middleware/csrf.ts index c537083de..051d59946 100644 --- a/platform/packages/api/src/admin/middleware/csrf.ts +++ b/platform/packages/api/src/admin/middleware/csrf.ts @@ -27,7 +27,7 @@ export const adminCsrfMiddleware: MiddlewareHandler = async (context, ne await next(); }; -function parseOrigin(value: string): string | null { +export function parseOrigin(value: string): string | null { try { return new URL(value).origin; } catch { diff --git a/platform/packages/api/src/admin/plans.ts b/platform/packages/api/src/admin/plans.ts index 23c01e9b3..eea545365 100644 --- a/platform/packages/api/src/admin/plans.ts +++ b/platform/packages/api/src/admin/plans.ts @@ -1,4 +1,5 @@ import type { PlatformPlanCatalog } from '@void/platform/plans'; +import type { PlanSecurityCaps } from '@void/platform/security-policy'; import type { PlanAiLoggingSettings } from '../ai-logging-policy.ts'; import type { PlanCatalogAction } from '../operator/plans.ts'; @@ -12,6 +13,11 @@ export type AdminPlanPreview = { /** Plan AI logging defaults before and after the change. */ aiLoggingBefore: PlanAiLoggingSettings['modes']; aiLoggingAfter: PlanAiLoggingSettings['modes']; + /** Per-plan security scan caps before and after the change (M27). */ + securityCapsBefore: PlanSecurityCaps; + securityCapsAfter: PlanSecurityCaps; + /** The scan cap row shows only while security audits are on, as on the Plans page. */ + securityAudits: boolean; affectedAccounts: number; warnings: Array; overLimitAccounts: Array<{ id: string; login: string; reasons: Array }>; diff --git a/platform/packages/api/src/admin/react/pages.ts b/platform/packages/api/src/admin/react/pages.ts index 59cb0144f..de0344019 100644 --- a/platform/packages/api/src/admin/react/pages.ts +++ b/platform/packages/api/src/admin/react/pages.ts @@ -66,6 +66,10 @@ export const adminComponents = { invitations: async () => ({ default: (await import('./views/InvitationsPage.tsx')).InvitationsPage, }), + security: async () => ({ default: (await import('./views/SecurityPage.tsx')).SecurityPage }), + securityPreview: async () => ({ + default: (await import('./views/SecurityPage.tsx')).SecurityPreviewPage, + }), zeroTrust: async () => ({ default: (await import('./views/ZeroTrustPage.tsx')).ZeroTrustPage }), }; @@ -151,6 +155,14 @@ export function matchAdminRoute(path: string): AdminPageId | null { if (path === '/admin/invitations') { return 'invitations'; } + if ( + path === '/admin/security' || + path === '/admin/security/findings' || + path === '/admin/security/scans' || + path === '/admin/security/requests' + ) { + return 'security'; + } if (path === '/admin/zero-trust') { return 'zeroTrust'; } diff --git a/platform/packages/api/src/admin/react/server.ts b/platform/packages/api/src/admin/react/server.ts index 7e5c2abc1..92d72b936 100644 --- a/platform/packages/api/src/admin/react/server.ts +++ b/platform/packages/api/src/admin/react/server.ts @@ -4,11 +4,14 @@ import type { PageObject } from 'void/pages-protocol'; import type { ApiEnv } from '../../env.ts'; import { formatPlatformPageTitle } from '../../platform-identity.ts'; import type { createAdminFateClient } from '../fate/client.ts'; +import { loadSecurityChrome } from '../security-data.ts'; import { adminComponents, adminLayoutTree } from './pages.ts'; import type { AdminPageId } from './pages.ts'; export async function renderAdminPage( - context: Pick, 'get'> & { req: Pick['req'], 'url' | 'header'> }, + context: Pick, 'env' | 'get'> & { + req: Pick['req'], 'url' | 'header'>; + }, component: AdminPageId, title: string, props: Record, @@ -18,6 +21,8 @@ export async function renderAdminPage( } = {}, ): Promise { const platformName = String(props.platformName ?? 'Void'); + // Banners and the nav badge for security audits; `null` while the capability is off. + const securityChrome = context.get('user') ? await loadSecurityChrome(context) : null; const { pathname, search } = new URL(context.req.url); const pageObj: PageObject = { component, @@ -26,6 +31,7 @@ export async function renderAdminPage( shared: { platformName, adminPageUrl: pathname + search, + ...(securityChrome ? { securityChrome } : {}), adminFateSession: `${context.get('user')?.id ?? 'guest'}:${context.get('humanSession')?.id ?? 'none'}`, ...(options.fateSnapshot ? { adminFateSnapshot: options.fateSnapshot } : {}), }, diff --git a/platform/packages/api/src/admin/react/styles.css b/platform/packages/api/src/admin/react/styles.css index 1a3bcea7d..f4b4771ca 100644 --- a/platform/packages/api/src/admin/react/styles.css +++ b/platform/packages/api/src/admin/react/styles.css @@ -996,3 +996,32 @@ body { grid-template-columns: repeat(auto-fit, minmax(min(100%, 280px), 1fr)); gap: var(--spacing-4); } + +.void-admin-security { + max-width: 1120px; + grid-template-columns: minmax(0, 1fr); +} +.void-admin-security h1, +.void-admin-security h2, +.void-admin-security h3, +.void-admin-security p { + margin: 0; +} +.void-admin-security-intro p { + color: var(--color-text-secondary); +} +.void-admin-security-tabs { + display: flex; + flex-wrap: wrap; + gap: var(--spacing-2); +} +.void-admin-security-models { + display: grid; + gap: var(--spacing-2); + min-width: 0; + border: 0; + padding: 0; +} +.void-admin-security-form { + align-items: flex-start; +} diff --git a/platform/packages/api/src/admin/react/views/Layout.tsx b/platform/packages/api/src/admin/react/views/Layout.tsx index 035f62ad1..bc642ca91 100644 --- a/platform/packages/api/src/admin/react/views/Layout.tsx +++ b/platform/packages/api/src/admin/react/views/Layout.tsx @@ -1,10 +1,13 @@ /** @jsxImportSource react */ import { AppShell } from '@astryxdesign/core/AppShell'; +import { Badge } from '@astryxdesign/core/Badge'; +import { Banner } from '@astryxdesign/core/Banner'; +import { Button } from '@astryxdesign/core/Button'; import { DropdownMenu } from '@astryxdesign/core/DropdownMenu'; import { SideNav, SideNavItem, SideNavSection } from '@astryxdesign/core/SideNav'; import { TopNav, TopNavHeading } from '@astryxdesign/core/TopNav'; -import { useNavigation, useRouter } from '@void/react'; +import { SharedContext, useNavigation, useRouter } from '@void/react'; import { FolderKanban, Activity, @@ -15,18 +18,26 @@ import { Rocket, SlidersHorizontal, ShieldCheck, + ShieldAlert, ShieldLock, Terminal, Users, } from 'lucide-react'; -import { useEffect, useState } from 'react'; +import { useContext, useEffect, useState } from 'react'; import type { ReactNode } from 'react'; import { formatPlatformPageTitle } from '../../../platform-identity.ts'; +import type { SecurityChrome } from '../../security-data.ts'; import { PageStack } from './PageStack.tsx'; import { VoidLogo } from './VoidLogo.tsx'; let isSideNavCollapsed = false; +/** The navigation fallback renders the shell outside a Void page, where there is no shared data. */ +function useSecurityChrome(): SecurityChrome | undefined { + const shared = useContext(SharedContext) as { securityChrome?: SecurityChrome } | null; + return shared?.securityChrome; +} + export function Layout({ title, platformName, @@ -39,6 +50,7 @@ export function Layout({ children: ReactNode; }) { const routerPath = useRouter().path; + const securityChrome = useSecurityChrome(); const path = useNavigation().location?.pathname ?? routerPath; const [collapsed, setCollapsed] = useState(isSideNavCollapsed); useEffect(() => { @@ -171,6 +183,19 @@ export function Layout({ href="/admin/email" isSelected={path.startsWith('/admin/email')} /> + {securityChrome && ( + 0 ? ( + + ) : undefined + } + /> + )} } > - {children} + + {securityChrome?.banners.map((banner) => ( + + } + /> + ))} + {children} + ); } diff --git a/platform/packages/api/src/admin/react/views/Pagination.tsx b/platform/packages/api/src/admin/react/views/Pagination.tsx index de14d55f3..1c48e93c8 100644 --- a/platform/packages/api/src/admin/react/views/Pagination.tsx +++ b/platform/packages/api/src/admin/react/views/Pagination.tsx @@ -2,6 +2,13 @@ import { Button } from '@astryxdesign/core/Button'; +/** `baseUrl` may carry a query (list filters); only `page` changes. */ +function pageHref(baseUrl: string, page: number): string { + const url = new URL(baseUrl, 'https://admin.invalid'); + url.searchParams.set('page', String(page)); + return url.pathname + url.search; +} + export function Pagination({ page, totalPages, @@ -17,7 +24,7 @@ export function Pagination({ return (