From 46c78c2766c6620c2ea7336e8ff15a228963cb31 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Mon, 2 Nov 2026 23:20:28 +0000 Subject: [PATCH 1/2] CONTRACT: fix(ui-server): exempt validated provider-relay requests from session taint (#3246) A validated request through the brain CLI's provider relay no longer taints a governed session, and taint no longer narrows it (maintainer option C on #3246). Reranking and WebFetch now work in either order. The proxy tags the operation by the relay that sent it. Worker HTTP and CONNECT traffic has no relay tag and cannot claim the exemption, even to a provider's host. Turn egress records neither a taint nor a contacted host for the operation. Deny and allowlist rules, origin, route and recipient authorization, byte ceilings, budgets, cancellation and accounting still apply. Breaking before 1.0: documented taint-policy semantics change, with no event, configuration or wire shape change. Recorded in the integration contract, supported inputs, the G6 and #1673 decision sections (dated supersession), the hosting doc and the capability note. Refs #3246 Co-Authored-By: Claude Opus 5.5 --- .changeset/provider-relay-taint-exemption.md | 7 + docs/decisions/governed-writable-workers.md | 62 +++++- docs/hosting/agent-workers.md | 13 +- docs/integration-contract.md | 25 +++ docs/supported-inputs.md | 2 +- packages/ui-sdk/src/server/egress-proxy.ts | 35 ++-- packages/ui-sdk/src/server/outward-policy.ts | 4 +- packages/ui-sdk/tests/egress-proxy.test.ts | 13 +- packages/ui-sdk/tests/outward-actions.test.ts | 5 +- packages/ui-server/src/brain/turn-egress.ts | 10 +- .../tests/provider-relay-taint.test.ts | 188 ++++++++++++++++++ packages/ui-server/tests/turn-egress.test.ts | 5 +- 12 files changed, 332 insertions(+), 37 deletions(-) create mode 100644 .changeset/provider-relay-taint-exemption.md create mode 100644 packages/ui-server/tests/provider-relay-taint.test.ts diff --git a/.changeset/provider-relay-taint-exemption.md b/.changeset/provider-relay-taint-exemption.md new file mode 100644 index 0000000000..bf67e3f6b1 --- /dev/null +++ b/.changeset/provider-relay-taint-exemption.md @@ -0,0 +1,7 @@ +--- +"@schlessera/brain-ui-sdk": minor +"@schlessera/brain-ui-server": minor +--- +**Breaking (taint policy, #3246):** a validated request through the brain CLI's provider relay no longer taints a governed session, and taint no longer narrows it. Reranking and WebFetch now work in either order, instead of whichever came first refusing the other with `taint_allowlist`. Every other control still applies to these requests: the egress deny and allowlist rules, exact origin, recipient and route authorization, byte ceilings, budgets, cancellation and accounting. Worker HTTP and `CONNECT` traffic cannot claim the exemption, even to a provider's host. + +Migration: after untrusted input, taint alone no longer keeps content from a session's approved providers. Use `egress.deny`, `allowlist` mode or `BRAIN_UI_CLI_PROVIDER_ORIGINS` to fence a provider. No event, configuration or wire shape changes. diff --git a/docs/decisions/governed-writable-workers.md b/docs/decisions/governed-writable-workers.md index a7cc7ee193..32264a6345 100644 --- a/docs/decisions/governed-writable-workers.md +++ b/docs/decisions/governed-writable-workers.md @@ -626,6 +626,14 @@ holds it as withheld, so a relayed Claude API-key turn's `anthropic-haiku` reaches the host's key instead of failing authentication. Video and the `jev` reranker are not relayed and keep the named roadblock. +**Provider requests and taint — 2026-11-02 +([#3246](https://github.com/schlessera/brain-kit/issues/3246)).** As built, +the relayed request was the turn's ordinary egress with "the turn's deny/allow +and taint rules". That rule is superseded for taint only: a validated +provider-relay request neither taints the session nor is narrowed by its taint. +Every other rule of this section still applies. The full ruling is under +"Untrusted input (G6)". + **Why tier B is protected by default.** Allow rules in project settings would skip the server's approval prompts. Releasing one is a policy choice the user makes in the brain. @@ -2173,7 +2181,7 @@ reports which applies as `governed.egress`. Making the relay work without managed storage is follow-up work. Each connection is recorded as a governance event, and a recording failure ends the turn. Without a governance recorder the policy still applies and only the records are absent (`prepareTurnEgress`, -`packages/ui-server/src/brain/turn-egress.ts:60-166`). The note says egress is +`packages/ui-server/src/brain/turn-egress.ts:60-168`). The note says egress is recorded only when the backend actually routed the worker through the proxy. API-key Claude profiles (2026-10-22) and pi turns (2026-10-23) are routed too. A pi turn whose credential the relay cannot carry is refused rather than @@ -3766,7 +3774,9 @@ author: - files the user marks untrusted; - **any connection from inside the worker other than the inference relay**, recorded by the egress proxy. This covers `curl`, CLI scrapers, headless - Chromium and opaque scripts, whose provenance cannot be told apart. + Chromium and opaque scripts, whose provenance cannot be told apart. Since + 2026-11-02 a validated provider-relay request is exempt as well (#3246, + below). Before the egress proxy lands, Bash commands classified as fetching (`curl`, `wget`, `git clone` and `fetch`, the `brain` scrape and import commands, and @@ -3825,7 +3835,7 @@ session's proxies already admitted (a record with charged bytes; the proxy charges only after admission); otherwise it is refused and recorded as an `egress_denial` with reason `taint_allowlist`. The taint list narrows and never widens: deny and `allowlist` mode still apply first (`prepareTurnEgress`, -`packages/ui-server/src/brain/turn-egress.ts:60-166`). Hosts without managed +`packages/ui-server/src/brain/turn-egress.ts:60-168`). Hosts without managed native storage have no proxy, so the Bash classifier remains their shell rule and nothing narrows their egress. @@ -3845,11 +3855,55 @@ only check on a fetch (`RELAYED_TURN_SETTINGS`, sends only relayed inference, and WebSearch runs inside that inference. The taint rule is unchanged: any other worker connection still taints, including one a tool opens to the vendor's host. A relayed provider request (#1673) is -the turn's own egress and taints as before. The host's own opt-out does not +the turn's own egress and taints as before. #3246 superseded this the same day +(below). The host's own opt-out does not count as the operator's, so title usage is still observed (`telemetryConfigured`, `packages/ui-backend-claude/src/relayed-turn-traffic.ts:26-30`). +**Provider-relay requests neither taint nor narrow — 2026-11-02 +([#3246](https://github.com/schlessera/brain-kit/issues/3246)).** The brain +CLI's paid providers reach their upstream through the metered provider relay +(#1673), which shares the turn proxy's admission. As first built, an admitted +relayed request tainted the session like any worker connection. Once a session +was tainted, the relay was refused any provider host the session had not +contacted. So tool order decided what worked: reranking first made a later +WebFetch of a new host fail, and WebFetch first made later reranking degrade +to `lifecycle_order`. + +The maintainer selected option C. An approved host-relayed provider request +neither taints the session nor is narrowed by its taint. It still passes the +ordinary deny and allowlist rules, the exact origin, recipient and route +authorization, the byte ceilings, budget admission, cancellation and +accounting. It keeps its own `egress_connection` record, which never carries +`inference: true`. The exemption belongs to the operation, never to a +hostname. Only the relay's validated routes reach the proxy's provider +admission (`relayed`, `packages/ui-sdk/src/server/egress-proxy.ts:250`), and +worker HTTP and `CONNECT` traffic cannot claim it, even to a provider's host +(`narrowed`, `packages/ui-sdk/src/server/egress-proxy.ts:126`). Turn egress +records neither a taint nor a contacted host for the operation +(`admitted`, `packages/ui-server/src/brain/turn-egress.ts:133-136`). So in a +tainted session, the worker's own traffic stays narrowed away from the +provider's host. + +The accepted tradeoff is explicit. After untrusted input enters a session, +content the turn sends through the relay can still reach that session's +already-approved providers. The ruling does not declare provider output +trusted, add a recipient, clear or replace an existing taint, or relax any +other untrusted-input or outward-action rule. Browsing and the other input +sources still taint. + +Rejected: (A) keep both restrictions and document them, which leaves both +tool-order failures; (B) stop the taint but keep the narrowing, which repairs +only the provider-first order. + +This changes documented taint-policy semantics without changing any event, +configuration or wire shape, so it is a pre-1.0 breaking minor +([integration contract](../integration-contract.md#provider-relay-requests-and-session-taint-breaking-before-10-3246)). +There is no opt-out field. A host that relied on taint to fence its approved +providers after untrusted input has two levers left: the ordinary egress deny +and allowlist rules, and the exact origins in `BRAIN_UI_CLI_PROVIDER_ORIGINS`. + The capabilities note states the taint sources, these rules, whether this turn's egress is narrowed or explicitly not enforced, and the session's first recorded source once it is tainted (`workerOutwardNote`, diff --git a/docs/hosting/agent-workers.md b/docs/hosting/agent-workers.md index 500337d7d7..5de28742a8 100644 --- a/docs/hosting/agent-workers.md +++ b/docs/hosting/agent-workers.md @@ -86,7 +86,7 @@ The explicitly prepared ordinary egress proxy follows that same helper selection. Its directory and socket remain owned by the server and use its shared primary group, with exact `0750`/`0660` modes; a setgid temporary parent cannot choose another IPC group (`const separateIdentity`, -`packages/ui-sdk/src/server/egress-proxy.ts:77-83`). Without a helper they retain +`packages/ui-sdk/src/server/egress-proxy.ts:78-84`). Without a helper they retain owner-only `0700`/`0600` modes. Before mounting the proxy, the launcher checks canonical paths, server ownership, the expected helper group, exact modes and socket type. Missing entries, symlinks and widened permissions refuse before @@ -1372,10 +1372,15 @@ runs on arrival and again just before dispatch. Nothing is reserved in advance, blocked complete and are counted: a busy turn can end slightly above its stop. -**Egress.** A turn's relayed request is ordinary turn egress (G5): it passes -the turn's deny, allowlist and taint rules and byte ceiling, and appears as an +**Egress.** A turn's relayed request is turn egress (G5): it passes the turn's +deny and allowlist rules and byte ceiling, and appears as an `egress_connection` with the provider's host and path. An `allowlist` policy -therefore has to allow the provider's host for the CLI to reach it. +therefore has to allow the provider's host for the CLI to reach it. Since +#3246, a relayed request neither taints the session nor is narrowed by its +taint. Reranking and WebFetch therefore work in either order, and content can +still reach an approved provider after untrusted input. The worker's own +connections to the provider's host stay narrowed +([G6](../decisions/governed-writable-workers.md#untrusted-input-g6)). **Every governed and strict turn has the relay.** The server boots only on managed native storage (#1793), and a turn whose startup view the native diff --git a/docs/integration-contract.md b/docs/integration-contract.md index 81969fc67c..7c6f3cf53c 100644 --- a/docs/integration-contract.md +++ b/docs/integration-contract.md @@ -20,6 +20,31 @@ same-commit update of the index or relevant authoritative component. How they ar The reasoning is in [decisions/contract-versioning.md](decisions/contract-versioning.md). +## Provider-relay requests and session taint (breaking before 1.0, #3246) + +Under the [maintainer's option C](https://github.com/schlessera/brain-kit/issues/3246), +a validated request through the brain CLI's provider relay no longer taints a +governed session (G6), and a tainted session no longer narrows it with +`taint.egress.allow`. So `brain_context` reranking and WebFetch work in either +order. Before, whichever came first tainted the session, and the other then +failed with `taint_allowlist`. Reranking degraded with a `provider_unavailable` +event. + +This changes documented taint-policy semantics. No event, configuration or +wire shape changes. A relayed request still records its own +`egress_connection` without `inference: true`. It is still refused by the +ordinary egress deny or allowlist rules, an unlisted origin, recipient or +route, the byte ceilings, budget stops and cancellation. Worker HTTP and +`CONNECT` traffic cannot claim the exemption, even to a provider's host, and +the operation grants that traffic no contacted host. + +**Migration.** After untrusted input, taint alone no longer keeps content +from a session's approved providers. To fence a provider, use `egress.deny`, +an `allowlist` egress mode, or the exact origins in +`BRAIN_UI_CLI_PROVIDER_ORIGINS`. There is no new opt-out field. See +[the G6 ruling](decisions/governed-writable-workers.md#untrusted-input-g6) and +[supported inputs](supported-inputs.md). + ## Agent runner unavailable in maintenance workers (additive, 0.45.0, #3243) A credential-free maintenance worker's launcher sets diff --git a/docs/supported-inputs.md b/docs/supported-inputs.md index 3cfd0b665b..d5219f434c 100644 --- a/docs/supported-inputs.md +++ b/docs/supported-inputs.md @@ -68,7 +68,7 @@ objects merge per field. No value grants authority to autonomous turns. | `commands` | `deny`, `confirm`: arrays of `{ pattern: string, reason?: string }` | Additions to existing permissions, default `[]`. Regex sources preserve their literal anchors and compile case-insensitively under [confirmation rules](decisions/confirm-patterns.md). Mixed lists retain valid entries in order and report skipped sources; nonempty entirely invalid lists refuse. | | `egress` | `mode`: `record`/`allowlist`; `allow`, `deny`: string arrays; `max_bytes_per_turn`: nonnegative safe integer | `record`, empty lists and no byte cap by default. This reader does not establish network enforcement. | | `outward` | `allow`: array of `{ command: string, remotes: string[] }`; `hosts`: string array | Default empty additions to the existing outward-action rules and built-in destination list. Parsing grants no action. | -| `taint` | `egress: { allow: string[] }` | Default empty additions; session-derived hosts/inference relay and taint enforcement remain their owning guardrail's responsibility. | +| `taint` | `egress: { allow: string[] }` | Default empty additions; session-derived hosts/inference relay and taint enforcement remain their owning guardrail's responsibility. Validated provider-relay requests are outside taint narrowing and create no taint ([#3246](integration-contract.md#provider-relay-requests-and-session-taint-breaking-before-10-3246)); this list never needs a provider host for them. | | `providers` | Array of `{ paths?: string[], types?: string[], allow: string[] }` | Default `[]`. At least one selector is present. Paths use canonical brain-relative Bun glob patterns; types are exact runtime taxonomy names. Either selector matches; every matching rule must allow the actual recipient. Unknown recipients cannot authorize matching content. | The [budget](https://github.com/schlessera/brain-kit/issues/1669#issuecomment-6128541024) diff --git a/packages/ui-sdk/src/server/egress-proxy.ts b/packages/ui-sdk/src/server/egress-proxy.ts index c01b5b86bc..93ed5fd841 100644 --- a/packages/ui-sdk/src/server/egress-proxy.ts +++ b/packages/ui-sdk/src/server/egress-proxy.ts @@ -40,8 +40,9 @@ export interface EgressProxyOptions { observe(record: EgressRecord): void; /** * Untrusted-input narrowing (G6). While `tainted()` holds, a destination - * other than the inference relay must also match `allow` or be one - * `contacted()` reports; deny and the ordinary rules still apply first. + * other than a host relay (the inference relay or a validated provider-relay + * operation, #3246) must also match `allow` or be one `contacted()` reports; + * deny and the ordinary rules still apply first. */ taint?: { allow: readonly string[]; tainted(): boolean; contacted(host: string): boolean }; /** @@ -49,7 +50,7 @@ export interface EgressProxyOptions { * A returned promise is awaited first, so a durable record it makes commits * before any byte flows; its rejection refuses the connection. */ - admitted?(destination: { host: string; port: number; method: string; inference: boolean }): unknown; + admitted?(destination: { host: string; port: number; method: string; inference: boolean; provider: boolean }): unknown; signal?: AbortSignal; } const hostname = (value: string) => value.toLowerCase().replace(/\.$/, ""); @@ -90,7 +91,12 @@ export async function startEgressProxy(options: EgressProxyOptions) { server.requestTimeout = 30_000; server.on("connection", socket => { connections.add(socket); socket.on("error", () => {}); socket.once("close", () => connections.delete(socket)); }); const track = (socket: Socket) => { connections.add(socket); socket.on("error", () => {}); socket.once("close", () => connections.delete(socket)); return socket; }; - function operation(method: string, url: URL, inference = false) { + /** + * `relay` names the host relay that sent this operation; worker HTTP and + * CONNECT traffic has none and cannot claim one, whatever its destination. + */ + function operation(method: string, url: URL, relay?: "inference" | "provider") { + const inference = relay === "inference"; const started = performance.now(); const controller = new AbortController(); controllers.add(controller); const host = hostname(url.hostname), port = Number(url.port || (url.protocol === "https:" ? "443" : "80")); @@ -116,7 +122,8 @@ export async function startEgressProxy(options: EgressProxyOptions) { if (stopped || options.signal?.aborted) { finish("cancelled", "turn_cancelled"); return false; } if (matches(host, options.deny) || options.mode === "allowlist" && !matches(host, options.allow)) { finish("denied", "destination_not_allowed"); return false; } // Checked again after an approval wait, during which another connection may taint the session. - const narrowed = () => !inference && options.taint?.tainted() && !matches(host, options.taint.allow) && !options.taint.contacted(host); + // Neither host relay is narrowed by taint (G6; #3246 for the provider relay). + const narrowed = () => !relay && options.taint?.tainted() && !matches(host, options.taint.allow) && !options.taint.contacted(host); if (narrowed()) { finish("denied", "taint_not_allowed"); return false; } if (usedBytes >= options.maxBytes) { finish("denied", "max_bytes_per_turn"); return false; } if (matches(host, options.outwardHosts) || options.outwardPorts?.includes(port)) { @@ -135,7 +142,7 @@ export async function startEgressProxy(options: EgressProxyOptions) { } if (narrowed()) { finish("denied", "taint_not_allowed"); return false; } // A recorder failure aborts the turn through its own signal; it cannot admit. - try { await options.admitted?.({ host, port, method, inference }); } catch { finish("failed", "proxy_error"); return false; } + try { await options.admitted?.({ host, port, method, inference, provider: relay === "provider" }); } catch { finish("failed", "proxy_error"); return false; } if (stopped || controller.signal.aborted) { finish("cancelled", "turn_cancelled"); return false; } return true; }; @@ -232,16 +239,18 @@ export async function startEgressProxy(options: EgressProxyOptions) { if (options.signal?.aborted) stop(); return { dir, socketPath, stop, usedBytes: () => usedBytes, /** The existing inference relay shares this turn's admission, counter and audit. */ - inference(method: string, target: URL, signal: AbortSignal) { return relayedOperation(method, target, signal, true); }, + inference(method: string, target: URL, signal: AbortSignal) { return relayedOperation(method, target, signal, "inference"); }, /** - * The CLI provider relay's requests (#1673): ordinary egress to the - * provider (G5), with the turn's deny/allow and taint rules, byte ceiling - * and connection record, sent by the host so the key stays there. + * The CLI provider relay's validated requests (#1673): egress to the + * provider (G5), with the turn's deny/allow rules, byte ceiling and + * connection record, sent by the host so the key stays there. Like the + * inference relay, it neither taints the session nor is narrowed by its + * taint (G6, #3246); only the relay's own validated routes reach this. */ - relayed(method: string, target: URL, signal: AbortSignal) { return relayedOperation(method, target, signal, false); }, + relayed(method: string, target: URL, signal: AbortSignal) { return relayedOperation(method, target, signal, "provider"); }, }; - function relayedOperation(method: string, target: URL, signal: AbortSignal, inference: boolean) { - const op = operation(method, new URL(target), inference); + function relayedOperation(method: string, target: URL, signal: AbortSignal, relay: "inference" | "provider") { + const op = operation(method, new URL(target), relay); const abort = () => op.finish("cancelled", "client_disconnected"); signal.addEventListener("abort", abort, { once: true }); if (signal.aborted) abort(); diff --git a/packages/ui-sdk/src/server/outward-policy.ts b/packages/ui-sdk/src/server/outward-policy.ts index 64c3d0c485..edd56ad3cf 100644 --- a/packages/ui-sdk/src/server/outward-policy.ts +++ b/packages/ui-sdk/src/server/outward-policy.ts @@ -104,9 +104,9 @@ function workerOutwardRules(egressActive: boolean): string[] { /** The untrusted-input rules (G6), and this session's taint once one is recorded. */ function untrustedInputNote(egressActive: boolean, taint: WorkerSessionTaint | null): string[] { return ["# Untrusted input", - `WebFetch/WebSearch and web tool results, reads under .brain-ui/inbox/ or workspaces/, results from any MCP server other than brain-kit's own, and Bash calls that fetch or cannot be classified as network-free taint the session${egressActive ? ", as does any connection other than the inference relay" : ""}.`, + `WebFetch/WebSearch and web tool results, reads under .brain-ui/inbox/ or workspaces/, results from any MCP server other than brain-kit's own, and Bash calls that fetch or cannot be classified as network-free taint the session${egressActive ? ", as does any connection other than the host's inference and provider relays" : ""}.`, "A tainted session stays tainted: every outward action asks for approval even when outward.allow matches, and its steering-file changes are flagged in the turn journal.", - egressActive ? "While tainted, this turn's egress reaches only the policy's taint.egress.allow hosts, hosts this session already contacted, and the inference relay." + egressActive ? "While tainted, this turn's egress reaches only the policy's taint.egress.allow hosts, hosts this session already contacted, and the host's inference and provider relays. Content you send through the provider relay (brain CLI reranking, embeddings, completions, images) still reaches its approved provider after untrusted input." : "Tainted egress is not enforced for this turn: it does not run on the host egress proxy.", ...(taint ? [`This session is tainted (first recorded source: ${taint.source}).`] : [])]; } diff --git a/packages/ui-sdk/tests/egress-proxy.test.ts b/packages/ui-sdk/tests/egress-proxy.test.ts index a5ceb71e0f..ce2187cb3e 100644 --- a/packages/ui-sdk/tests/egress-proxy.test.ts +++ b/packages/ui-sdk/tests/egress-proxy.test.ts @@ -276,15 +276,15 @@ test("turn stop synchronously records an active CONNECT exactly once", async () expect(records).toHaveLength(1); } finally { proxy.stop(); client.destroy(); for (const peer of peers) peer.destroy(); origin.close(); await closed; } }); -test("a tainted turn reaches only taint-allowed or already contacted hosts; the inference relay is exempt", async () => { - let calls = 0; const records: EgressRecord[] = [], admitted: Array<{ host: string; inference: boolean }> = []; +test("a tainted turn reaches only taint-allowed or already contacted hosts; the inference and provider relays are exempt", async () => { + let calls = 0; const records: EgressRecord[] = [], admitted: Array<{ host: string; inference: boolean; provider: boolean }> = []; const origin = Bun.serve({ hostname: "127.0.0.1", port: 0, fetch() { calls++; return new Response("Ithaca"); } }); let tainted = false; const contacted = new Set(), allow: string[] = []; const proxy = await startEgressProxy({ ...defaults(records), maxBytes: 65536, taint: { allow, tainted: () => tainted, contacted: host => contacted.has(host) }, - admitted: destination => admitted.push({ host: destination.host, inference: destination.inference }) }); + admitted: destination => admitted.push({ host: destination.host, inference: destination.inference, provider: destination.provider }) }); try { expect((await get(proxy.socketPath, origin.url.href)).status, "EGRESS_CLEAN_TURN_UNCHANGED").toBe(200); - expect(admitted, "EGRESS_ADMISSION_REPORTED").toEqual([{ host: "127.0.0.1", inference: false }]); + expect(admitted, "EGRESS_ADMISSION_REPORTED").toEqual([{ host: "127.0.0.1", inference: false, provider: false }]); tainted = true; expect((await get(proxy.socketPath, origin.url.href)).status, "EGRESS_TAINT_REFUSES_UNLISTED_HOST").toBe(403); expect(calls).toBe(1); @@ -293,6 +293,11 @@ test("a tainted turn reaches only taint-allowed or already contacted hosts; the // The relay's own admission is never narrowed. const relay = proxy.inference("POST", new URL(`${origin.url.href}v1/messages`), new AbortController().signal); expect(await relay.admit(), "EGRESS_TAINT_EXEMPTS_INFERENCE").toBe(true); relay.finish("completed"); + // So is a validated provider-relay operation (#3246); it is reported as one, never as inference. + const provider = proxy.relayed("POST", new URL(`${origin.url.href}v1beta/models/gemini-2.5-flash:generateContent`), new AbortController().signal); + expect(await provider.admit(), "EGRESS_TAINT_EXEMPTS_PROVIDER_RELAY").toBe(true); provider.finish("completed"); + expect(admitted.at(-1), "EGRESS_PROVIDER_ADMISSION_REPORTED").toEqual({ host: "127.0.0.1", inference: false, provider: true }); + expect(records.at(-1)?.inference, "EGRESS_PROVIDER_RECORD_NOT_INFERENCE").toBeUndefined(); contacted.add("127.0.0.1"); expect((await get(proxy.socketPath, origin.url.href)).status, "EGRESS_TAINT_KEEPS_CONTACTED_HOST").toBe(200); contacted.clear(); allow.push("127.0.0.1"); diff --git a/packages/ui-sdk/tests/outward-actions.test.ts b/packages/ui-sdk/tests/outward-actions.test.ts index 624e1b29e6..04c899f898 100644 --- a/packages/ui-sdk/tests/outward-actions.test.ts +++ b/packages/ui-sdk/tests/outward-actions.test.ts @@ -52,6 +52,7 @@ test("the capabilities note states the taint rules, the session's taint and wher expect(clean).not.toContain("This session is tainted"); const tainted = workerOutwardNote(true, { eventId: 7, source: "web_fetch" }); expect(tainted, "G6_NOTE_STATES_TAINT").toContain("This session is tainted (first recorded source: web_fetch)."); - expect(tainted).toContain("as does any connection other than the inference relay"); - expect(tainted).toContain("taint.egress.allow hosts, hosts this session already contacted, and the inference relay"); + expect(tainted).toContain("as does any connection other than the host's inference and provider relays"); + expect(tainted).toContain("taint.egress.allow hosts, hosts this session already contacted, and the host's inference and provider relays"); + expect(tainted).toContain("still reaches its approved provider after untrusted input"); }); diff --git a/packages/ui-server/src/brain/turn-egress.ts b/packages/ui-server/src/brain/turn-egress.ts index d508bd3334..c8803c37a8 100644 --- a/packages/ui-server/src/brain/turn-egress.ts +++ b/packages/ui-server/src/brain/turn-egress.ts @@ -116,8 +116,8 @@ export async function prepareTurnEgress(options: { } catch { fail(); } }; /** - * Any admitted connection other than the inference relay taints the session - * (G6), recorded before its first byte. Sticky: once read, never re-read. + * Any admitted connection other than a host relay taints the session (G6), + * recorded before its first byte. Sticky: once read, never re-read. */ const taint = db ? { allow: options.policy.taint.egress.allow, @@ -130,8 +130,10 @@ export async function prepareTurnEgress(options: { * has committed by then. It is in force for every later admission from the * moment it is submitted. */ - const admitted = async (destination: { host: string; port: number; method: string; inference: boolean }): Promise => { - if (destination.inference) return; + const admitted = async (destination: { host: string; port: number; method: string; inference: boolean; provider: boolean }): Promise => { + // A host relay's operation neither taints the session nor makes its host + // one the worker's own traffic may reach once tainted (G6, #3246). + if (destination.inference || destination.provider) return; contacted.add(destination.host); if (!writes || tainted) return; tainted = true; diff --git a/packages/ui-server/tests/provider-relay-taint.test.ts b/packages/ui-server/tests/provider-relay-taint.test.ts new file mode 100644 index 0000000000..7e08461c0d --- /dev/null +++ b/packages/ui-server/tests/provider-relay-taint.test.ts @@ -0,0 +1,188 @@ +/** + * #3246: a validated provider-relay operation neither taints a governed session + * nor is narrowed by its taint (G6), so tool order no longer decides whether + * WebFetch or reranking works. Composed as a turn runs it: the real provider + * relay shares the real turn proxy's admission, and taint lives in the + * session's governance record. The provider is a fictional loopback Gemini + * endpoint the operator lists; nothing here needs a key or the network. + */ +import { afterAll, beforeAll, expect, test } from "bun:test"; +import { request as httpRequest } from "node:http"; +import { connect } from "node:net"; +import { resolveGovernancePolicy, type GovernancePolicyInput } from "@schlessera/brain-common/internal/governance-policy"; +import { startProviderRelay, type ProviderRelayOptions, type ProviderRelayRefusal } from "@schlessera/brain-ui-sdk/internal"; +import type { BackendBridge } from "@schlessera/brain-ui-sdk/server"; +import type { Database } from "bun:sqlite"; +import { createUiDb } from "../src/db/client.js"; +import { queryGovernanceEvents, recordGovernanceEvent } from "../src/governance/events.js"; +import { prepareTurnEgress } from "../src/brain/turn-egress.js"; + +const HOST_KEY = "odysseus-host-gemini-key"; +const RERANK = "/v1beta/models/gemini-2.5-flash:generateContent"; +let provider: ReturnType, harbour: ReturnType, island: ReturnType; +const reached: string[] = []; +beforeAll(() => { + // Three loopback hosts: the provider, WebFetch's target and a later new host. + provider = Bun.serve({ hostname: "127.0.0.1", port: 0, async fetch(request) { + reached.push(`${request.headers.get("x-goog-api-key")} ${new URL(request.url).pathname}`); + await request.arrayBuffer(); + return Response.json({ candidates: [], usageMetadata: { promptTokenCount: 4, candidatesTokenCount: 1 } }); + } }); + harbour = Bun.serve({ hostname: "127.0.0.2", port: 0, fetch: () => new Response("Ithaca") }); + island = Bun.serve({ hostname: "127.0.0.3", port: 0, fetch: () => new Response("Aeaea") }); +}); +afterAll(() => { provider.stop(true); harbour.stop(true); island.stop(true); }); + +function connectStatus(socketPath: string, target: string): Promise { + return new Promise((resolve, reject) => { + const socket = connect(socketPath); let text = ""; + socket.on("connect", () => socket.write(`CONNECT ${target} HTTP/1.1\r\nHost: ${target}\r\n\r\n`)); + socket.on("data", data => { text += data; const status = /^HTTP\/1\.1 (\d{3})/.exec(text); if (status) { socket.destroy(); resolve(Number(status[1])); } }); + socket.on("close", () => resolve(0)); socket.on("error", reject); + }); +} +function httpStatus(socketPath: string, target: string, method = "GET"): Promise { + return new Promise((resolve, reject) => { + const child = httpRequest({ socketPath, path: target, method }, response => { + response.resume(); response.once("end", () => resolve(response.statusCode!)); response.once("error", reject); + }); + child.once("error", reject); child.end(); + }); +} + +const bridge = { requestPermission: async () => ({ behavior: "deny", message: "Odysseus declines" }), emit() {} } as unknown as BackendBridge; + +/** One governed turn of session `sessionId`: its proxy, and the real provider relay sharing its admission. */ +async function turn(db: Database, sessionId: string, turnId: string, policy: GovernancePolicyInput = { schema_version: 1 }, + relayOptions: Partial = {}) { + const controller = new AbortController(); + const egress = await prepareTurnEgress({ controller, policy: resolveGovernancePolicy(policy), turnId, sessionId: () => sessionId, + model: () => "claude-haiku-4-5", profile: "governed", origin: "interactive", bridge, + record: event => recordGovernanceEvent(db, event), governanceDb: db }); + const refusals: ProviderRelayRefusal[] = []; + const relay = startProviderRelay({ egress, credential: name => (name === "GEMINI_API_KEY" ? HOST_KEY : undefined), + origins: new Map([["GEMINI_API_KEY", [provider.url.origin]]]), refused: refusal => refusals.push(refusal), ...relayOptions }); + /** What the brain CLI sends for reranking, through the relay's socket. */ + const rerank = (request: { path?: string; origin?: string; body?: string } = {}) => new Promise<{ status: number; body: string }>((resolve, reject) => { + const body = Buffer.from(request.body ?? JSON.stringify({ contents: [{ parts: [{ text: "Rank the harbours of Ithaca." }] }] })); + const outgoing = httpRequest({ socketPath: relay.socketPath, method: "POST", path: request.path ?? RERANK, headers: { + "content-type": "application/json", "content-length": String(body.byteLength), "x-brain-provider": "gemini", + "x-brain-provider-key": "GEMINI_API_KEY", "x-brain-provider-origin": request.origin ?? provider.url.origin } }, incoming => { + const chunks: Buffer[] = []; + incoming.on("data", chunk => chunks.push(chunk)); + incoming.on("end", () => resolve({ status: incoming.statusCode ?? 0, body: Buffer.concat(chunks).toString("utf8") })); + }); + outgoing.on("error", reject); outgoing.end(body); + }); + const stop = async () => { await relay.stop(); egress.stop(); await egress.settled(); }; + return { egress, relay, rerank, refusals, controller, stop }; +} + +function session(db: Database, id: string) { + db.query("INSERT INTO sessions (id,title,created_at,last_active_at) VALUES (?,?,0,0)").run(id, id); + const events = (kind: "taint" | "egress_connection" | "egress_denial") => queryGovernanceEvents(db, { sessionId: id, kinds: [kind], limit: 50 }); + return { taints: () => events("taint").map(event => event.payload), events }; +} + +test("provider first, then WebFetch: the provider request never taints, and WebFetch's target is the first taint (#3246)", async () => { + const db = createUiDb(":memory:"), voyage = session(db, "ithaca"); + const first = await turn(db, "ithaca", "turn-provider-first"); + reached.length = 0; + try { + expect((await first.rerank()).status, "PROVIDER_FIRST_ADMITTED").toBe(200); + expect(reached, "PROVIDER_FIRST_REACHED_WITH_HOST_KEY").toEqual([`${HOST_KEY} ${RERANK}`]); + expect(voyage.taints(), "PROVIDER_RELAY_CREATES_NO_TAINT").toEqual([]); + // WebFetch's target, then the next new host. + expect(await connectStatus(first.egress.socketPath, `127.0.0.2:${harbour.port}`), "WEBFETCH_AFTER_PROVIDER_ADMITTED").toBe(200); + expect(voyage.taints(), "WEBFETCH_IS_FIRST_TAINT").toEqual([{ source: "egress_connection", tool: null, detail: `CONNECT 127.0.0.2:${harbour.port}` }]); + expect(await connectStatus(first.egress.socketPath, `127.0.0.3:${island.port}`), "WORKER_NEW_HOST_STILL_NARROWED").toBe(403); + // The provider's host is not a contacted host the worker's own traffic may now reach. + expect(await connectStatus(first.egress.socketPath, `127.0.0.1:${provider.port}`), "WORKER_CONNECT_TO_PROVIDER_HOST_NARROWED").toBe(403); + expect(await httpStatus(first.egress.socketPath, `${provider.url.origin}${RERANK}`, "POST"), "WORKER_HTTP_TO_PROVIDER_HOST_NARROWED").toBe(403); + // The provider keeps working after taint, and neither clears nor replaces it. + expect((await first.rerank()).status, "PROVIDER_AFTER_TAINT_ADMITTED").toBe(200); + await first.stop(); + expect(voyage.taints(), "PROVIDER_LEAVES_FIRST_TAINT").toEqual([{ source: "egress_connection", tool: null, detail: `CONNECT 127.0.0.2:${harbour.port}` }]); + expect(reached).toHaveLength(2); + const denials = voyage.events("egress_denial").map(event => event.payload); + expect(denials, "ONLY_WORKER_TRAFFIC_DENIED").toEqual([ + { host: "127.0.0.3", port: island.port, method: "CONNECT", reason: "taint_allowlist", bytes: 0 }, + { host: "127.0.0.1", port: provider.port, method: "CONNECT", reason: "taint_allowlist", bytes: 0 }, + { host: "127.0.0.1", port: provider.port, method: "POST", reason: "taint_allowlist", bytes: 0 }]); + // Provider requests keep their own connection receipt, never tagged as inference. + const providerRecords = voyage.events("egress_connection").map(event => event.payload).filter(record => record.host === "127.0.0.1" && record.outcome === "completed"); + expect(providerRecords.map(record => [record.method, record.path, record.inference]), "PROVIDER_CONNECTION_RECEIPTS").toEqual([["POST", RERANK, undefined], ["POST", RERANK, undefined]]); + } finally { await first.stop(); db.close(); } +}); + +test("WebFetch first, then provider: the session stays tainted by WebFetch and the provider request is admitted (#3246)", async () => { + const db = createUiDb(":memory:"), voyage = session(db, "calypso"); + const first = await turn(db, "calypso", "turn-fetch-first"); + reached.length = 0; + try { + expect(await connectStatus(first.egress.socketPath, `127.0.0.2:${harbour.port}`), "WEBFETCH_FIRST_ADMITTED").toBe(200); + const fetched = { source: "egress_connection", tool: null, detail: `CONNECT 127.0.0.2:${harbour.port}` }; + expect(voyage.taints()).toEqual([fetched]); + const reranked = await first.rerank(); + expect(reranked.status, "TAINTED_SESSION_ADMITS_PROVIDER").toBe(200); + expect(first.refusals, "NO_TAINT_DERIVED_PROVIDER_REFUSAL").toEqual([]); + expect(reached, "PROVIDER_REACHED_AFTER_TAINT").toEqual([`${HOST_KEY} ${RERANK}`]); + expect(await connectStatus(first.egress.socketPath, `127.0.0.1:${provider.port}`), "WORKER_STILL_NARROWED_FROM_PROVIDER_HOST").toBe(403); + await first.stop(); + // A later turn of the same tainted session: the provider still works, the worker is still narrowed. + const later = await turn(db, "calypso", "turn-fetch-later"); + try { + expect((await later.rerank()).status, "LATER_TURN_PROVIDER_ADMITTED").toBe(200); + expect(await connectStatus(later.egress.socketPath, `127.0.0.3:${island.port}`), "LATER_TURN_NEW_HOST_NARROWED").toBe(403); + } finally { await later.stop(); } + expect(voyage.taints(), "PROVIDER_NEITHER_CLEARS_NOR_REPLACES_TAINT").toEqual([fetched]); + expect(voyage.events("egress_denial").every(event => !(event.payload.host === "127.0.0.1" && event.payload.method === "POST")), "NO_PROVIDER_TAINT_DENIAL").toBe(true); + } finally { await first.stop(); db.close(); } +}); + +test("in a tainted session, every other control still refuses the provider request through the real relay (#3246)", async () => { + const db = createUiDb(":memory:"); + const cases: Array<{ name: string; policy?: GovernancePolicyInput; relay?: Partial; + request?: { path?: string; origin?: string; body?: string }; status: number; reason: ProviderRelayRefusal["reason"]; denial?: string }> = [ + { name: "DENIED_PROVIDER_HOST", policy: { schema_version: 1, egress: { deny: ["127.0.0.1"] } }, status: 403, reason: "egress_refused", denial: "denied_host" }, + { name: "NOT_ALLOWLISTED_PROVIDER_HOST", policy: { schema_version: 1, egress: { mode: "allowlist", allow: ["127.0.0.2"] } }, status: 403, reason: "egress_refused", denial: "not_allowlisted" }, + { name: "BYTE_CEILING", policy: { schema_version: 1, egress: { max_bytes_per_turn: 200 } }, request: { body: JSON.stringify({ contents: [{ parts: [{ text: "Odysseus ".repeat(64) }] }] }) }, status: 403, reason: "egress_refused", denial: "byte_cap" }, + { name: "BUDGET_STOP", relay: { admit: () => ({ allowed: false, message: "Athena stops the voyage" }) }, status: 403, reason: "budget_exceeded" }, + { name: "UNLISTED_ORIGIN", request: { origin: "http://localhost:1" }, status: 403, reason: "recipient_not_authorized" }, + { name: "FORGED_ROUTE", request: { path: "/v1beta/files" }, status: 403, reason: "route_not_allowed" }, + { name: "UNAVAILABLE_CREDENTIAL", relay: { credential: () => undefined }, status: 403, reason: "credential_unavailable" }, + ]; + try { + for (const [index, entry] of cases.entries()) { + const voyage = session(db, `voyage-${index}`); + const current = await turn(db, `voyage-${index}`, `turn-${index}`, entry.policy, entry.relay); + reached.length = 0; + try { + expect(await connectStatus(current.egress.socketPath, `127.0.0.2:${harbour.port}`), `${entry.name}_TAINT_SOURCE`).toBe(200); + const result = await current.rerank(entry.request); + expect(result.status, entry.name).toBe(entry.status); + expect(current.refusals.map(refusal => refusal.reason), entry.name).toEqual([entry.reason]); + expect(reached, `${entry.name}_NEVER_REACHES_PROVIDER`).toEqual([]); + await current.stop(); + const denials = voyage.events("egress_denial").map(event => event.payload); + expect(denials.map(denial => denial.reason), `${entry.name}_DENIAL`).toEqual(entry.denial ? [entry.denial] : []); + expect(voyage.taints(), `${entry.name}_TAINT_UNCHANGED`).toEqual([{ source: "egress_connection", tool: null, detail: `CONNECT 127.0.0.2:${harbour.port}` }]); + } finally { await current.stop(); } + } + } finally { db.close(); } +}); + +test("a cancelled turn refuses a tainted session's provider request before contact (#3246)", async () => { + const db = createUiDb(":memory:"), voyage = session(db, "scylla"); + const current = await turn(db, "scylla", "turn-cancelled"); + reached.length = 0; + try { + expect(await connectStatus(current.egress.socketPath, `127.0.0.2:${harbour.port}`)).toBe(200); + current.controller.abort(); + const result = await current.rerank(); + expect(result.status, "CANCELLED_TURN_REFUSES_PROVIDER").not.toBe(200); + expect(reached, "CANCELLED_NEVER_REACHES_PROVIDER").toEqual([]); + await current.stop(); + expect(voyage.taints()).toHaveLength(1); + } finally { await current.stop(); db.close(); } +}); diff --git a/packages/ui-server/tests/turn-egress.test.ts b/packages/ui-server/tests/turn-egress.test.ts index 3a7991bb09..bdcae4f807 100644 --- a/packages/ui-server/tests/turn-egress.test.ts +++ b/packages/ui-server/tests/turn-egress.test.ts @@ -291,9 +291,8 @@ test("a governed turn whose runtime sends only relayed inference stays untainted const rerank = proxy.relayed("POST", new URL("https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash:generateContent"), new AbortController().signal); expect(await rerank.admit(), "UNTAINTED_SESSION_ADMITS_RERANKING").toBe(true); rerank.finish("completed"); - // A relayed provider request is the turn's own egress (G5) and taints under G6 as it always did. - expect(events("taint").map(event => event.payload), "PROVIDER_RELAY_TAINT_UNCHANGED").toEqual([ - { source: "egress_connection", tool: null, detail: "POST generativelanguage.googleapis.com:443" }]); + // A validated provider-relay request is a host relay's operation: it never taints (G6, #3246). + expect(events("taint"), "PROVIDER_RELAY_NEVER_TAINTS").toEqual([]); // WebFetch's own target, reached first in a fresh turn of a clean session. db.query("INSERT INTO sessions (id,title,created_at,last_active_at) VALUES ('calypso','Calypso',0,0)").run(); const fresh = await prepareTurnEgress({ ...inputs(new AbortController()), turnId: "turn-fetch", sessionId: () => "calypso", From 24bcc50f1adae3f2e147f0954b7ad4dbce9dbbb5 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Mon, 2 Nov 2026 23:40:45 +0000 Subject: [PATCH 2/2] CONTRACT: fix(ui-server): keep provider-relay records out of later turns' contacted hosts (#3246) A later turn rebuilt its contacted hosts from the session's earlier egress_connection records, excluding only inference: true. A provider-relay record looked like a worker's, so a turn-1 provider request let a tainted turn-2 worker CONNECT reach the provider's host. Per the maintainer's ruling on #3246, a validated provider-relay operation now records the optional provider: true literal (mirroring inference: true), and contactedHosts excludes those records. Additive governance-event field, documented in docs/http-api.md and the integration-contract entry. Co-Authored-By: Claude Opus 5.5 --- .changeset/provider-relay-taint-exemption.md | 2 +- api-report/ui-server.txt | 1 + docs/decisions/governed-writable-workers.md | 24 ++++++++++---- docs/hosting/agent-workers.md | 7 +++-- docs/http-api.md | 2 +- docs/integration-contract.md | 13 ++++++-- packages/ui-sdk/src/server/egress-proxy.ts | 8 +++-- packages/ui-sdk/tests/egress-proxy.test.ts | 4 +++ packages/ui-server/src/governance/events.ts | 2 +- .../ui-server/src/governance/session-taint.ts | 12 ++++--- .../tests/provider-relay-taint.test.ts | 31 +++++++++++++++++-- 11 files changed, 81 insertions(+), 25 deletions(-) diff --git a/.changeset/provider-relay-taint-exemption.md b/.changeset/provider-relay-taint-exemption.md index bf67e3f6b1..4b5406451b 100644 --- a/.changeset/provider-relay-taint-exemption.md +++ b/.changeset/provider-relay-taint-exemption.md @@ -4,4 +4,4 @@ --- **Breaking (taint policy, #3246):** a validated request through the brain CLI's provider relay no longer taints a governed session, and taint no longer narrows it. Reranking and WebFetch now work in either order, instead of whichever came first refusing the other with `taint_allowlist`. Every other control still applies to these requests: the egress deny and allowlist rules, exact origin, recipient and route authorization, byte ceilings, budgets, cancellation and accounting. Worker HTTP and `CONNECT` traffic cannot claim the exemption, even to a provider's host. -Migration: after untrusted input, taint alone no longer keeps content from a session's approved providers. Use `egress.deny`, `allowlist` mode or `BRAIN_UI_CLI_PROVIDER_ORIGINS` to fence a provider. No event, configuration or wire shape changes. +Migration: after untrusted input, taint alone no longer keeps content from a session's approved providers. Use `egress.deny`, `allowlist` mode or `BRAIN_UI_CLI_PROVIDER_ORIGINS` to fence a provider. No configuration or wire shape changes. The `egress_connection` governance event gains an optional `provider: true` field (additive), set only on a validated provider-relay request. A later turn no longer counts such a record's host as one the worker already contacted, so a provider request never lets worker traffic reach the provider's host after taint. diff --git a/api-report/ui-server.txt b/api-report/ui-server.txt index 9c2753d14e..5e64e29be4 100644 --- a/api-report/ui-server.txt +++ b/api-report/ui-server.txt @@ -646,6 +646,7 @@ signatures (every public export and the types it is made of) }>; path: z.ZodOptional; port: z.ZodNumber; + provider: z.ZodOptional>; reason: z.ZodOptional; }, z.core.$strict>; version: number; diff --git a/docs/decisions/governed-writable-workers.md b/docs/decisions/governed-writable-workers.md index 32264a6345..8116800621 100644 --- a/docs/decisions/governed-writable-workers.md +++ b/docs/decisions/governed-writable-workers.md @@ -3875,17 +3875,29 @@ The maintainer selected option C. An approved host-relayed provider request neither taints the session nor is narrowed by its taint. It still passes the ordinary deny and allowlist rules, the exact origin, recipient and route authorization, the byte ceilings, budget admission, cancellation and -accounting. It keeps its own `egress_connection` record, which never carries -`inference: true`. The exemption belongs to the operation, never to a +accounting. It keeps its own `egress_connection` record, which carries +`provider: true` and never `inference: true`. The exemption belongs to the operation, never to a hostname. Only the relay's validated routes reach the proxy's provider -admission (`relayed`, `packages/ui-sdk/src/server/egress-proxy.ts:250`), and +admission (`relayed`, `packages/ui-sdk/src/server/egress-proxy.ts:252`), and worker HTTP and `CONNECT` traffic cannot claim it, even to a provider's host -(`narrowed`, `packages/ui-sdk/src/server/egress-proxy.ts:126`). Turn egress +(`narrowed`, `packages/ui-sdk/src/server/egress-proxy.ts:128`). Turn egress records neither a taint nor a contacted host for the operation (`admitted`, `packages/ui-server/src/brain/turn-egress.ts:133-136`). So in a tainted session, the worker's own traffic stays narrowed away from the provider's host. +A later turn rebuilds its contacted hosts from the session's earlier +`egress_connection` records, and a provider record there would look like a +worker's. So the maintainer added the optional `provider: true` tag, mirroring +`inference: true`, on the record of every validated provider-relay operation +(`finish`, `packages/ui-sdk/src/server/egress-proxy.ts:107-114`). The rebuild +excludes those records (`contactedHosts`, +`packages/ui-server/src/governance/session-taint.ts:45-51`), so a provider +request never gives the worker's own `CONNECT` a contacted-host pass, in the +same turn or a later one. Records written before the tag existed stay +unmarked, so they can still count for a session that already has them. That is +an additive event field, so it ships in a minor. + The accepted tradeoff is explicit. After untrusted input enters a session, content the turn sends through the relay can still reach that session's already-approved providers. The ruling does not declare provider output @@ -3897,8 +3909,8 @@ Rejected: (A) keep both restrictions and document them, which leaves both tool-order failures; (B) stop the taint but keep the narrowing, which repairs only the provider-first order. -This changes documented taint-policy semantics without changing any event, -configuration or wire shape, so it is a pre-1.0 breaking minor +This changes documented taint-policy semantics, with no configuration or wire +change and one additive event field, so it is a pre-1.0 breaking minor ([integration contract](../integration-contract.md#provider-relay-requests-and-session-taint-breaking-before-10-3246)). There is no opt-out field. A host that relied on taint to fence its approved providers after untrusted input has two levers left: the ordinary egress deny diff --git a/docs/hosting/agent-workers.md b/docs/hosting/agent-workers.md index 5de28742a8..392d4aefd3 100644 --- a/docs/hosting/agent-workers.md +++ b/docs/hosting/agent-workers.md @@ -86,7 +86,7 @@ The explicitly prepared ordinary egress proxy follows that same helper selection. Its directory and socket remain owned by the server and use its shared primary group, with exact `0750`/`0660` modes; a setgid temporary parent cannot choose another IPC group (`const separateIdentity`, -`packages/ui-sdk/src/server/egress-proxy.ts:78-84`). Without a helper they retain +`packages/ui-sdk/src/server/egress-proxy.ts:80-86`). Without a helper they retain owner-only `0700`/`0600` modes. Before mounting the proxy, the launcher checks canonical paths, server ownership, the expected helper group, exact modes and socket type. Missing entries, symlinks and widened permissions refuse before @@ -1374,12 +1374,13 @@ stop. **Egress.** A turn's relayed request is turn egress (G5): it passes the turn's deny and allowlist rules and byte ceiling, and appears as an -`egress_connection` with the provider's host and path. An `allowlist` policy +`egress_connection` with the provider's host and path, tagged `provider: true`. An `allowlist` policy therefore has to allow the provider's host for the CLI to reach it. Since #3246, a relayed request neither taints the session nor is narrowed by its taint. Reranking and WebFetch therefore work in either order, and content can still reach an approved provider after untrusted input. The worker's own -connections to the provider's host stay narrowed +connections to the provider's host stay narrowed, in that turn and in later +ones: the tag keeps the relay's request from making the host a contacted one ([G6](../decisions/governed-writable-workers.md#untrusted-input-g6)). **Every governed and strict turn has the relay.** The server boots only on diff --git a/docs/http-api.md b/docs/http-api.md index 2a5decfa32..e8b8fc264b 100644 --- a/docs/http-api.md +++ b/docs/http-api.md @@ -1223,7 +1223,7 @@ read by any authenticated principal. | Kind | Version | Fields | Meaning | | --- | --- | --- | --- | -| `egress_connection` | 1 | `host`, `port`, `method`, `path` (optional), `bytes`, `accounting`, `durationMs`, `outcome`, `inference` (optional), `reason` (optional) | A completed, denied, failed or cancelled proxy connection. HTTP has a path and conservative wire accounting; opaque CONNECT has no path or plaintext claim. Only the concrete inference relay sets `inference: true`. Headers, query strings and content are absent. | +| `egress_connection` | 1 | `host`, `port`, `method`, `path` (optional), `bytes`, `accounting`, `durationMs`, `outcome`, `inference` (optional), `provider` (optional, #3246), `reason` (optional) | A completed, denied, failed or cancelled proxy connection. HTTP has a path and conservative wire accounting; opaque CONNECT has no path or plaintext claim. Only the concrete inference relay sets `inference: true`, and only a validated provider-relay operation sets `provider: true`; a record never carries both. Neither relay's record makes its host a contacted one for a tainted session's worker traffic. Headers, query strings and content are absent. | | `steering_change` | 1 | `path`, `sequence`, `beforeHash`, `afterHash`, `taintSourceEventId`, `overlappingTurnIds` | One observed steering change, attributed to its turn. Hashes identify retained regular-file versions or are `null`; the source is an existing prior taint event or `null`. Shared windows remain shared, not exclusive writer claims. | | `policy_change` | 1 | `requestId`, `baseHash`, `proposedHash`, `sections`, `outcome` | Explicit user-approved policy publication. Actor is `user`; outcome is `updated`; hashes identify the exact reviewed and written bytes. | | `scratch_overage` | 1 | `bytes`, `pinnedFiles`, `pinnedBytes`, `overageBytes` | Scratch remains above its cap after a prune that preserved retained links. Counts are remaining bytes and pinned files/bytes; `overageBytes` is the excess. A background pass has actor `server` and no session or turn; unbound retention applies. | diff --git a/docs/integration-contract.md b/docs/integration-contract.md index 7c6f3cf53c..5a513b50a9 100644 --- a/docs/integration-contract.md +++ b/docs/integration-contract.md @@ -30,9 +30,16 @@ order. Before, whichever came first tainted the session, and the other then failed with `taint_allowlist`. Reranking degraded with a `provider_unavailable` event. -This changes documented taint-policy semantics. No event, configuration or -wire shape changes. A relayed request still records its own -`egress_connection` without `inference: true`. It is still refused by the +This changes documented taint-policy semantics. No configuration or wire +shape changes. A relayed request still records its own `egress_connection`, +never with `inference: true`. That record gains one additive field: the +optional `provider: true` literal, mirroring `inference: true` and set only +by a validated provider-relay operation +([governance events](http-api.md#governance-events-additive-1651)). A later turn excludes +those records when it rebuilds the session's contacted hosts, so a provider +request never lets worker `CONNECT` reach the provider's host after taint, in +the same turn or a later one. Records written before this field stay +unmarked. The relayed request is still refused by the ordinary egress deny or allowlist rules, an unlisted origin, recipient or route, the byte ceilings, budget stops and cancellation. Worker HTTP and `CONNECT` traffic cannot claim the exemption, even to a provider's host, and diff --git a/packages/ui-sdk/src/server/egress-proxy.ts b/packages/ui-sdk/src/server/egress-proxy.ts index 93ed5fd841..9593f4a5d2 100644 --- a/packages/ui-sdk/src/server/egress-proxy.ts +++ b/packages/ui-sdk/src/server/egress-proxy.ts @@ -14,6 +14,8 @@ export const WORKER_EGRESS_TRANSPORT_ENV = Object.freeze(["HTTP_PROXY", "HTTPS_P export interface EgressRecord { /** Only the server's concrete inference-relay admission supplies this tag. */ inference?: true; + /** Only a validated provider-relay operation supplies this tag (#3246); never with `inference`. */ + provider?: true; method: string; host: string; port: number; @@ -96,7 +98,7 @@ export async function startEgressProxy(options: EgressProxyOptions) { * CONNECT traffic has none and cannot claim one, whatever its destination. */ function operation(method: string, url: URL, relay?: "inference" | "provider") { - const inference = relay === "inference"; + const inference = relay === "inference", provider = relay === "provider"; const started = performance.now(); const controller = new AbortController(); controllers.add(controller); const host = hostname(url.hostname), port = Number(url.port || (url.protocol === "https:" ? "443" : "80")); @@ -106,7 +108,7 @@ export async function startEgressProxy(options: EgressProxyOptions) { if (finished) return; finished = true; finalOutcome = outcome; controllers.delete(controller); controller.abort(); // Records never contain request headers, content, credentials or query strings. - try { options.observe({ ...(inference ? { inference: true } : {}), method, host, port, ...(method === "CONNECT" ? {} : { path: url.pathname }), bytes, + try { options.observe({ ...(inference ? { inference: true } : {}), ...(provider ? { provider: true } : {}), method, host, port, ...(method === "CONNECT" ? {} : { path: url.pathname }), bytes, accounting: method === "CONNECT" ? "opaque_bytes" : "http_wire_bound", durationMs: performance.now() - started, outcome, ...(reason ? { reason } : {}) }); } catch { /* A recorder cannot keep a connection alive. */ } }; @@ -142,7 +144,7 @@ export async function startEgressProxy(options: EgressProxyOptions) { } if (narrowed()) { finish("denied", "taint_not_allowed"); return false; } // A recorder failure aborts the turn through its own signal; it cannot admit. - try { await options.admitted?.({ host, port, method, inference, provider: relay === "provider" }); } catch { finish("failed", "proxy_error"); return false; } + try { await options.admitted?.({ host, port, method, inference, provider }); } catch { finish("failed", "proxy_error"); return false; } if (stopped || controller.signal.aborted) { finish("cancelled", "turn_cancelled"); return false; } return true; }; diff --git a/packages/ui-sdk/tests/egress-proxy.test.ts b/packages/ui-sdk/tests/egress-proxy.test.ts index ce2187cb3e..1e8accfe0e 100644 --- a/packages/ui-sdk/tests/egress-proxy.test.ts +++ b/packages/ui-sdk/tests/egress-proxy.test.ts @@ -298,6 +298,10 @@ test("a tainted turn reaches only taint-allowed or already contacted hosts; the expect(await provider.admit(), "EGRESS_TAINT_EXEMPTS_PROVIDER_RELAY").toBe(true); provider.finish("completed"); expect(admitted.at(-1), "EGRESS_PROVIDER_ADMISSION_REPORTED").toEqual({ host: "127.0.0.1", inference: false, provider: true }); expect(records.at(-1)?.inference, "EGRESS_PROVIDER_RECORD_NOT_INFERENCE").toBeUndefined(); + expect(records.at(-1)?.provider, "EGRESS_PROVIDER_RECORD_MARKED").toBe(true); + // Worker and inference records never carry the provider tag. + expect(records.slice(0, -1).map(record => [record.inference, record.provider]), "EGRESS_ONLY_PROVIDER_RECORD_MARKED") + .toEqual([[undefined, undefined], [undefined, undefined], [undefined, undefined], [true, undefined]]); contacted.add("127.0.0.1"); expect((await get(proxy.socketPath, origin.url.href)).status, "EGRESS_TAINT_KEEPS_CONTACTED_HOST").toBe(200); contacted.clear(); allow.push("127.0.0.1"); diff --git a/packages/ui-server/src/governance/events.ts b/packages/ui-server/src/governance/events.ts index 5f200484b1..18cba8c47f 100644 --- a/packages/ui-server/src/governance/events.ts +++ b/packages/ui-server/src/governance/events.ts @@ -66,7 +66,7 @@ export const GOVERNANCE_EVENT_SCHEMAS = { method: z.string().min(1).max(20), path: z.string().max(16384).optional(), bytes: count, accounting: z.enum(["http_wire_bound", "opaque_bytes"]), durationMs: amount, outcome: z.enum(["completed", "denied", "failed", "cancelled"]), - inference: z.literal(true).optional(), reason: z.string().max(200).optional(), + inference: z.literal(true).optional(), provider: z.literal(true).optional(), reason: z.string().max(200).optional(), })), steering_change: kind(1, z.strictObject({ path, sequence: count, beforeHash: policyHash, afterHash: policyHash, taintSourceEventId: z.number().int().positive().nullable(), diff --git a/packages/ui-server/src/governance/session-taint.ts b/packages/ui-server/src/governance/session-taint.ts index e88792657c..365a8258a9 100644 --- a/packages/ui-server/src/governance/session-taint.ts +++ b/packages/ui-server/src/governance/session-taint.ts @@ -35,15 +35,17 @@ export function insertFirstTaint(db: Database, row: GovernanceEventRow): boolean } /** - * Hosts the session's turn proxies admitted before, excluding the inference - * relay. The proxy charges bytes only after admission, so a charged record is - * admission evidence whatever its final outcome; an attempt cancelled or - * refused before admission never counts. + * Hosts the session's turn proxies admitted before, excluding both host + * relays: the inference relay and a validated provider-relay operation, whose + * host never becomes one the worker's own traffic may reach once tainted, in + * any turn (#3246). The proxy charges bytes only after admission, so a charged + * record is admission evidence whatever its final outcome; an attempt + * cancelled or refused before admission never counts. */ export function contactedHosts(db: Database, sessionId: string | null): string[] { if (!sessionId) return []; const rows = db.query(`SELECT DISTINCT json_extract(payload, '$.host') AS host FROM governance_events WHERE kind='egress_connection' AND session_id=? AND json_extract(payload, '$.bytes') > 0 - AND json_extract(payload, '$.inference') IS NULL`).all(sessionId) as { host: string }[]; + AND json_extract(payload, '$.inference') IS NULL AND json_extract(payload, '$.provider') IS NULL`).all(sessionId) as { host: string }[]; return rows.map(row => row.host); } diff --git a/packages/ui-server/tests/provider-relay-taint.test.ts b/packages/ui-server/tests/provider-relay-taint.test.ts index 7e08461c0d..d273a8ba34 100644 --- a/packages/ui-server/tests/provider-relay-taint.test.ts +++ b/packages/ui-server/tests/provider-relay-taint.test.ts @@ -1,7 +1,8 @@ /** * #3246: a validated provider-relay operation neither taints a governed session * nor is narrowed by its taint (G6), so tool order no longer decides whether - * WebFetch or reranking works. Composed as a turn runs it: the real provider + * WebFetch or reranking works. Its `provider: true` connection record never + * makes its host a contacted one for the worker, in this turn or a later one. Composed as a turn runs it: the real provider * relay shares the real turn proxy's admission, and taint lives in the * session's governance record. The provider is a fictional loopback Gemini * endpoint the operator lists; nothing here needs a key or the network. @@ -111,7 +112,11 @@ test("provider first, then WebFetch: the provider request never taints, and WebF { host: "127.0.0.1", port: provider.port, method: "POST", reason: "taint_allowlist", bytes: 0 }]); // Provider requests keep their own connection receipt, never tagged as inference. const providerRecords = voyage.events("egress_connection").map(event => event.payload).filter(record => record.host === "127.0.0.1" && record.outcome === "completed"); - expect(providerRecords.map(record => [record.method, record.path, record.inference]), "PROVIDER_CONNECTION_RECEIPTS").toEqual([["POST", RERANK, undefined], ["POST", RERANK, undefined]]); + expect(providerRecords.map(record => [record.method, record.path, record.inference, record.provider]), "PROVIDER_CONNECTION_RECEIPTS") + .toEqual([["POST", RERANK, undefined, true], ["POST", RERANK, undefined, true]]); + // Worker records never carry the provider tag, even to the provider's host. + expect(voyage.events("egress_connection").filter(record => record.payload.method === "CONNECT").every(record => record.payload.provider === undefined), + "WORKER_RECORDS_NEVER_PROVIDER").toBe(true); } finally { await first.stop(); db.close(); } }); @@ -186,3 +191,25 @@ test("a cancelled turn refuses a tainted session's provider request before conta expect(voyage.taints()).toHaveLength(1); } finally { await current.stop(); db.close(); } }); + +test("a provider request in one turn grants a later tainted turn's worker CONNECT no contacted-host pass (#3246)", async () => { + const db = createUiDb(":memory:"), voyage = session(db, "aeolus"); + const first = await turn(db, "aeolus", "turn-provider-earlier"); + reached.length = 0; + try { + expect((await first.rerank()).status, "EARLIER_TURN_PROVIDER_ADMITTED").toBe(200); + await first.stop(); + expect(voyage.taints(), "EARLIER_PROVIDER_CREATES_NO_TAINT").toEqual([]); + const marked = voyage.events("egress_connection").map(event => event.payload).filter(record => record.host === "127.0.0.1"); + expect(marked.map(record => [record.method, record.provider, record.inference]), "PROVIDER_RECORD_MARKED").toEqual([["POST", true, undefined]]); + const later = await turn(db, "aeolus", "turn-worker-later"); + try { + expect(await connectStatus(later.egress.socketPath, `127.0.0.2:${harbour.port}`), "LATER_TURN_WEBFETCH_TAINTS").toBe(200); + expect(voyage.taints()).toEqual([{ source: "egress_connection", tool: null, detail: `CONNECT 127.0.0.2:${harbour.port}` }]); + expect(await connectStatus(later.egress.socketPath, `127.0.0.1:${provider.port}`), "CROSS_TURN_PROVIDER_HOST_NARROWED").toBe(403); + // The worker's own earlier contact still counts: WebFetch's host stays reachable. + expect(await connectStatus(later.egress.socketPath, `127.0.0.2:${harbour.port}`), "LATER_TURN_OWN_HOST_STILL_CONTACTED").toBe(200); + expect((await later.rerank()).status, "LATER_TURN_PROVIDER_STILL_ADMITTED").toBe(200); + } finally { await later.stop(); } + } finally { await first.stop(); db.close(); } +});