From dd7d5608addb40705105fb84925f38552c451a00 Mon Sep 17 00:00:00 2001 From: Jacob Prall Date: Thu, 3 Dec 2026 09:30:15 -0800 Subject: [PATCH] Add Sandbox credential brokering Co-authored-by: Cursor --- AGENTS.md | 7 +- README.md | 24 ++++--- app/agent-runs/run.ts | 7 +- app/harness/index.ts | 2 +- app/harness/pi.ts | 30 +++++++- app/harness/types.ts | 12 ++++ app/runner/main.ts | 23 ++----- app/sandbox/client.ts | 34 +++++++-- app/sandbox/credentials.ts | 30 ++++++++ app/sandbox/egress.ts | 2 +- app/sandbox/groups.ts | 33 +++++++++ app/sandbox/index.ts | 1 + app/sandbox/sandbox.ts | 54 +++++++-------- app/sandbox/snapshot.ts | 37 ++++------ app/sandbox/types.ts | 14 ++++ docs/architecture.md | 54 +++++++++------ docs/configuration.md | 45 +++++++++--- docs/quickstart.md | 6 +- docs/runbooks/extend.md | 9 ++- docs/runbooks/setup.md | 16 +++-- package-lock.json | 10 +-- package.json | 2 +- sandbox/build/git-credential-staged.sh | 17 ----- sandbox/build/scrub-credentials.sh | 43 ------------ sandbox/run-agent.sh | 21 +----- sandbox/verify.sh | 2 +- tests/agents-catalog.test.ts | 10 ++- tests/agents.test.ts | 13 +++- tests/harness-pi.test.ts | 32 +++++++++ tests/helpers/fake-sandbox.ts | 21 +++++- tests/helpers/pi-scripted.ts | 15 +++- tests/helpers/runner.ts | 8 +-- tests/publish.test.ts | 1 + tests/runner.test.ts | 20 ++---- tests/sandbox-render.test.ts | 95 +++++++++++++++++++++----- tests/sandbox-scripts.test.ts | 87 +++-------------------- 36 files changed, 494 insertions(+), 343 deletions(-) create mode 100644 app/sandbox/credentials.ts create mode 100644 app/sandbox/groups.ts delete mode 100755 sandbox/build/git-credential-staged.sh delete mode 100755 sandbox/build/scrub-credentials.sh diff --git a/AGENTS.md b/AGENTS.md index bd1b4c9..cc5b270 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -116,9 +116,10 @@ strict output schemas. - App permission, event, or label: update `scripts/lib/requirements.ts`, setup behavior, and doctor tests. - Agent harness: declare the env var of its key as the adapter's - `credential` and the hosts it calls as its `egress`; setup and `doctor` - derive the key list, and Sandbox allow-lists include every harness's - hosts. It must give the model only the factory's tools; add it to `HARNESSES` in + `credential`, its exact non-overlapping `credentialBroker` route, and the + hosts it calls as its `egress`; setup and `doctor` derive the key list, and + Sandbox allow-lists include every harness's hosts. It must give the model + only the factory's tools; add it to `HARNESSES` in `tests/helpers/runner.ts` if it can run the conformance suite. - Database migration: keep `app/db/migrations/` additive, because one service can run old code while the other migrates. Derive projections in diff --git a/README.md b/README.md index a886b37..b850549 100644 --- a/README.md +++ b/README.md @@ -87,8 +87,10 @@ can start a run. Credentials stay out of reach of the agents: -- GitHub write credentials never enter a Sandbox. Clone and fetch credentials - are read-only and removed before repository code or agents run. +- GitHub write credentials never enter a Sandbox. Render brokers read-only + clone and fetch credentials only to the configured repository path. +- Render brokers the model key only to the selected provider endpoint; the + key never enters Sandbox files, environment variables, stdin, or memory. - Sandboxes reach only an HTTPS allow-list: GitHub and the agents' model APIs. Add anything your repository's install and verify commands need. - Nothing in a Sandbox holds a database credential. The Workflows host records @@ -99,10 +101,12 @@ Credentials stay out of reach of the agents: submodules, oversized changes, and branches with human commits, and GitHub must reproduce the candidate tree SHA before the factory publishes it. -Allowed hosts can still carry data out, and the model key exists in runner -memory during a call. Read the [trust boundaries](docs/architecture.md#trust-boundaries) -and [residual risks](docs/architecture.md#residual-risks) before using private -code or untrusted pull requests. +Allowed hosts can still carry data out, and any Sandbox process can exercise +a credential by making a request that matches its broker route even though it +cannot read the value. Read the +[trust boundaries](docs/architecture.md#trust-boundaries) and +[residual risks](docs/architecture.md#residual-risks) before using private code +or untrusted pull requests. ## Deploy @@ -121,9 +125,9 @@ service), and `factory-db` (a Basic-256mb Postgres database). Sandbox and model usage are billed separately. Setup is agent-guided. Prepare a fork of this repository, a Render workspace -with Sandboxes access, a Render API key, an Anthropic API key with a spend -limit, and admin access to each target repository. Then open your fork in a -coding agent: +with Sandboxes and Sandbox credential brokering access, a Render API key owned +by a workspace admin, an Anthropic API key with a spend limit, and admin +access to each target repository. Then open your fork in a coding agent: ```text Set up software-factory by following docs/runbooks/setup.md. @@ -152,7 +156,7 @@ Configure each repository in [`factory.config.ts`](factory.config.ts): | --- | --- | --- | | `baseBranch` | Yes | Branch used for Triage, implementation, and snapshots | | `verify` | Yes | Commands that must pass before publishing, and that PR Reviewer runs | -| `install` | No | Dependency command, run after clone credentials are removed | +| `install` | No | Dependency command, run after the repository is cloned | | `egress` | No | Extra HTTPS hosts the repository's Sandboxes may reach, or `"allow-all"` | Labels, `minimumPermission`, and limits are set in the same file, with their diff --git a/app/agent-runs/run.ts b/app/agent-runs/run.ts index 7410f93..cbe0089 100644 --- a/app/agent-runs/run.ts +++ b/app/agent-runs/run.ts @@ -3,7 +3,7 @@ import type { z } from "zod"; import type { Agent, OutputSchema } from "../agents/index.js"; import { type Db, workflowsDb } from "../db/index.js"; import { PROTOCOL_VERSION, type RunnerErrorCode, RunnerEvent, type RunnerInput, type ToolName, type Usage } from "../runner/index.js"; -import { APP_DIR, type ExecStreamOptions, REPO_DIR, type Sandbox, SCRATCH_DIR } from "../sandbox/index.js"; +import { APP_DIR, type ExecStreamOptions, modelCredential, REPO_DIR, type Sandbox, SCRATCH_DIR } from "../sandbox/index.js"; import type { ThreadKey } from "../threads/index.js"; import { errorMessage } from "../util/index.js"; import { AgentRunRecorder } from "./recorder.js"; @@ -86,12 +86,13 @@ export async function runAgent { const event = parseLine(line); if (event) recorder.onRunnerEvent(event); }); - const stdout = await runInSandbox(sandbox, runnerInput, apiKey, timeoutMs, relay, base.signal); + const stdout = await runInSandbox(sandbox, runnerInput, timeoutMs, relay, base.signal); const { events, invalidLines } = parseEvents(stdout.text); summary = summarize(events, invalidLines); const end = summary.terminal; @@ -121,7 +122,6 @@ interface RunnerOutput { async function runInSandbox( sandbox: Sandbox, input: RunnerInput, - apiKey: string, timeoutMs: number, relay: LineRelay, signal?: AbortSignal, @@ -131,7 +131,6 @@ async function runInSandbox( if (mkdir.exitCode !== 0) return { text: "", detail: `mkdir ${runDir} exited ${mkdir.exitCode}: ${tail(mkdir.stderr)}` }; try { await sandbox.upload(`${runDir}/input.json`, JSON.stringify(input)); - await sandbox.upload(`${runDir}/key`, apiKey); const details: string[] = []; const deadline = Date.now() + timeoutMs + EXEC_GRACE_MS; let stderr = ""; diff --git a/app/harness/index.ts b/app/harness/index.ts index 9097391..1f69fc0 100644 --- a/app/harness/index.ts +++ b/app/harness/index.ts @@ -1,4 +1,4 @@ export type { Driver, DriverContext, DriverSession, HarnessRun, HarnessRuntime, Report, SubmitTool } from "../runner/index.js"; export { InvalidInput } from "../runner/index.js"; export { type PiOptions, pi, type ThinkingLevel } from "./pi.js"; -export type { Harness } from "./types.js"; +export type { CredentialBrokerRoute, Harness } from "./types.js"; diff --git a/app/harness/pi.ts b/app/harness/pi.ts index 6e31b62..3398c7b 100644 --- a/app/harness/pi.ts +++ b/app/harness/pi.ts @@ -1,6 +1,6 @@ import type { Api, Model, MutableModels } from "@earendil-works/pi-ai"; import { piDriver, type ThinkingLevel } from "../runner/index.js"; -import type { Harness } from "./types.js"; +import type { CredentialBrokerRoute, Harness } from "./types.js"; export type { ThinkingLevel }; @@ -15,6 +15,7 @@ export interface PiOptions { thinkingLevel?: ThinkingLevel; models?: () => MutableModels; credential?: string; + credentialBroker?: CredentialBrokerRoute; egress?: string[]; } @@ -24,12 +25,37 @@ export function pi(opts: PiOptions): Harness { if (!credential) { throw new Error(`pi: no default key for provider "${provider}"; pass credential, or use one of ${Object.keys(PI_PROVIDER_KEY_ENV).join(", ")}`); } + const credentialBroker = opts.credentialBroker ?? defaultCredentialBroker(opts.model); + if (!credentialBroker) throw new Error(`pi: no default credential broker route for API "${opts.model.api}"; pass credentialBroker`); + const modelHost = new URL(opts.model.baseUrl).hostname; + if (credentialBroker.domain !== modelHost) { + throw new Error(`pi: credential broker domain "${credentialBroker.domain}" does not match model host "${modelHost}"`); + } + if (!credentialBroker.methods?.length || !credentialBroker.paths?.length) { + throw new Error("pi: credentialBroker must restrict both methods and paths"); + } const thinkingLevel = opts.thinkingLevel ?? "medium"; return { name: "pi", label: `${provider}/${id}`, credential, - egress: opts.egress ?? [new URL(opts.model.baseUrl).hostname], + credentialBroker, + egress: opts.egress ?? [modelHost], driver: piDriver({ model: opts.model, thinkingLevel, models: opts.models }), }; } + +function defaultCredentialBroker(model: Model): CredentialBrokerRoute | undefined { + const url = new URL(model.baseUrl); + const route = (path: string, injection: CredentialBrokerRoute["injection"]): CredentialBrokerRoute => ({ + domain: url.hostname, + injection, + methods: ["POST"], + paths: [`${url.pathname.replace(/\/+$/, "")}${path}`], + }); + if (model.api === "anthropic-messages") return route("/v1/messages", { type: "header", name: "x-api-key" }); + if (model.api === "openai-responses") return route("/responses", { type: "header", name: "Authorization", template: `Bearer \${SECRET}` }); + if (model.api === "openai-completions") + return route("/chat/completions", { type: "header", name: "Authorization", template: `Bearer \${SECRET}` }); + if (model.api === "google-generative-ai") return route("/models/*", { type: "header", name: "x-goog-api-key" }); +} diff --git a/app/harness/types.ts b/app/harness/types.ts index 06e2df9..0066c73 100644 --- a/app/harness/types.ts +++ b/app/harness/types.ts @@ -1,7 +1,19 @@ import type { HarnessRuntime } from "../runner/index.js"; +export interface CredentialBrokerRoute { + readonly domain: string; + readonly injection: { + readonly type: "header" | "basic" | "cookie" | "query"; + readonly name?: string; + readonly template?: string; + }; + readonly methods?: readonly string[]; + readonly paths?: readonly string[]; +} + export interface Harness extends HarnessRuntime { readonly label: string; readonly credential: string; + readonly credentialBroker: CredentialBrokerRoute; readonly egress: readonly string[]; } diff --git a/app/runner/main.ts b/app/runner/main.ts index bd379a3..669c68f 100644 --- a/app/runner/main.ts +++ b/app/runner/main.ts @@ -9,6 +9,8 @@ import { executeHarness } from "./core/kernel.js"; import { scrubKeys } from "./core/keys.js"; import { PROTOCOL_VERSION, RUNNER_EXIT } from "./core/protocol.js"; +const BROKERED_MODEL_KEY = "render-credential-broker"; + interface MainIO { stdin: AsyncIterable; write(chunk: string): Promise; @@ -35,12 +37,12 @@ export async function main(argv: string[], io: MainIO = processIO()): Promise a.id === input.agent_id); if (!agent) return fail("invalid_input", `unknown agent "${input.agent_id}": the runner bundle doesn't define it`); - if (!apiKey) return fail("invalid_input", "no model key: pass it as the first line of stdin with --key-stdin"); + if (!args["brokered-key"]) return fail("invalid_input", "no brokered model key: pass --brokered-key"); try { if (input.scratch_dir) useScratch(input.scratch_dir); - return await executeHarness({ input, emit, apiKey, startedAt }, agent.harness); + return await executeHarness({ input, emit, apiKey: BROKERED_MODEL_KEY, startedAt }, agent.harness); } catch (err) { console.error(err); if (!emit.terminated) return await fail("agent_error", errorMessage(err)); diff --git a/app/sandbox/client.ts b/app/sandbox/client.ts index 310aee6..9c37914 100644 --- a/app/sandbox/client.ts +++ b/app/sandbox/client.ts @@ -1,12 +1,19 @@ import { setTimeout as sleep } from "node:timers/promises"; -import { ClientError, Render, ServerError } from "@renderinc/sdk"; -import type { SandboxesClient, SandboxUploadContentType } from "@renderinc/sdk/experimental"; +import { + ClientError, + Render, + SandboxCredentialNotFoundError, + type SandboxesClient, + type SandboxUploadContentType, + ServerError, +} from "@renderinc/sdk"; import { requireEnv } from "../config/index.js"; import { errorMessage } from "../util/index.js"; import { log } from "./shell.js"; -import type { ExecResult, ExecStreamOptions } from "./types.js"; +import type { BrokerCredential, ExecResult, ExecStreamOptions } from "./types.js"; -export type SandboxApi = Pick & { +export type SandboxApi = Pick & { + credentials: Pick; snapshots: Pick; }; @@ -116,6 +123,23 @@ export class SandboxClient { return file.data; } + async brokerCredential(sandboxGroupId: string, credential: BrokerCredential): Promise { + const { id: credentialId, ...fields } = credential; + const input = { sandboxGroupId, credentialId, ...fields }; + const update = () => this.call(() => this.api.credentials.update(input), { retryOn: TRANSIENT }); + try { + await update(); + } catch (err) { + if (!(err instanceof SandboxCredentialNotFoundError)) throw err; + try { + await this.call(() => this.api.credentials.create(input), { retryOn: TRANSIENT }); + } catch (createErr) { + if (!(createErr instanceof ClientError) || createErr.statusCode !== 409) throw createErr; + await update(); + } + } + } + async waitRunning(id: string): Promise { const until = Date.now() + this.t.bootTimeoutMs; for (;;) { @@ -148,7 +172,7 @@ export function sandboxClient(): SandboxClient { const workspaceId = requireEnv("RENDER_WORKSPACE_ID"); if (!workspaceId.startsWith("tea-")) throw new Error("RENDER_WORKSPACE_ID must be a tea-… workspace id"); const render = new Render({ useLocalDev: false, token: requireEnv("RENDER_API_KEY"), ownerId: workspaceId }); - shared = new SandboxClient(render.experimental.sandboxes); + shared = new SandboxClient(render.sandboxes); } return shared; } diff --git a/app/sandbox/credentials.ts b/app/sandbox/credentials.ts new file mode 100644 index 0000000..3811f72 --- /dev/null +++ b/app/sandbox/credentials.ts @@ -0,0 +1,30 @@ +import { createHash } from "node:crypto"; +import type { RepoContext } from "../config/index.js"; +import type { CredentialBrokerRoute } from "../harness/index.js"; +import type { BrokerCredential } from "./types.js"; + +export function githubCredential(repo: RepoContext, value: string): BrokerCredential { + return { + id: credentialId("github", repo.fullName), + domain: "github.com", + value, + injection: { type: "basic", template: `x-access-token:\${SECRET}` }, + methods: ["GET", "POST"], + paths: [`/${repo.owner}/${repo.name}.git/**`], + }; +} + +export function modelCredential(credential: string, route: CredentialBrokerRoute, value: string): BrokerCredential { + return { + id: credentialId("model", credential), + domain: route.domain, + value, + injection: { ...route.injection }, + ...(route.methods ? { methods: [...route.methods] } : {}), + ...(route.paths ? { paths: [...route.paths] } : {}), + }; +} + +function credentialId(kind: string, source: string): string { + return `factory-${kind}-${createHash("sha256").update(source).digest("hex").slice(0, 24)}`; +} diff --git a/app/sandbox/egress.ts b/app/sandbox/egress.ts index 0d02130..4d61fb8 100644 --- a/app/sandbox/egress.ts +++ b/app/sandbox/egress.ts @@ -1,4 +1,4 @@ -import type { SandboxNetworkPolicy } from "@renderinc/sdk/experimental"; +import type { SandboxNetworkPolicy } from "@renderinc/sdk"; import { AGENTS } from "../agents/index.js"; import { assertEgressHosts, type RepoContext } from "../config/index.js"; diff --git a/app/sandbox/groups.ts b/app/sandbox/groups.ts new file mode 100644 index 0000000..3de478e --- /dev/null +++ b/app/sandbox/groups.ts @@ -0,0 +1,33 @@ +import { createHash } from "node:crypto"; +import { ClientError } from "@renderinc/sdk"; +import type { RepoContext } from "../config/index.js"; +import { type SandboxClient, TRANSIENT } from "./client.js"; + +function sandboxGroupName(repo: Pick): string { + const suffix = createHash("sha256").update(repo.fullName).digest("hex").slice(0, 24); + return `factory-${repo.owner}-${repo.name}-${suffix}`.replace(/[^A-Za-z0-9_.-]/g, "-"); +} + +export async function ensureSandboxGroup(client: SandboxClient, repo: RepoContext): Promise { + const name = sandboxGroupName(repo); + const existing = await findSandboxGroup(client, name); + if (existing) return existing; + try { + return (await client.call(() => client.api.createGroup({ name }), { retryOn: TRANSIENT })).id; + } catch (err) { + if (!(err instanceof ClientError) || err.statusCode !== 409) throw err; + const raced = await findSandboxGroup(client, name); + if (raced) return raced; + throw err; + } +} + +async function findSandboxGroup(client: SandboxClient, name: string): Promise { + for (let cursor: string | undefined; ; ) { + const page = await client.call(() => client.api.listGroups({ cursor, limit: 100 }), { retryOn: TRANSIENT }); + const match = page.find(({ sandboxGroup }) => sandboxGroup.name === name); + if (match) return match.sandboxGroup.id; + cursor = page.at(-1)?.cursor; + if (page.length < 100 || !cursor) return undefined; + } +} diff --git a/app/sandbox/index.ts b/app/sandbox/index.ts index 008d5bf..af9a2af 100644 --- a/app/sandbox/index.ts +++ b/app/sandbox/index.ts @@ -1,4 +1,5 @@ export { type SandboxApi, SandboxClient, type SandboxTimings, sandboxClient } from "./client.js"; +export { modelCredential } from "./credentials.js"; export { type OpenSandboxDeps, openSandbox, withSandbox } from "./sandbox.js"; export { SAFE_REF, shq } from "./shell.js"; export { type BuiltSnapshot, buildSnapshot, type SnapshotDeps } from "./snapshot.js"; diff --git a/app/sandbox/sandbox.ts b/app/sandbox/sandbox.ts index 536b16e..f01c9dc 100644 --- a/app/sandbox/sandbox.ts +++ b/app/sandbox/sandbox.ts @@ -1,19 +1,17 @@ -import { randomUUID } from "node:crypto"; -import { SandboxSnapshotNotFoundError, SandboxSnapshotNotReadyError } from "@renderinc/sdk"; -import type { SandboxNetworkPolicy } from "@renderinc/sdk/experimental"; +import { type SandboxNetworkPolicy, SandboxSnapshotNotFoundError, SandboxSnapshotNotReadyError } from "@renderinc/sdk"; import { z } from "zod"; import { config, type RepoContext } from "../config/index.js"; import { errorMessage, SHA } from "../util/index.js"; import { type SandboxClient, sandboxClient } from "./client.js"; +import { githubCredential } from "./credentials.js"; import { egressHint, taskEgress } from "./egress.js"; +import { ensureSandboxGroup } from "./groups.js"; import { log, SAFE_REF } from "./shell.js"; import { asRunner, type BuiltSnapshot, buildSnapshot, computeLockfileHash, - credentialFile, - credentialHelperArgs, ensureRunnerPayload, readToken, resolveBaseHead, @@ -21,7 +19,7 @@ import { type SnapshotDeps, snapshotName, } from "./snapshot.js"; -import { APP_DIR, type OpenedSandbox, REPO_DIR, RUN_AS, type Sandbox, type SandboxRef, SCRATCH_DIR, type SnapshotManifest } from "./types.js"; +import { APP_DIR, type OpenedSandbox, type Sandbox, type SandboxRef, type SnapshotManifest } from "./types.js"; import { verifySandbox } from "./verify.js"; const SnapshotManifestSchema = z.object({ @@ -33,10 +31,13 @@ const SnapshotManifestSchema = z.object({ createdAt: z.string(), }) satisfies z.ZodType; -function connectSandbox(id: string, client?: SandboxClient): Sandbox { +function connectSandbox(id: string, sandboxGroupId: string, client?: SandboxClient): Sandbox { const get = () => client ?? sandboxClient(); return { id, + async brokerCredential(credential) { + await get().brokerCredential(sandboxGroupId, credential); + }, async exec(command, opts = {}) { const c = get(); const wrapped = opts.asRunner ? asRunner("bash", "-c", command) : command; @@ -68,7 +69,10 @@ export async function openSandbox(repo: RepoContext, ref: SandboxRef, deps: Open checkRef(ref); const client = deps.client ?? sandboxClient(); const egress = taskEgress(repo); - const id = await createFromSnapshot(client, repo, egress, deps); + const sandboxGroupId = await ensureSandboxGroup(client, repo); + const token = await (deps.readToken ?? readToken)(repo); + await client.brokerCredential(sandboxGroupId, githubCredential(repo, token)); + const id = await createFromSnapshot(client, repo, sandboxGroupId, egress, deps); try { await client.waitRunning(id); await ensureRunnerPayload(client, id); @@ -77,7 +81,7 @@ export async function openSandbox(repo: RepoContext, ref: SandboxRef, deps: Open const manifest = SnapshotManifestSchema.parse(JSON.parse((await client.download(id, `${APP_DIR}/manifest.json`)).toString("utf8"))); if (manifest.repo !== repo.fullName) throw new Error(`snapshot in ${id} is for ${manifest.repo}, not ${repo.fullName}`); - const headSha = await fetchRef(client, id, repo, ref, deps); + const headSha = await fetchRef(client, id, repo, ref); const install = repo.config.install?.trim() || null; if (install) { const lockfileHash = await computeLockfileHash(client, id); @@ -86,7 +90,7 @@ export async function openSandbox(repo: RepoContext, ref: SandboxRef, deps: Open await runInstall(client, id, install, egressHint(repo, egress)); } } - return { ...connectSandbox(id, client), headSha, manifest }; + return { ...connectSandbox(id, sandboxGroupId, client), headSha, manifest }; } catch (err) { await client.terminateQuietly(id); throw err; @@ -117,12 +121,19 @@ function isSnapshotUnavailable(err: unknown): boolean { return err instanceof SandboxSnapshotNotFoundError || err instanceof SandboxSnapshotNotReadyError; } -async function createFromSnapshot(client: SandboxClient, repo: RepoContext, egress: SandboxNetworkPolicy, deps: OpenSandboxDeps): Promise { +async function createFromSnapshot( + client: SandboxClient, + repo: RepoContext, + sandboxGroupId: string, + egress: SandboxNetworkPolicy, + deps: OpenSandboxDeps, +): Promise { const name = snapshotName(repo); const create = async () => ( await client.call(() => client.api.create({ + sandboxGroupId, snapshotName: name, networkPolicy: egress, timeoutSeconds: config.sandbox.timeoutSeconds, @@ -147,27 +158,14 @@ async function createFromSnapshot(client: SandboxClient, repo: RepoContext, egre } } -async function fetchRef(client: SandboxClient, id: string, repo: RepoContext, ref: SandboxRef, deps: SnapshotDeps): Promise { - const dir = `/tmp/factory-fetch-${randomUUID()}`; +async function fetchRef(client: SandboxClient, id: string, repo: RepoContext, ref: SandboxRef): Promise { const quick = { timeoutMs: client.t.verifyTimeoutMs }; const source = ref.kind === "branch" ? `refs/heads/${ref.name}` : `refs/pull/${ref.number}/head`; const refspecs = [source]; if (ref.kind === "pull" && ref.baseBranch) refspecs.push(`+refs/heads/${ref.baseBranch}:refs/remotes/origin/${ref.baseBranch}`); - await client.check(id, `mkdir -m 700 ${dir}`, quick); - let fetchError: unknown; - try { - const token = await (deps.readToken ?? readToken)(repo); - await client.upload(id, `${dir}/github.com`, credentialFile(token)); - await client.check(id, `chown -R ${RUN_AS}: ${dir} && chmod 600 ${dir}/github.com`, quick); - await client.check(id, asRunner("git", ...credentialHelperArgs(dir), "fetch", "--quiet", "--no-tags", "origin", ...refspecs), { - timeoutMs: client.t.prepareTimeoutMs, - }); - } catch (err) { - fetchError = err; - } - const scrub = await client.exec(id, `bash ${APP_DIR}/build/scrub-credentials.sh ${dir} ${REPO_DIR} ${SCRATCH_DIR}/home`, quick); - if (scrub.exitCode !== 0) throw new Error(`credential scrub failed: ${(scrub.stderr || scrub.stdout).trim().slice(-2000)}`); - if (fetchError) throw fetchError; + await client.check(id, asRunner("git", "fetch", "--quiet", "--no-tags", "origin", ...refspecs), { + timeoutMs: client.t.prepareTimeoutMs, + }); const fetched = (await client.check(id, asRunner("git", "rev-parse", "FETCH_HEAD^{commit}"), quick)).trim(); if (!SHA.test(fetched)) throw new Error(`fetching ${source} gave ${JSON.stringify(fetched.slice(0, 100))}`); diff --git a/app/sandbox/snapshot.ts b/app/sandbox/snapshot.ts index 102d238..1cf51dd 100644 --- a/app/sandbox/snapshot.ts +++ b/app/sandbox/snapshot.ts @@ -5,15 +5,16 @@ import { tmpdir } from "node:os"; import { dirname, join } from "node:path"; import { setTimeout as sleep } from "node:timers/promises"; import { fileURLToPath } from "node:url"; -import { ClientError, SandboxSnapshotNotFoundError } from "@renderinc/sdk"; -import type { SandboxSnapshot } from "@renderinc/sdk/experimental"; +import { ClientError, type SandboxSnapshot, SandboxSnapshotNotFoundError } from "@renderinc/sdk"; import { create as createTar } from "tar"; import type { RepoContext } from "../config/index.js"; import { githubToken } from "../github/index.js"; import { bundleRunner } from "../runner-bundle/index.js"; import { errorMessage, SHA } from "../util/index.js"; import { type SandboxApi, type SandboxClient, TRANSIENT } from "./client.js"; +import { githubCredential } from "./credentials.js"; import { builderEgress, egressHint } from "./egress.js"; +import { ensureSandboxGroup } from "./groups.js"; import { log, SAFE_REF, shq } from "./shell.js"; import { APP_DIR, REPO_DIR, RUN_AS, SANDBOX_ROOT, SCRATCH_DIR, type SnapshotManifest } from "./types.js"; import { verifySandbox } from "./verify.js"; @@ -33,12 +34,9 @@ const RUNTIME_SCRIPTS = [ "collect-changes.sh", "lockfile-hash.sh", "verify.sh", - "build/git-credential-staged.sh", - "build/scrub-credentials.sh", ] as const; const STAGING_DIR = "/tmp/factory-stage"; -const STAGING_CREDS = `${STAGING_DIR}/creds`; const SANDBOX_GITCONFIG = "[core]\n\tfsmonitor = false\n[advice]\n\tdetachedHead = false\n"; const GITHUB_TOKEN_USER = "x-access-token"; @@ -61,14 +59,6 @@ export function asRunner(...argv: string[]): string { return `bash ${APP_DIR}/as-runner.sh ${argv.map(shq).join(" ")}`; } -export function credentialHelperArgs(credsDir: string): string[] { - return ["-c", "credential.helper=", "-c", `credential.helper=!bash ${APP_DIR}/build/git-credential-staged.sh ${credsDir}`]; -} - -export function credentialFile(token: string): string { - return `${GITHUB_TOKEN_USER}\n${token}`; -} - export async function buildSnapshot(client: SandboxClient, repo: RepoContext, sha: string, deps: SnapshotDeps = {}): Promise { if (!SHA.test(sha)) throw new Error(`refusing to build ${repo.fullName} at ${JSON.stringify(sha)}: not a commit SHA`); const branch = repo.config.baseBranch; @@ -81,7 +71,13 @@ export async function buildSnapshot(client: SandboxClient, repo: RepoContext, sh log("info", "snapshot build started", { repo: repo.fullName, sha, snapshot: name }); const egress = builderEgress(repo); - const { id } = await client.call(() => client.api.create({ timeoutSeconds: BUILDER_TIMEOUT_SECONDS, networkPolicy: egress })); + const sandboxGroupId = await ensureSandboxGroup(client, repo); + const token = await (deps.readToken ?? readToken)(repo); + await client.brokerCredential(sandboxGroupId, githubCredential(repo, token)); + const created = await client.call(() => + client.api.create({ sandboxGroupId, timeoutSeconds: BUILDER_TIMEOUT_SECONDS, networkPolicy: egress }), + ); + const { id } = created; try { await client.waitRunning(id); @@ -91,8 +87,8 @@ export async function buildSnapshot(client: SandboxClient, repo: RepoContext, sh await client.check(id, `tar -xzf ${STAGING_DIR}/stage.tgz -C ${STAGING_DIR} && rm ${STAGING_DIR}/stage.tgz`, boot); await client.check( id, - `mkdir -p ${APP_DIR}/runner ${APP_DIR}/build ${REPO_DIR} ${SCRATCH_DIR}` + - ` && cp ${STAGING_DIR}/*.sh ${APP_DIR}/ && cp ${STAGING_DIR}/build/*.sh ${APP_DIR}/build/` + + `mkdir -p ${APP_DIR}/runner ${REPO_DIR} ${SCRATCH_DIR}` + + ` && cp ${STAGING_DIR}/*.sh ${APP_DIR}/` + ` && cp -R ${STAGING_DIR}/runner/. ${APP_DIR}/runner/`, boot, ); @@ -113,12 +109,7 @@ export async function buildSnapshot(client: SandboxClient, repo: RepoContext, sh prepare, ); - const token = await (deps.readToken ?? readToken)(repo); - await client.check(id, `mkdir -p -m 700 ${STAGING_CREDS}`, boot); - await client.upload(id, `${STAGING_CREDS}/github.com`, credentialFile(token)); await client.check(id, cloneCommand(repo, sha), prepare); - const scrub = await client.exec(id, `bash ${APP_DIR}/build/scrub-credentials.sh ${STAGING_CREDS} ${REPO_DIR} ${SCRATCH_DIR}/home`, prepare); - if (scrub.exitCode !== 0) throw new Error(`credential scrub failed: ${(scrub.stderr || scrub.stdout).trim().slice(-2000)}`); await client.check(id, `chown -R ${RUN_AS}: ${REPO_DIR}`, prepare); const lockfileHash = await computeLockfileHash(client, id); @@ -176,9 +167,8 @@ function envFileContent(nodePath: string): string { function cloneCommand(repo: RepoContext, sha: string): string { const url = `https://github.com/${repo.owner}/${repo.name}.git`; const branch = repo.config.baseBranch; - const auth = credentialHelperArgs(STAGING_CREDS).map(shq).join(" "); return [ - `GIT_TERMINAL_PROMPT=0 git ${auth} clone --quiet --single-branch --branch ${shq(branch)} --no-tags -- ${shq(url)} ${REPO_DIR}`, + `GIT_TERMINAL_PROMPT=0 git clone --quiet --single-branch --branch ${shq(branch)} --no-tags -- ${shq(url)} ${REPO_DIR}`, `git -C ${REPO_DIR} checkout --quiet -B ${shq(branch)} ${sha}`, `head=$(git -C ${REPO_DIR} rev-parse HEAD) && [ "$head" = ${sha} ]`, ].join(" && "); @@ -320,7 +310,6 @@ async function stagingArchive(payload: RunnerPayload): Promise { const dir = await mkdtemp(join(tmpdir(), "factory-stage-")); try { await mkdir(join(dir, "runner")); - await mkdir(join(dir, "build")); for (const [path, data] of payload.files) { await mkdir(dirname(join(dir, "runner", path)), { recursive: true }); await writeFile(join(dir, "runner", path), data); diff --git a/app/sandbox/types.ts b/app/sandbox/types.ts index f1367a3..67d66d6 100644 --- a/app/sandbox/types.ts +++ b/app/sandbox/types.ts @@ -22,8 +22,22 @@ export interface ExecStreamOptions { signal?: AbortSignal; } +export interface BrokerCredential { + id: string; + domain: string; + value: string; + injection: { + type: "header" | "basic" | "cookie" | "query"; + name?: string; + template?: string; + }; + methods?: string[]; + paths?: string[]; +} + export interface Sandbox { readonly id: string; + brokerCredential(credential: BrokerCredential): Promise; exec(command: string, opts?: ExecOptions): Promise; execStream(command: string, opts: ExecStreamOptions): Promise; upload(path: string, data: string | Buffer): Promise; diff --git a/docs/architecture.md b/docs/architecture.md index 6b613d9..52ebf3d 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -263,22 +263,23 @@ A harness adapter in `app/harness/` wraps an agent library's own configuration. Agent definitions and their harnesses are bundled into the Sandbox runner, which runs the agent named in its input on that agent's harness. The host and the runner speak a versioned contract -(`app/runner/core/protocol.ts`): JSON on stdin, with the key on the first line, -and JSON Lines events on stdout. Every harness gives the model the factory's -own tools and `submit`, so tool authority and the read-only shell policy don't -depend on the library. In the runner, a kernel owns each run: its events, turn -and time limits, tools, and submission. A harness's driver only translates its -library. +(`app/runner/core/protocol.ts`): JSON on stdin and JSON Lines events on +stdout. The runner gives the model library a non-secret placeholder; Render +replaces it with the brokered credential only on the matching outbound HTTPS +request. Every harness gives the model the factory's own tools and `submit`, +so tool authority and the read-only shell policy don't depend on the library. +In the runner, a kernel owns each run: its events, turn and time limits, +tools, and submission. A harness's driver only translates its library. The built-in harness runs Pi's coding agent SDK (`@earendil-works/pi-coding-agent`) through `createAgentSession` (`app/runner/pi/driver.ts`). The session's working directory is the untrusted -checkout, and the runner holds the model key in memory, so the driver turns -off Pi's discovery: it loads no context file such as `AGENTS.md`, skill, -prompt template, theme, or extension from the checkout or anywhere else. The -system prompt is the agent's prompt file, and the tools are exactly the -factory's. Every model request passes the kernel's turn limit before it is -sent, including Pi's retries of transient errors and its context compaction. +checkout. The driver turns off Pi's discovery: it loads no context file such +as `AGENTS.md`, skill, prompt template, theme, or extension from the checkout +or anywhere else. The system prompt is the agent's prompt file, and the tools +are exactly the factory's. Every model request passes the kernel's turn limit +before it is sent, including Pi's retries of transient errors and its context +compaction. Every agent finishes through a typed `submit` tool. The runner validates the submission against JSON Schema. The host validates it again with the agent's @@ -354,13 +355,17 @@ only to requests that present `EVENTS_READ_TOKEN`, compared in constant time. The Workflows service holds GitHub, Render, and database credentials. It selects every destination, checks thread ownership, validates Sandbox output, -and performs GitHub writes. +performs GitHub writes, and configures brokered credentials on the target +repository's dedicated Sandbox group. ### Sandbox -Clone and fetch credentials are read-only and temporary. Runtime files are -root-owned and read-only. Agents and repository commands run as an -unprivileged user. +GitHub clone and fetch requests receive a read-only installation token from +Render's credential broker only when their host, repository path, and method +match. Model requests receive the selected harness's provider key only when +their host, endpoint path, and method match. The real values remain outside +the Sandbox. Runtime files are root-owned and read-only. Agents and repository +commands run as an unprivileged user. Every Sandbox is created with an HTTPS egress allow-list built by the Workflows host from trusted configuration. Task Sandboxes reach `github.com`, @@ -370,10 +375,11 @@ repository's hosts. Render enforces the list outside the Sandbox and fixes it at creation, so nothing inside the Sandbox can widen it. See [Sandbox egress](configuration.md#sandbox-egress). -The model key enters the Sandbox during an agent call. The runner receives it -through a root-only path and stdin, removes provider keys from tool -environments, and runs under a non-dumpable Node binary. These controls and -the allow-list reduce exposure; they do not make untrusted code safe. +The runner uses a non-secret placeholder to make the model library construct +its normal request, removes provider keys from tool environments, and runs +under a non-dumpable Node binary. Render replaces the placeholder outside the +Sandbox. These controls and the allow-list reduce exposure; they do not make +untrusted code safe. ## Security invariants @@ -402,6 +408,10 @@ Changes must preserve these properties: 14. Load no repository file as a prompt, skill, prompt template, or extension. An agent's instructions are its prompt file and task message, and its tools are the factory's. +15. Keep GitHub and model credential values outside Sandboxes. Broker them + only to exact trusted HTTPS hosts, paths, and methods. +16. Put each repository in its own Sandbox group so brokered credentials for + one repository never apply to another repository's Sandboxes. Tests pin these invariants and the tool authority of every built-in agent. @@ -414,7 +424,9 @@ Tests pin these invariants and the tool authority of every built-in agent. after the fetch. - DNS resolution is not restricted by the allow-list. - A repository configured with `egress: "allow-all"` has unrestricted egress. -- The model key exists in runner memory during a call. +- Any process in the Sandbox can make a request that matches a broker route. + It cannot read the injected value, but it can exercise that credential's + authority, including model spend. - Prompt injection can influence specifications, code, and reviews. - Anyone with `minimumPermission` can start model spend. - PR Reviewer runs repository-defined commands from the labeled pull request. diff --git a/docs/configuration.md b/docs/configuration.md index e4a09cc..78ddc35 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -51,7 +51,7 @@ from any other repository, even if the App is installed there. | Field | Required | Meaning | |---|---|---| | `baseBranch` | Yes | Branch used for Triage, implementation, and snapshots | -| `install` | No | Dependency command run after clone credentials are removed | +| `install` | No | Dependency command run after the repository is cloned | | `verify` | Yes | Commands required before publishing and during PR review | | `egress` | No | Extra HTTPS hosts this repository's Sandboxes may reach, or `"allow-all"` | @@ -88,8 +88,15 @@ the allow-list names the allowed hosts in its error. Set `egress: "allow-all"` to lift the restriction for one repository. Prefer listing hosts: the allow-list is what stops dependency scripts and -prompt-injected agents from sending code or the model key to arbitrary -destinations. +prompt-injected agents from sending code to arbitrary destinations. + +The Workflows host gives each repository its own Render Sandbox group and +configures credential brokering there. Render injects a repository-scoped +GitHub installation token only into the matching repository's clone and fetch +requests. It injects a model key only into the model endpoint declared by the +selected harness. Neither secret enters the Sandbox filesystem, environment, +stdin, or process memory. A Sandbox group supports 25 brokered credentials: +one GitHub route plus up to 24 distinct model routes for that repository. Render fixes a Sandbox's policy when it is created, so an `egress` change applies to the next Sandbox after a Workflows deploy. No snapshot refresh is @@ -155,11 +162,16 @@ them together. Pi retries a model request that fails transiently up to twice and compacts a conversation that nears the model's context window. Each retry and compaction request counts toward the agent's turn limit. -Each harness declares the env var of its key, its `credential`. Setup and -`doctor` derive the keys they manage from the agents' harnesses, so a harness that needs a new key -needs no other configuration change. The `pi` adapter supports Anthropic +Each harness declares the env var of its key, its `credential`, and the HTTPS +route where Render brokers that key, its `credentialBroker`. Setup and +`doctor` derive the keys they manage from the agents' harnesses, so a harness +that needs a new key needs no other environment configuration change. The +`pi` adapter supplies broker routes for Anthropic (`ANTHROPIC_API_KEY`), Google (`GEMINI_API_KEY`), and OpenAI -(`OPENAI_API_KEY`). After a harness change that needs a new key: +(`OPENAI_API_KEY`). A custom API adapter must pass `credentialBroker` with an +exact domain, methods, paths, and header, basic-auth, cookie, or query +injection. Do not define overlapping routes: Render applies only one matching +credential. After a harness change that needs a new key: 1. add the key to local `.env`; 2. run `npm run setup:render` to add it to the `software-factory-workflows` @@ -185,6 +197,11 @@ The factory has no hard dollar budget. ## Environment variables +The Render workspace must have Sandbox credential brokering enabled. The +identity that owns `RENDER_API_KEY` must be a workspace admin, and a scoped +key must include write access to manage Sandbox credentials. Creating a +credential and rotating its secret require admin authority. + Local variables are listed in [`.env.example`](../.env.example). The Blueprint supplies `RENDER_WORKFLOW_SLUG` and `DATABASE_URL` to the gateway from the Workflows service and `factory-db`. Every other deployed value, @@ -206,7 +223,7 @@ including Workflows' `DATABASE_URL`, comes from an | Variable | Purpose | |---|---| -| `RENDER_API_KEY` | Manage Sandboxes, snapshots, and task cancellation | +| `RENDER_API_KEY` | Manage Sandboxes, snapshots, brokered credentials, and task cancellation | | `RENDER_WORKSPACE_ID` | Workspace that owns Sandboxes and snapshots | | `GITHUB_APP_ID` | Authenticate the GitHub App | | `GITHUB_APP_PRIVATE_KEY` | Mint installation tokens | @@ -383,9 +400,15 @@ works on. ## Snapshots -Each configured repository has a dependency-installed Sandbox snapshot. A -push to its base branch refreshes it. If no snapshot exists, the first task -builds one. A failed refresh does not delete the previous usable snapshot. +Each configured repository has a dedicated Sandbox group and a +dependency-installed snapshot in that group. A push to its base branch +refreshes it. If the group or snapshot does not exist, the first task creates +it. A failed refresh does not delete the previous usable snapshot. + +After upgrading an existing deployment to credential brokering, refresh every +repository once. Earlier snapshots in the default Sandbox group are not +reused, because group isolation is what prevents one repository's brokered +credentials from applying to another repository's Sandbox. ### Refresh a snapshot diff --git a/docs/quickstart.md b/docs/quickstart.md index ed79c02..63502fe 100644 --- a/docs/quickstart.md +++ b/docs/quickstart.md @@ -9,8 +9,10 @@ checkpoints. Prepare: - a fork of this repository; -- a Render workspace with Sandboxes access in Oregon; -- a Render API key; +- a Render workspace with Sandboxes and Sandbox credential brokering access + in Oregon; +- a Render API key owned by a workspace admin, with Sandbox credential write + access if it is scoped; - a dedicated Anthropic API key with a provider-enforced spend limit; - admin access to each target GitHub repository, with Issues enabled (Settings > General > Features); and diff --git a/docs/runbooks/extend.md b/docs/runbooks/extend.md index 59e8448..2082c4b 100644 --- a/docs/runbooks/extend.md +++ b/docs/runbooks/extend.md @@ -142,7 +142,9 @@ driver that only translates the library. configuration and returns a `Harness` (`app/harness/types.ts`): - `name` and `label` name the library and model before a run; - `credential` is the env var on the Workflows service that holds its key; - the host sends its value into the Sandbox; + - `credentialBroker` is the exact HTTPS domain, methods, and paths where + Render may inject that key, plus the header, basic-auth, cookie, or query + injection. Keep routes narrow and non-overlapping; - `egress` lists the HTTPS hosts the library calls from the Sandbox, such as its model API. Sandboxes block every host not on their allow-list, so derive it from the library's configuration when you can; and @@ -155,7 +157,7 @@ driver that only translates the library. or subagent tools: their authority isn't the factory's; - turn off the library's discovery of instructions, skills, prompt templates, and plugins. `ctx.cwd` is the untrusted checkout, and a plugin - would run its code beside the key; + would run its code with access to the brokered endpoint; - call `ctx.requestModel()` before every model request, retries included, and don't send the request when it returns false; - report text, usage, and tool calls and results through `ctx.report`; and @@ -378,6 +380,7 @@ for which services and snapshots your change affects, plus: [Environment groups](../configuration.md#environment-groups)). - For a harness that introduces a new provider key, setup and `doctor` derive its `credential` automatically; add the key to `.env`, rerun - `npm run setup:render`, and deploy `factory-workflows`. + `npm run setup:render`, define its narrow `credentialBroker` route, and + deploy `factory-workflows`. State the required deploy and refresh actions in the handoff. diff --git a/docs/runbooks/setup.md b/docs/runbooks/setup.md index 657d206..e220e1a 100644 --- a/docs/runbooks/setup.md +++ b/docs/runbooks/setup.md @@ -17,7 +17,8 @@ Collect: - deterministic dependency install command, if needed; - verification commands; - GitHub App owner: a user or organization; -- Render workspace with Sandboxes access in Oregon; and +- Render workspace with Sandboxes and Sandbox credential brokering access in + Oregon; - confirmation that the default Anthropic models are acceptable. Secrets reach Render through local `.env` and @@ -179,9 +180,11 @@ Continue only after the user confirms access to every configured repository. in the workspace before the Blueprint is applied. `setup:render` creates them from local `.env`. -Ask which workspace to deploy to. It needs Sandboxes access in Oregon. The -workspace ID starts with `tea-` and is not a secret. If the Render CLI is -signed in, list the IDs with: +Ask which workspace to deploy to. It needs Sandboxes and Sandbox credential +brokering access in Oregon. The identity that creates `RENDER_API_KEY` must be +a workspace admin; a scoped key must include write access for Sandbox +credentials. The workspace ID starts with `tea-` and is not a secret. If the +Render CLI is signed in, list the IDs with: ```bash render workspaces -o json @@ -198,8 +201,9 @@ RENDER_API_KEY= ANTHROPIC_API_KEY= ``` -The Anthropic key enters the Sandbox during agent runs. Do not read or print -`.env` to check the values; `setup:render` reports which are missing. +The Workflows service gives the Anthropic key to Render's credential broker; +the key does not enter the Sandbox. Do not read or print `.env` to check the +values; `setup:render` reports which are missing. Run: diff --git a/package-lock.json b/package-lock.json index fb9550e..1f47295 100644 --- a/package-lock.json +++ b/package-lock.json @@ -13,7 +13,7 @@ "@earendil-works/pi-ai": "1.5.2", "@earendil-works/pi-coding-agent": "1.5.2", "@hono/node-server": "^2.0.0", - "@renderinc/sdk": "^1.3.0", + "@renderinc/sdk": "^1.12.0", "esbuild": "^0.28.2", "hono": "^4.0.0", "pg": "^8.23.1", @@ -31,7 +31,7 @@ "vitest": "^4.1.11" }, "engines": { - "node": ">=22.19" + "node": ">=24" } }, "node_modules/@anthropic-ai/sdk": { @@ -1347,9 +1347,9 @@ } }, "node_modules/@renderinc/sdk": { - "version": "1.3.0", - "resolved": "https://registry.npmjs.org/@renderinc/sdk/-/sdk-1.3.0.tgz", - "integrity": "sha512-665ea4IbCRZ9dKXJtmTZDx+YpBu5tKDS2qvyHfwVB/hqRbZjX38fSUpiXDpmVccjztCH8bOLhVI723kNrUuJFA==", + "version": "1.12.0", + "resolved": "https://registry.npmjs.org/@renderinc/sdk/-/sdk-1.12.0.tgz", + "integrity": "sha512-bJODAB07EVx8kkjKSImURrEqd16UZJNzwVWxR4AYJU6xTxwLkKIGwvQF9Vw0JD9vXlxwsRqHtLQXri7Yh8KBNg==", "license": "MIT", "dependencies": { "eventsource": "^4.0.0", diff --git a/package.json b/package.json index f83dd5f..a53c944 100644 --- a/package.json +++ b/package.json @@ -32,7 +32,7 @@ "@earendil-works/pi-ai": "1.5.2", "@earendil-works/pi-coding-agent": "1.5.2", "@hono/node-server": "^2.0.0", - "@renderinc/sdk": "^1.3.0", + "@renderinc/sdk": "^1.12.0", "esbuild": "^0.28.2", "hono": "^4.0.0", "pg": "^8.23.1", diff --git a/sandbox/build/git-credential-staged.sh b/sandbox/build/git-credential-staged.sh deleted file mode 100755 index a6bc996..0000000 --- a/sandbox/build/git-credential-staged.sh +++ /dev/null @@ -1,17 +0,0 @@ -#!/usr/bin/env bash -set -euo pipefail - -creds_dir=$1 -action=${2:-} -[ "$action" = get ] || exit 0 - -host="" -while IFS= read -r line; do - case "$line" in host=*) host=${line#host=} ;; esac -done -case "$host" in "" | *[!A-Za-z0-9.:-]* | .*) exit 0 ;; esac - -file="$creds_dir/$host" -[ -s "$file" ] || exit 0 -{ IFS= read -r username && { IFS= read -r token || [ -n "$token" ]; }; } <"$file" -printf 'username=%s\npassword=%s\n' "$username" "$token" diff --git a/sandbox/build/scrub-credentials.sh b/sandbox/build/scrub-credentials.sh deleted file mode 100755 index 2936965..0000000 --- a/sandbox/build/scrub-credentials.sh +++ /dev/null @@ -1,43 +0,0 @@ -#!/usr/bin/env bash -set -euo pipefail - -creds_dir=$1 -repo_dir=$2 -shift 2 -homes=("$HOME" "$@") -fail() { - printf 'scrub-credentials: %s\n' "$*" >&2 - exit 1 -} -[ -d "$repo_dir/.git" ] || fail "$repo_dir is not a git checkout" - -if [ -d "$creds_dir" ]; then - pattern_file=$(mktemp) - trap 'rm -f "$pattern_file"' EXIT - for cf in "$creds_dir"/*; do - [ -s "$cf" ] || continue - sed -n '2p' "$cf" >"$pattern_file" - [ -s "$pattern_file" ] || continue - for h in "${homes[@]}"; do - for f in "$h/.gitconfig" "$h/.git-credentials" "$h/.config/git"; do - if [ -e "$f" ] && grep -rqsF -f "$pattern_file" -- "$f"; then fail "token for $(basename "$cf") found in $f"; fi - done - done - if [ -e /etc/gitconfig ] && grep -qsF -f "$pattern_file" -- /etc/gitconfig; then fail "token for $(basename "$cf") found in /etc/gitconfig"; fi - if grep -rqsF --exclude-dir=objects -f "$pattern_file" -- "$repo_dir/.git"; then fail "token for $(basename "$cf") found in $repo_dir/.git"; fi - done -fi - -rm -rf "$creds_dir" -[ ! -e "$creds_dir" ] || fail "could not delete $creds_dir" - -settings='^(credential\.|url\..*\.insteadof|http\..*\.extraheader)' -for h in "${homes[@]}"; do - [ ! -e "$h/.git-credentials" ] || fail "$h/.git-credentials exists" -done -for scope in --system --global; do - if git config "$scope" --get-regexp "$settings" >/dev/null 2>&1; then fail "credential settings in git $scope config"; fi -done -if git -c safe.directory='*' -C "$repo_dir" config --local --get-regexp "$settings" >/dev/null 2>&1; then fail "$repo_dir: credential settings"; fi -url=$(git -c safe.directory='*' -C "$repo_dir" config --local --get remote.origin.url 2>/dev/null || true) -case "$url" in *@*) fail "$repo_dir: remote URL carries credentials" ;; esac diff --git a/sandbox/run-agent.sh b/sandbox/run-agent.sh index 8bfd299..c172f01 100755 --- a/sandbox/run-agent.sh +++ b/sandbox/run-agent.sh @@ -10,29 +10,12 @@ app=$(dirname "${BASH_SOURCE[0]}") # shellcheck source=/dev/null . "$app/env" -key_file="$run_dir/key" -trap 'rm -f "$key_file"' EXIT -if [ ! -f "$key_file" ]; then - echo "run-agent: $key_file is missing" >&2 - exit 1 -fi -key=$(<"$key_file") -rm -f "$key_file" -if [ -e "$key_file" ]; then - echo "run-agent: cannot delete $key_file" >&2 - exit 1 -fi -if [[ $key == *$'\n'* ]]; then - echo "run-agent: $key_file holds more than one line" >&2 - exit 1 -fi if [ "$(id -u)" = 0 ] && [ "$FACTORY_RUN_AS" != root ]; then chown -R "$FACTORY_RUN_AS": "$run_dir"; fi set +e -{ printf '%s\n' "$key"; cat "$run_dir/input.json"; } | - timeout --kill-after=10s "$seconds" bash "$app/as-runner.sh" "$FACTORY_RUNNER_NODE" "$FACTORY_APP_DIR/runner/runner.mjs" --key-stdin | +timeout --kill-after=10s "$seconds" bash "$app/as-runner.sh" "$FACTORY_RUNNER_NODE" "$FACTORY_APP_DIR/runner/runner.mjs" --brokered-key <"$run_dir/input.json" | tee -p "$run_dir.jsonl" -status=${PIPESTATUS[1]} +status=${PIPESTATUS[0]} set -e echo "$status" >"$run_dir.exit" exit "$status" diff --git a/sandbox/verify.sh b/sandbox/verify.sh index da3ccb0..7d440af 100755 --- a/sandbox/verify.sh +++ b/sandbox/verify.sh @@ -12,7 +12,7 @@ as_runner() { bash "$app/as-runner.sh" "$@"; } [ $# -eq 0 ] || fail "unexpected arguments: $*" for d in "$FACTORY_APP_DIR" "$FACTORY_REPO_DIR" "$FACTORY_SCRATCH_DIR"; do [ -d "$d" ] || fail "missing $d"; done -for f in as-runner.sh run-agent.sh lockfile-hash.sh build/git-credential-staged.sh build/scrub-credentials.sh runner/runner.mjs manifest.json; do +for f in as-runner.sh run-agent.sh lockfile-hash.sh runner/runner.mjs manifest.json; do [ -f "$FACTORY_APP_DIR/$f" ] || fail "missing $FACTORY_APP_DIR/$f" done for tool in git rg timeout sha256sum; do PATH="$FACTORY_PATH" command -v "$tool" >/dev/null || fail "missing $tool"; done diff --git a/tests/agents-catalog.test.ts b/tests/agents-catalog.test.ts index cbab734..6280a3c 100644 --- a/tests/agents-catalog.test.ts +++ b/tests/agents-catalog.test.ts @@ -31,7 +31,15 @@ describe("agent authority", () => { }); it("lets every agent's sandbox reach only its model provider's API beyond the factory's own hosts", () => { - for (const agent of agents) expect(agent.harness.egress, agent.id).toEqual(["api.anthropic.com"]); + for (const agent of agents) { + expect(agent.harness.egress, agent.id).toEqual(["api.anthropic.com"]); + expect(agent.harness.credentialBroker, agent.id).toEqual({ + domain: "api.anthropic.com", + injection: { type: "header", name: "x-api-key" }, + methods: ["POST"], + paths: ["/v1/messages"], + }); + } }); it("rejects unknown fields in every object an agent can submit, so a misspelled field is named in the error", () => { diff --git a/tests/agents.test.ts b/tests/agents.test.ts index c6d8dd5..4ad1bce 100644 --- a/tests/agents.test.ts +++ b/tests/agents.test.ts @@ -56,7 +56,7 @@ describe("runAgent in a sandbox", () => { process.env.ANTHROPIC_API_KEY = HOST_KEY; }); - it("runs tool-using agents in the sandbox without exposing the model key to commands or events", async () => { + it("brokers the model key without exposing it to sandbox files, commands, or events", async () => { const sandbox = new FakeSandbox({ jsonl: `${cannedRun({ verdict: "ok", findings: ["x"] })}\n` }); const run = await runAgent(reviewer, "Review it.", { traceId: "trace-2", @@ -76,7 +76,16 @@ describe("runAgent in a sandbox", () => { const runDir = sandbox.runDir as string; expect(runDir).toMatch(/^\/tmp\/agent-[0-9a-f-]{36}$/); - expect(sandbox.uploads.get(`${runDir}/key`)).toBe(HOST_KEY); + expect(sandbox.credentials).toEqual([ + expect.objectContaining({ + domain: "api.anthropic.com", + value: HOST_KEY, + injection: { type: "header", name: "x-api-key" }, + methods: ["POST"], + paths: ["/v1/messages"], + }), + ]); + expect(sandbox.uploads.has(`${runDir}/key`)).toBe(false); const input = RunnerInput.parse(JSON.parse(sandbox.uploads.get(`${runDir}/input.json`) as string)); expect(input).toMatchObject({ protocol_version: PROTOCOL_VERSION, diff --git a/tests/harness-pi.test.ts b/tests/harness-pi.test.ts index 98aa26d..b9df873 100644 --- a/tests/harness-pi.test.ts +++ b/tests/harness-pi.test.ts @@ -1,7 +1,9 @@ import { existsSync, mkdirSync, writeFileSync } from "node:fs"; import { join } from "node:path"; import { fauxAssistantMessage, fauxText, fauxToolCall, type JsonObject, type TranscriptContext } from "@earendil-works/pi-ai"; +import { getBuiltinModel } from "@earendil-works/pi-ai/providers/all"; import { describe, expect, it } from "vitest"; +import { pi } from "../app/harness/index.js"; import { fauxPi } from "./helpers/pi-scripted.js"; import { GOOD, makeInput, makeWorkspace, parseEvents, runContract, SUBMIT } from "./helpers/runner.js"; @@ -12,6 +14,36 @@ const calls = (...list: [string, JsonObject][]) => ); describe("pi driver", { timeout: 30_000 }, () => { + it.each([ + { + provider: "anthropic", + harness: pi({ model: getBuiltinModel("anthropic", "claude-sonnet-5") }), + route: { domain: "api.anthropic.com", injection: { type: "header", name: "x-api-key" }, methods: ["POST"], paths: ["/v1/messages"] }, + }, + { + provider: "openai", + harness: pi({ model: getBuiltinModel("openai", "gpt-5.2") }), + route: { + domain: "api.openai.com", + injection: { type: "header", name: "Authorization", template: `Bearer \${SECRET}` }, + methods: ["POST"], + paths: ["/v1/responses"], + }, + }, + { + provider: "google", + harness: pi({ model: getBuiltinModel("google", "gemini-2.5-pro") }), + route: { + domain: "generativelanguage.googleapis.com", + injection: { type: "header", name: "x-goog-api-key" }, + methods: ["POST"], + paths: ["/v1beta/models/*"], + }, + }, + ] as const)("scopes the $provider credential to its inference endpoint", ({ harness, route }) => { + expect(harness.credentialBroker).toEqual(route); + }); + it("streams each assistant message as deltas, then its final text under the same message ID", async () => { const text = "Looking at the repository layout before I submit."; const harness = fauxPi([fauxAssistantMessage([fauxText(text), fauxToolCall(SUBMIT, GOOD)], { stopReason: "toolUse" })]); diff --git a/tests/helpers/fake-sandbox.ts b/tests/helpers/fake-sandbox.ts index 6462f43..23e41f8 100644 --- a/tests/helpers/fake-sandbox.ts +++ b/tests/helpers/fake-sandbox.ts @@ -1,6 +1,15 @@ import { asciiJson } from "../../app/runner/core/emit.js"; import type { RunnerEvent } from "../../app/runner/core/protocol.js"; -import type { ExecOptions, ExecResult, ExecStreamOptions, OpenedSandbox, Sandbox, SandboxRef, SnapshotManifest } from "../../app/sandbox/types.js"; +import type { + BrokerCredential, + ExecOptions, + ExecResult, + ExecStreamOptions, + OpenedSandbox, + Sandbox, + SandboxRef, + SnapshotManifest, +} from "../../app/sandbox/types.js"; type WithoutAt = E extends unknown ? Omit : never; @@ -15,10 +24,15 @@ export class FakeSandbox implements Sandbox { readonly id = "sbx-fake"; readonly execs: Array<{ command: string; opts?: ExecOptions | ExecStreamOptions }> = []; readonly uploads = new Map(); + readonly credentials: BrokerCredential[] = []; runDir: string | undefined; constructor(private readonly options: FakeSandboxOptions) {} + async brokerCredential(credential: BrokerCredential): Promise { + this.credentials.push(credential); + } + async exec(command: string, opts?: ExecOptions): Promise { this.execs.push({ command, opts }); const mkdir = /^mkdir -m 700 (\S+)$/.exec(command); @@ -68,6 +82,7 @@ export class FakeOpenedSandbox implements OpenedSandbox { readonly manifest: SnapshotManifest; readonly execs: Array<{ command: string; opts?: ExecOptions }> = []; readonly opened: Array = []; + readonly credentials: BrokerCredential[] = []; closed = 0; results: Record; @@ -83,6 +98,10 @@ export class FakeOpenedSandbox implements OpenedSandbox { return this; }; + async brokerCredential(credential: BrokerCredential): Promise { + this.credentials.push(credential); + } + async exec(command: string, opts?: ExecOptions): Promise { this.execs.push({ command, opts }); const key = Object.keys(this.results).find((prefix) => command.startsWith(prefix)); diff --git a/tests/helpers/pi-scripted.ts b/tests/helpers/pi-scripted.ts index 00a1355..8fb7acb 100644 --- a/tests/helpers/pi-scripted.ts +++ b/tests/helpers/pi-scripted.ts @@ -37,6 +37,17 @@ export function fauxPi(responses: FauxResponseStep[], modelId = "scripted"): Har registry.setProvider(stub.provider); return registry; }; - const model = { ...stub.getModel(), id: modelId }; - return pi({ model, models, thinkingLevel: "off", credential: "SCRIPTED_API_KEY" }); + const model = { ...stub.getModel(), id: modelId, baseUrl: "https://scripted.invalid" }; + return pi({ + model, + models, + thinkingLevel: "off", + credential: "SCRIPTED_API_KEY", + credentialBroker: { + domain: "scripted.invalid", + injection: { type: "header", name: "Authorization", template: `Bearer \${SECRET}` }, + methods: ["POST"], + paths: ["/v1/messages"], + }, + }); } diff --git a/tests/helpers/runner.ts b/tests/helpers/runner.ts index 711b60c..efe1919 100644 --- a/tests/helpers/runner.ts +++ b/tests/helpers/runner.ts @@ -41,8 +41,6 @@ export function testAgent(harness: Harness): Agent { export const HARNESSES: ReadonlyArray<{ name: string; make: (turns: readonly TestTurn[]) => Harness }> = [{ name: "pi", make: scriptedPi }]; -export const TEST_KEY = "sk-test-STDINKEY-0123456789"; - export interface Workspace { cwd: string; scratchDir: string; @@ -104,10 +102,10 @@ export const toolResults = (events: RunnerEvent[]) => events.flatMap((e) => (e.t export const call = (name: string, args: Record): TestTurn => ({ calls: [{ name, args }] }); -export async function runContract(harness: Harness, input: RunnerInput, key = TEST_KEY) { +export async function runContract(harness: Harness, input: RunnerInput) { let stdout = ""; - const code = await main(["--key-stdin"], { - stdin: Readable.from([`${key}\n${JSON.stringify(input)}`]), + const code = await main(["--brokered-key"], { + stdin: Readable.from([JSON.stringify(input)]), write: async (chunk) => { stdout += chunk; }, diff --git a/tests/publish.test.ts b/tests/publish.test.ts index fa6e097..37b220e 100644 --- a/tests/publish.test.ts +++ b/tests/publish.test.ts @@ -283,6 +283,7 @@ class LocalSandbox implements Sandbox { readonly id = "sbx-local"; tamper: ((file: Buffer) => Buffer) | undefined; + async brokerCredential(): Promise {} exec(command: string): Promise { return new Promise((resolve) => { execFile("bash", ["-c", command], { encoding: "utf8", maxBuffer: 1 << 26 }, (err, stdout, stderr) => { diff --git a/tests/runner.test.ts b/tests/runner.test.ts index 23981fe..f2325b1 100644 --- a/tests/runner.test.ts +++ b/tests/runner.test.ts @@ -15,7 +15,6 @@ import { runCli, runContract, SUBMIT, - TEST_KEY, terminal, toolResults, } from "./helpers/runner.js"; @@ -49,23 +48,19 @@ describe("bundled runner (runner.mjs)", { timeout: 60_000 }, () => { expect(code).toBe(0); }); - it("rejects an agent the bundle doesn't define, input from another protocol version, and a run without a key", () => { - const keyed = (input: unknown) => `${TEST_KEY}\n${JSON.stringify(input)}`; - const unknown = runCli(["--key-stdin"], keyed(makeInput(undefined, { agent_id: "nope" }))); + it("rejects an agent the bundle doesn't define, input from another protocol version, and a run without brokered credentials", () => { + const unknown = runCli(["--brokered-key"], JSON.stringify(makeInput(undefined, { agent_id: "nope" }))); expect(terminal(parseEvents(unknown.stdout))).toMatchObject({ code: "invalid_input", message: expect.stringContaining('unknown agent "nope"') }); expect(unknown.code).toBe(2); - const old = runCli(["--key-stdin"], keyed({ ...makeInput(undefined, { agent_id: "triage" }), protocol_version: 1 })); + const old = runCli(["--brokered-key"], JSON.stringify({ ...makeInput(undefined, { agent_id: "triage" }), protocol_version: 1 })); expect(terminal(parseEvents(old.stdout))).toMatchObject({ code: "invalid_input", message: expect.stringContaining(`speaks protocol ${PROTOCOL_VERSION}, but the input is protocol 1`), }); const keyless = runCli([], JSON.stringify(makeInput(undefined, { agent_id: "triage" }))); - expect(terminal(parseEvents(keyless.stdout))).toMatchObject({ code: "invalid_input", message: expect.stringContaining("no model key") }); - - const empty = runCli(["--key-stdin"], `\n${JSON.stringify(makeInput(undefined, { agent_id: "triage" }))}`); - expect(terminal(parseEvents(empty.stdout))).toMatchObject({ code: "invalid_input", message: "--key-stdin: the first line of stdin is empty" }); + expect(terminal(parseEvents(keyless.stdout))).toMatchObject({ code: "invalid_input", message: expect.stringContaining("no brokered model key") }); }); }); @@ -133,23 +128,22 @@ describe.each(HARNESSES)("$name harness conformance", { timeout: 30_000 }, ({ ma expect(code).toBe(1); }); - it("takes the key from stdin and keeps every secret out of the tool env and the output", async () => { + it("uses the broker placeholder and keeps every host secret out of the tool env and output", async () => { const ws = makeWorkspace(); - const stdinKey = "sk-ant-test-STDINKEY-0123456789"; process.env.ANTHROPIC_API_KEY = "sk-ant-test-ENVKEY-9876543210"; process.env.ANTHROPIC_OAUTH_TOKEN = "oauth-token-value"; process.env.OPENAI_API_KEY = "sk-openai-not-for-the-model"; process.env.RENDER_API_KEY = "rnd-not-for-the-model"; const harness = make([call("bash", { command: "env > $HOME/env.txt" }), call(SUBMIT, GOOD)]); - const { code, stdout, events } = await runContract(harness, makeInput(ws, { tools: ["bash", "write"] }), stdinKey); + const { code, stdout, events } = await runContract(harness, makeInput(ws, { tools: ["bash", "write"] })); expect(toolResults(events)[0]?.is_error).toBe(false); const env = readFileSync(join(ws.scratchDir, "env.txt"), "utf8"); expect(env).toContain(`HOME=${ws.scratchDir}`); for (const leaked of ["sk-ant", "sk-openai", "ANTHROPIC", "OPENAI", "oauth-token-value", "RENDER_API_KEY", "rnd-not"]) expect(env).not.toContain(leaked); - expect(stdout).not.toContain(stdinKey); + expect(stdout).not.toContain("sk-ant-test-ENVKEY-9876543210"); expect(process.env.ANTHROPIC_API_KEY).toBeUndefined(); expect(code).toBe(0); }); diff --git a/tests/sandbox-render.test.ts b/tests/sandbox-render.test.ts index f614ba1..ba0a4d4 100644 --- a/tests/sandbox-render.test.ts +++ b/tests/sandbox-render.test.ts @@ -1,11 +1,17 @@ import { Readable } from "node:stream"; import { pipeline } from "node:stream/promises"; -import { SandboxSnapshotNotFoundError } from "@renderinc/sdk"; -import type { SandboxExecEvent } from "@renderinc/sdk/experimental"; +import { SandboxCredentialNotFoundError, type SandboxExecEvent, SandboxSnapshotNotFoundError } from "@renderinc/sdk"; import { list as listTar } from "tar"; import { beforeEach, describe, expect, it, vi } from "vitest"; import type { RepoContext } from "../app/config/index.js"; -import { buildSnapshot, type OpenSandboxDeps, openSandbox, type SandboxApi, SandboxClient, type SnapshotManifest } from "../app/sandbox/index.js"; +import { + buildSnapshot, + type OpenSandboxDeps, + openSandbox, + type SandboxApi, + SandboxClient, + type SnapshotManifest, +} from "../app/sandbox/index.js"; import { runnerPayload } from "../app/sandbox/snapshot.js"; async function untar(data: Buffer): Promise> { @@ -47,6 +53,8 @@ type Call = | { op: "exec"; id: string; command: string } | { op: "upload"; id: string; path: string; data: unknown } | { op: "download" | "terminate"; id: string; path?: string } + | { op: "credential.create" | "credential.update"; input: unknown } + | { op: "group.create" | "group.list"; input: unknown } | { op: "snapshot.create" | "snapshot.get" | "snapshot.list" | "snapshot.delete"; input: unknown }; type ExecHandler = (id: string, command: string) => SandboxExecEvent[]; @@ -73,6 +81,8 @@ function snapshot(id: string, status: "creating" | "available" | "failed", name: class FakeApi { calls: Call[] = []; createError?: (input: Parameters[0]) => Error | undefined; + credentialError?: Error; + credentialIds = new Set(); lockfileHash = HASH; fetchedSha = HEAD_SHA; overrides: ExecHandler = () => []; @@ -88,6 +98,7 @@ class FakeApi { { snapshot: snapshot("snp-new", "available", NAME), cursor: "a" }, { snapshot: snapshot("snp-other", "available", "factory-acme-api"), cursor: "b" }, ]; + groups: Array<{ sandboxGroup: { id: string; name: string }; cursor: string }> = []; #n = 0; exec(id: string, command: string): SandboxExecEvent[] { @@ -108,10 +119,10 @@ class FakeApi { if (err) throw err; const id = `sbx-${++self.#n}`; self.calls.push({ op: "create", id, input }); - return { id, status: "creating", networkPolicy: input.networkPolicy, timeoutSeconds: input.timeoutSeconds }; + return { id, sandboxGroupId: "sbg-1", status: "creating", networkPolicy: input.networkPolicy, timeoutSeconds: input.timeoutSeconds }; }, async get(id: string) { - return { id, status: "running" }; + return { id, sandboxGroupId: "sbg-1", status: "running" }; }, async exec(id: string, command: string) { self.calls.push({ op: "exec", id, command }); @@ -132,6 +143,31 @@ class FakeApi { async terminate(id: string) { self.calls.push({ op: "terminate", id }); }, + async listGroups(input: unknown) { + self.calls.push({ op: "group.list", input }); + return self.groups; + }, + async createGroup(input: { name: string }) { + self.calls.push({ op: "group.create", input }); + const number = self.groups.length + 1; + const sandboxGroup = { id: `sbg-${number}`, name: input.name }; + self.groups.push({ sandboxGroup, cursor: `g${number}` }); + return sandboxGroup; + }, + credentials: { + async create(input: { credentialId: string }) { + if (self.credentialError) throw self.credentialError; + self.calls.push({ op: "credential.create", input }); + self.credentialIds.add(input.credentialId); + return { id: input.credentialId }; + }, + async update(input: { credentialId: string }) { + if (self.credentialError) throw self.credentialError; + self.calls.push({ op: "credential.update", input }); + if (!self.credentialIds.has(input.credentialId)) throw new SandboxCredentialNotFoundError("missing", 404); + return { id: input.credentialId }; + }, + }, snapshots: { async create(input: { name?: string }) { self.calls.push({ op: "snapshot.create", input }); @@ -181,16 +217,34 @@ beforeEach(() => { fake = new FakeApi(); }); +describe("Sandbox credential isolation", () => { + it("creates the repository group before its first builder", async () => { + await buildSnapshot(client(), repo(), BASE_SHA, { readToken }); + expect(fake.inputs("group.create")).toEqual([{ name: expect.stringMatching(/^factory-acme-web-[0-9a-f]{24}$/) }]); + expect(fake.inputs("create")).toEqual([expect.objectContaining({ sandboxGroupId: "sbg-1" })]); + }); +}); + describe("buildSnapshot", () => { - it("keeps the token out of commands, scrubs it before install, and snapshots under the repository's name", async () => { + it("brokers the token before clone and snapshots under the repository's name", async () => { const built = await buildSnapshot(client(), repo(), BASE_SHA, { readToken }); expect(built).toMatchObject({ id: "snp-new", name: NAME, manifest: { sha: BASE_SHA, lockfileHash: HASH } }); expect(fake.commands().some((c) => c.includes(TOKEN))).toBe(false); - const scrub = fake.execIndex("scrub-credentials.sh"); - expect(scrub).toBeGreaterThanOrEqual(0); - expect(fake.execIndex("npm ci")).toBeGreaterThan(scrub); + expect(fake.calls.some((c) => c.op === "upload" && String(c.data).includes(TOKEN))).toBe(false); + const credential = fake.inputs("credential.create")[0]; + expect(credential).toMatchObject({ + sandboxGroupId: "sbg-1", + domain: "github.com", + value: TOKEN, + injection: { type: "basic", template: `x-access-token:\${SECRET}` }, + methods: ["GET", "POST"], + paths: ["/acme/web.git/**"], + }); + expect(fake.index((c) => c.op === "credential.create")).toBeLessThan(fake.execIndex("git clone")); + expect(fake.execIndex("npm ci")).toBeGreaterThan(fake.execIndex("git clone")); + expect(fake.inputs("create")).toEqual([expect.objectContaining({ sandboxGroupId: "sbg-1" })]); expect(fake.inputs("snapshot.create")).toEqual([{ sandboxId: "sbx-1", kind: "filesystem", name: NAME }]); expect(fake.terminated()).toEqual(["sbx-1"]); }); @@ -202,13 +256,14 @@ describe("buildSnapshot", () => { ); }); - it("never installs when the scrub fails", async () => { - fake.overrides = (_id, command) => - command.includes("scrub-credentials.sh") ? [out("scrub-credentials: token for github.com found in x\n", "stderr"), exit(1)] : []; - await expect(buildSnapshot(client(), repo(), BASE_SHA, { readToken })).rejects.toThrow("credential scrub failed"); + it("never clones or installs when credential brokering fails", async () => { + fake.credentialError = new Error("credential broker unavailable"); + await expect(buildSnapshot(client(), repo(), BASE_SHA, { readToken })).rejects.toThrow("credential broker unavailable"); + expect(fake.execIndex("git clone")).toBe(-1); expect(fake.execIndex("npm ci")).toBe(-1); + expect(fake.inputs("create")).toEqual([]); expect(fake.inputs("snapshot.create")).toEqual([]); - expect(fake.calls.at(-1)).toEqual({ op: "terminate", id: "sbx-1" }); + expect(fake.terminated()).toEqual([]); }); }); @@ -241,9 +296,14 @@ describe("openSandbox", () => { it("restores by snapshot name, verifies, and checks out the fetched head without the token in any command", async () => { const sbx = await openSandbox(repo(), { kind: "branch", name: "main" }, deps()); expect(sbx).toMatchObject({ id: "sbx-1", headSha: HEAD_SHA, manifest: fake.manifest }); - expect(fake.inputs("create")).toMatchObject([{ snapshotName: NAME }]); + expect(fake.inputs("create")).toMatchObject([{ sandboxGroupId: "sbg-1", snapshotName: NAME }]); expect(fake.execIndex("verify.sh")).toBeGreaterThanOrEqual(0); expect(fake.commands().some((c) => c.includes(TOKEN))).toBe(false); + expect(fake.calls.some((c) => c.op === "upload" && String(c.data).includes(TOKEN))).toBe(false); + expect(fake.inputs("credential.create")).toEqual([ + expect.objectContaining({ sandboxGroupId: "sbg-1", domain: "github.com", value: TOKEN, paths: ["/acme/web.git/**"] }), + ]); + expect(fake.index((c) => c.op === "credential.create")).toBeLessThan(fake.execIndex("'fetch'")); expect(fake.execIndex("npm ci")).toBe(-1); expect(fake.terminated()).toEqual([]); }); @@ -278,10 +338,11 @@ describe("openSandbox", () => { expect(fake.execIndex("'bash' '-c' 'npm ci'")).toBeGreaterThan(fake.execIndex("'checkout'")); }); - it("scrubs the token even when the fetch fails", async () => { + it("keeps the brokered token out of the sandbox when fetch fails", async () => { fake.overrides = (_id, command) => (command.includes("'fetch'") ? [out("fatal: couldn't find remote ref\n", "stderr"), exit(128)] : []); await expect(openSandbox(repo(), { kind: "branch", name: "gone" }, deps())).rejects.toThrow("couldn't find remote ref"); - expect(fake.execIndex("scrub-credentials.sh")).toBeGreaterThan(fake.execIndex("'fetch'")); + expect(fake.commands().some((c) => c.includes(TOKEN))).toBe(false); + expect(fake.calls.some((c) => c.op === "upload" && String(c.data).includes(TOKEN))).toBe(false); expect(fake.calls.at(-1)).toEqual({ op: "terminate", id: "sbx-1" }); }); diff --git a/tests/sandbox-scripts.test.ts b/tests/sandbox-scripts.test.ts index 177e068..3ca239f 100644 --- a/tests/sandbox-scripts.test.ts +++ b/tests/sandbox-scripts.test.ts @@ -1,5 +1,4 @@ import { execFile } from "node:child_process"; -import { existsSync } from "node:fs"; import { cp, mkdir, mkdtemp, readFile, realpath, rm, writeFile } from "node:fs/promises"; import { tmpdir, userInfo } from "node:os"; import { dirname, join } from "node:path"; @@ -20,17 +19,9 @@ const head = Buffer.alloc(65536); const first = head.subarray(0, readSync(0, head, 0, head.length, null)).toString("utf8"); if (first.includes('"mode":"no-read"')) process.exit(0); const text = first + readFileSync(0, "utf8"); -let key = null; -let rest = text; -if (args.includes("--key-stdin")) { - const newline = text.indexOf("\\n"); - key = text.slice(0, newline); - rest = text.slice(newline + 1); -} -const input = JSON.parse(rest); -const keyFileExists = input.keyFile ? existsSync(input.keyFile) : null; +const input = JSON.parse(text); if (input.probe) writeFileSync(input.probe, JSON.stringify({ argv: process.argv, env: process.env })); -const report = { input, key, keyFileExists, args, cwd: process.cwd(), envKeys: Object.keys(process.env).sort() }; +const report = { input, args, cwd: process.cwd(), envKeys: Object.keys(process.env).sort() }; console.log(JSON.stringify({ type: "started" })); console.log(JSON.stringify({ type: "report", report })); process.stderr.write("fake runner diagnostics\\n"); @@ -189,11 +180,10 @@ describe("verify.sh", { timeout: 30_000 }, () => { }); describe("run-agent.sh", { timeout: 30_000 }, () => { - async function runDir(name: string, input: object, key?: string): Promise { + async function runDir(name: string, input: object): Promise { const dir = join(tmp, "runs", name); await mkdir(dir, { recursive: true, mode: 0o700 }); - await writeFile(join(dir, "input.json"), JSON.stringify({ ...input, keyFile: join(dir, "key"), probe: `${dir}.probe` })); - if (key) await writeFile(join(dir, "key"), key); + await writeFile(join(dir, "input.json"), JSON.stringify({ ...input, probe: `${dir}.probe` })); return dir; } @@ -205,9 +195,8 @@ describe("run-agent.sh", { timeout: 30_000 }, () => { return lines.find((l) => l.type === "report").report; }; - it("deletes the key file before the runner starts and feeds the key as the first line of stdin with --key-stdin", async () => { - const key = "sk-ant-script-key"; - const dir = await runDir("run-ok", { mode: "ok", task: "hello" }, `${key}\n`); + it("feeds only the task input to a runner configured for brokered credentials", async () => { + const dir = await runDir("run-ok", { mode: "ok", task: "hello" }); const res = await bash(join(app, "run-agent.sh"), [dir, "30"]); expect(res.code).toBe(0); expect(res.stderr).toContain("fake runner diagnostics"); @@ -216,18 +205,16 @@ describe("run-agent.sh", { timeout: 30_000 }, () => { const jsonl = await readFile(`${dir}.jsonl`, "utf8"); expect(res.stdout).toBe(jsonl); const report = reportOf(jsonl); - expect(report).toMatchObject({ input: { task: "hello" }, key, keyFileExists: false, args: ["--key-stdin"], cwd: repo }); + expect(report).toMatchObject({ input: { task: "hello" }, args: ["--brokered-key"], cwd: repo }); expect(report.envKeys).not.toContain("DATABASE_URL"); expect(report.envKeys).toEqual(expect.arrayContaining(["HOME", "PATH", "TMPDIR", "GIT_CONFIG_GLOBAL"])); - expect(await readFile(`${dir}.probe`, "utf8")).not.toContain(key); - expect(existsSync(join(dir, "key"))).toBe(false); }); it.each([ ["fails", "fail", "30", 3], ["times out", "hang", "1", 124], ])("writes the same output to stdout and the file and keeps the runner's status when the runner %s", async (_, mode, seconds, status) => { - const dir = await runDir(`run-${mode}`, { mode }, "sk-ant-script-key\n"); + const dir = await runDir(`run-${mode}`, { mode }); const res = await bash(join(app, "run-agent.sh"), [dir, seconds]); expect(res.code).toBe(status); expect(await readFile(`${dir}.exit`, "utf8")).toBe(`${status}\n`); @@ -236,61 +223,3 @@ describe("run-agent.sh", { timeout: 30_000 }, () => { expect(res.stdout).toBe(jsonl); }); }); - -describe("credential scripts", { timeout: 30_000 }, () => { - const helper = () => join(app, "build/git-credential-staged.sh"); - const scrub = () => join(app, "build/scrub-credentials.sh"); - - async function stageCreds(): Promise { - const dir = await mkdtemp(join(tmp, "creds-")); - await writeFile(join(dir, "github.com"), `x-access-token\n${TOKEN}`); - return dir; - } - - it("scrub-credentials.sh fails without echoing the token when it reached .git", async () => { - const creds = await stageCreds(); - await git(["-C", repo, "config", "remote.origin.pushurl", `https://x:${TOKEN}@github.com/acme/widget.git`]); - try { - const res = await bash(scrub(), [creds, repo]); - expect(res.code).toBe(1); - expect(res.stderr).toContain("token for github.com found in"); - expect(res.stderr).not.toContain(TOKEN); - expect(existsSync(creds)).toBe(true); - } finally { - await git(["-C", repo, "config", "--unset", "remote.origin.pushurl"]); - } - }); - - it("fetches through the staged helper as the runner, then scrubs (the open flow, against a local remote)", async () => { - const creds = await stageCreds(); - const work = join(tmp, "work"); - await writeFile(join(work, "feature.txt"), "feature\n"); - await git(["-C", work, "checkout", "-q", "-b", "feature"]); - await git(["-C", work, "add", "-A"]); - await git(["-C", work, "commit", "-q", "-m", "feature"]); - const featureSha = await git(["-C", work, "rev-parse", "HEAD"]); - await git(["-C", work, "push", "-q", join(tmp, "remote.git"), "feature"]); - - const asRunner = (...args: string[]) => bash(join(app, "as-runner.sh"), args); - const helperArg = `credential.helper=!bash ${helper()} ${creds}`; - const fetched = await asRunner( - "git", - "-c", - "credential.helper=", - "-c", - helperArg, - "fetch", - "--quiet", - "--no-tags", - "origin", - "refs/heads/feature", - ); - expect(fetched.stderr).toBe(""); - expect(fetched.code).toBe(0); - expect((await bash(scrub(), [creds, repo, join(scratch, "home")])).code).toBe(0); - expect((await asRunner("git", "rev-parse", "FETCH_HEAD^{commit}")).stdout.trim()).toBe(featureSha); - expect((await asRunner("git", "checkout", "--quiet", "--detach", featureSha)).code).toBe(0); - expect(await git(["-C", repo, "rev-parse", "HEAD"])).toBe(featureSha); - await git(["-C", repo, "checkout", "-q", "main"]); - }); -});