diff --git a/cloud/apps/sandbox-control/src/lifecycle.ts b/cloud/apps/sandbox-control/src/lifecycle.ts index 963c7c2ac08..38d58858695 100644 --- a/cloud/apps/sandbox-control/src/lifecycle.ts +++ b/cloud/apps/sandbox-control/src/lifecycle.ts @@ -819,8 +819,23 @@ export async function rewriteLivePolicy(deps: LifecycleDeps, row: SandboxRow, se */ export async function compileSandboxPolicy( deps: LifecycleDeps, - row: SandboxRow + row: SandboxRow, + options: { tokenFree?: boolean } = {} ): Promise<{ policy: ReturnType; gitExpiresAt: number | null }> { + if (options.tokenFree) { + // A4: what a stopped sandbox's record keeps. The same routes, but nothing the firewall itself would swap: + // every firewall value answered by the firewall (respond), no App token. Proxy routes hold no values anyway. + const [members, firewall] = await Promise.all([memberPlaceholdersFor(deps, row), firewallInputsFor(deps, row)]) + const scrubbed: FirewallInputs | null = firewall + ? { + ...firewall, + classes: new Set([...firewall.classes].filter((name) => name !== 'github_app')), + accounts: firewall.accounts.map((account) => ({ ...account, authorization: null, accountId: null })), + secrets: new Map([...firewall.secrets.keys()].map((name) => [name, null])) + } + : null + return { policy: egressPolicy(deps, row, undefined, members, scrubbed), gitExpiresAt: null } + } const [members, firewall, minted] = await Promise.all([ memberPlaceholdersFor(deps, row), firewallInputsFor(deps, row), @@ -829,6 +844,23 @@ export async function compileSandboxPolicy( return { policy: egressPolicy(deps, row, minted?.token, members, firewall), gitExpiresAt: minted?.expiresAt ?? null } } +/** + * A4 primitive (probe 2: the last session policy survives a stop and is re-applied on resume): write the + * token-free compile to the stopped sandbox's persistent record. Returns the provider's outcome. + */ +export async function scrubRecordPolicy(deps: LifecycleDeps, row: SandboxRow): Promise<'scrubbed' | 'unsupported' | { failed: string }> { + if (!deps.provider.updateRecordNetworkPolicy) { + return 'unsupported' + } + try { + const { policy } = await compileSandboxPolicy(deps, row, { tokenFree: true }) + await deps.provider.updateRecordNetworkPolicy(row.provider_name, policy) + return 'scrubbed' + } catch (error) { + return { failed: error instanceof ProviderError ? (error.code ?? `status_${error.status}`) : error instanceof Error ? error.name : 'unknown' } + } +} + /** * Policy writes that take access away (design ยง7.1). A narrowing write that still fails after its retries * stops the session rather than leave a real credential live in the firewall; any other failure only marks diff --git a/cloud/apps/sandbox-control/src/operator.ts b/cloud/apps/sandbox-control/src/operator.ts index 172aaad03f4..b1a6d298fb2 100644 --- a/cloud/apps/sandbox-control/src/operator.ts +++ b/cloud/apps/sandbox-control/src/operator.ts @@ -18,7 +18,7 @@ import { readBearer } from './auth' import type { GitHubAppMinter } from './github-app' import { bindInstallation, revokeInstallation, timingSafeEqual } from './github-connect' import { countAllActive, getControlState, killSwitchOn, setKillSwitch } from './guardrails' -import { applySandboxPolicy, egressSwapModeFor, guardrails, type LifecycleDeps } from './lifecycle' +import { applySandboxPolicy, egressSwapModeFor, guardrails, scrubRecordPolicy, type LifecycleDeps } from './lifecycle' import { drainAll, housekeeping } from './retention' import { memberChangeTime, recordMemberChange } from './member-changes' import { memberEventActor, memberEventTarget, removeMember } from './member-removal' @@ -91,6 +91,33 @@ export async function handleOperator( console.log(JSON.stringify({ event: 'egress_mode_set', sandboxId: row.id, mode: body.data.mode, applied: applied?.applied ?? false })) return Response.json({ sandboxId: row.id, mode: egressSwapModeFor(life, next), applied: applied?.applied ?? false }) } + // Dev only (probe 2, egress-docs): redacted facts about what Vercel holds for one sandbox, read with the + // Worker's own token. Never a value or a body; anywhere but dev, these routes don't exist. + const policyAudit = /^\/v1\/internal\/sandboxes\/([A-Za-z0-9_]+)\/(provider-policy-audit|provider-policy-scrub-test)$/.exec(path) + if (policyAudit && life.config.environment === 'dev') { + const row = await getSandbox(life.db, policyAudit[1]!) + if (!row) { + return Response.json({ error: 'not_found' }, { status: 404 }) + } + if (policyAudit[2] === 'provider-policy-scrub-test' && request.method === 'POST') { + const outcome = await scrubRecordPolicy(life, row) + console.log(JSON.stringify({ event: 'provider_policy_scrub_test', sandboxId: row.id, outcome: typeof outcome === 'string' ? outcome : 'failed' })) + return Response.json({ sandboxId: row.id, outcome }) + } + if (policyAudit[2] === 'provider-policy-audit' && request.method === 'GET') { + const marker = new URL(request.url).searchParams.get('marker') ?? '' + if (marker.length < 12 || !marker.startsWith('orcaprobebogus')) { + return Response.json({ error: 'invalid_marker' }, { status: 400 }) + } + if (!life.provider.readRawForAudit) { + return Response.json({ error: 'unsupported' }, { status: 501 }) + } + const raw = await life.provider.readRawForAudit(row.provider_name) + const facts = { state: raw.state, sessionStatus: raw.sessionStatus, record: policyFacts(raw.record, marker), session: raw.session === null ? null : policyFacts(raw.session, marker) } + console.log(JSON.stringify({ event: 'provider_policy_audit', sandboxId: row.id, markerFound: facts.record.markerFound || Boolean(facts.session?.markerFound) })) + return Response.json(facts) + } + } switch (route) { case 'GET /v1/internal/status': return Response.json({ @@ -222,3 +249,42 @@ export async function handleOperator( } const EgressModeBody = z.object({ mode: z.enum(['proxy', 'firewall']).nullable() }) + +/** Redacted facts about a raw provider body: rule counts and header NAMES only, plus a marker substring test. */ +export function policyFacts(body: string, marker: string): { hasNetworkPolicy: boolean; transformRuleCount: number; headerNames: string[]; markerFound: boolean } { + let parsed: unknown = null + try { + parsed = JSON.parse(body) + } catch { + // Facts from the substring test only. + } + let hasNetworkPolicy = false + let transformRuleCount = 0 + const headerNames = new Set() + const walk = (value: unknown, key: string): void => { + if (Array.isArray(value)) { + if (/transform/i.test(key)) { + transformRuleCount += value.length + } + value.forEach((item) => walk(item, key)) + return + } + if (value && typeof value === 'object') { + for (const [name, child] of Object.entries(value)) { + if (/^networkpolicy$/i.test(name)) { + hasNetworkPolicy = true + } + if (/^headerNames$/i.test(name) && Array.isArray(child)) { + for (const header of child) { + if (typeof header === 'string' && /^[A-Za-z0-9-]{1,64}$/.test(header)) { + headerNames.add(header.toLowerCase()) + } + } + } + walk(child, name) + } + } + } + walk(parsed, '') + return { hasNetworkPolicy, transformRuleCount, headerNames: [...headerNames].sort(), markerFound: body.includes(marker) } +} diff --git a/cloud/apps/sandbox-control/src/sandbox-provider.ts b/cloud/apps/sandbox-control/src/sandbox-provider.ts index 8eba9363a31..8645e5dcffc 100644 --- a/cloud/apps/sandbox-control/src/sandbox-provider.ts +++ b/cloud/apps/sandbox-control/src/sandbox-provider.ts @@ -106,6 +106,13 @@ export type SandboxProviderApi = { updateNetworkPolicy(sessionId: string, policy: NetworkPolicy): Promise /** Sets the full exposed-port list on the sandbox (live on a running session); returns its routes. */ updatePorts(name: string, ports: number[]): Promise + /** + * The persistent record's network policy (A4, probe 2: the last session policy otherwise survives a stop + * or timeout and is re-applied on resume). Allowed while stopped, unlike updateNetworkPolicy. + */ + updateRecordNetworkPolicy?(name: string, policy: NetworkPolicy): Promise + /** Dev audit only (provider-policy-audit): the raw record and session bodies. Never returned or logged. */ + readRawForAudit?(name: string): Promise<{ record: string; session: string | null; state: string | null; sessionStatus: string | null }> runCommand(sessionId: string, params: RunCommandParams): Promise /** Provider-side snapshot expiry after last use (archive TTL backstop). */ updateSnapshotExpiration(name: string, expirationMs: number): Promise diff --git a/cloud/apps/sandbox-control/src/vercel-sandbox-api.ts b/cloud/apps/sandbox-control/src/vercel-sandbox-api.ts index 3eee9bdbc1b..5dbc1c48b7c 100644 --- a/cloud/apps/sandbox-control/src/vercel-sandbox-api.ts +++ b/cloud/apps/sandbox-control/src/vercel-sandbox-api.ts @@ -258,6 +258,31 @@ export function createVercelSandboxApi( }) }, + async updateRecordNetworkPolicy(name, policy: NetworkPolicy) { + await request('PATCH', `/v2/sandboxes/${encodeURIComponent(name)}`, { + query: { projectId: config.projectId }, + body: { networkPolicy: policy } + }) + }, + + async readRawForAudit(name) { + const recordResponse = await request('GET', `/v2/sandboxes/${encodeURIComponent(name)}`, { + query: { projectId: config.projectId, resume: 'false' } + }) + const record = await recordResponse.text() + let parsed: { sandbox?: { status?: string }; session?: { id?: string; status?: string } } = {} + try { + parsed = JSON.parse(record) as typeof parsed + } catch { + // An unreadable body still gets its substring test. + } + const sessionId = parsed.session?.id + const session = sessionId + ? await (await request('GET', `/v2/sandboxes/sessions/${encodeURIComponent(sessionId)}`)).text() + : null + return { record, session, state: parsed.sandbox?.status ?? null, sessionStatus: parsed.session?.status ?? null } + }, + async updatePorts(name, ports) { // PATCH treats `ports` as the full list; a running session gets the new routes immediately // (measured live: ~260 ms, route answers at once). diff --git a/cloud/apps/sandbox-control/test/fake-vercel.ts b/cloud/apps/sandbox-control/test/fake-vercel.ts index 0416c2aa987..1a9d242373f 100644 --- a/cloud/apps/sandbox-control/test/fake-vercel.ts +++ b/cloud/apps/sandbox-control/test/fake-vercel.ts @@ -26,6 +26,8 @@ type FakeBox = { /** Extra exposed ports beyond orcad's (updatePorts / create params). */ ports: number[] policy: NetworkPolicy + /** The persistent record's policy once PATCHed (A4); the create's otherwise. */ + recordPolicy?: NetworkPolicy /** orcad's recipe line for the current boot, once the start command ran. */ orcadReady?: string /** Files in the VM, as the files API would read them. */ @@ -262,6 +264,25 @@ export function createFakeVercel(now: () => number): FakeVercel { async updateNetworkPolicy(sessionId, policy) { bySession(sessionId).policy = policy }, + async updateRecordNetworkPolicy(name, policy) { + const box = boxes.get(name) + if (!box) { + throw new ProviderError(404, 'not_found') + } + box.recordPolicy = policy + }, + async readRawForAudit(name) { + const box = boxes.get(name) + if (!box) { + throw new ProviderError(404, 'not_found') + } + return { + record: JSON.stringify({ sandbox: { status: box.status, networkPolicy: box.recordPolicy ?? box.params.networkPolicy } }), + session: JSON.stringify({ session: { status: box.status, networkPolicy: box.policy } }), + state: box.status, + sessionStatus: box.status + } + }, async updatePorts(name, ports) { const box = boxes.get(name) if (!box) { diff --git a/cloud/apps/sandbox-control/test/provider-policy-audit.test.ts b/cloud/apps/sandbox-control/test/provider-policy-audit.test.ts new file mode 100644 index 00000000000..5cad17477a4 --- /dev/null +++ b/cloud/apps/sandbox-control/test/provider-policy-audit.test.ts @@ -0,0 +1,60 @@ +// Dev-only redacted provider-policy audit and the A4 scrub primitive (egress-docs probe 2). +import { describe, expect, it } from 'vitest' +import { policyFacts } from '../src/operator' +import { createHarness } from './harness' + +const OP = 'o'.repeat(40) +const MARKER = 'orcaprobebogus-0123456789' + +async function setup(env: Record) { + const h = await createHarness({ + SECRETS_KEK: Buffer.alloc(32, 7).toString('base64'), + EGRESS_PROXY_URL: 'https://sandbox.test/v1/egress/proxy', + SECRETS_EGRESS_PLACEHOLDERS: 'on', + OPERATOR_TOKEN: OP, + EGRESS_SWAP_MODE: 'firewall', + ...env + }) + const mia = await h.token('mia', 'acme', 'sandbox', {}) + await h.call('PUT', '/v1/secrets/personal/ANTHROPIC_API_KEY', { body: { value: `sk-ant-api03-${MARKER}` }, bearer: mia }) + const created = await h.call('POST', '/v1/sandboxes', { bearer: mia, body: { workspaceId: 'ws-1', machineSize: 'standard' } }) + const id: string = created.body.sandbox.id + const box = () => [...h.vercel.boxes.values()].find((b) => b.params.tags.orcaSandbox === id)! + return { h, id, box } +} + +describe('provider-policy-audit (dev only)', () => { + it('answers redacted facts: the marker is found, but no value or body comes back', async () => { + const { h, id } = await setup({ SANDBOX_ENV: 'dev' }) + const res = await h.call('GET', `/v1/internal/sandboxes/${id}/provider-policy-audit?marker=${MARKER}`, { bearer: OP }) + expect(res.status).toBe(200) + expect(res.body.session.markerFound).toBe(true) + expect(res.body.session.hasNetworkPolicy).toBe(true) + expect(JSON.stringify(res.body)).not.toContain(MARKER) + expect(JSON.stringify(res.body)).not.toContain('sk-ant') + }) + + it('refuses a short or foreign marker, and does not exist outside dev', async () => { + const dev = await setup({ SANDBOX_ENV: 'dev' }) + expect((await dev.h.call('GET', `/v1/internal/sandboxes/${dev.id}/provider-policy-audit?marker=sk-ant`, { bearer: OP })).status).toBe(400) + const prod = await setup({ SANDBOX_ENV: 'prod' }) + expect((await prod.h.call('GET', `/v1/internal/sandboxes/${prod.id}/provider-policy-audit?marker=${MARKER}`, { bearer: OP })).status).toBe(404) + }) + + it('scrub-test writes the token-free compile to the record: routes kept, no value', async () => { + const { h, id, box } = await setup({ SANDBOX_ENV: 'dev' }) + expect(JSON.stringify(box().policy)).toContain(MARKER) + const res = await h.call('POST', `/v1/internal/sandboxes/${id}/provider-policy-scrub-test`, { bearer: OP }) + expect(res.body.outcome).toBe('scrubbed') + const record = JSON.stringify(box().recordPolicy) + expect(record).not.toContain(MARKER) + expect(record).toContain('api.anthropic.com') + }) +}) + +describe('policyFacts', () => { + it('counts transform rules and keeps header names only', () => { + const body = JSON.stringify({ session: { networkPolicy: { transformRules: [{ domain: 'a.com', headerNames: ['Authorization', 'x-api-key'] }, { domain: 'b.com', headerNames: ['bad header'] }] } } }) + expect(policyFacts(body, MARKER)).toEqual({ hasNetworkPolicy: true, transformRuleCount: 2, headerNames: ['authorization', 'x-api-key'], markerFound: false }) + }) +})