From 60289e9575bd5e4a98ff533e88675a226d96494d Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 3 Nov 2026 15:34:20 +0000 Subject: [PATCH 1/2] CONTRACT: feat(ui-sdk): a tainted interactive session asks before a new destination (#3430) When a tainted session's connection passes deny, allowlist mode and the byte ceiling but matches neither taint.egress.allow nor a contacted host, the turn proxy now asks through the existing tool-permission card (Network, kind command) instead of refusing silently. The card names the destination, the session's first taint source and the consequence of allowing. An allowed host's admission and charged egress_connection record keep it admitted for the rest of the session; concurrent connections to one host share one card. A declined connection gets a 403 whose status text and body say the user declined. Voice keeps refusing without a card; autonomous turns have no turn proxy. G6 records the dated supersession (maintainer ruling A); the contract index, the governance-events component, the HTTP egress_denial row and the hosting guide describe the card. Refs #3430 Co-Authored-By: Claude Opus 5.5 --- .changeset/tainted-destinations-ask.md | 6 + docs/decisions/governed-writable-workers.md | 45 +++- docs/hosting/agent-workers.md | 8 +- docs/http-api.md | 2 +- docs/integration-contract.md | 13 ++ docs/integration-contract/http.md | 16 ++ .../tests/render/approval-effect.test.tsx | 32 +++ packages/ui-sdk/src/server/egress-proxy.ts | 80 +++++-- packages/ui-sdk/tests/egress-proxy.test.ts | 21 ++ packages/ui-server/src/brain/turn-egress.ts | 52 ++++- .../tests/tainted-destination-ask.test.ts | 206 ++++++++++++++++++ 11 files changed, 446 insertions(+), 35 deletions(-) create mode 100644 .changeset/tainted-destinations-ask.md create mode 100644 packages/ui-server/tests/tainted-destination-ask.test.ts diff --git a/.changeset/tainted-destinations-ask.md b/.changeset/tainted-destinations-ask.md new file mode 100644 index 0000000000..2959c1ec68 --- /dev/null +++ b/.changeset/tainted-destinations-ask.md @@ -0,0 +1,6 @@ +--- +"@schlessera/brain-ui-sdk": minor +"@schlessera/brain-ui-server": minor +--- + +A tainted interactive session now asks before reaching a new destination instead of refusing it silently (#3430). When a governed or strict turn behind the egress proxy connects to a host outside its `taint.egress.allow` list and the hosts the session already contacted, the user sees a `Network` permission card naming the host, what tainted the session, and that allowing it admits the host for the rest of the session. Allowing admits the connection and every later one to that host in the session; declining refuses it with a 403 whose status text and body tell the tool the user declined. Voice turns still refuse without a card, autonomous turns are unchanged, and `deny` and `allowlist` egress modes still refuse first. `startEgressProxy`'s `taint` option gains an optional `approve` callback. diff --git a/docs/decisions/governed-writable-workers.md b/docs/decisions/governed-writable-workers.md index 95059f4307..d2e784a903 100644 --- a/docs/decisions/governed-writable-workers.md +++ b/docs/decisions/governed-writable-workers.md @@ -2177,7 +2177,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:80-213`). 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 @@ -3738,7 +3738,7 @@ outward host skips the card only while every classified call in progress is a visible read, or an approved outward action that names that host. A GitHub write names the GitHub API hosts, and a push or HTTP write names its target's host. Any unknown or opaque call in progress withholds the exception -(`createOutwardCalls`, `packages/ui-server/src/brain/turn-egress.ts:36-58`). +(`createOutwardCalls`, `packages/ui-server/src/brain/turn-egress.ts:56-78`). A background process left by an earlier call can still connect inside such a window; the proxy records it either way. @@ -3783,7 +3783,9 @@ Taint is sticky for the session, because that content stays in the context window. A tainted session runs under tighter rules: - egress switches to the policy's `taint.egress` allow-list, which by default - is the hosts already used in the session plus the inference relay; + is the hosts already used in the session plus the inference relay (an + interactive turn asks before any other host since 2026-11-03, see + [below](#tainted-destinations-ask)); - every outward action asks, even if `outward.allow` would allow it; - writes to steering artifacts are flagged in the journal (below). @@ -3829,9 +3831,10 @@ first byte. Once the session is tainted, a new connection must pass the ordinary egress rules and also match `taint.egress.allow` or a host the 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 +`egress_denial` with reason `taint_allowlist` (an interactive turn asks first +since 2026-11-03, see [below](#tainted-destinations-ask)). The taint list +narrows and never widens: deny and `allowlist` mode still apply first (`prepareTurnEgress`, +`packages/ui-server/src/brain/turn-egress.ts:80-213`). Hosts without managed native storage have no proxy, so the Bash classifier remains their shell rule and nothing narrows their egress. @@ -3864,6 +3867,36 @@ workspaces/x/README`, or a marked file) does not taint. Path detection is not extended to shell arguments, because parsing them is the shell classifier this ruling removes. File tools reading the same path still taint. + + +**Tainted destinations ask — 2026-11-03 +([#3430](https://github.com/schlessera/brain-kit/issues/3430)).** This +supersedes the refusal in the implemented note above for interactive turns. +The silent, final refusal read as an outage: the agent saw `proxy refused the +connection` or a bare 403, the user was never asked, and the only workaround +was a hostname-wide `taint.egress.allow`. Now, when a tainted interactive +turn's connection passes deny, `allowlist` mode and the byte ceiling but +matches neither `taint.egress.allow` nor a contacted host, the proxy asks +through the turn's tool-permission card (`toolName: "Network"`, `kind: +"command"`, never remembered as a tool grant) before refusing +(`const narrowing`, `packages/ui-sdk/src/server/egress-proxy.ts:148-153`). The +card names the destination, the session's first taint source and the +consequence of allowing it +(`taintedDestinationDescription`, `packages/ui-server/src/brain/turn-egress.ts:35-40`). +Concurrent connections to the same host share one card. An allowed +connection's admission adds its host to the turn's contacted hosts, and its +charged `egress_connection` record carries the host into the session's later +turns, so it is not asked for again; a different host still asks +(`const approveTainted`, `packages/ui-server/src/brain/turn-egress.ts:153-164`). +A decline refuses: the record stays an `egress_denial` with reason +`taint_allowlist`, and the 403 carries a short reason the tool can print (`function refusal`, +`packages/ui-sdk/src/server/egress-proxy.ts:70-74`). Stopping the turn while the +card is pending cancels the connection, and a late allow admits nothing. Voice turns, which have no +grant surface, and autonomous turns, which have no turn proxy, refuse without +a card as before; deny and `allowlist` mode still refuse first. Maintainer +ruling A on #3430; B (ask only for reads) and C (keep refusing with an +after-the-fact notice) were rejected. + **Files the user marks untrusted — 2026-11-02 ([#2673](https://github.com/schlessera/brain-kit/issues/2673)).** A user can mark a brain file untrusted from Files, and the recorder above then treats an diff --git a/docs/hosting/agent-workers.md b/docs/hosting/agent-workers.md index 8a84e768f0..2ae67da314 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:90-96`). 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 @@ -1618,7 +1618,11 @@ A tainted session's outward actions all ask, whatever `outward.allow` says, on both backends. On the turn proxy, every admitted connection other than the inference relay taints the session too, and a tainted session's new connections reach only `taint.egress.allow` and hosts its proxies already -admitted. Refusals are `egress_denial` events with reason `taint_allowlist`. +admitted. In an interactive turn, a connection to any other host first shows +a permission card naming the host and what tainted the session; allowing it +admits that host for the rest of the session (#3430). Voice turns refuse +without a card. Refusals, including a declined card, are `egress_denial` +events with reason `taint_allowlist`. Without the proxy (hosts without managed native storage) nothing narrows egress, and the capabilities note says so. On a turn behind the proxy, the Bash classifier above is off: the proxy's connection taint is the shell signal, so diff --git a/docs/http-api.md b/docs/http-api.md index 432e9dc0e3..3469543d7c 100644 --- a/docs/http-api.md +++ b/docs/http-api.md @@ -1319,7 +1319,7 @@ read by any authenticated principal. | `state_room_warning` | 1 | `usedBytes`, `allowanceBytes`, `observedAt` | A resumed conversation's measured state reached its existing 75% warning threshold. The numbers and Unix-millisecond timestamp are the same observation sent with its result and history. One quiet event per session, backend and allowance; it does not change admission or start a continuation. | | `budget_block` | 1 | `scope`, `unit`, `limit`, `observed`, `source`, `stage` | A block limit was reached. `stage` is `admission`, `mid_turn` or `sdk_backstop`. | | `scope_cap` | 1 | `cap`, `limit`, `observed`, `overshoot`, `frozen`, `outcome`, `source` | A per-turn cap was reached. `cap` is `files_changed`, `minutes`, `tool_calls`, `free_space_floor` or `turn_bytes`; `overshoot` is how far past the cap the turn went, in the cap's unit; `outcome` is `paused`, `continued`, `stopped`, `voice_stopped` or `turn_ended`. `paused` records the confirmed freeze before the user decides; retained turn scope receipts record its eventual decision or interruption. A free-space overshoot is the measured deficit below its floor. | -| `egress_denial` | 1 | `host`, `port`, `method`, `reason`, `bytes` | The egress proxy refused a connection. `method` is set for plain HTTP; `reason` is `denied_host`, `not_allowlisted`, `byte_cap` or `taint_allowlist`. | +| `egress_denial` | 1 | `host`, `port`, `method`, `reason`, `bytes` | The egress proxy refused a connection. `method` is set for plain HTTP; `reason` is `denied_host`, `not_allowlisted`, `byte_cap` or `taint_allowlist`; `taint_allowlist` includes a tainted destination the user declined (#3430). | | `strict_fallback` | 1 | `path`, `reason` | A turn ran under `strict` instead of `governed` because a protected path is a `symlink`, a `hardlink` or a `mount_point`. | | `revert_conflict` | 1 | `conflicts`, `restored` | A revert skipped paths that changed after the reverted turn. Each conflict is `{ path, state }`, with `state` one of `changed`, `deleted`, `created` or `type_changed`; `restored` counts the paths it did restore. | | `outward_action` | 1 | `tool`, `input`, `inputTruncated`, `action`, `target`, `historyRewrite`, `tainted`, `decision`, `rule` | An action outside the brain in the user's name, allowed or not. `action` is `git_push`, `gh_write`, `mcp_tool`, `http_write` or `outward_host_connect`; `decision` is `policy_allowed`, `approved`, `declined` or `refused`; `rule` is the matching `outward.allow` rule or `null`. | diff --git a/docs/integration-contract.md b/docs/integration-contract.md index 9d164ffd30..7f002712cd 100644 --- a/docs/integration-contract.md +++ b/docs/integration-contract.md @@ -20,6 +20,19 @@ 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). +## Tainted destinations ask (additive, #3430) + +In a tainted interactive session behind the turn egress proxy, a connection to +a host outside the session's taint allow-list and contacted hosts raises the +existing tool-permission request (`toolName: "Network"`, `kind: "command"`) +instead of being refused at once. An allow admits that host for the rest of +the session. The request shape, the governance event kinds and the +`egress_denial` reasons are unchanged; `egress_connection` gains the `reason` +value `taint_not_approved` for a declined card. Voice and +autonomous turns keep refusing without a request. See the +[governance events component](integration-contract/http.md#tainted-destinations-ask-additive-3430) +and the [decision](decisions/governed-writable-workers.md#tainted-destinations-ask). + ## Shell taint behind the egress proxy (breaking before 1.0, #3429) On a turn whose worker runs behind the turn egress proxy diff --git a/docs/integration-contract/http.md b/docs/integration-contract/http.md index 0abc646a61..1f1460f2f2 100644 --- a/docs/integration-contract/http.md +++ b/docs/integration-contract/http.md @@ -294,6 +294,22 @@ turn behind the turn egress proxy, `taint` is no longer recorded with the proxy still records both. The payload shape and version are unchanged, and stored events keep their recorded sources. + + +**Tainted destinations ask (additive, #3430).** In a tainted interactive turn +behind the proxy, a connection to a host outside `taint.egress.allow` and the +session's contacted hosts now raises the existing tool-permission request +before it is refused: `toolName: "Network"`, `kind: "command"`, `input` of +`{ host, port, method, target }` with `target` as `host:port`, and a +`description` naming what tainted the session and what allowing does. No +request field, kind or card variant is added. An allowed connection records +`egress_connection` as any admitted one does; a declined one records +`egress_connection` with `reason: "taint_not_approved"` and the existing +`egress_denial` with `reason: "taint_allowlist"`. A turn stopped while the card +is pending records the connection as `cancelled` with `turn_cancelled`, as any +connection its turn stops. Voice turns refuse without a request, as before, +with `reason: "taint_not_allowed"`. + The kinds and each kind's payload are versioned separately. A payload change that is not purely additive bumps that kind's `schemaVersion`, and stored events keep the version they were written with, so a new version or a new diff --git a/packages/ui-react/tests/render/approval-effect.test.tsx b/packages/ui-react/tests/render/approval-effect.test.tsx index 580a712efe..f0f8dacab6 100644 --- a/packages/ui-react/tests/render/approval-effect.test.tsx +++ b/packages/ui-react/tests/render/approval-effect.test.tsx @@ -82,3 +82,35 @@ describe("the effect of a confirmed command, on the card", () => { expect(view.container.textContent ?? "").not.toContain(EFFECT); }); }); + +// A tainted session's new destination asks (#3430). The host sends a +// `Network` command approval whose input carries the destination as `target` +// and whose description names what tainted the session and what allowing +// does; both cards draw them, from the existing request shape. +describe("a tainted session's destination card", () => { + const COPY = "This session fetched a web page, so content you did not write may be steering it. " + + "Allow it to connect to aeaea.example:443? Allowing lets it send data to aeaea.example for the rest of this session without asking again."; + const network = pending({ + id: "net-1", + name: "Network", + input: { host: "aeaea.example", port: 443, method: "CONNECT", target: "aeaea.example:443" }, + inputJson: '{"host":"aeaea.example","port":443,"method":"CONNECT","target":"aeaea.example:443"}', + approvalDescription: COPY, + }); + + test("the Actions-pane card names the destination, the taint source and the consequence", () => { + const view = render( {}} />); + const card = view.getByRole("group", { name: "Approval: Network" }); + expect(card.textContent, "TAINTED_CARD_DESTINATION").toContain("aeaea.example:443"); + expect(card.textContent, "TAINTED_CARD_SOURCE").toContain("This session fetched a web page"); + expect(card.textContent, "TAINTED_CARD_CONSEQUENCE").toContain("for the rest of this session"); + }); + + test("the transcript's card says the same and offers no always-allow", () => { + const view = render( {}} />); + const panel = view.container.textContent ?? ""; + expect(panel).toContain("aeaea.example:443"); + expect(panel).toContain(COPY); + expect(panel.toLowerCase(), "TAINTED_CARD_NOT_REMEMBERED").not.toContain("always"); + }); +}); diff --git a/packages/ui-sdk/src/server/egress-proxy.ts b/packages/ui-sdk/src/server/egress-proxy.ts index c01b5b86bc..092ac2c860 100644 --- a/packages/ui-sdk/src/server/egress-proxy.ts +++ b/packages/ui-sdk/src/server/egress-proxy.ts @@ -42,8 +42,11 @@ export interface EgressProxyOptions { * 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. + * `approve`, when present, asks before refusing a narrowed destination + * (#3430); absent, or resolving anything but `true`, refuses. */ - taint?: { allow: readonly string[]; tainted(): boolean; contacted(host: string): boolean }; + taint?: { allow: readonly string[]; tainted(): boolean; contacted(host: string): boolean; + approve?(destination: { host: string; port: number; method: string }, signal: AbortSignal): Promise }; /** * A destination passed every check; called before its first upstream byte. * A returned promise is awaited first, so a durable record it makes commits @@ -59,6 +62,16 @@ function matches(host: string, patterns: readonly string[]): boolean { return pattern.startsWith("*.") ? host.endsWith(pattern.slice(1)) && host !== pattern.slice(2) : host === pattern; }); } +/** + * What a tool is told when the user declined a destination a tainted session + * asked for (#3430): curl, git and HTTP clients print the status text or body. + * Every other refusal keeps its bare 403. + */ +function refusal(reason: string | undefined): { status: string; body: string } | undefined { + if (reason !== "taint_not_approved") return undefined; + return { status: "Forbidden - declined by the user", + body: "Blocked: this session read untrusted content, this host is outside its allow-list, and the user declined the connection. Do not retry it; say what you needed it for.\n" }; +} /** No header controlled by the peer can select a second upstream or carry proxy authority. */ const hopHeaders = new Set(["proxy-authorization", "proxy-connection", "connection", "keep-alive", "te", "trailer", "transfer-encoding", "upgrade"]); function headers(message: IncomingMessage): Record { @@ -95,10 +108,10 @@ export async function startEgressProxy(options: EgressProxyOptions) { const controller = new AbortController(); controllers.add(controller); const host = hostname(url.hostname), port = Number(url.port || (url.protocol === "https:" ? "443" : "80")); let bytes = 0, finished = false; - let finalOutcome: EgressRecord["outcome"] | undefined; + let finalOutcome: EgressRecord["outcome"] | undefined, finalReason: string | undefined; const finish = (outcome: EgressRecord["outcome"], reason?: string) => { if (finished) return; - finished = true; finalOutcome = outcome; controllers.delete(controller); controller.abort(); + finished = true; finalOutcome = outcome; finalReason = reason; 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, accounting: method === "CONNECT" ? "opaque_bytes" : "http_wire_bound", @@ -112,34 +125,47 @@ export async function startEgressProxy(options: EgressProxyOptions) { if (count > options.maxBytes - usedBytes) { finish("denied", "max_bytes_per_turn"); return false; } usedBytes += count; bytes += count; return true; }; + /** One approval wait; cancelling this connection or the turn resolves it as refused. */ + const approval = async (ask: ((destination: { host: string; port: number; method: string }, signal: AbortSignal) => Promise) | undefined) => { + if (!ask) return false; + let approved = false; + let cancelled: (() => void) | undefined; + try { + const cancellation = new Promise(resolve => { + cancelled = () => resolve(false); + controller.signal.addEventListener("abort", cancelled, { once: true }); + if (controller.signal.aborted) resolve(false); + }); + approved = await Promise.race([ask({ host, port, method }, controller.signal), cancellation]) === true; + } catch { /* A failed approval denies. */ } + finally { if (cancelled) controller.signal.removeEventListener("abort", cancelled); } + return approved && !controller.signal.aborted && !stopped; + }; + // An approval of this destination outside the taint allow-list (#3430). + let granted = false; + // Checked again after an approval wait, during which another connection may taint the session. + const narrowed = () => !granted && !inference && options.taint?.tainted() && !matches(host, options.taint.allow) && !options.taint.contacted(host); + const narrowing = async () => { + if (!narrowed()) return true; + if (options.taint?.approve) granted = await approval(options.taint.approve.bind(options.taint)); + if (!granted) finish(stopped ? "cancelled" : "denied", options.taint?.approve ? "taint_not_approved" : "taint_not_allowed"); + return granted; + }; const admit = async () => { 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); - if (narrowed()) { finish("denied", "taint_not_allowed"); return false; } if (usedBytes >= options.maxBytes) { finish("denied", "max_bytes_per_turn"); return false; } + if (!await narrowing()) return false; if (matches(host, options.outwardHosts) || options.outwardPorts?.includes(port)) { - let approved = false; - let cancelled: (() => void) | undefined; - try { - const cancellation = new Promise(resolve => { - cancelled = () => resolve(false); - controller.signal.addEventListener("abort", cancelled, { once: true }); - if (controller.signal.aborted) resolve(false); - }); - approved = await Promise.race([options.approveOutward?.({ host, port, method }, controller.signal), cancellation]) === true; - } catch { /* Missing/failed approval denies. */ } - finally { if (cancelled) controller.signal.removeEventListener("abort", cancelled); } - if (!approved || controller.signal.aborted || stopped) { finish(stopped ? "cancelled" : "denied", "outward_not_approved"); return false; } + if (!await approval(options.approveOutward)) { finish(stopped ? "cancelled" : "denied", "outward_not_approved"); return false; } } - if (narrowed()) { finish("denied", "taint_not_allowed"); return false; } + if (!await narrowing()) 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; } if (stopped || controller.signal.aborted) { finish("cancelled", "turn_cancelled"); return false; } return true; }; - return { finish, charge, admit, signal: controller.signal, outcome: () => finalOutcome }; + return { finish, charge, admit, signal: controller.signal, outcome: () => finalOutcome, reason: () => finalReason }; } server.on("connect", (request, client, head) => { client.on("error", () => {}); @@ -153,7 +179,12 @@ export async function startEgressProxy(options: EgressProxyOptions) { let connected = false; client.once("close", () => op.finish(stopped || !connected ? "cancelled" : "completed")); void (async () => { - if (!await op.admit() || client.destroyed) { client.end("HTTP/1.1 403 Forbidden\r\nConnection: close\r\n\r\n"); return; } + if (!await op.admit() || client.destroyed) { + const declined = refusal(op.reason()); + client.end(declined ? `HTTP/1.1 403 ${declined.status}\r\nContent-Type: text/plain; charset=utf-8\r\nContent-Length: ${Buffer.byteLength(declined.body)}\r\nConnection: close\r\n\r\n${declined.body}` + : "HTTP/1.1 403 Forbidden\r\nConnection: close\r\n\r\n"); + return; + } const upstream = track(connect({ host: target.hostname, port: Number(target.port || 80) })); upstream.once("connect", () => { if (stopped || client.destroyed) { upstream.destroy(); return; } @@ -180,7 +211,12 @@ export async function startEgressProxy(options: EgressProxyOptions) { const op = operation(request.method ?? "GET", target); response.once("close", () => op.finish(stopped ? "cancelled" : response.writableFinished ? "completed" : "cancelled")); void (async () => { - if (!await op.admit() || response.destroyed) { response.writeHead(403); response.end(); return; } + if (!await op.admit() || response.destroyed) { + const declined = refusal(op.reason()); + if (declined) response.writeHead(403, declined.status, { "content-type": "text/plain; charset=utf-8" }).end(declined.body); + else { response.writeHead(403); response.end(); } + return; + } const outgoingHeaders = { ...headers(request), host: target.host, connection: "close" }; // Include the complete observable target and headers: a body-only cap // would allow uncharged exfiltration in query strings or header values. diff --git a/packages/ui-sdk/tests/egress-proxy.test.ts b/packages/ui-sdk/tests/egress-proxy.test.ts index a5ceb71e0f..504c113963 100644 --- a/packages/ui-sdk/tests/egress-proxy.test.ts +++ b/packages/ui-sdk/tests/egress-proxy.test.ts @@ -299,6 +299,27 @@ test("a tainted turn reaches only taint-allowed or already contacted hosts; the expect((await get(proxy.socketPath, origin.url.href)).status, "EGRESS_TAINT_ALLOW_LIST").toBe(200); } finally { proxy.stop(); origin.stop(true); } }); +test("a narrowed destination asks through taint.approve before refusing; a failed or absent approval refuses (#3430)", async () => { + let calls = 0; const records: EgressRecord[] = [], asked: Array<{ host: string; port: number; method: string }> = []; + const origin = Bun.serve({ hostname: "127.0.0.1", port: 0, fetch() { calls++; return new Response("Ithaca"); } }); + let answer: () => Promise = async () => true; + const proxy = await startEgressProxy({ ...defaults(records), maxBytes: 65536, + taint: { allow: [], tainted: () => true, contacted: () => false, approve: async destination => { asked.push(destination); return answer(); } } }); + try { + expect((await get(proxy.socketPath, origin.url.href)).status, "EGRESS_TAINT_APPROVED_ADMITS").toBe(200); + expect(asked, "EGRESS_TAINT_APPROVE_NAMES_DESTINATION").toEqual([{ host: "127.0.0.1", port: origin.port!, method: "GET" }]); + answer = async () => { throw new Error("Scylla"); }; + const refused = await get(proxy.socketPath, origin.url.href); + expect(refused.status, "EGRESS_TAINT_FAILED_APPROVAL_REFUSES").toBe(403); + expect(refused.body, "EGRESS_TAINT_DECLINE_REASON").toContain("the user declined the connection"); + expect(records.at(-1)).toMatchObject({ outcome: "denied", reason: "taint_not_approved", bytes: 0 }); + // The relay's own admission is never narrowed, so never asked about. + const relay = proxy.inference("POST", new URL(`${origin.url.href}v1/messages`), new AbortController().signal); + expect(await relay.admit()).toBe(true); relay.finish("completed"); + expect(asked, "EGRESS_TAINT_INFERENCE_NOT_ASKED").toHaveLength(2); + expect(calls).toBe(1); + } finally { proxy.stop(); origin.stop(true); } +}); test("taint narrowing never overrides deny or the ordinary allowlist, and its patterns are validated", async () => { const records: EgressRecord[] = []; const origin = Bun.serve({ hostname: "127.0.0.1", port: 0, fetch: () => new Response("Ithaca") }); diff --git a/packages/ui-server/src/brain/turn-egress.ts b/packages/ui-server/src/brain/turn-egress.ts index d508bd3334..58ea2c8362 100644 --- a/packages/ui-server/src/brain/turn-egress.ts +++ b/packages/ui-server/src/brain/turn-egress.ts @@ -4,7 +4,7 @@ import { startEgressProxy, type EgressRecord } from "@schlessera/brain-ui-sdk/in import { requestToolPermission, type BackendActivityEvent, type BackendBridge } from "@schlessera/brain-ui-sdk/server"; import type { Database } from "bun:sqlite"; import type { GovernanceEventInput } from "../governance/events.js"; -import { contactedHosts, recordFirstTaint, sessionTaint } from "../governance/session-taint.js"; +import { contactedHosts, recordFirstTaint, sessionTaint, type TaintSource } from "../governance/session-taint.js"; import type { GovernanceWrites } from "../governance/event-writes.js"; type Classification = Extract["classification"]; @@ -19,6 +19,26 @@ export const MAIL_SUBMISSION_HOSTS = ["gmail.googleapis.com", "graph.microsoft.c "api.fastmail.com", "api.sendgrid.com", "smtp.sendgrid.net", "api.mailgun.net", "api.eu.mailgun.net", "smtp.mailgun.org", "smtp.eu.mailgun.org", "api.postmarkapp.com", "smtp.postmarkapp.com", "api.resend.com", "smtp.resend.com"] as const; +/** What the session did that tainted it, as the destination card names it (#3430). */ +const TAINT_SOURCE_WORDING: Readonly> = { + web_fetch: "fetched a web page", web_search: "ran a web search", staged_share: "opened a shared file", + workspace_read: "read a file under workspaces/", mcp_document: "read a document from an external MCP server", + user_marked: "read a file marked untrusted", egress_connection: "received data from another site", + fetching_command: "ran a command that fetches content", unclassified_command: "ran a command that may have fetched content", +}; + +/** + * The card a tainted interactive session raises for a destination outside its + * taint allow-list (#3430): the destination, what tainted the session, and + * what allowing it does. + */ +export function taintedDestinationDescription(destination: { host: string; port: number; method: string }, source: TaintSource | null): string { + const cause = source ? `This session ${TAINT_SOURCE_WORDING[source]}, so content you did not write may be steering it.` + : "This session read content you did not write, which may be steering it."; + return `${cause} Allow it to connect to ${destination.host}:${destination.port}? ` + + `Allowing lets it send data to ${destination.host} for the rest of this session without asking again.`; +} + /** Hosts an approved visible action names; an unresolved destination names none. */ function actionHosts(action: Classification["actions"][number]): readonly string[] { if (action.action === "gh_write") return GITHUB_API_HOSTS; @@ -109,7 +129,8 @@ export async function prepareTurnEgress(options: { return normalized.startsWith("*.") ? record.host.endsWith(normalized.slice(1)) && record.host !== normalized.slice(2) : record.host === normalized; }); const reason = record.reason === "destination_not_allowed" ? denied ? "denied_host" : "not_allowlisted" - : record.reason === "max_bytes_per_turn" ? "byte_cap" : record.reason === "taint_not_allowed" ? "taint_allowlist" : undefined; + : record.reason === "max_bytes_per_turn" ? "byte_cap" + : record.reason === "taint_not_allowed" || record.reason === "taint_not_approved" ? "taint_allowlist" : undefined; if (reason) track(options.record({ ...base(), kind: "egress_denial", payload: { host: record.host, port: record.port, method: record.method, reason, bytes: record.bytes, } })); @@ -119,11 +140,34 @@ export async function prepareTurnEgress(options: { * Any admitted connection other than the inference relay taints the session * (G6), recorded before its first byte. Sticky: once read, never re-read. */ + // A taint submitted but not yet committed counts (#2850). + const firstTaint = () => db ? writes ? writes.taint(options.turnId, options.sessionId()) : sessionTaint(db, options.turnId, options.sessionId()) : null; + /** + * One card per destination host at a time: concurrent connections to the + * same new host share its answer. An allowed connection's admission adds + * its host to `contacted`, so the rest of this turn admits it, and its + * charged `egress_connection` record carries it into later turns + * (`contactedHosts`). + */ + const asking = new Map>(); + const approveTainted = async (destination: { host: string; port: number; method: string }, signal: AbortSignal): Promise => { + let pending = asking.get(destination.host); + if (!pending) { + pending = requestToolPermission(options.bridge, { toolUseId: crypto.randomUUID(), toolName: "Network", kind: "command", + input: { ...destination, target: `${destination.host}:${destination.port}` }, + description: taintedDestinationDescription(destination, firstTaint()?.source ?? null), + }).then(decision => decision.behavior === "allow", () => false).finally(() => asking.delete(destination.host)); + asking.set(destination.host, pending); + } + const allowed = await pending; + return allowed && !signal.aborted; + }; const taint = db ? { allow: options.policy.taint.egress.allow, - // A taint submitted but not yet committed counts (#2850). - tainted: () => tainted ||= (writes ? writes.taint(options.turnId, options.sessionId()) : sessionTaint(db, options.turnId, options.sessionId())) !== null, + tainted: () => tainted ||= firstTaint() !== null, contacted: (host: string) => contacted.has(host), + // Voice has no grant surface; it keeps refusing without a card (#3430). + ...(options.origin === "interactive" ? { approve: approveTainted } : {}), } : undefined; /** * The proxy awaits this before the connection's first byte, so the taint diff --git a/packages/ui-server/tests/tainted-destination-ask.test.ts b/packages/ui-server/tests/tainted-destination-ask.test.ts new file mode 100644 index 0000000000..0ffa880d0c --- /dev/null +++ b/packages/ui-server/tests/tainted-destination-ask.test.ts @@ -0,0 +1,206 @@ +/** + * A tainted interactive session asks before reaching a destination outside + * its taint allow-list (#3430). Every case runs the real turn proxy on + * loopback with a permission bridge double at `requestPermission`, the + * lowest request method every host's card goes through. + */ +import { expect, test } from "bun:test"; +import { request } from "node:http"; +import { connect } from "node:net"; +import { resolveGovernancePolicy, type GovernancePolicyInput } from "@schlessera/brain-common/internal/governance-policy"; +import type { BackendBridge, PermissionDecision, PermissionRequest } from "@schlessera/brain-ui-sdk/server"; +import { createUiDb } from "../src/db/client.js"; +import { queryGovernanceEvents, recordGovernanceEvent } from "../src/governance/events.js"; +import { prepareTurnEgress, taintedDestinationDescription } from "../src/brain/turn-egress.js"; + +function get(socketPath: string, target: string): Promise<{ status: number; statusText: string; body: string }> { + return new Promise((resolve, reject) => { + const child = request({ socketPath, path: target }, response => { + let body = ""; response.on("data", bytes => body += bytes); + response.once("end", () => resolve({ status: response.statusCode!, statusText: response.statusMessage ?? "", body })); + response.once("error", reject); + }); + child.once("error", reject); child.end(); + }); +} +function tunnel(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; if (text.startsWith("HTTP/1.1 200")) socket.destroy(); }); + socket.on("close", () => resolve(text)); socket.on("error", reject); + }); +} + +/** A session that fetched a web page earlier, and one host its proxy already reached. */ +function taintedSession() { + const db = createUiDb(":memory:"); + db.query("INSERT INTO sessions (id,title,created_at,last_active_at) VALUES ('ithaca','Ithaca',0,0)").run(); + recordGovernanceEvent(db, { kind: "taint", turnId: "turn-suitors", sessionId: "ithaca", actor: "interactive", model: null, profile: "governed", + payload: { source: "web_fetch", tool: "WebFetch", detail: "https://suitors.example/letter" } }); + return db; +} +interface Asks { requests: PermissionRequest[]; answer(decision: PermissionDecision): void; asked: Promise } +/** A bridge whose cards wait until the test answers them, in order. */ +function cards(): { bridge: BackendBridge; asks: Asks } { + const requests: PermissionRequest[] = [], waiting: Array<(decision: PermissionDecision) => void> = []; + let notify: () => void = () => {}; + const asks: Asks = { requests, answer: decision => waiting.shift()?.(decision), asked: new Promise(resolve => { notify = resolve; }) }; + const bridge = { emit() {}, requestPermission: (request: PermissionRequest) => { + requests.push(request); + const pending = new Promise(resolve => waiting.push(resolve)); + notify(); asks.asked = new Promise(resolve => { notify = resolve; }); + return pending; + } } as unknown as BackendBridge; + return { bridge, asks }; +} +/** The card for `pending`, or a named failure when the connection settles without one (the pre-#3430 refusal). */ +async function raised(asks: Asks, pending: Promise): Promise { + const settled = pending.then(() => "settled" as const, () => "settled" as const); + const outcome = await Promise.race([asks.asked.then(() => "asked" as const), settled]); + expect(outcome, "TAINTED_ASK_CARD_RAISED").toBe("asked"); +} +const turn = (db: ReturnType, bridge: BackendBridge, options: { turnId?: string; origin?: "interactive" | "voice"; policy?: GovernancePolicyInput; controller?: AbortController } = {}) => + prepareTurnEgress({ controller: options.controller ?? new AbortController(), policy: resolveGovernancePolicy(options.policy ?? { schema_version: 1 }), + turnId: options.turnId ?? "turn-island", sessionId: () => "ithaca", model: () => "claude-haiku-4-5", profile: "governed", + origin: options.origin ?? "interactive", bridge, record: event => recordGovernanceEvent(db, event), governanceDb: db }); +const events = (db: ReturnType, kind: "egress_connection" | "egress_denial") => + queryGovernanceEvents(db, { sessionId: "ithaca", kinds: [kind], limit: 20 }).map(event => event.payload as Record); + +test("a tainted interactive session asks before a new host, naming it and the taint source; allowing admits and records it", async () => { + const db = taintedSession(); let calls = 0; + const island = Bun.serve({ hostname: "127.0.0.2", port: 0, fetch() { calls++; return new Response("Aeaea"); } }); + const { bridge, asks } = cards(); + const proxy = await turn(db, bridge); + try { + const response = get(proxy.socketPath, island.url.href); + await raised(asks, response); + expect(calls, "TAINTED_ASK_WAITS_FOR_CARD").toBe(0); + expect(asks.requests).toHaveLength(1); + expect(asks.requests[0], "TAINTED_ASK_CARD_NAMES_DESTINATION_AND_SOURCE").toMatchObject({ toolName: "Network", kind: "command", + input: { host: "127.0.0.2", port: island.port, method: "GET", target: `127.0.0.2:${island.port}` }, + description: taintedDestinationDescription({ host: "127.0.0.2", port: island.port!, method: "GET" }, "web_fetch") }); + expect(asks.requests[0]!.description).toContain("fetched a web page"); + asks.answer({ behavior: "allow" }); + expect((await response).status, "TAINTED_ASK_ALLOW_ADMITS").toBe(200); + expect(calls).toBe(1); + proxy.stop(); + expect(events(db, "egress_connection"), "TAINTED_ASK_ALLOW_RECORDS_CONNECTION").toMatchObject([{ host: "127.0.0.2", port: island.port, outcome: "completed" }]); + expect(events(db, "egress_denial")).toEqual([]); + } finally { asks.answer({ behavior: "deny", message: "Fixture cleanup" }); proxy.stop(); island.stop(true); db.close(); } +}); + +test("declining refuses with a reason the tool sees, records the denial and contacts nothing", async () => { + const db = taintedSession(); let calls = 0; + const island = Bun.serve({ hostname: "127.0.0.2", port: 0, fetch() { calls++; return new Response("Aeaea"); } }); + const { bridge, asks } = cards(); + const proxy = await turn(db, bridge); + try { + const response = get(proxy.socketPath, island.url.href); + await raised(asks, response); asks.answer({ behavior: "deny", message: "Penelope declines" }); + const refused = await response; + expect(refused.status, "TAINTED_ASK_DENY_REFUSES").toBe(403); + expect(refused.statusText, "TAINTED_ASK_DENY_STATUS_TEXT").toBe("Forbidden - declined by the user"); + expect(refused.body, "TAINTED_ASK_DENY_REASON_VISIBLE").toContain("the user declined the connection"); + const connecting = tunnel(proxy.socketPath, `127.0.0.2:${island.port}`); + await raised(asks, connecting); asks.answer({ behavior: "deny", message: "Penelope declines" }); + const head = await connecting; + expect(head, "TAINTED_ASK_DENY_CONNECT_REASON_VISIBLE").toStartWith("HTTP/1.1 403 Forbidden - declined by the user\r\n"); + expect(head).toContain("the user declined the connection"); + expect(calls).toBe(0); + proxy.stop(); + expect(events(db, "egress_denial"), "TAINTED_ASK_DENY_RECORDED").toEqual([ + { host: "127.0.0.2", port: island.port, method: "GET", reason: "taint_allowlist", bytes: 0 }, + { host: "127.0.0.2", port: island.port, method: "CONNECT", reason: "taint_allowlist", bytes: 0 }]); + } finally { asks.answer({ behavior: "deny", message: "Fixture cleanup" }); proxy.stop(); island.stop(true); db.close(); } +}); + +test("an allowed host stays admitted for the rest of the session without asking; a different host still asks", async () => { + const db = taintedSession(); + const island = Bun.serve({ hostname: "127.0.0.2", port: 0, fetch: () => new Response("Aeaea") }); + const harbour = Bun.serve({ hostname: "127.0.0.3", port: 0, fetch: () => new Response("Ithaca") }); + const { bridge, asks } = cards(); + try { + const first = await turn(db, bridge, { turnId: "turn-aeaea" }); + const response = get(first.socketPath, island.url.href); + await raised(asks, response); asks.answer({ behavior: "allow" }); + expect((await response).status).toBe(200); + expect((await get(first.socketPath, island.url.href)).status, "TAINTED_GRANT_SAME_TURN").toBe(200); + first.stop(); + const second = await turn(db, bridge, { turnId: "turn-return" }); + try { + expect((await get(second.socketPath, island.url.href)).status, "TAINTED_GRANT_LATER_TURN").toBe(200); + expect(asks.requests, "TAINTED_GRANT_ASKS_ONCE").toHaveLength(1); + const other = get(second.socketPath, harbour.url.href); + await raised(asks, other); + expect(asks.requests.at(-1)?.input, "TAINTED_GRANT_IS_PER_HOST").toMatchObject({ host: "127.0.0.3" }); + asks.answer({ behavior: "deny", message: "Not this one" }); + expect((await other).status).toBe(403); + } finally { second.stop(); } + } finally { asks.answer({ behavior: "deny", message: "Fixture cleanup" }); island.stop(true); harbour.stop(true); db.close(); } +}); + +test("concurrent connections to the same new host share one card", async () => { + const db = taintedSession(); + const island = Bun.serve({ hostname: "127.0.0.2", port: 0, fetch: () => new Response("Aeaea") }); + const { bridge, asks } = cards(); + const proxy = await turn(db, bridge); + try { + const both = [get(proxy.socketPath, island.url.href), get(proxy.socketPath, `${island.url.href}again`)]; + await raised(asks, Promise.all(both)); await Bun.sleep(50); + expect(asks.requests, "TAINTED_ASK_ONE_CARD_PER_HOST").toHaveLength(1); + asks.answer({ behavior: "allow" }); + expect((await Promise.all(both)).map(result => result.status)).toEqual([200, 200]); + } finally { asks.answer({ behavior: "deny", message: "Fixture cleanup" }); proxy.stop(); island.stop(true); db.close(); } +}); + +test("voice refuses a narrowed host without a card, as before", async () => { + const db = taintedSession(); let calls = 0; + const island = Bun.serve({ hostname: "127.0.0.2", port: 0, fetch() { calls++; return new Response("Aeaea"); } }); + // A bridge that would allow at once: only the missing grant surface can refuse. + const asks: PermissionRequest[] = []; + const bridge = { emit() {}, requestPermission: async (request: PermissionRequest) => { asks.push(request); return { behavior: "allow" }; } } as unknown as BackendBridge; + const proxy = await turn(db, bridge, { origin: "voice" }); + try { + const refused = await get(proxy.socketPath, island.url.href); + expect(refused.status, "TAINTED_VOICE_REFUSES").toBe(403); + expect(refused.body, "TAINTED_VOICE_BARE_REFUSAL").toBe(""); + expect(asks, "TAINTED_VOICE_NO_CARD").toEqual([]); + expect(calls).toBe(0); + proxy.stop(); + expect(events(db, "egress_connection")).toMatchObject([{ outcome: "denied", reason: "taint_not_allowed" }]); + } finally { proxy.stop(); island.stop(true); db.close(); } +}); + +test("deny and allowlist mode refuse first, without a card", async () => { + const db = taintedSession(); let calls = 0; + const island = Bun.serve({ hostname: "127.0.0.2", port: 0, fetch() { calls++; return new Response("Aeaea"); } }); + const { bridge, asks } = cards(); + try { + for (const policy of [{ schema_version: 1, egress: { deny: ["127.0.0.2"] } }, { schema_version: 1, egress: { mode: "allowlist", allow: ["ithaca.invalid"] } }] as GovernancePolicyInput[]) { + const proxy = await turn(db, bridge, { policy }); + try { expect((await get(proxy.socketPath, island.url.href)).status).toBe(403); } finally { proxy.stop(); } + } + expect(asks.requests, "TAINTED_DENY_AND_ALLOWLIST_NO_CARD").toEqual([]); + expect(calls).toBe(0); + expect(events(db, "egress_denial").map(payload => payload.reason)).toEqual(["denied_host", "not_allowlisted"]); + } finally { island.stop(true); db.close(); } +}); + +test("cancelling the turn while the card is pending refuses the connection; a late allow admits nothing", async () => { + const db = taintedSession(); let calls = 0; + const island = Bun.serve({ hostname: "127.0.0.2", port: 0, fetch() { calls++; return new Response("Aeaea"); } }); + const { bridge, asks } = cards(); + const controller = new AbortController(); + const proxy = await turn(db, bridge, { controller }); + try { + const response = get(proxy.socketPath, island.url.href).catch(() => ({ status: 0, statusText: "", body: "" })); + await raised(asks, response); + controller.abort(); + asks.answer({ behavior: "allow" }); + expect((await response).status, "TAINTED_ASK_CANCEL_REFUSES").not.toBe(200); + await Bun.sleep(50); + expect(calls, "TAINTED_ASK_CANCEL_NO_CONTACT").toBe(0); + expect(events(db, "egress_connection"), "TAINTED_ASK_CANCEL_NOT_ADMITTED").toMatchObject([{ outcome: "cancelled", bytes: 0 }]); + } finally { proxy.stop(); island.stop(true); db.close(); } +}); From 7184e3eec8304f8494f755f14477658c4af3839a Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 3 Nov 2026 15:36:35 +0000 Subject: [PATCH 2/2] test(ui-server): the G6 session test declines the tainted destination card over the WebSocket (#3430) Refs #3430 Co-Authored-By: Claude Opus 5.5 --- packages/ui-server/tests/session-taint.test.ts | 15 +++++++++++++-- 1 file changed, 13 insertions(+), 2 deletions(-) diff --git a/packages/ui-server/tests/session-taint.test.ts b/packages/ui-server/tests/session-taint.test.ts index 077acf7aa8..3d643a7d78 100644 --- a/packages/ui-server/tests/session-taint.test.ts +++ b/packages/ui-server/tests/session-taint.test.ts @@ -31,7 +31,7 @@ const SKILL = ".claude/skills/voyage/SKILL.md"; * worker's curl and the turn journal. The backend is a fixture; the hook-level * outward wiring is proven by each backend's command-effect probe. */ -test("a WebFetch taints the session: outward asks, a non-listed host is refused, the skill edit is flagged, and the next turn keeps it", async () => { +test("a WebFetch taints the session: outward asks, a non-listed host asks and, declined, is refused, the skill edit is flagged, and the next turn keeps it", async () => { const storage = spyOn(startup, "isManagedWorkerStartupView").mockReturnValue(true); const root = await mkdtemp(resolve(tmpdir(), "odysseus-session-taint-")), brain = resolve(root, "brain"); await createFixtureBrain(resolve(import.meta.dir, "../../.."), brain); @@ -67,9 +67,18 @@ test("a WebFetch taints the session: outward asks, a non-listed host is refused, const app = await createApp({ config: resolveServerConfig({ BRAIN_PATH: brain, DB_PATH: resolve(root, "ui.db"), HOST: "127.0.0.1", AUTH_MODE: "none", NODE_ENV: "test", BRAIN_UI_MODEL_DISCOVERY: "0", BRAIN_UI_PRICING_DISCOVERY: "0" }), registry, observability: createRecordingObservability() }); const principal = createPrincipal(app.db, { authMethod: "password", label: "Odysseus taint", ttlSeconds: 60 }); + // Destination cards a tainted interactive turn raised (#3430); the user declines each. + const networkCards: Array<{ host: unknown }> = []; async function chat(text: string, sessionId?: string) { const count = seen.length, handlers = createWsHandlers(app.wsHost, principal), sent: string[] = []; - const ws = { send: (frame: string) => sent.push(frame), close() {}, readyState: 1 } as WSContext; + const ws = { send: (frame: string) => { + sent.push(frame); + const parsed = JSON.parse(frame) as { type?: string; toolName?: string; toolUseId?: string; turnId?: string; input?: { host?: unknown } }; + if (parsed.type !== "tool_approval_request" || parsed.toolName !== "Network") return; + networkCards.push({ host: parsed.input?.host }); + queueMicrotask(() => handlers.onMessage({ data: JSON.stringify({ type: "tool_denial", toolUseId: parsed.toolUseId, + message: "Penelope declines.", ...(parsed.turnId ? { turnId: parsed.turnId } : {}) }) } as MessageEvent, ws)); + }, close() {}, readyState: 1 } as WSContext; await handlers.onOpen(undefined as never, ws); handlers.onMessage({ data: JSON.stringify({ type: "chat_message", text, requestId: `taint-${count}`, ...(sessionId ? { sessionId } : {}) }) } as MessageEvent, ws); await until(() => seen.length === count + 1 && !app.wsHost.coordinator.isTurnActive(), () => sent); @@ -93,6 +102,7 @@ test("a WebFetch taints the session: outward asks, a non-listed host is refused, expect(source, "G6_WEBFETCH_TAINTS_SESSION").toMatchObject({ turnId, payload: { source: "web_fetch", tool: "WebFetch", detail: null } }); expect(tainted.outwardAsks, "G6_TAINT_OVERRIDES_OUTWARD_ALLOW").toBe(true); expect(events(sessionId, "outward_action")[0]).toMatchObject({ payload: { action: "git_push", tainted: true, decision: "declined", rule: null } }); + expect(networkCards, "G6_TAINTED_NEW_HOST_ASKS").toEqual([{ host: "127.0.0.1" }]); expect(tainted.curl, "G6_TAINTED_NON_LISTED_HOST_REFUSED").not.toBe(0); expect(events(sessionId, "egress_denial").map(event => event.payload), "G6_TAINT_DENIAL_RECORDED").toEqual([ { host: "127.0.0.1", port: origin.port, method: "GET", reason: "taint_allowlist", bytes: 0 }, @@ -105,6 +115,7 @@ test("a WebFetch taints the session: outward asks, a non-listed host is refused, expect(next.taint, "G6_TAINT_STICKY_NEXT_TURN").toBe("web_fetch"); expect(next.outwardAsks, "G6_STICKY_OUTWARD_ASKS").toBe(true); expect(next.curl, "G6_STICKY_EGRESS_REFUSED").not.toBe(0); + expect(networkCards, "G6_DECLINED_HOST_ASKS_AGAIN").toHaveLength(2); expect(events(sessionId, "egress_denial")).toHaveLength(2); expect(events(sessionId, "taint"), "G6_FIRST_SOURCE_KEPT").toHaveLength(1); expect(next.note).toContain("This session is tainted (first recorded source: web_fetch).");