From 50cc41808c3c83146218d2c644ff9c61571c2931 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Sun, 8 Nov 2026 15:30:46 +0000 Subject: [PATCH 1/3] fix(ui-server): settle session binding before relay admission --- .changeset/relay-session-binding.md | 5 + docs/decisions/session-safety-reviews.md | 6 + packages/ui-server/src/brain/turn-egress.ts | 13 +- .../src/ws/bridge-session-binding.ts | 28 ++ packages/ui-server/src/ws/bridge.ts | 2 + .../tests/fixtures/relay-binding-probe.ts | 13 + .../tests/relay-session-binding.test.ts | 241 ++++++++++++++++++ 7 files changed, 303 insertions(+), 5 deletions(-) create mode 100644 .changeset/relay-session-binding.md create mode 100644 packages/ui-server/src/ws/bridge-session-binding.ts create mode 100644 packages/ui-server/tests/fixtures/relay-binding-probe.ts create mode 100644 packages/ui-server/tests/relay-session-binding.test.ts diff --git a/.changeset/relay-session-binding.md b/.changeset/relay-session-binding.md new file mode 100644 index 0000000000..5e1ba66ba5 --- /dev/null +++ b/.changeset/relay-session-binding.md @@ -0,0 +1,5 @@ +--- +"@schlessera/brain-ui-server": patch +--- + +Wait for a turn's announced session binding before relay admission, avoiding a healthy inference refusal when its identity commits between safety checks. Keep final safety and authority fences, and refuse failed or cancelled binding settlement. diff --git a/docs/decisions/session-safety-reviews.md b/docs/decisions/session-safety-reviews.md index ed2eb31511..b2d65b332f 100644 --- a/docs/decisions/session-safety-reviews.md +++ b/docs/decisions/session-safety-reviews.md @@ -124,6 +124,12 @@ history adoption and local pending/loss changes advance admission even when the global cursor does not. Pending-input overlays and capacity grouping use the same retained aliases. The history/review cursor keeps its existing meaning. +A host relay joins its own announced session binding before taking a fresh +admission snapshot. The wait is bounded and abortable, and a drained catalog +queue alone does not prove that the binding committed. Failed or indeterminate +binding refuses. This ordering never exempts independent pending input or retries +a provider request; the final synchronous safety and authority fences still apply. + Only effective taint and the trust slice update live. Ordinary governance budgets, profiles and commands keep turn-bound semantics. Trust removal fences new active-turn dispatch before its enforcing receipt; ongoing input must split diff --git a/packages/ui-server/src/brain/turn-egress.ts b/packages/ui-server/src/brain/turn-egress.ts index dcd4156036..19c7445e22 100644 --- a/packages/ui-server/src/brain/turn-egress.ts +++ b/packages/ui-server/src/brain/turn-egress.ts @@ -8,6 +8,7 @@ import type { GovernanceEventInput } from "../governance/events.js"; import { contactedHosts, recordFirstTaint, sessionTaint, type TaintSource } from "../governance/session-taint.js"; import type { GovernanceWrites } from "../governance/event-writes.js"; import { safetyProjection } from "../governance/safety-store.js"; +import { settleTurnSessionBinding } from "../ws/bridge-session-binding.js"; type Classification = Extract["classification"]; const GITHUB_API_HOSTS = ["api.github.com", "uploads.github.com"] as const; @@ -248,18 +249,20 @@ export async function prepareTurnEgress(options: { const relayOperation = (kind: "inference" | "relayed", method: string, target: URL, signal: AbortSignal) => { const operation = proxy[kind](method, target, signal); return { ...operation, async admit() { - // A completed worker connection may still be committing its terminal - // exposure. Join only this turn proxy's submitted records before taking - // a fresh admission snapshot; independent pending input still refuses. + // Join this proxy's terminal records and this bridge's announced + // session binding before the new snapshot. A concurrent FULL binding + // must not change a healthy scope underneath its first admission. + // Independent pending input still refuses in the unchanged final fences. if (operation.signal.aborted) return false; let abort: (() => void) | undefined; try { - const ready = await Promise.race([settled().then(() => true), new Promise(resolve => { + const ready = await Promise.race([settled().then(() => settleTurnSessionBinding(original, operation.signal)).catch(() => false), new Promise(resolve => { abort = () => resolve(false); operation.signal.addEventListener("abort", abort, { once: true }); if (operation.signal.aborted) resolve(false); })]); - return ready && !operation.signal.aborted && await operation.admit(); + if (!ready) { operation.finish("denied", "session_binding_unavailable"); return false; } + return !operation.signal.aborted && await operation.admit(); } finally { if (abort) operation.signal.removeEventListener("abort", abort); } } }; }; diff --git a/packages/ui-server/src/ws/bridge-session-binding.ts b/packages/ui-server/src/ws/bridge-session-binding.ts new file mode 100644 index 0000000000..4256545589 --- /dev/null +++ b/packages/ui-server/src/ws/bridge-session-binding.ts @@ -0,0 +1,28 @@ +/** The host bridge owns its announced identity's storage settlement. */ +import type { BackendBridge } from "@schlessera/brain-ui-sdk/server"; +import { waitWhile } from "../brain/authority-hold.js"; +import { STORAGE_SETTLEMENT_MS } from "../db/settlement.js"; +import type { BridgeContext } from "./bridge-capabilities/context.js"; + +const contexts = new WeakMap(); + +export function retainTurnSessionBinding(bridge: BackendBridge, context: BridgeContext): void { + contexts.set(bridge, context); +} + +/** Join only this bridge's announced binding, before minting admission authority. */ +export async function settleTurnSessionBinding(bridge: BackendBridge, signal: AbortSignal): Promise { + const ctx = contexts.get(bridge); + if (!ctx) return true; + const settled = await waitWhile(() => !!ctx.sessionBinding.pending && ctx.current(), + () => ctx.sessionBinding.pending!, signal, Date.now() + STORAGE_SETTLEMENT_MS); + if (!settled || signal.aborted || !ctx.current() || ctx.sessionBinding.pending || ctx.sessionBinding.failed) return false; + const db = ctx.host.activity?.governanceDb, sessionId = ctx.turn.sessionId; + // Catalog accounting reports failures without rejecting settled(). Check + // the actual collection binding too; a drained queue is not commit proof. + if (db && sessionId !== null) { + return !!db.query(`SELECT 1 FROM safety_collections c JOIN safety_sessions s ON s.session_id=c.session_id + WHERE c.turn_id=? AND c.session_id=?`).get(ctx.turnId, sessionId); + } + return true; +} diff --git a/packages/ui-server/src/ws/bridge.ts b/packages/ui-server/src/ws/bridge.ts index 638a8e077e..e315dfb699 100644 --- a/packages/ui-server/src/ws/bridge.ts +++ b/packages/ui-server/src/ws/bridge.ts @@ -14,6 +14,7 @@ import { createApplication } from "./bridge-capabilities/application.js"; import { createScratch } from "./bridge-capabilities/scratch.js"; import { createAttachmentRead } from "./bridge-capabilities/attachments.js"; import { createEffectiveSafety } from "../governance/effective-safety.js"; +import { retainTurnSessionBinding } from "./bridge-session-binding.js"; export { emitTurnError } from "./bridge-capabilities/turn-error.js"; @@ -88,6 +89,7 @@ export async function makeBridge(host: WsHost, turn: RunningTurn, options: MakeB }, }); } + retainTurnSessionBinding(bridge, ctx); return bridge; } diff --git a/packages/ui-server/tests/fixtures/relay-binding-probe.ts b/packages/ui-server/tests/fixtures/relay-binding-probe.ts new file mode 100644 index 0000000000..efb2faec37 --- /dev/null +++ b/packages/ui-server/tests/fixtures/relay-binding-probe.ts @@ -0,0 +1,13 @@ +import type { Database } from "bun:sqlite"; +export const url = import.meta.url; +export function setup(db: Database) { + return { + hold(gate: Int32Array, entered: Int32Array) { + db.transaction(() => { + Atomics.store(entered, 0, 1); Atomics.notify(entered, 0); + if (Atomics.wait(gate, 0, 0, 5000) === "timed-out") throw new Error("BINDING_PROBE_RELEASE_REQUIRED"); + }).immediate(); + }, + committed(done: Int32Array) { Atomics.store(done, 0, 1); Atomics.notify(done, 0); }, + }; +} diff --git a/packages/ui-server/tests/relay-session-binding.test.ts b/packages/ui-server/tests/relay-session-binding.test.ts new file mode 100644 index 0000000000..915b354e65 --- /dev/null +++ b/packages/ui-server/tests/relay-session-binding.test.ts @@ -0,0 +1,241 @@ +import { expect, test } from "bun:test"; +import { mkdtempSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { request } from "node:http"; +import { resolveGovernancePolicy } from "@schlessera/brain-common/internal/governance-policy"; +import { startInferenceRelay, startProviderRelay } from "@schlessera/brain-ui-sdk/internal"; +import { createUiDb } from "../src/db/client"; +import { openSqliteWriter } from "../src/db/write-worker"; +import { createGovernanceWrites } from "../src/governance/event-writes"; +import { createActivityStore } from "../src/activity/store"; +import { createActivityStream } from "../src/activity/stream"; +import { createSessionCatalog } from "../src/ws/session-catalog"; +import { makeBridge } from "../src/ws/bridge"; +import { WsHost } from "../src/ws/host"; +import { createStaticBackendRegistry } from "../src/agent/backend"; +import { makeFakeBackend } from "./helpers/fake-backend"; +import { prepareTurnEgress } from "../src/brain/turn-egress"; +import * as probe from "./fixtures/relay-binding-probe"; +import type { AdmissionSafetySnapshot } from "../../ui-sdk/src/server/admission-safety"; + +for (const kind of ["inference", "provider"] as const) for (const releaseAt of [0, 2, 3]) test(`${kind} joins own session binding at safety read ${releaseAt}`, async () => { + const root = mkdtempSync(join(tmpdir(), "odysseus-binding-probe-")); + const db = createUiDb(join(root, "ui.db")), writer = openSqliteWriter(db), writes = createGovernanceWrites(db, writer); + const store = createActivityStore(db, { writer: "odysseus" }); + const catalog = createSessionCatalog(() => db, undefined, undefined, { writer, governance: writes, pricing: { resolve: () => null }, store }); + const host = new WsHost({ brainPath: root, catalog, registry: createStaticBackendRegistry([makeFakeBackend({ id: "claude" })], "claude"), + isPrincipalAuthorized: () => true, activity: { store, stream: createActivityStream(store), governanceDb: db, governanceWrites: writes } }); + const authorization = host.coordinator.openAuthorization({ principalId: "odysseus", valid: true, expiresAt: Number.MAX_SAFE_INTEGER }); + const controller = new AbortController(); + const turn = { turnId: "voyage", requestId: "voyage-request", principalId: "odysseus", authorization, sessionId: null, startedAt: Date.now(), + abortController: controller, queue: [] } as unknown as import("../src/ws/turns").RunningTurn; + const channel = writer.channel(probe, undefined); await channel.ready; + const gate = new Int32Array(new SharedArrayBuffer(4)), entered = new Int32Array(new SharedArrayBuffer(4)), done = new Int32Array(new SharedArrayBuffer(4)); + const release = () => { Atomics.store(gate, 0, 1); Atomics.notify(gate, 0); }; + let held: Promise | undefined, marked: Promise | undefined, requests = 0; + const upstream = Bun.serve({ hostname: "127.0.0.1", port: 0, fetch() { requests++; return Response.json({ content: [] }); } }); + let proxy: Awaited> | undefined; + let relay: ReturnType | ReturnType | undefined; + const samples: unknown[] = []; + try { + await writes.safetyBegin({ turnId: "voyage", bindingId: crypto.randomUUID(), sessionId: null, principalId: "odysseus", backendId: "claude", at: 0 }); + await writes.safetyReady("voyage", "claude", 1); + const bridge = await makeBridge(host, turn, { backendId: "claude", promptText: "Plan the return to Ithaca." }); + const safety = bridge.admissionSafety!; + const original = safety.read.bind(safety); + safety.read = () => { + if (samples.length + 1 === releaseAt) { + release(); + expect(Atomics.wait(done, 0, 0, 5000), "BINDING_WRITER_COMMITTED_WITHOUT_EVENT_LOOP_PROGRESS").not.toBe("timed-out"); + } + const value = original(); samples.push({ ...value }); return value; + }; + proxy = await prepareTurnEgress({ policy: resolveGovernancePolicy({ schema_version: 1 }), bridge, + controller, turnId: "voyage", sessionId: () => turn.sessionId, model: () => null, profile: "governed", origin: "interactive", governanceDb: db, governanceWrites: writes, + record: event => writes.record(event) }); + held = channel.call("hold", gate, entered); + if (Atomics.load(entered, 0) === 0) await Atomics.waitAsync(entered, 0, 0, 5000).value; + expect(Atomics.load(entered, 0)).toBe(1); + bridge.emit({ type: "session_info", sessionId: "ithaca", isNew: true }); + marked = channel.call("committed", done); + expect(turn.sessionId, "REAL_EMISSION_ANNOUNCES_SESSION_BEFORE_BINDING_COMMITS").toBe("ithaca"); + if (releaseAt === 0) { release(); await catalog.settled!(); await marked; } + const enteredAdmission = Promise.withResolvers(); + const observeOperation = (operation: ReturnType["inference"]>) => ({ ...operation, admit() { + enteredAdmission.resolve(); return operation.admit(); + } }); + relay = kind === "inference" + ? startInferenceRelay({ upstream: upstream.url.origin, routes: ["/v1/messages"], credentials: { "x-api-key": "odysseus-offline-only-key" }, + egress: { inference: (...args) => observeOperation(proxy!.inference(...args)) } }) + : startProviderRelay({ origins: new Map([["ODYSSEUS_RELAY_KEY", [upstream.url.origin]]]), credential: () => "odysseus-offline-only-key", + egress: { relayed: (...args) => observeOperation(proxy!.relayed(...args)) } }); + const responsePending = new Promise<{ status: number; body: string }>((resolve, reject) => { + const outgoing = request({ socketPath: relay!.socketPath, path: "/v1/messages", method: "POST", headers: { "content-type": "application/json", "x-brain-provider": "anthropic", "x-brain-provider-key": "ODYSSEUS_RELAY_KEY", "x-brain-provider-origin": upstream.url.origin } }, incoming => { + const chunks: Buffer[] = []; incoming.on("data", chunk => chunks.push(chunk)); incoming.on("error", reject); + incoming.on("end", () => resolve({ status: incoming.statusCode!, body: Buffer.concat(chunks).toString() })); + }); outgoing.on("error", reject); outgoing.end(JSON.stringify({ model: "odysseus", messages: [] })); + }); + await enteredAdmission.promise; + // A fixed host waits before its first read. The baseline reaches the + // controlled second/third read first, during the same microtask drain. + await new Promise(resolve => setImmediate(() => { release(); resolve(); })); + const response = await responsePending; + await proxy.settled(); + const egress = db.query("SELECT json_extract(payload,'$.outcome') outcome,json_extract(payload,'$.reason') reason FROM governance_events WHERE kind='egress_connection'").all(); + expect(response.status, "HEALTHY_OWN_BINDING_JOINS_BEFORE_INFERENCE_SNAPSHOT").toBe(200); + expect(requests, "EXACTLY_ONE_PROVIDER_DISPATCH_AFTER_OWN_BINDING").toBe(1); + expect(egress, "HEALTHY_BINDING_HAS_ONE_COMPLETED_EGRESS").toEqual([{ outcome: "completed", reason: null }]); + } finally { + release(); await held?.catch(() => {}); await marked?.catch(() => {}); await relay?.stop(); proxy?.stop(); await proxy?.settled(); upstream.stop(true); + authorization.release(); await catalog.settled!(); host.close(); await writer.close(); db.close(); rmSync(root, { recursive: true, force: true }); + } +}); + +async function adverseFixture(kind: "inference" | "provider", finalWait = false) { + const root = mkdtempSync(join(tmpdir(), "odysseus-binding-adverse-")); + const db = createUiDb(join(root, "ui.db")), writer = openSqliteWriter(db), writes = createGovernanceWrites(db, writer); + const store = createActivityStore(db, { writer: "odysseus" }); + const catalog = createSessionCatalog(() => db, undefined, undefined, + { writer, governance: writes, pricing: { resolve: () => null }, store }); + let authorized = true, requests = 0; + const host = new WsHost({ brainPath: root, catalog, registry: createStaticBackendRegistry([makeFakeBackend({ id: "claude" })], "claude"), + isPrincipalAuthorized: () => authorized, activity: { store, stream: createActivityStream(store), governanceDb: db, governanceWrites: writes } }); + const authorization = host.coordinator.openAuthorization({ principalId: "odysseus", valid: true, expiresAt: Number.MAX_SAFE_INTEGER }); + const controller = new AbortController(); + const turn = { turnId: "voyage", requestId: "voyage-request", principalId: "odysseus", authorization, sessionId: null, startedAt: Date.now(), + abortController: controller, queue: [] } as unknown as import("../src/ws/turns").RunningTurn; + await writes.safetyBegin({ turnId: "voyage", bindingId: crypto.randomUUID(), sessionId: null, principalId: "odysseus", backendId: "claude", at: 0 }); + await writes.safetyReady("voyage", "claude", 1); + await writes.safetyBegin({ turnId: "other-voyage", bindingId: crypto.randomUUID(), sessionId: null, principalId: "odysseus", backendId: "claude", at: 0 }); + await writes.safetyReady("other-voyage", "claude", 1); + const bridge = await makeBridge(host, turn, { backendId: "claude", promptText: "Plan the return to Ithaca." }); + const reads: AdmissionSafetySnapshot[] = [], read = bridge.admissionSafety!.read.bind(bridge.admissionSafety); + bridge.admissionSafety!.read = () => { const value = read(); reads.push(value); return value; }; + const channel = writer.channel(probe, undefined); await channel.ready; + const pending: Promise[] = [], releases: (() => void)[] = []; + const hold = async () => { + const gate = new Int32Array(new SharedArrayBuffer(4)), entered = new Int32Array(new SharedArrayBuffer(4)); + const release = () => { Atomics.store(gate, 0, 1); Atomics.notify(gate, 0); }; + releases.push(release); const committed = channel.call("hold", gate, entered); pending.push(committed); void committed.catch(() => {}); + if (!Atomics.load(entered, 0)) await Atomics.waitAsync(entered, 0, 0, 5000).value; + expect(Atomics.load(entered, 0), "ADVERSE_FIXTURE_HOLDS_REAL_FULL_WRITER").toBe(1); + return { release, committed }; + }; + const upstream = Bun.serve({ hostname: "127.0.0.1", port: 0, fetch() { requests++; return Response.json({ content: [] }); } }); + const proxy = await prepareTurnEgress({ policy: resolveGovernancePolicy({ schema_version: 1 }), bridge, controller, + turnId: "voyage", sessionId: () => turn.sessionId, model: () => null, profile: "governed", origin: "interactive", governanceDb: db, + governanceWrites: writes, record: event => writes.record(event) }); + const enteredAdmission = Promise.withResolvers(), finalReached = Promise.withResolvers(), releaseFinal = Promise.withResolvers(); + const observeOperation = (operation: ReturnType) => ({ ...operation, admit() { + enteredAdmission.resolve(); return operation.admit(); + } }); + let providerAdmissions = 0; + const relay = kind === "inference" + ? startInferenceRelay({ upstream: upstream.url.origin, routes: ["/v1/messages"], credentials: async () => { + if (finalWait) { finalReached.resolve(); await releaseFinal.promise; } + return { "x-api-key": "odysseus-offline-only-key" }; + }, egress: { inference: (...args) => observeOperation(proxy.inference(...args)) } }) + : startProviderRelay({ origins: new Map([["ODYSSEUS_RELAY_KEY", [upstream.url.origin]]]), credential: () => "odysseus-offline-only-key", + admit: async () => { + if (++providerAdmissions === 2 && finalWait) { finalReached.resolve(); await releaseFinal.promise; } + return { allowed: true }; + }, egress: { relayed: (...args) => observeOperation(proxy.relayed(...args)) } }); + return { + db, writer, writes, turn, bridge, catalog, controller, reads, proxy, hold, + enteredAdmission: enteredAdmission.promise, finalReached: finalReached.promise, releaseFinal: releaseFinal.resolve, + revoke() { authorized = false; }, requests: () => requests, + track(work: Promise) { pending.push(work); void work.catch(() => {}); }, + announce() { bridge.emit({ type: "session_info", sessionId: "ithaca", isNew: true }); }, + send() { + return new Promise<{ status: number; body: string }>((resolve, reject) => { + const body = JSON.stringify({ model: "odysseus", messages: [] }); + const outgoing = request({ socketPath: relay.socketPath, path: "/v1/messages", method: "POST", headers: { + "content-type": "application/json", "content-length": String(Buffer.byteLength(body)), "x-brain-provider": "anthropic", + "x-brain-provider-key": "ODYSSEUS_RELAY_KEY", "x-brain-provider-origin": upstream.url.origin, + } }, incoming => { + const chunks: Buffer[] = []; incoming.on("data", chunk => chunks.push(chunk)); incoming.on("error", reject); + incoming.on("end", () => resolve({ status: incoming.statusCode!, body: Buffer.concat(chunks).toString() })); + }); outgoing.on("error", reject); outgoing.end(body); + }); + }, + async close() { + for (const release of releases) release(); releaseFinal.resolve(); + await Promise.allSettled(pending); await relay.stop(); proxy.stop(); await proxy.settled(); upstream.stop(true); + authorization.release(); await catalog.settled!(); host.close(); await writer.close(); db.close(); rmSync(root, { recursive: true, force: true }); + }, + }; +} + +for (const kind of ["inference", "provider"] as const) { + for (const mode of ["cancelled", "authority-revoked", "catalog-failed", "deadline"] as const) { + test(`${kind} refuses ${mode} while its own announced binding is pending`, async () => { + const f = await adverseFixture(kind), clock = Object.getOwnPropertyDescriptor(Date, "now")!, now = Date.now; + try { + if (mode === "catalog-failed") f.db.exec("CREATE TRIGGER refuse_session BEFORE INSERT ON sessions BEGIN SELECT RAISE(ABORT,'Odysseus catalog unavailable'); END"); + const held = await f.hold(); f.announce(); + const response = f.send(); await f.enteredAdmission; + await new Promise(resolve => setImmediate(resolve)); + expect(f.reads, "NO_ADMISSION_SNAPSHOT_BEFORE_OWN_BINDING_SETTLES").toHaveLength(0); + expect(f.requests()).toBe(0); + if (mode === "cancelled") f.controller.abort(); + else if (mode === "authority-revoked") f.revoke(); + else if (mode === "deadline") Object.defineProperty(Date, "now", { ...clock, value: () => now() + 10001 }); + else held.release(); + const result = await response; + expect(result.status, "FAILED_BINDING_NEVER_DISPATCHES").toBe(mode === "cancelled" ? 499 : 403); + expect(f.requests(), "FAILED_BINDING_HAS_ZERO_PROVIDER_REQUESTS").toBe(0); + expect(f.reads, "FAILED_BINDING_NEVER_MINTS_ADMISSION_AUTHORITY").toHaveLength(0); + } finally { Object.defineProperty(Date, "now", clock); await f.close(); } + }); + } + + test(`${kind} does not join or exempt an independent pending input after binding`, async () => { + const f = await adverseFixture(kind); + try { + f.announce(); await f.catalog.settled!(); + const held = await f.hold(); + f.track(f.writes.firstTaint({ kind: "taint", turnId: "voyage", sessionId: "ithaca", actor: "interactive", model: null, profile: null, + payload: { source: "web_fetch", tool: "WebFetch", detail: "Odysseus harbour notice" } })); + expect(f.writes.recordingAvailable("voyage", "ithaca")).toBe(false); + const result = await f.send(); + expect(result.status).toBe(403); + expect(f.requests(), "INDEPENDENT_PENDING_INPUT_NEVER_REACHES_PROVIDER").toBe(0); + expect(f.reads.some(value => !value.recordingAvailable)).toBe(true); + held.release(); + } finally { await f.close(); } + }); + + for (const mode of ["recording-loss", "authority-revoked", "changed-scope"] as const) { + test(`${kind} preserves the final ${mode} fence after initial binding admission`, async () => { + const f = await adverseFixture(kind, true); + try { + f.announce(); await f.catalog.settled!(); + const response = f.send(); await f.finalReached; + expect(f.reads.length, "INITIAL_ADMISSION_SUCCEEDED_BEFORE_FINAL_WAIT").toBeGreaterThanOrEqual(3); + expect(f.requests()).toBe(0); + if (mode === "recording-loss") await f.writes.safetyFail("other-voyage"); + else if (mode === "authority-revoked") f.revoke(); + else { + f.bridge.emit({ type: "session_info", sessionId: "troy", isNew: true }); + await f.catalog.settled!(); + } + f.releaseFinal(); + expect((await response).status).toBe(403); + expect(f.requests(), "FINAL_SAFETY_CHANGE_NEVER_REACHES_PROVIDER").toBe(0); + await f.proxy.settled(); + if (mode === "changed-scope") { + // A contradictory backend announcement also makes its egress + // attribution invalid. The existing recorder must stop the turn + // rather than invent a binding for this terminal denial. + expect(f.proxy.recordingFailure()).toBeDefined(); + expect(f.controller.signal.aborted).toBe(true); + } else { + const reason = mode === "authority-revoked" && kind === "inference" ? "session_binding_unavailable" : "safety_changed"; + expect(f.db.query("SELECT json_extract(payload,'$.reason') reason FROM governance_events WHERE kind='egress_connection'").all()) + .toEqual([{ reason }]); + } + } finally { await f.close(); } + }); + } +} From d8709a2d47b8634afab8c15789f8e6401ee30db9 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Sun, 8 Nov 2026 15:33:06 +0000 Subject: [PATCH 2/3] docs: align relay safety ordering and source citations --- docs/decisions/governed-writable-workers.md | 16 ++++++++-------- docs/plans/reviewable-session-safety.md | 8 +++++--- 2 files changed, 13 insertions(+), 11 deletions(-) diff --git a/docs/decisions/governed-writable-workers.md b/docs/decisions/governed-writable-workers.md index efa291b5b2..56ab9d1d86 100644 --- a/docs/decisions/governed-writable-workers.md +++ b/docs/decisions/governed-writable-workers.md @@ -2249,7 +2249,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:83-203`). The note says egress is +`packages/ui-server/src/brain/turn-egress.ts:84-204`). 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 @@ -3845,7 +3845,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:59-81`). +(`createOutwardCalls`, `packages/ui-server/src/brain/turn-egress.ts:60-82`). A background process left by an earlier call can still connect inside such a window; the proxy records it either way. @@ -3859,7 +3859,7 @@ listen on other ports: `gmail.googleapis.com`, `graph.microsoft.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` and `smtp.resend.com` -(`MAIL_SUBMISSION_PORTS`, `packages/ui-server/src/brain/turn-egress.ts:19-22`). +(`MAIL_SUBMISSION_PORTS`, `packages/ui-server/src/brain/turn-egress.ts:20-23`). Microsoft Graph and Exchange Online carry more than mail, so their reads by an opaque script also wait on the card. The coordinator chose this list for #1665; the maintainer may override it. @@ -3985,7 +3985,7 @@ charges only after admission); otherwise it is refused and recorded as an `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:83-229`). Hosts without managed +`packages/ui-server/src/brain/turn-egress.ts:84-230`). Hosts without managed native storage have no proxy, so the Bash classifier remains their shell rule and nothing narrows their egress. @@ -4033,12 +4033,12 @@ through the turn's tool-permission card (`toolName: "Network"`, `kind: (`const narrowing`, `packages/ui-sdk/src/server/egress-proxy.ts:198-203`). 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:38-43`). +(`taintedDestinationDescription`, `packages/ui-server/src/brain/turn-egress.ts:39-44`). 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:167-178`). +(`const approveTainted`, `packages/ui-server/src/brain/turn-egress.ts:168-179`). 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 describeRefusal`, `packages/ui-sdk/src/server/egress-proxy.ts:88-104`). Stopping the turn while the @@ -4062,7 +4062,7 @@ the byte ceiling, an unapproved outward host, or a tainted session's host outside its allow-list, with the session's first taint source and what the user can do (`function describeRefusal`, `packages/ui-sdk/src/server/egress-proxy.ts:88-104`; the source wording, -`cause: () =>`, `packages/ui-server/src/brain/turn-egress.ts:194`). The status +`cause: () =>`, `packages/ui-server/src/brain/turn-egress.ts:195`). The status line carries the reason because `curl -v`, `git` and `egress-connect` print only that line for a refused CONNECT. The provider relay passes the proxy's reason through as the refusal body's `error.message` and an additive @@ -4167,7 +4167,7 @@ admission (`relayed`, `packages/ui-sdk/src/server/egress-proxy.ts:338`), and worker HTTP and `CONNECT` traffic cannot claim it, even to a provider's host (`narrowed`, `packages/ui-sdk/src/server/egress-proxy.ts:196`). Turn egress records neither a taint nor a contacted host for the operation -(`admitted`, `packages/ui-server/src/brain/turn-egress.ts:154-157`). So in a +(`admitted`, `packages/ui-server/src/brain/turn-egress.ts:204-209`). So in a tainted session, the worker's own traffic stays narrowed away from the provider's host. diff --git a/docs/plans/reviewable-session-safety.md b/docs/plans/reviewable-session-safety.md index 2fe9795369..3dc13973c9 100644 --- a/docs/plans/reviewable-session-safety.md +++ b/docs/plans/reviewable-session-safety.md @@ -36,9 +36,11 @@ public design or its fixtures. Fictional examples use the Odysseus world. never prove finalized delivery or complete coverage. - The turn proxy records each admitted non-provider connection and terminal exposure observation (`prepareTurnEgress`, - `packages/ui-server/src/brain/turn-egress.ts:83-269`). Relay admissions join - this proxy's submitted terminal observations before reading fresh safety, - without excluding independent pending input. A raw CONNECT reveals + `packages/ui-server/src/brain/turn-egress.ts:84-272`). Relay admissions join + this proxy's submitted terminal observations and its own announced session + binding before reading fresh safety (`settleTurnSessionBinding`, + `packages/ui-server/src/ws/bridge-session-binding.ts:14-28`), without excluding + independent pending input. A raw CONNECT reveals only an authority and opaque bytes, not a repository path or inner protocol (`startEgressProxy`, `packages/ui-sdk/src/server/egress-proxy.ts:124-359`). - Outward decisions read session taint at admission (`prepareOutwardPlan`, From 6057be27456fc0b2ec439045b29d0302bd7ec284 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 10 Nov 2026 10:52:45 +0000 Subject: [PATCH 3/3] test(ui): give provider-history hosts live principal authority --- tests/fixtures/provider-history-host.ts | 14 ++++- tests/provider-history-host-authority.test.ts | 56 +++++++++++++++++++ 2 files changed, 67 insertions(+), 3 deletions(-) create mode 100644 tests/provider-history-host-authority.test.ts diff --git a/tests/fixtures/provider-history-host.ts b/tests/fixtures/provider-history-host.ts index 6de707ffaa..8a5695e917 100644 --- a/tests/fixtures/provider-history-host.ts +++ b/tests/fixtures/provider-history-host.ts @@ -2,6 +2,7 @@ import type { AgentBackend, ClientEnvironment, ServerMessage } from "@schlessera/brain-ui-sdk/server"; import { createFixtureTurnHost } from "./turn-host-fixture.js"; import { createUiDb } from "../../packages/ui-server/src/db/client.js"; +import { createPrincipal, isUsablePrincipal, resolvePrincipal } from "../../packages/ui-server/src/db/principals.js"; import { createTurnBudgets } from "../../packages/ui-server/src/brain/turn-budgets.js"; import { createStaticBackendRegistry } from "../../packages/ui-server/src/agent/backend.js"; import { createSessionCatalog } from "../../packages/ui-server/src/ws/session-catalog.js"; @@ -10,14 +11,21 @@ import { runSession } from "../../packages/ui-server/src/ws/run-session.js"; export function historyHost(brainPath: string, backend: AgentBackend) { const db = createUiDb(":memory:"); + const principal = createPrincipal(db, { authMethod: "password", label: "Odysseus", ttlSeconds: 3600 }); const native = createFixtureTurnHost(brainPath, db); const budgets = createTurnBudgets(db, { resolve: () => null }, () => Date.parse("2026-07-12T00:00:00Z")); const host = new WsHost({ ...native, brainPath, registry: createStaticBackendRegistry([backend], backend.id), - catalog: createSessionCatalog(() => db), budgets, turnTimeoutMs: 30_000 }); - const authorization = host.coordinator.openAuthorization({ principalId: "odysseus", valid: true, expiresAt: Number.MAX_SAFE_INTEGER }); + catalog: createSessionCatalog(() => db), budgets, turnTimeoutMs: 30_000, + // Match application auth: every continuation reads the durable principal. + isPrincipalAuthorized(id) { + const current = resolvePrincipal(db, id); + return current !== null && isUsablePrincipal(current, Date.now()); + } }); + const authorization = host.coordinator.openAuthorization({ principalId: principal.id, valid: true, expiresAt: principal.expiresAt }); const frames: ServerMessage[] = []; - host.clients.add({ send(text) { frames.push(JSON.parse(text)); } }, "odysseus"); + host.clients.add({ send(text) { frames.push(JSON.parse(text)); } }, principal.id); return { + host, db, principalId: principal.id, async turn(text: string, client: ClientEnvironment, sessionId?: string): Promise { frames.length = 0; await runSession(host, { authorization, text, client, sessionId, attachments: [], providerId: "fixture" }); diff --git a/tests/provider-history-host-authority.test.ts b/tests/provider-history-host-authority.test.ts new file mode 100644 index 0000000000..5760e15700 --- /dev/null +++ b/tests/provider-history-host-authority.test.ts @@ -0,0 +1,56 @@ +import { expect, test } from "bun:test"; +import { mkdtempSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { request } from "node:http"; +import { resolveGovernancePolicy } from "@schlessera/brain-common/internal/governance-policy"; +import { startInferenceRelay, startProviderRelay } from "@schlessera/brain-ui-sdk/internal"; +import { historyHost } from "./fixtures/provider-history-host"; +import { fixtureBrain } from "./fixtures/provider-history-brain"; +import { makeFakeBackend } from "../packages/ui-server/tests/helpers/fake-backend"; +import { makeBridge } from "../packages/ui-server/src/ws/bridge"; +import { prepareTurnEgress } from "../packages/ui-server/src/brain/turn-egress"; +import { revokePrincipal } from "../packages/ui-server/src/db/principals"; +import type { RunningTurn } from "../packages/ui-server/src/ws/turns"; + +for (const backendId of ["pi", "claude"] as const) for (const kind of ["inference", "provider"] as const) { + test(`${backendId} provider-history host gives its relay live owner authority and observes revocation: ${kind}`, async () => { + const root = mkdtempSync(join(tmpdir(), "odysseus-history-authority-")); + const brain = fixtureBrain(root, "voyage"), f = historyHost(brain, makeFakeBackend({ id: backendId })); + const controller = new AbortController(); + const authorization = f.host.coordinator.openAuthorization({ principalId: f.principalId, valid: true, expiresAt: Number.MAX_SAFE_INTEGER }); + const turn = { turnId: "voyage", requestId: "voyage-request", principalId: f.principalId, authorization, sessionId: null, + startedAt: Date.now(), abortController: controller, queue: [] } as unknown as RunningTurn; + let requests = 0; + const origin = Bun.serve({ hostname: "127.0.0.1", port: 0, fetch() { requests++; return Response.json({ content: [] }); } }); + let proxy: Awaited> | undefined; + let relay: ReturnType | ReturnType | undefined; + try { + const bridge = await makeBridge(f.host, turn, { backendId, promptText: "Odysseus reads the harbour notice." }); + bridge.emit({ type: "session_info", sessionId: "ithaca", isNew: true }); + await f.host.catalog.settled?.(); + proxy = await prepareTurnEgress({ policy: resolveGovernancePolicy({ schema_version: 1 }), bridge, controller, turnId: turn.turnId, + sessionId: () => turn.sessionId, model: () => null, profile: "strict", origin: "interactive" }); + relay = kind === "inference" + ? startInferenceRelay({ upstream: origin.url.origin, routes: ["/v1/messages"], credentials: { "x-api-key": "odysseus-offline-only-key" }, egress: proxy }) + : startProviderRelay({ origins: new Map([["ODYSSEUS_RELAY_KEY", [origin.url.origin]]]), credential: () => "odysseus-offline-only-key", egress: proxy }); + const send = () => new Promise((resolve, reject) => { + const body = JSON.stringify({ model: "odysseus", messages: [] }); + const outgoing = request({ socketPath: relay!.socketPath, path: "/v1/messages", method: "POST", headers: { + "content-type": "application/json", "content-length": String(Buffer.byteLength(body)), "x-brain-provider": "anthropic", + "x-brain-provider-key": "ODYSSEUS_RELAY_KEY", "x-brain-provider-origin": origin.url.origin, + } }, incoming => { incoming.resume(); incoming.on("error", reject); incoming.on("end", () => resolve(incoming.statusCode!)); }); + outgoing.on("error", reject); outgoing.end(body); + }); + expect(await send(), "PROVIDER_HISTORY_FIXTURE_HAS_LIVE_HOST_AUTHORITY").toBe(200); + expect(requests, "AUTHORIZED_HISTORY_REQUEST_DISPATCHES_ONCE").toBe(1); + expect(revokePrincipal(f.db, f.principalId, Date.now())).toEqual([f.principalId]); + expect(authorization.valid, "COORDINATOR_FIELDS_ALONE_DO_NOT_GRANT_AUTHORITY").toBe(true); + expect(await send(), "REVOKED_HISTORY_OWNER_NEVER_DISPATCHES").toBe(403); + expect(requests, "REVOCATION_CANNOT_RETRY_OR_REACH_THE_PROVIDER").toBe(1); + } finally { + controller.abort(); await relay?.stop(); proxy?.stop(); await proxy?.settled(); origin.stop(true); + authorization.release(); await f.close(); rmSync(root, { recursive: true, force: true }); + } + }); +}