diff --git a/docs/guide/platform/administration/security-audits.md b/docs/guide/platform/administration/security-audits.md index 0b3b59d59..74eba69bb 100644 --- a/docs/guide/platform/administration/security-audits.md +++ b/docs/guide/platform/administration/security-audits.md @@ -31,7 +31,7 @@ void platform security budget --platform-usd 500 void platform security policy public ``` -`probe` tells you which requirements your account meets and what you still need to configure. Spending caps are off by default. When you enable a scan mode, the probe must pass. Void checks again daily. If a later check fails, the administrator UI shows a banner and scans pause until the account is ready again. +`probe` tells you which requirements your account meets and what you still need to configure. Monthly spending caps are off by default. When you enable a scan mode, the probe must pass. Void checks again daily. If a later check fails, the administrator UI shows a banner and scans pause until the account is ready again. | Mode | Scans | | -------------------- | --------------------------------------------------------------- | @@ -67,7 +67,7 @@ To check a change before you deploy it, run this from the app’s directory: void project security check ``` -The CLI lists the files it will upload, the model that will review them, and the maximum cost. It includes your current edits to Git-tracked files and skips untracked files, secret-like files, lockfiles, and binaries. Confirm to queue the check. +The CLI lists the files it will upload, the model that will review them, and the [scan’s spend limit](#scan-spend-limit). It includes your current edits to Git-tracked files and skips untracked files, secret-like files, lockfiles, and binaries. Confirm to queue the check. Anyone with deploy access can run a check on a project covered by the scan policy. It counts toward the same spending caps as a deploy scan. Read the result in the terminal now, or look it up by its check ID for up to 30 days. A local check doesn’t update project findings, send email, or change a request to go public. See [project security commands](../../../reference/cli/project.md#void-project-security). @@ -152,7 +152,7 @@ These scans review more than a deploy scan. Each costs money and counts toward t | 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). +A full scan names its model and its [spend limit](#scan-spend-limit), 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} @@ -173,10 +173,33 @@ void platform config plans set pro --security-cap 200 A Pro project can now use up to $200 of the shared $500 budget. A project-specific limit takes precedence over the owner’s plan, followed by the default project cap. An owner or project admin can choose a lower limit for their own project. Plan caps apply even when default project caps are off. Set a plan’s `--security-cap` to `none` to remove its cap or `inherit` to use the default. See [Security scan cap](./plans.md#security-scan-cap). -Void starts a scan only if its maximum cost fits both the project and platform budgets. All scans, including rescans and scans before going public, count toward these budgets. Deployments continue when a cap is reached. The first scan after you raise the cap or the calendar month resets (UTC) includes the skipped changes. +All scans, including rescans and scans before going public, count toward these budgets, which reset each calendar month (UTC). A monthly cap can skip or stop a scan while deploys continue. When scanning resumes, the next scan reviews changes since the last successful scan, or the whole app if there isn’t one to compare with. Both caps are off by default. The platform pays for scans separately from a plan’s AI usage. On the **Scans** page, you can compare the metered cost with the cost AI Gateway reports about an hour later. Project owners and admins receive email when a project reaches 80% and 100% of its cap. Platform admins receive the same alerts for the platform cap, once per threshold each month. +### Scan spend limit {#scan-spend-limit} + +Every scan has a spend limit, including when monthly caps are off. To start a scan, Void reserves that amount against the monthly caps that apply. Commands that start scans show it as the estimated cost. + +Before each model call, Void estimates what the call costs. If that is more than what is left of the limit, Void refuses the call. The scan ends as incomplete (spend limit reached) and keeps the findings it has confirmed. A call can cost more than its estimate, so a scan can go a little over its limit. + +Spending counts cached input at the model's cached price. Only DeepSeek and GLM have one. For the other models, cached input counts at full price. + +By default, the limit is the model's list price for the smaller of the input-token limit and 1.2 million tokens, plus the output-token limit. With the default token settings this is $0.504 for DeepSeek, $2.208 for GLM and $7.20 for Opus. The input-token limit counts cached input in full and defaults to 10 million. To set one limit for every model, from $0.01 to $12: + +```sh +void platform security limits --scan-usd 2.50 +void platform security limits --scan-usd auto # back to the default +``` + +Turning scans on saves the token limits, and upgrading doesn't change saved values. An installation that turned scans on when the default was 1.2 million input tokens keeps that limit until you raise it: + +```sh +void platform security limits --scan-input-tokens 10000000 +``` + +A saved input-token limit above 1.2 million no longer raises the default spend limit. For example, a DeepSeek policy with 2 million input tokens and the default output limit goes from $0.744 to $0.504. Set `--scan-usd` to keep a higher limit. + ## Emails | Email | Sent to | diff --git a/docs/reference/cli/platform-security.md b/docs/reference/cli/platform-security.md index 88f65d516..b1912b717 100644 --- a/docs/reference/cli/platform-security.md +++ b/docs/reference/cli/platform-security.md @@ -43,7 +43,7 @@ The `never` rule skips deploy scans, rescans, sweeps, backfill, and local checks ```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 limits [--concurrency ] [--scan-timeout ] [--scan-input-tokens ] [--scan-usd ] [--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] @@ -51,7 +51,7 @@ void platform security model [--accept-provide **Models.** Accept the provider notice with `--accept-provider-notice` when choosing a third-party model. To bill your own OpenAI or Anthropic account, pipe the key from your password manager to `models --provider --key-stdin --yes`. Void saves it after a successful test call. Use `--remove-key` to switch back. See [Use your own provider key](/guide/platform/administration/security-audits#own-provider-key). -**Scan limits.** Set `--concurrency` to the number of scans the platform can run at once. Each Cloudflare model runs one scan at a time, so additional slots can serve different models. Set `--scan-timeout` in minutes. +**Scan limits.** Set `--concurrency` to the number of scans the platform can run at once. Each Cloudflare model runs one scan at a time, so additional slots can serve different models. Set `--scan-timeout` in minutes. `--scan-input-tokens` caps the input tokens one scan may send, cached ones included. `--scan-usd` sets the [spend limit](/guide/platform/administration/security-audits#scan-spend-limit) of every scan; `auto` prices it from the token limits. **Budget.** Run `void platform security budget` to see this month’s spend and caps. Use `--platform-usd` to enable a platform cap or `--project-default-usd` to enable default project caps. Turn off the default with `--project-caps off`. @@ -77,9 +77,9 @@ Use `--page` and `--limit` (up to 100) to page through findings, oldest first. F To update several findings together, separate their IDs with commas. Void checks every ID before applying the change. -`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`. +`rescan` runs a full scan of the live deployment. It tells you which model it uses and the [scan's spend limit](/guide/platform/administration/security-audits#scan-spend-limit), 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. +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 total of the scans' spend limits. 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. diff --git a/docs/reference/cli/project.md b/docs/reference/cli/project.md index feb277b1f..699ba10b5 100644 --- a/docs/reference/cli/project.md +++ b/docs/reference/cli/project.md @@ -142,7 +142,7 @@ void project security check void project security scan ``` -Both commands name the model and maximum cost before you confirm. Pass `--yes` with `--json` or in a non-interactive shell. Monthly caps apply. +Both commands name the model and its estimated cost, the [scan’s spend limit](/guide/platform/administration/security-audits#scan-spend-limit), before you confirm. Pass `--yes` with `--json` or in a non-interactive shell. Monthly caps apply. - **Local changes.** `check` lists the Git-tracked files it will send, including uncommitted edits. Untracked files, secret-like files such as `.env*`, keys and `.npmrc`, lockfiles, binaries, and media stay local. The limit is 10,000 files and 32 MB per check. For a larger repository, run it in the app’s subdirectory. - **Live deployment.** Add `--client-assets` to review the original sources of browser bundles. Deploy the source map next to the bundle (for example, `app.js.map`) or reference it with `sourceMappingURL`. Without a map, Void reviews the bundle. Sending the additional code can increase the cost. diff --git a/packages/platform/src/security-models.ts b/packages/platform/src/security-models.ts index bd91209fd..44333d1fe 100644 --- a/packages/platform/src/security-models.ts +++ b/packages/platform/src/security-models.ts @@ -123,7 +123,7 @@ export const SECURITY_PROVIDER_NAMES: Readonly */ export const SECURITY_PROVIDER_NOTICE_VERSION = 1; -/** Token counts a scan reserve is computed from when no limits are given (spec §16.1). */ +/** Input token ceiling for pricing the automatic scan reserve. */ export const SECURITY_RESERVE_INPUT_TOKENS = 1_200_000; export const SECURITY_RESERVE_OUTPUT_TOKENS = 120_000; @@ -220,15 +220,24 @@ export function securityModelCostUsd( return nano === null ? null : nano / 1_000_000_000; } -/** Worst-case cost of one scan, reserved against the caps at start (spec §16.1). */ +/** The amount reserved at scan start in USD, or `null` for an unpriced model. */ export function securityScanReserveUsd( id: SecurityModelId, - limits: Readonly<{ maxInputTokens: number; maxOutputTokens: number }> = { + limits: Readonly<{ + maxInputTokens: number; + maxOutputTokens: number; + maxScanUsd?: number | null; + }> = { maxInputTokens: SECURITY_RESERVE_INPUT_TOKENS, maxOutputTokens: SECURITY_RESERVE_OUTPUT_TOKENS, }, ): number | null { - return securityModelCostUsd(id, limits.maxInputTokens, limits.maxOutputTokens); + const defaultUsd = securityModelCostUsd( + id, + Math.min(limits.maxInputTokens, SECURITY_RESERVE_INPUT_TOKENS), + limits.maxOutputTokens, + ); + return defaultUsd === null ? null : (limits.maxScanUsd ?? defaultUsd); } /** diff --git a/packages/platform/src/security-policy.ts b/packages/platform/src/security-policy.ts index 5516969b6..33e5fa956 100644 --- a/packages/platform/src/security-policy.ts +++ b/packages/platform/src/security-policy.ts @@ -30,21 +30,30 @@ export type SecurityLimitRange = Readonly<{ min: number; max: number; default: n /** * 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. + * from the spec. The input token cap counts every input token, cached or not. The + * per-scan spend limit (`maxScanUsd`) is separate: see `SECURITY_SCAN_USD_RANGE`. */ 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 }, + maxInputTokens: { min: 50_000, max: 20_000_000, default: 10_000_000 }, maxOutputTokens: { min: 5000, max: 200_000, default: 120_000 }, modelCallsPerScan: { min: 10, max: 200, default: 80 }, } as const; +/** Allowed per-scan spend limit (`maxScanUsd`) in USD, whole cents. */ +export const SECURITY_SCAN_USD_RANGE = { min: 0.01, max: 12 } as const; + +/** The whole-number limits. Each has a range in `SECURITY_LIMIT_RANGES`. */ export type SecurityLimitKey = keyof typeof SECURITY_LIMIT_RANGES; -export type SecurityPolicyLimits = Readonly>; +export type SecurityPolicyLimits = Readonly< + Record & { + /** Per-scan spend limit in USD. `null` or missing: priced from the token limits. */ + maxScanUsd?: number | null; + } +>; export const SECURITY_LIMIT_KEYS: ReadonlyArray = [ 'concurrency', @@ -282,14 +291,19 @@ function limitsFrom(value: unknown, strict: boolean): SecurityPolicyLimits { maxInputTokens: read('maxInputTokens'), maxOutputTokens: read('maxOutputTokens'), modelCallsPerScan: read('modelCallsPerScan'), + maxScanUsd: scanUsd(input.maxScanUsd ?? null, strict), }; } /** 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> = {}; + const patch: { -readonly [K in keyof SecurityPolicyLimits]?: SecurityPolicyLimits[K] } = {}; for (const [key, limit] of Object.entries(input)) { + if (key === 'maxScanUsd') { + patch.maxScanUsd = scanUsd(limit ?? null, true); + continue; + } const known = SECURITY_LIMIT_KEYS.find((candidate) => candidate === key); if (!known) { throw new Error(`Unknown security limit: ${key}.`); @@ -299,6 +313,23 @@ export function parseSecurityLimitsPatch(value: unknown): Partial { budgets: { platformCapOn: false, projectCapsOn: false }, }); expect(parseSecurityPolicy(stored())).toEqual(policy); + expect(policy.limits).toMatchObject({ maxInputTokens: 10_000_000, maxScanUsd: null }); + }); + + it.each([1_200_000, 2_000_000])('keeps a saved %s input-token limit', (maxInputTokens) => { + const row = stored({ + limits: { ...defaultSecurityPolicy().limits, maxInputTokens, maxScanUsd: undefined }, + }); + expect(readSecurityPolicy(row).limits).toMatchObject({ maxInputTokens, maxScanUsd: null }); + expect(parseSecurityPolicy(row).limits).toMatchObject({ maxInputTokens, maxScanUsd: null }); + }); + + it.each([null, 0.01, 2.58, 12])('accepts %s as the spend limit in all readers', (maxScanUsd) => { + const row = stored({ limits: { ...defaultSecurityPolicy().limits, maxScanUsd } }); + expect(readSecurityPolicy(row).limits.maxScanUsd).toBe(maxScanUsd); + expect(parseSecurityPolicy(row).limits.maxScanUsd).toBe(maxScanUsd); + expect(parseSecurityLimitsPatch({ maxScanUsd })).toEqual({ maxScanUsd }); + }); + + it.each([ + [0, 0.01], + [12.01, 12], + [1.236, 1.24], + ])('normalizes a stored spend limit of %s to %s', (maxScanUsd, expected) => { + const row = stored({ limits: { ...defaultSecurityPolicy().limits, maxScanUsd } }); + expect(readSecurityPolicy(row).limits.maxScanUsd).toBe(expected); + expect(() => parseSecurityPolicy(row)).toThrow('maxScanUsd'); + expect(() => parseSecurityLimitsPatch({ maxScanUsd })).toThrow('maxScanUsd'); + }); + + it('keeps every exported limit key paired with its range', () => { + expect(SECURITY_LIMIT_KEYS).toEqual(Object.keys(SECURITY_LIMIT_RANGES)); + for (const key of SECURITY_LIMIT_KEYS) { + expect(SECURITY_LIMIT_RANGES[key].max).toBeGreaterThan(SECURITY_LIMIT_RANGES[key].min); + } + // Limits written without the spend limit still type-check and read as automatic. + const { maxScanUsd: _, ...whole } = defaultSecurityPolicy().limits; + const limits: SecurityPolicyLimits = whole; + expect(readSecurityPolicy(stored({ limits })).limits.maxScanUsd).toBeNull(); + }); + + it('rejects a stored or requested spend limit of the wrong type', () => { + const maxScanUsd = '1.00'; + const row = stored({ limits: { ...defaultSecurityPolicy().limits, maxScanUsd } }); + expect(() => readSecurityPolicy(row)).toThrow('maxScanUsd'); + expect(() => parseSecurityPolicy(row)).toThrow('maxScanUsd'); + expect(() => parseSecurityLimitsPatch({ maxScanUsd })).toThrow('maxScanUsd'); }); it('repairs a row another release wrote, which the write path refuses', () => { diff --git a/packages/void/src/cli/client.ts b/packages/void/src/cli/client.ts index 759f4631f..04dea91e4 100644 --- a/packages/void/src/cli/client.ts +++ b/packages/void/src/cli/client.ts @@ -1186,7 +1186,7 @@ export class PlatformClient { }); } - /** What a local check would run (model, provider notice, most it can cost). Sends no code. */ + /** What a local check would run (model, provider notice, estimated cost). Sends no code. */ async previewProjectSecurityCheck( projectId: string, tree: SecurityCheckTree, diff --git a/packages/void/src/cli/deploy-security-notice.ts b/packages/void/src/cli/deploy-security-notice.ts index 076426b18..c03949f53 100644 --- a/packages/void/src/cli/deploy-security-notice.ts +++ b/packages/void/src/cli/deploy-security-notice.ts @@ -165,6 +165,9 @@ function failureWhy(scan: SecurityScanSummary): string | null { ? 'a platform problem' : cleanLine(scan.statusReason ?? 'failed'); case 'incomplete': + if (scan.statusReason === 'spend_cap') { + return 'the scan reached its spend limit'; + } return (scan.statusReason ?? '').startsWith('budget') ? 'the monthly scan budget ran out' : `partial: ${cleanLine(scan.statusReason ?? 'stopped early')}`; diff --git a/packages/void/src/cli/operator-security-args.ts b/packages/void/src/cli/operator-security-args.ts index 8d07843f0..db4e02ded 100644 --- a/packages/void/src/cli/operator-security-args.ts +++ b/packages/void/src/cli/operator-security-args.ts @@ -58,11 +58,16 @@ const commands: Array> = [ }, { action: 'limits', - description: 'Set scan limits: concurrent scans and the time one scan may run', + description: + 'Set scan limits: concurrent scans, the time one scan may run, its input tokens and its spend limit', path: '/security/policy', values: { concurrency: 'Scans that run at once (1 to 10)', 'scan-timeout': 'Minutes one scan may run (5 to 60)', + 'scan-input-tokens': + 'Input tokens one scan may send, cached ones included (50000 to 20000000)', + 'scan-usd': + 'Spend limit of one scan in USD (0.01 to 12), or auto to price it from the token limits', }, method: 'POST', }, @@ -512,10 +517,19 @@ export function applySecurityArgs( ...(values['scan-timeout'] ? { timeoutMinutes: wholeNumber(values['scan-timeout'], 'scan-timeout') } : {}), + ...(values['scan-input-tokens'] + ? { maxInputTokens: wholeNumber(values['scan-input-tokens'], 'scan-input-tokens') } + : {}), + ...(values['scan-usd'] + ? { + maxScanUsd: + values['scan-usd'] === 'auto' ? null : dollars(values['scan-usd'], 'scan-usd'), + } + : {}), }; if (Object.keys(limits).length === 0) { throw new Error( - 'platform: Usage: void platform security limits [--concurrency ] [--scan-timeout ].', + 'platform: Usage: void platform security limits [--concurrency ] [--scan-timeout ] [--scan-input-tokens ] [--scan-usd ].', ); } parsed.body = { limits }; diff --git a/packages/void/src/cli/operator-security.ts b/packages/void/src/cli/operator-security.ts index 8b6dc7d85..f8fa4058d 100644 --- a/packages/void/src/cli/operator-security.ts +++ b/packages/void/src/cli/operator-security.ts @@ -77,6 +77,12 @@ function number(value: unknown): number | undefined { return typeof value === 'number' && Number.isSafeInteger(value) ? value : undefined; } +/** The preview's estimated cost. Older platforms send it only as `worstCaseUsd`. */ +function estimateOf(preview: Record): number | undefined { + const value = preview.estimatedUsd ?? preview.worstCaseUsd; + return typeof value === 'number' ? value : undefined; +} + /** Reads. `show` takes comma-separated finding ids. */ async function runRead(client: OperatorClient, args: OperatorArgs, io: SecurityIo): Promise { if (args.action === 'show') { @@ -316,7 +322,7 @@ async function runRescan( ); } 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. + // The server's preview is the cost check (edge #43): say what it would run and its estimated cost. const id = typeof preview.deploymentId === 'string' ? preview.deploymentId : String(preview.target); const model = typeof preview.model === 'string' ? preview.model : 'the scan model'; @@ -329,7 +335,7 @@ async function runRescan( ? `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`, + `${first}${estimateOf(preview) === undefined ? '' : ` Estimated cost: up to ${money(estimateOf(preview))}.`}\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); @@ -362,10 +368,9 @@ async function runBackfill( const count = number(preview.willQueue) ?? 0; if (!args.json && !args.plan) { const remaining = number(preview.remaining) ?? 0; + const estimate = estimateOf(preview); const cost = - typeof preview.worstCaseUsd === 'number' - ? ` Together they can cost up to ${money(preview.worstCaseUsd)}.` - : ''; + typeof estimate === 'number' ? ` Estimated cost together: up to ${money(estimate)}.` : ''; const missing = number(preview.noStoredCode) ?? 0; const missingText = missing > 0 diff --git a/packages/void/src/cli/project-security-check.ts b/packages/void/src/cli/project-security-check.ts index 2896f5003..1b929ddb7 100644 --- a/packages/void/src/cli/project-security-check.ts +++ b/packages/void/src/cli/project-security-check.ts @@ -227,9 +227,10 @@ export function checkResultLines( options: { fresh?: boolean } = {}, ): Array { const { check, result } = view; + const reason = check.statusReason === 'spend_cap' ? 'spend limit reached' : check.statusReason; 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)}` : ''}`, + ` ${cleanLine(check.status)}${reason ? ` (${cleanLine(reason)})` : ''}${check.coverageLabel ? ` · ${cleanLine(check.coverageLabel)}` : ''} · ${plural(check.filesScanned, 'file')}${check.model ? ` · ${cleanLine(check.model)}` : ''}`, ]; if (!ENDED_WITH_RESULT.has(check.status)) { return head; diff --git a/packages/void/src/cli/project-security.ts b/packages/void/src/cli/project-security.ts index 0abde20fa..cb0015dd6 100644 --- a/packages/void/src/cli/project-security.ts +++ b/packages/void/src/cli/project-security.ts @@ -151,8 +151,8 @@ export function budgetSkipCopy( } 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)},`}`; + // `one scan with needs $2.04, more than is left of …` + const oneScan = `one scan with ${cleanLine(model ?? 'this model')} needs${reserve === null ? '' : ` ${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 }; @@ -252,6 +252,9 @@ export function scanStatusCopy(status: ProjectSecurityStatus, projectId?: string lastScan.refusalCategory ?? 'unknown', )}). The next deploy is scanned again. To switch model: void project security model `; case 'incomplete': + if (reason === 'spend_cap') { + return `Last scan reached its spend limit. Confirmed findings are kept. ${next}`; + } 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}`; @@ -473,7 +476,7 @@ export function formatStatus( ); } else { const parts = [ - cleanLine(lastScan.status + (lastScan.statusReason ? ` (${lastScan.statusReason})` : '')), + formatScanState(lastScan), lastScan.deploymentId ? cleanLine(lastScan.deploymentId) : null, duration(lastScan), lastScan.coverageLabel ? cleanLine(lastScan.coverageLabel) : null, @@ -621,11 +624,16 @@ export function formatFinding( return lines; } +function formatScanState(scan: SecurityScanSummary): string { + const reason = scan.statusReason === 'spend_cap' ? 'scan spend limit reached' : scan.statusReason; + return cleanLine(scan.status + (reason ? ` (${reason})` : '')); +} + export function formatScans(scans: Array): Array { return scans.map((scan) => [ day(scan.createdAt).padEnd(7), - cleanLine(scan.status + (scan.statusReason ? ` (${scan.statusReason})` : '')).padEnd(24), + formatScanState(scan).padEnd(24), cleanLine(scan.deploymentId ?? '-').padEnd(12), cleanLine(scan.trigger).padEnd(9), duration(scan) ?? '-', @@ -713,14 +721,12 @@ export type ProjectSecurityDeps = { check?: SecurityCheckDeps; }; -/** The rescan cost confirm (spec §13.4 rescan rule): what it runs and what it can cost. */ +/** The rescan cost confirm (spec §13.4 rescan rule): what it runs and its estimated 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 estimate = preview.estimatedUsd ?? preview.worstCaseUsd; + const cost = typeof estimate === 'number' ? ` Estimated cost: up to ${usd(estimate)}.` : ''; const whole = preview.clientAssets ? 'This reviews the whole app, and the sources of its client bundles.' : 'This reviews the whole app.'; @@ -1148,9 +1154,10 @@ async function runSecurityCheck( if (preview.notice) { lines.push('', ...preview.notice.map((line) => ` ${cleanLine(line)}`)); } + const estimate = preview.estimatedUsd ?? preview.worstCaseUsd; 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 code goes to the platform and is reviewed by ${model}.${typeof estimate === 'number' ? ` Estimated cost: up to ${usd(estimate)}; monthly caps apply.` : ' Monthly caps apply.'}`, ' The result is not saved as project findings. The platform keeps it for 30 days.', ); log(lines); diff --git a/packages/void/src/cli/security-api-types.ts b/packages/void/src/cli/security-api-types.ts index 3ab299f2b..b0b55f22a 100644 --- a/packages/void/src/cli/security-api-types.ts +++ b/packages/void/src/cli/security-api-types.ts @@ -1,7 +1,7 @@ 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. */ +/** `*_cap`: that cap is used up; `*_reserve`: one scan's spend limit does not fit in what is left. */ export type SecurityBudgetCause = | 'project_cap' | 'platform_cap' @@ -90,7 +90,7 @@ export type ProjectSecurityStatus = { spentUsd: number; month: string; resetsAt: string; - /** The most one scan with the current model can cost; older platforms do not send it. */ + /** One scan's spend limit with the current model; older platforms do not send it. */ scanReserveUsd?: number | null; } | null; lastScan: SecurityScanSummary | null; @@ -193,6 +193,9 @@ export type SecurityRescanPreview = { /** M31: the scan also reads client bundle sources; older platforms omit it. */ clientAssets?: boolean; model: string | null; + /** The scan's estimated cost (its spend limit); older platforms send only `worstCaseUsd`. */ + estimatedUsd?: number | null; + /** @deprecated Read `estimatedUsd`. */ worstCaseUsd: number | null; budget: ProjectSecurityStatus['budget']; }; @@ -214,6 +217,9 @@ export type SecurityCheckPreview = { model: string; /** The provider notice, for a third-party model; `null` for a Cloudflare model. */ notice: Array | null; + /** The check's estimated cost (its spend limit); older platforms send only `worstCaseUsd`. */ + estimatedUsd?: number | null; + /** @deprecated Read `estimatedUsd`. */ worstCaseUsd: number | null; }; diff --git a/packages/void/test/unit/deploy-security-notice.test.ts b/packages/void/test/unit/deploy-security-notice.test.ts index 698945076..394bca092 100644 --- a/packages/void/test/unit/deploy-security-notice.test.ts +++ b/packages/void/test/unit/deploy-security-notice.test.ts @@ -34,6 +34,22 @@ async function run(reply: () => Promise, env: NodeJS.ProcessEnv = {}) { } describe('deploy security notice', () => { + it('explains a scan spend stop on the preceding deploy', async () => { + const lastScan = status().lastScan!; + const { lines } = await run(async () => + status({ + previousScan: { + ...lastScan, + deploymentId: 'dpl_prior', + status: 'incomplete', + statusReason: 'spend_cap', + }, + }), + ); + expect(lines).toContain( + ' Warning: the security scan of dpl_prior did not finish (the scan reached its spend limit).', + ); + }); 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'); diff --git a/packages/void/test/unit/operator-cli.test.ts b/packages/void/test/unit/operator-cli.test.ts index 6264fd2a9..eb82e2f3f 100644 --- a/packages/void/test/unit/operator-cli.test.ts +++ b/packages/void/test/unit/operator-cli.test.ts @@ -2140,6 +2140,25 @@ describe('platform security commands', () => { ); }); + it('sets the scan input-token and spend limits, with auto for the automatic spend limit', async () => { + quiet(); + const calls = serve([ + { dryRun: true, action: 'security.policy', target: 'platform', expectedRevision: 3 }, + { ok: true }, + { dryRun: true, action: 'security.policy', target: 'platform', expectedRevision: 4 }, + { ok: true }, + ]); + await run('limits', '--scan-input-tokens', '10000000', '--scan-usd', 'auto', '--yes'); + await run('limits', '--scan-usd', '2.50', '--yes'); + expect(calls.filter((call) => call.body?.dryRun).map((call) => call.body?.limits)).toEqual([ + { maxInputTokens: 10_000_000, maxScanUsd: null }, + { maxScanUsd: 2.5 }, + ]); + expect(() => parseOperatorArgs(['security', 'limits', '--scan-usd', 'lots'])).toThrow( + '--scan-usd must be a dollar amount', + ); + }); + 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* () { diff --git a/packages/void/test/unit/project-security-command.test.ts b/packages/void/test/unit/project-security-command.test.ts index fc453209f..6de360e59 100644 --- a/packages/void/test/unit/project-security-command.test.ts +++ b/packages/void/test/unit/project-security-command.test.ts @@ -1,6 +1,8 @@ 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 { checkResultLines } from '../../src/cli/project-security-check.ts'; +import { formatScans, rescanConfirmLines, scanStatusCopy } from '../../src/cli/project-security.ts'; import { captureOutput, linkedProject } from '../helpers/cli-command.ts'; import { withPlatformDiscovery } from '../helpers/platform-discovery.ts'; import { securityStatus } from '../helpers/security-status.ts'; @@ -51,6 +53,31 @@ function route(handlers: Record Response>) { const run = (root: string, args: Array) => runProjectCommand(root, parseProjectArgs(args)); const S = '/projects/project_1/security'; const F = `${S}/findings`; +it('explains the per-scan spend limit in project status and scan history', () => { + const lastScan = { + ...status.lastScan!, + status: 'incomplete' as const, + statusReason: 'spend_cap', + }; + expect(scanStatusCopy({ ...status, lastScan })).toContain('Last scan reached its spend limit.'); + expect(formatScans([lastScan]).join('\n')).toContain('scan spend limit reached'); + const check = { check: { ...lastScan, coverageNotes: [] }, ended: true, result: null }; + expect(checkResultLines('acme-web', check)[1]).toContain('incomplete (spend limit reached)'); +}); + +it('calls the rescan cost an estimate, also from a platform that sends only worstCaseUsd', () => { + const preview = { + deploymentId: 'dep_1', + alreadyScanned: false, + model: '@cf/deepseek-ai/deepseek-v4.1-flash-1017', + budget: null, + }; + for (const amounts of [{ estimatedUsd: 0.504, worstCaseUsd: 0.504 }, { worstCaseUsd: 0.504 }]) { + const text = rescanConfirmLines({ ...preview, ...amounts }).join('\n'); + expect(text).toContain('Estimated cost: up to $0.50.'); + expect(text).not.toContain('can cost'); + } +}); const finding = (id: string, extra: Record = {}) => ({ id, verdict: 'confirmed', diff --git a/platform/meta/design-docs/0095-security-audits.md b/platform/meta/design-docs/0095-security-audits.md index 6eec07375..ea55d5735 100644 --- a/platform/meta/design-docs/0095-security-audits.md +++ b/platform/meta/design-docs/0095-security-audits.md @@ -48,7 +48,7 @@ Each one has tests (named) or a spike that checks it. | 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) | +| I7 | Scan start reserves the scan limit against monthly caps. Each call checks its scan estimate and monthly worst case. Own-key calls count 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` | @@ -240,9 +240,9 @@ Migration `0065_security_audits.sql`, 11 tables in `security/schema.ts`: 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)`. +- Save the attempt's reserve on the scan and reserve that amount on both month rows. + A monthly refusal stores `skipped (budget)`. Otherwise, start through the controller 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. @@ -296,10 +296,36 @@ Migration `0065_security_audits.sql`, 11 tables in `security/schema.ts`: `/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`. +- `limits.maxScanUsd` sets the reserve for every scan, including when monthly caps are off. + A `null` or missing value uses list price for `min(maxInputTokens, 1_200_000)` and + `maxOutputTokens`. The default raw input cap is 10M. Upgrades keep saved token caps + but lower the automatic reserve for saved caps above 1.2M. +- Each call holds its estimate on the scan row if it fits the remaining reserve. The estimate + prices `ceil(forwarded UTF-8 bytes / 2.5)` input tokens and the call's output allowance at + list price. Both month rows price one input token per forwarded byte and the same output + allowance. Both prices use twice the input price for Messages calls. A call whose estimate + does not fit the scan row the proxy read is refused before it takes a session call or a + `@cf` rate token; the hold checks again on the fresh row. +- Settlement replaces each hold with the metered cost, including any cache discounts. + Actual costs can take the scan over its limit. A possibly billed call whose usage isn't + recorded, including a stream cut off after its usage arrived, adds fallback token counts. + The scan keeps its estimate, leaving room for a retry if it fits, and both month rows keep + the worst case. A failed settlement also leaves each hold in + place. A known upstream rejection costs zero. +- Stops answer 429 (402 for credits) with `x-void-scan-stop`. The 429 response and + `/v1/void/last-failure` report `tokens` for a spend refusal, so runners handle it as a + token stop. When a runner reports `incomplete (token_cap)`, ingest stores + `spend_cap` if the attempt's recorded failure is a spend refusal. If the ledger is + unreadable, it stores `token_cap`. +- The ledger keeps each attempt's latest stop on the scan's own limits (`session_calls`, + `scan_calls`, `tokens`, `spend`). A later `upstream`, `rate_wait`, `not_allowed` or + `refused` failure does not replace it, so SDK engines still read the stop and keep the + attempt's findings. Any later failure replaces a `budget` or `credits` stop, because + those can pass (another scan's hold settles, credits are added) and the session may have + gone on. A newer stop replaces an older one: a `credits` stop after a token or spend stop + ends the scan `failed (credits)`. If the lookup fails, an engine can report + `failed (infrastructure)`, which Void retries if an attempt is left. If the runner's + report was already accepted, a later stop can leave the scan `succeeded`. - 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 diff --git a/platform/packages/api/src/operator/audit.ts b/platform/packages/api/src/operator/audit.ts index 69f5f1959..1a5628001 100644 --- a/platform/packages/api/src/operator/audit.ts +++ b/platform/packages/api/src/operator/audit.ts @@ -337,10 +337,11 @@ function auditTarget( const limits = body.limits && typeof body.limits === 'object' && !Array.isArray(body.limits) ? Object.fromEntries( - Object.entries(body.limits).filter( - ([key, value]) => - (SECURITY_LIMIT_KEYS as ReadonlyArray).includes(key) && - Number.isSafeInteger(value), + Object.entries(body.limits).filter(([key, value]) => + key === 'maxScanUsd' + ? securityUsdTarget(value) !== undefined + : (SECURITY_LIMIT_KEYS as ReadonlyArray).includes(key) && + Number.isSafeInteger(value), ), ) : undefined; diff --git a/platform/packages/api/src/operator/security-routes.ts b/platform/packages/api/src/operator/security-routes.ts index f5b19cf3d..a2f407b7d 100644 --- a/platform/packages/api/src/operator/security-routes.ts +++ b/platform/packages/api/src/operator/security-routes.ts @@ -115,6 +115,7 @@ export function rescanPreviewView(result: RescanPreview) { clientAssets: result.clientAssets, model: result.model, thirdParty: result.thirdParty, + estimatedUsd: result.estimatedUsd, worstCaseUsd: result.worstCaseUsd, budget: result.budget, }; @@ -124,6 +125,7 @@ export function rescanPreviewView(result: RescanPreview) { export function rescanQueuedView(scanId: string, result: RescanPreview) { const { thirdParty: _thirdParty, + estimatedUsd: _estimate, worstCaseUsd: _cost, budget: _budget, ...shown diff --git a/platform/packages/api/src/security/budget.ts b/platform/packages/api/src/security/budget.ts index 67cf1a383..780ab394a 100644 --- a/platform/packages/api/src/security/budget.ts +++ b/platform/packages/api/src/security/budget.ts @@ -1,18 +1,22 @@ /** - * Monthly scan budgets (spec §16): cap rules, month math and the spend meter writes. + * Scan and monthly budgets (spec §16): cap rules, month math and spend meter writes. * * scan start (scheduler, M9) ─► reserveSecurityScanBudget spent + reserved + reserve ≤ cap - * each model call (proxy) ─► holdSecurityModelCall spent + this call's worst case ≤ cap - * ─► settleSecurityModelCall spent += real − worst case + * each model call (proxy) ─► holdSecurityModelCall scan spent + estimate ≤ reserve + * month spent + worst case ≤ cap + * ─► settleSecurityModelCall spent += actual cost − hold * scan end (ingest/reaper) ─► releaseSecurityScanReserve reserved −= reserve (its own month) * - * Every check runs in the `UPDATE … WHERE … RETURNING` that writes the row, so two - * writers near a cap can never both pass (edge #51). Money is whole nano-dollars; - * caps are whole cents (`policy.budgets` is USD with at most two decimals). + * Each hold must fit when its row is updated. Actual cost can exceed the hold. + * Meters use whole nano-dollars. Monthly caps use whole cents. */ -import { securityModelCostNanoUsd } from '@void/platform/security-models'; +import { securityScanReserveUsd } from '@void/platform/security-models'; import type { SecurityModelId } from '@void/platform/security-models'; -import type { SecurityPlanCap, SecurityPolicyBudgets } from '@void/platform/security-policy'; +import type { + SecurityPlanCap, + SecurityPolicyBudgets, + SecurityPolicyLimits, +} from '@void/platform/security-policy'; import { and, eq, gt, lt, sql } from 'drizzle-orm'; import type { SQL } from 'drizzle-orm'; import type { Db, DbOrTx } from '../db.ts'; @@ -182,12 +186,13 @@ export function securityBudgetThresholds( return SECURITY_BUDGET_THRESHOLDS.filter((percent) => spentNano * 100 >= capNano * percent); } -/** Worst-case cost of one scan at list price (spec §16.1); `null` for an unpriced model. */ +/** The scan's spend limit (spec §16.1). */ export function securityScanReserveNano( model: SecurityModelId, - limits: Readonly<{ maxInputTokens: number; maxOutputTokens: number }>, + limits: SecurityPolicyLimits, ): number | null { - return securityModelCostNanoUsd(model, limits.maxInputTokens, limits.maxOutputTokens); + const usd = securityScanReserveUsd(model, limits); + return usd === null ? null : Math.round(usd * NANO_USD_PER_USD); } // --- Spend meter writes --- @@ -331,7 +336,7 @@ export type SecurityReserveResult = class ScanGone extends Error {} /** - * Scan start: reserve the worst case on both spend rows if `spent + reserved + reserve ≤ cap` + * Scan start reserves the scan's spend limit on both month rows if `spent + reserved + reserve ≤ cap` * (a refusal writes nothing). Fenced: a cancel after the claim reserves nothing (`gone`), * and a scan already holding a reserve throws, so a retry never reserves twice. * `started_at` is the month the reserve is released from. @@ -429,6 +434,7 @@ export type SecurityCallRefusal = | Readonly<{ ok: false; reason: 'fence' }> | Readonly<{ ok: false; reason: 'scan_calls' }> | Readonly<{ ok: false; reason: 'tokens' }> + | Readonly<{ ok: false; reason: 'spend' }> | (SecurityBudgetRefusal & Readonly<{ reason: 'budget' }>); export type SecurityCallHold = Readonly<{ @@ -440,8 +446,8 @@ export type SecurityCallHold = Readonly<{ }>; /** - * Before a model call: count it on the scan (fenced, under the call and token caps) and - * charge its worst case to both spend rows if `spent + worst ≤ cap`, until it is settled. + * Hold the estimate on the scan and the worst case on both month rows when all three + * fit their respective limits. The holds commit together. */ export async function holdSecurityModelCall( db: Db, @@ -450,6 +456,7 @@ export async function holdSecurityModelCall( attempt: number; projectId: string; worstNano: number; + estimateNano: number; maxCalls: number; maxInputTokens: number; maxOutputTokens: number; @@ -466,7 +473,7 @@ export async function holdSecurityModelCall( .update(securityScans) .set({ model_calls: sql`${securityScans.model_calls} + 1`, - metered_nano_usd: sql`${securityScans.metered_nano_usd} + ${worst}`, + metered_nano_usd: sql`${securityScans.metered_nano_usd} + ${input.estimateNano}`, }) .where( and( @@ -477,6 +484,8 @@ export async function holdSecurityModelCall( lt(securityScans.model_calls, input.maxCalls), lt(securityScans.tokens_in, input.maxInputTokens), lt(securityScans.tokens_out, input.maxOutputTokens), + gt(securityScans.reserved_nano_usd, 0), + sql`${securityScans.metered_nano_usd} + ${input.estimateNano} <= ${securityScans.reserved_nano_usd}`, ), ) .returning({ modelCalls: securityScans.model_calls }); @@ -502,7 +511,7 @@ export async function holdSecurityModelCall( } class CallRefused extends Error { - constructor(readonly reason: 'fence' | 'scan_calls' | 'tokens') { + constructor(readonly reason: 'fence' | 'scan_calls' | 'tokens' | 'spend') { super(`security model call refused: ${reason}`); } } @@ -517,7 +526,7 @@ async function callRefusalReason( maxOutputTokens: number; }>, now: number, -): Promise<'fence' | 'scan_calls' | 'tokens'> { +): Promise { const [row] = await tx .select({ attempt: securityScans.attempt, @@ -542,7 +551,9 @@ async function callRefusalReason( if (row.modelCalls >= input.maxCalls) { return 'scan_calls'; } - return 'tokens'; + return row.tokensIn >= input.maxInputTokens || row.tokensOut >= input.maxOutputTokens + ? 'tokens' + : 'spend'; } export type SecurityCallSettlement = Readonly<{ @@ -551,8 +562,7 @@ export type SecurityCallSettlement = Readonly<{ }>; /** - * After a model call: the real cost replaces the hold on the scan and the hold's month, and - * the tokens are added, also for a stale attempt. Returns the month totals for the alerts. + * Add the tokens and replace each hold when the actual cost is known, also for stale attempts. */ export async function settleSecurityModelCall( db: Db, @@ -561,19 +571,21 @@ export async function settleSecurityModelCall( projectId: string; month: string; holdNano: number; - actualNano: number; + estimateNano: number; + actualNano: number | null; inputTokens: number; outputTokens: number; }>, ): Promise { - const delta = input.actualNano - input.holdNano; + const scanDelta = (input.actualNano ?? input.estimateNano) - input.estimateNano; + const monthDelta = (input.actualNano ?? input.holdNano) - input.holdNano; return db.transaction(async (tx) => { await tx .update(securityScans) .set({ tokens_in: sql`${securityScans.tokens_in} + ${input.inputTokens}`, tokens_out: sql`${securityScans.tokens_out} + ${input.outputTokens}`, - metered_nano_usd: sql`GREATEST(0, ${securityScans.metered_nano_usd} + ${delta})`, + metered_nano_usd: sql`GREATEST(0, ${securityScans.metered_nano_usd} + ${scanDelta})`, }) .where(eq(securityScans.id, input.scanId)); // A project deleted mid-call has no row left; the platform total still counts. @@ -582,7 +594,7 @@ export async function settleSecurityModelCall( input.projectId, input.month, 'spent_nano_usd', - delta, + monthDelta, { floor: true }, ); return { projectSpentNano: project ?? 0, platformSpentNano: platform ?? 0 }; diff --git a/platform/packages/api/src/security/call-ledger.ts b/platform/packages/api/src/security/call-ledger.ts index 536b9bc63..e6d4467c6 100644 --- a/platform/packages/api/src/security/call-ledger.ts +++ b/platform/packages/api/src/security/call-ledger.ts @@ -17,6 +17,7 @@ export type ModelCallFailureReason = | 'session_calls' | 'scan_calls' | 'tokens' + | 'spend' | 'budget' | 'credits' | 'not_allowed' @@ -124,13 +125,37 @@ export async function modelRateWaitMs( return rateWaitMs(refillRateBucket(await storage.get(rateKey(model)), now).tokens); } +/** + * Stops on the scan's own limits (`spend` is sent to the runner as `tokens`). They end the + * attempt with its confirmed findings, so a later transient failure (a 503 from another + * call, a rate wait) must not hide them. Calls and tokens only grow, and spend only grows + * by more than a settled call gives back. A `budget` or `credits` stop can pass (another + * scan's hold settles, credits are added), so a later failure still replaces it. + */ +const LIMIT_STOPS: ReadonlySet = new Set([ + 'session_calls', + 'scan_calls', + 'tokens', + 'spend', +]); +/** Every failure the runner reads as a stop. A newer stop always replaces an older one. */ +const STOPS: ReadonlySet = new Set([...LIMIT_STOPS, 'budget', 'credits']); + +/** Keeps the attempt's latest stop; a transient failure does not replace a limit stop. */ export async function recordModelCallFailure( storage: CallLedgerStorage, scanId: string, attempt: number, failure: ModelCallFailure, ): Promise { - await storage.put(failureKey(scanId, attempt), failure); + const key = failureKey(scanId, attempt); + if (!STOPS.has(failure.reason)) { + const current = await storage.get(key); + if (current && LIMIT_STOPS.has(current.reason)) { + return; + } + } + await storage.put(key, failure); } export async function readModelCallFailure( diff --git a/platform/packages/api/src/security/ingest.ts b/platform/packages/api/src/security/ingest.ts index 59b1ced9a..329ba3b31 100644 --- a/platform/packages/api/src/security/ingest.ts +++ b/platform/packages/api/src/security/ingest.ts @@ -633,7 +633,7 @@ export async function ingestSecurityScanResult( ): Promise { const now = options.now ?? Date.now(); const noModelRun = options.noModelRun ?? null; - const status: SecurityParsedStatus = noModelRun + let status: SecurityParsedStatus = noModelRun ? { status: 'succeeded', reason: null, @@ -642,6 +642,16 @@ export async function ingestSecurityScanResult( engineVersion: null, } : parseRunnerStatus(report.status, scanId, attempt); + if (status.status === 'incomplete' && status.reason === 'token_cap') { + try { + const failure = await securityScheduler(env).modelCallFailure(scanId, attempt); + if (failure?.reason === 'spend') { + status = { ...status, reason: 'spend_cap' }; + } + } catch { + // Keep the runner's `token_cap` reason when the ledger is unavailable. + } + } // A container or controller failure gets one more attempt (spec §6.2). if ( diff --git a/platform/packages/api/src/security/local-check.ts b/platform/packages/api/src/security/local-check.ts index b893a46e5..8813fa3c0 100644 --- a/platform/packages/api/src/security/local-check.ts +++ b/platform/packages/api/src/security/local-check.ts @@ -194,12 +194,15 @@ export async function previewSecurityLocalCheck(db: Db, project: CheckProject) { ); } const host = securityModelThirdPartyHost(model.id); - const worstCase = securityScanReserveNano(model.id, policy.limits); + const reserve = securityScanReserveNano(model.id, policy.limits); + const estimatedUsd = reserve === null ? null : reserve / NANO_USD_PER_USD; return { model: model.id, thirdParty: model.thirdParty, notice: host ? [...securityProviderNotice(host)] : null, - worstCaseUsd: worstCase === null ? null : worstCase / NANO_USD_PER_USD, + estimatedUsd, + /** @deprecated The same estimate as `estimatedUsd`, for older CLIs. */ + worstCaseUsd: estimatedUsd, budget: await securityProjectBudgetView(db, project.id, policy, settings.caps), limits: SECURITY_LOCAL_CHECK_LIMITS, }; diff --git a/platform/packages/api/src/security/model-proxy.ts b/platform/packages/api/src/security/model-proxy.ts index 08efd6a5b..9a47ff1fe 100644 --- a/platform/packages/api/src/security/model-proxy.ts +++ b/platform/packages/api/src/security/model-proxy.ts @@ -4,11 +4,12 @@ * * fence ─► model allowlist (+ third-party credits check and notice) ─► body (only * function/custom tools) ─► caps (session, scan calls, tokens) ─► `@cf` rate token - * ─► budget hold ─► @cf: env.AI.run │ anthropic / openai: /ai/v1 (or a saved key, M33) + * ─► scan and monthly spend holds ─► @cf: env.AI.run │ anthropic / openai: /ai/v1 (or a saved key, M33) * ─► usage from the JSON or SSE answer ─► settle * * A stop the runner must act on carries `x-void-scan-stop` (402 for credits); other - * refusals are retried once. `GET /v1/void/last-failure` returns the last refused call. + * refusals are retried once. `GET /v1/void/last-failure` returns the attempt's latest stop, + * or its latest failure when it had no stop, and reports a spend refusal as `tokens`. */ import { getSecurityModel, @@ -90,7 +91,7 @@ const ROUTE_HOST: Readonly> = { responses: 'openai', }; -/** A request body above this is refused; 2M input tokens fit with room to spare. */ +/** Reject a model request body above 16 MiB. */ const SECURITY_MODEL_MAX_REQUEST_BYTES = 16 * 1024 * 1024; /** Output limit of one call when the caller sets none (Engine B sends none). */ export const SECURITY_DEFAULT_CALL_OUTPUT_TOKENS = 16_384; @@ -131,6 +132,9 @@ export type SecurityModelScan = Readonly<{ modelCalls: number; tokensIn: number; tokensOut: number; + /** The scan's spend so far (open call estimates included) and its spend limit. */ + meteredNano: number; + reservedNano: number; /** `project_security_settings`; `null` when the project has no row. */ projectNoticeVersion: number | null; monthlyCapCents: number | null; @@ -236,6 +240,8 @@ export async function loadSecurityModelScan( modelCalls: securityScans.model_calls, tokensIn: securityScans.tokens_in, tokensOut: securityScans.tokens_out, + meteredNano: securityScans.metered_nano_usd, + reservedNano: securityScans.reserved_nano_usd, projectNoticeVersion: projectSecuritySettings.provider_notice_version, monthlyCapCents: projectSecuritySettings.monthly_cap_cents, capCeilingCents: projectSecuritySettings.cap_ceiling_cents, @@ -675,7 +681,7 @@ type CallPlan = Readonly<{ type Upstream = | Readonly<{ kind: 'json'; value: unknown }> | Readonly<{ kind: 'stream'; body: ReadableStream }> - // Billing unknown (unreadable 2xx, or lost with no status): the worst case stays charged. + // An unreadable success or connection loss can leave billing unknown. | Readonly<{ kind: 'paid_unreadable'; detail: string }> | Readonly<{ kind: 'failed'; status: number; credits: boolean; detail: string }>; @@ -976,7 +982,10 @@ export async function handleSecurityModelRequest( ): Promise { const url = new URL(request.url); if (request.method === 'GET' && url.pathname === SECURITY_MODEL_FAILURE_PATH) { - return Response.json({ failure: await deps.lastFailure(scanId, attempt) }); + const failure = await deps.lastFailure(scanId, attempt); + return Response.json({ + failure: failure?.reason === 'spend' ? { ...failure, reason: 'tokens' } : failure, + }); } const route = ROUTES[url.pathname]; if (request.method !== 'POST' || route === undefined) { @@ -1060,11 +1069,19 @@ export async function handleSecurityModelRequest( } const stream = body.stream === true; const forwarded = route === 'chat' ? { ...body, model: undefined } : body; - // A token is at least one byte, so the body length bounds the input tokens. + // Use the forwarded byte count as the conservative input allowance for monthly holds. const worstInput = new TextEncoder().encode(JSON.stringify(forwarded)).byteLength; // An Anthropic input token written to the 1 h cache costs 2× input. - const worstBilledInput = route === 'messages' ? worstInput * 2 : worstInput; - const worstNano = securityModelCostNanoUsd(model, worstBilledInput, callOutput) ?? 0; + const inputMultiplier = route === 'messages' ? 2 : 1; + const worstNano = securityModelCostNanoUsd(model, worstInput * inputMultiplier, callOutput) ?? 0; + const estimateInput = Math.ceil((worstInput * 2) / 5); + const estimateNano = + securityModelCostNanoUsd(model, estimateInput * inputMultiplier, callOutput) ?? 0; + // A call the scan's spend limit cannot fit is refused before it takes a session call or + // a `@cf` rate token. The hold checks again on the fresh row. + if (scan.meteredNano + estimateNano > scan.reservedNano) { + return failed('spend', stop('tokens')); + } // Session count and `@cf` rate token. Waiting here does not use a model call. const waitUntil = deps.now() + SECURITY_RATE_WAIT_LIMIT_MS; @@ -1091,7 +1108,7 @@ export async function handleSecurityModelRequest( await deps.sleep(Math.min(admitted.waitMs, left)); } - // A cap lowered during the wait applies to this call (spec §16.1, edge #50). + // Refresh the monthly caps after the rate wait. const capScan = waited ? await deps.loadScan(scanId) : scan; if (!capScan || !judgeScanFence(capScan, attempt, deps.now()).ok) { return notRunning(); @@ -1102,6 +1119,7 @@ export async function handleSecurityModelRequest( attempt, projectId: scan.projectId, worstNano, + estimateNano, maxCalls: limits.modelCallsPerScan, maxInputTokens: limits.maxInputTokens, maxOutputTokens: limits.maxOutputTokens, @@ -1112,6 +1130,9 @@ export async function handleSecurityModelRequest( if (hold.reason === 'fence') { return notRunning(); } + if (hold.reason === 'spend') { + return failed('spend', stop('tokens')); + } // Only a cap whose spend reached it is used up; a call too big for what is left is not. if (hold.reason === 'budget' && hold.spentNano >= hold.capNano) { await deps @@ -1125,8 +1146,8 @@ export async function handleSecurityModelRequest( return stopped(hold.reason); } - // `paid`: the model answered. Without usage in that answer the worst case stays - // charged, tokens included; a call that failed upstream costs nothing. + // A possibly billed call with missing usage keeps both holds and adds fallback tokens. + // A known upstream rejection costs nothing. const settle = async (usage: ModelUsage | null, paid: boolean) => { const tokens = usage ?? (paid ? { input: worstInput, output: callOutput } : { input: 0, output: 0 }); @@ -1138,7 +1159,7 @@ export async function handleSecurityModelRequest( usage.cachedInput, ) ?? 0) : paid - ? hold.holdNano + ? null : 0; try { const settlement = await deps.settle({ @@ -1146,6 +1167,7 @@ export async function handleSecurityModelRequest( projectId: scan.projectId, month: hold.month, holdNano: hold.holdNano, + estimateNano, actualNano, inputTokens: tokens.input, outputTokens: tokens.output, @@ -1154,7 +1176,7 @@ export async function handleSecurityModelRequest( .notifyCaps?.({ projectId: scan.projectId, month: hold.month, caps, settlement }) .catch(capAlertFailed); } catch (error) { - // The hold stays charged: the meter errs high, never low. + // Each meter retains its own hold when settlement fails. console.error('[security-model-proxy] settle failed', { scanId, attempt, error }); } }; diff --git a/platform/packages/api/src/security/operator.ts b/platform/packages/api/src/security/operator.ts index 4ea72b0f5..d4e44e585 100644 --- a/platform/packages/api/src/security/operator.ts +++ b/platform/packages/api/src/security/operator.ts @@ -797,7 +797,8 @@ export async function previewSecurityRescan( .limit(1); const settings = await readSecurityProjectSettings(db, projectId); const model = securityProjectModelView(policy, settings); - const worstCase = model.id === null ? null : securityScanReserveNano(model.id, policy.limits); + const reserve = model.id === null ? null : securityScanReserveNano(model.id, policy.limits); + const estimatedUsd = reserve === null ? null : reserve / NANO_USD_PER_USD; return { target: { projectId, slug: project.slug, deploymentId: live.id }, alreadyScanned: scanned !== undefined, @@ -805,7 +806,9 @@ export async function previewSecurityRescan( clientAssets: options.clientAssets === true, model: model.id, thirdParty: model.thirdParty, - worstCaseUsd: worstCase === null ? null : worstCase / NANO_USD_PER_USD, + estimatedUsd, + /** @deprecated The same estimate as `estimatedUsd`, for older CLIs. */ + worstCaseUsd: estimatedUsd, budget: await securityProjectBudgetView(db, projectId, policy, settings.caps), }; } diff --git a/platform/packages/api/src/security/policy.ts b/platform/packages/api/src/security/policy.ts index 74e7d1914..6e1ad7fb0 100644 --- a/platform/packages/api/src/security/policy.ts +++ b/platform/packages/api/src/security/policy.ts @@ -511,11 +511,22 @@ export function proposeSecurityPolicyChange( blocked: next.blockedModels.filter((id) => !current.blockedModels.includes(id)), unblocked: current.blockedModels.filter((id) => !next.blockedModels.includes(id)), noticeAccepted: request.acceptProviderNoticeVersion ?? null, - limits: SECURITY_LIMIT_KEYS.flatMap((key) => - limits[key] === current.limits[key] + limits: [ + ...SECURITY_LIMIT_KEYS.flatMap((key) => + limits[key] === current.limits[key] + ? [] + : [{ key, from: current.limits[key], to: limits[key] }], + ), + ...((limits.maxScanUsd ?? null) === (current.limits.maxScanUsd ?? null) ? [] - : [{ key, from: current.limits[key], to: limits[key] }], - ), + : [ + { + key: 'maxScanUsd' as const, + from: current.limits.maxScanUsd ?? null, + to: limits.maxScanUsd ?? null, + }, + ]), + ], publicGateOn: !current.publicGate && next.publicGate, publicGateOff: current.publicGate && !next.publicGate, sweeps: @@ -566,6 +577,14 @@ function scansText(count: number, adjective: string): string { return `${count} ${adjective} ${count === 1 ? 'scan' : 'scans'}`; } +/** A limit value for the preview: the spend limit is USD, and `null` means automatic. */ +function limitText(key: string, value: number | null): string { + if (key !== 'maxScanUsd') { + return String(value); + } + return value === null ? 'automatic' : `$${value.toFixed(2)}`; +} + /** The first non-blocked, priced `@cf` model: where a project without the notice stays. */ export function securityFallbackModel( blocked: ReadonlyArray, @@ -613,10 +632,9 @@ function modeLines( ); } if (!next.budgets.platformCapOn && !next.budgets.projectCapsOn) { + const scopes = counts.planCapped ? 'plans or projects' : 'individual projects'; lines.push( - counts.planCapped - ? ' Monthly scan budgets are off: only plans with a scan cap have a money limit. Set them with: void platform security budget' - : ' Monthly scan budgets are off (no money limit). Set them with: void platform security budget', + ` There is no default monthly scan limit. Limits set for ${scopes} still apply. Set monthly budgets with void platform security budget.`, ); } return lines; @@ -771,7 +789,7 @@ export function securityPolicyPreviewLines( } if (changes.limits.length > 0) { lines.push( - `Limits: ${changes.limits.map((limit) => `${limit.key} ${limit.from} → ${limit.to}`).join(', ')}`, + `Limits: ${changes.limits.map((limit) => `${limit.key} ${limitText(limit.key, limit.from)} → ${limitText(limit.key, limit.to)}`).join(', ')}`, ); } if (changes.publicGateOn) { diff --git a/platform/packages/api/src/security/project-page.ts b/platform/packages/api/src/security/project-page.ts index 7b716df17..609cd4a11 100644 --- a/platform/packages/api/src/security/project-page.ts +++ b/platform/packages/api/src/security/project-page.ts @@ -401,10 +401,10 @@ function budgetSkipCopy( case 'platform_cap': return `Not scanned: the platform's monthly scan budget is used up. ${resets} Your platform admin can raise it.`; case 'platform_reserve': - return `Not scanned: one scan with ${model ?? 'this model'} can cost${reserve === null ? '' : ` up to ${usd(reserve)},`} more than is left of the platform's monthly scan budget. Ask your platform admin, or pick a cheaper model.`; + return `Not scanned: one scan with ${model ?? 'this model'} needs${reserve === null ? '' : ` ${usd(reserve)},`} more than is left of the platform's monthly scan budget. Ask your platform admin, or pick a cheaper model.`; case 'project_reserve': if (budget.capUsd !== null) { - return `Not scanned: one scan with ${model ?? 'this model'} can cost${reserve === null ? '' : ` up to ${usd(reserve)},`} more than is left of this project's monthly scan budget (${usd(Math.max(0, budget.capUsd - budget.spentUsd))} of ${usd(budget.capUsd)}). Raise the cap or pick a cheaper model.`; + return `Not scanned: one scan with ${model ?? 'this model'} needs${reserve === null ? '' : ` ${usd(reserve)},`} more than is left of this project's monthly scan budget (${usd(Math.max(0, budget.capUsd - budget.spentUsd))} of ${usd(budget.capUsd)}). Raise the cap or pick a cheaper model.`; } return 'Not scanned: one scan costs more than was left of the monthly scan budget. The cap was removed since; the next deploy is scanned.'; case 'project_cap': @@ -445,6 +445,9 @@ export function scanStatusCopy(data: SecurityPageData): string | null { lastScan.refusalCategory ?? 'unknown' }). The next deploy is scanned again.`; case 'incomplete': + if (reason === 'spend_cap') { + return `Last scan reached its spend limit. Confirmed findings are kept. ${next}`; + } 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}`; diff --git a/platform/packages/api/src/security/project-view.ts b/platform/packages/api/src/security/project-view.ts index 499d75cfc..822e9cba5 100644 --- a/platform/packages/api/src/security/project-view.ts +++ b/platform/packages/api/src/security/project-view.ts @@ -250,7 +250,7 @@ export function securityProjectModelView( /** * `capUsd` is the cap that applies now (the lower of the limit and the project's own) and * `ceilingUsd` the most a project admin may set; `null` is none. `scanReserveUsd` is the - * most one scan with `model` can cost (spec §16.1): a scan starts only when it still fits. + * spend limit of one scan with `model` (spec §16.1): a scan starts only when it still fits. */ export async function securityProjectBudgetView( db: DbOrTx, @@ -327,7 +327,7 @@ type ScanRow = Awaited>[number]; /** * Why the budget skipped a scan (spec §16.1), from the scheduler's `error_class`: `*_cap` - * = that cap is used up, `*_reserve` = one scan's worst case does not fit in what is left. + * = that cap is used up, `*_reserve` = one scan's spend limit does not fit in what is left. */ const BUDGET_CAUSES = [ 'project_cap', diff --git a/platform/packages/api/src/security/sweeps.ts b/platform/packages/api/src/security/sweeps.ts index 8f68bb64f..c0098c88e 100644 --- a/platform/packages/api/src/security/sweeps.ts +++ b/platform/packages/api/src/security/sweeps.ts @@ -28,8 +28,8 @@ const REFUSAL_SLACK = 10; type Env = Pick; -/** The most each candidate's next scan can cost, summed; `null` when a model has no price. */ -function worstCaseUsd(policy: SecurityPolicy, candidates: ReadonlyArray) { +/** Each candidate's scan spend limit, summed; `null` when a model has no price. */ +function estimatedUsd(policy: SecurityPolicy, candidates: ReadonlyArray) { let total = 0; for (const candidate of candidates) { const model = securityProjectModelView(policy, { @@ -70,6 +70,7 @@ export async function previewSecurityBackfill(db: Db, now = Date.now()) { listSecurityScanCandidates(db, query, SECURITY_BACKFILL_MAX), countSecurityScanCandidates(db, query, 'missing'), ]); + const estimate = estimatedUsd(policy, candidates); return { projects: total, willQueue: candidates.length, @@ -77,7 +78,9 @@ export async function previewSecurityBackfill(db: Db, now = Date.now()) { /** Never-scanned live deployments whose code is no longer stored: deploy them again. */ noStoredCode, slugs: candidates.slice(0, PREVIEW_SLUGS).map((candidate) => candidate.slug), - worstCaseUsd: worstCaseUsd(policy, candidates), + estimatedUsd: estimate, + /** @deprecated The same estimate as `estimatedUsd`, for older CLIs. */ + worstCaseUsd: estimate, budgetsOn: policy.budgets.platformCapOn || policy.budgets.projectCapsOn, }; } diff --git a/platform/packages/api/test/integration/admin-security.test.ts b/platform/packages/api/test/integration/admin-security.test.ts index b0d3700b5..61c31e048 100644 --- a/platform/packages/api/test/integration/admin-security.test.ts +++ b/platform/packages/api/test/integration/admin-security.test.ts @@ -1,3 +1,5 @@ +import { DEFAULT_SECURITY_MODEL, SECURITY_MODEL_IDS } from '@void/platform/security-models'; +import { defaultSecurityPolicy } from '@void/platform/security-policy'; import type { SecurityPolicy } from '@void/platform/security-policy'; import { eq } from 'drizzle-orm'; import { @@ -133,6 +135,27 @@ describe('admin security pages', () => { expect((await post('/admin/security/budget', { ...fields, step: 'apply' })).status).toBe(409); }); + it('preserves saved token and spend limits through an admin policy edit', async () => { + const limits = { + ...defaultSecurityPolicy().limits, + maxInputTokens: 1_200_000, + maxScanUsd: 2.58, + }; + await saveSecurityPolicy(env, { revision: 4, limits }); + const fields = { + expectedRevision: '4', + mode: 'all', + defaultModel: DEFAULT_SECURITY_MODEL, + concurrency: '5', + timeoutMinutes: String(limits.timeoutMinutes), + ...Object.fromEntries(SECURITY_MODEL_IDS.map((id) => ['allow:' + id, 'yes'])), + }; + const path = '/admin/security/policy'; + expect((await post(path, { ...fields, step: 'preview' })).status).toBe(200); + expect((await post(path, { ...fields, step: 'apply' })).status).toBe(302); + expect((await readPolicy()).limits).toEqual({ ...limits, concurrency: 5 }); + }); + it('offers no bypass while findings hold a public request, and refuses one (I6)', async () => { const s = await setupGate(env); await askPublic(s); diff --git a/platform/packages/api/test/integration/api-project-security.test.ts b/platform/packages/api/test/integration/api-project-security.test.ts index 3827f1251..edaa270bf 100644 --- a/platform/packages/api/test/integration/api-project-security.test.ts +++ b/platform/packages/api/test/integration/api-project-security.test.ts @@ -1,3 +1,4 @@ +import { defaultSecurityPolicy } from '@void/platform/security-policy'; import { eq } from 'drizzle-orm'; import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from 'vite-plus/test'; import app from '../../src/index.ts'; @@ -17,6 +18,7 @@ import { saveSecurityPolicy, securityOff, securityOn, + storedSecurityPolicy, } from './security-fixtures.ts'; import { askPublic, @@ -138,7 +140,9 @@ describe('project security routes', () => { }); it('queues one rescan of the live deployment and refuses a second', async () => { - await saveSecurityPolicy(env); + await saveSecurityPolicy(env, { + limits: { ...defaultSecurityPolicy().limits, maxScanUsd: 2.58 }, + }); const { project, people } = await projectWithRoles(env); const deployment = await createTestDeployment(env.db, project.id); await env.STATIC_ASSETS_R2.put( @@ -146,6 +150,9 @@ describe('project security routes', () => { '[]', ); const path = `/projects/${project.id}/security/scans`; + const preview = await call(path, people.owner.jwt, { method: 'POST', body: { dryRun: true } }); + expect(preview.status).toBe(200); + expect(await json(preview)).toMatchObject({ estimatedUsd: 2.58, worstCaseUsd: 2.58 }); const queued = await call(path, people.owner.jwt, { method: 'POST', body: {} }); expect(queued.status).toBe(202); const { scanId } = await json(queued); @@ -161,6 +168,7 @@ describe('project security routes', () => { it('a third-party model needs the provider notice; writes answer 501 with the capability off (I8, I13)', async () => { const FOREIGN = 'openai/gpt-6.1-terra'; await saveSecurityPolicy(env, { + limits: { ...defaultSecurityPolicy().limits, maxInputTokens: 1_200_000, maxScanUsd: 2.58 }, entitlement: freshEntitlement({ openai: true, anthropic: false }), thirdPartyNotice: { version: 1, acceptedAt: new Date().toISOString(), acceptedByUserId: 'u' }, }); @@ -183,5 +191,9 @@ describe('project security routes', () => { expect(accepted.status).toBe(200); const [row] = await env.db.select().from(projectSecuritySettings); expect(row).toMatchObject({ model: FOREIGN, provider_notice_version: 1 }); + expect((await storedSecurityPolicy(env))?.limits).toMatchObject({ + maxInputTokens: 1_200_000, + maxScanUsd: 2.58, + }); }); }); diff --git a/platform/packages/api/test/integration/operator-security.test.ts b/platform/packages/api/test/integration/operator-security.test.ts index 1dd920ba9..d634ad800 100644 --- a/platform/packages/api/test/integration/operator-security.test.ts +++ b/platform/packages/api/test/integration/operator-security.test.ts @@ -1,3 +1,4 @@ +import { defaultSecurityPolicy } from '@void/platform/security-policy'; import { eq } from 'drizzle-orm'; import { afterAll, @@ -10,6 +11,7 @@ import { vi, } from 'vite-plus/test'; import { + operatorEvents, projectZeroTrust, securityFindingEvents, securityFindings, @@ -27,12 +29,14 @@ import { } from './helpers.ts'; import type { TestEnv } from './helpers.ts'; import { + freshEntitlement, insertSecurityFinding, insertSecurityScan, liveProject, saveSecurityPolicy, securityBindings, securityOff, + storedSecurityPolicy, } from './security-fixtures.ts'; import { askPublic, setupGate } from './security-gate-fixtures.ts'; @@ -87,8 +91,91 @@ async function call( } describe('operator security routes', () => { + it('previews and applies input-token and spend limits by revision', async () => { + await saveSecurityPolicy(env, { + revision: 4, + limits: { ...defaultSecurityPolicy().limits, maxInputTokens: 2_000_000 }, + }); + const setAmount = await call('/security/policy', { + body: { expectedRevision: 4, limits: { maxScanUsd: 2.58 } }, + }); + expect(setAmount.status).toBe(200); + expect(setAmount.body.policy.limits.maxScanUsd).toBe(2.58); + const partial = await call('/security/policy', { + body: { expectedRevision: 5, limits: { timeoutMinutes: 30 } }, + }); + expect(partial.status).toBe(200); + const savedLimits = { maxInputTokens: 2_000_000, maxScanUsd: 2.58, timeoutMinutes: 30 }; + expect(partial.body.policy.limits).toMatchObject(savedLimits); + const limits = { maxInputTokens: 10_000_000, maxScanUsd: null }; + const previewBody = { dryRun: true, limits }; + const preview = await call('/security/policy', { body: previewBody }); + expect(preview.status).toBe(200); + expect(preview.body).toMatchObject({ + expectedRevision: 6, + policy: { limits }, + changes: { + limits: [ + { key: 'maxInputTokens', from: 2_000_000, to: 10_000_000 }, + { key: 'maxScanUsd', from: 2.58, to: null }, + ], + }, + }); + expect(preview.body.preview).toContainEqual( + expect.stringContaining('maxScanUsd $2.58 → automatic'), + ); + expect((await storedSecurityPolicy(env))?.limits).toMatchObject(savedLimits); + const applyBody = { expectedRevision: preview.body.expectedRevision, limits }; + const applied = await call('/security/policy', { body: applyBody }); + expect(applied.status).toBe(200); + expect(applied.body).toMatchObject({ ok: true, policy: { revision: 7, limits } }); + expect((await call('/security/policy', { body: applyBody })).status).toBe(409); + const events = await env.db.select().from(operatorEvents); + for (const amount of [2.58, null]) { + expect(events.some(({ target }) => JSON.parse(target).limits?.maxScanUsd === amount)).toBe( + true, + ); + } + }); + + it('clamps a saved spend limit and preserves audits, the gate and monthly caps on edit', async () => { + const budgets = { + platformCapOn: true, + platformMonthlyUsd: 55, + projectCapsOn: true, + projectDefaultMonthlyUsd: 24, + }; + await saveSecurityPolicy(env, { + mode: 'all', + revision: 4, + publicGate: true, + entitlement: freshEntitlement(), + budgets, + limits: { ...defaultSecurityPolicy().limits, maxInputTokens: 2_000_000, maxScanUsd: 12.01 }, + }); + const limits = { concurrency: 3 }; + const preview = await call('/security/policy', { body: { dryRun: true, limits } }); + expect(preview.status).toBe(200); + const applied = await call('/security/policy', { + body: { expectedRevision: preview.body.expectedRevision, limits }, + }); + expect(applied.status).toBe(200); + expect(await storedSecurityPolicy(env)).toMatchObject({ + mode: 'all', + revision: 5, + publicGate: true, + budgets, + limits: { concurrency: 3, maxInputTokens: 2_000_000, maxScanUsd: 12 }, + }); + }); + it('writes the budget by revision after a preview; writes answer 501 with the capability off', async () => { - await saveSecurityPolicy(env, { revision: 4 }); + const limits = { + ...defaultSecurityPolicy().limits, + maxInputTokens: 2_000_000, + maxScanUsd: 2.58, + }; + await saveSecurityPolicy(env, { revision: 4, limits }); const body = { expectedRevision: 4, platformMonthlyUsd: 250 }; const preview = await call('/security/budget', { body: { ...body, dryRun: true } }); expect(preview.body).toMatchObject({ dryRun: true, to: { platformMonthlyUsd: 250 } }); @@ -98,6 +185,7 @@ describe('operator security routes', () => { ).toBe(409); const written = await call('/security/budget', { body }); expect(written.body).toMatchObject({ ok: true, revision: 5 }); + expect((await storedSecurityPolicy(env))?.limits).toEqual(limits); expect((await call('/security/budget', { body, bindings: securityOff(env) })).status).toBe(501); }); diff --git a/platform/packages/api/test/integration/security-byok.test.ts b/platform/packages/api/test/integration/security-byok.test.ts index 4c7224657..039d3a07f 100644 --- a/platform/packages/api/test/integration/security-byok.test.ts +++ b/platform/packages/api/test/integration/security-byok.test.ts @@ -1,4 +1,5 @@ import { getSecurityModel, securityModelCostNanoUsd } from '@void/platform/security-models'; +import { defaultSecurityPolicy } from '@void/platform/security-policy'; import type { SecurityEntitlement, SecurityPolicy } from '@void/platform/security-policy'; import { eq } from 'drizzle-orm'; import { afterAll, beforeAll, beforeEach, describe, expect, test, vi } from 'vite-plus/test'; @@ -11,9 +12,10 @@ import { loadSecurityModelScan, } from '../../src/security/model-proxy.ts'; import type { SecurityModelProxyDeps } from '../../src/security/model-proxy.ts'; -import { readSecurityPolicyLenient } from '../../src/security/policy.ts'; +import { readSecurityPolicyLenient, recordSecurityEntitlement } from '../../src/security/policy.ts'; import { loadSecurityProviderKey, + securityProviderKeyIds, SECURITY_PROVIDER_KEYS_SETTINGS_KEY, } from '../../src/security/provider-keys.ts'; import { operatorFetch } from './ai-logging-helpers.ts'; @@ -27,7 +29,7 @@ import { teardownEnv, } from './helpers.ts'; import type { TestEnv } from './helpers.ts'; -import { saveSecurityPolicy, securityOn } from './security-fixtures.ts'; +import { saveSecurityPolicy, securityOn, storedSecurityPolicy } from './security-fixtures.ts'; // BYOK (design doc 0095 M33): an installation's own provider key, stored encrypted, // added server-side by the model proxy (I3), and still metered toward the caps (I7, R14). @@ -82,7 +84,12 @@ function gatewayCall(index = 0) { describe('own provider keys (I3)', () => { test('a refused key is not saved; a good one is stored encrypted and never shown', async () => { - await savePolicy(); + const limits = { + ...defaultSecurityPolicy().limits, + maxInputTokens: 2_000_000, + maxScanUsd: 2.58, + }; + await savePolicy({ limits }); gatewayRun.mockResolvedValueOnce(Response.json({ error: 'invalid' }, { status: 401 })); const refused = await post('/security/provider-keys', { host: 'anthropic', key: KEY }); expect(refused.status).toBe(422); @@ -104,6 +111,15 @@ describe('own provider keys (I3)', () => { 'anthropic', ), ).rejects.toThrow('Failed to decrypt'); + expect((await storedSecurityPolicy(env))?.limits).toEqual(limits); + await expect( + recordSecurityEntitlement(env.db, PASSED, await securityProviderKeyIds(env.db)), + ).resolves.toMatchObject({ saved: true }); + expect((await storedSecurityPolicy(env))?.limits).toEqual(limits); + expect((await post('/security/provider-keys', { host: 'anthropic', key: null })).status).toBe( + 200, + ); + expect((await storedSecurityPolicy(env))?.limits).toEqual(limits); }); test('the proxy adds the key server-side and meters the call like any other (I7)', async () => { @@ -120,6 +136,7 @@ describe('own provider keys (I3)', () => { attempt: 1, lease_until: '2026-11-18T13:00:00.000Z', model_used: OPUS, + reserved_nano_usd: 7_200_000_000, engine: getSecurityModel(OPUS).engine, }); await env.db.insert(projectSecuritySettings).values({ diff --git a/platform/packages/api/test/integration/security-ingest.test.ts b/platform/packages/api/test/integration/security-ingest.test.ts index 4ad40607e..5f4989639 100644 --- a/platform/packages/api/test/integration/security-ingest.test.ts +++ b/platform/packages/api/test/integration/security-ingest.test.ts @@ -16,12 +16,18 @@ import { securityNotifications, securityScans, } from '../../src/schema.ts'; +import { + forgetModelCalls, + readModelCallFailure, + recordModelCallFailure, +} from '../../src/security/call-ledger.ts'; import { ingestSecurityScanResult } from '../../src/security/ingest.ts'; import { prepareSecurityScanInput } from '../../src/security/input/prepare.ts'; import { readSecurityPolicyLenient } from '../../src/security/policy.ts'; import { reapExpiredSecurityScans } from '../../src/security/queue.ts'; import { runSecurityScanQueue, securityScanQueueStore } from '../../src/security/scheduler.ts'; import type { SchedulerStorage } from '../../src/security/scheduler.ts'; +import { memoryDurableStorage } from '../helpers/memory-storage.ts'; import { clearTables, createTestDeployment, @@ -124,6 +130,81 @@ function ingest(scanId: string, report: ReturnType, attempt = } describe('scan result ingest', () => { + it.each([ + ['spend', 'spend_cap'], + ['spend-then-upstream', 'spend_cap'], + ['tokens', 'token_cap'], + ['previous-attempt', 'token_cap'], + ['unavailable', 'token_cap'], + ] as const)( + 'labels a token stop from the current attempt ledger (%s)', + async (latest, expected) => { + const p = await setup(); + const deployment = await deploy(p.id); + const id = 'ss_ledger'; + await runningScan(id, p.id, deployment.id, { attempt: 2 }); + const { storage } = memoryDurableStorage(); + const spend = { reason: 'spend', httpStatus: 429, at: 100 } as const; + await recordModelCallFailure(storage, id, 1, spend); + if (latest !== 'previous-attempt') { + await recordModelCallFailure(storage, id, 2, spend); + } + if (latest === 'tokens') { + await recordModelCallFailure(storage, id, 2, { ...spend, reason: 'tokens', at: 200 }); + } + if (latest === 'spend-then-upstream') { + // Another call fails after the refusal; the stop must still decide the result. + await recordModelCallFailure(storage, id, 2, { + reason: 'upstream', + httpStatus: 503, + at: 200, + }); + } + const keepsFindings = latest === 'spend' || latest === 'spend-then-upstream'; + const operations: Array = []; + onEnv = securityBindings(env, { + scheduler: { + modelCallFailure: async (scanId: string, attempt: number) => { + operations.push('read:' + attempt); + if (latest === 'unavailable') { + throw new Error('fixture ledger unavailable'); + } + return readModelCallFailure(storage, scanId, attempt); + }, + forgetModelCalls: async (scanId: string, attempt: number) => { + if (keepsFindings) { + expect((await scan(id)).status_reason).toBe('spend_cap'); + } + operations.push('forget:' + attempt); + return forgetModelCalls(storage, scanId, attempt); + }, + }, + }); + await expect( + ingest( + id, + scanResult(id, keepsFindings ? [findingRecord()] : [], { + attempt: 2, + status: 'incomplete', + reason: 'token_cap', + }), + 2, + ), + ).resolves.toMatchObject({ kind: 'stored', status: 'incomplete' }); + expect(await scan(id)).toMatchObject({ + status: 'incomplete', + status_reason: expected, + attempt: 2, + }); + if (keepsFindings) { + expect(await findingsOf(p.id)).toMatchObject([{ verdict: 'confirmed' }]); + } + expect(operations).toEqual(['read:2', 'forget:2']); + expect(await readModelCallFailure(storage, id, 2)).toBeNull(); + expect(await readModelCallFailure(storage, id, 1)).toMatchObject({ reason: 'spend' }); + }, + ); + it('drives a queued scan through claim, input and result to stored findings', async () => { await saveSecurityPolicy(env); const project = await setup(); diff --git a/platform/packages/api/test/integration/security-page.test.ts b/platform/packages/api/test/integration/security-page.test.ts index e32476c91..c71e4f5a1 100644 --- a/platform/packages/api/test/integration/security-page.test.ts +++ b/platform/packages/api/test/integration/security-page.test.ts @@ -76,10 +76,14 @@ describe('read-only security page', () => { await saveSecurityPolicy(env); const { project, people } = await projectWithRoles(env); const deployment = await createTestDeployment(env.db, project.id); - await insertCompletedScan(env, project.id, deployment.id); + await insertCompletedScan(env, project.id, deployment.id, { + status: 'incomplete', + status_reason: 'spend_cap', + }); await insertSecurityFinding(env, project.id, { number: 1, severity: 'critical' }); const owner = await view(await signIn(people.owner.id, project.id)); + expect(owner).toContain('Last scan reached its spend limit. Confirmed findings are kept.'); expect(owner).toContain('1 urgent finding is open'); expect(owner).toContain('SECRET TITLE 1'); expect(owner).toContain('src/routes/secret-1.ts:41'); diff --git a/platform/packages/api/test/integration/security-public-gate.test.ts b/platform/packages/api/test/integration/security-public-gate.test.ts index 468007124..f3d287176 100644 --- a/platform/packages/api/test/integration/security-public-gate.test.ts +++ b/platform/packages/api/test/integration/security-public-gate.test.ts @@ -69,6 +69,42 @@ async function gateScans(s: Setup) { } describe('public gate (I6)', () => { + it('keeps a public request protected after a spend stop', async () => { + const s = await setup(); + await keepInput(s); + const scanId = 'ss_partial'; + await insertRunningScan(env, scanId, s.project.id, s.deployment.id, { trigger: 'gate' }); + expect((await ask(s)).publicRequest?.state).toBe('waiting_scan'); + const bindings = { + ...s.platform, + SECURITY_SCAN_SCHEDULER: schedulerStub({ + modelCallFailure: async () => ({ reason: 'spend', httpStatus: 429, at: Date.now() }), + forgetModelCalls: async () => {}, + }), + }; + await expect( + ingestSecurityScanResult( + bindings, + env.db, + scanId, + 1, + scanResult(scanId, [], { + status: 'incomplete', + reason: 'token_cap', + }), + ), + ).resolves.toMatchObject({ status: 'incomplete' }); + expect(await gateScans(s)).toMatchObject([ + { + status: 'incomplete', + status_reason: 'spend_cap', + }, + ]); + const rechecked = await recheckPublicRequest(s.platform, env.db, s.project.id); + expect(rechecked?.state).toBe('held_no_result'); + expect((await ztRow(s)).desired_protected).toBe(true); + }); + it('holds a request with no scan, then goes public once a scan passes', async () => { const s = await setup(); const asked = await ask(s); diff --git a/platform/packages/api/test/integration/security-spend.test.ts b/platform/packages/api/test/integration/security-spend.test.ts index 096b0b1a6..1a16d1975 100644 --- a/platform/packages/api/test/integration/security-spend.test.ts +++ b/platform/packages/api/test/integration/security-spend.test.ts @@ -1,4 +1,5 @@ import { securityModelCostNanoUsd } from '@void/platform/security-models'; +import { defaultSecurityPolicy } from '@void/platform/security-policy'; import type { SecurityPolicy } from '@void/platform/security-policy'; import { and, eq } from 'drizzle-orm'; import { afterAll, beforeAll, beforeEach, describe, expect, test, vi } from 'vite-plus/test'; @@ -11,6 +12,7 @@ import { import { holdSecurityModelCall, reserveSecurityScanBudget, + securityScanReserveNano, settleSecurityModelCall, } from '../../src/security/budget.ts'; import { @@ -19,7 +21,7 @@ import { SECURITY_STOP_HEADER, } from '../../src/security/model-proxy.ts'; import type { SecurityModelProxyDeps } from '../../src/security/model-proxy.ts'; -import { readSecurityPolicyLenient } from '../../src/security/policy.ts'; +import { changeSecurityPolicy, readSecurityPolicyLenient } from '../../src/security/policy.ts'; import { clearTables, createTestDeployment, @@ -32,6 +34,7 @@ import type { TestEnv } from './helpers.ts'; import { saveSecurityPolicy } from './security-fixtures.ts'; const CF = '@cf/zai-org/glm-5.3'; +const DEEPSEEK = '@cf/deepseek-ai/deepseek-v4.1-flash-1017'; const NOV = '2026-11-01'; const NOW = Date.parse('2026-11-18T12:00:00.000Z'); const LEASE = '2026-11-18T13:00:00.000Z'; @@ -101,6 +104,113 @@ async function scanRow(id: string) { return row; } +describe('per-scan model holds on real SQL', () => { + async function fixture(reserved: number, metered = 0, attempt = 1) { + const app = await project('scan-hold'); + await scan(app.id, app.deploymentId, 'ss_hold', { + attempt, + reserved_nano_usd: reserved, + metered_nano_usd: metered, + lease_until: '2026-12-02T00:00:00.000Z', + }); + return { + scanId: 'ss_hold', + attempt, + projectId: app.id, + maxCalls: 80, + maxInputTokens: 10_000_000, + maxOutputTokens: 120_000, + caps: { projectNano: null, platformNano: null }, + now: NOW, + }; + } + + test.each([ + ['one nano-dollar over', 100, 91, 10, 40], + ['a zero reserve', 0, 0, 0, 0], + ] as const)( + 'refuses %s without changing either meter', + async (_case, reserve, metered, estimateNano, worstNano) => { + const input = { ...(await fixture(reserve, metered)), worstNano, estimateNano }; + const before = await scanRow(input.scanId); + await expect(holdSecurityModelCall(env.db, input)).resolves.toEqual({ + ok: false, + reason: 'spend', + }); + expect(await scanRow(input.scanId)).toEqual(before); + expect(await projectSpend(input.projectId)).toBeUndefined(); + expect(await platformSpend()).toBeUndefined(); + }, + ); + + test('accepts a hold that exactly fits the saved reserve', async () => { + const input = { ...(await fixture(101, 91)), worstNano: 40, estimateNano: 10 }; + await expect(holdSecurityModelCall(env.db, input)).resolves.toMatchObject({ ok: true }); + expect(await scanRow(input.scanId)).toMatchObject({ metered_nano_usd: 101, model_calls: 1 }); + expect((await projectSpend(input.projectId)).spent_nano_usd).toBe(40); + expect((await platformSpend()).spent_nano_usd).toBe(40); + }); + + test('a retried attempt counts the spend of earlier attempts against its new reserve', async () => { + // The claim keeps `metered_nano_usd`; the new attempt saves a fresh reserve. + const input = { ...(await fixture(100, 90, 2)), worstNano: 40 }; + await expect(holdSecurityModelCall(env.db, { ...input, estimateNano: 11 })).resolves.toEqual({ + ok: false, + reason: 'spend', + }); + await expect( + holdSecurityModelCall(env.db, { ...input, estimateNano: 10 }), + ).resolves.toMatchObject({ ok: true }); + }); + + // PGlite runs one transaction at a time; the guarantee is the single conditional UPDATE. + test('one of two overlapping holds fits, then a refund frees room across month rollover', async () => { + const input = { ...(await fixture(100)), estimateNano: 60, worstNano: 120 }; + const holds = await Promise.all([ + holdSecurityModelCall(env.db, input), + holdSecurityModelCall(env.db, input), + ]); + expect(holds).toEqual( + expect.arrayContaining([ + { ok: true, month: NOV, holdNano: 120, modelCalls: 1 }, + { ok: false, reason: 'spend' }, + ]), + ); + expect(await scanRow(input.scanId)).toMatchObject({ metered_nano_usd: 60, model_calls: 1 }); + expect((await projectSpend(input.projectId)).spent_nano_usd).toBe(120); + expect((await platformSpend()).spent_nano_usd).toBe(120); + const december = { ...input, now: Date.parse('2026-12-01T00:01:00.000Z') }; + await expect(holdSecurityModelCall(env.db, december)).resolves.toMatchObject({ + reason: 'spend', + }); + await settleSecurityModelCall(env.db, { + ...input, + month: NOV, + holdNano: 120, + actualNano: 40, + inputTokens: 150, + outputTokens: 10, + }); + expect(await scanRow(input.scanId)).toMatchObject({ + metered_nano_usd: 40, + tokens_in: 150, + tokens_out: 10, + }); + await expect(holdSecurityModelCall(env.db, december)).resolves.toMatchObject({ + ok: true, + month: '2026-12-01', + }); + expect(await scanRow(input.scanId)).toMatchObject({ metered_nano_usd: 100, model_calls: 2 }); + for (const [month, expected] of [ + [NOV, 40], + ['2026-12-01', 120], + ] as const) { + expect((await projectSpend(input.projectId, month)).spent_nano_usd).toBe(expected); + expect((await platformSpend(month)).spent_nano_usd).toBe(expected); + } + }); +}); + describe('scan start reserve', () => { test('two scans near the platform cap: both reserve, only one fits (edge #51)', async () => { const a = await project('spend-a'); @@ -204,16 +314,16 @@ describe('model proxy on real SQL', () => { const savePolicy = (changes: Partial) => saveSecurityPolicy(env, changes); - function chat(): Request { + function chat(model: string = CF, content = 'scan', stream?: boolean): Request { return new Request('http://model.void.internal/v1/chat/completions', { method: 'POST', - body: JSON.stringify({ model: CF, messages: [{ role: 'user', content: 'scan' }] }), + body: JSON.stringify({ model, messages: [{ role: 'user', content }], stream }), }); } test('meters tokens × list price, and a project cap stops the next call that could cross it', async () => { const p = await project('spend-meter'); - await scan(p.id, p.deploymentId, 'ss_1'); + await scan(p.id, p.deploymentId, 'ss_1', { reserved_nano_usd: 2 * USD }); await savePolicy({}); const run = vi.fn(async () => ({ response: 'ok', @@ -239,4 +349,206 @@ describe('model proxy on real SQL', () => { expect(stopped.headers.get(SECURITY_STOP_HEADER)).toBe('budget'); expect(run).toHaveBeenCalledTimes(1); }); + + test.each([ + { case: 'a paid answer lacks usage', rejectSettlement: false }, + { case: 'settlement fails', rejectSettlement: true }, + ])('keeps each hold when $case', async ({ rejectSettlement }) => { + const p = await project('spend-unsettled'); + await scan(p.id, p.deploymentId, 'ss_1', { reserved_nano_usd: 2 * USD }); + await savePolicy({}); + let estimate = 0; + let worst = 0; + const proxy = deps({ + hold: (input) => { + estimate = input.estimateNano; + worst = input.worstNano; + return holdSecurityModelCall(env.db, input); + }, + ai: { + run: async () => { + expect(estimate).toBeLessThan(worst); + expect((await scanRow('ss_1')).metered_nano_usd).toBe(estimate); + expect((await projectSpend(p.id)).spent_nano_usd).toBe(worst); + return { + response: 'ok', + usage: rejectSettlement ? { prompt_tokens: 1, completion_tokens: 1 } : undefined, + }; + }, + } as unknown as Ai, + settle: (input) => + rejectSettlement + ? Promise.reject(new Error('fixture settlement failed')) + : settleSecurityModelCall(env.db, input), + }); + expect((await handleSecurityModelRequest(proxy, 'ss_1', 1, chat())).status).toBe(200); + const row = await scanRow('ss_1'); + expect(row.metered_nano_usd).toBe(estimate); + expect(row.tokens_in).toBe(rejectSettlement ? 0 : 66); + expect(row.tokens_out).toBe(rejectSettlement ? 0 : 16_384); + expect((await projectSpend(p.id)).spent_nano_usd).toBe(worst); + expect((await platformSpend()).spent_nano_usd).toBe(worst); + }); + + test('the 1.6 MB retry fits the original reserve while the first call is outstanding', async () => { + const p = await project('spend-retry'); + await savePolicy({ defaultModel: DEEPSEEK }); + const policy = await readSecurityPolicyLenient(env.db); + const reserve = securityScanReserveNano(DEEPSEEK, policy.limits)!; + await scan(p.id, p.deploymentId, 'ss_1', { reserved_nano_usd: reserve, model_used: DEEPSEEK }); + const request = () => chat(DEEPSEEK, 'x'.repeat(1_600_000)); + let markEntered!: () => void; + let finishFirstCall!: () => void; + const entered = new Promise((resolve) => { + markEntered = resolve; + }); + const release = new Promise((resolve) => { + finishFirstCall = resolve; + }); + const run = vi.fn(async () => { + if (run.mock.calls.length === 1) { + markEntered(); + await release; + } + return { response: 'ok', usage: { prompt_tokens: 1, completion_tokens: 1 } }; + }); + const proxy = deps({ ai: { run } as unknown as Ai }); + const initial = handleSecurityModelRequest(proxy, 'ss_1', 1, request()); + try { + await entered; + expect((await scanRow('ss_1')).metered_nano_usd).toBeLessThan(reserve / 2); + expect((await platformSpend()).spent_nano_usd).toBeGreaterThan(reserve / 2); + await savePolicy({ defaultModel: DEEPSEEK, limits: { ...policy.limits, maxScanUsd: 0.01 } }); + expect((await handleSecurityModelRequest(proxy, 'ss_1', 1, request())).status).toBe(200); + expect((await scanRow('ss_1')).reserved_nano_usd).toBe(reserve); + } finally { + finishFirstCall(); + await initial; + } + const actual = securityModelCostNanoUsd(DEEPSEEK, 1, 1)! * 2; + expect(await scanRow('ss_1')).toMatchObject({ metered_nano_usd: actual, model_calls: 2 }); + expect((await platformSpend()).spent_nano_usd).toBe(actual); + }); + + test.each(['connection reset', 'stream cancellation'])( + 'fits a retry after %s with a saved 2M token limit', + async (failure) => { + const p = await project('spend-retry-settled'); + const policy = await savePolicy({ + defaultModel: DEEPSEEK, + limits: { ...defaultSecurityPolicy().limits, maxInputTokens: 2_000_000 }, + }); + const reserve = securityScanReserveNano(DEEPSEEK, policy.limits)!; + await scan(p.id, p.deploymentId, 'ss_1', { + reserved_nano_usd: reserve, + model_used: DEEPSEEK, + }); + const stream = failure === 'stream cancellation'; + const run = vi.fn<() => Promise>(async () => ({ + response: 'ok', + usage: { prompt_tokens: 1, completion_tokens: 1 }, + })); + if (stream) { + run.mockResolvedValueOnce(new ReadableStream()); + } else { + run.mockRejectedValueOnce(new Error('connection reset by peer')); + } + const hold = vi.fn((input) => + holdSecurityModelCall(env.db, input), + ); + const proxy = deps({ ai: { run } as unknown as Ai, hold }); + const request = () => chat(DEEPSEEK, 'x'.repeat(1_600_000), stream); + const first = await handleSecurityModelRequest(proxy, 'ss_1', 1, request()); + expect(first.status).toBe(stream ? 200 : 502); + if (stream) { + await first.body!.cancel(); + } + const [firstHold] = hold.mock.calls[0]; + const afterLoss = await scanRow('ss_1'); + expect((await handleSecurityModelRequest(proxy, 'ss_1', 1, request())).status).toBe(200); + expect(run).toHaveBeenCalledTimes(2); + expect(afterLoss.metered_nano_usd).toBe(firstHold.estimateNano); + expect(afterLoss.tokens_in).toBeGreaterThan(1_600_000); + const monthly = firstHold.worstNano + securityModelCostNanoUsd(DEEPSEEK, 1, 1)!; + expect((await projectSpend(p.id)).spent_nano_usd).toBe(monthly); + expect((await platformSpend()).spent_nano_usd).toBe(monthly); + }, + ); + + test.each([ + { name: 'cached default', policySource: 'default', cached: true, refusal: null }, + { name: 'uncached default', policySource: 'default', cached: false, refusal: 'spend' }, + { name: 'saved limit', policySource: 'saved', cached: true, refusal: 'tokens' }, + { name: 'raised limit', policySource: 'raised', cached: true, refusal: null }, + ])( + 'applies token and spend limits to the next #966 call ($name)', + async ({ policySource, cached, refusal }) => { + const p = await project('replay-next-call'); + const saved = await savePolicy({ + defaultModel: DEEPSEEK, + ...(policySource !== 'default' + ? { limits: { ...defaultSecurityPolicy().limits, maxInputTokens: 2_000_000 } } + : {}), + }); + if (policySource === 'raised') { + await changeSecurityPolicy( + env.db, + { + limits: { maxInputTokens: 10_000_000, maxScanUsd: null }, + expectedRevision: saved.revision, + }, + { userId: 'fixture', preview: false }, + ); + } + const policy = await readSecurityPolicyLenient(env.db); + const inputTokens = cached ? 2_034_125 : 1_400_000; + const metered = cached ? 57_100_000 : securityModelCostNanoUsd(DEEPSEEK, inputTokens, 1200)!; + const reserve = securityScanReserveNano(DEEPSEEK, policy.limits)!; + expect(metered).toBeLessThan(reserve); + await scan(p.id, p.deploymentId, 'ss_966', { + model_used: DEEPSEEK, + model_calls: 32, + started_at: new Date(NOW).toISOString(), + tokens_in: inputTokens, + tokens_out: 1200, + metered_nano_usd: metered, + }); + await reserveSecurityScanBudget(env.db, { + scanId: 'ss_966', + attempt: 1, + projectId: p.id, + reserveNano: reserve, + caps: { platformNano: null, projectNano: null }, + now: NOW, + }); + const run = vi.fn(async () => ({ + response: 'ok', + usage: { + prompt_tokens: 250_000, + prompt_tokens_details: { cached_tokens: cached ? 235_000 : 0 }, + completion_tokens: 200, + }, + })); + const recordFailure = vi + .fn() + .mockResolvedValue(undefined); + const proxy = deps({ ai: { run } as unknown as Ai, recordFailure }); + const response = await handleSecurityModelRequest( + proxy, + 'ss_966', + 1, + chat(DEEPSEEK, 'x'.repeat(1_600_000)), + ); + expect(response.status).toBe(refusal ? 429 : 200); + expect(response.headers.get(SECURITY_STOP_HEADER)).toBe(refusal ? 'tokens' : null); + expect(recordFailure.mock.lastCall?.[2].reason ?? null).toBe(refusal); + expect(run).toHaveBeenCalledTimes(refusal ? 0 : 1); + expect(await scanRow('ss_966')).toMatchObject({ + model_calls: refusal ? 32 : 33, + tokens_in: refusal ? inputTokens : 2_284_125, + metered_nano_usd: refusal ? metered : 63_250_000, + reserved_nano_usd: 504_000_000, + }); + }, + ); }); diff --git a/platform/packages/api/test/unit/security-budget.test.ts b/platform/packages/api/test/unit/security-budget.test.ts index 104819aef..8ee37a3c0 100644 --- a/platform/packages/api/test/unit/security-budget.test.ts +++ b/platform/packages/api/test/unit/security-budget.test.ts @@ -1,4 +1,4 @@ -import { defaultSecurityBudgets } from '@void/platform/security-policy'; +import { defaultSecurityBudgets, defaultSecurityPolicy } from '@void/platform/security-policy'; import type { SecurityPolicyBudgets } from '@void/platform/security-policy'; import { expect, it } from 'vite-plus/test'; import { @@ -9,9 +9,12 @@ import { } from '../../src/security/budget.ts'; import { admitModelCall, + readModelCallFailure, + recordModelCallFailure, SECURITY_CF_CALLS_PER_MINUTE, SECURITY_SESSION_CALL_LIMIT, } from '../../src/security/call-ledger.ts'; +import type { ModelCallFailureReason } from '../../src/security/call-ledger.ts'; import { memoryDurableStorage } from '../helpers/memory-storage.ts'; function budgets(overrides: Partial = {}): SecurityPolicyBudgets { @@ -43,9 +46,22 @@ it.each([ ); }); -it('reserves the worst case of one scan at list price (spec §16.1)', () => { - const limits = { maxInputTokens: 600_000, maxOutputTokens: 60_000 }; - expect(securityScanReserveNano('anthropic/claude-opus-5.5', limits)).toBe(3_600_000_000); +it('computes the automatic and explicit scan reserves', () => { + const { limits } = defaultSecurityPolicy(); + const deepseek = '@cf/deepseek-ai/deepseek-v4.1-flash-1017'; + for (const [maxInputTokens, expected] of [ + [600_000, 324_000_000], + [1_200_000, 504_000_000], + [2_000_000, 504_000_000], + ]) { + expect(securityScanReserveNano(deepseek, { ...limits, maxInputTokens })).toBe(expected); + } + expect(securityScanReserveNano(deepseek, limits)).toBe(504_000_000); + expect(securityScanReserveNano('@cf/zai-org/glm-5.3', limits)).toBe(2_208_000_000); + expect(securityScanReserveNano('anthropic/claude-opus-5.5', limits)).toBe(7_200_000_000); + expect(securityScanReserveNano('@cf/zai-org/glm-5.3', { ...limits, maxScanUsd: 2.58 })).toBe( + 2_580_000_000, + ); expect(securityScanReserveNano('anthropic/claude-sonnet-5.5', limits)).toBeNull(); }); @@ -74,3 +90,28 @@ it('stops the 41st call of a session and rate-limits @cf calls per model', async }); await expect(admitModelCall(storage, { ...cf, now: 6000 })).resolves.toMatchObject({ ok: true }); }); + +it.each([ + [['spend', 'upstream'], 'spend', 1], + [['tokens', 'rate_wait'], 'tokens', 1], + [['upstream', 'spend'], 'spend', 2], + [['spend', 'spend'], 'spend', 2], + [['spend', 'session_calls'], 'session_calls', 2], + [['upstream', 'refused'], 'refused', 2], + // A monthly cap or credits can free up, so a later failure replaces those stops. + [['budget', 'upstream'], 'upstream', 2], + [['credits', 'rate_wait'], 'rate_wait', 2], + // A newer stop of any kind still replaces a limit stop. + [['spend', 'credits'], 'credits', 2], + [['tokens', 'budget'], 'budget', 2], +] as const)('the ledger keeps a stop over later failures: %j', async (reasons, reason, at) => { + const { storage } = memoryDurableStorage(); + for (const [index, failure] of (reasons as ReadonlyArray).entries()) { + await recordModelCallFailure(storage, 'ss_1', 1, { + reason: failure, + httpStatus: 429, + at: index + 1, + }); + } + expect(await readModelCallFailure(storage, 'ss_1', 1)).toMatchObject({ reason, at }); +}); diff --git a/platform/packages/api/test/unit/security-model-proxy.test.ts b/platform/packages/api/test/unit/security-model-proxy.test.ts index b4bef3571..56eef7c7e 100644 --- a/platform/packages/api/test/unit/security-model-proxy.test.ts +++ b/platform/packages/api/test/unit/security-model-proxy.test.ts @@ -1,6 +1,8 @@ +import { setImmediate } from 'node:timers/promises'; import { securityModelCostNanoUsd } from '@void/platform/security-models'; import { beforeEach, describe, expect, it, vi } from 'vite-plus/test'; import type { SecurityCallHold, SecurityCallRefusal } from '../../src/security/budget.ts'; +import { readModelCallFailure, recordModelCallFailure } from '../../src/security/call-ledger.ts'; import type { AdmitModelCallResult, ModelCallFailure } from '../../src/security/call-ledger.ts'; import { handleSecurityModelRequest, @@ -9,6 +11,7 @@ import { SECURITY_STOP_HEADER, } from '../../src/security/model-proxy.ts'; import type { SecurityModelProxyDeps, SecurityModelScan } from '../../src/security/model-proxy.ts'; +import { memoryDurableStorage } from '../helpers/memory-storage.ts'; import { onPolicy, passingEntitlement } from '../helpers/security-policy.ts'; // The runner's own mapping, so a proxy stop is checked end to end (spec §8.4). A @@ -32,6 +35,8 @@ function scanRow(overrides: Partial = {}): SecurityModelScan modelCalls: 0, tokensIn: 0, tokensOut: 0, + meteredNano: 0, + reservedNano: 12_000_000_000, projectNoticeVersion: 1, monthlyCapCents: null, capCeilingCents: null, @@ -42,6 +47,8 @@ function scanRow(overrides: Partial = {}): SecurityModelScan function harness() { const clock = { now: NOW }; + // The real ledger rule decides what `last-failure` returns. + const { storage: ledger } = memoryDurableStorage(); const state = { scan: scanRow() as SecurityModelScan | undefined, policy: onPolicy(), @@ -70,10 +77,11 @@ function harness() { loadScan: async () => state.scan, readPolicy: async () => state.policy, admit: state.admit, - recordFailure: async (_scanId, _attempt, failure) => { + recordFailure: async (scanId, attempt, failure) => { state.failures.push(failure); + await recordModelCallFailure(ledger, scanId, attempt, failure); }, - lastFailure: async () => state.failures.at(-1) ?? null, + lastFailure: (scanId, attempt) => readModelCallFailure(ledger, scanId, attempt), rateLimited: async () => {}, hold: state.hold, settle: async (input) => { @@ -142,6 +150,128 @@ function fetchOk() { } describe('metering (I7)', () => { + it.each([ + [400_226, 160_091], + [1_609_427, 643_771], + ])('estimates the token cost of %d forwarded UTF-8 bytes', async (bytes, estimatedTokens) => { + const end = { + ...chatBody(), + model: undefined, + max_tokens: SECURITY_DEFAULT_CALL_OUTPUT_TOKENS, + }; + const empty = { ...end, messages: [{ role: 'user', content: '' }] }; + const encoder = new TextEncoder(); + const padding = + bytes - encoder.encode(JSON.stringify(empty)).byteLength - encoder.encode('漢').byteLength; + const result = await call( + '/v1/chat/completions', + chatBody({ + messages: [{ role: 'user', content: '漢' + 'x'.repeat(padding) }], + }), + ); + expect(result.status).toBe(200); + expect(h.holds[0]).toMatchObject({ + worstNano: securityModelCostNanoUsd(CF, bytes, SECURITY_DEFAULT_CALL_OUTPUT_TOKENS), + estimateNano: securityModelCostNanoUsd( + CF, + estimatedTokens, + SECURITY_DEFAULT_CALL_OUTPUT_TOKENS, + ), + }); + }); + + it('records the spend refusal before returning tokens to the runner', async () => { + h.hold.mockResolvedValue({ ok: false, reason: 'spend' }); + let markRecording!: () => void; + let finishRecording!: () => void; + const recording = new Promise((resolve) => { + markRecording = resolve; + }); + const recorded = new Promise((resolve) => { + finishRecording = resolve; + }); + const notifyCapRefused = vi.fn(); + const deps = { + ...h.deps, + notifyCapRefused, + recordFailure: async (...args: Parameters) => { + markRecording(); + await recorded; + await h.deps.recordFailure(...args); + }, + }; + let finished = false; + const pending = handleSecurityModelRequest( + deps, + 'ss_1', + 2, + new Request('http://model.void.internal/v1/chat/completions', { + method: 'POST', + body: JSON.stringify(chatBody()), + }), + ).then((response) => { + finished = true; + return response; + }); + try { + await Promise.race([recording, pending]); + await setImmediate(); + expect(finished).toBe(false); + } finally { + finishRecording(); + } + const response = await pending; + expect(response.status).toBe(429); + expect(stop(response)).toBe('tokens'); + expect(h.failures.at(-1)).toMatchObject({ reason: 'spend', httpStatus: 429 }); + expect(h.admit).toHaveBeenCalledTimes(1); + expect(h.aiRun).not.toHaveBeenCalled(); + expect(notifyCapRefused).not.toHaveBeenCalled(); + const last = await handleSecurityModelRequest( + deps, + 'ss_1', + 2, + new Request('http://model.void.internal/v1/void/last-failure'), + ); + expect(await last.json()).toMatchObject({ failure: { reason: 'tokens', httpStatus: 429 } }); + }); + + it('refuses a call the spend limit cannot fit before it takes a session call or rate token', async () => { + h.scan = scanRow({ meteredNano: 12_000_000_000 }); + const response = await call('/v1/chat/completions', chatBody(), { 'x-void-scan-session': '1' }); + expect(response.status).toBe(429); + expect(stop(response)).toBe('tokens'); + expect(h.failures.at(-1)).toMatchObject({ reason: 'spend' }); + expect(h.admit).not.toHaveBeenCalled(); + expect(h.hold).not.toHaveBeenCalled(); + }); + + it('keeps reporting the spend stop after a later call fails upstream', async () => { + h.scan = scanRow({ modelUsed: TERRA }); + h.hold.mockResolvedValueOnce({ ok: false, reason: 'spend' }); + expect(stop(await call('/v1/responses', { model: TERRA, input: 'x' }))).toBe('tokens'); + // A smaller call still fits, then the provider answers 503. + h.fetch.mockResolvedValue(Response.json({ error: { message: 'busy' } }, { status: 503 })); + const failedCall = await call('/v1/responses', { model: TERRA, input: 'y' }); + expect(failedCall.status).toBe(503); + expect(h.failures.map((failure) => failure.reason)).toEqual(['spend', 'upstream']); + const last = await handleSecurityModelRequest( + h.deps, + 'ss_1', + 2, + new Request('http://model.void.internal/v1/void/last-failure'), + ); + const { failure } = await last.json<{ failure: ModelCallFailure }>(); + expect(failure).toMatchObject({ reason: 'tokens', httpStatus: 429 }); + const runner = (await import(/* @vite-ignore */ RUNNER_STATUS)) as { + classifyProxyStop(httpStatus: number, reason: unknown): unknown; + readProxyStopReason(value: string | null): unknown; + }; + expect( + runner.classifyProxyStop(failure.httpStatus, runner.readProxyStopReason(failure.reason)), + ).toEqual({ kind: 'stopped', reason: 'tokens' }); + }); + it('runs @cf on the binding with fixed gateway options and settles the hold to the real cost', async () => { h.aiRun.mockResolvedValue({ response: 'ok', @@ -163,6 +293,7 @@ describe('metering (I7)', () => { expect(h.settles).toEqual([ expect.objectContaining({ holdNano: h.holds[0].worstNano, + estimateNano: h.holds[0].estimateNano, actualNano: securityModelCostNanoUsd(CF, 1000, 200), inputTokens: 1000, outputTokens: 200, @@ -170,13 +301,14 @@ describe('metering (I7)', () => { ]); }); - it('keeps the worst case charged for a lost call or an answer with no usage', async () => { + it('keeps each hold and adds fallback tokens when billing is unknown', async () => { h.aiRun.mockRejectedValueOnce(new Error('Network connection lost.')); expect((await call('/v1/chat/completions', chatBody())).status).toBe(502); h.aiRun.mockResolvedValueOnce({ response: 'ok' }); expect((await call('/v1/chat/completions', chatBody())).status).toBe(200); - for (const [index, settled] of h.settles.entries()) { - expect(settled.actualNano).toBe(h.holds[index].worstNano); + expect(h.settles).toHaveLength(2); + for (const settled of h.settles) { + expect(settled.actualNano).toBeNull(); expect(settled.inputTokens).toBeGreaterThan(0); } // A known status means no answer was made: it costs nothing. @@ -185,7 +317,7 @@ describe('metering (I7)', () => { expect(h.settles[2]).toMatchObject({ actualNano: 0, inputTokens: 0, outputTokens: 0 }); }); - it('keeps the worst case for a stream that is dropped, cut short or ends in an error', async () => { + it('keeps each hold for a stream that is dropped, cut short or ends in an error', async () => { h.scan = scanRow({ modelUsed: OPUS }); const start = { type: 'message_start', @@ -203,8 +335,8 @@ describe('metering (I7)', () => { h.fetch.mockResolvedValueOnce(sse([start, text])); await (await call('/v1/messages', opusBody({ stream: true }))).body!.cancel(); expect(h.settles).toHaveLength(3); - for (const [index, settled] of h.settles.entries()) { - expect(settled.actualNano).toBe(h.holds[index].worstNano); + for (const settled of h.settles) { + expect(settled.actualNano).toBeNull(); } const done = { type: 'message_delta', delta: {}, usage: { output_tokens: 450 } }; @@ -251,6 +383,11 @@ describe('third-party calls through AI Gateway REST (I3)', () => { 'cf-aig-skip-cache': 'true', }); expect(body).toEqual({ model: 'claude-opus-5.5', max_tokens: 4096, messages: [] }); + const bytes = new TextEncoder().encode(JSON.stringify(body)).byteLength; + expect(h.holds[0]).toMatchObject({ + estimateNano: securityModelCostNanoUsd(OPUS, Math.ceil((bytes * 2) / 5) * 2, 4096), + worstNano: securityModelCostNanoUsd(OPUS, bytes * 2, 4096), + }); // An upstream 401 (a token problem) is never passed on to the engine. h.fetch.mockResolvedValue(new Response('{"error":"nope"}', { status: 401 })); @@ -368,7 +505,7 @@ describe('refusals and caps before a call is sent', () => { it('stops the scan at the call, token and session caps', async () => { const cases: Array<[SecurityModelScan, string]> = [ [scanRow({ modelCalls: 80 }), 'scan_calls'], - [scanRow({ tokensIn: 1_200_000 }), 'tokens'], + [scanRow({ tokensIn: 10_000_000 }), 'tokens'], [scanRow({ tokensOut: 120_000 }), 'tokens'], ]; for (const [scan, reason] of cases) {