@buildanagent/harness 0.1.0-alpha.29 → 0.1.0-alpha.30
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +41 -0
- package/dist/credentials/addresses.d.ts +11 -0
- package/dist/credentials/addresses.js +41 -2
- package/dist/credentials/addresses.js.map +1 -1
- package/dist/errors.d.ts +6 -3
- package/dist/errors.js +5 -2
- package/dist/errors.js.map +1 -1
- package/dist/sandbox/escalation-table.d.ts +38 -0
- package/dist/sandbox/escalation-table.js +95 -0
- package/dist/sandbox/escalation-table.js.map +1 -0
- package/dist/sandbox/escalation.d.ts +191 -0
- package/dist/sandbox/escalation.js +370 -0
- package/dist/sandbox/escalation.js.map +1 -0
- package/dist/sandbox/index.d.ts +6 -3
- package/dist/sandbox/index.js +6 -3
- package/dist/sandbox/index.js.map +1 -1
- package/dist/sandbox/widen.d.ts +10 -0
- package/dist/sandbox/widen.js +150 -0
- package/dist/sandbox/widen.js.map +1 -0
- package/dist/session/approvals.d.ts +30 -1
- package/dist/session/approvals.js +12 -4
- package/dist/session/approvals.js.map +1 -1
- package/dist/session/code-call.d.ts +15 -1
- package/dist/session/code-call.js +2 -1
- package/dist/session/code-call.js.map +1 -1
- package/dist/session/escalation-log.d.ts +65 -0
- package/dist/session/escalation-log.js +84 -0
- package/dist/session/escalation-log.js.map +1 -0
- package/dist/session/rebuild.js +12 -3
- package/dist/session/rebuild.js.map +1 -1
- package/llms.txt +18 -0
- package/package.json +5 -5
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"escalation.js","sourceRoot":"","sources":["../../src/sandbox/escalation.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AACH,OAAO,EACL,kBAAkB,EAClB,oBAAoB,EAIpB,gBAAgB,GACjB,MAAM,mBAAmB,CAAC;AAE3B,OAAO,EAAE,YAAY,EAAE,MAAM,cAAc,CAAC;AAE5C,OAAO,EAEL,gBAAgB,EAChB,gBAAgB,EA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AS;QACnD,MAAM,OAAO,GAAG,MAAM,OAAO,CAAC,MAAM,CAAC,QAAQ,CAAC,SAAS,CAAC,OAAO,EAAE,OAAO,CAAC,GAAG,CAAC,SAAS,CAAC,OAAO,CAAC,EAAE,CAAC,IAAI,EAAE,CAAC,CAAC;QAC1G,IAAI,OAAO,KAAK,SAAS;YAAE,SAAS;QACpC,KAAK,CAAC,IAAI,CAAC,EAAE,YAAY,EAAE,EAAE,EAAE,OAAO,EAAE,SAAS,CAAC,OAAO,EAAE,MAAM,EAAE,SAAS,CAAC,KAAK,EAAE,CAAC,CAAC;IACxF,CAAC;IACD,OAAO,KAAK,CAAC;AACf,CAAC;AAED;;;GAGG;AACH,MAAM,UAAU,UAAU,CAAc,OAA6B;IACnE,MAAM,EAAE,OAAO,EAAE,MAAM,EAAE,GAAG,SAAS,CAAC,OAAO,CAAC,CAAC;IAC/C,MAAM,OAAO,GAAe;QAC1B,OAAO;QACP,MAAM;QACN,cAAc,EAAE,OAAO,CAAC,cAAc;QACtC,KAAK,EAAE,OAAO,CAAC,QAAQ,IAAI,EAAE;KAC9B,CAAC;IACF,OAAO;QACL,cAAc,EAAE,OAAO,CAAC,cAAc;QACtC,WAAW,EAAE,sBAAsB;QACnC,GAAG,EAAE,CAAC,OAAO,EAAE,IAAI,EAAE,EAAE,CAAC,UAAU,CAAC,OAAO,EAAE,OAAO,EAAE,IAAI,CAAC;QAC1D,OAAO,EAAE,CAAC,OAAO,EAAE,EAAE,CAAC,SAAS,CAAC,OAAO,EAAE,OAAO,CAAC;QACjD,OAAO,CAAC,OAAO,EAAE,UAAU,EAAE,cAAc;YACzC,OAAO,eAAe,CAAC,OAAO,EAAE,GAAG,EAAE,CAAC,aAAa,CAAC,OAAO,EAAE,OAAO,EAAE,UAAU,EAAE,cAAc,CAAC,CAAC,CAAC;QACrG,CAAC;KACF,CAAC;AACJ,CAAC","sourcesContent":["/**\n * `escalation()`: what the host does when a sandbox denies a command. Under `never` the denial goes back to the caller\n * and nothing is written. Under `on-request`, and under `granular` where a rule allows it, the denial becomes a signed\n * `approval_requested` entry, and once a person or a hook allows it, the command runs once more under the policy\n * widened by exactly what the denial named. The widened policy is built here, on the host, from the signed record and\n * the verified answer; no tool input or model output reaches it, and it lasts for that one rerun.\n */\nimport {\n canonicalInputHash,\n createPendingRequest,\n type Resolution,\n type SignedPendingRequest,\n type ToolResult,\n verifyResolution,\n} from \"@buildanagent/sdk\";\nimport type { Clock } from \"@buildanagent/sdk/testing\";\nimport { HarnessError } from \"../errors.js\";\nimport type { Harness } from \"../harness.js\";\nimport {\n type Approvals,\n answersByRequest,\n approvalsBinding,\n checkAnswers,\n type QuorumPolicy,\n settled,\n} from \"../session/approvals.js\";\nimport { type Io, inCodeCallQueue, ioOf } from \"../session/code-call.js\";\nimport {\n ESCALATION_TOOL,\n type EscalationLogRecord,\n type EscalationRecord,\n escalationsOf,\n isEscalationRecord,\n waitingEscalations,\n} from \"../session/escalation-log.js\";\nimport { recordSessionStart } from \"../session/runner.js\";\nimport type { Session } from \"../session/session.js\";\nimport {\n ESCALATION_TRANSITIONS,\n type EscalationEvent,\n type EscalationState,\n type EscalationTransition,\n nextEscalationState,\n} from \"./escalation-table.js\";\nimport type {\n ApprovalPolicy,\n ExecResult,\n Sandbox,\n SandboxClient,\n SandboxDenial,\n SandboxPolicy,\n WorkspaceManifest,\n} from \"./types.js\";\nimport { widenPolicy } from \"./widen.js\";\n\n/**\n * One rule of a `granular` policy: a denial of `kind` for `tool` may be asked about (`on-request`) or goes back to the\n * caller (`never`). A rule with no `kind` or no `tool` matches every kind or every tool. The first rule that matches\n * decides, and a denial no rule matches goes back to the caller.\n */\nexport interface EscalationRule {\n /** The kind of denial the rule covers. Left out, every kind. */\n readonly kind?: SandboxDenial[\"kind\"];\n /** A tool's canonical name or alias, as the registry knows it. */\n readonly tool?: string;\n /** Whether a matching denial may become a request. */\n readonly escalate: \"on-request\" | \"never\";\n}\n\n/** The options of `escalation()`. */\nexport interface EscalationOptions<H = unknown> {\n /** When a denial may become a request: `on-request`, `granular` (by `granular`'s rules) or `never`. */\n readonly approvalPolicy: ApprovalPolicy;\n /**\n * The approvals from `createApprovals()`. The escalation signs with their harness's signer, decides the rerun with\n * their harness's permission pipeline, and lets their quorum policy decide each answer.\n */\n readonly approvals: Approvals<H>;\n /** The rules a `granular` policy needs, and that any other policy refuses. */\n readonly granular?: readonly EscalationRule[];\n}\n\n/** One command to run in a sandbox, for one tool call, and what the host provisions the sandbox with. */\nexport interface EscalationRun<H = unknown> {\n /** The tool the command runs for, which the permission pipeline decides again before a rerun. */\n readonly tool: string;\n /** That tool call's input, as the pipeline sees it. It is recorded, so it needs a canonical JSON form. */\n readonly input: unknown;\n /** Who chose the call. Default `model`. */\n readonly initiator?: \"model\" | \"code\";\n /** The tool call's own id, recorded for the approver to see. */\n readonly toolCallId?: string;\n /** The executable and its arguments, with no shell. */\n readonly command: readonly string[];\n /** The working directory, relative to the workspace root. */\n readonly cwd?: string;\n /** Stops the command, and its rerun, after this long, as `Sandbox.exec()` does. */\n readonly timeoutMs?: number;\n /** The most bytes of each output stream to keep, as `Sandbox.exec()` does. */\n readonly maxOutputBytes?: number;\n /** The command's whole environment, from `spawnEnv()`. It is never recorded. */\n readonly env: Readonly<Record<string, string>>;\n /** Aborts the command. */\n readonly signal: AbortSignal;\n /** The backend `run()` provisions from when it is given no `sandbox`. */\n readonly client: SandboxClient;\n /** The workspace. Its root is recorded, and a rerun needs the same root. */\n readonly manifest: WorkspaceManifest;\n /** The policy the command runs under. It is recorded, and a rerun widens this record of it. */\n readonly policy: SandboxPolicy;\n /** A sandbox already provisioned with `policy`. Left out, `run()` provisions one and disposes it. */\n readonly sandbox?: Sandbox;\n /** The caller's identity. A request binds a MAC of it, so only the same value can resolve it. */\n readonly hostContext?: H;\n /** The clock of the entries and the signed request. Default the system clock. */\n readonly clock?: Clock;\n /** Makes the escalation's id and the ids of its entries and request. Default `crypto.randomUUID()`. */\n readonly newId?: () => string;\n}\n\n/** The options of `EscalationMachine.resolve()`: where the rerun runs, which the log does not hold. */\nexport interface EscalationResolveOptions<H = unknown> {\n /** The backend the rerun provisions a fresh sandbox from. */\n readonly client: SandboxClient;\n /** The workspace, whose root must be the recorded one. */\n readonly manifest: WorkspaceManifest;\n /** The rerun's whole environment, from `spawnEnv()`. */\n readonly env: Readonly<Record<string, string>>;\n /**\n * Aborts the call and its rerun. A signal aborted when `resolve()` is called writes nothing. One aborted later, but\n * before the answer is written, writes no answer and runs nothing, so the request still waits. One aborted after the\n * answer is written only reaches the rerun, as `Sandbox.exec()` takes a signal, and the approval is spent.\n */\n readonly signal: AbortSignal;\n /** The same host context the request was made with, when it bound one. */\n readonly hostContext?: H;\n /** Who asked. An approver equal to it is refused. */\n readonly requesterId?: string;\n /** The clock of the entries. Default the system clock. */\n readonly clock?: Clock;\n /** Makes the ids of the entries. Default `crypto.randomUUID()`. */\n readonly newId?: () => string;\n}\n\n/**\n * How an escalation call ended. `states` is the path it took through the transition table in this call. `result` is a\n * tool result a tool can return to the model: the command's output, or why it did not run. The model reads it only\n * when nothing was written, as under `never`; once a request exists, the rebuilt context leaves it out and the host\n * reads it.\n *\n * - `ran`: the command finished without a denial. `rerun` is true when it was the approved rerun.\n * - `denied`: the command did not run to an end the caller can use: a denial that went back with no request, a refused\n * answer, the pipeline's deny, or a second denial on the rerun.\n * - `awaiting_approval`: `pending` waits for an answer through `resolve()`. `widened` is the policy the rerun would get.\n *\n * `escalationId` names the escalation once it has a request; a denial that went back with no request has none.\n * `denial` is what the backend refused, and `reason` is the sentence `result` carries.\n */\nexport type EscalationResult =\n | {\n readonly status: \"ran\";\n readonly exec: Extract<ExecResult, { exitCode: number }>;\n readonly rerun: boolean;\n readonly escalationId?: string;\n readonly states: readonly EscalationState[];\n readonly result: ToolResult<unknown>;\n }\n | {\n readonly status: \"denied\";\n readonly reason: string;\n readonly denial?: SandboxDenial;\n readonly rerun: boolean;\n readonly escalationId?: string;\n readonly states: readonly EscalationState[];\n readonly result: ToolResult<unknown>;\n }\n | {\n readonly status: \"awaiting_approval\";\n readonly escalationId: string;\n readonly pending: SignedPendingRequest;\n readonly denial: SandboxDenial;\n readonly widened: SandboxPolicy;\n readonly states: readonly EscalationState[];\n readonly result: ToolResult<unknown>;\n };\n\n/** An escalation that waits for an answer: its id, its signed request and the record the request signs. */\nexport interface PendingEscalation {\n /** The escalation's id, which its request names as its call id. */\n readonly escalationId: string;\n /** The signed request, to show the approver with the record. */\n readonly request: SignedPendingRequest;\n /** What the request signs: the tool and its input, the command, the workspace root, the policy and the denial. */\n readonly record: EscalationRecord;\n}\n\n/** The machine `escalation()` returns. */\nexport interface EscalationMachine<H = unknown> {\n /** The approval policy the machine was made with. */\n readonly approvalPolicy: ApprovalPolicy;\n /** The table every move follows. */\n readonly transitions: readonly EscalationTransition[];\n /**\n * Runs a command in the sandbox. A command the backend does not deny ends `ran`, and nothing is written. A denial\n * ends `denied`, with nothing written, unless the policy allows a request and the denial names one path or host that\n * can be widened; then a signed `approval_requested` entry is written and the call ends `awaiting_approval`.\n *\n * Writing a request appends to the session, so under `on-request` and `granular` call it from host code outside a\n * turn's tool step, as `invokeTool()` runs. Throws `invalid_escalation` for an input or host context with no\n * canonical JSON form, before anything is written.\n */\n run(session: Session, run: EscalationRun<H>): Promise<EscalationResult>;\n /**\n * The escalations of the session that wait for an answer. The quorum policy is asked about each one with the answers\n * written so far, and one it says has expired is left out. Listing writes nothing, so such an escalation stays in the\n * log until it is answered: `resolve()` then writes the policy's denial, and it never reruns.\n */\n pending(session: Session): Promise<PendingEscalation[]>;\n /**\n * Answers one waiting escalation. The answer is checked before anything is written: the signature under a key in the\n * ring, the bound host context, the call and the record. An allow must name its approver in `by`, and a classifier's\n * allow (`by: \"classifier:…\"`) never approves a rerun; both are refused with nothing written. `by` is not covered by\n * the request's signature, so the host sets it only after it has authenticated the approver. The answer is written,\n * the quorum policy decides the answer, and an allow then goes through the permission pipeline again, so a deny rule\n * added since the pause wins. The rerun runs once in a fresh sandbox under the recorded policy widened by exactly the\n * recorded denial, and that sandbox is disposed after it. A second denial is the rerun's result.\n *\n * It first settles every escalation a crash left open: a rerun that started and has no result is never run again.\n * Throws `approval_not_pending` for a request that does not wait, `approval_refused` for one that fails its check, an\n * allow with no `by` or a classifier's allow, `approver_is_requester`, and `invalid_escalation` for a workspace with\n * another root.\n */\n resolve(session: Session, resolution: Resolution, options: EscalationResolveOptions<H>): Promise<EscalationResult>;\n}\n\nconst POLICIES: readonly string[] = [\"on-request\", \"granular\", \"never\"];\nconst KINDS: readonly string[] = [\"filesystem_read\", \"filesystem_write\", \"network\"];\n// The characters of each output stream the log keeps of a rerun. Even at six bytes a character, as JSON escapes a\n// control character, two streams stay under the store's 64 KiB entry bound.\nconst STORED_CHARS = 4 * 1024;\n\nconst invalid = (message: string, cause?: unknown) =>\n new HarnessError(\"invalid_escalation\", message, cause === undefined ? {} : { cause });\n\nfunction checkRules(rules: unknown): void {\n if (!Array.isArray(rules) || rules.length === 0) {\n throw invalid(\"a granular approval policy needs a non-empty list of escalation rules\");\n }\n for (const rule of rules as EscalationRule[]) {\n const ok =\n (rule?.escalate === \"on-request\" || rule?.escalate === \"never\") &&\n (rule.kind === undefined || KINDS.includes(rule.kind)) &&\n (rule.tool === undefined || (typeof rule.tool === \"string\" && rule.tool !== \"\"));\n if (!ok) throw invalid(`an escalation rule is unusable: ${JSON.stringify(rule)}`);\n }\n}\n\n/** Checks the options and returns the harness and quorum policy the approvals were made with. */\nfunction bindingOf<H>(options: EscalationOptions<H>): { harness: Harness<H>; quorum: QuorumPolicy } {\n if (!POLICIES.includes(options?.approvalPolicy)) {\n throw invalid(`the approval policy must be on-request, granular or never, got ${String(options?.approvalPolicy)}`);\n }\n if (options.approvalPolicy === \"granular\") checkRules(options.granular);\n else if (options.granular !== undefined) throw invalid(\"escalation rules apply only to a granular approval policy\");\n const binding = options.approvals === undefined ? undefined : approvalsBinding(options.approvals);\n if (binding === undefined) throw invalid(\"escalation() needs the approvals createApprovals() made\");\n if (options.approvalPolicy !== \"never\") {\n if (binding.harness.signer === undefined) {\n throw new HarnessError(\"approval_unavailable\", \"the harness has no signer, so no escalation could be asked\");\n }\n if (binding.harness.pipeline === undefined) {\n throw invalid(\"the harness has no permission pipeline, so no rerun could be decided again\");\n }\n }\n return binding;\n}\n\nconst text = (body: string, isError: boolean, details?: unknown): ToolResult<unknown> => ({\n content: [{ type: \"text\", text: body }],\n isError,\n ...(details === undefined ? {} : { details }),\n});\n\n/** The moves of one call: each goes through the table, so an edge it does not list throws. */\ninterface Walker {\n readonly states: EscalationState[];\n step(event: EscalationEvent): void;\n /** The states so far and an error result with `body`, for a call that ends without the command's output. */\n end(body: string): { readonly states: readonly EscalationState[]; readonly result: ToolResult<unknown> };\n}\n\nfunction walker(start: EscalationState): Walker {\n const states: EscalationState[] = [start];\n return {\n states,\n step(event) {\n states.push(nextEscalationState(states.at(-1) as EscalationState, event));\n },\n end: (body) => ({ states, result: text(body, true) }),\n };\n}\n\nconst what = (denial: SandboxDenial): string =>\n `The sandbox refused a ${denial.kind.replace(\"_\", \" \")} of ${denial.target}: ${denial.reason}.`;\n\nfunction clip(value: string, most = STORED_CHARS): string {\n return value.length <= most ? value : `${value.slice(0, most)}\\n[output cut]`;\n}\n\nfunction execText(exec: Extract<ExecResult, { exitCode: number }>, keep: (value: string) => string): string {\n const signal = exec.signal === undefined ? \"\" : ` (${exec.signal})`;\n return [`exit code ${exec.exitCode}${signal}`, keep(exec.stdout), keep(exec.stderr)].join(\"\\n\");\n}\n\nconst ranResult = (exec: Extract<ExecResult, { exitCode: number }>, keep = (value: string) => value) =>\n text(execText(exec, keep), exec.exitCode !== 0, {\n exitCode: exec.exitCode,\n ...(exec.signal === undefined ? {} : { signal: exec.signal }),\n });\n\n/**\n * Where an escalation's result text came from. `command`: the rerun's output. `quoted`: a sentence of the harness's\n * that quotes text it did not write, such as a backend's denial, an error's message or an approver's reason. `fixed`:\n * one of the harness's own fixed sentences.\n */\ntype ResultSource = \"command\" | \"quoted\" | \"fixed\";\n\n/** Writes the escalation's result, which ends it: the model never reads it, and the host gets it back. */\nasync function writeResult(io: Io, id: string, result: ToolResult<unknown>, source: ResultSource): Promise<void> {\n const first = result.content[0];\n // The streams were clipped one by one already; this bounds the whole text, the exit line included.\n const body = first?.type === \"text\" ? clip(first.text, 2 * STORED_CHARS + 256) : \"\";\n await io.write(source === \"command\" ? \"tool\" : \"harness\", {\n type: \"tool_result\",\n callId: id,\n tool: ESCALATION_TOOL,\n content: [{ type: \"text\", text: body }],\n isError: result.isError === true,\n ...(result.details === undefined ? {} : { details: result.details }),\n // A command's output, a backend's message or a quoted reason can carry instructions an attacker wrote; only the\n // harness's fixed sentences can't.\n trust: source === \"fixed\" ? \"trusted\" : \"untrusted\",\n });\n}\n\nconst INTERRUPTED = \"The rerun stopped before its result was recorded, so it may have run. It is not run again.\";\nconst NEVER_RAN = \"The escalation stopped after its answer was written and before its rerun started, so it never ran.\";\n\n/** Settles each escalation a crash left open, by the crash rule: a started rerun is never run again. */\nasync function settleOpen(path: readonly EscalationLogRecord[], io: Io): Promise<void> {\n for (const record of path) {\n if (record.result !== undefined || !(record.answered || record.started)) continue;\n nextEscalationState(record.started ? \"rerun\" : \"requested\", \"settled\");\n await writeResult(io, record.id, text(record.started ? INTERRUPTED : NEVER_RAN, true), \"fixed\");\n }\n}\n\nasync function hashable(value: unknown, what: string): Promise<void> {\n try {\n await canonicalInputHash(value);\n } catch (error) {\n throw invalid(`the escalation's ${what} has no canonical JSON form`, error);\n }\n}\n\n/** The fields of `fields` that are set, so an optional field left out is not written as `undefined`. */\nfunction present<T extends object>(fields: T): Partial<T> {\n return Object.fromEntries(Object.entries(fields).filter(([, value]) => value !== undefined)) as Partial<T>;\n}\n\n/** Runs one command in a sandbox provisioned for it, and disposes that sandbox whatever happens. */\nasync function execIn(\n where: { readonly client: SandboxClient; readonly manifest: WorkspaceManifest; readonly sandbox?: Sandbox },\n policy: SandboxPolicy,\n command: Pick<EscalationRecord, \"command\" | \"cwd\" | \"timeoutMs\" | \"maxOutputBytes\">,\n run: { readonly env: Readonly<Record<string, string>>; readonly signal: AbortSignal },\n): Promise<ExecResult> {\n const used = where.sandbox ?? (await where.client.provision(where.manifest, policy));\n const { cwd, timeoutMs, maxOutputBytes } = command;\n try {\n return await used.exec(command.command, {\n env: run.env,\n signal: run.signal,\n ...present({ cwd, timeoutMs, maxOutputBytes }),\n });\n } finally {\n // A sandbox the caller provisioned is the caller's to dispose.\n if (where.sandbox === undefined) await used.dispose();\n }\n}\n\n/** What every call of one machine shares: the harness, its quorum policy, the approval policy and its rules. */\ninterface Machine<H> {\n readonly harness: Harness<H>;\n readonly quorum: QuorumPolicy;\n readonly approvalPolicy: ApprovalPolicy;\n readonly rules: readonly EscalationRule[];\n}\n\nconst nameOf = <H>(machine: Machine<H>, tool: string): string =>\n machine.harness.registry.get(tool)?.canonicalName ?? tool;\n\n/** Why a denial goes back with no request, or `undefined` when the policy allows one. */\nfunction refusal<H>(machine: Machine<H>, denial: SandboxDenial, tool: string): string | undefined {\n if (machine.approvalPolicy === \"never\") return \"The approval policy is never, so no one was asked.\";\n if (machine.approvalPolicy !== \"granular\") return undefined;\n const rule = machine.rules.find(\n (each) =>\n (each.kind === undefined || each.kind === denial.kind) &&\n (each.tool === undefined || nameOf(machine, each.tool) === nameOf(machine, tool)),\n );\n return rule?.escalate === \"on-request\"\n ? undefined\n : \"No escalation rule lets the host ask about this, so no one was asked.\";\n}\n\n/** The record a request signs, from the run and the denial: the host's facts, never the tool's input alone. */\nfunction recordOf<H>(machine: Machine<H>, call: EscalationRun<H>, denial: SandboxDenial): EscalationRecord {\n const { toolCallId, cwd, timeoutMs, maxOutputBytes } = call;\n return {\n tool: nameOf(machine, call.tool),\n input: call.input,\n initiator: call.initiator ?? \"model\",\n command: [...call.command],\n ...present({ toolCallId, cwd, timeoutMs, maxOutputBytes }),\n root: call.manifest.root,\n policy: call.policy,\n denial: { kind: denial.kind, target: denial.target, reason: denial.reason },\n };\n}\n\n/** Writes the session's start if it lacks one, settles what a crash left open, then signs and writes the request. */\nasync function ask<H>(\n machine: Machine<H>,\n session: Session,\n call: EscalationRun<H>,\n asked: { readonly record: EscalationRecord; readonly widened: SandboxPolicy; readonly walk: Walker },\n): Promise<EscalationResult> {\n const { harness } = machine;\n const { record, widened, walk } = asked;\n const io = ioOf(session, call);\n const id = io.newId();\n await recordSessionStart(harness, (origin, body) => io.write(origin, body), harness.model, await session.path());\n await settleOpen([...escalationsOf(await session.path()).values()], io);\n const reason = what(record.denial);\n const pending = await createPendingRequest(\n {\n kind: \"approval\",\n callId: id,\n tool: ESCALATION_TOOL,\n input: record,\n reason,\n ...present({ app: call.hostContext }),\n },\n harness.signer as NonNullable<Harness<H>[\"signer\"]>,\n { generateId: io.newId, now: () => new Date(io.clock.now()) },\n );\n await io.write(\"harness\", { type: \"approval_requested\", request: pending, input: record });\n walk.step(\"asked\");\n const body = `${reason} A person was asked to allow it once (request ${pending.id}).`;\n return { status: \"awaiting_approval\", escalationId: id, pending, denial: record.denial, widened, ...walk.end(body) };\n}\n\nasync function runCommand<H>(machine: Machine<H>, session: Session, call: EscalationRun<H>): Promise<EscalationResult> {\n if (typeof call?.tool !== \"string\" || call.tool === \"\") throw invalid(\"an escalation run needs the tool's name\");\n const walk = walker(\"sandboxed\");\n const exec = await execIn(call, call.policy, call, call);\n if (!(\"denied\" in exec)) {\n walk.step(\"ran\");\n return { status: \"ran\", exec, rerun: false, states: walk.states, result: ranResult(exec) };\n }\n walk.step(\"denied\");\n const denial = exec.denied;\n const widened = widenPolicy(call.policy, denial);\n const why =\n refusal(machine, denial, call.tool) ??\n (widened === undefined ? \"The policy can't be widened to that, so no one was asked.\" : undefined);\n if (why !== undefined || widened === undefined) {\n walk.step(\"returned\");\n const reason = `${what(denial)} ${why}`;\n return { status: \"denied\", reason, denial, rerun: false, ...walk.end(reason) };\n }\n const record = recordOf(machine, call, denial);\n await hashable(record, \"record\");\n if (call.hostContext !== undefined) await hashable(call.hostContext, \"host context\");\n return inCodeCallQueue(session, () => ask(machine, session, call, { record, widened, walk }));\n}\n\n/** What an answer resolves once it passed its checks: the escalation, its verified record and the rerun's policy. */\ninterface Checked {\n readonly found: EscalationLogRecord;\n readonly record: EscalationRecord;\n readonly widened: SandboxPolicy;\n}\n\n/** Checks an answer against the waiting request before anything is written, and returns the escalation it answers. */\nasync function check<H>(\n machine: Machine<H>,\n path: readonly EscalationLogRecord[],\n resolution: Resolution,\n options: EscalationResolveOptions<H>,\n): Promise<Checked> {\n const { harness } = machine;\n const waiting = path.filter((record) => record.result === undefined && !record.answered && !record.started);\n const byRequest = new Map(waiting.map((record) => [record.requested.request.id, record]));\n checkAnswers(harness, byRequest, [resolution], options.requesterId);\n const found = byRequest.get(resolution.requestId) as EscalationLogRecord;\n const refuse = (cause: string) =>\n new HarnessError(\n \"approval_refused\",\n `the request for escalation ${found.id} failed its check (${cause}), so nothing ran and nothing was written`,\n );\n if (\"decision\" in resolution && resolution.decision === \"allow\") {\n // `by` is not signed, so the guard holds only as far as the host sets it truthfully; an allow that names no one\n // is refused rather than read as a person's.\n const by = typeof resolution.by === \"string\" ? resolution.by.trim().toLowerCase() : \"\";\n if (by === \"\") throw refuse(\"an allow that names no approver does not cover a sandbox rerun\");\n if (by.startsWith(\"classifier:\")) throw refuse(\"a classifier's allow does not cover a sandbox rerun\");\n }\n const verified = await verifyResolution(found.requested.request, resolution, {\n signer: harness.signer as NonNullable<Harness<H>[\"signer\"]>,\n call: { callId: found.id, tool: ESCALATION_TOOL, input: found.requested.input },\n ...present({ app: options.hostContext }),\n });\n if (!verified.ok) throw refuse(verified.cause);\n const record = found.requested.input;\n if (!isEscalationRecord(record)) throw refuse(\"malformed\");\n const widened = widenPolicy(record.policy, record.denial);\n if (widened === undefined) throw refuse(\"not_widenable\");\n if (options.manifest?.root !== record.root) {\n throw invalid(\"the rerun's workspace must have the root the escalation recorded\");\n }\n return { found, record, widened };\n}\n\n/** Decides the call again with the pipeline, which writes the `permission_decision` the rerun starts after. */\nasync function decideAgain<H>(machine: Machine<H>, io: Io, id: string, record: EscalationRecord, hostContext?: H) {\n // bindingOf() refused a harness without a pipeline for every policy that can ask.\n const pipeline = machine.harness.pipeline as NonNullable<Harness<H>[\"pipeline\"]>;\n return pipeline.decide(\n { callId: id, tool: record.tool, input: record.input, initiator: record.initiator },\n { session: { append: (entry) => io.write(\"harness\", entry) }, hostContext, entries: await io.session.path() },\n );\n}\n\n/** Ends an escalation that will not rerun: writes the reason as its result and returns the denial. */\nasync function refuseRerun(io: Io, checked: Checked, walk: Walker, reason: string): Promise<EscalationResult> {\n walk.step(\"refused\");\n const ended = walk.end(reason);\n await writeResult(io, checked.found.id, ended.result, \"quoted\");\n return {\n status: \"denied\",\n reason,\n denial: checked.record.denial,\n rerun: false,\n escalationId: checked.found.id,\n ...ended,\n };\n}\n\nasync function resolveQueued<H>(\n machine: Machine<H>,\n session: Session,\n resolution: Resolution,\n options: EscalationResolveOptions<H>,\n): Promise<EscalationResult> {\n options.signal?.throwIfAborted();\n const io = ioOf(session, options);\n await settleOpen([...escalationsOf(await session.path()).values()], io);\n const path = await session.path();\n const checked = await check(machine, [...escalationsOf(path).values()], resolution, options);\n const { found, record, widened } = checked;\n const walk = walker(\"requested\");\n const outcome = await settled(machine.quorum, [found.requested], answersByRequest(path), [{ resolution }]);\n // The check and the quorum policy may await, so an abort since the call began stops it here, before the answer is\n // written: once it is, the approval is spent, and an abort then can only stop the rerun.\n options.signal?.throwIfAborted();\n for (const entry of outcome.records) await io.write(\"user\", { type: \"approval_resolved\", ...entry });\n const answer = outcome.forRun[0];\n if (answer === undefined) {\n walk.step(\"waiting\");\n const body = `${what(record.denial)} The request waits for more answers.`;\n const pending = found.requested.request;\n return {\n status: \"awaiting_approval\",\n escalationId: found.id,\n pending,\n denial: record.denial,\n widened,\n ...walk.end(body),\n };\n }\n if (!(\"decision\" in answer) || answer.decision !== \"allow\") {\n const why = (\"reason\" in answer ? answer.reason : undefined) ?? \"denied\";\n return refuseRerun(io, checked, walk, `The rerun was not allowed: ${why}.`);\n }\n walk.step(\"allowed\");\n const decision = await decideAgain(machine, io, found.id, record, options.hostContext);\n // A person allowed the rerun, so a question the pipeline would ask again doesn't stop it; a deny does.\n if (decision.decision === \"deny\") {\n return refuseRerun(io, checked, walk, `The permission policy now denies the call: ${decision.reason}`);\n }\n walk.step(\"started\");\n return rerun(io, checked, options, walk);\n}\n\n/** Runs the one rerun in a fresh sandbox under the widened policy, and writes its result. */\nasync function rerun<H>(\n io: Io,\n checked: Checked,\n options: EscalationResolveOptions<H>,\n walk: Walker,\n): Promise<EscalationResult> {\n const id = checked.found.id;\n let exec: ExecResult;\n try {\n exec = await execIn(options, checked.widened, checked.record, options);\n } catch (error) {\n // The rerun started, so it gets a result and is never run again, and the caller still sees why it failed.\n const reason = `The rerun failed: ${error instanceof Error ? error.message : String(error)}`;\n await writeResult(io, id, text(reason, true), \"quoted\");\n throw error;\n }\n walk.step(\"ran\");\n if (\"denied\" in exec) {\n const reason = `${what(exec.denied)} This was the approved rerun, so no one is asked again.`;\n const ended = walk.end(reason);\n await writeResult(io, id, ended.result, \"quoted\");\n return { status: \"denied\", reason, denial: exec.denied, rerun: true, escalationId: id, ...ended };\n }\n await writeResult(\n io,\n id,\n ranResult(exec, (value) => clip(value)),\n \"command\",\n );\n return { status: \"ran\", exec, rerun: true, escalationId: id, states: walk.states, result: ranResult(exec) };\n}\n\n/** The escalations that wait, less the ones the quorum policy says have expired. It writes nothing. */\nasync function pendingOf<H>(machine: Machine<H>, session: Session): Promise<PendingEscalation[]> {\n const path = await session.path();\n const answers = answersByRequest(path);\n const found: PendingEscalation[] = [];\n for (const { id, requested } of waitingEscalations(path)) {\n if (!isEscalationRecord(requested.input)) continue;\n const verdict = await machine.quorum.evaluate(requested.request, answers.get(requested.request.id) ?? []);\n if (verdict === \"expired\") continue;\n found.push({ escalationId: id, request: requested.request, record: requested.input });\n }\n return found;\n}\n\n/**\n * Creates the escalation machine for a harness's approvals. Throws `invalid_escalation` for unusable options, and\n * `approval_unavailable` when a policy that can ask has a harness with no signer.\n */\nexport function escalation<H = unknown>(options: EscalationOptions<H>): EscalationMachine<H> {\n const { harness, quorum } = bindingOf(options);\n const machine: Machine<H> = {\n harness,\n quorum,\n approvalPolicy: options.approvalPolicy,\n rules: options.granular ?? [],\n };\n return {\n approvalPolicy: options.approvalPolicy,\n transitions: ESCALATION_TRANSITIONS,\n run: (session, call) => runCommand(machine, session, call),\n pending: (session) => pendingOf(machine, session),\n resolve(session, resolution, resolveOptions) {\n return inCodeCallQueue(session, () => resolveQueued(machine, session, resolution, resolveOptions));\n },\n };\n}\n"]}
|
package/dist/sandbox/index.d.ts
CHANGED
|
@@ -1,9 +1,12 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* `@buildanagent/harness/sandbox`: the sandbox interface, the unsafe `none` backend, `spawnEnv()`,
|
|
3
|
-
*
|
|
4
|
-
* conformance suite are in `./testing`.
|
|
2
|
+
* `@buildanagent/harness/sandbox`: the sandbox interface, the unsafe `none` backend, `spawnEnv()`, the policy read-back and
|
|
3
|
+
* capability helpers, and `escalation()`, the host's state machine for a denied command. The `srt` and Docker backends
|
|
4
|
+
* have their own subpaths. `fakeSandbox()` and the conformance suite are in `./testing`.
|
|
5
5
|
*/
|
|
6
|
+
export { ESCALATION_TOOL, type EscalationRecord } from "../session/escalation-log.js";
|
|
6
7
|
export { SandboxDeniedError, SandboxPolicyMismatchError, SandboxUnavailableError, SandboxUnsupportedError, } from "./errors.js";
|
|
8
|
+
export { type EscalationMachine, type EscalationOptions, type EscalationResolveOptions, type EscalationResult, type EscalationRule, type EscalationRun, escalation, type PendingEscalation, } from "./escalation.js";
|
|
9
|
+
export { ESCALATION_EVENTS, ESCALATION_STATES, ESCALATION_TRANSITIONS, type EscalationEvent, type EscalationState, type EscalationTransition, nextEscalationState, } from "./escalation-table.js";
|
|
7
10
|
export { NONE_SANDBOX_WARNING, type NoneSandboxOptions, noneSandbox } from "./none.js";
|
|
8
11
|
export { confirmPolicy, hasCapability, pauseSandbox, policyDifference, resumeSandbox, snapshotSandbox, stopsFor, } from "./policy.js";
|
|
9
12
|
export { spawnEnv } from "./spawn-env.js";
|
package/dist/sandbox/index.js
CHANGED
|
@@ -1,9 +1,12 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* `@buildanagent/harness/sandbox`: the sandbox interface, the unsafe `none` backend, `spawnEnv()`,
|
|
3
|
-
*
|
|
4
|
-
* conformance suite are in `./testing`.
|
|
2
|
+
* `@buildanagent/harness/sandbox`: the sandbox interface, the unsafe `none` backend, `spawnEnv()`, the policy read-back and
|
|
3
|
+
* capability helpers, and `escalation()`, the host's state machine for a denied command. The `srt` and Docker backends
|
|
4
|
+
* have their own subpaths. `fakeSandbox()` and the conformance suite are in `./testing`.
|
|
5
5
|
*/
|
|
6
|
+
export { ESCALATION_TOOL } from "../session/escalation-log.js";
|
|
6
7
|
export { SandboxDeniedError, SandboxPolicyMismatchError, SandboxUnavailableError, SandboxUnsupportedError, } from "./errors.js";
|
|
8
|
+
export { escalation, } from "./escalation.js";
|
|
9
|
+
export { ESCALATION_EVENTS, ESCALATION_STATES, ESCALATION_TRANSITIONS, nextEscalationState, } from "./escalation-table.js";
|
|
7
10
|
export { NONE_SANDBOX_WARNING, noneSandbox } from "./none.js";
|
|
8
11
|
export { confirmPolicy, hasCapability, pauseSandbox, policyDifference, resumeSandbox, snapshotSandbox, stopsFor, } from "./policy.js";
|
|
9
12
|
export { spawnEnv } from "./spawn-env.js";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/sandbox/index.ts"],"names":[],"mappings":"AAAA;;;;GAIG;
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/sandbox/index.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH,OAAO,EAAE,eAAe,EAAyB,MAAM,8BAA8B,CAAC;AACtF,OAAO,EACL,kBAAkB,EAClB,0BAA0B,EAC1B,uBAAuB,EACvB,uBAAuB,GACxB,MAAM,aAAa,CAAC;AACrB,OAAO,EAOL,UAAU,GAEX,MAAM,iBAAiB,CAAC;AACzB,OAAO,EACL,iBAAiB,EACjB,iBAAiB,EACjB,sBAAsB,EAItB,mBAAmB,GACpB,MAAM,uBAAuB,CAAC;AAC/B,OAAO,EAAE,oBAAoB,EAA2B,WAAW,EAAE,MAAM,WAAW,CAAC;AACvF,OAAO,EACL,aAAa,EACb,aAAa,EACb,YAAY,EACZ,gBAAgB,EAChB,aAAa,EACb,eAAe,EACf,QAAQ,GACT,MAAM,aAAa,CAAC;AACrB,OAAO,EAAE,QAAQ,EAAE,MAAM,gBAAgB,CAAC","sourcesContent":["/**\n * `@buildanagent/harness/sandbox`: the sandbox interface, the unsafe `none` backend, `spawnEnv()`, the policy read-back and\n * capability helpers, and `escalation()`, the host's state machine for a denied command. The `srt` and Docker backends\n * have their own subpaths. `fakeSandbox()` and the conformance suite are in `./testing`.\n */\n\nexport { ESCALATION_TOOL, type EscalationRecord } from \"../session/escalation-log.js\";\nexport {\n SandboxDeniedError,\n SandboxPolicyMismatchError,\n SandboxUnavailableError,\n SandboxUnsupportedError,\n} from \"./errors.js\";\nexport {\n type EscalationMachine,\n type EscalationOptions,\n type EscalationResolveOptions,\n type EscalationResult,\n type EscalationRule,\n type EscalationRun,\n escalation,\n type PendingEscalation,\n} from \"./escalation.js\";\nexport {\n ESCALATION_EVENTS,\n ESCALATION_STATES,\n ESCALATION_TRANSITIONS,\n type EscalationEvent,\n type EscalationState,\n type EscalationTransition,\n nextEscalationState,\n} from \"./escalation-table.js\";\nexport { NONE_SANDBOX_WARNING, type NoneSandboxOptions, noneSandbox } from \"./none.js\";\nexport {\n confirmPolicy,\n hasCapability,\n pauseSandbox,\n policyDifference,\n resumeSandbox,\n snapshotSandbox,\n stopsFor,\n} from \"./policy.js\";\nexport { spawnEnv } from \"./spawn-env.js\";\nexport type {\n ApprovalPolicy,\n ExecOptions,\n ExecResult,\n Sandbox,\n SandboxCapability,\n SandboxClient,\n SandboxDenial,\n SandboxPolicy,\n SandboxStop,\n SandboxTier,\n WorkspaceManifest,\n} from \"./types.js\";\n"]}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import type { SandboxDenial, SandboxPolicy } from "./types.js";
|
|
2
|
+
/** True when `value` has the shape of a `SandboxDenial`. A record read from the log is checked with it. */
|
|
3
|
+
export declare function isDenial(value: unknown): value is SandboxDenial;
|
|
4
|
+
/**
|
|
5
|
+
* `policy` with exactly the denial's target added, or `undefined` when the denial can't be widened: a path that is the
|
|
6
|
+
* root, relative or untidy, a host with a wildcard or anything but a host and port, an address in a form other than
|
|
7
|
+
* its canonical one, a host that reaches the machine itself or its link (see `isWidenableHost()`), or a host an entry
|
|
8
|
+
* of the policy's own `network.deny` closes (see `isClosed()`), since the host closed it on purpose.
|
|
9
|
+
*/
|
|
10
|
+
export declare function widenPolicy(policy: SandboxPolicy, denial: SandboxDenial): SandboxPolicy | undefined;
|
|
@@ -0,0 +1,150 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The one place a sandbox policy grows: by exactly the path or host one denial named, and never to host-wide access.
|
|
3
|
+
* Only the escalation runner calls it, with the denial from a verified, signed record and the policy that record
|
|
4
|
+
* holds. No tool input or model output reaches it.
|
|
5
|
+
*/
|
|
6
|
+
import { ipv4Of, isAddressLiteral, isLocalAddress } from "../credentials/addresses.js";
|
|
7
|
+
// A plain host name or address with an optional port: no wildcard, no scheme, no path and no user.
|
|
8
|
+
const HOST = /^(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*(?::[0-9]{1,5})?$/;
|
|
9
|
+
const IPV6 = /^\[[0-9a-f:.]+\](?::[0-9]{1,5})?$/;
|
|
10
|
+
/** True for an absolute POSIX path in its tidy form, below the root: no `.`, `..`, empty segment or NUL. */
|
|
11
|
+
function isWidenablePath(target) {
|
|
12
|
+
if (!target.startsWith("/") || target === "/" || target.includes("\u0000"))
|
|
13
|
+
return false;
|
|
14
|
+
const parts = target.slice(1).split("/");
|
|
15
|
+
return parts.every((part) => part !== "" && part !== "." && part !== "..");
|
|
16
|
+
}
|
|
17
|
+
// Names that resolve to the host itself on common systems without asking DNS.
|
|
18
|
+
const LOCAL_NAMES = ["localhost", "localhost.localdomain", "ip6-localhost", "ip6-loopback"];
|
|
19
|
+
// A last label that a URL parser or `inet_aton()` reads as a number, which makes the whole host an IPv4 address.
|
|
20
|
+
const NUMERIC_LABEL = /^(?:0x[0-9a-f]*|[0-9]+)$/;
|
|
21
|
+
/**
|
|
22
|
+
* True for a host and optional port that a rerun may be allowed to reach. An address must be written in its one
|
|
23
|
+
* canonical form, so it can be compared with a deny entry: an IPv4 address as four decimal octets with no leading
|
|
24
|
+
* zero, and an IPv6 address that does not wrap an IPv4 one. A host whose last label is a number is an IPv4 address, so
|
|
25
|
+
* `127.1`, `2130706433` and `0x7f.1` are refused rather than read as names. A host that reaches the machine itself or
|
|
26
|
+
* its link is never widened, whatever `deny` says: `localhost` and the names under it, and the unspecified, loopback
|
|
27
|
+
* and link-local addresses, which hold the cloud metadata address.
|
|
28
|
+
*/
|
|
29
|
+
function isWidenableHost(target) {
|
|
30
|
+
if (target.length > 255)
|
|
31
|
+
return false;
|
|
32
|
+
const host = hostOf(target);
|
|
33
|
+
if (IPV6.test(target))
|
|
34
|
+
return isAddressLiteral(host) && ipv4Of(host) === undefined && !isLocalAddress(host);
|
|
35
|
+
if (!HOST.test(target))
|
|
36
|
+
return false;
|
|
37
|
+
if (LOCAL_NAMES.includes(host) || host.endsWith(".localhost"))
|
|
38
|
+
return false;
|
|
39
|
+
const last = host.slice(host.lastIndexOf(".") + 1);
|
|
40
|
+
if (NUMERIC_LABEL.test(last))
|
|
41
|
+
return isAddressLiteral(host) && !isLocalAddress(host);
|
|
42
|
+
return true;
|
|
43
|
+
}
|
|
44
|
+
const KINDS = ["filesystem_read", "filesystem_write", "network"];
|
|
45
|
+
/** True when `value` has the shape of a `SandboxDenial`. A record read from the log is checked with it. */
|
|
46
|
+
export function isDenial(value) {
|
|
47
|
+
if (typeof value !== "object" || value === null)
|
|
48
|
+
return false;
|
|
49
|
+
const denial = value;
|
|
50
|
+
return (KINDS.includes(denial.kind) && typeof denial.target === "string" && typeof denial.reason === "string");
|
|
51
|
+
}
|
|
52
|
+
/** The host of a host-and-port entry, in lower case: brackets off an IPv6 address, and any `:port` and trailing dot off. */
|
|
53
|
+
function hostOf(entry) {
|
|
54
|
+
const lower = entry.trim().toLowerCase();
|
|
55
|
+
if (lower.startsWith("[")) {
|
|
56
|
+
const close = lower.indexOf("]");
|
|
57
|
+
return close < 0 ? lower : lower.slice(1, close);
|
|
58
|
+
}
|
|
59
|
+
const colon = lower.lastIndexOf(":");
|
|
60
|
+
// Two or more colons are an IPv6 address without brackets, which has no port to take off.
|
|
61
|
+
const host = colon >= 0 && lower.indexOf(":") === colon ? lower.slice(0, colon) : lower;
|
|
62
|
+
return host.endsWith(".") ? host.slice(0, -1) : host;
|
|
63
|
+
}
|
|
64
|
+
const isIpv6 = (host) => host.includes(":");
|
|
65
|
+
/** One part of an IPv4 address as `inet_aton()` reads it: decimal, octal after a `0`, or hex after `0x`. */
|
|
66
|
+
function looseOctets(part) {
|
|
67
|
+
if (/^0x[0-9a-f]*$/.test(part))
|
|
68
|
+
return part.length === 2 ? 0 : Number.parseInt(part.slice(2), 16);
|
|
69
|
+
if (/^0[0-7]+$/.test(part))
|
|
70
|
+
return Number.parseInt(part, 8);
|
|
71
|
+
return /^(?:0|[1-9][0-9]*)$/.test(part) ? Number(part) : undefined;
|
|
72
|
+
}
|
|
73
|
+
/**
|
|
74
|
+
* The IPv4 address a deny entry's host names in any form `inet_aton()` accepts (`127.1`, `2130706433`, `0x7f.0.0.1`,
|
|
75
|
+
* `0177.0.0.1`), or in an IPv6 form that wraps one, as a number. `undefined` when it names no IPv4 address.
|
|
76
|
+
*/
|
|
77
|
+
function denyIpv4(pattern) {
|
|
78
|
+
if (isIpv6(pattern))
|
|
79
|
+
return ipv4Of(pattern);
|
|
80
|
+
const parts = pattern.split(".");
|
|
81
|
+
if (parts.length > 4)
|
|
82
|
+
return undefined;
|
|
83
|
+
const values = [];
|
|
84
|
+
for (const part of parts) {
|
|
85
|
+
const value = looseOctets(part);
|
|
86
|
+
if (value === undefined || !Number.isSafeInteger(value))
|
|
87
|
+
return undefined;
|
|
88
|
+
values.push(value);
|
|
89
|
+
}
|
|
90
|
+
const last = values.pop();
|
|
91
|
+
if (values.some((value) => value > 255) || last >= 256 ** (4 - values.length))
|
|
92
|
+
return undefined;
|
|
93
|
+
return values.reduce((sum, value, index) => sum + value * 256 ** (3 - index), 0) + last;
|
|
94
|
+
}
|
|
95
|
+
/**
|
|
96
|
+
* True when an entry of `deny` closes `target` on some port. An entry matches as `srt` matches a denied domain: `*`
|
|
97
|
+
* matches every host, `*.name` every name under `name` but not `name` itself, and any other entry the host alone, with
|
|
98
|
+
* case ignored. A `*.name` entry also closes an IPv4 address that ends in `.name`, which `srt` would not match. That
|
|
99
|
+
* errs towards not asking. An entry's port is ignored, so a host closed on one port is never widened on any. An IPv4
|
|
100
|
+
* target is closed by an entry that names the same address in any spelling, such as `127.1`, `2130706433` or an IPv6
|
|
101
|
+
* form that wraps it. An IPv6 address counts as closed while `deny` names any IPv6 address, because one address has
|
|
102
|
+
* many spellings. A loopback or link-local entry needs no rule of its own: `isWidenableHost()` refuses every such
|
|
103
|
+
* target. A name that DNS resolves to a closed address can't be seen here; the backend's own deny list covers it.
|
|
104
|
+
*/
|
|
105
|
+
function isClosed(deny, target) {
|
|
106
|
+
const host = hostOf(target);
|
|
107
|
+
const address = isIpv6(host) ? undefined : ipv4Of(host);
|
|
108
|
+
return deny.some((entry) => {
|
|
109
|
+
const pattern = hostOf(entry);
|
|
110
|
+
if (pattern === "*")
|
|
111
|
+
return true;
|
|
112
|
+
if (isIpv6(host))
|
|
113
|
+
return isIpv6(pattern);
|
|
114
|
+
if (address !== undefined && denyIpv4(pattern) === address)
|
|
115
|
+
return true;
|
|
116
|
+
if (pattern.startsWith("*."))
|
|
117
|
+
return host.endsWith(pattern.slice(1));
|
|
118
|
+
return host === pattern;
|
|
119
|
+
});
|
|
120
|
+
}
|
|
121
|
+
const plus = (list, item) => (list.includes(item) ? [...list] : [...list, item]);
|
|
122
|
+
/**
|
|
123
|
+
* `policy` with exactly the denial's target added, or `undefined` when the denial can't be widened: a path that is the
|
|
124
|
+
* root, relative or untidy, a host with a wildcard or anything but a host and port, an address in a form other than
|
|
125
|
+
* its canonical one, a host that reaches the machine itself or its link (see `isWidenableHost()`), or a host an entry
|
|
126
|
+
* of the policy's own `network.deny` closes (see `isClosed()`), since the host closed it on purpose.
|
|
127
|
+
*/
|
|
128
|
+
export function widenPolicy(policy, denial) {
|
|
129
|
+
const { readRoots, writeRoots, network } = policy;
|
|
130
|
+
const base = {
|
|
131
|
+
readRoots: [...readRoots],
|
|
132
|
+
writeRoots: [...writeRoots],
|
|
133
|
+
network: { allow: [...network.allow], deny: [...network.deny] },
|
|
134
|
+
};
|
|
135
|
+
switch (denial.kind) {
|
|
136
|
+
case "filesystem_read":
|
|
137
|
+
return isWidenablePath(denial.target) ? { ...base, readRoots: plus(readRoots, denial.target) } : undefined;
|
|
138
|
+
case "filesystem_write":
|
|
139
|
+
return isWidenablePath(denial.target) ? { ...base, writeRoots: plus(writeRoots, denial.target) } : undefined;
|
|
140
|
+
case "network": {
|
|
141
|
+
const host = denial.target;
|
|
142
|
+
if (!isWidenableHost(host) || isClosed(network.deny, host))
|
|
143
|
+
return undefined;
|
|
144
|
+
return { ...base, network: { ...base.network, allow: plus(network.allow, host) } };
|
|
145
|
+
}
|
|
146
|
+
default:
|
|
147
|
+
return undefined;
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
//# sourceMappingURL=widen.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"widen.js","sourceRoot":"","sources":["../../src/sandbox/widen.ts"],"names":[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eAAe,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,EAAE,GAAG,IAAI,EAAE,UAAU,EAAE,IAAI,CAAC,UAAU,EAAE,MAAM,CAAC,MAAM,CAAC,EAAE,CAAC,CAAC,CAAC,SAAS,CAAC;QAC/G,KAAK,SAAS,EAAE,CAAC;YACf,MAAM,IAAI,GAAG,MAAM,CAAC,MAAM,CAAC;YAC3B,IAAI,CAAC,eAAe,CAAC,IAAI,CAAC,IAAI,QAAQ,CAAC,OAAO,CAAC,IAAI,EAAE,IAAI,CAAC;gBAAE,OAAO,SAAS,CAAC;YAC7E,OAAO,EAAE,GAAG,IAAI,EAAE,OAAO,EAAE,EAAE,GAAG,IAAI,CAAC,OAAO,EAAE,KAAK,EAAE,IAAI,CAAC,OAAO,CAAC,KAAK,EAAE,IAAI,CAAC,EAAE,EAAE,CAAC;QACrF,CAAC;QACD;YACE,OAAO,SAAS,CAAC;IACrB,CAAC;AACH,CAAC","sourcesContent":["/**\n * The one place a sandbox policy grows: by exactly the path or host one denial named, and never to host-wide access.\n * Only the escalation runner calls it, with the denial from a verified, signed record and the policy that record\n * holds. No tool input or model output reaches it.\n */\nimport { ipv4Of, isAddressLiteral, isLocalAddress } from \"../credentials/addresses.js\";\nimport type { SandboxDenial, SandboxPolicy } from \"./types.js\";\n\n// A plain host name or address with an optional port: no wildcard, no scheme, no path and no user.\nconst HOST = /^(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)(?:\\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*(?::[0-9]{1,5})?$/;\nconst IPV6 = /^\\[[0-9a-f:.]+\\](?::[0-9]{1,5})?$/;\n\n/** True for an absolute POSIX path in its tidy form, below the root: no `.`, `..`, empty segment or NUL. */\nfunction isWidenablePath(target: string): boolean {\n if (!target.startsWith(\"/\") || target === \"/\" || target.includes(\"\\u0000\")) return false;\n const parts = target.slice(1).split(\"/\");\n return parts.every((part) => part !== \"\" && part !== \".\" && part !== \"..\");\n}\n\n// Names that resolve to the host itself on common systems without asking DNS.\nconst LOCAL_NAMES: readonly string[] = [\"localhost\", \"localhost.localdomain\", \"ip6-localhost\", \"ip6-loopback\"];\n// A last label that a URL parser or `inet_aton()` reads as a number, which makes the whole host an IPv4 address.\nconst NUMERIC_LABEL = /^(?:0x[0-9a-f]*|[0-9]+)$/;\n\n/**\n * True for a host and optional port that a rerun may be allowed to reach. An address must be written in its one\n * canonical form, so it can be compared with a deny entry: an IPv4 address as four decimal octets with no leading\n * zero, and an IPv6 address that does not wrap an IPv4 one. A host whose last label is a number is an IPv4 address, so\n * `127.1`, `2130706433` and `0x7f.1` are refused rather than read as names. A host that reaches the machine itself or\n * its link is never widened, whatever `deny` says: `localhost` and the names under it, and the unspecified, loopback\n * and link-local addresses, which hold the cloud metadata address.\n */\nfunction isWidenableHost(target: string): boolean {\n if (target.length > 255) return false;\n const host = hostOf(target);\n if (IPV6.test(target)) return isAddressLiteral(host) && ipv4Of(host) === undefined && !isLocalAddress(host);\n if (!HOST.test(target)) return false;\n if (LOCAL_NAMES.includes(host) || host.endsWith(\".localhost\")) return false;\n const last = host.slice(host.lastIndexOf(\".\") + 1);\n if (NUMERIC_LABEL.test(last)) return isAddressLiteral(host) && !isLocalAddress(host);\n return true;\n}\n\nconst KINDS: readonly string[] = [\"filesystem_read\", \"filesystem_write\", \"network\"];\n\n/** True when `value` has the shape of a `SandboxDenial`. A record read from the log is checked with it. */\nexport function isDenial(value: unknown): value is SandboxDenial {\n if (typeof value !== \"object\" || value === null) return false;\n const denial = value as Record<string, unknown>;\n return (\n KINDS.includes(denial.kind as string) && typeof denial.target === \"string\" && typeof denial.reason === \"string\"\n );\n}\n\n/** The host of a host-and-port entry, in lower case: brackets off an IPv6 address, and any `:port` and trailing dot off. */\nfunction hostOf(entry: string): string {\n const lower = entry.trim().toLowerCase();\n if (lower.startsWith(\"[\")) {\n const close = lower.indexOf(\"]\");\n return close < 0 ? lower : lower.slice(1, close);\n }\n const colon = lower.lastIndexOf(\":\");\n // Two or more colons are an IPv6 address without brackets, which has no port to take off.\n const host = colon >= 0 && lower.indexOf(\":\") === colon ? lower.slice(0, colon) : lower;\n return host.endsWith(\".\") ? host.slice(0, -1) : host;\n}\n\nconst isIpv6 = (host: string): boolean => host.includes(\":\");\n\n/** One part of an IPv4 address as `inet_aton()` reads it: decimal, octal after a `0`, or hex after `0x`. */\nfunction looseOctets(part: string): number | undefined {\n if (/^0x[0-9a-f]*$/.test(part)) return part.length === 2 ? 0 : Number.parseInt(part.slice(2), 16);\n if (/^0[0-7]+$/.test(part)) return Number.parseInt(part, 8);\n return /^(?:0|[1-9][0-9]*)$/.test(part) ? Number(part) : undefined;\n}\n\n/**\n * The IPv4 address a deny entry's host names in any form `inet_aton()` accepts (`127.1`, `2130706433`, `0x7f.0.0.1`,\n * `0177.0.0.1`), or in an IPv6 form that wraps one, as a number. `undefined` when it names no IPv4 address.\n */\nfunction denyIpv4(pattern: string): number | undefined {\n if (isIpv6(pattern)) return ipv4Of(pattern);\n const parts = pattern.split(\".\");\n if (parts.length > 4) return undefined;\n const values: number[] = [];\n for (const part of parts) {\n const value = looseOctets(part);\n if (value === undefined || !Number.isSafeInteger(value)) return undefined;\n values.push(value);\n }\n const last = values.pop() as number;\n if (values.some((value) => value > 255) || last >= 256 ** (4 - values.length)) return undefined;\n return values.reduce((sum, value, index) => sum + value * 256 ** (3 - index), 0) + last;\n}\n\n/**\n * True when an entry of `deny` closes `target` on some port. An entry matches as `srt` matches a denied domain: `*`\n * matches every host, `*.name` every name under `name` but not `name` itself, and any other entry the host alone, with\n * case ignored. A `*.name` entry also closes an IPv4 address that ends in `.name`, which `srt` would not match. That\n * errs towards not asking. An entry's port is ignored, so a host closed on one port is never widened on any. An IPv4\n * target is closed by an entry that names the same address in any spelling, such as `127.1`, `2130706433` or an IPv6\n * form that wraps it. An IPv6 address counts as closed while `deny` names any IPv6 address, because one address has\n * many spellings. A loopback or link-local entry needs no rule of its own: `isWidenableHost()` refuses every such\n * target. A name that DNS resolves to a closed address can't be seen here; the backend's own deny list covers it.\n */\nfunction isClosed(deny: readonly string[], target: string): boolean {\n const host = hostOf(target);\n const address = isIpv6(host) ? undefined : ipv4Of(host);\n return deny.some((entry) => {\n const pattern = hostOf(entry);\n if (pattern === \"*\") return true;\n if (isIpv6(host)) return isIpv6(pattern);\n if (address !== undefined && denyIpv4(pattern) === address) return true;\n if (pattern.startsWith(\"*.\")) return host.endsWith(pattern.slice(1));\n return host === pattern;\n });\n}\n\nconst plus = (list: readonly string[], item: string): string[] => (list.includes(item) ? [...list] : [...list, item]);\n\n/**\n * `policy` with exactly the denial's target added, or `undefined` when the denial can't be widened: a path that is the\n * root, relative or untidy, a host with a wildcard or anything but a host and port, an address in a form other than\n * its canonical one, a host that reaches the machine itself or its link (see `isWidenableHost()`), or a host an entry\n * of the policy's own `network.deny` closes (see `isClosed()`), since the host closed it on purpose.\n */\nexport function widenPolicy(policy: SandboxPolicy, denial: SandboxDenial): SandboxPolicy | undefined {\n const { readRoots, writeRoots, network } = policy;\n const base = {\n readRoots: [...readRoots],\n writeRoots: [...writeRoots],\n network: { allow: [...network.allow], deny: [...network.deny] },\n };\n switch (denial.kind) {\n case \"filesystem_read\":\n return isWidenablePath(denial.target) ? { ...base, readRoots: plus(readRoots, denial.target) } : undefined;\n case \"filesystem_write\":\n return isWidenablePath(denial.target) ? { ...base, writeRoots: plus(writeRoots, denial.target) } : undefined;\n case \"network\": {\n const host = denial.target;\n if (!isWidenableHost(host) || isClosed(network.deny, host)) return undefined;\n return { ...base, network: { ...base.network, allow: plus(network.allow, host) } };\n }\n default:\n return undefined;\n }\n}\n"]}
|
|
@@ -1,7 +1,17 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `createApprovals()`: the pause and resume of a call that waits for a person. A gate `ask` ends a turn
|
|
3
|
+
* `awaiting_approval` with the signed request in the log, as an `approval_requested` entry written before the harness's
|
|
4
|
+
* own observers hear of it, and a code call that asks writes the same entry. `pending()` reads the requests that still
|
|
5
|
+
* wait, and `resolve()` answers them from any process that can open the session and load the key ring, because the log
|
|
6
|
+
* holds everything the resume needs. A turn's answers resume the turn; a code call's answer runs the call with no model
|
|
7
|
+
* step. An answer may also cover more than its own call (sticky and grouped answers), and a quorum policy may need
|
|
8
|
+
* several answers before a call runs.
|
|
9
|
+
*/
|
|
10
|
+
import type { SessionEntry } from "@buildanagent/protocol";
|
|
1
11
|
import type { Resolution, SignedPendingRequest } from "@buildanagent/sdk";
|
|
2
12
|
import type { CodeCallResult, Harness } from "../harness.js";
|
|
3
13
|
import { type PendingApproval } from "./rebuild.js";
|
|
4
|
-
import { type ResumeOptions, type TurnResult } from "./runner.js";
|
|
14
|
+
import { type ResolutionRecord, type ResumeOptions, type TurnResult } from "./runner.js";
|
|
5
15
|
import type { Session } from "./session.js";
|
|
6
16
|
/** What a quorum policy says about one request: its answers are enough, not yet, a refusal, or too old. */
|
|
7
17
|
export type QuorumVerdict = "met" | "pending" | "rejected" | "expired";
|
|
@@ -77,5 +87,24 @@ export interface Approvals<H = unknown> {
|
|
|
77
87
|
*/
|
|
78
88
|
resolve(session: Session, resolutions: readonly Resolution[], options?: ResolveOptions<H>): Promise<TurnResult | CodeCallResult>;
|
|
79
89
|
}
|
|
90
|
+
/** The answers already written for each request, oldest first. */
|
|
91
|
+
export declare function answersByRequest(path: readonly SessionEntry[]): Map<string, Resolution[]>;
|
|
92
|
+
/** Refuses an answer set that can't be applied: no signer, an answer twice, a request that doesn't wait, a self-approval. */
|
|
93
|
+
export declare function checkAnswers<H>(harness: Harness<H>, waiting: ReadonlyMap<string, unknown>, resolutions: readonly Resolution[], requesterId: string | undefined): void;
|
|
94
|
+
/**
|
|
95
|
+
* What each waiting request gets once the quorum policy has looked at it: the answer the SDK applies for `met`, a denial
|
|
96
|
+
* for `rejected` and `expired`, and nothing for `pending`, whose new answers are marked as waited on so a crash
|
|
97
|
+
* of this resume never counts them as given. The records returned are the entries to write, denials by the policy
|
|
98
|
+
* included, so the log tells an expiry from any other refusal.
|
|
99
|
+
*/
|
|
100
|
+
export declare function settled(policy: QuorumPolicy, waiting: readonly Pick<PendingApproval, "request">[], earlier: ReadonlyMap<string, Resolution[]>, records: readonly ResolutionRecord[]): Promise<{
|
|
101
|
+
forRun: Resolution[];
|
|
102
|
+
records: ResolutionRecord[];
|
|
103
|
+
}>;
|
|
104
|
+
/** The harness and quorum policy `approvals` was made with, or `undefined` for one `createApprovals()` did not make. */
|
|
105
|
+
export declare function approvalsBinding<H>(approvals: Approvals<H>): {
|
|
106
|
+
readonly harness: Harness<H>;
|
|
107
|
+
readonly quorum: QuorumPolicy;
|
|
108
|
+
} | undefined;
|
|
80
109
|
/** Creates the approvals of `harness`, which needs a `signer` to check the requests it resumes. */
|
|
81
110
|
export declare function createApprovals<H = unknown>(harness: Harness<H>, settings?: ApprovalsOptions): Approvals<H>;
|
|
@@ -48,7 +48,7 @@ function expandGroup(resolutions, groups, groupOf) {
|
|
|
48
48
|
return [...out.values()];
|
|
49
49
|
}
|
|
50
50
|
/** The answers already written for each request, oldest first. */
|
|
51
|
-
function answersByRequest(path) {
|
|
51
|
+
export function answersByRequest(path) {
|
|
52
52
|
const answers = new Map();
|
|
53
53
|
for (const entry of path) {
|
|
54
54
|
if (entry.type === "approval_resolved") {
|
|
@@ -58,7 +58,7 @@ function answersByRequest(path) {
|
|
|
58
58
|
return answers;
|
|
59
59
|
}
|
|
60
60
|
/** Refuses an answer set that can't be applied: no signer, an answer twice, a request that doesn't wait, a self-approval. */
|
|
61
|
-
function checkAnswers(harness, waiting, resolutions, requesterId) {
|
|
61
|
+
export function checkAnswers(harness, waiting, resolutions, requesterId) {
|
|
62
62
|
if (harness.signer === undefined) {
|
|
63
63
|
throw new HarnessError("approval_unavailable", "the harness has no signer, so no approval can be checked");
|
|
64
64
|
}
|
|
@@ -109,7 +109,7 @@ function outcomeOf(verdict, requestId, answers, fresh) {
|
|
|
109
109
|
* of this resume never counts them as given. The records returned are the entries to write, denials by the policy
|
|
110
110
|
* included, so the log tells an expiry from any other refusal.
|
|
111
111
|
*/
|
|
112
|
-
async function settled(policy, waiting, earlier, records) {
|
|
112
|
+
export async function settled(policy, waiting, earlier, records) {
|
|
113
113
|
const forRun = [];
|
|
114
114
|
const out = [];
|
|
115
115
|
for (const { request } of waiting) {
|
|
@@ -122,10 +122,16 @@ async function settled(policy, waiting, earlier, records) {
|
|
|
122
122
|
}
|
|
123
123
|
return { forRun, records: out };
|
|
124
124
|
}
|
|
125
|
+
/** The harness and quorum policy each `Approvals` was made with, so a sandbox escalation shares them. */
|
|
126
|
+
const made = new WeakMap();
|
|
127
|
+
/** The harness and quorum policy `approvals` was made with, or `undefined` for one `createApprovals()` did not make. */
|
|
128
|
+
export function approvalsBinding(approvals) {
|
|
129
|
+
return made.get(approvals);
|
|
130
|
+
}
|
|
125
131
|
/** Creates the approvals of `harness`, which needs a `signer` to check the requests it resumes. */
|
|
126
132
|
export function createApprovals(harness, settings = {}) {
|
|
127
133
|
const policy = settings.quorum ?? oneResolution;
|
|
128
|
-
|
|
134
|
+
const approvals = {
|
|
129
135
|
async pending(session) {
|
|
130
136
|
const path = await session.path();
|
|
131
137
|
return [...pendingApprovals(path), ...pendingCodeCalls(path).map(({ request, input }) => ({ request, input }))];
|
|
@@ -150,6 +156,8 @@ export function createApprovals(harness, settings = {}) {
|
|
|
150
156
|
return resumeTurn(session, harness, { ...options, resolutions: forRun, records: toWrite });
|
|
151
157
|
},
|
|
152
158
|
};
|
|
159
|
+
made.set(approvals, { harness: harness, quorum: policy });
|
|
160
|
+
return approvals;
|
|
153
161
|
}
|
|
154
162
|
const nameOf = (harness, tool) => harness.registry.get(tool)?.canonicalName ?? tool;
|
|
155
163
|
const reuseOf = (harness, tool) => harness.registry.get(tool)?.approvalReuse ?? "both";
|