diff --git a/.changeset/4029-github-g2-routing.md b/.changeset/4029-github-g2-routing.md new file mode 100644 index 0000000000..4cd9aa3d2c --- /dev/null +++ b/.changeset/4029-github-g2-routing.md @@ -0,0 +1,7 @@ +--- +"@schlessera/brain-ui-server": minor +--- + +The host GitHub read tools now follow the provider policy's data routing (#4029). GitHub is the provider-policy recipient `github`, beside `apify` and the web providers. `brain_github_issue_read` and `brain_github_issue_search` send a repository, a number or search text to GitHub, so a conversation that has shown a provider folder the policy does not let `github` receive is refused before any request, with `policy_denied` and reason `recipient_restricted`, and GitHub receives nothing. A conversation whose exposure cannot be judged under a policy that restricts `github` is refused the same way, with `recipient_unproven`. A conversation that showed no such folder reads as before. + +If your policy has `providers` rules whose `allow` lists do not name `github`, GitHub reads start being refused in conversations that have shown those folders. That is the intended effect. Add `github` to a rule's `allow` list to let GitHub receive that rule's folders. The write tools are not routed: each write is still gated by its approval card, which shows exactly what is sent, and by `outward.github.repositories`. diff --git a/docs/integration-contract.md b/docs/integration-contract.md index b573a691c3..97364992e6 100644 --- a/docs/integration-contract.md +++ b/docs/integration-contract.md @@ -104,6 +104,21 @@ shape changes. See [the package API](integration-contract/package-api.md#start-card-persona-choice-3698). This ships in a minor. +## Data routing for the host GitHub reads (additive, 0.45.0, #4029) + +GitHub is a provider-policy recipient, named `github`. Before any request, +`brain_github_issue_read` and `brain_github_issue_search` refuse a +conversation that has shown a provider folder the policy keeps from `github` +(`policy_denied`, reason `recipient_restricted`), and, under a policy that +restricts `github`, one whose exposure cannot be judged (`policy_denied`, +reason `recipient_unproven`). The two reasons are new on the read tools. A +policy whose `providers` rules do not allow `github` therefore starts +restricting GitHub reads for those folders. The write tools are not routed: +their card and `outward.github.repositories` stay their gate. See +[the MCP component](integration-contract/mcp.md#github-data-routing-additive-0450-4029) +and [supported inputs](supported-inputs.md#governance-policy). +This ships in a minor. + ## Host GitHub writes and their repository allow-list (additive, 0.45.0, #3798) Both first-party backends register `brain_github_issue_create` and diff --git a/docs/integration-contract/mcp.md b/docs/integration-contract/mcp.md index 6a04b9d97f..6bfbf7c733 100644 --- a/docs/integration-contract/mcp.md +++ b/docs/integration-contract/mcp.md @@ -1471,7 +1471,9 @@ Each result is one JSON document, `{ ok: true, tool, result }` or `unavailable` carries `reason` `no_credential` (the host has no `BRAIN_UI_GITHUB_TOOLS_TOKEN`), `credential_rejected`, `no_host` (no host handler in this turn), `recording_unavailable` (a write's approval could not -be recorded) or, before #3798 only, `not_registered`. The write reasons are +be recorded) or, before #3798 only, `not_registered`. A read's +`policy_denied` carries `recipient_restricted` or `recipient_unproven`; see +[Data routing](#github-data-routing-additive-0450-4029). The write reasons are listed under [Writes](#github-writes-additive-0450-3798). **Payloads.** `result` is typed data, never formatted text @@ -1537,6 +1539,33 @@ any GitHub text returns, the session's taint is recorded with the new source `github_result` ([governance events](../http-api.md)); if that record cannot be written, the text is withheld. +### GitHub data routing (additive, 0.45.0, #4029) + +GitHub is the provider-policy recipient `github` +([supported inputs](../supported-inputs.md#governance-policy)). A read or a +search sends GitHub text the model chose: a repository and number, or a +search query that can quote anything the conversation was shown. So before +any request, the host checks it under the turn's frozen policy and the +conversation's recorded provider exposures, by the rules the web providers and +Apify use: + +- A conversation that has shown a provider folder the policy does not let + `github` receive is refused with `policy_denied`, + `reason: "recipient_restricted"`. +- Under a policy whose `providers` rules restrict `github`, a conversation + whose exposure cannot be judged is refused with `policy_denied`, + `reason: "recipient_unproven"`. That covers a conversation not yet named, a + recorded exposure the server cannot read, a type selector without its + folders, and a turn with no frozen policy. +- A policy whose rules all allow `github`, or a conversation that showed none + of the folders they keep from it, reads as before. + +A refused call sends GitHub nothing, returns no GitHub text and taints +nothing. The writes are not routed (maintainer ruling on #4029): each write's +gate is its per-use card, which shows exactly what is sent, and +`outward.github.repositories`. A write in a conversation whose reads are +refused still reaches its card unchanged. + ### GitHub writes (additive, 0.45.0, #3798) `brain_github_issue_create` files one issue and `brain_github_issue_comment` diff --git a/docs/supported-inputs.md b/docs/supported-inputs.md index f907846408..481cae6579 100644 --- a/docs/supported-inputs.md +++ b/docs/supported-inputs.md @@ -324,6 +324,21 @@ provider masks, empty. So whatever is hidden from every turn under a provider rule, such as the generated-text caches (#2692), stays hidden from it too, until those caches move into a masked directory (#2725). +**Tool recipients (G2).** One exception to the egress rule above: a host +tool that sends a third party text the model chose makes that party a +recipient, named in `allow` like an inference recipient. A conversation that +has shown a provider folder a rule keeps from it sends it nothing, and under a +rule that restricts it, neither does a conversation whose exposure cannot be +judged. These recipients are named: `apify` for Apify discovery, inspection +and runs; the curated web providers `exa`, `duckduckgo`, `brave`, `jina`, +`perplexity`, `tavily`, `openai`, `google` (Gemini), `firecrawl` and `kagi`; +`typesafe` for the extraction judge; and `github` for the host GitHub reads +and searches (additive in 0.45.0, #4029). The GitHub write tools are not routed: each write +is gated by its per-use approval card, which shows exactly what is sent, and +by `outward.github.repositories`. To let GitHub receive a rule's folders, +add `github` to that rule's `allow`. See +[the MCP contract](integration-contract/mcp.md#github-data-routing-additive-0450-4029). + **Which selectors hosted turns enforce (additive in 0.44.0, #2694).** A selector is enforced only when it maps exactly onto whole folders; the turn then masks those folders as above. Every other selector refuses turn admission diff --git a/packages/ui-server/src/github/host.ts b/packages/ui-server/src/github/host.ts index 354e33add6..4a66757116 100644 --- a/packages/ui-server/src/github/host.ts +++ b/packages/ui-server/src/github/host.ts @@ -16,9 +16,17 @@ * what will be sent; only an unedited allow sends it, once. Voice refuses * before the card. Each admission, refusal and answer is recorded as an * `outward_action` (`gh_write`), which the turn journal lists as irreversible. + * + * Data routing (G2, #4029): GitHub is the provider-policy recipient `github`. + * A read or search sends model-chosen text (a query, a repository and number), + * so a conversation that has shown a provider folder the policy keeps from + * `github`, or whose exposure cannot be judged, sends GitHub nothing. Writes + * are not routed: the per-use card, which shows the exact body, and the + * allow-list are their gate (maintainer ruling, 2026-11-16). */ import { githubWriteAllowance } from "@schlessera/brain-common/internal/governance-policy"; import type { PermissionDecision, PermissionRequest } from "@schlessera/brain-ui-sdk/server"; +import type { RecipientRoutingRefusal } from "../web-tools/routing.js"; import { GITHUB_API_ORIGIN, GITHUB_ISSUE_COMMENT_INPUT_SCHEMA, GITHUB_ISSUE_CREATE_INPUT_SCHEMA, GITHUB_ISSUE_READ_INPUT_SCHEMA, GITHUB_ISSUE_SEARCH_INPUT_SCHEMA, GITHUB_LIMITS, GITHUB_TOOL_NAMES, GITHUB_AUTHOR_ASSOCIATIONS, githubDirectUrl, githubSearchUrl, parseGithubRepository, @@ -29,6 +37,12 @@ import { type GithubIssueCreatePayload, type GithubIssueCommentPayload, } from "@schlessera/brain-ui-sdk/tool-contracts"; +/** GitHub's name as a provider-policy recipient (G2), beside `apify` and the web providers. */ +export const GITHUB_RECIPIENT = "github"; + +/** Why the turn's data routing refuses a recipient; see `recipientRouting`. */ +export type GithubRoutingRefusal = RecipientRoutingRefusal; + /** The recorded `outward_action` of one GitHub write, as the governance writer takes it. */ export interface GithubOutwardAction { kind: "outward_action"; @@ -64,6 +78,12 @@ export interface GithubToolsTurn { readonly principalId: string; readonly sessionId: () => string | null; readonly signal?: AbortSignal; + /** + * Data routing (G2, #4029) under the turn's frozen policy and the + * conversation's recorded exposures, asked before any read or search + * request. A throw counts as unproven. + */ + readonly routing: (recipient: typeof GITHUB_RECIPIENT) => Promise; /** Present only on a turn that may write (#3798); an autonomous turn has none. */ readonly write?: GithubWriteTurn; } @@ -517,6 +537,13 @@ export function createGithubToolsHost(options: GithubToolsHostOptions): GithubTo } const token = options.token(); if (!token) return noCredential(tool); + // G2 before any request: a refusal sends GitHub nothing, so nothing returns to taint. + let routed: GithubRoutingRefusal | null = "recipient_unproven"; + try { routed = await turn.routing(GITHUB_RECIPIENT); } catch { /* Unknown exposure is unproven. */ } + if (routed === "recipient_restricted") return refusal(tool, "policy_denied", routed, + "This conversation has shown folders the provider policy does not allow github to receive, so nothing was sent to GitHub. Start a new conversation for this GitHub work."); + if (routed) return refusal(tool, "policy_denied", "recipient_unproven", + "The provider policy restricts folders for github, and this conversation's exposure to them is unknown here, so nothing was sent to GitHub."); try { if (tool === GITHUB_TOOL_NAMES.read) { const input = GITHUB_ISSUE_READ_INPUT_SCHEMA.parse(call.input); diff --git a/packages/ui-server/src/web-tools/routing.ts b/packages/ui-server/src/web-tools/routing.ts index 148d8da39d..84c6c06035 100644 --- a/packages/ui-server/src/web-tools/routing.ts +++ b/packages/ui-server/src/web-tools/routing.ts @@ -1,26 +1,37 @@ /** - * Data routing (G2) for one web recipient (#3687), by the rules Apify's + * Data routing (G2) for one tool recipient (#3687), by the rules Apify's * consent applies (`routingGate`, `packages/common/src/apify/consent.ts`): * nothing leaves for a recipient from a conversation that has shown it a * provider folder the policy does not let it receive. A recipient no rule * restricts is admitted; one whose exposure cannot be judged here is refused, - * since an unknown never becomes clean. + * since an unknown never becomes clean. The web providers, the extraction + * judge and the host GitHub reads (#4029) share these rules. */ import type { EffectiveGovernancePolicy } from "@schlessera/brain-common/internal/governance-policy"; import { exposureConflicts, providerDeniedFolders, unsupportedProviderSelectors, type ProviderExposure } from "../brain/governance-policy.js"; import type { WebCallRefusal } from "./broker.js"; -export function webRoutingRefusal(policy: Pick, typeFolders: Readonly> | undefined, - exposures: readonly ProviderExposure[] | undefined, recipient: string): WebCallRefusal | null { +/** Why routing refuses a recipient: it was shown a folder kept from it, or what it was shown cannot be judged. */ +export type RecipientRoutingRefusal = "recipient_restricted" | "recipient_unproven"; + +export function recipientRouting(policy: Pick, typeFolders: Readonly> | undefined, + exposures: readonly ProviderExposure[] | undefined, recipient: string): RecipientRoutingRefusal | null { const restricting = policy.providers.filter(rule => !rule.allow.includes(recipient)); if (!restricting.length) return null; const selectsTypes = restricting.some(rule => rule.types?.length); // A selector no folder mask can express cannot be checked against exposures either. - if (!exposures || unsupportedProviderSelectors({ providers: restricting }).length || (selectsTypes && !typeFolders)) { + if (!exposures || unsupportedProviderSelectors({ providers: restricting }).length || (selectsTypes && !typeFolders)) return "recipient_unproven"; + const denied = providerDeniedFolders(policy, typeFolders ?? {}, recipient); + return exposureConflicts(exposures, denied).length ? "recipient_restricted" : null; +} + +export function webRoutingRefusal(policy: Pick, typeFolders: Readonly> | undefined, + exposures: readonly ProviderExposure[] | undefined, recipient: string): WebCallRefusal | null { + const refused = recipientRouting(policy, typeFolders, exposures, recipient); + if (refused === "recipient_unproven") { return { code: "policy_denied", message: `The provider policy restricts folders for ${recipient}, and this conversation's exposure to them is unknown here, so nothing was sent to it.` }; } - const denied = providerDeniedFolders(policy, typeFolders ?? {}, recipient); - if (exposureConflicts(exposures, denied).length) { + if (refused === "recipient_restricted") { return { code: "policy_denied", message: `This conversation has shown folders the provider policy does not allow ${recipient} to receive, so nothing was sent to it. Start a new conversation for this web work, or use another provider.` }; } return null; diff --git a/packages/ui-server/src/ws/bridge-capabilities/context.ts b/packages/ui-server/src/ws/bridge-capabilities/context.ts index 0f3d2c7722..1c2c1d37ed 100644 --- a/packages/ui-server/src/ws/bridge-capabilities/context.ts +++ b/packages/ui-server/src/ws/bridge-capabilities/context.ts @@ -39,8 +39,12 @@ export interface MakeBridgeOptions { * startup view, that view's root: where its `Read` of a brain path resolves. */ turnData?: { tree: TurnDataTree; view?: string } | undefined; - /** The governed turn's frozen policy: hosted external compute is admitted only under it (#3108). */ - governance?: { policy: TurnGovernancePolicy } | undefined; + /** + * The governed turn's frozen policy: hosted external compute is admitted + * only under it (#3108). `typeFolders` translates its type selectors to + * folders for tool data routing (G2, #4029). + */ + governance?: { policy: TurnGovernancePolicy; typeFolders?: Readonly> } | undefined; } interface WorkerProfileBinding { origin: "interactive" | "voice"; actualProfile: "governed" | "strict"; draftId?: string; preference?: "governed" | "strict" } diff --git a/packages/ui-server/src/ws/bridge.ts b/packages/ui-server/src/ws/bridge.ts index f2a065a4ec..b1835b58a3 100644 --- a/packages/ui-server/src/ws/bridge.ts +++ b/packages/ui-server/src/ws/bridge.ts @@ -18,6 +18,8 @@ import { createWebAccess } from "./bridge-capabilities/web.js"; import { createEffectiveSafety } from "../governance/effective-safety.js"; import { sessionTaint } from "../governance/session-taint.js"; import type { GithubOutwardAction } from "../github/host.js"; +import type { ProviderExposure } from "../brain/governance-policy.js"; +import { recipientRouting } from "../web-tools/routing.js"; import { retainTurnSessionBinding } from "./bridge-session-binding.js"; export { emitTurnError } from "./bridge-capabilities/turn-error.js"; @@ -133,10 +135,21 @@ function applyExternalServices(ctx: BridgeContext, bridge: BackendBridge, transc // taint; the turn, never the call, names principal and session. Writes // (#3798) take the allow-list from this turn's admitted policy, and their // card from this bridge's own approval surface, so voice and revoked turns - // refuse as they do for every other card. No policy, no writes. + // refuse as they do for every other card. No policy, no writes. Reads and + // searches are routed (G2, #4029) under the same frozen policy and the + // conversation's recorded exposures; writes are not, their card is the gate. if (host.githubTools) { const github = host.githubTools; const sessionId = () => transcript.collectedSessionId ?? turn.sessionId ?? null; + const routing = async (recipient: string) => { + // Without the frozen policy nothing says which folders GitHub may receive. + if (!governance) return "recipient_unproven" as const; + // Before the conversation is named, nothing recorded says what it showed. + const named = sessionId(); + let shown: ProviderExposure[] | undefined; + if (named && host.governedTurns) try { shown = await host.governedTurns.exposures([named]); } catch { shown = undefined; } + return recipientRouting(governance.policy.policy, governance.typeFolders, shown, recipient); + }; const posture = work?.posture === "voice" ? "voice" as const : "interactive" as const; const write = { repositories: () => governance?.policy.policy.outward?.github?.repositories ?? null, @@ -156,7 +169,7 @@ function applyExternalServices(ctx: BridgeContext, bridge: BackendBridge, transc host.catalog.recordGovernanceEvent?.(input); }, }; - bridge.github = call => github.call({ turnId, principalId, sessionId, signal, write }, call); + bridge.github = call => github.call({ turnId, principalId, sessionId, signal, routing, write }, call); } } diff --git a/packages/ui-server/src/ws/session-run/backend-entry.ts b/packages/ui-server/src/ws/session-run/backend-entry.ts index 7f0dd0601f..7432673718 100644 --- a/packages/ui-server/src/ws/session-run/backend-entry.ts +++ b/packages/ui-server/src/ws/session-run/backend-entry.ts @@ -111,7 +111,7 @@ export async function openTurnBridge( ...(governedHold.typeFolders ? { typeFolders: governedHold.typeFolders } : {}), ...(governedHold.sandbox.inferenceRecipient ? { recipient: governedHold.sandbox.inferenceRecipient.name } : {}) } : undefined, turnData: governedHold?.dataTree ? { tree: governedHold.dataTree, ...(governedHold.startupView ? { view: governedHold.startupView.root } : {}) } : undefined, - governance: governedHold ? { policy: governedHold.policy } : undefined, + governance: governedHold ? { policy: governedHold.policy, ...(governedHold.typeFolders ? { typeFolders: governedHold.typeFolders } : {}) } : undefined, }); const safetyWrites=host.activity?.governanceWrites, safetyDb=host.activity?.governanceDb; if(safetyWrites&&safetyDb){ diff --git a/packages/ui-server/tests/github-details.test.ts b/packages/ui-server/tests/github-details.test.ts index 2c776a89c9..bd93ad55ec 100644 --- a/packages/ui-server/tests/github-details.test.ts +++ b/packages/ui-server/tests/github-details.test.ts @@ -120,7 +120,7 @@ function github(options: FakeGithubOptions & { comments?: number } = {}): FakeGi /** What the real host's tools returned, as the session's history records it. */ async function toolResults(fake: FakeGithub): Promise { const host = createGithubToolsHost({ token: () => GITHUB_TOOLS_SENTINEL, fetch: standInFetch(fake), now: () => NOW, untrusted: async () => {} }); - const turn = { turnId: "turn-ithaca", principalId: owner.id, sessionId: () => SESSION }; + const turn = { turnId: "turn-ithaca", principalId: owner.id, sessionId: () => SESSION, routing: async () => null }; const results = [ await host.call(turn, { tool: "brain_github_issue_read", input: { repository: "odysseus/ithaca", number: 7 } }), await host.call(turn, { tool: "brain_github_issue_read", input: { repository: "odysseus/ithaca", number: 8 } }), diff --git a/packages/ui-server/tests/github-tools-host.test.ts b/packages/ui-server/tests/github-tools-host.test.ts index fa70dd890e..ac40f23ecd 100644 --- a/packages/ui-server/tests/github-tools-host.test.ts +++ b/packages/ui-server/tests/github-tools-host.test.ts @@ -2,18 +2,19 @@ * The host GitHub read tools (#3797) against a loopback stand-in for the * GitHub API: the dedicated credential and nothing else, the contract's * payloads, direct links that pass the validator or are null, the taint - * recorded before any text returns, and refusals that send nothing. + * recorded before any text returns, and refusals that send nothing, + * including data routing (G2, #4029) asked before any request. */ import { afterEach, describe, expect, test } from "bun:test"; import { GITHUB_RESULT_SCHEMAS, type GithubIssue, type GithubIssueSearchPayload, type GithubPullRequest, type GithubToolResult } from "@schlessera/brain-ui-sdk/tool-contracts"; -import { createGithubToolsHost, reviewDecisions, type GithubToolsHostOptions, type GithubToolsTurn } from "../src/github/host.js"; +import { GITHUB_RECIPIENT, createGithubToolsHost, reviewDecisions, type GithubRoutingRefusal, type GithubToolsHostOptions, type GithubToolsTurn } from "../src/github/host.js"; import { githubToolsTokenSource } from "../src/config/env.js"; import { COMMIT_SHAS, GENERIC_GITHUB_SENTINEL, GITHUB_TOOLS_SENTINEL, HEAD_SHA, fakeGithub, standInFetch, type FakeGithub, type FakeGithubOptions } from "./fixtures/github-host-fixture.js"; const stops: FakeGithub[] = []; afterEach(() => { for (const fake of stops.splice(0)) fake.stop(); }); -const turn: GithubToolsTurn = { turnId: "turn-ithaca", principalId: "principal-penelope", sessionId: () => "sess-ithaca" }; +const turn: GithubToolsTurn = { turnId: "turn-ithaca", principalId: "principal-penelope", sessionId: () => "sess-ithaca", routing: async () => null }; const NOW = Date.parse("2026-07-12T12:00:00Z"); function host(options: FakeGithubOptions = {}, overrides: Partial = {}) { @@ -190,6 +191,41 @@ describe("refusals and taint", () => { }); }); +describe("data routing (G2, #4029)", () => { + const READS = [{ tool: "brain_github_issue_read", input: { repository: "odysseus/ithaca", number: 7 } }, + { tool: "brain_github_issue_search", input: { repository: "odysseus/ithaca", query: "the suitors' feast", kind: "any", state: "any", limit: 10 } }] as const; + const routed = (answer: () => Promise) => { + const asked: string[] = []; + return { asked, turn: { ...turn, routing: async (recipient: string) => { asked.push(recipient); return answer(); } } satisfies GithubToolsTurn }; + }; + + for (const [label, reason, answer] of [["shown a folder kept from github", "recipient_restricted", async () => "recipient_restricted" as const], + ["exposure unknown", "recipient_unproven", async () => "recipient_unproven" as const], + ["routing threw", "recipient_unproven", async (): Promise => { throw new Error("exposure store unreadable"); }]] as const) { + test(`a read or search the turn's routing refuses (${label}) sends GitHub nothing`, async () => { + const { fake, taints, github } = host(); + const { asked, turn: refused } = routed(answer); + for (const call of READS) { + const result = parsed(await github.call(refused, call)); + expect(result, `GITHUB_ROUTING_REFUSED_${call.tool}`).toMatchObject({ ok: false, error: { code: "policy_denied", reason } }); + expect(JSON.stringify(result)).not.toContain("Suitors"); + } + expect(asked, "GITHUB_ROUTING_NAMES_GITHUB").toEqual([GITHUB_RECIPIENT, GITHUB_RECIPIENT]); + expect(GITHUB_RECIPIENT).toBe("github"); + expect(fake.seen, "GITHUB_ROUTING_NOTHING_SENT").toEqual([]); + expect(taints, "GITHUB_ROUTING_NOTHING_TAINTED").toEqual([]); + }); + } + + test("a turn its routing admits reads as before", async () => { + const { fake, github } = host(); + const { asked, turn: admitted } = routed(async () => null); + for (const call of READS) expect((await github.call(admitted, call)).ok, `GITHUB_ROUTING_ADMITTED_${call.tool}`).toBe(true); + expect(asked).toEqual([GITHUB_RECIPIENT, GITHUB_RECIPIENT]); + expect(fake.seen.length).toBeGreaterThan(1); + }); +}); + test("review decisions: a later comment never hides a decision, and pending is not one", () => { const review = (login: string, state: "approved" | "commented" | "pending" | "changes_requested", day: number) => ({ id: day, state, author: { login, is_bot: false, author_association: null }, submitted_at: `2026-07-0${day}T09:00:00Z`, body: null, body_length: 0, body_truncated: false, html_url: null }); diff --git a/packages/ui-server/tests/github-write-tools.test.ts b/packages/ui-server/tests/github-write-tools.test.ts index 49533e59ac..85dd4cf001 100644 --- a/packages/ui-server/tests/github-write-tools.test.ts +++ b/packages/ui-server/tests/github-write-tools.test.ts @@ -36,7 +36,7 @@ function harness(answer: (request: PermissionRequest) => PermissionDecision | Pr toolName: name => `mcp__brain-ui__${name}`, tainted: () => false, isCurrent: () => true, govern: event => { recorded.push(event); }, ...overrides, }; - return github.call({ turnId: "turn-ithaca", principalId: "principal-penelope", sessionId: () => "sess-ithaca", write, ...turnOverrides }, call); + return github.call({ turnId: "turn-ithaca", principalId: "principal-penelope", sessionId: () => "sess-ithaca", routing: async () => null, write, ...turnOverrides }, call); } }; } const writes = (fake: FakeGithub) => fake.seen.filter(request => request.method !== "GET"); @@ -200,6 +200,23 @@ describe("the repository allow-list", () => { }); }); +describe("data routing (G2, #4029) does not gate writes", () => { + test("a write in a turn whose routing refuses github still reaches its card unchanged and is sent once on approval", async () => { + const plain = harness(), routed = harness(); + const asked: string[] = []; + const restricted = { routing: async (recipient: string) => { asked.push(recipient); return "recipient_restricted" as const; } }; + for (const call of [CREATE, COMMENT] as GithubToolCall[]) { + const baseline = await plain.call(call), result = await routed.call(call, {}, restricted); + expect(result, `GITHUB_WRITE_NOT_ROUTED ${call.tool}`).toEqual(baseline); + expect(result.ok).toBe(true); + } + expect(routed.cards.map(card => [card.toolName, card.input]), "GITHUB_WRITE_CARD_UNCHANGED_UNDER_ROUTING").toEqual(plain.cards.map(card => [card.toolName, card.input])); + expect(routed.cards).toHaveLength(2); + expect(writes(routed.fake).map(request => [request.path, request.body]), "GITHUB_WRITE_SENT_UNDER_ROUTING").toEqual(writes(plain.fake).map(request => [request.path, request.body])); + expect(asked, "GITHUB_WRITE_NEVER_ASKS_ROUTING").toEqual([]); + }); +}); + describe("postures that never approve", () => { test("voice cannot approve a write: it is refused before any card, even when the surface would allow it", async () => { const h = harness(() => ({ behavior: "allow" })); diff --git a/packages/ui-server/tests/ws-github.test.ts b/packages/ui-server/tests/ws-github.test.ts index b795fa0774..d9f514d415 100644 --- a/packages/ui-server/tests/ws-github.test.ts +++ b/packages/ui-server/tests/ws-github.test.ts @@ -7,7 +7,9 @@ * the credential; with only `GITHUB_TOKEN` set the tools answer * `unavailable` and send nothing. Writes (#3798) take their allow-list from * the turn's admitted governance policy and their card from the turn's own - * approval surface, and are recorded as `outward_action`. + * approval surface, and are recorded as `outward_action`. Reads and searches + * are routed (G2, #4029) under the turn's policy and the conversation's + * recorded exposures; writes are not, their card is the gate. * * Keyless and offline: the fixed API origin is routed to a loopback fake * after the network preload; the tokens are synthetic sentinels. @@ -35,7 +37,7 @@ import { GENERIC_GITHUB_SENTINEL, GITHUB_TOOLS_SENTINEL, fakeGithub, routeGithub const SESSION = "sess-ithaca-github"; async function hostedTurn(backendId: "pi" | "claude", env: Record, script: (github: (tool: string, input: unknown) => Promise) => Promise, - options: { policy?: string; answer?: (request: Record) => Record } = {}) { + options: { policy?: string; answer?: (request: Record) => Record; exposure?: { visible: string; hidden: string } } = {}) { const root = await mkdtemp(resolve(tmpdir(), "odysseus-host-github-")), brain = resolve(root, "brain"); await createFixtureBrain(resolve(import.meta.dir, "../../.."), brain); if (options.policy !== undefined) { @@ -71,6 +73,9 @@ async function hostedTurn(backendId: "pi" | "claude", env: Record { sent.push(text); }, close() {}, readyState: 1 } as WSContext; await handlers.onOpen(undefined as never, ws); @@ -164,3 +169,48 @@ test("without a governance policy entry a write is refused before any card and s expect(outcome.fake.seen).toEqual([]); } finally { await rm(outcome.root, { recursive: true, force: true }); } }, 60_000); + +// G2 (#4029): journal is kept from github; an earlier turn of this conversation showed it. +const ROUTED_POLICY = `${POLICY}\nproviders: [{ paths: [journal/**], allow: [anthropic] }]`; +const READS = [["brain_github_issue_read", { repository: "odysseus/ithaca", number: 7 }], + ["brain_github_issue_search", { repository: "odysseus/ithaca", query: "the suitors' feast", kind: "any", state: "any", limit: 10 }]] as const; + +test("a conversation shown a folder kept from github is refused every read and search, sends nothing, and still files a write through its card", async () => { + const results: GithubToolResult[] = []; + const outcome = await hostedTurn("claude", { BRAIN_UI_GITHUB_TOOLS_TOKEN: GITHUB_TOOLS_SENTINEL }, async github => { + for (const [tool, input] of READS) results.push(await github(tool, input)); + results.push(await github("brain_github_issue_create", ISSUE)); + }, { policy: ROUTED_POLICY, exposure: { visible: '["journal"]', hidden: "[]" }, answer: () => ({ type: "tool_approval" }) }); + try { + for (const result of results.slice(0, 2)) expect(result, `GITHUB_APP_ROUTING_RESTRICTED ${result.tool}`).toMatchObject({ ok: false, error: { code: "policy_denied", reason: "recipient_restricted" } }); + expect(outcome.taint, "GITHUB_APP_ROUTING_NOTHING_TAINTED").toEqual([]); + // The write is not routed: its card shows exactly what is sent, and only it reaches GitHub. + expect(results[2], "GITHUB_APP_WRITE_NOT_ROUTED").toMatchObject({ ok: true, result: { kind: "issue_created", repository: "odysseus/ithaca" } }); + expect(outcome.cards.map(card => card.input), "GITHUB_APP_WRITE_CARD_UNDER_ROUTING").toEqual([ISSUE]); + expect(outcome.fake.seen.map(request => [request.method, request.path]), "GITHUB_APP_ROUTING_ONLY_THE_WRITE_SENT").toEqual([["POST", "/repos/odysseus/ithaca/issues"]]); + } finally { await rm(outcome.root, { recursive: true, force: true }); } +}, 60_000); + +test("a conversation whose exposure cannot be judged under a policy restricting github is refused, and sends nothing", async () => { + const results: GithubToolResult[] = []; + // A record the server cannot read says nothing it could trust about what was shown. + const outcome = await hostedTurn("claude", { BRAIN_UI_GITHUB_TOOLS_TOKEN: GITHUB_TOOLS_SENTINEL }, async github => { + for (const [tool, input] of READS) results.push(await github(tool, input)); + }, { policy: ROUTED_POLICY, exposure: { visible: "journal", hidden: "[]" } }); + try { + for (const result of results) expect(result, `GITHUB_APP_ROUTING_UNPROVEN ${result.tool}`).toMatchObject({ ok: false, error: { code: "policy_denied", reason: "recipient_unproven" } }); + expect(outcome.fake.seen, "GITHUB_APP_ROUTING_UNPROVEN_NOTHING_SENT").toEqual([]); + expect(outcome.taint).toEqual([]); + } finally { await rm(outcome.root, { recursive: true, force: true }); } +}, 60_000); + +test("a conversation that showed github no restricted folder reads as before under the same policy", async () => { + const results: GithubToolResult[] = []; + const outcome = await hostedTurn("claude", { BRAIN_UI_GITHUB_TOOLS_TOKEN: GITHUB_TOOLS_SENTINEL }, async github => { + for (const [tool, input] of READS) results.push(await github(tool, input)); + }, { policy: ROUTED_POLICY, exposure: { visible: '["journal"]', hidden: '["journal"]' } }); + try { + expect(results.map(result => result.ok ? (result.result as { kind: string }).kind : result.error.reason), "GITHUB_APP_ROUTING_ADMITTED").toEqual(["issue", "search"]); + expect(outcome.fake.seen.length).toBeGreaterThan(1); + } finally { await rm(outcome.root, { recursive: true, force: true }); } +}, 60_000);