diff --git a/.changeset/3613-approved-owner-read-resolution.md b/.changeset/3613-approved-owner-read-resolution.md new file mode 100644 index 0000000000..664498f97f --- /dev/null +++ b/.changeset/3613-approved-owner-read-resolution.md @@ -0,0 +1,5 @@ +--- +"@schlessera/brain-ui-server": patch +--- + +Bind immutable read identity evidence to independently published Settings owner approval. Record unavailable qualification for missing or mismatched approval, repository transfer/name reuse and replaced policy roots, and recheck inside the write transaction after waits. Bind publication to the qualified native filesystem and live-brain subvolume UUID, preserving ordinary restart while refusing recreated roots and unqualified hosts. Source trust remains disabled. diff --git a/.changeset/combined-trigger-future-rule.md b/.changeset/combined-trigger-future-rule.md new file mode 100644 index 0000000000..488c35329b --- /dev/null +++ b/.changeset/combined-trigger-future-rule.md @@ -0,0 +1,7 @@ +--- +"@schlessera/brain-ui-sdk": minor +"@schlessera/brain-ui-server": minor +"@schlessera/brain-ui-react": minor +--- + +Review one finalized trigger with optional future origin or tunnel trust. Show exact policy changes, keep recipient permission independent, and preserve publication/verdict receipts across retries and partial completion. diff --git a/.changeset/conservative-trust-capabilities.md b/.changeset/conservative-trust-capabilities.md new file mode 100644 index 0000000000..966754aceb --- /dev/null +++ b/.changeset/conservative-trust-capabilities.md @@ -0,0 +1,5 @@ +--- +"@schlessera/brain-ui-react": patch +--- + +Keep Security settings readable and enforcement-dependent edits disabled when a host omits trust capability advertisements. diff --git a/.changeset/egress-upstream-socket-ownership.md b/.changeset/egress-upstream-socket-ownership.md new file mode 100644 index 0000000000..c9eec440ba --- /dev/null +++ b/.changeset/egress-upstream-socket-ownership.md @@ -0,0 +1,5 @@ +--- +"@schlessera/brain-ui-sdk": patch +--- + +Give each cleartext HTTP proxy operation its own non-pooled upstream connection so a stale same-origin socket cannot produce a spurious 502. Preserve cancellation, admission fences and byte accounting without retrying requests. diff --git a/.changeset/exact-origin-trust.md b/.changeset/exact-origin-trust.md new file mode 100644 index 0000000000..557d93dae6 --- /dev/null +++ b/.changeset/exact-origin-trust.md @@ -0,0 +1,73 @@ +--- +"@schlessera/brain-ui-server": minor +"@schlessera/brain-ui-sdk": minor +"@schlessera/brain-ui-react": minor +--- + +Enforce prospective exact-origin and explicit-tunnel source trust with separate restricted-recipient permission. This pre-1.0 semantic break lets qualified future inputs avoid unresolved triggers while retaining their historical rule, policy hash and revision. Removing a rule fences active admissions and interrupts trusted input streams; repository trust remains unavailable. Existing triggers, independent controls and provider history are preserved. + +Bind pending Network approvals to actual transport identity and record the hash of freshly verified valid policy bytes even when trust rules are unchanged. + +Enforce canonical bracketed IPv6 tunnels, retain last-valid live trust on bounded policy read failures, and prove DNS subdomains cannot inherit parent trust. + +Classify live trust observations consistently: stable invalid or unreadable policy retains last-valid rules with an error, verification races fence, and unchanged chunks use metadata generation checks instead of full policy reads. Refresh rechecks after its durable write. + +Normalize all transport host identities, recheck send authority on every HTTP write/end and tunnel chunk, and retain explicit recipient approvals independently of source trust. + +Validate complete trusted admission variants on the wire, avoid absent-approval and unchanged-stream evidence scans with live change counters, and let independent readers recover after projection publication races. + +Record unmatched source hash and revision from the same live snapshot used for matching, and display IPv6 provenance with bracketed authorities. + +Preserve absolute DNS authorities during resolution/dialing separately from comparison keys, and retain the version-1 detector ID contract while strictly validating admission evidence. + +Cancel queued turn-start trust refreshes with the turn signal, and distinguish budget, safety and unavailable charge results across proxy, inference/provider relays and managed reference acquisition. + +Revalidate only an active input’s admitted source rule across trust revisions, unify source revocation audit/safety results, and reject invalid byte counts before either charge counter changes. + +Retire source-rule instances durably across independent publishers, preserve typed commit/charge failures on managed streams, and classify post-write source revocation identically to notification and send fences. + +Allow HTTP and tunnel completion exactly at the byte ceiling while preserving terminal safety checks and refusing bytes beyond it. + +Separate preparation byte charging from dispatch notification and contacted-host grants, classify initial recording loss as unavailable, and preserve historical IPv6 session grants through canonical host lookup. + +Capture one immutable typed refusal per egress operation before abort, preserve it through every caller and audit record, and fence outward exemptions with the active call-classification generation. + +Guard the concrete proxy lifecycle through pending, admitted, dispatched and terminal states; distinguish exhausted new dispatch from exact-cap stream completion, fence closed wait continuations, and release all per-operation admission keys after terminal evidence. + +Validate destination provenance through the wire schema before durable writes, cancel every upstream cleanup/request with its operation and deadline, and preserve unavailable classifications through repeated inference admission. + +Capture relay error causes before terminal signal cleanup, preserve failed versus cancelled receipts and statuses across every response path, and release caller listeners from every operation termination path. + +Preserve provider cancellation reasons, fence sends after preparation observers, and meter Files cleanup response headers. + +Keep provider receipt status as upstream evidence and fence buffered response release at EOF. + +Share relay response metering and EOF fencing across normal, Files, redirect and cleanup paths. + +Separate preparation from actual dispatch facts and fence streaming delivery in the same synchronous handoff. + +Fence upstream HTTP request construction and prove in-place selector edits retire source instances. + +Require remaining allowance on every governed web/relay route and debit received overflow consistently across proxy and relay traffic. + +Preserve ordinary upstream-failure classification for synchronous transport handoff errors. + +Meter raw proxy header pairs and all observable Fetch headers before forwarding filters; clarify the conservative HTTP wire bound. + +Publish dispatched exposure and contacted-host grants only after the transport constructor or fetch call returns successfully; synchronous construction failures remain upstream failures without granting recipient permission. + +Bind recipient receipts to the final dispatch authority and share verified, bounded admission validation between durable ingestion, projection and history, including retained provenance after pruning. + +Meter relay worker request headers before filtering and cover upstream credential/header growth with the same shared head meter. + +Add remainingBytes as an optional SDK route reader, preserving older operation-only routes with a documented 32 MiB per-request compatibility ceiling; host builders require it internally. Meter informational HTTP response heads before the final response. + +Require a confirmed durable occurrence before trusted dispatch; false or failed source writes refuse the affected operation as recording unavailable, including permanently restricted turns and legacy recorder adapters. + +Keep an approved connection valid across the occurrence and initial collection writes of every peer admitted under that same Network card. Independent evidence still fences dispatch. Restore safety-changed 403 for peer recorder loss or independent pending input while preserving operation-specific recorder-unavailable 503. Preserve the fixed inference refusal wire message and its stored-history classification, keeping detailed causes in host-only denialReason. Document all optional egress receipt fields. + +Preserve a committed explicit session recipient grant across later input without relaxing the first-dispatch fence. Keep outward callback payloads compatible and align peer-loss audit/status assertions and received-header byte-cap expectations with their contract. + +Keep shared-card peer admissions usable with the real governance writer: exclude only their exact owned local/durable pending reservations from approval freshness and recording-availability fences. Independent pending input, recorder failures and capacity remain enforced; global safety projections and history remain unchanged. + +Preserve typed refusal causes through session-binding settlement: revoked authority answers 403 safety_changed, an aborted wait is cancelled, and genuinely pending/failed/missing binding remains 503 unavailable. Native Pi credential-error assertions follow the existing 502 failed-attempt contract without changing the relay. diff --git a/.changeset/security-trust-settings.md b/.changeset/security-trust-settings.md new file mode 100644 index 0000000000..760d7a8b35 --- /dev/null +++ b/.changeset/security-trust-settings.md @@ -0,0 +1,12 @@ +--- +"@schlessera/brain-ui-react": minor +"@schlessera/brain-ui-server": minor +"@schlessera/brain-ui-sdk": minor +"@schlessera/brain-common": minor +--- + +Add Security settings for exact origin and opaque tunnel source trust and separate data-sending permission, using protected exact-byte owner review. Show repository scopes as disabled/unverified until enforcement is available. Authenticated callers can read sanitized trust facts without gaining mutation authority; older hosts remain read-only. + +Recheck live read authority after waits, discard private reviews on owner loss, recover expired prepared reviews, and prevent refreshed drafts from restoring revoked permissions or removing replacement rules. + +Keep editor transitions explicit, clear drafts after denied reads, allow leaving unknown outcomes, recheck enforcement on writes, preserve unchanged selections using observation-only rule instances, and refresh enforcing policy facts with trust settings. diff --git a/.changeset/trust-refresh-admission.md b/.changeset/trust-refresh-admission.md new file mode 100644 index 0000000000..a653fbf8e3 --- /dev/null +++ b/.changeset/trust-refresh-admission.md @@ -0,0 +1,5 @@ +--- +"@schlessera/brain-ui-server": patch +--- + +Keep turn admission independent of a running index when the verified policy hash already matches the healthy durable trust projection. Changed or unavailable policy still refreshes under the cancellable brain lock. diff --git a/api-report/common.txt b/api-report/common.txt index 865bc57094..1b7c20ca0c 100644 --- a/api-report/common.txt +++ b/api-report/common.txt @@ -480,6 +480,25 @@ export "./internal/safe-path" (./src/safe-path.ts) resolveContained resolveContainedSync +export "./internal/taint-trust" (./src/taint-trust.ts) + TRUST_LIMITS + TRUST_RUNTIME_CAPABILITIES + type TrustAdmission + type TrustMatch + type TrustProvenance + TrustProvenanceSchema + type TrustRule + TrustRuleSchema + type TrustSelector + TrustSelectorSchema + type TrustVerification + TrustedSourcesSchema + canonicalTrustHost + matchTrustRules + parseTrustGithub + parseTrustOrigin + parseTrustTunnel + export "./internal/worker-areas" (./src/worker-areas.ts) BRAIN_SCRATCH_DIR BRAIN_WORKSPACES_DIR diff --git a/api-report/ui-react.txt b/api-report/ui-react.txt index f0138dccda..0250775cb5 100644 --- a/api-report/ui-react.txt +++ b/api-report/ui-react.txt @@ -920,6 +920,89 @@ signatures (every public export and the types it is made of) view: TrackFileView; props: TrackMapProps; } + TrustCapabilities (packages/ui-react/src/lib/trust-settings.ts) + export interface TrustCapabilities { + originRules: boolean; + repositoryRules: boolean; + recipientRules: boolean; + repositoryIdentity: boolean; + readOnlyReason: string | null; + } + TrustChange (packages/ui-react/src/lib/trust-settings.ts) + export type TrustChange = { + action: "create" | "edit"; + rule: TrustRule; + } | { + action: "remove"; + ruleId: string; + }; + TrustOperation (packages/ui-react/src/lib/trust-settings.ts) + export interface TrustOperation { + receipt: { + requestId: string; + stage: "prepared" | "file_published" | "committed" | "partial" | "unknown" | "refused"; + publication: "not_published" | "proved" | "unknown"; + currentRule: "present" | "removed" | "changed" | "unknown"; + enforcement: "enforced" | "unavailable"; + reason: string | null; + }; + review: { + reviewId: string; + reviewedBytesHash: string; + base: string | null; + proposed: string; + diff: string; + expiresAt: number; + includesFutureRepositories: boolean; + }; + policy: TrustPolicy; + capabilities: TrustCapabilities; + } + TrustPolicy (packages/ui-react/src/lib/trust-settings.ts) + export interface TrustPolicy { + revision: string; + policyHash: string | null; + error: string | null; + rules: TrustRule[]; + } + TrustRule (packages/ui-react/src/lib/trust-settings.ts) + export interface TrustRule { + id: string; + label: string; + selector: TrustSelector; + incomingContent: boolean; + recipientWhileRestricted: boolean; + } + TrustSelector (packages/ui-react/src/lib/trust-settings.ts) + export type TrustSelector = { + kind: "web_origin"; + scheme: "http" | "https"; + host: string; + port: number; + } | { + kind: "tunnel_authority"; + host: string; + port: number; + } | { + kind: "github_repository"; + host: "github.com"; + owner: string; + repository: string; + repositoryId: string; + } | { + kind: "github_owner"; + host: "github.com"; + owner: string; + ownerId: string; + }; + TrustSettingsRead (packages/ui-react/src/lib/trust-settings.ts) + export interface TrustSettingsRead extends TrustPolicy { + origins: TrustRule[]; + repositories: TrustRule[]; + capabilities: TrustCapabilities; + mutationAllowed?: boolean; + instances?: Record; + } TurnNotice (packages/ui-react/src/stores/chat-state.ts) export interface TurnNotice { cause: "timeout" | "aborted" | "unspecified"; @@ -1414,6 +1497,256 @@ signatures (every public export and the types it is made of) }; version: 1; }>; + safetyFutureCommit: (sessionId: string, body: SafetyFutureCommit, signal: AbortSignal) => Promise<{ + currentProjection: { + coverage: { + detectorVersion: 1; + epochs: { + acknowledged: string[]; + backendId: string; + endSequence: null | string; + id: string; + mandatory: string[]; + reason: null | string; + startSequence: string; + status: "complete" | "incomplete" | "unknown"; + }[]; + exclusions: string[]; + state: "complete" | "incomplete" | "unknown"; + }; + earliestUnresolvedId: null | string; + evidenceRevision: string; + pendingCount: number; + reasons: ("capacity" | "coverage_unknown" | "recording_failed" | "recording_pending" | "unresolved")[]; + restriction: "normal" | "restricted"; + session: null | { + historyGeneration: string; + historyOwnerId: string; + sessionId: string; + }; + unresolvedCount: number; + }; + occurrenceId: string; + requestId: string; + rule: { + currentRule: "changed" | "present" | "removed" | "unknown"; + enforcement: "enforced" | "unavailable"; + operationId: string; + publication: "not_published" | "proved" | "unknown"; + publishedTrustRevision: null | string; + reason: null | string; + requestId: string; + ruleId: string; + stage: "committed" | "file_published" | "partial" | "prepared" | "refused" | "unknown"; + version: 1; + }; + session: { + historyGeneration: string; + historyOwnerId: string; + sessionId: string; + }; + stage: "partial" | "prepared" | "refused" | "unknown" | "verdict_committed"; + verdict: null | { + occurrenceId: string; + operationId: null | string; + projection: null | { + coverage: { + detectorVersion: 1; + epochs: { + acknowledged: string[]; + backendId: string; + endSequence: null | string; + id: string; + mandatory: string[]; + reason: null | string; + startSequence: string; + status: "complete" | "incomplete" | "unknown"; + }[]; + exclusions: string[]; + state: "complete" | "incomplete" | "unknown"; + }; + earliestUnresolvedId: null | string; + evidenceRevision: string; + pendingCount: number; + reasons: ("capacity" | "coverage_unknown" | "recording_failed" | "recording_pending" | "unresolved")[]; + restriction: "normal" | "restricted"; + session: null | { + historyGeneration: string; + historyOwnerId: string; + sessionId: string; + }; + unresolvedCount: number; + }; + reason: null | string; + requestId: null | string; + session: { + historyGeneration: string; + historyOwnerId: string; + sessionId: string; + }; + stage: "prepared" | "refused" | "verdict_committed"; + verdict: "committed" | "unresolved"; + version: 1; + }; + version: 1; + }>; + safetyFuturePrepare: (body: SafetyFuturePrepare, signal: AbortSignal) => Promise<{ + currentProjection: null | { + coverage: { + detectorVersion: 1; + epochs: { + acknowledged: string[]; + backendId: string; + endSequence: null | string; + id: string; + mandatory: string[]; + reason: null | string; + startSequence: string; + status: "complete" | "incomplete" | "unknown"; + }[]; + exclusions: string[]; + state: "complete" | "incomplete" | "unknown"; + }; + earliestUnresolvedId: null | string; + evidenceRevision: string; + pendingCount: number; + reasons: ("capacity" | "coverage_unknown" | "recording_failed" | "recording_pending" | "unresolved")[]; + restriction: "normal" | "restricted"; + session: null | { + historyGeneration: string; + historyOwnerId: string; + sessionId: string; + }; + unresolvedCount: number; + }; + occurrenceId: string; + requestId: string; + review: { + base: null | string; + diff: string; + expiresAt: number; + includesFutureRepositories: boolean; + proposed: string; + repositoryIdentity: null; + reviewId: string; + reviewedBytesHash: string; + }; + rule: { + currentRule: "changed" | "present" | "removed" | "unknown"; + enforcement: "enforced" | "unavailable"; + operationId: string; + publication: "not_published" | "proved" | "unknown"; + publishedTrustRevision: null | string; + reason: null | string; + requestId: string; + ruleId: string; + stage: "committed" | "file_published" | "partial" | "prepared" | "refused" | "unknown"; + version: 1; + }; + session: { + historyGeneration: string; + historyOwnerId: string; + sessionId: string; + }; + version: 1; + }>; + safetyFutureStatus: (body: { + occurrenceId: string; + session: import("@schlessera/brain-ui-sdk/protocol").SafetySessionKey; + version: 1; + }, signal: AbortSignal) => Promise; safetyPrepare: (body: SafetyReviewBody, signal: AbortSignal) => Promise<{ code: "capacity" | "not_finalized" | "recording_failed" | "request_conflict" | "request_expired" | "resync_required" | "retired" | "stale_revision" | "unauthorized" | "unavailable"; currentProjection: null | { @@ -1651,6 +1984,10 @@ signatures (every public export and the types it is made of) toolPermissions: () => Promise<{ tools: string[]; }>; + trustCommit: (operation: TrustOperation, signal?: AbortSignal) => Promise; + trustPrepare: (change: TrustChange, expectedTrustRevision: string, expectedPolicyHash: null | string, signal?: AbortSignal) => Promise; + trustReceipt: (requestId: string, signal?: AbortSignal) => Promise; + trustSettings: (signal?: AbortSignal) => Promise; turnJournal: (sessionId: string, turnId: string, signal?: AbortSignal) => Promise; turnJournalPreview: (sessionId: string, turnId: string, sequence: number, signal?: AbortSignal) => Promise<{ after?: string; @@ -2235,6 +2572,256 @@ signatures (every public export and the types it is made of) }; version: 1; }>; + safetyFutureCommit: (sessionId: string, body: import("@schlessera/brain-ui-sdk").SafetyFutureCommit, signal: AbortSignal) => Promise<{ + currentProjection: { + coverage: { + detectorVersion: 1; + epochs: { + acknowledged: string[]; + backendId: string; + endSequence: null | string; + id: string; + mandatory: string[]; + reason: null | string; + startSequence: string; + status: "complete" | "incomplete" | "unknown"; + }[]; + exclusions: string[]; + state: "complete" | "incomplete" | "unknown"; + }; + earliestUnresolvedId: null | string; + evidenceRevision: string; + pendingCount: number; + reasons: ("capacity" | "coverage_unknown" | "recording_failed" | "recording_pending" | "unresolved")[]; + restriction: "normal" | "restricted"; + session: null | { + historyGeneration: string; + historyOwnerId: string; + sessionId: string; + }; + unresolvedCount: number; + }; + occurrenceId: string; + requestId: string; + rule: { + currentRule: "changed" | "present" | "removed" | "unknown"; + enforcement: "enforced" | "unavailable"; + operationId: string; + publication: "not_published" | "proved" | "unknown"; + publishedTrustRevision: null | string; + reason: null | string; + requestId: string; + ruleId: string; + stage: "committed" | "file_published" | "partial" | "prepared" | "refused" | "unknown"; + version: 1; + }; + session: { + historyGeneration: string; + historyOwnerId: string; + sessionId: string; + }; + stage: "partial" | "prepared" | "refused" | "unknown" | "verdict_committed"; + verdict: null | { + occurrenceId: string; + operationId: null | string; + projection: null | { + coverage: { + detectorVersion: 1; + epochs: { + acknowledged: string[]; + backendId: string; + endSequence: null | string; + id: string; + mandatory: string[]; + reason: null | string; + startSequence: string; + status: "complete" | "incomplete" | "unknown"; + }[]; + exclusions: string[]; + state: "complete" | "incomplete" | "unknown"; + }; + earliestUnresolvedId: null | string; + evidenceRevision: string; + pendingCount: number; + reasons: ("capacity" | "coverage_unknown" | "recording_failed" | "recording_pending" | "unresolved")[]; + restriction: "normal" | "restricted"; + session: null | { + historyGeneration: string; + historyOwnerId: string; + sessionId: string; + }; + unresolvedCount: number; + }; + reason: null | string; + requestId: null | string; + session: { + historyGeneration: string; + historyOwnerId: string; + sessionId: string; + }; + stage: "prepared" | "refused" | "verdict_committed"; + verdict: "committed" | "unresolved"; + version: 1; + }; + version: 1; + }>; + safetyFuturePrepare: (body: import("@schlessera/brain-ui-sdk").SafetyFuturePrepare, signal: AbortSignal) => Promise<{ + currentProjection: null | { + coverage: { + detectorVersion: 1; + epochs: { + acknowledged: string[]; + backendId: string; + endSequence: null | string; + id: string; + mandatory: string[]; + reason: null | string; + startSequence: string; + status: "complete" | "incomplete" | "unknown"; + }[]; + exclusions: string[]; + state: "complete" | "incomplete" | "unknown"; + }; + earliestUnresolvedId: null | string; + evidenceRevision: string; + pendingCount: number; + reasons: ("capacity" | "coverage_unknown" | "recording_failed" | "recording_pending" | "unresolved")[]; + restriction: "normal" | "restricted"; + session: null | { + historyGeneration: string; + historyOwnerId: string; + sessionId: string; + }; + unresolvedCount: number; + }; + occurrenceId: string; + requestId: string; + review: { + base: null | string; + diff: string; + expiresAt: number; + includesFutureRepositories: boolean; + proposed: string; + repositoryIdentity: null; + reviewId: string; + reviewedBytesHash: string; + }; + rule: { + currentRule: "changed" | "present" | "removed" | "unknown"; + enforcement: "enforced" | "unavailable"; + operationId: string; + publication: "not_published" | "proved" | "unknown"; + publishedTrustRevision: null | string; + reason: null | string; + requestId: string; + ruleId: string; + stage: "committed" | "file_published" | "partial" | "prepared" | "refused" | "unknown"; + version: 1; + }; + session: { + historyGeneration: string; + historyOwnerId: string; + sessionId: string; + }; + version: 1; + }>; + safetyFutureStatus: (body: { + occurrenceId: string; + session: import("@schlessera/brain-ui-sdk").SafetySessionKey; + version: 1; + }, signal: AbortSignal) => Promise; safetyPrepare: (body: import("@schlessera/brain-ui-sdk").SafetyReviewBody, signal: AbortSignal) => Promise<{ code: "capacity" | "not_finalized" | "recording_failed" | "request_conflict" | "request_expired" | "resync_required" | "retired" | "stale_revision" | "unauthorized" | "unavailable"; currentProjection: null | { @@ -2472,6 +3059,10 @@ signatures (every public export and the types it is made of) toolPermissions: () => Promise<{ tools: string[]; }>; + trustCommit: (operation: import("./lib/trust-settings.js").TrustOperation, signal?: AbortSignal) => Promise; + trustPrepare: (change: import("./lib/trust-settings.js").TrustChange, expectedTrustRevision: string, expectedPolicyHash: null | string, signal?: AbortSignal) => Promise; + trustReceipt: (requestId: string, signal?: AbortSignal) => Promise; + trustSettings: (signal?: AbortSignal) => Promise; turnJournal: (sessionId: string, turnId: string, signal?: AbortSignal) => Promise; turnJournalPreview: (sessionId: string, turnId: string, sequence: number, signal?: AbortSignal) => Promise<{ after?: string; diff --git a/api-report/ui-sdk.txt b/api-report/ui-sdk.txt index dede9504c5..7d8a6226e2 100644 --- a/api-report/ui-sdk.txt +++ b/api-report/ui-sdk.txt @@ -337,6 +337,9 @@ export "." (./src/index.ts) SUBSCRIPTION_AUTH_INSTRUCTIONS SUBSCRIPTION_RELOGIN_PROCEDURE type SafetyCapabilities + type SafetyFutureCommit + type SafetyFuturePrepare + type SafetyFuturePrepared type SafetyHistoryProjection type SafetyIdentity type SafetyPage @@ -1115,6 +1118,9 @@ export "./client" (./src/client/index.ts) SUBSCRIPTION_AUTH_INSTRUCTIONS SUBSCRIPTION_RELOGIN_PROCEDURE type SafetyCapabilities + type SafetyFutureCommit + type SafetyFuturePrepare + type SafetyFuturePrepared type SafetyHistoryProjection type SafetyIdentity type SafetyPage @@ -1384,7 +1390,10 @@ export "./internal" (./src/internal.ts) type CompiledWorkerCommandPolicy DEFAULT_TURN_TEMP_BYTES EgressAdmissionRefused + type EgressChargeFailure + type EgressChargeResult type EgressDestinationPolicy + type EgressFailureReason type EgressRecord type EgressRefusal FIRST_PARTY_PROVIDER_RECIPIENTS @@ -1492,6 +1501,7 @@ export "./internal" (./src/internal.ts) assertManagedTurnStartupView assertScratchMaskAsync bashCommand + canonicalEgressHost canonicalModelId claudeMaskFilename claudeReportedMaskPath @@ -1511,6 +1521,7 @@ export "./internal" (./src/internal.ts) describeClient egressAddressRefusal egressBootstrapEntry + egressChargeRefusal envMaskedPaths execWrapperSpawnOptions handleTurnTemp @@ -1588,6 +1599,9 @@ export "./internal" (./src/internal.ts) runMaintenanceWorker runMaintenanceWorkerSync safetyAdmissionRefusal + safetyAdmissionSchema + safetyOccurrenceAdmissionSchema + safetyRecordSchema sameSafetyAdmission sessionPromptContext sessionPromptContextLocation @@ -1599,6 +1613,7 @@ export "./internal" (./src/internal.ts) stripHostContextFromTitle turnTempLimit turnTempSpace + validatedEgressProvenance verifiedWorkerIdentity webSearchBrief webSearchKeySource @@ -1971,6 +1986,9 @@ export "./protocol" (./src/protocol.ts) SUBSCRIPTION_AUTH_INSTRUCTIONS SUBSCRIPTION_RELOGIN_PROCEDURE type SafetyCapabilities + type SafetyFutureCommit + type SafetyFuturePrepare + type SafetyFuturePrepared type SafetyHistoryProjection type SafetyIdentity type SafetyPage @@ -2172,6 +2190,8 @@ export "./schemas" (./src/schemas.ts) MAX_PROMPT_CHARS MAX_SERVER_FRAME_BYTES type ParseFrameResult + TrustRuleSchema + TrustedSourcesSchema approvalDisplaySchema attachmentFileSchema attachmentLimitsSchema @@ -2281,11 +2301,19 @@ export "./schemas" (./src/schemas.ts) messageSourceSchema parseClientMessage parseServerMessage + parseTrustGithub + parseTrustOrigin + parseTrustTunnel queueAddRequestSchema queueAddResultSchema queuedFollowUpViewSchema resolutionEffectSchema safetyCapabilitiesSchema + safetyFutureCommitSchema + safetyFuturePrepareSchema + safetyFuturePreparedSchema + safetyFutureResultSchema + safetyFutureStatusSchema safetyPageSchema safetyProjectionSchema safetyReviewBodySchema @@ -3034,6 +3062,9 @@ export "./server" (./src/server/index.ts) SUBSCRIPTION_AUTH_INSTRUCTIONS SUBSCRIPTION_RELOGIN_PROCEDURE type SafetyCapabilities + type SafetyFutureCommit + type SafetyFuturePrepare + type SafetyFuturePrepared type SafetyHistoryProjection type SafetyIdentity type SafetyPage @@ -11955,10 +11986,10 @@ signatures (every public export and the types it is made of) reviewBodyBytes?: 16384 | undefined; reviewLifetimeMs?: 900000 | undefined; }; - originRules: false; + originRules: boolean; read: true; readOnlyReason: "owner_required" | "review_unavailable" | null; - recipientRules: false; + recipientRules: boolean; repositoryRules: false; review: boolean; version: 1; @@ -13443,6 +13474,12 @@ signatures (every public export and the types it is made of) const SUBSCRIPTION_RELOGIN_PROCEDURE: string; SafetyCapabilities (packages/ui-sdk/src/safety.ts) export type SafetyCapabilities = z.infer; + SafetyFutureCommit (packages/ui-sdk/src/safety.ts) + export type SafetyFutureCommit = z.infer; + SafetyFuturePrepare (packages/ui-sdk/src/safety.ts) + export type SafetyFuturePrepare = z.infer; + SafetyFuturePrepared (packages/ui-sdk/src/safety.ts) + export type SafetyFuturePrepared = z.infer; SafetyHistoryProjection (packages/ui-sdk/src/safety.ts) export type SafetyHistoryProjection = z.infer; SafetyIdentity (packages/ui-sdk/src/safety.ts) @@ -14939,6 +14976,68 @@ signatures (every public export and the types it is made of) } TranscriptionFailureReason (packages/ui-sdk/src/protocol.ts) export type TranscriptionFailureReason = "provider_error" | "rate_limit" | "provider_timeout" | "media" | "parameters" | "validation" | "authentication" | "outcome_unknown"; + TrustRuleSchema (packages/common/src/taint-trust.ts) + const TrustRuleSchema: z.ZodObject<{ + id: z.ZodString; + incomingContent: z.ZodDefault; + label: z.ZodString; + recipientWhileRestricted: z.ZodDefault; + selector: z.ZodDiscriminatedUnion<[z.ZodObject<{ + host: z.ZodString; + kind: z.ZodLiteral<"web_origin">; + port: z.ZodNumber; + scheme: z.ZodEnum<{ + http: "http"; + https: "https"; + }>; + }, z.core.$strict>, z.ZodObject<{ + host: z.ZodString; + kind: z.ZodLiteral<"tunnel_authority">; + port: z.ZodNumber; + }, z.core.$strict>, z.ZodObject<{ + host: z.ZodLiteral<"github.com">; + kind: z.ZodLiteral<"github_repository">; + owner: z.ZodString; + repository: z.ZodString; + repositoryId: z.ZodString; + }, z.core.$strict>, z.ZodObject<{ + host: z.ZodLiteral<"github.com">; + kind: z.ZodLiteral<"github_owner">; + owner: z.ZodString; + ownerId: z.ZodString; + }, z.core.$strict>], "kind">; + }, z.core.$strict>; + TrustedSourcesSchema (packages/common/src/taint-trust.ts) + const TrustedSourcesSchema: z.ZodArray; + label: z.ZodString; + recipientWhileRestricted: z.ZodDefault; + selector: z.ZodDiscriminatedUnion<[z.ZodObject<{ + host: z.ZodString; + kind: z.ZodLiteral<"web_origin">; + port: z.ZodNumber; + scheme: z.ZodEnum<{ + http: "http"; + https: "https"; + }>; + }, z.core.$strict>, z.ZodObject<{ + host: z.ZodString; + kind: z.ZodLiteral<"tunnel_authority">; + port: z.ZodNumber; + }, z.core.$strict>, z.ZodObject<{ + host: z.ZodLiteral<"github.com">; + kind: z.ZodLiteral<"github_repository">; + owner: z.ZodString; + repository: z.ZodString; + repositoryId: z.ZodString; + }, z.core.$strict>, z.ZodObject<{ + host: z.ZodLiteral<"github.com">; + kind: z.ZodLiteral<"github_owner">; + owner: z.ZodString; + ownerId: z.ZodString; + }, z.core.$strict>], "kind">; + }, z.core.$strict>>; TurnBudgetCoverage (packages/ui-sdk/src/turn-budgets.ts) export type TurnBudgetCoverage = "Built-in inference, relayed brain CLI providers and Apify runs this host admitted; other provider and tool spend is not metered" | "Built-in inference and relayed brain CLI providers; Apify accounting is unavailable, so Apify spend is not counted; other provider and tool spend is not metered" | "Built-in inference and relayed brain CLI providers; other provider and tool spend is not metered" | "Built-in inference only; provider and tool spend is not metered"; TurnBudgetReceipt (packages/ui-sdk/src/turn-budgets.ts) @@ -15310,6 +15409,7 @@ signatures (every public export and the types it is made of) export interface WebModelEgress { dir: string; inference(method: string, target: URL, signal: AbortSignal): unknown; + remainingBytes?(): number; } WebModelGrant (packages/ui-sdk/src/tool-contracts/web.ts) export interface WebModelGrant { @@ -16275,6 +16375,7 @@ signatures (every public export and the types it is made of) }>; }, z.core.$strict>, z.ZodObject<{ cursor: z.ZodOptional>; + includeAdmissions: z.ZodOptional>; includeEntries: z.ZodOptional>; limit: z.ZodOptional; requestId: z.ZodString; @@ -16441,6 +16542,7 @@ signatures (every public export and the types it is made of) clientSafetyReadSchema (packages/ui-sdk/src/safety.ts) const clientSafetyReadSchema: z.ZodObject<{ cursor: z.ZodOptional>; + includeAdmissions: z.ZodOptional>; includeEntries: z.ZodOptional>; limit: z.ZodOptional; requestId: z.ZodString; @@ -21078,6 +21180,16 @@ signatures (every public export and the types it is made of) export function parseSubprocessEnvExtra(value: string | undefined): string[]; parseToolPayload (packages/ui-sdk/src/tool-contracts/contract.ts) export function parseToolPayload(contract: Contract, output: string | undefined): ToolPayload | null; + parseTrustGithub (packages/common/src/taint-trust.ts) + export function parseTrustGithub(input: string): { + host: "github.com"; + owner: string; + repository?: string; + }; + parseTrustOrigin (packages/common/src/taint-trust.ts) + export function parseTrustOrigin(input: string): z.output; + parseTrustTunnel (packages/common/src/taint-trust.ts) + export function parseTrustTunnel(input: string): z.output; parseWebToolInput (packages/ui-sdk/src/tool-contracts/web.ts) export function parseWebToolInput(name: WebToolName, input: unknown): WebToolParse; planPlaces (packages/ui-sdk/src/places.ts) @@ -21226,17 +21338,307 @@ signatures (every public export and the types it is made of) reviewBodyBytes: z.ZodOptional>; reviewLifetimeMs: z.ZodOptional>; }, z.core.$strict>; - originRules: z.ZodLiteral; + originRules: z.ZodBoolean; read: z.ZodLiteral; readOnlyReason: z.ZodNullable>; - recipientRules: z.ZodLiteral; + recipientRules: z.ZodBoolean; repositoryRules: z.ZodLiteral; review: z.ZodBoolean; version: z.ZodLiteral<1>; }, z.core.$strict>; + safetyFutureCommitSchema (packages/ui-sdk/src/safety.ts) + const safetyFutureCommitSchema: z.ZodObject<{ + requestId: z.ZodString; + reviewId: z.ZodString; + reviewedBytesHash: z.ZodString; + version: z.ZodLiteral<1>; + }, z.core.$strict>; + safetyFuturePrepareSchema (packages/ui-sdk/src/safety.ts) + const safetyFuturePrepareSchema: z.ZodObject<{ + expectedEvidenceRevision: z.ZodString; + future: z.ZodObject<{ + incomingContent: z.ZodLiteral; + recipientWhileRestricted: z.ZodBoolean; + }, z.core.$strict>; + occurrenceId: z.ZodString; + session: z.ZodObject<{ + historyGeneration: z.ZodString; + historyOwnerId: z.ZodString; + sessionId: z.ZodString; + }, z.core.$strict>; + verdict: z.ZodLiteral<"safe">; + version: z.ZodLiteral<1>; + }, z.core.$strict>; + safetyFuturePreparedSchema (packages/ui-sdk/src/safety.ts) + const safetyFuturePreparedSchema: z.ZodObject<{ + currentProjection: z.ZodNullable; + epochs: z.ZodArray; + backendId: z.ZodString; + endSequence: z.ZodNullable; + id: z.ZodString; + mandatory: z.ZodArray; + reason: z.ZodNullable; + startSequence: z.ZodString; + status: z.ZodEnum<{ + complete: "complete"; + incomplete: "incomplete"; + unknown: "unknown"; + }>; + }, z.core.$strict>>; + exclusions: z.ZodArray; + state: z.ZodEnum<{ + complete: "complete"; + incomplete: "incomplete"; + unknown: "unknown"; + }>; + }, z.core.$strict>; + earliestUnresolvedId: z.ZodNullable; + evidenceRevision: z.ZodString; + pendingCount: z.ZodNumber; + reasons: z.ZodArray>; + restriction: z.ZodEnum<{ + normal: "normal"; + restricted: "restricted"; + }>; + session: z.ZodNullable>; + unresolvedCount: z.ZodNumber; + }, z.core.$strict>>; + occurrenceId: z.ZodString; + requestId: z.ZodString; + review: z.ZodObject<{ + base: z.ZodNullable; + diff: z.ZodString; + expiresAt: z.ZodNumber; + includesFutureRepositories: z.ZodBoolean; + proposed: z.ZodString; + repositoryIdentity: z.ZodNull; + reviewId: z.ZodString; + reviewedBytesHash: z.ZodString; + }, z.core.$strict>; + rule: z.ZodObject<{ + currentRule: z.ZodEnum<{ + changed: "changed"; + present: "present"; + removed: "removed"; + unknown: "unknown"; + }>; + enforcement: z.ZodEnum<{ + enforced: "enforced"; + unavailable: "unavailable"; + }>; + operationId: z.ZodString; + publication: z.ZodEnum<{ + not_published: "not_published"; + proved: "proved"; + unknown: "unknown"; + }>; + publishedTrustRevision: z.ZodNullable; + reason: z.ZodNullable; + requestId: z.ZodString; + ruleId: z.ZodString; + stage: z.ZodEnum<{ + committed: "committed"; + file_published: "file_published"; + partial: "partial"; + prepared: "prepared"; + refused: "refused"; + unknown: "unknown"; + }>; + version: z.ZodLiteral<1>; + }, z.core.$strict>; + session: z.ZodObject<{ + historyGeneration: z.ZodString; + historyOwnerId: z.ZodString; + sessionId: z.ZodString; + }, z.core.$strict>; + version: z.ZodLiteral<1>; + }, z.core.$strict>; + safetyFutureResultSchema (packages/ui-sdk/src/safety.ts) + const safetyFutureResultSchema: z.ZodObject<{ + currentProjection: z.ZodObject<{ + coverage: z.ZodObject<{ + detectorVersion: z.ZodLiteral<1>; + epochs: z.ZodArray; + backendId: z.ZodString; + endSequence: z.ZodNullable; + id: z.ZodString; + mandatory: z.ZodArray; + reason: z.ZodNullable; + startSequence: z.ZodString; + status: z.ZodEnum<{ + complete: "complete"; + incomplete: "incomplete"; + unknown: "unknown"; + }>; + }, z.core.$strict>>; + exclusions: z.ZodArray; + state: z.ZodEnum<{ + complete: "complete"; + incomplete: "incomplete"; + unknown: "unknown"; + }>; + }, z.core.$strict>; + earliestUnresolvedId: z.ZodNullable; + evidenceRevision: z.ZodString; + pendingCount: z.ZodNumber; + reasons: z.ZodArray>; + restriction: z.ZodEnum<{ + normal: "normal"; + restricted: "restricted"; + }>; + session: z.ZodNullable>; + unresolvedCount: z.ZodNumber; + }, z.core.$strict>; + occurrenceId: z.ZodString; + requestId: z.ZodString; + rule: z.ZodObject<{ + currentRule: z.ZodEnum<{ + changed: "changed"; + present: "present"; + removed: "removed"; + unknown: "unknown"; + }>; + enforcement: z.ZodEnum<{ + enforced: "enforced"; + unavailable: "unavailable"; + }>; + operationId: z.ZodString; + publication: z.ZodEnum<{ + not_published: "not_published"; + proved: "proved"; + unknown: "unknown"; + }>; + publishedTrustRevision: z.ZodNullable; + reason: z.ZodNullable; + requestId: z.ZodString; + ruleId: z.ZodString; + stage: z.ZodEnum<{ + committed: "committed"; + file_published: "file_published"; + partial: "partial"; + prepared: "prepared"; + refused: "refused"; + unknown: "unknown"; + }>; + version: z.ZodLiteral<1>; + }, z.core.$strict>; + session: z.ZodObject<{ + historyGeneration: z.ZodString; + historyOwnerId: z.ZodString; + sessionId: z.ZodString; + }, z.core.$strict>; + stage: z.ZodEnum<{ + partial: "partial"; + prepared: "prepared"; + refused: "refused"; + unknown: "unknown"; + verdict_committed: "verdict_committed"; + }>; + verdict: z.ZodNullable; + projection: z.ZodNullable; + epochs: z.ZodArray; + backendId: z.ZodString; + endSequence: z.ZodNullable; + id: z.ZodString; + mandatory: z.ZodArray; + reason: z.ZodNullable; + startSequence: z.ZodString; + status: z.ZodEnum<{ + complete: "complete"; + incomplete: "incomplete"; + unknown: "unknown"; + }>; + }, z.core.$strict>>; + exclusions: z.ZodArray; + state: z.ZodEnum<{ + complete: "complete"; + incomplete: "incomplete"; + unknown: "unknown"; + }>; + }, z.core.$strict>; + earliestUnresolvedId: z.ZodNullable; + evidenceRevision: z.ZodString; + pendingCount: z.ZodNumber; + reasons: z.ZodArray>; + restriction: z.ZodEnum<{ + normal: "normal"; + restricted: "restricted"; + }>; + session: z.ZodNullable>; + unresolvedCount: z.ZodNumber; + }, z.core.$strict>>; + reason: z.ZodNullable; + requestId: z.ZodNullable; + session: z.ZodObject<{ + historyGeneration: z.ZodString; + historyOwnerId: z.ZodString; + sessionId: z.ZodString; + }, z.core.$strict>; + stage: z.ZodEnum<{ + prepared: "prepared"; + refused: "refused"; + verdict_committed: "verdict_committed"; + }>; + verdict: z.ZodEnum<{ + committed: "committed"; + unresolved: "unresolved"; + }>; + version: z.ZodLiteral<1>; + }, z.core.$strict>>; + version: z.ZodLiteral<1>; + }, z.core.$strict>; + safetyFutureStatusSchema (packages/ui-sdk/src/safety.ts) + const safetyFutureStatusSchema: z.ZodObject<{ + occurrenceId: z.ZodString; + session: z.ZodObject<{ + historyGeneration: z.ZodString; + historyOwnerId: z.ZodString; + sessionId: z.ZodString; + }, z.core.$strict>; + version: z.ZodLiteral<1>; + }, z.core.$strict>; safetyIdentitySchema (packages/ui-sdk/src/safety.ts) const safetyIdentitySchema: z.ZodUnion; records: z.ZodArray; + trustRevision: z.ZodString; + trusted: z.ZodLiteral; + }, z.core.$strict>, z.ZodObject<{ + collectionRevision: z.ZodString; + policyHash: z.ZodString; + ruleId: z.ZodString; + trustRevision: z.ZodString; + trusted: z.ZodLiteral; + }, z.core.$strict>], "trusted">>; bindingId: z.ZodString; detailPruned: z.ZodBoolean; detector: z.ZodNullable; @@ -21452,6 +21865,17 @@ signatures (every public export and the types it is made of) }, z.core.$strict>; safetyRecordSchema (packages/ui-sdk/src/safety.ts) const safetyRecordSchema: z.ZodDiscriminatedUnion<[z.ZodObject<{ + admission: z.ZodOptional; + trustRevision: z.ZodString; + trusted: z.ZodLiteral; + }, z.core.$strict>, z.ZodObject<{ + collectionRevision: z.ZodString; + policyHash: z.ZodString; + ruleId: z.ZodString; + trustRevision: z.ZodString; + trusted: z.ZodLiteral; + }, z.core.$strict>], "trusted">>; bindingId: z.ZodString; detailPruned: z.ZodBoolean; detector: z.ZodNullable; @@ -21949,6 +22373,17 @@ signatures (every public export and the types it is made of) unresolvedCount: z.ZodNumber; }, z.core.$strict>; records: z.ZodArray; + trustRevision: z.ZodString; + trusted: z.ZodLiteral; + }, z.core.$strict>, z.ZodObject<{ + collectionRevision: z.ZodString; + policyHash: z.ZodString; + ruleId: z.ZodString; + trustRevision: z.ZodString; + trusted: z.ZodLiteral; + }, z.core.$strict>], "trusted">>; bindingId: z.ZodString; detailPruned: z.ZodBoolean; detector: z.ZodNullable; @@ -23136,13 +23571,13 @@ signatures (every public export and the types it is made of) reviewBodyBytes: z.ZodOptional>; reviewLifetimeMs: z.ZodOptional>; }, z.core.$strict>; - originRules: z.ZodLiteral; + originRules: z.ZodBoolean; read: z.ZodLiteral; readOnlyReason: z.ZodNullable>; - recipientRules: z.ZodLiteral; + recipientRules: z.ZodBoolean; repositoryRules: z.ZodLiteral; review: z.ZodBoolean; version: z.ZodLiteral<1>; @@ -24096,13 +24531,13 @@ signatures (every public export and the types it is made of) reviewBodyBytes: z.ZodOptional>; reviewLifetimeMs: z.ZodOptional>; }, z.core.$strict>; - originRules: z.ZodLiteral; + originRules: z.ZodBoolean; read: z.ZodLiteral; readOnlyReason: z.ZodNullable>; - recipientRules: z.ZodLiteral; + recipientRules: z.ZodBoolean; repositoryRules: z.ZodLiteral; review: z.ZodBoolean; version: z.ZodLiteral<1>; @@ -26860,6 +27295,17 @@ signatures (every public export and the types it is made of) unresolvedCount: z.ZodNumber; }, z.core.$strict>; records: z.ZodArray; + trustRevision: z.ZodString; + trusted: z.ZodLiteral; + }, z.core.$strict>, z.ZodObject<{ + collectionRevision: z.ZodString; + policyHash: z.ZodString; + ruleId: z.ZodString; + trustRevision: z.ZodString; + trusted: z.ZodLiteral; + }, z.core.$strict>], "trusted">>; bindingId: z.ZodString; detailPruned: z.ZodBoolean; detector: z.ZodNullable; @@ -27018,6 +27464,17 @@ signatures (every public export and the types it is made of) unresolvedCount: z.ZodNumber; }, z.core.$strict>; records: z.ZodArray; + trustRevision: z.ZodString; + trusted: z.ZodLiteral; + }, z.core.$strict>, z.ZodObject<{ + collectionRevision: z.ZodString; + policyHash: z.ZodString; + ruleId: z.ZodString; + trustRevision: z.ZodString; + trusted: z.ZodLiteral; + }, z.core.$strict>], "trusted">>; bindingId: z.ZodString; detailPruned: z.ZodBoolean; detector: z.ZodNullable; @@ -27697,6 +28154,17 @@ signatures (every public export and the types it is made of) unresolvedCount: z.ZodNumber; }, z.core.$strict>; records: z.ZodArray; + trustRevision: z.ZodString; + trusted: z.ZodLiteral; + }, z.core.$strict>, z.ZodObject<{ + collectionRevision: z.ZodString; + policyHash: z.ZodString; + ruleId: z.ZodString; + trustRevision: z.ZodString; + trusted: z.ZodLiteral; + }, z.core.$strict>], "trusted">>; bindingId: z.ZodString; detailPruned: z.ZodBoolean; detector: z.ZodNullable; @@ -27871,6 +28339,17 @@ signatures (every public export and the types it is made of) unresolvedCount: z.ZodNumber; }, z.core.$strict>; records: z.ZodArray; + trustRevision: z.ZodString; + trusted: z.ZodLiteral; + }, z.core.$strict>, z.ZodObject<{ + collectionRevision: z.ZodString; + policyHash: z.ZodString; + ruleId: z.ZodString; + trustRevision: z.ZodString; + trusted: z.ZodLiteral; + }, z.core.$strict>], "trusted">>; bindingId: z.ZodString; detailPruned: z.ZodBoolean; detector: z.ZodNullable; @@ -29072,6 +29551,12 @@ signatures (every public export and the types it is made of) export function toolBriefLines(contracts: readonly ToolContract[], available: (contract: ToolContract) => string | false | undefined): string[]; toolInputJsonSchema (packages/ui-sdk/src/tool-contracts/contract.ts) export function toolInputJsonSchema(contract: ToolContract | z.ZodObject): Record; + tunnel (packages/common/src/taint-trust.ts) + const tunnel: z.ZodObject<{ + host: z.ZodString; + kind: z.ZodLiteral<"tunnel_authority">; + port: z.ZodNumber; + }, z.core.$strict>; turnBudgetReceiptSchema (packages/ui-sdk/src/schemas.ts) const turnBudgetReceiptSchema: z.ZodObject<{ coverage: z.ZodEnum<{ @@ -29377,6 +29862,16 @@ signatures (every public export and the types it is made of) }, z.core.$strip>; revision: z.ZodNumber; }, z.core.$loose>; + web (packages/common/src/taint-trust.ts) + const web: z.ZodObject<{ + host: z.ZodString; + kind: z.ZodLiteral<"web_origin">; + port: z.ZodNumber; + scheme: z.ZodEnum<{ + http: "http"; + https: "https"; + }>; + }, z.core.$strict>; webToolProviders (packages/ui-sdk/src/tool-contracts/web.ts) export function webToolProviders(input: Record): readonly string[]; wrapCommand (packages/ui-sdk/src/server/exec-wrapper.ts) diff --git a/api-report/ui-server.txt b/api-report/ui-server.txt index 94c76ae996..ed4cfda466 100644 --- a/api-report/ui-server.txt +++ b/api-report/ui-server.txt @@ -684,7 +684,15 @@ signatures (every public export and the types it is made of) }>; bytes: z.ZodNumber; connectionId: z.ZodOptional; + dispatched: z.ZodOptional; durationMs: z.ZodNumber; + failureReason: z.ZodOptional>; host: z.ZodString; inference: z.ZodOptional>; managedReference: z.ZodOptional>; @@ -699,6 +707,16 @@ signatures (every public export and the types it is made of) port: z.ZodNumber; provider: z.ZodOptional>; reason: z.ZodOptional; + recipientAdmission: z.ZodOptional; + policyHash: z.ZodString; + ruleId: z.ZodString; + trustRevision: z.ZodString; + }, z.core.$strict>>; + recipientApproved: z.ZodOptional>; + standingRecipient: z.ZodOptional>; + trustedSource: z.ZodOptional>; }, z.core.$strict>; version: number; }; @@ -1079,11 +1097,17 @@ signatures (every public export and the types it is made of) payload: z.ZodObject<{ detail: z.ZodNullable; occurrence: z.ZodOptional; - trustRevision: z.ZodLiteral<"0">; + trustRevision: z.ZodString; trusted: z.ZodLiteral; - }, z.core.$strict>>; + }, z.core.$strict>, z.ZodObject<{ + collectionRevision: z.ZodString; + policyHash: z.ZodString; + ruleId: z.ZodString; + trustRevision: z.ZodString; + trusted: z.ZodLiteral; + }, z.core.$strict>], "trusted">>; detector: z.ZodEnum<{ attachment_input: "attachment_input"; compute_input: "compute_input"; diff --git a/docs/decisions/async-collaboration.md b/docs/decisions/async-collaboration.md index 45a7b4e456..2f43d7bbb3 100644 --- a/docs/decisions/async-collaboration.md +++ b/docs/decisions/async-collaboration.md @@ -306,7 +306,7 @@ costs or a provider-enforced spend ceiling. Narrower per-request relay accounting is not selected for v1. The current observer reports method, path, outcome and status, with no trusted token or cost bound (`InferenceRelayEvent`, -`packages/ui-sdk/src/server/inference-relay.ts:47-55`). Completed-response +`packages/ui-sdk/src/server/inference-relay.ts:55-63`). Completed-response snapshots cannot bound a pre-header continuation's input, output, cache usage or hidden requests. A smaller fraction, historical average, guessed zero or clipping below known spend would invent evidence. Revisit narrower accounting diff --git a/docs/decisions/governed-writable-workers.md b/docs/decisions/governed-writable-workers.md index a32d00a47e..4cfbecbedb 100644 --- a/docs/decisions/governed-writable-workers.md +++ b/docs/decisions/governed-writable-workers.md @@ -707,7 +707,7 @@ the key and forwards it as the turn's own egress (G5). A key goes only to its built-in first-party origin, or to an exact origin the operator lists for that key in `BRAIN_UI_CLI_PROVIDER_ORIGINS`, under the 2026-10-23 ruling on #1673; the backends' origin rulings grant the CLI nothing by analogy -(`startProviderRelay`, `packages/ui-sdk/src/server/provider-relay.ts:329-334`). +(`startProviderRelay`, `packages/ui-sdk/src/server/provider-relay.ts:336-341`). The inference relay's placeholder is not a key: the launcher names a key that holds it as withheld, so a relayed Claude API-key turn's `anthropic-haiku` reaches the host's key instead of failing authentication. The `jev` reranker @@ -2540,7 +2540,7 @@ so nothing in them can be recorded or limited. **The design.** A `governed` or `strict` worker gets `--unshare-net` and a server-owned egress proxy, bind-mounted as a Unix socket in the same way as the inference relay. The relay's `observe` hook already exists but is not -connected (`observe?(event`, `packages/ui-sdk/src/server/inference-relay.ts:38`). +connected (`observe?(event`, `packages/ui-sdk/src/server/inference-relay.ts:46`). Inside the worker, a small loopback listener forwards to the socket, and `HTTPS_PROXY`, `HTTP_PROXY` and `ALL_PROXY` point at it. @@ -2601,7 +2601,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:86-216`). The note says egress is +`packages/ui-server/src/brain/turn-egress.ts:94-389`). 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 @@ -3623,7 +3623,7 @@ recipient only when it can record what the turn is shown (`const recipient = opt view is not on managed native storage, where the relay runs, is refused before this (#3314). The turn's relay is then held to that origin: it refuses to start toward any other -(`if (options.recipientOrigin`, `packages/ui-sdk/src/server/inference-relay.ts:81-83`), +(`if (options.recipientOrigin`, `packages/ui-sdk/src/server/inference-relay.ts:89-91`), pi refuses a changed endpoint before its credential is read, and a turn that has a recipient but no relay refuses to start. A model change inside a turn cannot leave the one relay socket the worker has. @@ -3753,7 +3753,7 @@ group, with setgid directories. Setgid sets only the group, though, and the kit creates its per-turn objects with private modes today. Runtime state (`export function createClaudeWorkerState`, `packages/ui-backend-claude/src/worker-state.ts:136`) and the inference relay -(`export function startInferenceRelay`, `packages/ui-sdk/src/server/inference-relay.ts:73`) +(`export function startInferenceRelay`, `packages/ui-sdk/src/server/inference-relay.ts:81`) both use `0700` directories and `0600` files or sockets. With a helper configured, the kit therefore creates these with explicit group ownership and group modes: @@ -4217,7 +4217,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:62-84`). +(`createOutwardCalls`, `packages/ui-server/src/brain/turn-egress.ts:67-89`). A background process left by an earlier call can still connect inside such a window; the proxy records it either way. @@ -4231,7 +4231,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:22-25`). +(`MAIL_SUBMISSION_PORTS`, `packages/ui-server/src/brain/turn-egress.ts:25-28`). 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. @@ -4261,7 +4261,7 @@ and a documented "no GitHub here" were both rejected. The rest of the ruling: approves a write, and autonomous turns have no write surface. - **The Network card stays.** An unclassified connection to an outward GitHub host keeps its `Network` approval card (`approveOutward`, - `packages/ui-server/src/brain/turn-egress.ts:256-263`); it is not refused + `packages/ui-server/src/brain/turn-egress.ts:386-393`); it is not refused outright. The hosted report behind #3791 was a compound shell command that ended in `curl` to `api.github.com`. The classifier reads such a command as opaque, so no visible-read exception covers it. Its `CONNECT` was held for @@ -4394,7 +4394,7 @@ rules (maintainer ruling, 2026-10-22). Historically the first source was the session's one `taint` event; the collection supersession above now records every signal. A write that fails stops the turn rather than leaving its outward rules loose. Binding, duplicate checks and the write share a SQLite transaction -(`recordFirstTaint`, `packages/ui-server/src/governance/session-taint.ts:21-27`). +(`recordFirstTaint`, `packages/ui-server/src/governance/session-taint.ts:22-28`). The hosted server runs that transaction on its write worker (`insertGovernanceEvent`, `packages/ui-server/src/governance/events.ts:376`; [#2850](https://github.com/schlessera/brain-kit/issues/2850)). A taint counts @@ -4421,7 +4421,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:86-242`). Hosts without managed +`packages/ui-server/src/brain/turn-egress.ts:94-389`). Hosts without managed native storage have no proxy, so the Bash classifier remains their shell rule and nothing narrows their egress. @@ -4466,18 +4466,18 @@ 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:198-203`). The +(`const narrowing`, `packages/ui-sdk/src/server/egress-proxy.ts:390-395`). 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:41-46`). +(`taintedDestinationDescription`, `packages/ui-server/src/brain/turn-egress.ts:46-51`). 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:172-183`). +(`const approveTainted`, `packages/ui-server/src/brain/turn-egress.ts:273-284`). 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 +`packages/ui-sdk/src/server/egress-proxy.ts:205-221`). 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 @@ -4561,14 +4561,14 @@ with a status text and a body that name it: the deny list, `allowlist` mode, 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:207`). The status +`packages/ui-sdk/src/server/egress-proxy.ts:205-221`; the source wording, +`cause: () =>`, `packages/ui-server/src/brain/turn-egress.ts:320`). 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 `error.reason`, using the `egress_denial` reason words plus `outward_not_approved` (`const refuse`, -`packages/ui-sdk/src/server/provider-relay.ts:392-397`). The OpenAI image +`packages/ui-sdk/src/server/provider-relay.ts:399-404`). The OpenAI image provider no longer appends its account hint to a relay refusal (`const relayRefusal`, `packages/module-images/src/providers/openai.ts:258-259`). A cancelled connection keeps its bare 403. The system prompt's turn-lifecycle @@ -4663,11 +4663,11 @@ authorization, the byte ceilings, budget admission, cancellation and accounting. It keeps its own `egress_connection` record, which carries `provider: true` and never `inference: true`. The exemption belongs to the operation, never to a hostname. Only the relay's validated routes reach the proxy's provider -admission (`relayed`, `packages/ui-sdk/src/server/egress-proxy.ts:338`), and +admission (`relayed`, `packages/ui-sdk/src/server/egress-proxy.ts:618`), 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 +(`narrowed`, `packages/ui-sdk/src/server/egress-proxy.ts:389`). Turn egress records neither a taint nor a contacted host for the operation -(`admitted`, `packages/ui-server/src/brain/turn-egress.ts:216-221`). So in a +(`admitted`, `packages/ui-server/src/brain/turn-egress.ts:329-334`). So in a tainted session, the worker's own traffic stays narrowed away from the provider's host. @@ -4675,9 +4675,9 @@ A later turn rebuilds its contacted hosts from the session's earlier `egress_connection` records, and a provider record there would look like a worker's. So the maintainer added the optional `provider: true` tag, mirroring `inference: true`, on the record of every validated provider-relay operation -(`finish`, `packages/ui-sdk/src/server/egress-proxy.ts:159-166`). The rebuild +(`observe`, `packages/ui-sdk/src/server/egress-proxy.ts:318-324`). The rebuild excludes those records (`contactedHosts`, -`packages/ui-server/src/governance/session-taint.ts:34-40`), so a provider +`packages/ui-server/src/governance/session-taint.ts:35-48`), so a provider request never gives the worker's own `CONNECT` a contacted-host pass, in the same turn or a later one. Records written before the tag existed stay unmarked, so they can still count for a session that already has them. That is diff --git a/docs/decisions/proportionate-containment.md b/docs/decisions/proportionate-containment.md index 2e84820035..e343ef5a41 100644 --- a/docs/decisions/proportionate-containment.md +++ b/docs/decisions/proportionate-containment.md @@ -12,10 +12,10 @@ Ruled by the maintainer on 2026-11-09 (#3812). Tracked under #3813. A hosted instance refused every turn in every chat. One turn's safety-recording write had failed, and the guard reacted by setting one durable flag for the whole brain (`latchSafety`, -`packages/ui-server/src/governance/safety-store.ts:115-125`). From then on, turn +`packages/ui-server/src/governance/safety-store.ts:118-128`). From then on, turn admission threw for every chat, including new chats that had never seen untrusted input (`beginSafetyCollection`, -`packages/ui-server/src/governance/safety-store.ts:193-202`). The error that +`packages/ui-server/src/governance/safety-store.ts:196-205`). The error that set the flag was recorded as "capacity" while the store was at a fraction of a percent of its limits, and its real cause was never stored. The only way back was to stop the server and run `recoverSafetyRecording` from a script, a diff --git a/docs/decisions/reference-source-acquisition.md b/docs/decisions/reference-source-acquisition.md index 871fc437a9..93eba5f80c 100644 --- a/docs/decisions/reference-source-acquisition.md +++ b/docs/decisions/reference-source-acquisition.md @@ -191,7 +191,7 @@ reclamation is observed. The concrete access owner (`createGitHubReferenceAccess`, `packages/ui-server/src/brain/github-reference-access.ts:19-189`) uses the fixed transport (`createGitHubReferenceWire`, -`packages/ui-server/src/brain/github-reference-wire.ts:19-254`). +`packages/ui-server/src/brain/github-reference-wire.ts:20-257`). The host-only GitHub access service binds one canonical repository and short branch/tag to a bounded acquisition. Anonymous metadata precedes a private @@ -436,3 +436,48 @@ names together before recording. A changed or missing observation refuses that read; a fresh call can acquire again. Old receipts remain historical evidence, including across restart, and cannot establish current identity or source trust. Approved-owner rule evaluation remains independently required. + +## Approved-owner resolution for immutable reads + +The host read service resolves each actual transport observation against the +Settings' existing live-policy interpretation, its matching durable trust +projection and operation-bound approved-owner evidence. No independent policy +parser or live cache selects owner rules. The policy root's directory identity is +captured with a no-follow directory descriptor and qualified against the native +manager's filesystem ID and fixed live-brain subvolume UUID. The kernel Btrfs +identity is read from that already held descriptor, including across native +library startup waits; lexical replacement before qualification completes +withholds the result. Holding the directory descriptor prevents live inode +reuse, and each read still checks the named root against that descriptor's +identity. Publication records filesystem ID and subvolume UUID from this host +qualification. Ordinary restart requalifies the same native brain and preserves +approval; recreation at the same path, inode and policy bytes has a different +subvolume UUID and cannot inherit it. An unqualified host or legacy proof without +that native binding withholds qualification. Replaced roots, verification races, incoherent projection data +and missing/malformed publication proof produce unavailable qualification. Stable +invalid/unreadable policy retains Settings' last-valid rules and records its +honest error; they do not prevent an otherwise authorized untrusted read. + +Exact repository approval requires the freshly observed stable repository ID, +current canonical owner and the independently approved owner ID. A same-owner +repository rename can qualify only from that new transport observation. Transfer, +repository name reuse and owner namespace reassignment cannot borrow approval. +Owner rules deliberately include future repositories currently in that same +canonical namespace and stable owner ID. A validated policy permits at most one +matching repository and one matching owner rule. Other policy edits do not erase +a retained approval of the same selector, and bounded operation-receipt pruning +or approving-login deletion does not erase the durable owner evidence. It +is interpreted only against a freshly qualified native brain after restart. + +Resolution runs provisionally before recording and again inside the acquired +SQLite writer transaction against the host snapshot and current metadata +generation and durable projection. A generation change during the queue wait +withholds only this qualification; a later read uses a new live Settings +snapshot. The recorded operation ID, policy hash/revision, +approved owner, selector and publication operation/proof hash are historical +qualification evidence. They are separate from the original acquisition and the +prepared/observed/unknown delivery state. Removal affects later resolutions and +retains earlier read evidence. This is neither a trust-at-admission decision nor +a private-access, recipient, Git-write or mutable-content grant. Every read still +produces workspace input; standing-rule enforcement and review targets remain +separately qualified work. diff --git a/docs/decisions/session-principals.md b/docs/decisions/session-principals.md index b4c90f5548..697f8e3eee 100644 --- a/docs/decisions/session-principals.md +++ b/docs/decisions/session-principals.md @@ -110,7 +110,7 @@ Both reviewers verified every row below against the source. | Sockets | `ClientSet`, `ws/clients.ts:41` | `ClientSet` keyed on `ws.raw` — hono mints a fresh `WSContext` per callback | | Activity subscriptions | `activity/stream.ts:153` | a **separate** registry keyed on the wrapper, not `ws.raw` | | Rollups | `migrations/007_activity.sql`; `upsertRollup`, `activity/sql.ts:19-24` | `activity_run_rollups` survives span pruning and carries its own origin/session/job | -| Client logout | `logout: () =>`, `ui-react/src/lib/api-client.ts:724`; `Sign out everywhere`, `passkey-list.tsx:108-108` | "Sign out everywhere" POSTs `/auth/logout` with no arguments | +| Client logout | `logout: () =>`, `packages/ui-react/src/lib/api-client.ts:792-793`; `Sign out everywhere`, `passkey-list.tsx:108-108` | "Sign out everywhere" POSTs `/auth/logout` with no arguments | | Unauthorized in the UI | `res.status === 401`, `ui-react/src/hooks/use-vpn-status.ts:36` | reached by `/api/vpn-check` returning 401, not by a close code | Two findings that are true today, independent of this plan: diff --git a/docs/hosting/agent-workers.md b/docs/hosting/agent-workers.md index 23c804f1b1..2f615fbbf8 100644 --- a/docs/hosting/agent-workers.md +++ b/docs/hosting/agent-workers.md @@ -96,7 +96,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:132-138`). Without a helper they retain +`packages/ui-sdk/src/server/egress-proxy.ts:275-281`). 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 @@ -856,7 +856,7 @@ the host root, `/home`, `/etc`, `/run`, `/var`, `/tmp` or an ancestor of the brain. No host home, stored login or `/run` socket is visible. The worker's only route out is the server-owned inference relay -(`export function startInferenceRelay(`, `packages/ui-sdk/src/server/inference-relay.ts:73-261`). +(`export function startInferenceRelay(`, `packages/ui-sdk/src/server/inference-relay.ts:81-254`). It is a Unix socket in a private `0700` directory, bind-mounted read-only at `/run/brain-inference`. It forwards only `POST` to the provider's inference routes, such as `/v1/messages` and `/v1/messages/count_tokens` for Anthropic, @@ -1673,7 +1673,7 @@ wrappers do not borrow that exemption (`commandTaintSource`, `packages/ui-server/src/activity/command-taint.ts:2-27`). The first source is kept as a session `taint` governance event, using the same SQLite transaction for the existing-source check and write -(`recordFirstTaint`, `packages/ui-server/src/governance/session-taint.ts:21-27`). +(`recordFirstTaint`, `packages/ui-server/src/governance/session-taint.ts:22-28`). The recorder waits for a tool result and excludes known denied calls; failed calls can still return untrusted partial output. It records the source kind and tool name, without copying command text or content into the payload. If diff --git a/docs/hosting/paid-cli-provider-qualification.md b/docs/hosting/paid-cli-provider-qualification.md index abfd985d6b..2f2cbb9dc7 100644 --- a/docs/hosting/paid-cli-provider-qualification.md +++ b/docs/hosting/paid-cli-provider-qualification.md @@ -92,9 +92,9 @@ providers refused rather than treated as first-party evidence. The current inference relay already strips inbound credentials, selects its fixed origin/routes and invokes host credentials for each dispatch -(`startInferenceRelay`, `packages/ui-sdk/src/server/inference-relay.ts:73-261`). +(`startInferenceRelay`, `packages/ui-sdk/src/server/inference-relay.ts:81-254`). Its event has outcome/status, not provider usage -(`InferenceRelayEvent`, `packages/ui-sdk/src/server/inference-relay.ts:47-55`). +(`InferenceRelayEvent`, `packages/ui-sdk/src/server/inference-relay.ts:55-63`). For these CLI consumers, the host would supply a non-secret transport projection and keep real keys outside the worker. A fixture key reaching a loopback upstream is not proof of that credential-free projection. diff --git a/docs/http-api-coverage.md b/docs/http-api-coverage.md index 919cddbd3b..467445efd8 100644 --- a/docs/http-api-coverage.md +++ b/docs/http-api-coverage.md @@ -7,7 +7,7 @@ fake backends and injected transports keep the checks keyless. Each ordinary row runs the named `mounted supported handler: METHOD PATH` test in [http-supported-mounts.test.ts](../packages/ui-server/tests/http-supported-mounts.test.ts) -(`checkHandler`, `packages/ui-server/tests/http-supported-mounts.test.ts:191-210`). +(`checkHandler`, `packages/ui-server/tests/http-supported-mounts.test.ts:212-231`). The explicit [lifetime audit](../packages/ui-server/tests/helpers/http-mount-lifetimes.ts) permits a bounded group of immutable readers to share startup, with a new owner per case. Principal enumeration, activity ownership, CLI dispatch, caches, @@ -129,6 +129,9 @@ row's real mounting check. They do not establish mounting by themselves. | `GET /api/sessions/:id/safety` | `mounted supported handler: GET /api/sessions/:id/safety` | S | | `POST /api/sessions/:id/safety/reviews/prepare` | `mounted supported handler: POST /api/sessions/:id/safety/reviews/prepare` | SR | | `POST /api/sessions/:id/safety/reviews/:requestId/commit` | `mounted supported handler: POST /api/sessions/:id/safety/reviews/:requestId/commit` | SR | +| `POST /api/sessions/:id/safety/reviews/future/prepare` | `mounted supported handler: POST /api/sessions/:id/safety/reviews/future/prepare` | SR | +| `POST /api/sessions/:id/safety/reviews/future/commit` | `mounted supported handler: POST /api/sessions/:id/safety/reviews/future/commit` | SR | +| `POST /api/sessions/:id/safety/reviews/future/status` | `mounted supported handler: POST /api/sessions/:id/safety/reviews/future/status` | SR | | `GET /api/sessions/:id/attachment-reads` | `mounted supported handler: GET /api/sessions/:id/attachment-reads` | X | | `GET /api/sessions/:id/recovery` | `mounted supported handler: GET /api/sessions/:id/recovery` | S | | `POST /api/queue` | `mounted supported handler: POST /api/queue` | Q | diff --git a/docs/http-api.md b/docs/http-api.md index b538c1dca1..2324f13854 100644 --- a/docs/http-api.md +++ b/docs/http-api.md @@ -10,7 +10,7 @@ compatibility guarantee. Authentication requirements are a separate property. A public liveness probe can be supported; an authenticated settings route can be internal. -The inventory includes the additive Queue intake, poke, scheduled-task, session-draft, composer-file, session-recovery, attachment-read, interactive HTML preview, saved-audio transcription, human-started hygiene-review, governance-event, roadblock-report, reference-grant, Apify-state, Apify-policy, retained-journal/user-revert, untrusted-mark, chat-deletion, individual safety-review, safety-recording recovery, GitHub detail-page, live-persona and markup-upload, human trust Settings and sync policy-review routes (whose `/api/settings/voice` also carries the live-service default) mounted by `createApp`: 196 unique declared +The inventory includes the additive Queue intake, poke, scheduled-task, session-draft, composer-file, session-recovery, attachment-read, interactive HTML preview, saved-audio transcription, human-started hygiene-review, governance-event, roadblock-report, reference-grant, Apify-state, Apify-policy, retained-journal/user-revert, untrusted-mark, chat-deletion, individual and combined future-source safety-review, safety-recording recovery, GitHub detail-page, live-persona and markup-upload, human trust Settings and sync policy-review routes (whose `/api/settings/voice` also carries the live-service default) mounted by `createApp`: 199 unique declared method/path pairs, plus the conditional SPA fallback. It describes the current implementation, including limitations, rather than a proposed redesign. Unknown response fields must be tolerated. There is no HTTP API revision @@ -158,13 +158,16 @@ client code has a gap. Source owners are listed after the table. | GET | `/api/journal/configuration-coverage` | S | Read the brain's current untraced configuration-input set | Latest complete inventoried turn only; explicit `unknown`, never an empty list. | | GET | `/api/agent-policy` | I | Read shared admission policy and reported enforcing limits | Read-only Devices & agents facts; no editor or duplicate policy cache. | | GET | `/api/policy-proposals/:turnId/:requestId` | I | Read one principal-owned policy request receipt | Same-request reconciliation only; never writes or reactivates approval. | -| GET | `/api/trust-settings` | I | Read trust policy data and publication availability | Paired Security settings transport (#3608); live password-mode human owners only; runtime trust remains disabled. | +| GET | `/api/trust-settings` | I | Read trust policy data and publication availability | Paired Security settings transport; authenticated sanitized reads expose mutationAllowed, while only live password/passkey owners mutate; origin/tunnel enforcement is independent from unavailable repository enforcement. | | GET | `/api/trust-settings/:request` | I | Read one owner-bound trust publication receipt and review | Same-request reconciliation only; never republishes or resolves a taint trigger. | | POST | `/api/trust-settings/prepare` | I | Prepare one exact-base trust change | Paired Security settings transport; same-origin JSON and live owner authority; repository create/edit independently verifies host metadata. | -| POST | `/api/trust-settings/commit` | I | Publish the exact owner-reviewed trust change | Shared descriptor-bound publisher; bounded durable receipt; saved policy does not imply runtime enforcement. | +| POST | `/api/trust-settings/commit` | I | Publish the exact owner-reviewed trust change | Shared descriptor-bound publisher; bounded durable receipt; enforced origin/tunnel publication joins live admission fences, while repository publication remains unavailable. | | GET | `/api/sessions/:id/safety` | S | Read bounded revisioned host safety evidence | Authenticated principal of the history owner's account (#3952); immutable records, snapshot aggregate/high-water, scoped cursor, explicit coverage/unavailable, no mutation (#3604). | | POST | `/api/sessions/:id/safety/reviews/prepare` | S | Prepare review of one finalized safety occurrence | Live password-mode human owner, exact Origin and bounded JSON; host-issued body/brain/principal/generation-bound handle (#3603). | | POST | `/api/sessions/:id/safety/reviews/:requestId/commit` | S | Commit or read back one individual safe verdict | Live owner rechecked on the acquired FULL transaction and final response; immutable receipt plus fresh aggregate, no bulk clear or standing rule (#3603). | +| POST | `/api/sessions/:id/safety/reviews/future/prepare` | S | Prepare one selected verdict and optional future source rule | Live password-mode human owner, exact Origin and bounded JSON; host-attested origin/tunnel and exact evidence revision; no publication or verdict yet (#3611). | +| POST | `/api/sessions/:id/safety/reviews/future/commit` | S | Publish the reviewed rule then commit its original selected verdict | Same live owner/session authority; exact review ID and reviewed-bytes hash; durable publication proof precedes verdict; retries never republish (#3611). | +| POST | `/api/sessions/:id/safety/reviews/future/status` | S | Read retained combined completion and current rule presence | Same live owner, exact Origin and bounded JSON session/occurrence; read-only, redacted uncommitted verdict handles, JSON null for unretained receipts (#3611). | | GET | `/api/sessions/:id/github/:owner/:repo/:number/:part` | I | Page one part of a GitHub object a session's GitHub tool result returned | Chat GitHub components (#3796, #3795); owner account only, display data never provider context, no compatibility guarantee. | | GET | `/api/sessions/:id/github/avatars/:login` | I | Serve the avatar of a login in a session's GitHub results from this origin | Chat GitHub components (#3796, #3795); owner account only, magic-byte image check, bounded in-memory cache, every failure 404. | | GET | `/api/sessions/:id/attachment-reads` | S | Read a session's recorded attachment reads, outcome and scope only | Sent-row read states (#3589, #3155); preserve the session and message-reference filters, no text and no provider path. | @@ -229,7 +232,7 @@ Authentication factories live in [auth.ts](../packages/ui-server/src/middleware/ [passkeys.ts](../packages/ui-server/src/middleware/passkeys.ts) and [principals.ts](../packages/ui-server/src/middleware/principals.ts). [app.ts](../packages/ui-server/src/app.ts) owns prefixing and middleware order. -All 196 declared endpoints are mounted regardless of backend, renderer or +All 199 declared endpoints are mounted regardless of backend, renderer or speech-provider availability: unavailable capabilities return the responses below rather than removing their handlers. Only static serving is conditional. @@ -1928,7 +1931,7 @@ read by any authenticated principal. | Kind | Version | Fields | Meaning | | --- | --- | --- | --- | | `safety_admission_expired` | 1 | `toolUseId`, `evidenceRevision`, `trustRevision`, `authorityEpoch`, `reason` | A waiting or claimed safety-bound approval was withdrawn before dispatch. The server commits this terminal fact before settling the backend wait or publishing the coordinator's `expired` result. Revisions describe the card's original host snapshot; `reason` is `safety_changed`, `turn_ended` or `grant_storage_failed`. Storage failure stops the turn with an explicit failed terminal outcome, without claiming durable withdrawal. This grants no replay and changes no historical approval. | -| `egress_connection` | 1 | `connectionId` (optional), `host`, `port`, `method`, `path` (optional), `bytes`, `accounting`, `durationMs`, `outcome`, `inference` (optional), `provider` (optional, #3246), `managedReference` (optional, #3613), `reason` (optional) | A completed, denied, failed or cancelled proxy connection. HTTP has a path and conservative wire accounting; opaque CONNECT has no path or plaintext claim. Only the concrete inference relay sets `inference: true`, only a validated provider-relay operation sets `provider: true`, and only the fixed host GitHub acquisition wire sets `managedReference: true`. Each operation supplies its own exclusive tag. These host records grant no contacted-host authority to a tainted session's worker traffic. Managed acquisition retains ordinary recipient restrictions and claims no model-content delivery or repository trust. Headers, query strings and content are absent. | +| `egress_connection` | 1 | `connectionId` (optional), `dispatched` (optional), `failureReason` (optional), `recipientAdmission` (optional), `recipientApproved` (optional), `standingRecipient` (optional), `trustedSource` (optional), `host`, `port`, `method`, `path` (optional), `bytes`, `accounting`, `durationMs`, `outcome`, `inference` (optional), `provider` (optional, #3246), `managedReference` (optional, #3613), `reason` (optional) | A completed, denied, failed or cancelled proxy connection. HTTP has a path and conservative wire accounting; opaque CONNECT has no path or plaintext claim. Only the concrete inference relay sets `inference: true`, only a validated provider-relay operation sets `provider: true`, and only the fixed host GitHub acquisition wire sets `managedReference: true`. Each operation supplies its own exclusive tag. These host records grant no contacted-host authority to a tainted session's worker traffic. Managed acquisition retains ordinary recipient restrictions and claims no model-content delivery or repository trust. Headers, query strings and content are absent. | | `steering_change` | 1 | `path`, `sequence`, `beforeHash`, `afterHash`, `taintSourceEventId`, `overlappingTurnIds`, `tainted` (optional) | One observed steering change, attributed to its turn. Hashes identify retained regular-file versions or are `null`; the source is the current unresolved taint event or `null`. New observations may carry `tainted: true` for effective restriction, including unknown coverage without an attributable source. Historical rows retain their original attribution. Shared windows remain shared, not exclusive writer claims. | | `policy_change` | 1 | `requestId`, `baseHash`, `proposedHash`, `sections`, `outcome` | Explicit user-approved policy publication. Actor is `user`; outcome is `updated`; hashes identify the exact reviewed and written bytes. | | `scratch_overage` | 1 | `bytes`, `pinnedFiles`, `pinnedBytes`, `overageBytes` | Scratch remains above its cap after a prune that preserved retained links. Counts are remaining bytes and pinned files/bytes; `overageBytes` is the excess. A background pass has actor `server` and no session or turn; unbound retention applies. | @@ -2423,19 +2426,38 @@ separately. It is never part of public `/health`. The four `/api/trust-settings` operations are internal paired Security settings transport. Their exact review/receipt shapes and limits are described in the [publication contract](integration-contract/package-api.md#human-trust-settings-publication). -They require a live password-mode human owner; mutation additionally requires a -present exact same-origin Origin and bounded JSON. Principal, voice and channel +The list GET exposes sanitized policy facts to authenticated callers, with +`mutationAllowed` reporting live owner availability. Prepare, commit and +per-request receipt reads require a live password/passkey owner; mutation also +requires a present exact same-origin Origin and bounded JSON. Principal, voice and channel claims in a body supply no authority. Receipts are private, no-store, scoped to the served brain and requesting owner, and readback never repeats a write. Publication reuses the protected policy writer without an agent turn. Prepared state, reviewed bytes/base, publication proof and partial/unknown completion -survive restart. Saved origin/tunnel rules do not enable unbuilt trust admission; +survive restart. Saved rules alone do not establish runtime capability; repository create/edit independently verifies fixed-endpoint metadata at review and again inside the publication observation window. Browser IDs cannot self-verify; unknown or changed identity withholds the write. Approved owner boundaries derive from this operation's durable publication proof and are not inferred from matching policy bytes. Owner-scope review explicitly covers -future repositories currently in that namespace. Runtime trust remains disabled. +future repositories currently in that namespace. Repository runtime trust remains +unavailable; origin/tunnel capabilities are independently advertised. Removal/readback remain available for existing rules. Revision exhaustion refuses before protected publication. No historical trigger is resolved by these routes. + +### Combined selected-trigger and future-source review + +The three supported POST endpoints under +`/api/sessions/:id/safety/reviews/future/` use the individual review's live +password-mode owner, exact Origin, JSON and session-generation fences. +`prepare` binds one finalized host-attested origin or explicit tunnel to exact +reviewed policy bytes and the original single-verdict request. `commit` requires +the request ID, review ID and reviewed-bytes hash; publication proof precedes +any verdict. `status` is a read-only POST accepting version, session and +occurrence ID, not a GET endpoint. It returns retained operation completion, +separate live restriction and current rule presence, or JSON null after receipt +retention expires. Neither status nor retries republish a rule. Uncommitted +verdict handles are redacted. The complete envelopes, partial/unknown semantics, +legacy capability encoding and browser correlation requirements are specified in +the [combined-review wire contract](integration-contract/wire.md#combined-single-trigger-and-future-source-review-3611). diff --git a/docs/integration-contract/http.md b/docs/integration-contract/http.md index 8b145790bf..bf0e97b280 100644 --- a/docs/integration-contract/http.md +++ b/docs/integration-contract/http.md @@ -476,8 +476,7 @@ The version 1 governance taint payload optionally adds strict host occurrence metadata; the source enum adds `legacy_unknown`. Every input/output/path/mark signal is independent, including later signals from the same source. Exact host-key retries deduplicate; changed identity/payload retries refuse. Admission -records `trusted: false`, the admitted policy hash (or `null`) and trust revision -`"0"`. Runtime source trust remains disabled. Verified proxy provenance records +records the host admission decision. Unmatched input retains `trusted:false` and the policy hash (or `null`) and trust revision from the same live projection snapshot used for matching. Since #3609, verified exact-origin/tunnel matches retain `trusted:true`, `ruleId`, exact trust policy hash, `trustRevision` and `collectionRevision`; these immutable facts survive rule removal and detail pruning. The wire validator discriminates `trusted:true` (all evidence fields required, non-null hash) from `trusted:false` (no rule ID or collection revision); malformed trusted evidence is refused rather than shown as trusted. The existing v1 detector field continues accepting any valid ID; admission negotiation does not narrow it. Trusted admissions remain inspectable and do not contribute unresolved triggers. Unknown or independent signals stay restrictive. Verified proxy provenance records only the actual web origin or opaque tunnel authority; worker tool arguments never establish transport or repository provenance. The proxy's optional `connectionId` relates its admission and receipt, without guessing a tool call. @@ -695,9 +694,10 @@ stored events keep their recorded sources. 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 +`{ host, port, method, protocol, managedReference, target }` with `target` as +`host:port` (bracketed for IPv6), 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 +new card kind or 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 @@ -1326,3 +1326,129 @@ Authenticated `GET /api/status` adds `journalCleanup`: `retained` contains `retrying: true` at the time it was recorded. The historical cause survives recovery and restart; it does not assert a currently blocked turn. Current charges remain separate in `retained`. No field changes public `/health`. + + +### Prospective origin enforcement (breaking before 1.0, #3609) + +The composed host enables incoming-source and explicit restricted-recipient +rules for verified exact web origins and explicitly selected opaque tunnel +authorities. Repository enforcement stays unavailable pending its independent +read qualification. A CONNECT authority never asserts HTTPS or a Git path. +Redirects and concurrent traffic receive independent decisions; scheme, port +and subdomain cannot borrow another selector's permission. + +Standing recipient permission bypasses only the taint-network card. Source-only +trust grants no recipient permission after unrelated input restricts a chat. +Egress evidence retains `trustedSource` and/or `standingRecipient` markers; a standing recipient decision also records `recipientAdmission` with its rule ID, exact policy hash, trust revision and collection revision. A standing capability alone creates no legacy hostname grant. An explicit +Network card approval independently records `recipientApproved:true` and +retains its legacy session grant, including when source trust also matched. +Transport receipt hosts use lowercase DNS or canonical bare IP literals. +Deny/allowlists, byte ceilings, provider credentials and outward-action approval +remain independent. Removing a standing capability affects future admissions; +source streams revalidate their admitted incoming-content rule when trust changes. +They stop before later bytes if that same rule no longer matches; unrelated +recipient edits alone do not revoke that source decision. Historical admission +facts remain unchanged, and independent recipient/approval fences still apply. +Approval and recording waits recheck live authority and recipient permission at +final dispatch. No earlier trigger, verdict or provider message is rewritten. + + +Origin admission also fences a valid disk/projection mismatch while publication +is being durably projected. The other protected policy publisher joins the same +trust refresh before reporting its update; each qualified proxy turn refreshes +this slice before starting. Invalid policy retains last-valid rules and an +honest error. No ordinary admitted governance setting reloads live. + +Both taint-network and outward cards bind committed evidence, independent +pending/coverage state, trust and authority through later writes and connection +setup. Only the exact connection's own immutable occurrence may be excluded +from its marker; another signal never borrows that exclusion. Cancellation +destroys both tunnel sockets before a delayed connect callback can return 200. +Managed HTTPS reference traffic carries a host-only verified transport tag for +recipient matching and audit, independently of its opaque wire accounting; it +cannot borrow a raw CONNECT selector or grant source/private/write authority. + +Pending network cards coalesce only for the same destination and immutable live +approval context; later evidence cannot join an earlier card. Fork reconstruction +copies unresolved untrusted occurrences only, with identical admission handling +before and after detail pruning. CONNECT and relay rechecks revalidate every time +but notify the host's committed observer exactly once per operation. + +Mixed history groups count trusted admissions and human safe verdicts separately. +An unresolved group names an actually unresolved input for review; a trusted or +reviewed row cannot supply that label. Historical source trust is not relabelled +as a human decision, and a human verdict is not relabelled as source trust. + + +## Egress charge failures + +Egress charge refusals retain their cause. Before response headers, a changed +safety/authority decision reports 403 (including `safety_changed`), and unavailable +recording/admission reports 503 with `egress_unavailable`. These never claim a +network byte limit was exhausted. A byte ceiling retains its existing refusal. +A stream which already began terminates; its relay error and connection evidence +retain the corresponding safety, unavailable or budget classification. + + +Source trust revocation uses one path whether a publication notification or a +send fence or post-write admission check observes it first: connection evidence records `source_trust_changed` +and subsequent charge results classify it as safety, never turn cancellation +or unavailable recording. The turn and unrelated connections remain active. + +Active trusted inputs retain a durable source-rule instance (rule ID plus its +creation revision). Removing, disabling or retargeting that source retires the +instance even if another publisher restores the same ID before the next chunk. +Recipient-only edits preserve the source instance. Instance metadata stays out +of Settings responses and never grants trust independently of policy files. + +New egress records carry optional `dispatched` evidence. Charged preparation +with `dispatched:false` never grants contacted-host permission in later turns; +older records without the field retain their existing interpretation. Historical +contacted hosts use the same canonical comparison key as current destinations, +including legacy bracketed IPv6 literals. This operation's recording +unavailability is 503 `egress_unavailable`, including initial admission. +Another recorder's loss or an independent pending input is a safety change, +403 `safety_changed`. + +A shared Network card excludes every occurrence admitted under that exact +card from its approval-evidence marker, including completed peers, their +initial collection metadata, and their exact in-flight write reservation IDs. +The host tracks reservation ownership through occurrence IDs; both local +overlays and durable pending rows are excluded from only that group's pending +count, recording-pending reason and recording-availability send fence. Global +projection/history reads, failures and capacity are unchanged. Host-only read +arguments are additive and optional; callers that omit them retain the global +view. Independent inputs, cards, human decisions and +authority or trust changes still invalidate the pending approval. These host +exclusions never remove occurrences from safety history or effective taint. +Inference refusal wire messages retain their existing fixed text (including +`Inference network admission refused`); the specific cause stays in the host's +`denialReason`, preserving runtime classification and stored-history readers. + +Egress audit records add optional `failureReason` with the stored terminal +category: `budget`, `safety_changed`, `policy_denied`, `unavailable` or +`cancelled`. This category is captured before abort listeners run and is shared +by every caller; reading it never retries admission or recomputes a cause. +Outward approval markers include the active call-classification generation, +so a covering call ending or an opaque call starting withdraws its exemption +even across a durable occurrence write. + +Malformed proxy destination fields return HTTP 400 before recording input +evidence. They cannot poison a safety-history page or stop later valid +requests in the turn. Authority loss while settling a binding reports 403 +`safety_changed`; an aborted wait reports 499/cancelled. Only pending, failed +or missing session binding reports 503 `egress_unavailable`, on both initial +and repeated inference admission. A cancelled cleanup cannot +send its credentialed DELETE, and cancellation interrupts an in-flight DELETE. + +A credential resolver or upstream transport failure is a failed attempt, not +cancellation caused by the proxy closing its own signal. Before response +headers it reports 502; cancellation reports 499 and existing admission +refusals retain their typed cause. Provider receipts keep 0 when no upstream +HTTP status was observed, or the observed status for interrupted responses. + +`egress_connection.accounting: "http_wire_bound"` counts received headers before +hop-by-hop filtering. The Node proxy meters `rawHeaders`, its actual HTTP start +line and framing; Fetch relays meter all unfiltered header pairs exposed by +Fetch with a runtime framing allowance. The bound is not an exact TLS/wire-byte +measurement and does not reconstruct formatting that Fetch does not expose. diff --git a/docs/integration-contract/package-api.md b/docs/integration-contract/package-api.md index 308c1b6ce9..c32fecc4d6 100644 --- a/docs/integration-contract/package-api.md +++ b/docs/integration-contract/package-api.md @@ -77,7 +77,27 @@ The internal turn proxy has a first-party `managedReference(target, signal)` operation for fixed GitHub HTTPS acquisition and a `remainingBytes()` counter. It retains ordinary G6 recipient narrowing, final admission fences and byte accounting; it cannot grant a contacted-host allowance. No worker -header selects it. The internal entry also exports the existing +header selects it. Network approval destinations carry `protocol` and the +host-owned `managedReference` identity; pending approvals never coalesce a +managed HTTPS acquisition with an opaque CONNECT to the same authority. +CONNECT accepts explicit bracketed IPv6 authorities as well as canonical DNS +and IPv4 hosts. `canonicalEgressHost` supplies one lowercase DNS or canonical bare +IP comparison identity for host checks, cards and receipts. Resolution/dialing +preserves the requested URL hostname, including a DNS root dot; destination +policy resolves that exact hostname before pinning a checked IP. Settings selectors +retain URL brackets for IPv6; the trust matcher adapts that schema boundary. +Absent approvals never request an approval revision. Unchanged safety reads, +approval markers and taint/projection reads use local-write, external SQLite +change and pending/loss counters; changed evidence revalidates the scoped +marker, including the exact own-occurrence exception. +Every upstream write/end and tunnel chunk uses the same current authority, +recipient, source-trust, approval-freshness and byte-budget fence. +Live trust reads and durable refresh share one policy observation state machine. +Stable invalid or unreadable policy retains last-valid rules/hash with an error; +a changed-file or ancestry verification mismatch fences. Unchanged-file chunk +fences compare ancestry/file metadata generations without reading policy bytes +or querying SQLite. Refresh rechecks the generation after its durable write. +The internal entry also exports the existing `egressAddressRefusal` validator so the fixed acquisition wire validates every DNS address before connecting to a checked IP. These are implementation sharing, with no supported public transport extension seam (#3613). @@ -444,7 +464,7 @@ admitted model as its backend lends it on the host, and `handleWebTool` takes it as an optional fifth argument, `model`. `WebModelAccess` is `{ provider, model, open(egress, signal?) }`; `open` starts a host relay for exactly that model into a web executor's egress route (`WebModelEgress`: -`{ dir, inference }`) and resolves to `{ grant, stop() }`. `WebModelGrant` +`{ dir, inference, remainingBytes? }`) and resolves to `{ grant, stop() }`. `WebModelGrant` (`{ provider, model, credential: "api_key" | "oauth", basePath, socket }`) is everything the executor is told, and never holds a credential. A backend that does not set `model` behaves as before. @@ -5611,10 +5631,37 @@ capability, HTTP endpoint, history DTO or provider conversation changes here. ### Human trust Settings publication -The optional owner-only `/api/trust-settings` HTTP surface is a policy-publication +Security Settings now consumes the protected trust publication surface. The +list GET is available to authenticated callers and adds `mutationAllowed`; +this reflects a live password/passkey owner at read time, never grants commit +authority. It exposes only the current served brain's trust policy facts, not +operation identities, review bytes, private grants or history. Prepare, commit +and per-request receipt reads retain the live owner checks. Mixed-version hosts +that omit `mutationAllowed` are read-only in the UI. List reads recheck live +principal usability after the brain-lock wait: a revoked or expired caller gets +no policy facts. Losing owner availability invalidates private review bytes and +pending mutation replies; a failed list refresh disables writes until a fresh +successful read. Expired, uncommitted prepared reviews can be discarded without +republishing, while unknown publication remains uncertain. The list's optional `instances` maps each rule ID to an observation-only source +incarnation token captured with that policy. It grants no publication authority. +An edit/remove draft can refresh across unrelated trust revisions only when its +selected rule bytes and incarnation are unchanged. A changed/missing incarnation +or selected rule requires explicit re-selection; older hosts without tokens keep +the conservative same-revision requirement. A denied read clears every protected +draft field. Missing retained receipts can be left as outcome unknown, without +replay or a success claim. Required enforcement capabilities are rechecked for +both Review and Save; removing a rule remains available when enforcement is +unavailable. Enforcing policy facts refresh with list reads and after Save; old +facts during refresh are labeled last-read, never current enforcing facts. Missing runtime capabilities +never imply active trust; repository rows remain disabled/unverified while +repository enforcement is unavailable. Settings edits are prospective and never +commit historical safety verdicts. The SDK schemas entry point exposes the +existing canonical trust parsers and rule/list validators for browser inputs. + +The optional `/api/trust-settings` HTTP surface is a policy-publication building block. `GET /api/trust-settings` reads the current trust-only revision, exact policy hash, `origins`, `repositories`, repository-identity availability, -and disabled runtime enforcement capabilities. +and independently advertised runtime enforcement capabilities. The composed host enables origin/recipient enforcement; repository enforcement remains unavailable. `POST /api/trust-settings/prepare` accepts strict version-1 JSON with `expectedTrustRevision`, `expectedPolicyHash` and exactly one `change`: `{action:create|edit,rule}` or `{action:remove,ruleId}`. The host issues the @@ -5663,12 +5710,10 @@ only read the original outcome; changed data conflicts. Expired handles can never create operations. Prepared/readback text survives stale-base refusal. The receipt stages are `prepared|file_published|committed|partial|unknown|refused`; -`committed` is an internal publication-completion stage, never proof of live -runtime enforcement. Current responses use `partial` for saved policy because -`enforcement:unavailable` remains truthful until the admission implementation. +`committed` with `enforcement:enforced` reports a qualified origin/tunnel publication only after the live revision and active input fences have updated. Repository publication and hosts without origin enforcement continue to return `partial` with `enforcement:unavailable`. `currentRule:present|removed|changed|unknown` is refreshed on reads, independently of historical publication proof. Readback loads the durable operation and policy -projection within the same brain lock after any in-progress commit finishes. No removal receipt claims an enforcing fence. +projection within the same brain lock after any in-progress commit finishes. An enforced origin removal has already fenced later active-turn admission and interrupted affected source streams. No agent turn, provider message or ordinary governance snapshot is changed. The journal awaits asynchronous metadata and publication before releasing its Settings observation window. It records intervening changes with their ordinary attribution before @@ -5679,7 +5724,9 @@ The live trust projection retains last-valid rules on invalid policy, reports an error, and increments its decimal uint64 revision only for trust-list changes. Exhausted revisions refuse both new reviews and publication of retained reviews before any protected policy write; request revisions above uint64 also refuse. -It is supplied for future admission integration; runtime capabilities remain off. +The composed host shares its live trust revision with proxy and backend admission. The protected policy proposal publisher refreshes the same projection under the shared brain lock before reporting updated; qualified turn preparation refreshes it too. A synchronous anchored trust-list check refuses stale disk/projection matches during that refresh gap. Invalid policy retains last-valid rules with an error. Ordinary turn budgets, commands and profiles retain their admitted snapshots. + +`OriginTrust.refresh` returns without the brain lock when the observed policy hash equals the durable projection's hash and the projection carries no error; otherwise it queues the lock as before, cancellable on turn abort. The HTTP boundary admits at most 32 concurrent requests per principal and 256 for the served brain, including lock waiters; excess requests return retryable @@ -5993,3 +6040,181 @@ for every interactive session, so a new session's retained append contains the bullet. A session retained earlier keeps its append byte for byte. The same-commit API report records the additive types. See [the MCP component](mcp.md#raw-connections-to-githubs-api-0450-3799). + + +### Historical origin admission evidence (#3609) + +Safety occurrence DTOs add optional `admission` with `trusted`, `policyHash` +and `trustRevision`; a true decision also carries `ruleId` and +`collectionRevision`. A trusted admission requires the proxy detector and verified +HTTP-origin or tunnel provenance; both revisions are bounded unsigned 64-bit +decimal strings. Recorder ingestion, projection and history share this schema. +It is host-owned historical evidence, never client +permission or a human verdict. Older payloads without it retain conservative +interpretation. The aggregate excludes trusted admissions from unresolved +counts while keeping unrelated occurrences, coverage gaps and recording failures +restrictive. Pruning preserves these minimal admission facts and their verified provenance. The UI names +historical source trust separately and offers no safe-verdict action for it. +Provider history remains byte-identical as an earlier prefix. + + +## Turn egress charge and cancellation + +Each cleartext HTTP proxy operation uses its own non-pooled upstream connection, matching its `Connection: close` request header. A closed socket from an earlier operation is never reused, and transport failures do not automatically replay the request. Application-byte accounting and the final admission fence run once per send. CONNECT already owns a distinct upstream socket; inference and provider relays retain their separate Fetch transports. + +The concrete turn proxy's `charge(bytes)` returns `{ok:true}` or +`{ok:false,reason:"budget"|"safety_changed"|"policy_denied"|"unavailable"|"cancelled"}`. Callers preserve that +classification. Each terminal decision stores its typed reason before notifying +abort listeners; `failure()` reads that immutable decision without charging or +consulting live state. Callers never call `charge(0)` to classify an operation +that already refused. `prepare()` runs preparation observers without publishing a +dispatch fact. After charging, `dispatch(send)` runs the final typed fence and +calls the synchronous transport handoff. Only after the transport constructor or fetch call returns successfully does +it publish dispatched state and the committed/contacted notification, once. +The final fence returns the recipient authority it used (the exact rule instance, +explicit approval or independent allowance). Only that decision feeds the +dispatch receipt; preparation never supplies recipient evidence. +A refused preparation or fence never grants contacted-host access. A started +send still counts if it later fails. Preparation observers may revoke; fact +observers run after send and cannot erase bytes already handed to transport. A zero-byte terminal decision can complete at the exact byte ceiling while +still revalidating safety. `bytes` must be a nonnegative safe integer; invalid counts +throw RangeError before changing either the turn or connection byte counter. +Only budget refusal is byte exhaustion; authority/source or +approval changes are `safety_changed`, denied recipient/destination policy is +`policy_denied`, unverifiable recording/admission is `unavailable`, and turn or +client cancellation is `cancelled`. Their statuses are 403, 403, 503 and 499 +respectively; disconnected transports may have no response status. Inference/provider uploads, headers, streams and managed GitHub +wire metering consume this result. `OriginTrust.refresh(signal?)` cancels a +queued brain-lock acquisition on turn abort; it never releases another holder. `OriginTrust.refresh` returns without the brain lock when the observed policy hash equals the durable projection's hash and the projection carries no error; otherwise it queues the lock as before, cancellable on turn abort. +Turn startup rechecks abort before creating egress resources and normal turn +teardown releases its own governed hold and concurrency slot. + +The concrete operation lifecycle is pending → admitted → dispatched → finished +or aborted. Admission after a terminal transition is a no-op. A new dispatch +requires remaining byte capacity, including after approval or DNS waits; the +zero-byte ceiling exception applies only to an already-dispatched stream. +Admission effects already started are joined before terminal observation and +cleanup. Proxy `settled()` joins those effects before the host joins its durable +records. Each operation owns and releases all of its per-connection keys once. + +Proxy destination admission and server occurrence provenance use the history +record schema itself: host names fit 253 UTF-8 bytes and ports are integers +from 1 through 65535. Invalid destinations are refused before admission effects +or durable occurrence writes. Relay retries use the same stored-failure +classification as initial admission. All upstream requests use operation +cancellation together with their existing request/deadline signal, and check +cancellation again after observer callbacks immediately before dispatch. + +Relay failure classification snapshots the failure site before terminal +cleanup aborts the operation signal. Credential or upstream request failures +return 502, actual cancellation returns 499, and a previously decided policy +or safety refusal retains its typed status. Interrupted streams keep their +already-sent HTTP status and terminate with failed or cancelled evidence. +Caller-signal listeners belong to the operation lifecycle and are released +by every terminal transition, including internal admit/charge/dispatch refusals. + +Provider relay cancellation preserves `cancelled` in both the refusal observer +and `error.reason`. Preparation observers run before a final typed send fence; +a synchronous authority or recording change refuses the upstream request. +Files cleanup responses charge their headers against the same turn ceiling as +ordinary provider responses, with a budget refusal if those headers exceed it. + +Provider receipt `status` is exclusively the observed upstream HTTP status, +including cancellation and cleanup; it stays 0 until a response arrives. +Local refusal status remains in the caller response. Governed buffered Files +answers and streaming scrubber tails revalidate safety at EOF before exposing +held bytes or registering upload URLs and handles. + +Inference and provider relays share response accounting: observed headers debit +before redirect/status handling, every observed chunk debits before response +size checks, and EOF revalidates live admission before completion. Incoming +bytes beyond the remaining turn allowance consume the available allowance and +refuse the excess. Files cleanup drains through the same metered reader. + +`WebModelEgress.remainingBytes()` and the reader on governed relay `egress` +options are optional additive minor-version fields. Existing operation-only +adapters still compile and run. Without a reader, each relay operation uses a +32 MiB compatibility ceiling (the existing per-request limit) across its +accounted request and response bytes, while the route's own charge/admission +checks still apply. This fallback cannot know or saturate an older adapter's +remaining shared turn allowance; adapters should supply the reader for exact +shared accounting. Host web-model routes require it through an internal type, +and Pi forwards it unchanged. Ungoverned relays without an egress route +retain their existing behavior. Received proxy HTTP/CONNECT bytes and both +relay uploads/responses share the same saturating allowance accounting. + +Preparation and exposure notifications are separate: proxy `preparing` and +provider relay `preparing` run before the last send fence; `committed` and +provider `observe({outcome:"dispatched",...})` report an actual transport start. +Relayed operations expose `prepare()` and `dispatch(send)` in place of this +change's provisional `commit()` method. A pending terminal decision during a +synchronous transport handoff joins its final dispatched fact before audit only +if the handoff returns successfully. +Streaming read results carry a delivery closure that revalidates and enqueues +in one synchronous call. No awaited continuation separates that final check +from chunk delivery or scrubber-tail release. + +An upstream HTTP request constructor starts a connection attempt. The proxy +constructs it inside `dispatch(send)` after the final fence, even if the +client's body is still pending. That connection attempt is dispatched and +contacted exposure; later cancellation cannot erase it. Subsequent writes and +end still revalidate through the same send fence. + +A synchronous transport-handoff throw is classified by the same caller path +as an asynchronous upstream rejection. A synchronous throw publishes no +dispatched fact or contacted-host grant. Dispatch does not abort or store an +admission refusal before the caller classifies +that transport error. Both report failed upstream attempts (502 before response +headers), with provider receipt status 0 when no upstream response was seen. +The final fence and transport invocation remain synchronous. Proxy HTTP and +CONNECT use their ordinary upstream-failure handler for either failure order. + +Received HTTP heads are metered by the shared reader before forwarding filters. +The Node proxy supplies the actual HTTP version/status or request line and every +`rawHeaders` pair, including duplicate and Connection-nominated fields. Fetch +relays supply every unfiltered header pair exposed by Fetch, including repeated +Set-Cookie entries in the installed runtime. Counts cover all exposed name/value +bytes and CRLF framing plus the existing runtime allowance. `http_wire_bound` +is conservative application-level accounting: it does not claim exact TLS, +transport wire bytes, or original header formatting discarded by Fetch. This +clarifies the existing bound; forwarding policy never determines received cost. + +Relay request accounting charges the unfiltered worker head before any body read, +forwarding filter or credential injection. The logical request head costs at +least the larger of that received head and the constructed upstream head, +including the framing allowance; upstream growth is charged before dispatch. +The local relay hop does not count the same logical head twice. Generated +cleanup requests have no worker head and charge their constructed upstream head. + +The native HTTP proxy also meters every informational response head (including +100 Continue and 103 Early Hints) through the same raw-head meter, before the +final response. A 101 upgrade head is also metered; this HTTP route refuses +protocol switching and closes that socket. An interim refusal cannot be overwritten by a final head that +arrives in the same packet. + +A proxy input cannot use source trust until its occurrence write confirms a +durable commit. A false result or failed write refuses that operation with +503 egress_unavailable even if permanent-gap coverage reports recording +available. No trusted source fact or terminal exposure is published for a +missing occurrence. Legacy recorder adapters await their write result; an +otherwise unacknowledged trusted write must be present in the safety ledger. + +Network approval markers exclude only the approved operation’s own occurrence +and, when it creates the turn’s first collection, that same collection-start +metadata. Independent inputs, pending writes, failures, bindings and authority +changes still invalidate the decision. An unknown collection does not become +clean through this exclusion. + +An operation-specific recorder failure is 503 egress_unavailable. A different +recorder’s loss or an independent pending input changes the safety context and +refuses with 403 safety_changed. The internal optional +AdmissionSafetySnapshot.operationRecordingAvailable distinguishes the two; +legacy snapshots without that detail retain conservative unavailable behavior. + +Once a successfully dispatched explicit Network approval has become the session +contacted-host grant, later independent input does not revoke that recipient +grant or truncate the approved stream. Pre-dispatch approval freshness, source +rule removal, authority, recorder availability, outward permission and byte +ceilings remain independently fenced. Outward callbacks retain their original +{host, port, method} shape; transport metadata is confined to source/recipient +matching and the corresponding Network-card identity. diff --git a/docs/integration-contract/wire.md b/docs/integration-contract/wire.md index f855f99514..e9937c9871 100644 --- a/docs/integration-contract/wire.md +++ b/docs/integration-contract/wire.md @@ -3349,3 +3349,101 @@ These sidecars never change provider messages, tools or system prefixes. The host-only verdict store remains separate; this slice changes no effective-taint admission semantics or Settings policy. The semantic G6 break remains governed by the prior maintainer ruling in the session-safety ADR. + + +### Historical admission evidence (additive, #3609) + +A server advertising `sessionSafetyAdmissionEvidence:true` accepts optional +`includeAdmissions:true` on `safety_read`. Only opted-in snapshot pages and +their subscriptions include occurrence `admission` evidence. Cursor continuation +pins this choice alongside entry correlation; changing it requires a fresh +snapshot. Older readers retain their strict record shape and conservative +interpretation. New clients omit the field when the server capability is absent. +HTTP readers explicitly opt in with `admissions=1`; repeated/invalid query values are refused. This affects host UI sidecars only; it never changes provider history. + +### Combined single-trigger and future-source review (#3611) + +All three combined-review endpoints are supported POST operations in the +[classified HTTP inventory](../http-api.md#inventory-and-selection), with live +password-mode owner, exact Origin and bounded JSON authority fences. Status is +a read-only POST; it adds no GET or implicit HEAD endpoint. + +When `capabilities.sessionSafetyFutureRules` and `safetyCapabilities.review` +are true, a password-mode owner may +POST `/api/sessions/:id/safety/reviews/future/prepare` with the individual +review body plus `future: { incomingContent: true, recipientWhileRestricted: +boolean }`. The recipient flag is independently chosen, off by default. +Only finalized proxy occurrences with host-attested web-origin or explicitly +labelled tunnel provenance qualify. Repository choices remain unavailable. +The response binds a request ID, exact session/occurrence, the proposed policy +bytes/diff, review ID and SHA-256 reviewed-bytes hash. Clients must display this +review before POSTing `/future/commit` with `{ version: 1, requestId, reviewId, +reviewedBytesHash }`. No caller-supplied selector, principal or historical range +is accepted. Old clients retain the existing individual review endpoints. + +The protected Settings operation stores its original single-verdict handle +before publication. Publication precedes that verdict; publication alone never +resolves the occurrence. Responses distinguish `verdict_committed`, `partial`, +`unknown` and `refused`, retain publication evidence and the original verdict +receipt, and include separate live `currentProjection` and rule presence +(`present`, `removed`, `changed`, `unknown`). A proved publication can resume +only its original verdict request; unknown publication requires fresh review. +Retries never republish a removed rule. All other recorded triggers, including +later input from the same source, keep their identities and verdicts. + +Prepared reviews expire after 15 minutes, with existing 24-hour receipt +retention and bounded Settings/verdict capacity. Existing live owner epoch, +Origin/JSON, session generation, evidence revision and protected publication +fences apply. Auth/session changes discard pending browser work without replay. +These host sidecars never enter provider history. + +POST `/future/status` with `{ version: 1, session, occurrenceId }` reads the +retained combined operation selected by completion/publication evidence, +without publishing or committing a verdict. +It returns the same result envelope, or null when no receipt is retained. Commit and status derive +completion from the exact operation's durable verdict decision, including after +a lost acknowledgement or a retry refused by the pending-review quota. A retained +noncommitted verdict receipt has its internal request/operation IDs redacted on +both endpoints. Missing verdict receipts do not erase a durable decision. +Clients correlate prepared and committed responses with the originally requested +session and occurrence before using a handle or acknowledging completion. +A failed status read (including a mismatched target) displays explicit +could-not-verify uncertainty; successful JSON null clears the receipt display. +Only the newest overlapping status read can update that display. The +owner UI reads this after reload and on focus to show partial/unknown completion +and current rule presence separately from the remaining-trigger projection. + +#### Combined-review ordering and legacy capability encoding + +A verdict handle bound to a combined operation requires that operation's durable +publication proof inside the FULL verdict transaction, including commits through +the individual review endpoint and receipt replay. `publication_unproven` refuses +only that attempt without consuming the handle; equal current policy bytes are +not publication proof. Prepared/noncommitted status redacts the internal verdict +request and operation IDs. A separately prepared individual review remains an +independent human decision and does not finish the combined operation. + +For compatibility with the previously shipped strict SDK parser, every +`server_hello.safetyCapabilities` retains `originRules: false`, +`repositoryRules: false`, and `recipientRules: false`. Future-rule support is +instead offered as the additive boolean +`server_hello.capabilities.sessionSafetyFutureRules`. A new UI enables its local +future source/recipient controls only when that offer and `safetyCapabilities.review` +are both true. Old UIs ignore the boolean offer and retain safety history and +individual review. No protocol revision or breaking schema migration is required. + +Operation completion text never asserts current rule presence or current trigger +resolution. Refreshed status owns current rule presence; the live safety ledger +owns the selected trigger's verdict and remaining-trigger count. A partial +combined receipt can coexist with a later independent safe decision. + +Status recovery considers only the current principal/served brain/session's +retained Settings operations, using the same retention clock as Settings reads. +A committed verdict takes precedence. Otherwise, rule presence in the currently +verified policy takes precedence, then proved publication ordered by its durable +trust revision, then unknown publication, then the newest unpublished preparation. +Preparation expiry is not publication order. Selection and readback share a read transaction +after the policy lock and refresh waits. Expired or concurrently pruned receipts +return JSON null without needing another write to prune storage. Authority and +session fences still apply before delivery. The UI sequences focus reads so an older +success or failure cannot replace a newer rule-presence result. diff --git a/docs/plans/chat-history-deletion.md b/docs/plans/chat-history-deletion.md index c4eb15fe48..24f59832c0 100644 --- a/docs/plans/chat-history-deletion.md +++ b/docs/plans/chat-history-deletion.md @@ -216,7 +216,7 @@ must be tested through their installed runtime, not inferred from directory name readable projections according to the adopted extent. Retained digests can reveal guessed short text; discard unnecessary hashes, not just plaintext. Native history joins several of these owners - (`prepareHistory`, `packages/ui-server/src/ws/host.ts:690-702`). + (`prepareHistory`, `packages/ui-server/src/ws/host.ts:713-728`). - **Independent session ledgers.** `retry_receipts`, `session_work`, `turn_boundaries`, draft send/save/upload receipts and revisions, handoff IDs/lineage, Claude usage deduplication, worker profiles, provider-exposure and born-masked lineage are @@ -303,7 +303,7 @@ The paired WS dispatcher is `packages/ui-server/src/ws/dispatch.ts`, with one handler per frame under `ws/handlers/`; gating its resume handler alone would leave HTTP, background readers and provider startup open. Existing ordinary history publication checks concurrent turn changes -(`publishHistory`, `packages/ui-server/src/ws/host.ts:634-668`). Future deletion +(`publishHistory`, `packages/ui-server/src/ws/host.ts:639-673`). Future deletion must additionally invalidate it even when no turn starts or ends. Startup reads native history, canonical evidence and completed facts, and freezes a snapshot (`readLiveHistory`, `packages/ui-server/src/ws/live-history.ts:9-74`). Recheck the diff --git a/docs/plans/extraction-classifier.md b/docs/plans/extraction-classifier.md index 414dfa5bba..7cdde2bf3f 100644 --- a/docs/plans/extraction-classifier.md +++ b/docs/plans/extraction-classifier.md @@ -39,8 +39,8 @@ It is advisory and narrow: - An `allow` may relax exactly one thing, the #3430 card for a host the tainted session has not contacted - (`const narrowing`, `packages/ui-sdk/src/server/egress-proxy.ts:280-285`; - `const approveTainted`, `packages/ui-server/src/brain/turn-egress.ts:172-183`). + (`const narrowing`, `packages/ui-sdk/src/server/egress-proxy.ts:390-395`; + `const approveTainted`, `packages/ui-server/src/brain/turn-egress.ts:273-284`). Because the proxy cannot tell which process opened a connection, that relaxation can only cover the hosts a readable call names while it is in progress, as the outward exception already does. An opaque call withholds @@ -85,7 +85,7 @@ Each is deterministic and was scored alone | Taint host | A destination's site appears among the hosts the tainting content named. | | Encoded blob | A base64 or hex token of at least twelve characters in subdomain, path, query or body; an undecodable one must be twenty characters with a digit. `encodedText`: the blob decodes to readable text. | | Volume | A query of 120 characters or data of 512 bytes to a host the session has not contacted. | -| Write-shaped | Paste, webhook, request-bin, form, upload and collect hosts, the built-in outward mail hosts (`MAIL_SUBMISSION_PORTS`, `packages/ui-server/src/brain/turn-egress.ts:22`), a writing method to a submit, issue, comment, gist or message path, a beacon path, or an MCP tool named send, create, post, upload, comment, write, update, append or share. | +| Write-shaped | Paste, webhook, request-bin, form, upload and collect hosts, the built-in outward mail hosts (`MAIL_SUBMISSION_PORTS`, `packages/ui-server/src/brain/turn-egress.ts:25`), a writing method to a submit, issue, comment, gist or message path, a beacon path, or an MCP tool named send, create, post, upload, comment, write, update, append or share. | | Fan-out | Five earlier calls, or three distinct hosts, to one site the session had not used before its taint. | | Method | A writing method, or a tool the policy classifies outward or opaque. | diff --git a/docs/plans/google-workspace.md b/docs/plans/google-workspace.md index dc7e5fc806..292fd590e6 100644 --- a/docs/plans/google-workspace.md +++ b/docs/plans/google-workspace.md @@ -761,7 +761,7 @@ users, which suits a personal instance. A Google Workspace owner can use an PID namespace and `/proc`). - A worker's own `gog` finds no home and no keyring. Its connection to `gmail.googleapis.com` is already outward and waits on a Network card - (`MAIL_SUBMISSION_HOSTS`, `packages/ui-server/src/brain/turn-egress.ts:24-26`), + (`MAIL_SUBMISSION_HOSTS`, `packages/ui-server/src/brain/turn-egress.ts:26-28`), and reaches Google unauthenticated if allowed. A worker's `brain google` finds no credential and answers `unavailable`. diff --git a/docs/plans/reviewable-session-safety.md b/docs/plans/reviewable-session-safety.md index ed73ba16b9..9d22d69cfc 100644 --- a/docs/plans/reviewable-session-safety.md +++ b/docs/plans/reviewable-session-safety.md @@ -25,7 +25,7 @@ public design or its fixtures. Fictional examples use the Odysseus world. - Taint recording retains every independently observed signal and reads a durable revisioned aggregate, including pending/failure and explicit unknown coverage (`safetyProjection`, - `packages/ui-server/src/governance/safety-store.ts:418-423`). Legacy rows prove + `packages/ui-server/src/governance/safety-store.ts:429-434`). Legacy rows prove their own event, never a complete history. Owner review transport and its mutation capability remain disabled by this foundation. - Tool ingestion collects input and output signals independently (`inputTaintSignals`, @@ -36,13 +36,13 @@ 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:86-295`). Relay admissions join + `packages/ui-server/src/brain/turn-egress.ts:94-389`). 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 + `packages/ui-server/src/ws/bridge-session-binding.ts:15-32`), 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:200-435`). + (`startEgressProxy`, `packages/ui-sdk/src/server/egress-proxy.ts:264-608`). - Outward decisions read session taint at admission (`prepareOutwardPlan`, `packages/ui-sdk/src/server/outward-policy.ts:47-94`). Existing historical steering attribution must remain attribution at the time of a write. diff --git a/docs/supported-inputs.md b/docs/supported-inputs.md index d7ac72f626..fbcf3b4503 100644 --- a/docs/supported-inputs.md +++ b/docs/supported-inputs.md @@ -111,11 +111,13 @@ repeated hyphens; repository tokens are 1–100 ASCII alphanumeric/`_.-` bytes, excluding `.` and `..`. Stable provider IDs are nonzero decimal strings of at most 20 digits. A parsed worker remote never proves provider identity. -These are policy data and pure candidate matching only. All runtime origin, -recipient and repository rule capabilities remain **disabled**, with an -explicit reason in the internal availability facts. There is no new Settings -writer, transport, admission exemption, historical reclassification or safe -verdict. Incoming-only rules cannot authorize a restricted destination; repo +Schema parsing and pure candidate matching alone enable no runtime authority. +The data-only availability defaults remain disabled. Since #3609, the composed +host independently advertises qualified exact-origin/tunnel source and recipient +enforcement; repository enforcement remains disabled. See the +[admission contract](integration-contract/http.md#prospective-origin-enforcement-breaking-before-10-3609) +and [owner Settings publication](integration-contract/package-api.md#human-trust-settings-publication). +No rule retrospectively reclassifies a trigger or supplies a safe verdict. Incoming-only rules cannot authorize a restricted destination; repo rules cannot authorize a generic host, outward write or private acquisition. The existing `taint.egress.allow` list is not populated from these entries. diff --git a/packages/common/package.json b/packages/common/package.json index 8b89b858e3..dbee02e85a 100644 --- a/packages/common/package.json +++ b/packages/common/package.json @@ -110,6 +110,11 @@ "bun": "./src/safe-path.ts", "types": "./dist/safe-path.d.ts", "default": "./dist/safe-path.js" + }, + "./internal/taint-trust": { + "bun": "./src/taint-trust.ts", + "types": "./dist/taint-trust.d.ts", + "default": "./dist/taint-trust.js" } }, "files": [ diff --git a/packages/ui-backend-pi/src/host-inference.ts b/packages/ui-backend-pi/src/host-inference.ts index 1641b32a4e..73877aaeb4 100644 --- a/packages/ui-backend-pi/src/host-inference.ts +++ b/packages/ui-backend-pi/src/host-inference.ts @@ -244,7 +244,7 @@ export async function preparePiHostInference(options: { /** The origin turn admission proved the recipient from (#2695); any other endpoint refuses before a credential is read. */ recipientOrigin?: string; /** The turn proxy's private directory; the relay socket is linked into it. */ - egress: { dir: string; inference: NonNullable[0]["egress"]>["inference"] }; + egress: { dir:string } & NonNullable[0]["egress"]>; environment: Readonly>; signal?: AbortSignal; }): Promise { diff --git a/packages/ui-backend-pi/tests/fixtures/native-host-auth-probe.ts b/packages/ui-backend-pi/tests/fixtures/native-host-auth-probe.ts index 9edf00486f..008f2f4a75 100644 --- a/packages/ui-backend-pi/tests/fixtures/native-host-auth-probe.ts +++ b/packages/ui-backend-pi/tests/fixtures/native-host-auth-probe.ts @@ -159,7 +159,7 @@ try { unix: relay.socketPath, } as RequestInit); const body = await response.text(); - assert.equal(response.status, 503); + assert.equal(response.status, 502); assert(!body.includes(errorSecret)); assert(!body.includes("odysseus-refresh-cancel")); assert(body.includes("Inference credentials unavailable")); diff --git a/packages/ui-backend-pi/tests/native-host-auth-qualification.test.ts b/packages/ui-backend-pi/tests/native-host-auth-qualification.test.ts index ce55365e03..2146b3c3f1 100644 --- a/packages/ui-backend-pi/tests/native-host-auth-qualification.test.ts +++ b/packages/ui-backend-pi/tests/native-host-auth-qualification.test.ts @@ -73,7 +73,7 @@ test("installed native auth reads current credentials, serializes refresh, cance hostAuthUnchanged: true, }); expect(result.nativeAuthErrorRedaction).toEqual({ - status: 503, + status: 502, secretAbsent: true, namedRefusal: true, }); diff --git a/packages/ui-react/README.md b/packages/ui-react/README.md index 3c870566a0..2e59094a77 100644 --- a/packages/ui-react/README.md +++ b/packages/ui-react/README.md @@ -841,7 +841,13 @@ its groups each own their route and state, so the live-conversation service can join the same pane without sharing a revision. Theme and the single-key shortcut switch apply only on this device and live in Appearance & input. Accounts holds provider sign-in and web-search settings; -Security holds passkeys, always-allowed tool revocation and sign-out. +Security holds passkeys, source-trust and data-sending rules, always-allowed tool +revocation and sign-out. Trust rules use exact-byte protected owner review and +apply only to future input; historical safety events stay unchanged. Origin and +opaque-tunnel rules have separate incoming-trust and recipient controls, with +sending permission off by default. Repository/organization scopes remain +explicitly disabled and unverified until the host advertises enforcement. +Non-owner callers and older hosts without mutation availability remain read-only. Below 900px the tab strip scrolls horizontally; desktop groups the section column by This device, This brain and Access. Arrow keys and Home/End move focus diff --git a/packages/ui-react/src/components/chat/safety-indicator.tsx b/packages/ui-react/src/components/chat/safety-indicator.tsx index 8cd6349a14..43bac37f46 100644 --- a/packages/ui-react/src/components/chat/safety-indicator.tsx +++ b/packages/ui-react/src/components/chat/safety-indicator.tsx @@ -1,3 +1,4 @@ +import type { SafetyFuturePrepared } from "@schlessera/brain-ui-sdk/protocol"; import { useEffect, useId, useLayoutEffect, useMemo, useRef, useState } from "react"; import { createPortal } from "react-dom"; import { useStore } from "zustand"; @@ -7,6 +8,8 @@ import { activeChat, useChatStore } from "../../stores/chat-store.js"; import { entryEvidence, safetyEvidence, type SafetyEvidence } from "../../lib/safety-evidence.js"; import { createSafetyReviewer, type SafetyReviewProgress } from "../../lib/safety-reviewer.js"; +const formatAuthority = ({host,port}:{host:string;port:number}) => `${host.includes(":") && !host.startsWith("[") ? `[${host}]` : host}:${port}`; + const sources:Record={web_fetch:"Web fetch",web_search:"Web search",staged_share:"Shared input",chat_attachment:"Chat attachment", workspace_read:"Workspace read",mcp_document:"External tool input",user_marked:"Marked untrusted",fetching_command:"Fetching command",unclassified_command:"Unclassified command", compute_output:"Compute output",apify_result:"Apify result",github_result:"GitHub result",egress_connection:"Network input",legacy_unknown:"Legacy input evidence"}; @@ -70,9 +73,17 @@ function SafetyIndicator({entries:currentEntries}:{entries:SafetyEvidence[]}) { const entries=allowed?(currentEntries.length?currentEntries:open||readStatus!=="ready"?held.current.entries:[]):[]; useEffect(()=>{if(!allowed)setOpen(false);},[allowed]); useEffect(()=>{setOpen(false);},[scope,auth]); - const unresolved=entries.filter(e=>!e.decision).length,unknown=entries.some(e=>e.occurrence.detailPruned||e.occurrence.source==="legacy_unknown"); - const name=unresolved?`Safety restrictions: ${unresolved} unresolved trigger${unresolved===1?"":"s"}`:`Marked safe by you${entries.length>1?`: ${entries.length} triggers`:""}: show details`; - const reason=unresolved?`${sources[entries.find(e=>!e.decision)!.occurrence.source]} · Only this trigger can be reviewed`:"Human decision retained; content remains in the model context"; + const unresolvedEntries=entries.filter(e=>!e.decision&&!e.occurrence.admission?.trusted); + const unresolved=unresolvedEntries.length,unknown=entries.some(e=>e.occurrence.detailPruned||e.occurrence.source==="legacy_unknown"); + const trusted=entries.filter(e=>e.occurrence.admission?.trusted).length,reviewed=entries.filter(e=>e.decision).length; + const accepted=[...(trusted?[`${trusted} trusted at admission`]:[]),...(reviewed?[`${reviewed} marked safe by you`]:[])].join("; "); + const name=unresolved?`Safety restrictions: ${unresolved} unresolved trigger${unresolved===1?"":"s"}${accepted?`; ${accepted}`:""}` + :trusted===entries.length&&!reviewed?`Trusted at admission${entries.length>1?`: ${entries.length} inputs`:""}: show details` + :reviewed===entries.length&&!trusted?`Marked safe by you${entries.length>1?`: ${entries.length} triggers`:""}: show details` + :`Safety history: ${accepted}: show details`; + const reason=unresolved?`${sources[unresolvedEntries[0]!.occurrence.source]} · Only this trigger can be reviewed` + :trusted&&reviewed?"Historical source trust and human decisions retained; current rules may differ" + :trusted?"Historical source trust retained; current rules may differ":"Human decision retained; content remains in the model context"; useLayoutEffect(()=>{ if(!open)return; const place=()=>{const r=trigger.current?.getBoundingClientRect();if(r)setPosition({left:Math.max(12,Math.min(r.left,innerWidth-Math.min(384,innerWidth-24)-12)),top:Math.max(12,Math.min(r.bottom+4,innerHeight-Math.min(520,innerHeight*.65)-12))});}; @@ -102,33 +113,61 @@ function SafetyIndicator({entries:currentEntries}:{entries:SafetyEvidence[]}) { function SafetyTrigger({entry}:{entry:SafetyEvidence}) { const root=useBrainUiRoot(),state=useStore(root.stores.safety),auth=useStore(root.authLock.state,s=>s.phase); + const [savedRule,setSavedRule]=useState(null); + const [future,setFuture]=useState(false),[recipient,setRecipient]=useState(false),[prepared,setPrepared]=useState(null); const [review,setReview]=useState(false),[progress,setProgress]=useState(null); const reviewer=useRef|null>(null); useEffect(()=>{const r=createSafetyReviewer(root,setProgress);reviewer.current=r;return ()=>{r.dispose();reviewer.current=null;};},[root]); useEffect(()=>{if(state.status!=="ready"||!state.capabilities?.review||auth!=="active")setReview(false);},[state.status,state.capabilities?.review,auth]); + useEffect(()=>{if(auth!=="active"){setPrepared(null);setProgress(null);setReview(false);}},[auth]); const r=entry.occurrence,session=state.identity&&"sessionId" in state.identity?state.identity:null; const readable=state.status==="ready"&&!!session,owner=state.capabilities?.review===true&&auth==="active"; - const canReview=readable&&owner&&entry.exposure==="finalized"&&!entry.decision&&!state.projection?.pendingCount&&!state.projection?.reasons.includes("recording_failed"); + const sessionKey=JSON.stringify(session); + useEffect(()=>{ + if(!readable||!owner||!state.capabilities?.originRules||!session){setSavedRule(null);return;} + const controller=new AbortController();let sequence=0; + const read=()=>{ + const request=++sequence; + void root.api.safetyFutureStatus({version:1,session,occurrenceId:r.id},controller.signal).then(result=>{ + if(controller.signal.aborted||request!==sequence)return; + if(!result){setSavedRule(null);return;} + if(result.occurrenceId!==r.id||JSON.stringify(result.session)!==sessionKey)throw new Error("Different future review status"); + const presence=result.rule.currentRule; + setSavedRule(`${result.stage==="prepared"?"Future rule prepared but not published; fresh review is required. ":result.stage==="partial"?"Rule publication proved; this operation's verdict is incomplete. ":result.stage==="unknown"?"Rule publication is unknown; fresh review is required. ":""}Future rule: ${presence}.`); + }).catch(()=>{if(!controller.signal.aborted&&request===sequence)setSavedRule("Could not verify future rule publication or current presence. Refresh evidence to try again.");}); + }; + read();window.addEventListener("focus",read); + return()=>{controller.abort();window.removeEventListener("focus",read);}; + },[root,r.id,sessionKey,readable,owner,state.capabilities?.originRules,state.revision]); + const canReview=readable&&owner&&entry.exposure==="finalized"&&!entry.decision&&!r.admission?.trusted&&!state.projection?.pendingCount&&!state.projection?.reasons.includes("recording_failed"); + const futureAvailable=state.capabilities?.originRules===true&&r.detector==="proxy_input"&&!!r.provenance; const busy=progress?.stage==="pending",unknown=progress?.stage==="unknown"; - const provenance=r.provenance?.kind==="web_origin"?`${r.provenance.origin.scheme}://${r.provenance.origin.host}:${r.provenance.origin.port}`: - r.provenance?.kind==="tunnel_authority"?`${r.provenance.authority.host}:${r.provenance.authority.port}`:"Source provenance unavailable"; + const provenance=r.provenance?.kind==="web_origin"?`${r.provenance.origin.scheme}://${formatAuthority(r.provenance.origin)}`: + r.provenance?.kind==="tunnel_authority"?formatAuthority(r.provenance.authority):"Source provenance unavailable"; return
-

{entry.decision?"Marked safe by you":"Safety restrictions enabled"}

+

{r.admission?.trusted?"Trusted at admission":entry.decision?"Marked safe by you":"Safety restrictions enabled"}

{sources[r.source]} ·

{r.summary}

{provenance}

+ {savedRule&&

{savedRule}

} + {r.admission?.trusted&&

Source rule {r.admission.ruleId} · trust revision {r.admission.trustRevision}. This historical decision grants no current recipient permission.

} {r.detailPruned&&

Some source detail has expired. The trigger and any decision remain recorded.

} {entry.decision&&

Marked safe by you ·

} - {!entry.decision&&entry.exposure!=="finalized"&&

{entry.exposure==="open"?"Input is still arriving. Mark as safe is unavailable until delivery is finalized.":"Delivery could not be confirmed. This trigger cannot be marked safe."}

} - {!owner&&!entry.decision&&

Only the authenticated owner can mark this trigger safe.

} + {!r.admission?.trusted&&!entry.decision&&entry.exposure!=="finalized"&&

{entry.exposure==="open"?"Input is still arriving. Mark as safe is unavailable until delivery is finalized.":"Delivery could not be confirmed. This trigger cannot be marked safe."}

} + {!r.admission?.trusted&&!owner&&!entry.decision&&

Only the authenticated owner can mark this trigger safe.

} {!readable&&

Current evidence is unavailable or incomplete. Read it again before reviewing.

} - {canReview&&!review&&!progress&&
; } diff --git a/packages/ui-react/src/components/settings/agent-policy-group.tsx b/packages/ui-react/src/components/settings/agent-policy-group.tsx index 8a31d63099..d6016a2ced 100644 --- a/packages/ui-react/src/components/settings/agent-policy-group.tsx +++ b/packages/ui-react/src/components/settings/agent-policy-group.tsx @@ -5,21 +5,28 @@ import { useBrainApi, useBrainUiRoot } from "../../root-context.js"; import { rememberFileEntry } from "../../lib/file-entry-focus.js"; /** Read-only facts: the host's admission reader and actual resource-limit report. */ -export function AgentPolicyGroup({ active }: { active: boolean }) { +export function AgentPolicyGroup({ active, refreshKey = 0 }: { active: boolean; refreshKey?: number }) { const api = useBrainApi(), root = useBrainUiRoot(); - const [facts, setFacts] = useState(null), [error, setError] = useState(""); + const [loaded, setLoaded] = useState<{ facts: AgentPolicyRead; refreshKey: number; root: object; epoch: number } | null>(null); + const [failure, setFailure] = useState<{ text: string; refreshKey: number } | null>(null); + const facts = loaded?.root === root && loaded.epoch === root.authLock.epoch() ? loaded.facts : null; + const currentFacts = !!facts && loaded?.refreshKey === refreshKey; + const error = failure?.refreshKey === refreshKey ? failure.text : ""; const generation = useRef(0), owner = useRef(root.authLock.epoch()); useEffect(() => { const token = ++generation.current, controller = new AbortController(); owner.current = root.authLock.epoch(); - setFacts(null); setError(""); + setFailure(null); + if (!active) setLoaded(null); if (active) void api.agentPolicy(controller.signal).then(result => { - if (token === generation.current && owner.current === root.authLock.epoch()) setFacts(result); - }, () => { if (!controller.signal.aborted && token === generation.current && owner.current === root.authLock.epoch()) setError("Could not read this brain's enforcing policy. Open Settings again to check."); }); - const invalidate = () => { generation.current++; controller.abort(); }; return invalidate; - }, [api, active, root]); + if (token === generation.current && owner.current === root.authLock.epoch()) setLoaded({ facts: result, refreshKey, root, epoch: owner.current }); + }, () => { if (!controller.signal.aborted && token === generation.current && owner.current === root.authLock.epoch()) setFailure({ text: "Could not read this brain's enforcing policy. Refresh Settings to check again.", refreshKey }); }); + const stop = root.authLock.state.subscribe(state => { if (state.phase !== "active") { generation.current++; controller.abort(); setLoaded(null); setFailure(null); } }); + const invalidate = () => { generation.current++; controller.abort(); stop(); }; return invalidate; + }, [api, active, root, refreshKey]); const warning = facts?.errors.length ? `The policy file does not validate: ${facts.errors.join("; ")}. ${facts.source === "last_valid" ? `Enforcing the last valid version ${facts.hash}.` : "No valid policy has been loaded; built-in defaults apply."}` : facts?.source === "default" ? "No policy file. Built-in defaults apply." : ""; + if (!active) return null; return

Agent policy

{error ? : !facts ? : <> @@ -33,9 +40,10 @@ export function AgentPolicyGroup({ active }: { active: boolean }) { const opener = document.activeElement; if (opener instanceof HTMLElement) rememberFileEntry(root, opener, opener.matches(":focus-visible")); root.stores.ui.getState().openPanel("files"); void root.stores.file.getState().openFile(facts.path); }} /> -

Enforcing version: {facts.hash ?? "built-in defaults"}

+

{currentFacts ? "Enforcing version" : "Last read version"}: {facts.hash ?? "built-in defaults"}

+ {!currentFacts &&

Refreshing enforcing policy…

}

Policy minimum — Interactive: {facts.profiles.interactive} · Voice: {facts.profiles.voice}

-
+

Only reported enforcing limits are shown.

{facts.workerLimits ?
    {facts.workerLimits.enforced.map(limit =>
  • {limit.limit}: {limit.value} ({limit.source}{["data", "file_size", "memory"].includes(limit.limit) ? ", bytes" : limit.limit === "cpu" ? ", CPUs" : ""})
  • )} diff --git a/packages/ui-react/src/components/settings/passkey-tab.tsx b/packages/ui-react/src/components/settings/passkey-tab.tsx index b608e527a8..5ef3da418a 100644 --- a/packages/ui-react/src/components/settings/passkey-tab.tsx +++ b/packages/ui-react/src/components/settings/passkey-tab.tsx @@ -1,3 +1,4 @@ +import { TrustSettingsSection } from "./trust-settings-section.js"; import { useCallback, useEffect, useRef, useState } from "react"; import type { PasskeySummary } from "@schlessera/brain-ui-sdk/protocol"; import { useBrainUiRoot } from "../../root-context.js"; @@ -157,7 +158,7 @@ export function PasskeyTab({ active }: { active: boolean }) { return ( <> } + sections={<>} credentials={credentials} status={loading ? "loading" : passkeyMode ? "ready" : "unavailable"} busy={busy} diff --git a/packages/ui-react/src/components/settings/trust-settings-section.tsx b/packages/ui-react/src/components/settings/trust-settings-section.tsx new file mode 100644 index 0000000000..79d5dc5d30 --- /dev/null +++ b/packages/ui-react/src/components/settings/trust-settings-section.tsx @@ -0,0 +1,295 @@ +import { createStore, useStore, type StoreApi } from "zustand"; +import { useCallback, useEffect, useLayoutEffect, useRef, useState, type SetStateAction } from "react"; +import { Button, Callout, ChoiceOption, Surface } from "@schlessera/brain-ui-kit"; +import { parseTrustOrigin, parseTrustTunnel, parseTrustGithub, TrustRuleSchema, TrustedSourcesSchema } from "@schlessera/brain-ui-sdk/schemas"; +import { useBrainUiRoot } from "../../root-context.js"; +import { ApiRequestError } from "../../lib/api-client.js"; +import { trustTarget, type TrustChange, type TrustOperation, type TrustRule, type TrustSettingsRead } from "../../lib/trust-settings.js"; +import { AgentPolicyGroup } from "./agent-policy-group.js"; + +type Draft = { focusField?: string; focused?: boolean; action: "create" | "edit" | "remove"; rule: TrustRule | null; instance: string | null; kind: TrustRule["selector"]["kind"]; target: string; providerId: string; label: string; incoming: boolean; recipient: boolean; revision: string; hash: string | null }; +type Edit = { phase: "draft" | "preparing"; draft: Draft; operation: null } + | { phase: "review" | "committing" | "uncertain" | "receipt-lost"; draft: Draft; operation: TrustOperation }; +type Session = { edit: Edit | null; unknownOutcomes: number }; +const sessions = new WeakMap }>(); +const unresolvedSave = (edit: Edit | null) => edit && ["committing", "uncertain", "receipt-lost"].includes(edit.phase) ? 1 : 0; +const draftEdit = (draft: Draft): Edit => ({ phase: "draft", draft, operation: null }); +function sessionFor(root: object, epoch: number) { + let session = sessions.get(root); + if (!session || session.epoch !== epoch) { + // Auth changes discard private editor state, but an unresolved write stays unknown. + const previous = session?.store.getState(); + const unknownOutcomes = previous ? previous.unknownOutcomes + unresolvedSave(previous.edit) : 0; + session = { epoch, store: createStore(() => ({ edit: null, unknownOutcomes })) }; sessions.set(root, session); + } + return session.store; +} +const instanceAt = (read: TrustSettingsRead, id: string) => typeof read.instances?.[id] === "string" ? read.instances[id]! : null; +function selectionMatches(draft: Draft, read: TrustSettingsRead) { + if (!draft.rule) return true; + if (JSON.stringify(read.rules.find(rule => rule.id === draft.rule!.id)) !== JSON.stringify(draft.rule)) return false; + const instance = instanceAt(read, draft.rule.id); + return draft.instance !== null && instance !== null ? draft.instance === instance : draft.revision === read.revision; +} +function capabilitiesAllow(draft: Pick, read: TrustSettingsRead) { + if (draft.action === "remove") return true; + const caps = read.capabilities; + if (draft.kind.startsWith("github_")) return caps.repositoryRules && caps.repositoryIdentity; + return (!draft.incoming || caps.originRules) && (!draft.recipient || caps.recipientRules); +} + +/** The transition table and its browser cases live in hit-reach.trust-settings.pointer.tsx. */ +export function TrustSettingsSection({ active }: { active: boolean }) { + const root = useBrainUiRoot(), api = root.api; + const [readState, setReadState] = useState<{ root: object; epoch: number; value: TrustSettingsRead } | null>(null); + const read = readState?.root === root && readState.epoch === root.authLock.epoch() ? readState.value : null; + const setRead = useCallback((value: TrustSettingsRead | null) => setReadState(value ? { root, epoch: root.authLock.epoch(), value } : null), [root]); + const frameScope = useRef({ root, epoch: root.authLock.epoch() }); + const currentFrame = frameScope.current.root === root && frameScope.current.epoch === root.authLock.epoch(); + const [policyRefresh, setPolicyRefresh] = useState(0); + const session = sessionFor(root, root.authLock.epoch()); + const { edit, unknownOutcomes } = useStore(session); + const draft = edit?.draft ?? null, operation = edit?.operation ?? null; + const uncertain = edit?.phase === "uncertain" || edit?.phase === "receipt-lost"; + const [checking, setChecking] = useState(false); + const busy = checking || edit?.phase === "preparing" || edit?.phase === "committing"; + const setDraft = (value: SetStateAction) => session.setState(state => { + const next = typeof value === "function" ? value(state.edit?.draft ?? null) : value; + return { edit: next ? state.edit ? { ...state.edit, draft: next } : draftEdit(next) : null }; + }); + const [error, setError] = useState(""), [readError, setReadError] = useState(""), [notice, setNotice] = useState(""); + const readRequest = useRef(0), generation = useRef(0), epoch = useRef(root.authLock.epoch()), controller = useRef(new AbortController()); + const opener = useRef(null), heading = useRef(null), editor = useRef(null); + const focusEditor = useRef(draft?.focused ?? false), restoreFocus = useRef(false), focusReview = useRef(false); + const current = useCallback((token: number) => token === generation.current && epoch.current === root.authLock.epoch() && !controller.current.signal.aborted, [root]); + const ownerMessage = "Read-only: a live password or passkey owner login is required to manage trust."; + const invalidatePrivate = useCallback((readDenied: boolean) => { + generation.current++; session.setState(state => ({ + edit: readDenied || !state.edit ? null : draftEdit(state.edit.draft), + unknownOutcomes: state.unknownOutcomes + unresolvedSave(state.edit), + })); + setChecking(false); setError(""); setNotice(""); + }, [session]); + function ownerRefused(err: unknown) { + if (!(err instanceof ApiRequestError) || ![401, 403].includes(err.status)) return false; + invalidatePrivate(true); setRead(null); setReadError(ownerMessage); return true; + } + const load = useCallback(async () => { + const token = generation.current, request = ++readRequest.current; + try { + const data = await api.trustSettings(controller.current.signal); + // Mixed-version hosts may omit enforcement advertisements; only true supports a capability. + const next = { ...data, capabilities: { + originRules: data.capabilities?.originRules === true, + recipientRules: data.capabilities?.recipientRules === true, + repositoryRules: data.capabilities?.repositoryRules === true, + repositoryIdentity: data.capabilities?.repositoryIdentity === true, + readOnlyReason: data.capabilities?.readOnlyReason ?? null, + } }; + if (current(token) && request === readRequest.current) { + const pending = session.getState().edit; + if (next.mutationAllowed !== true) invalidatePrivate(false); + else if (pending && ["preparing", "review"].includes(pending.phase) && (pending.draft.revision !== next.revision || pending.draft.hash !== next.policyHash)) { + generation.current++; session.setState({ edit: draftEdit(pending.draft) }); setChecking(false); + setNotice("Policy changed. Refresh base and review again; your draft is kept."); + } + setRead(next); setReadError(""); setPolicyRefresh(request); return next; + } + } catch (err) { + if (current(token) && request === readRequest.current) { + setRead(null); + if (err instanceof ApiRequestError && [401, 403].includes(err.status)) { invalidatePrivate(true); setReadError(ownerMessage); } + else { + generation.current++; setChecking(false); + session.setState(state => ({ edit: !state.edit ? null : state.edit.phase === "preparing" ? draftEdit(state.edit.draft) + : state.edit.phase === "committing" ? { ...state.edit, phase: "uncertain" } : state.edit })); + setReadError("Trust settings unavailable. No configured rule is confirmed active."); + } + } + } + return null; + }, [api, current, invalidatePrivate, session, setRead]); + useEffect(() => { + frameScope.current = { root, epoch: root.authLock.epoch() }; + generation.current++; epoch.current = root.authLock.epoch(); const lifetime = new AbortController(); controller.current = lifetime; + setRead(null); setError(""); setReadError(""); setNotice(""); setChecking(false); + if (!active) return () => lifetime.abort(); + void load(); + const refresh = () => { if (document.visibilityState === "visible") void load(); }; + const timer = setInterval(refresh, 30_000); window.addEventListener("focus", refresh); + const stop = root.authLock.state.subscribe(state => { + if (state.phase !== "active") { lifetime.abort(); invalidatePrivate(true); setRead(null); setReadError(""); opener.current = null; } + }); + return () => { + generation.current++; lifetime.abort(); clearInterval(timer); window.removeEventListener("focus", refresh); stop(); + session.setState(state => ({ edit: !state.edit ? null : state.edit.phase === "preparing" ? draftEdit(state.edit.draft) + : state.edit.phase === "committing" ? { ...state.edit, phase: "uncertain" } : state.edit })); + }; + }, [active, root, load, session, invalidatePrivate, setRead]); + useLayoutEffect(() => { + if (focusReview.current && operation) { focusReview.current = false; editor.current?.querySelector("[data-trust-review]")?.focus(); } + if (focusEditor.current && draft && read) { + focusEditor.current = false; + const field = [...(editor.current?.querySelectorAll("[data-trust-focus]") ?? [])].find(node => node.dataset.trustFocus === draft.focusField && !node.matches(":disabled")); + (field ?? editor.current?.querySelector("[data-trust-review], h4"))?.focus(); + } + if (restoreFocus.current && !draft) { restoreFocus.current = false; (opener.current?.isConnected ? opener.current : heading.current)?.focus(); } + }, [draft, operation, read]); + function rememberFocus(target: EventTarget | null, focused: boolean) { + const field = target instanceof HTMLElement ? target.closest("[data-trust-focus]")?.dataset.trustFocus : undefined; + session.setState(state => !state.edit || state.edit.draft.focused === focused && (!field || state.edit.draft.focusField === field) ? {} : { + edit: { ...state.edit, draft: { ...state.edit.draft, focused, focusField: field ?? state.edit.draft.focusField } }, + }); + } + function close() { session.setState({ edit: null }); setError(""); setChecking(false); restoreFocus.current = true; } + function leaveUnknown() { + const pending = session.getState().edit; + if (!pending?.operation || !["uncertain", "receipt-lost", "committing"].includes(pending.phase)) return; + generation.current++; setChecking(false); setRead(null); + session.setState(state => ({ edit: null, unknownOutcomes: state.unknownOutcomes + 1 })); + setError(""); setNotice(""); restoreFocus.current = true; void load(); + } + function start(action: Draft["action"], rule: TrustRule | null = null, repository = false) { + if (!read || !canMutate || busy || edit) return; + opener.current = document.activeElement instanceof HTMLElement ? document.activeElement : null; + setError(""); setNotice(""); focusEditor.current = true; + session.setState({ edit: draftEdit({ action, rule, instance: rule ? instanceAt(read, rule.id) : null, + kind: rule?.selector.kind ?? (repository ? "github_repository" : "web_origin"), providerId: "", target: rule ? trustTarget(rule.selector).replace(" · opaque tunnel", "") : "", + label: rule?.label ?? "", incoming: rule?.incomingContent ?? true, recipient: rule?.recipientWhileRestricted ?? false, revision: read.revision, hash: read.policyHash }) }); + } + async function prepare() { + const pending = session.getState().edit; + if (!pending || pending.phase !== "draft" || !read || busy || !canWrite || selectedChanged) return; + const value = pending.draft; let change: TrustChange; + try { + if (value.action === "remove") change = { action: "remove", ruleId: value.rule!.id }; + else { + const rule = TrustRuleSchema.parse({ id: value.rule?.id ?? crypto.randomUUID(), label: value.label, + selector: value.rule?.selector ?? (() => { + if (value.kind === "web_origin") return parseTrustOrigin(value.target); + if (value.kind === "tunnel_authority") return parseTrustTunnel(value.target); + const names = parseTrustGithub(value.target); + if (value.kind === "github_repository") { + if (!names.repository) throw new Error("Enter owner/repository for an exact repository rule."); + return { kind: value.kind, host: names.host, owner: names.owner, repository: names.repository, repositoryId: value.providerId }; + } + if (names.repository) throw new Error("Enter only the owner for an organization rule."); + return { kind: value.kind, host: names.host, owner: names.owner, ownerId: value.providerId }; + })(), incomingContent: value.incoming, recipientWhileRestricted: value.recipient }); + TrustedSourcesSchema.parse([...read.rules.filter(r => r.id !== rule.id), rule]); change = { action: value.action, rule }; + } + } catch (err) { setError(err instanceof Error ? err.message.includes("Duplicate trust") ? "This canonical target already has a rule. Edit that rule instead." : err.message : "Check the fields."); return; } + const token = generation.current; session.setState({ edit: { phase: "preparing", draft: value, operation: null } }); setError(""); + try { + const next = await api.trustPrepare(change, value.revision, value.hash, controller.current.signal); + if (current(token)) { focusReview.current = true; session.setState({ edit: { phase: "review", draft: value, operation: next } }); } + } catch (err) { if (current(token) && !ownerRefused(err)) { session.setState({ edit: draftEdit(value) }); setError(`Nothing saved. ${err instanceof Error ? err.message : "Review failed"}. Refresh the base and review again; your draft is kept.`); } } + } + function expiredReview(value: Draft) { + session.setState({ edit: draftEdit(value) }); setChecking(false); + setError("Review expired. Nothing was published. Refresh base and review again; your draft is kept."); + } + async function settle(next: TrustOperation) { + const pending = session.getState().edit; if (!pending) return; + const receipt = next.receipt; + if (receipt.stage === "prepared" && receipt.publication === "not_published" && next.review.expiresAt < Date.now()) { expiredReview(pending.draft); return; } + if (["prepared", "unknown", "file_published"].includes(receipt.stage)) { + session.setState({ edit: { phase: "uncertain", draft: pending.draft, operation: next } }); + setNotice("Save is not confirmed. Check its receipt or leave its outcome unknown; no automatic retry will publish again."); return; + } + if (receipt.publication === "proved") { + setNotice(`Publication proved. ${receipt.enforcement === "enforced" ? "Future admissions updated." : "Runtime enforcement unavailable."} Current rule: ${receipt.currentRule}. Historical events are unchanged.`); + close(); setRead(null); await load(); + } else if (receipt.stage === "refused") { session.setState({ edit: draftEdit(pending.draft) }); setError(`Nothing saved: ${receipt.reason ?? "refused"}. Refresh the base and review again; your draft is kept.`); } + else { session.setState({ edit: { phase: "uncertain", draft: pending.draft, operation: next } }); setError(`Change not confirmed: ${receipt.reason ?? receipt.stage}. Your draft is kept.`); } + } + async function commit() { + const pending = session.getState().edit; + if (!pending || pending.phase !== "review" || busy || !canWrite || selectedChanged) return; + if (pending.operation.receipt.stage === "prepared" && pending.operation.receipt.publication === "not_published" && pending.operation.review.expiresAt < Date.now()) { expiredReview(pending.draft); return; } + const token = generation.current; session.setState({ edit: { ...pending, phase: "committing" } }); + try { const next = await api.trustCommit(pending.operation, controller.current.signal); if (current(token)) await settle(next); } + catch (err) { if (current(token)) { + if (ownerRefused(err)) return; + if (err instanceof ApiRequestError && err.message === "request_expired") expiredReview(pending.draft); + else { session.setState({ edit: { ...pending, phase: "uncertain" } }); setError("Save outcome unknown. Check the receipt or leave it unknown without replaying it."); } + } } + } + async function check() { + const pending = session.getState().edit; + if (!pending?.operation || busy) return; const token = generation.current; setChecking(true); + try { const next = await api.trustReceipt(pending.operation.receipt.requestId, controller.current.signal); if (current(token)) await settle(next); } + catch (err) { if (current(token) && !ownerRefused(err)) { + session.setState({ edit: { ...pending, operation: pending.operation, phase: err instanceof ApiRequestError && err.status === 404 ? "receipt-lost" : "uncertain" } }); + setError("Receipt unavailable. Save outcome remains unknown. You can leave without replaying or confirming it."); + } } + finally { if (current(token)) setChecking(false); } + } + const canMutate = !!read && read.mutationAllowed === true && !read.error; + const canWrite = canMutate && !!draft && !!read && capabilitiesAllow(draft, read); + const conflict = "Selected rule changed or cannot be verified. Your draft is kept; cancel and select the current rule before reviewing again."; + const selectedChanged = !!draft && !!read && !selectionMatches(draft, read); + const capabilityError = canMutate && draft && !canWrite ? "Required enforcement capability is unavailable. Your draft is kept; review and Save are disabled." : ""; + const message = currentFrame ? readError || error || (selectedChanged ? conflict : capabilityError) : ""; + async function refreshBase() { + if (busy) return; const token = generation.current; setChecking(true); + try { + const next = await load(), pending = session.getState().edit; + if (!current(token) || !next || next.mutationAllowed !== true || next.error || !pending || pending.phase !== "draft") return; + if (!selectionMatches(pending.draft, next)) { setError(conflict); return; } + setDraft({ ...pending.draft, revision: next.revision, hash: next.policyHash, instance: pending.draft.rule ? instanceAt(next, pending.draft.rule.id) : null }); setError(""); + } finally { if (current(token)) setChecking(false); } + } + if (!active) return null; + return
    +

    Source trust and data sending

    +

    Rules apply to future input only. Settings never marks historical events safe or clears a chat's restrictions.

    + {message &&
    } +

    {unknownOutcomes > 0 && `${unknownOutcomes === 1 ? "A previous save outcome remains unknown" : `${unknownOutcomes} save outcomes remain unknown`}. No operation was replayed. `}{currentFrame ? notice : ""}

    + {!read ?

    No trust policy loaded.

    : <> + {!canMutate &&

    Read-only. {read.error ? "Policy invalid or unavailable; last-valid rules (or empty defaults if none) are shown. No new rule can be saved." : "Only a live password or passkey owner can change these rules."}

    } +

    Trust revision {read.revision} · Policy {read.policyHash ?? "built-in empty defaults"}

    + {!read.capabilities.originRules && } + {!read.capabilities.recipientRules &&

    Recipient enforcement unavailable; configured permission is not confirmed active.

    } + {([['Trusted origins', read.origins], ['Repositories and organizations', read.repositories]] as const).map(([title, rules]) =>
    +

    {title}

    + {title === "Repositories and organizations" && !read.capabilities.repositoryRules &&

    Repository enforcement unavailable. Repository and organization rules are disabled / unverified until qualified repository enforcement exists. Owner scopes include future repositories.

    } + {rules.length === 0 &&

    No rules configured. No sources gain trust from this list.

    } + {rules.map(rule =>
    +

    {rule.label}

    {trustTarget(rule.selector)}

    +

    Source trust: {rule.incomingContent ? "configured" : "off"} · Sending data while restricted: {rule.recipientWhileRestricted ? "configured" : "off"}

    + {rule.selector.kind === "tunnel_authority" &&

    Opaque connection scope; this is not verified HTTPS.

    } +
    +
    )} +
    )} + } + {draft &&
    rememberFocus(event.target, true)} onBlurCapture={event => { + if (event.relatedTarget instanceof Node && !event.currentTarget.contains(event.relatedTarget)) rememberFocus(null, false); + }}> +

    {draft.action === "remove" ? "Review removal" : "Trust rule"}

    + {draft.action === "remove" ?

    Remove {trustTarget(draft.rule!.selector)}? This affects future input and data sending only. Historical events remain unchanged; already dispatched operations cannot be recalled.

    : <> + + {draft.rule ?

    Target: {trustTarget(draft.rule.selector)}. To change a target, remove it and add the new one.

    : <> + + + {draft.kind.startsWith("github_") && } + {draft.kind === "github_owner" &&

    This broad scope includes present and future repositories currently owned by this namespace.

    } + {draft.kind === "tunnel_authority" &&

    Trust covers the whole opaque connection, not verified HTTPS content.

    } + } +
    setDraft({ ...draft, incoming: !draft.incoming })} /> + setDraft({ ...draft, recipient: !draft.recipient })} />
    + } + {operation && canMutate &&

    Review exact policy change

    Source trust and recipient permission are independent. Review both in these exact bytes before Save. This does not resolve historical events.

    {operation.review.diff}
    } +
    +
    + {edit?.phase === "committing" &&

    Save is pending. It may still finish if you leave its outcome unknown.

    } +
    } + +
    ; +} diff --git a/packages/ui-react/src/lib/api-client.ts b/packages/ui-react/src/lib/api-client.ts index 4dccf3d716..1d4b44a9c4 100644 --- a/packages/ui-react/src/lib/api-client.ts +++ b/packages/ui-react/src/lib/api-client.ts @@ -1,3 +1,6 @@ +import { safetyFuturePreparedSchema, safetyFutureResultSchema } from "@schlessera/brain-ui-sdk/schemas"; +import type { SafetyFuturePrepare, SafetyFutureCommit } from "@schlessera/brain-ui-sdk/protocol"; +import type { TrustSettingsRead, TrustOperation, TrustChange } from "./trust-settings.js"; import type { AgentPolicyRead, ApifyPolicyChange, ApifyPolicyProposalRead, ApifySettingsRead } from "@schlessera/brain-ui-sdk/protocol"; import { POLICY_CHANGE_REVIEW_SCHEMA } from "@schlessera/brain-ui-sdk/tool-contracts"; import { apiBase } from "./backend.js"; @@ -346,7 +349,7 @@ export function createBrainApi( }); if (!res.ok) { const body = await res.json().catch(() => ({ error: res.statusText })); - throw new ApiRequestError(body.error || `HTTP ${res.status}`, res.status, body.errors ?? []); + throw new ApiRequestError(body.error || body.reason || body.code || `HTTP ${res.status}`, res.status, body.errors ?? []); } return res; } @@ -364,10 +367,17 @@ export function createBrainApi( } return { + safetyFutureStatus: async (body:{version:1;session:import("@schlessera/brain-ui-sdk/protocol").SafetySessionKey;occurrenceId:string},signal:AbortSignal) => safetyFutureResultSchema.nullable().parse(await fetchJson(`/sessions/${encodeURIComponent(body.session.sessionId)}/safety/reviews/future/status`,{method:"POST",body:JSON.stringify(body),signal})), + safetyFuturePrepare: async (body:SafetyFuturePrepare,signal:AbortSignal) => safetyFuturePreparedSchema.parse(await fetchJson(`/sessions/${encodeURIComponent(body.session.sessionId)}/safety/reviews/future/prepare`,{method:"POST",body:JSON.stringify(body),signal})), + safetyFutureCommit: async (sessionId:string,body:SafetyFutureCommit,signal:AbortSignal) => safetyFutureResultSchema.parse(await fetchJson(`/sessions/${encodeURIComponent(sessionId)}/safety/reviews/future/commit`,{method:"POST",body:JSON.stringify(body),signal})), safetyPrepare: (body:SafetyReviewBody,signal:AbortSignal)=>safetyReview(body,null,signal), safetyCommit: (requestId:string,body:SafetyReviewBody,signal:AbortSignal)=>safetyReview(body,requestId,signal), turnJournal: (sessionId: string, turnId: string, signal?: AbortSignal) => fetchJson(`/sessions/${encodeURIComponent(sessionId)}/turns/${encodeURIComponent(turnId)}/journal`, { signal }), turnJournalPreview: (sessionId: string, turnId: string, sequence: number, signal?: AbortSignal) => fetchJson<{ inline: boolean; before?: string; after?: string; reason?: string; beforeBytes?: number; afterBytes?: number }>(`/sessions/${encodeURIComponent(sessionId)}/turns/${encodeURIComponent(turnId)}/journal/${sequence}/preview`, { signal }), + trustSettings: (signal?: AbortSignal) => fetchJson("/trust-settings", { cache: "no-store", signal }), + trustPrepare: (change: TrustChange, expectedTrustRevision: string, expectedPolicyHash: string | null, signal?: AbortSignal) => fetchJson("/trust-settings/prepare", { method: "POST", body: JSON.stringify({ version: 1, change, expectedTrustRevision, expectedPolicyHash }), signal }), + trustCommit: (operation: TrustOperation, signal?: AbortSignal) => fetchJson("/trust-settings/commit", { method: "POST", body: JSON.stringify({ version: 1, requestId: operation.receipt.requestId, reviewId: operation.review.reviewId, reviewedBytesHash: operation.review.reviewedBytesHash }), signal }), + trustReceipt: (requestId: string, signal?: AbortSignal) => fetchJson(`/trust-settings/${encodeURIComponent(requestId)}`, { cache: "no-store", signal }), agentPolicy: (signal?: AbortSignal) => fetchJson("/agent-policy", { cache: "no-store", ...(signal ? { signal } : {}) }), policyProposal: async (turnId: string, requestId: string, sessionId: string | null, signal?: AbortSignal) => POLICY_CHANGE_REVIEW_SCHEMA.parse(await fetchJson(`/policy-proposals/${encodeURIComponent(turnId)}/${encodeURIComponent(requestId)}${sessionId ? `?session=${encodeURIComponent(sessionId)}` : ""}`, { cache: "no-store", ...(signal ? { signal } : {}) })), diff --git a/packages/ui-react/src/lib/safety-client.ts b/packages/ui-react/src/lib/safety-client.ts index fb8003254a..edc473d25c 100644 --- a/packages/ui-react/src/lib/safety-client.ts +++ b/packages/ui-react/src/lib/safety-client.ts @@ -5,11 +5,12 @@ import type { BrainUiServices } from "../root.js"; export function createSafetyClient(root:BrainUiServices,send:(message:ClientMessage)=>boolean){ let target:SafetyTarget|null=null,requestId:string|null=null,disposed=false,awaitingPage=false,capacityRecoveryUsed=false; const store=root.stores.safety; + let admissions=false; function read(next:SafetyTarget):void{ if(disposed||!store.getState().supported)return; target=next;requestId=crypto.randomUUID();awaitingPage=true;store.getState().begin(requestId); send({type:"safety_unsubscribe",version:1}); - send({type:"safety_read",version:1,requestId,target,...(store.getState().entryCorrelation?{includeEntries:true as const}:{})}); + send({type:"safety_read",version:1,requestId,target,...(store.getState().entryCorrelation?{includeEntries:true as const}:{}),...(admissions?{includeAdmissions:true as const}:{})}); } function selected(): void { capacityRecoveryUsed=false; @@ -29,14 +30,17 @@ export function createSafetyClient(root:BrainUiServices,send:(message:ClientMess frame(msg:ServerMessage):boolean{ if(disposed)return false; if(msg.type==="server_hello"){ - requestId=null;store.getState().reset(msg.capabilities?.sessionSafetyHistory===true&&msg.safetyCapabilities?.read===true,msg.safetyCapabilities??null,msg.capabilities?.sessionSafetyEntryCorrelation===true,msg.principalKey?`host:${msg.principalKey}`:`unbound:${crypto.randomUUID()}`);selected();return false; + admissions=msg.capabilities?.sessionSafetyAdmissionEvidence===true; + const future=msg.capabilities?.sessionSafetyFutureRules===true&&msg.safetyCapabilities?.review===true; + const capabilities=msg.safetyCapabilities?{...msg.safetyCapabilities,originRules:future,recipientRules:future}:null; + requestId=null;store.getState().reset(msg.capabilities?.sessionSafetyHistory===true&&msg.safetyCapabilities?.read===true,capabilities,msg.capabilities?.sessionSafetyEntryCorrelation===true,msg.principalKey?`host:${msg.principalKey}`:`unbound:${crypto.randomUUID()}`);selected();return false; } if(msg.type==="chat_retired"){store.getState().retire(msg.sessionId,msg.historyOwnerIds);if(target&&"sessionId" in target&&target.sessionId===msg.sessionId){requestId=null;target=null;store.getState().unavailable("retired");}return false;} if(msg.type==="safety_history"){ if(msg.requestId!==requestId||!target||!awaitingPage)return true; if(msg.page.cursor!==store.getState().nextCursor)return true; if(!store.getState().page(msg.requestId,msg.page)){read(target);return true;} - if(msg.page.nextCursor)send({type:"safety_read",version:1,requestId:msg.requestId,target,cursor:msg.page.nextCursor,...(store.getState().entryCorrelation?{includeEntries:true as const}:{})}); + if(msg.page.nextCursor)send({type:"safety_read",version:1,requestId:msg.requestId,target,cursor:msg.page.nextCursor,...(store.getState().entryCorrelation?{includeEntries:true as const}:{}),...(admissions?{includeAdmissions:true as const}:{})}); else{awaitingPage=false;send({type:"safety_subscribe",version:1,requestId:msg.requestId,identity:msg.page.identity,afterRevision:msg.page.highWater,snapshotId:msg.page.snapshotId});}return true; } if(msg.type==="safety_update"){ diff --git a/packages/ui-react/src/lib/safety-reviewer.ts b/packages/ui-react/src/lib/safety-reviewer.ts index 3ce53c0180..53d00f2315 100644 --- a/packages/ui-react/src/lib/safety-reviewer.ts +++ b/packages/ui-react/src/lib/safety-reviewer.ts @@ -1,24 +1,60 @@ -import type { SafetyReviewBody } from "@schlessera/brain-ui-sdk/protocol"; +import type { SafetyReviewBody, SafetyFuturePrepared } from "@schlessera/brain-ui-sdk/protocol"; import type { BrainUiServices } from "../root.js"; import { safetyEvidence } from "./safety-evidence.js"; -export type SafetyReviewProgress={stage:"pending"|"committed"|"refused"|"unknown";message:string}; +export type SafetyReviewProgress={stage:"pending"|"review"|"committed"|"partial"|"refused"|"unknown";message:string}; /** Ephemeral, explicit user action only. No persistence, retry or optimistic clear. */ export function createSafetyReviewer(root:BrainUiServices,changed:(value:SafetyReviewProgress)=>void) { let controller:AbortController|null=null,disposed=false,committing=false; const cancel=()=>{ - if(!controller||controller.signal.aborted)return; - controller.abort(); + if(!controller&&!prepared)return; + controller?.abort();prepared=null; if(!disposed)changed({stage:committing?"unknown":"refused",message:committing?"Review cancelled; the result is unknown. Refresh evidence to check. No decision will be sent again.":"Review cancelled because its owner or evidence changed. No decision was sent."}); }; const offSafety=root.stores.safety.subscribe((s,old)=>{ - if(s.status!=="ready"||s.requestId!==old.requestId||JSON.stringify(s.identity)!==JSON.stringify(old.identity)||!s.capabilities?.review)cancel(); + if(s.status!=="ready"||s.requestId!==old.requestId||(!controller&&s.revision!==old.revision)||JSON.stringify(s.identity)!==JSON.stringify(old.identity)||!s.capabilities?.review)cancel(); }); const offChat=root.stores.chat.subscribe((s,old)=>{if(s.activeSessionId!==old.activeSessionId)cancel();}); const offAuth=root.authLock.state.subscribe(s=>{if(s.phase!=="active")cancel();}); + let prepared:SafetyFuturePrepared|null=null,preparedEpoch:number|null=null,preparedRevision:string|null=null,preparedTarget:{session:SafetyReviewBody["session"];occurrenceId:string}|null=null; + const discardFuture=()=>{prepared=null;preparedTarget=null;preparedEpoch=null;preparedRevision=null;}; return { + cancelFuture:discardFuture, + async prepareFuture(occurrenceId:string,recipientWhileRestricted:boolean):Promise{ + const s=root.stores.safety.getState(),identity=s.identity,epoch=root.authLock.epoch(); + if(disposed||controller||s.status!=="ready"||!s.capabilities?.review||!s.capabilities?.originRules||!identity||!("sessionId" in identity)||root.stores.chat.getState().activeSessionId!==identity.sessionId||root.authLock.state.getState().phase!=="active")return null; + prepared=null; + const target={session:{...identity},occurrenceId}; + const owned=controller=new AbortController(); + changed({stage:"pending",message:"Preparing the exact future rule…"}); + try{ + const result=await root.api.safetyFuturePrepare({version:1,session:identity,occurrenceId,expectedEvidenceRevision:s.revision,verdict:"safe",future:{incomingContent:true,recipientWhileRestricted}},owned.signal); + if(disposed||owned.signal.aborted||root.authLock.epoch()!==epoch)return null; + if(result.occurrenceId!==target.occurrenceId||JSON.stringify(result.session)!==JSON.stringify(target.session)||result.rule.requestId!==result.requestId||!root.stores.safety.getState().capabilities?.originRules||root.stores.safety.getState().requestId!==s.requestId||root.stores.safety.getState().revision!==s.revision){changed({stage:"refused",message:"The evidence changed. Read current evidence before reviewing again."});return null;} + prepared=result;preparedTarget=target;preparedEpoch=epoch;preparedRevision=s.revision;changed({stage:"review",message:"Review the exact policy change before saving."});return result; + }catch{if(!owned.signal.aborted)changed({stage:"refused",message:"Could not prepare future trust. Refresh evidence before trying again."});return null;} + finally{if(controller===owned)controller=null;} + }, + async commitFuture():Promise{ + const p=prepared,target=preparedTarget;if(disposed||controller||!p||!target)return; + const s=root.stores.safety.getState(); + if(s.revision!==preparedRevision||root.authLock.epoch()!==preparedEpoch||root.authLock.state.getState().phase!=="active"||s.status!=="ready"||!s.capabilities?.originRules||JSON.stringify(s.identity)!==JSON.stringify(target.session)||root.stores.chat.getState().activeSessionId!==target.session.sessionId){prepared=null;return;} + const owned=controller=new AbortController();committing=true;prepared=null; + changed({stage:"pending",message:"Saving the reviewed rule, then recording this trigger's verdict…"}); + try{ + const result=await root.api.safetyFutureCommit(target.session.sessionId,{version:1,requestId:p.requestId,reviewId:p.review.reviewId,reviewedBytesHash:p.review.reviewedBytesHash},owned.signal); + if(disposed||owned.signal.aborted)return; + if(result.requestId!==p.requestId||result.occurrenceId!==target.occurrenceId||JSON.stringify(result.session)!==JSON.stringify(target.session)||result.verdict&&(result.verdict.occurrenceId!==target.occurrenceId||JSON.stringify(result.verdict.session)!==JSON.stringify(target.session)))throw new Error("Different future review receipt"); + // Completion is a historical operation fact. Only refreshed status + // reports current rule presence; only live evidence reports the verdict. + changed({stage:result.stage==="verdict_committed"?"committed":result.stage==="partial"?"partial":result.stage==="unknown"?"unknown":"refused",message:result.stage==="verdict_committed"?"This operation recorded a safe verdict. Reading current restrictions…":result.rule.publication==="proved"?"The rule was saved; this operation did not complete its verdict. Reading current restrictions…":`Publication was ${result.rule.publication==="unknown"?"not confirmed":"refused"}. This operation did not record a verdict. Fresh review is required.`}); + controller=null;s.refresh(); + }catch{if(!owned.signal.aborted)changed({stage:"unknown",message:"The result is unknown. Refresh evidence and Settings; this operation will not be sent again."});} + finally{if(controller===owned)controller=null;committing=false;} + }, async markSafe(occurrenceId:string):Promise { if(disposed||controller)return; + discardFuture(); const s=root.stores.safety.getState(),identity=s.identity,epoch=root.authLock.epoch(),requestId=s.requestId; const evidence=safetyEvidence(s.records).get(occurrenceId); if(s.status!=="ready"||!s.capabilities?.review||!identity||!("sessionId" in identity)||root.stores.chat.getState().activeSessionId!==identity.sessionId|| diff --git a/packages/ui-react/src/lib/trust-settings.ts b/packages/ui-react/src/lib/trust-settings.ts new file mode 100644 index 0000000000..746869332c --- /dev/null +++ b/packages/ui-react/src/lib/trust-settings.ts @@ -0,0 +1,24 @@ +/** Concrete Settings publication DTOs; the host remains the authority. */ +export type TrustSelector = + | { kind: "web_origin"; scheme: "http" | "https"; host: string; port: number } + | { kind: "tunnel_authority"; host: string; port: number } + | { kind: "github_repository"; host: "github.com"; owner: string; repository: string; repositoryId: string } + | { kind: "github_owner"; host: "github.com"; owner: string; ownerId: string }; +export interface TrustRule { id: string; label: string; selector: TrustSelector; incomingContent: boolean; recipientWhileRestricted: boolean } +export interface TrustPolicy { revision: string; policyHash: string | null; error: string | null; rules: TrustRule[] } +export interface TrustCapabilities { originRules: boolean; repositoryRules: boolean; recipientRules: boolean; repositoryIdentity: boolean; readOnlyReason: string | null } +export interface TrustSettingsRead extends TrustPolicy { origins: TrustRule[]; repositories: TrustRule[]; capabilities: TrustCapabilities; mutationAllowed?: boolean; instances?: Record } +export type TrustChange = { action: "create" | "edit"; rule: TrustRule } | { action: "remove"; ruleId: string }; +export interface TrustOperation { + receipt: { requestId: string; stage: "prepared" | "file_published" | "committed" | "partial" | "unknown" | "refused"; publication: "not_published" | "proved" | "unknown"; currentRule: "present" | "removed" | "changed" | "unknown"; enforcement: "enforced" | "unavailable"; reason: string | null }; + review: { reviewId: string; reviewedBytesHash: string; base: string | null; proposed: string; diff: string; expiresAt: number; includesFutureRepositories: boolean }; + policy: TrustPolicy; capabilities: TrustCapabilities; +} +export function trustTarget(selector: TrustSelector): string { + switch (selector.kind) { + case "web_origin": return `${selector.scheme}://${selector.host}:${selector.port}`; + case "tunnel_authority": return `${selector.host}:${selector.port} · opaque tunnel`; + case "github_repository": return `github.com/${selector.owner}/${selector.repository} · repository ID ${selector.repositoryId}`; + case "github_owner": return `github.com/${selector.owner} · owner ID ${selector.ownerId} · includes future repositories`; + } +} diff --git a/packages/ui-react/tests/browser/hit-reach.trust-settings.pointer.tsx b/packages/ui-react/tests/browser/hit-reach.trust-settings.pointer.tsx new file mode 100644 index 0000000000..b8a4d19e30 --- /dev/null +++ b/packages/ui-react/tests/browser/hit-reach.trust-settings.pointer.tsx @@ -0,0 +1,563 @@ +import { useLayoutEffect, type ReactNode } from "react"; +import { createBrainUiRoot } from "../../src/root.js"; +import { BrainUiProvider } from "../../src/root-context.js"; +/** + * Security Settings transition model (review round 2). + * Review = a host-prepared exact-byte proposal, with no publication yet. + * Unknown outcomes are retained as unknown when their editor is left. + * + * | ID | From | Event / evidence | To / invariant | + * | T01 | idle | owner + capability, Add/Edit/Remove | draft | + * | T02 | draft | prepare succeeds | preparing -> review (prepared) | + * | T03 | review | Save + proved receipt | committing -> idle, fresh facts | + * | T04 | draft/review | Cancel | idle, focus returns | + * | T05 | committing | reply lost | uncertain, no replay | + * | T06 | uncertain | proved receipt | idle, truthful current rule | + * | T07 | review/uncertain | expired unsent or prepared/not_published | draft | + * | T08 | uncertain | unknown receipt, including expired | uncertain | + * | T09 | uncertain | receipt permanently 404 | receipt-lost | + * | T10 | uncertain/receipt-lost | Leave as outcome unknown | idle + unknown notice | + * | T11 | draft/review/uncertain/receipt-lost | read denied (401/403) | idle, no protected draft/bytes; dispatched saves stay unknown | + * | T12 | any | auth epoch/root replaced | idle, no protected state; same-root unknown count retained | + * | T13 | preparing/review | readable but owner unavailable | draft, no private/late review | + * | T14 | any edit | read unavailable then recovers | suspended writes -> same edit; preparing -> draft, committing -> uncertain | + * | T15 | draft/review | required enforcement withdrawn | same edit, writes disabled | + * | T16 | capability-blocked | required enforcement restored | same intent, writes enabled | + * | T17 | draft | unrelated revision; selected bytes + instance unchanged | refresh base, preserve intent | + * | T18 | draft | selected bytes/instance changed or disappeared | conflict, explicit re-selection | + * | T19 | preparing/review | policy base changes | draft, discard stale preview/reply | + * | T20 | removal draft/review | enforcement withdrawn | revocation remains available | + * | T21 | any edit | responsive remount | preserve edit; preparing -> draft, committing -> uncertain | + * | T22 | any readable state | list refresh / Save | refresh enforcing facts, no stale current claim | + * | T23 | committing / receipt lookup pending | Leave as outcome unknown | idle + unknown notice; late reply fenced | + */ +import { expect, inject, test, vi, type TestContext } from "vitest"; +import { commands, page, userEvent } from "vitest/browser"; +import { flushSync } from "react-dom"; +import { PasskeyList } from "../../src/components/settings/passkey-list.js"; +import { TrustSettingsSection } from "../../src/components/settings/trust-settings-section.js"; +import type { TrustRule, TrustSettingsRead, TrustOperation, TrustChange } from "../../src/lib/trust-settings.js"; +import { mount, reach } from "./hit-reach-scene.js"; + +const button = (name: string | RegExp) => page.getByRole("button", { name, exact: typeof name === "string" }); +const rule = { id: "ithaca", label: "Ithaca", incomingContent: true, recipientWhileRestricted: false, selector: { kind: "web_origin", scheme: "https", host: "example.org", port: 443 } } satisfies TrustRule; +async function scene(ctx: TestContext, width: number, theme: string, rules: TrustRule[] = []) { + let read: TrustSettingsRead = { revision: "0", policyHash: null, error: null, instances: Object.fromEntries(rules.map(r => [r.id, "birth-0"])), rules, origins: rules.filter(r => !r.selector.kind.startsWith("github_")), repositories: rules.filter(r => r.selector.kind.startsWith("github_")), mutationAllowed: true, + capabilities: { originRules: true, recipientRules: true, repositoryRules: false, repositoryIdentity: true, readOnlyReason: null } }; + const calls: { path: string; body?: Record }[] = []; + let change: TrustChange, operation: TrustOperation, stale = false, loseReply = false; + let listFailure = 0, policyFailure = 0, receiptFailure = 0, commitFailure = 0, expired = false, dropCommit = false, prepareWait: Promise | undefined, listWait: Promise | undefined; + let releaseList: (() => void) | undefined; + let commitWait: Promise | undefined, policyWait: Promise | undefined, receiptWait: Promise | undefined; + let releaseReceipt: (() => void) | undefined; + let releaseCommit: (() => void) | undefined, releasePolicy: (() => void) | undefined; + let prepareReplies = 0, commitEnforced = true; + let releasePrepare: (() => void) | undefined; + const s = await mount(ctx, width, async (url, init) => { + const path = new URL(url, location.href).pathname, body = init?.body ? JSON.parse(String(init.body)) : undefined; calls.push({ path, body }); + if (path.endsWith("/agent-policy")) { + const hash = read.policyHash; if (policyWait) await policyWait; + return policyFailure ? Response.json({ reason: "unavailable" }, { status: policyFailure }) : Response.json({ source: hash ? "policy" : "default", hash, + path: "context/policies/governance.md", errors: [], warnings: [], profiles: { interactive: "governed", voice: "strict" }, protectedPaths: [], workerLimits: null }); + } + if (path.endsWith("/trust-settings/prepare")) { + if (stale) return Response.json({ error: "stale_base" }, { status: 409 }); + change = body.change; + operation = { receipt: { requestId: "ithaca-review", stage: "prepared", publication: "not_published", currentRule: "unknown", enforcement: "unavailable", reason: null }, + review: { reviewId: "ithaca-bytes", reviewedBytesHash: "a".repeat(64), base: null, proposed: JSON.stringify(change), diff: JSON.stringify(change), expiresAt: Date.now() + 60_000, includesFutureRepositories: false }, policy: read, capabilities: read.capabilities }; + if (prepareWait) await prepareWait; prepareReplies++; + return Response.json(operation); + } + if (path.endsWith("/trust-settings/commit")) { + if (commitFailure) return Response.json({ reason: "unauthorized" }, { status: commitFailure }); + if (dropCommit) throw new Error("connection ended before commit"); + if (expired) return Response.json({ reason: "request_expired" }, { status: 409 }); + const selected = change; + read.rules = selected.action === "remove" ? read.rules.filter(r => r.id !== selected.ruleId) : [...read.rules.filter(r => r.id !== selected.rule.id), selected.rule]; + read = { ...read, revision: String(Number(read.revision) + 1), policyHash: "a".repeat(64), origins: read.rules.filter(r => !r.selector.kind.startsWith("github_")), repositories: read.rules.filter(r => r.selector.kind.startsWith("github_")) }; + operation = { ...operation, receipt: { ...operation.receipt, stage: commitEnforced ? "committed" : "partial", publication: "proved", currentRule: change.action === "remove" ? "removed" : "present", enforcement: commitEnforced ? "enforced" : "unavailable" } }; + if (commitWait) await commitWait; + if (loseReply) throw new Error("lost reply"); + return Response.json(operation); + } + if (path.endsWith("/trust-settings/ithaca-review")) { if (receiptWait) await receiptWait; return receiptFailure ? Response.json({ reason: "unavailable" }, { status: receiptFailure }) : Response.json(operation); } + if (listWait) await listWait; + return listFailure ? Response.json({ reason: "read_unavailable" }, { status: listFailure }) : Response.json(read); + }); + s.ui.stores.connection.getState().setVpnStatus("connected", "odysseus"); + document.documentElement.dataset.theme = theme; + s.draw(); + await expect.element(button("Add origin")).toBeVisible(); + return { ...s, calls, setRead(next: Partial) { read = { ...read, ...next, ...(next.rules ? { origins: next.rules.filter(r => !r.selector.kind.startsWith("github_")), repositories: next.rules.filter(r => r.selector.kind.startsWith("github_")) } : {}) }; }, + holdReceipt() { receiptWait = new Promise(resolve => { releaseReceipt = resolve; }); }, + releaseReceipt() { releaseReceipt?.(); }, + holdCommit() { commitWait = new Promise(resolve => { releaseCommit = resolve; }); }, + releaseCommit() { releaseCommit?.(); }, + holdPolicy() { policyWait = new Promise(resolve => { releasePolicy = resolve; }); }, + releasePolicy() { releasePolicy?.(); }, + failPolicy(status: number) { policyFailure = status; }, + unavailableCommit() { commitEnforced = false; }, + prepareReplies() { return prepareReplies; }, + failReceipt(status: number) { receiptFailure = status; }, + rejectCommit(status: number) { commitFailure = status; }, + loseBeforeCommit() { dropCommit = true; }, + holdList() { listWait = new Promise(resolve => { releaseList = resolve; }); }, + releaseList() { releaseList?.(); }, + failList(status: number) { listFailure = status; }, + expireHostReview() { expired = true; operation.review.expiresAt = Date.now() - 1; }, + unknownExpiredReceipt() { operation.receipt.stage = "unknown"; operation.receipt.publication = "unknown"; operation.review.expiresAt = Date.now() - 1; }, + holdPrepare() { prepareWait = new Promise(resolve => { releasePrepare = resolve; }); }, + releasePrepare() { releasePrepare?.(); }, stale(value: boolean) { stale = value; }, loseReply() { loseReply = true; } }; +} +for (const width of [320, 1280]) for (const theme of ["dark", "light"]) { + test(`T01 T02 T03 trust canonical CRUD, exact review and independent permission at ${width} ${theme}`, async ctx => { + const s = await scene(ctx, width, theme); + if (inject("railPointer") === "fine") await button("Add origin").click(); + else { const node = button("Add origin").element(); node.scrollIntoView({ block: "center" }); const r = node.getBoundingClientRect(); await commands.rankTap({ x: r.x + r.width / 2, y: r.y + r.height / 2 }); } + await expect.element(page.getByRole("checkbox", { name: /Allow sending data while restricted/ })).not.toBeChecked(); + await page.getByLabelText("Origin", { exact: true }).fill("https://example.org/path"); + await button("Review change").click(); + await expect.element(page.getByRole("alert")).toHaveTextContent("bare HTTP(S) origin"); + await expect.element(page.getByLabelText("Origin", { exact: true })).toHaveValue("https://example.org/path"); + await page.getByLabelText("Origin", { exact: true }).fill("https://EXAMPLE.org/"); + await page.getByLabelText("Label", { exact: true }).fill("Ithaca"); + await button("Review change").click(); + await expect.element(button("Save rule")).toBeVisible(); + expect(s.calls.filter(c => c.path.endsWith("/commit"))).toHaveLength(0); + expect(s.host.textContent).toContain('"recipientWhileRestricted":false'); + await expect.poll(() => document.activeElement?.textContent).toBe("Review exact policy change"); + reach(s.host, "trust review"); + expect(document.documentElement.scrollWidth).toBeLessThanOrEqual(innerWidth); + await button("Save rule").click(); + await expect.element(button("Edit https://example.org:443")).toBeVisible(); + expect(s.host.scrollWidth).toBeLessThanOrEqual(width); + expect(document.documentElement.scrollWidth).toBeLessThanOrEqual(innerWidth); + await button("Edit https://example.org:443").click(); + await page.getByLabelText("Label", { exact: true }).fill("Home harbor"); + await page.getByRole("checkbox", { name: /Allow sending data while restricted/ }).click(); + await button("Review change").click(); await button("Save rule").click(); + await expect.poll(() => s.host.textContent).toContain("Home harbor"); + await button("Remove https://example.org:443").click(); + expect(s.host.textContent).toContain("Historical events remain unchanged"); + await button("Review change").click(); await button("Remove rule").click(); + await expect.element(button("Add origin")).toBeEnabled(); + expect(s.calls.filter(c => c.path.includes("safety"))).toHaveLength(0); + expect(s.host.textContent).toContain("Current rule: removed"); + }); + test(`T05 T06 T21 trust stale base, remount and lost save never discard or republish at ${width} ${theme}`, async ctx => { + const s = await scene(ctx, width, theme); + await button("Add origin").click(); + await page.getByLabelText("Origin", { exact: true }).fill("https://example.org"); + s.stale(true); await button("Review change").click(); + await expect.element(page.getByRole("alert")).toHaveTextContent("stale_base"); + s.draw(null); s.draw(); + await expect.element(page.getByLabelText("Origin", { exact: true })).toHaveValue("https://example.org"); + s.stale(false); await button("Refresh base").click(); await button("Review change").click(); + s.loseReply(); await button("Save rule").click(); + await expect.element(button("Check save receipt")).toBeVisible(); + s.draw(null); s.draw(); + await button("Check save receipt").click(); + await expect.element(button("Edit https://example.org:443")).toBeVisible(); + expect(s.calls.filter(c => c.path.endsWith("/commit"))).toHaveLength(1); + }); +} +test("read-only, missing capability, invalid policy and auth loss never expose mutation", async ctx => { + const s = await scene(ctx, 320, "light", [rule, { ...rule, id: "argo", selector: { kind: "github_owner", host: "github.com", owner: "odysseus", ownerId: "12" } }]); + await expect.element(button("Add repository or organization")).toBeDisabled(); + expect(s.host.textContent).toContain("includes future repositories"); + await button("Add origin").click(); await page.getByLabelText("Label", { exact: true }).fill("Private draft"); + s.setRead({ mutationAllowed: false, error: "policy_unavailable" }); window.dispatchEvent(new Event("focus")); + await expect.element(button("Review change")).toBeDisabled(); + await expect.element(page.getByLabelText("Label", { exact: true })).toHaveValue("Private draft"); + expect(s.host.textContent).toContain("last-valid rules"); + flushSync(() => { void s.ui.authLock.expire("revoked"); }); + await expect.poll(() => s.host.querySelectorAll("input").length).toBe(0); +}); + +test("duplicate canonical targets stay actionable and cancel returns focus", async ctx => { + const s = await scene(ctx, 320, "dark", [rule]); + await button("Add origin").click(); await page.getByLabelText("Origin", { exact: true }).fill("https://EXAMPLE.org/"); + await button("Review change").click(); + await expect.element(page.getByRole("alert")).toHaveTextContent("already has a rule"); + await button("Cancel").click(); + await expect.poll(() => document.activeElement?.getAttribute("aria-label") ?? document.activeElement?.textContent).toContain("Add origin"); + expect(s.calls.filter(c => c.path.endsWith("/prepare"))).toHaveLength(0); +}); + +test("mixed-version hosts are read-only and tunnel scope never looks like HTTPS", async ctx => { + const s = await scene(ctx, 320, "light", [{ ...rule, selector: { kind: "tunnel_authority", host: "example.org", port: 443 } }]); + expect(s.host.textContent).toContain("opaque tunnel"); + expect(s.host.textContent).toContain("not verified HTTPS"); + s.setRead({ mutationAllowed: undefined }); window.dispatchEvent(new Event("focus")); + await expect.element(button("Add origin")).toBeDisabled(); + expect(s.host.textContent).toContain("Read-only"); + expect(s.calls.filter(c => c.path.endsWith("/prepare"))).toHaveLength(0); +}); + +test("T04 keyboard review and cancel retain focus without changing the policy", async ctx => { + const s = await scene(ctx, 320, "dark"); + (button("Add origin").element() as HTMLElement).focus(); await userEvent.keyboard("{Enter}"); + await page.getByLabelText("Origin", { exact: true }).fill("https://example.org"); + (button("Review change").element() as HTMLElement).focus(); await userEvent.keyboard("{Enter}"); + await expect.poll(() => document.activeElement?.textContent).toBe("Review exact policy change"); + (button("Cancel").element() as HTMLElement).focus(); await userEvent.keyboard("{Enter}"); + await expect.poll(() => document.activeElement?.textContent).toContain("Add origin"); + expect(s.calls.filter(c => c.path.endsWith("/commit"))).toHaveLength(0); +}); + +for (const kind of ["github_repository", "github_owner"] as const) test(`qualified host exposes bounded ${kind} CRUD without recipient permission`, async ctx => { + const s = await scene(ctx, 320, "light"); + s.setRead({ capabilities: { originRules: true, recipientRules: true, repositoryRules: true, repositoryIdentity: true, readOnlyReason: null } }); + window.dispatchEvent(new Event("focus")); + await expect.element(button("Add repository or organization")).toBeEnabled(); + await button("Add repository or organization").click(); + if (kind === "github_owner") await page.getByRole("combobox", { name: /Target type/ }).selectOptions("github_owner"); + await page.getByLabelText(kind === "github_owner" ? "GitHub owner" : "GitHub owner/repository", { exact: true }).fill(kind === "github_owner" ? "Odysseus" : "Odysseus/Navigation.git"); + await page.getByLabelText("Stable provider ID (verified independently by the host)", { exact: true }).fill("12"); + await expect.element(page.getByRole("checkbox", { name: /Allow sending data while restricted/ })).toBeDisabled(); + if (kind === "github_owner") expect(s.host.textContent).toContain("includes present and future repositories"); + await button("Review change").click(); + const prepared = s.calls.find(c => c.path.endsWith("/prepare"))!.body!.change as TrustChange; + expect(prepared).toMatchObject({ action: "create", rule: { incomingContent: true, recipientWhileRestricted: false, selector: { kind, owner: "odysseus" } } }); + await button("Save rule").click(); + const target = kind === "github_owner" ? "github.com/odysseus · owner ID 12 · includes future repositories" : "github.com/odysseus/navigation · repository ID 12"; + await button(`Edit ${target}`).click(); await page.getByLabelText("Label", { exact: true }).fill("Argo"); + await button("Review change").click(); await button("Save rule").click(); + await expect.poll(() => s.host.textContent).toContain("Argo"); + await button(`Remove ${target}`).click(); await button("Review change").click(); await button("Remove rule").click(); + await expect.element(button("Add repository or organization")).toBeEnabled(); + expect(s.host.textContent).not.toContain(target); +}); + +async function prepared(ctx: TestContext) { + const s = await scene(ctx, 320, "dark"); + await button("Add origin").click(); await page.getByLabelText("Origin", { exact: true }).fill("https://example.org"); + await button("Review change").click(); await expect.element(button("Save rule")).toBeVisible(); + return s; +} + +test("T13 F2 owner downgrade removes the private review, including a late prepare reply", async ctx => { + const s = await prepared(ctx); + expect(s.host.querySelector("pre")).not.toBeNull(); + s.setRead({ mutationAllowed: false }); window.dispatchEvent(new Event("focus")); + await expect.element(button("Save rule")).not.toBeInTheDocument(); + expect(s.host.querySelector("pre")).toBeNull(); + s.setRead({ mutationAllowed: true }); window.dispatchEvent(new Event("focus")); + await expect.element(button("Review change")).toBeEnabled(); + s.holdPrepare(); await button("Review change").click(); + s.setRead({ mutationAllowed: false }); window.dispatchEvent(new Event("focus")); + await expect.element(button("Review change")).toBeDisabled(); + s.releasePrepare(); + await expect.poll(() => s.host.querySelector("pre")).toBeNull(); +}); + +test("F3 expired prepared reviews recover without replaying a commit", async ctx => { + const s = await prepared(ctx); s.expireHostReview(); + await button("Save rule").click(); + await expect.element(button("Cancel")).toBeEnabled(); + await expect.element(button("Review change")).toBeEnabled(); + await expect.element(page.getByLabelText("Origin", { exact: true })).toHaveValue("https://example.org"); + expect(s.calls.filter(c => c.path.endsWith("/commit"))).toHaveLength(1); + s.draw(null); s.draw(); + await expect.element(button("Cancel")).toBeEnabled(); +}); + +test("T08 F3 elapsed unknown publication remains uncertain after receipt expiry", async ctx => { + const s = await prepared(ctx); s.loseReply(); await button("Save rule").click(); + await expect.element(button("Check save receipt")).toBeVisible(); + s.unknownExpiredReceipt(); await button("Check save receipt").click(); + await expect.element(button("Cancel")).toBeDisabled(); + expect(s.calls.filter(c => c.path.endsWith("/commit"))).toHaveLength(1); +}); + +for (const action of ["edit", "remove"] as const) test(`F4 refresh never rebases ${action} onto a revoked capability or reused identity`, async ctx => { + const original = { ...rule, recipientWhileRestricted: true }; + const s = await scene(ctx, 320, "light", [original]); + await button(`${action === "edit" ? "Edit" : "Remove"} https://example.org:443`).click(); + if (action === "edit") await page.getByLabelText("Label", { exact: true }).fill("Edited harbor"); + s.setRead({ revision: "2", policyHash: "b".repeat(64), rules: [{ ...original, recipientWhileRestricted: false, + ...(action === "remove" ? { selector: { ...rule.selector, host: "troy.example.org" } } : {}) }] }); + await button("Refresh base").click(); + await expect.element(button("Review change")).toBeDisabled(); + await expect.element(page.getByRole("alert")).toHaveTextContent("select the current rule"); + if (action === "edit") await expect.element(page.getByLabelText("Label", { exact: true })).toHaveValue("Edited harbor"); + expect(s.calls.filter(c => c.path.endsWith("/prepare"))).toHaveLength(0); +}); + +for (const status of [403, 503]) test(`T11 T14 F5 failed ${status} refresh disables cached authority and successful reads clear its error`, async ctx => { + const s = await prepared(ctx); s.failList(status); window.dispatchEvent(new Event("focus")); + await expect.element(page.getByRole("alert")).toBeVisible(); + await expect.poll(() => button("Save rule").elements().every(node => node.getAttribute("aria-disabled") === "true")).toBe(true); + expect(s.host.querySelector("pre")).toBeNull(); + s.failList(0); window.dispatchEvent(new Event("focus")); + await expect.element(page.getByRole("alert")).not.toBeInTheDocument(); + if (status === 403) { await expect.element(button("Add origin")).toBeEnabled(); expect(s.host.querySelector("input")).toBeNull(); } + else await expect.element(page.getByLabelText("Origin", { exact: true })).toHaveValue("https://example.org"); +}); + +test("T07 F3 locally expired unsent review returns to the draft without dispatch", async ctx => { + const s = await prepared(ctx); vi.setSystemTime(Date.now() + 900_001); + await button("Save rule").click(); await expect.element(button("Review change")).toBeEnabled(); + expect(s.calls.filter(c => c.path.endsWith("/commit"))).toHaveLength(0); +}); + +test("T07 F3 expired prepared receipt proves an interrupted commit can leave review", async ctx => { + const s = await prepared(ctx); s.loseBeforeCommit(); await button("Save rule").click(); + await expect.element(button("Check save receipt")).toBeVisible(); + s.expireHostReview(); await button("Check save receipt").click(); + await expect.element(button("Review change")).toBeEnabled(); await expect.element(button("Cancel")).toBeEnabled(); + expect(s.calls.filter(c => c.path.endsWith("/commit"))).toHaveLength(1); +}); + +test("F4 even byte-identical ID reuse requires selecting the current rule", async ctx => { + const s = await scene(ctx, 320, "dark", [rule]); + await button("Remove https://example.org:443").click(); s.setRead({ revision: "2", rules: [rule], instances: { [rule.id]: "birth-2" } }); + await button("Refresh base").click(); await expect.element(button("Review change")).toBeDisabled(); + expect(s.calls.filter(c => c.path.endsWith("/prepare"))).toHaveLength(0); +}); + +test("F4 ordinary policy hash refresh preserves a label draft at the same trust revision", async ctx => { + const s = await scene(ctx, 320, "dark", [rule]); + await button("Edit https://example.org:443").click(); await page.getByLabelText("Label", { exact: true }).fill("Edited harbor"); + s.setRead({ policyHash: "b".repeat(64) }); await button("Refresh base").click(); await button("Review change").click(); + await expect.element(button("Save rule")).toBeVisible(); + expect(s.calls.find(c => c.path.endsWith("/prepare"))!.body).toMatchObject({ expectedTrustRevision: "0", expectedPolicyHash: "b".repeat(64), change: { rule: { label: "Edited harbor", recipientWhileRestricted: false } } }); +}); + +test("T12 F2 auth loss during a pending list read cannot restore private review or capability", async ctx => { + const s = await prepared(ctx); s.holdList(); window.dispatchEvent(new Event("focus")); + await expect.poll(() => s.calls.filter(c => c.path.endsWith("/trust-settings")).length).toBeGreaterThan(1); + flushSync(() => { void s.ui.authLock.expire("revoked"); }); s.releaseList(); + await expect.poll(() => s.host.querySelectorAll("input, pre").length).toBe(0); + await expect.element(button("Save rule")).not.toBeInTheDocument(); +}); + +for (const status of [401, 403]) test(`F2 a denied owner commit ${status} immediately removes private bytes and stale write authority`, async ctx => { + const s = await prepared(ctx); s.rejectCommit(status); await button("Save rule").click(); + await expect.poll(() => s.host.querySelectorAll("input, pre").length).toBe(0); + await expect.element(button("Review change")).not.toBeInTheDocument(); + expect(s.calls.filter(c => c.path.endsWith("/commit"))).toHaveLength(1); + expect(s.host.textContent).toContain("outcome remains unknown"); +}); + +for (const status of [401, 403]) for (const phase of ["draft", "review", "uncertain", "receipt-lost"] as const) test(`T11 F1 denied read ${status} clears protected ${phase} data across remount`, async ctx => { + const s = await scene(ctx, 320, "dark", [rule]); + await button("Edit https://example.org:443").click(); + await page.getByLabelText("Label", { exact: true }).fill("Protected harbor draft"); + if (phase !== "draft") { await button("Review change").click(); await expect.element(button("Save rule")).toBeVisible(); } + if (phase === "uncertain" || phase === "receipt-lost") { s.loseBeforeCommit(); await button("Save rule").click(); await expect.element(button("Check save receipt")).toBeVisible(); } + if (phase === "receipt-lost") { s.failReceipt(404); await button("Check save receipt").click(); } + s.failList(status); window.dispatchEvent(new Event("focus")); + await expect.poll(() => s.host.querySelector('[aria-label="Trust rule editor"]')).toBeNull(); + expect(s.host.textContent).not.toContain("example.org"); + if (phase === "uncertain" || phase === "receipt-lost") expect(s.host.textContent).toContain("outcome remains unknown"); + s.draw(null); s.draw(); + await expect.poll(() => s.host.querySelectorAll("input, pre").length).toBe(0); + if (phase === "uncertain" || phase === "receipt-lost") expect(s.host.textContent).toContain("outcome remains unknown"); +}); + +for (const status of [401, 403]) test(`F5 denied receipt ${status} retains the unknown outcome after clearing private data`, async ctx => { + const s = await prepared(ctx); s.loseBeforeCommit(); await button("Save rule").click(); + await expect.element(button("Check save receipt")).toBeVisible(); + s.failReceipt(status); await button("Check save receipt").click(); + await expect.poll(() => s.host.querySelectorAll("input, pre").length).toBe(0); + expect(s.host.textContent).toContain("outcome remains unknown"); + expect(s.calls.filter(c => c.path.endsWith("/commit"))).toHaveLength(1); +}); + +for (const status of [401, 403]) test(`F5 denied read ${status} retains an already abandoned unknown outcome without counting twice`, async ctx => { + const s = await prepared(ctx); s.loseBeforeCommit(); await button("Save rule").click(); + await expect.element(button("Check save receipt")).toBeVisible(); await button("Leave as outcome unknown").click(); + await expect.element(button("Add origin")).toBeEnabled(); await button("Add origin").click(); + s.failList(status); window.dispatchEvent(new Event("focus")); + await expect.poll(() => s.host.querySelectorAll("input, pre").length).toBe(0); + expect(s.host.textContent).toContain("A previous save outcome remains unknown"); + expect(s.host.textContent).not.toContain("2 save outcomes"); +}); + +for (const lost of [false, true]) test(`T09 T10 F2 leaving ${lost ? "receipt-lost" : "uncertain"} retains outcome unknown without replay`, async ctx => { + const s = await prepared(ctx); s.loseBeforeCommit(); await button("Save rule").click(); + await expect.element(button("Check save receipt")).toBeVisible(); + if (lost) { s.failReceipt(404); await button("Check save receipt").click(); } + await button("Leave as outcome unknown").click(); + await expect.element(button("Add origin")).toBeEnabled(); + expect(s.host.textContent).toContain("outcome remains unknown"); + s.draw(null); s.draw(); + await expect.element(button("Add origin")).toBeEnabled(); + expect(s.host.textContent).toContain("outcome remains unknown"); + expect(s.calls.filter(c => c.path.endsWith("/commit"))).toHaveLength(1); +}); + +for (const phase of ["draft", "review"] as const) for (const kind of ["origin", "recipient", "repository"] as const) test(`T15 T16 F3 ${kind} capability withdraw/restore preserves ${phase} but fences writes`, async ctx => { + const selected: TrustRule = kind === "repository" ? { ...rule, selector: { kind: "github_repository", host: "github.com", owner: "odysseus", repository: "navigation", repositoryId: "12" } } : { ...rule, recipientWhileRestricted: kind === "recipient" }; + const s = await scene(ctx, 320, "light", [selected]); + const caps = { originRules: true, recipientRules: true, repositoryRules: true, repositoryIdentity: true, readOnlyReason: null }; + s.setRead({ capabilities: caps }); window.dispatchEvent(new Event("focus")); + const target = kind === "repository" ? "github.com/odysseus/navigation · repository ID 12" : "https://example.org:443"; + await expect.element(button(`Edit ${target}`)).toBeEnabled(); await button(`Edit ${target}`).click(); + await page.getByLabelText("Label", { exact: true }).fill("Edited harbor"); + if (phase === "review") { await button("Review change").click(); await expect.element(button("Save rule")).toBeVisible(); } + const field = kind === "origin" ? "originRules" : kind === "recipient" ? "recipientRules" : "repositoryRules"; + s.setRead({ capabilities: { ...caps, [field]: false } }); window.dispatchEvent(new Event("focus")); + await expect.element(button(phase === "draft" ? "Review change" : "Save rule")).toBeDisabled(); + s.setRead({ capabilities: caps }); window.dispatchEvent(new Event("focus")); + await expect.element(button(phase === "draft" ? "Review change" : "Save rule")).toBeEnabled(); + await expect.element(page.getByLabelText("Label", { exact: true })).toHaveValue("Edited harbor"); +}); + +test("T17 F4 unrelated trust revision refresh preserves selected label and permission intent", async ctx => { + const s = await scene(ctx, 320, "dark", [rule]); + await button("Edit https://example.org:443").click(); await page.getByLabelText("Label", { exact: true }).fill("Edited harbor"); + await page.getByRole("checkbox", { name: /Allow sending data while restricted/ }).click(); + s.setRead({ revision: "2", policyHash: "b".repeat(64), rules: [rule, { ...rule, id: "argo", selector: { ...rule.selector, host: "troy.example.org" } }] }); + await button("Refresh base").click(); await expect.element(button("Review change")).toBeEnabled(); + await button("Review change").click(); await expect.element(button("Save rule")).toBeVisible(); + expect(s.calls.find(c => c.path.endsWith("/prepare"))!.body).toMatchObject({ expectedTrustRevision: "2", change: { rule: { label: "Edited harbor", recipientWhileRestricted: true } } }); +}); + +for (const trigger of ["focus", "save"] as const) test(`T22 F5 ${trigger} refreshes the enforcing policy facts with trust facts`, async ctx => { + const s = await scene(ctx, 320, "dark"); + await expect.poll(() => s.calls.filter(c => c.path.endsWith("/agent-policy")).length).toBe(1); + if (trigger === "focus") { s.setRead({ policyHash: "b".repeat(64) }); window.dispatchEvent(new Event("focus")); } + else { await button("Add origin").click(); await page.getByLabelText("Origin", { exact: true }).fill("https://example.org"); await button("Review change").click(); await button("Save rule").click(); } + await expect.poll(() => s.host.querySelector("[data-agent-policy]")?.textContent).toContain(`Enforcing version: ${(trigger === "focus" ? "b" : "a").repeat(64)}`); +}); + +for (const phase of ["draft", "review", "uncertain", "receipt-lost"] as const) test(`T14 unavailable/recovered read preserves ${phase} without stale write authority`, async ctx => { + const s = await scene(ctx, 320, "light", [rule]); await button("Edit https://example.org:443").click(); + await page.getByLabelText("Label", { exact: true }).fill("Preserved harbor"); + if (phase !== "draft") { await button("Review change").click(); await expect.element(button("Save rule")).toBeVisible(); } + if (phase === "uncertain" || phase === "receipt-lost") { s.loseBeforeCommit(); await button("Save rule").click(); await expect.element(button("Check save receipt")).toBeVisible(); } + if (phase === "receipt-lost") { s.failReceipt(404); await button("Check save receipt").click(); } + s.failList(503); window.dispatchEvent(new Event("focus")); await expect.poll(() => s.host.textContent).toContain("Trust settings unavailable."); + expect(s.host.querySelector("pre")).toBeNull(); + s.failList(0); window.dispatchEvent(new Event("focus")); await expect.poll(() => s.host.textContent).not.toContain("Trust settings unavailable."); + await expect.element(page.getByLabelText("Label", { exact: true })).toHaveValue("Preserved harbor"); + if (phase === "draft" || phase === "review") await expect.element(button(phase === "draft" ? "Review change" : "Save rule")).toBeEnabled(); + else await expect.element(button("Leave as outcome unknown")).toBeEnabled(); +}); + +for (const pending of [false, true]) test(`T19 base refresh discards ${pending ? "late prepared reply" : "prepared review"} and keeps draft`, async ctx => { + const s = await scene(ctx, 320, "dark", [rule]); await button("Edit https://example.org:443").click(); + await page.getByLabelText("Label", { exact: true }).fill("Preserved harbor"); + if (pending) s.holdPrepare(); await button("Review change").click(); + if (!pending) await expect.element(button("Save rule")).toBeVisible(); + s.setRead({ revision: "2", policyHash: "b".repeat(64) }); window.dispatchEvent(new Event("focus")); + await expect.element(button("Review change")).toBeEnabled(); + if (pending) { s.releasePrepare(); await expect.poll(() => s.prepareReplies()).toBe(1); await new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(() => resolve()))); } + await expect.element(button("Save rule")).not.toBeInTheDocument(); + await expect.element(page.getByLabelText("Label", { exact: true })).toHaveValue("Preserved harbor"); + await button("Refresh base").click(); await button("Review change").click(); await expect.element(button("Save rule")).toBeVisible(); +}); + +for (const phase of ["draft", "review"] as const) test(`T20 removal ${phase} remains available after enforcement disappears`, async ctx => { + const s = await scene(ctx, 320, "dark", [rule]); await button("Remove https://example.org:443").click(); + if (phase === "review") { await button("Review change").click(); await expect.element(button("Remove rule")).toBeVisible(); } + s.setRead({ capabilities: { originRules: false, recipientRules: false, repositoryRules: false, repositoryIdentity: false, readOnlyReason: "unavailable" } }); + window.dispatchEvent(new Event("focus")); await expect.element(button(phase === "draft" ? "Review change" : "Remove rule")).toBeEnabled(); + if (phase === "draft") await button("Review change").click(); s.unavailableCommit(); await button("Remove rule").click(); + await expect.poll(() => s.host.textContent).toContain("Runtime enforcement unavailable"); + expect(s.host.textContent).toContain("Current rule: removed"); +}); + +for (const phase of ["preparing", "committing"] as const) test(`T21 remount recovers ${phase} without duplicate dispatch`, async ctx => { + const s = await scene(ctx, 320, "light"); await button("Add origin").click(); await page.getByLabelText("Origin", { exact: true }).fill("https://example.org"); + if (phase === "preparing") s.holdPrepare(); await button("Review change").click(); + if (phase === "committing") { await expect.element(button("Save rule")).toBeVisible(); s.holdCommit(); await button("Save rule").click(); } + s.draw(null); s.draw(); + if (phase === "preparing") { s.releasePrepare(); await expect.element(button("Review change")).toBeEnabled(); expect(s.calls.filter(c => c.path.endsWith("/commit"))).toHaveLength(0); } + else { s.releaseCommit(); await button("Check save receipt").click(); await expect.element(button("Add origin")).toBeEnabled(); expect(s.calls.filter(c => c.path.endsWith("/commit"))).toHaveLength(1); } +}); + +test("T18 mixed-version observation gaps never rebase a selected rule across revisions", async ctx => { + const s = await scene(ctx, 320, "light", [rule]); s.setRead({ instances: undefined }); window.dispatchEvent(new Event("focus")); + await expect.poll(() => s.calls.filter(c => c.path.endsWith("/trust-settings")).length).toBeGreaterThan(1); + await button("Edit https://example.org:443").click(); s.setRead({ revision: "2" }); await button("Refresh base").click(); + await expect.element(button("Review change")).toBeDisabled(); +}); + +test("T22 pending and failed policy facts never label an old hash as enforcing", async ctx => { + const s = await scene(ctx, 320, "dark"); await expect.poll(() => s.host.textContent).toContain("Enforcing version: built-in defaults"); + s.holdPolicy(); s.setRead({ policyHash: "b".repeat(64) }); window.dispatchEvent(new Event("focus")); + await expect.poll(() => s.calls.filter(c => c.path.endsWith("/agent-policy")).length).toBe(2); + expect(s.host.textContent).not.toContain("Enforcing version: built-in defaults"); + s.failPolicy(503); s.releasePolicy(); await expect.poll(() => s.host.textContent).toContain("Could not read this brain's enforcing policy"); + s.failPolicy(0); window.dispatchEvent(new Event("focus")); await expect.poll(() => s.host.textContent).toContain(`Enforcing version: ${"b".repeat(64)}`); +}); + +for (const phase of ["preparing", "committing"] as const) test(`T14 unavailable read fences a pending ${phase} reply`, async ctx => { + const s = await scene(ctx, 320, "light"); await button("Add origin").click(); await page.getByLabelText("Origin", { exact: true }).fill("https://example.org"); + if (phase === "preparing") s.holdPrepare(); await button("Review change").click(); + if (phase === "committing") { await expect.element(button("Save rule")).toBeVisible(); s.holdCommit(); await button("Save rule").click(); } + s.failList(503); window.dispatchEvent(new Event("focus")); await expect.poll(() => s.host.textContent).toContain("Trust settings unavailable."); + if (phase === "preparing") s.releasePrepare(); else s.releaseCommit(); + s.failList(0); window.dispatchEvent(new Event("focus")); await expect.poll(() => s.host.textContent).not.toContain("Trust settings unavailable."); + if (phase === "preparing") { await expect.element(button("Review change")).toBeEnabled(); await expect.element(button("Save rule")).not.toBeInTheDocument(); } + else { await button("Check save receipt").click(); await expect.element(button("Add origin")).toBeEnabled(); expect(s.calls.filter(c => c.path.endsWith("/commit"))).toHaveLength(1); } +}); + +for (const pending of ["commit", "receipt"] as const) test(`T23 leave a pending ${pending} as unknown and fence its late reply`, async ctx => { + const s = await prepared(ctx); + if (pending === "commit") { s.holdCommit(); await button("Save rule").click(); } + else { s.loseBeforeCommit(); await button("Save rule").click(); await expect.element(button("Check save receipt")).toBeVisible(); s.holdReceipt(); await button("Check save receipt").click(); } + await button("Leave as outcome unknown").click(); + if (pending === "commit") s.releaseCommit(); else s.releaseReceipt(); + await expect.element(button("Add origin")).toBeEnabled(); + await new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(() => resolve()))); + expect(s.host.textContent).toContain("outcome remains unknown"); + expect(s.host.textContent).not.toContain("Publication proved"); + expect(s.calls.filter(c => c.path.endsWith("/commit"))).toHaveLength(1); +}); + +test("T21 a responsive remount restores focus to the retained draft field", async ctx => { + const s = await scene(ctx, 320, "dark"); await button("Add origin").click(); + await page.getByLabelText("Label", { exact: true }).fill("Preserved harbor"); + (page.getByLabelText("Label", { exact: true }).element() as HTMLElement).focus(); + s.draw(null); s.draw(); + await expect.element(button("Review change")).toBeEnabled(); + expect(document.activeElement).toBe(page.getByLabelText("Label", { exact: true }).element()); +}); + +test("T21 a retained draft does not steal deliberately moved destination focus", async ctx => { + const s = await scene(ctx, 320, "dark"); await button("Add origin").click(); await page.getByLabelText("Label", { exact: true }).fill("Preserved harbor"); + const destination = document.createElement("button"); destination.textContent = "Another destination"; document.body.append(destination); + ctx.onTestFinished(() => destination.remove()); destination.focus(); + s.draw(null); s.draw(); + await expect.element(button("Review change")).toBeEnabled(); expect(document.activeElement).toBe(destination); +}); + +test("T12 replacing the brain root exposes no prior-root facts even before passive effects", async ctx => { + const s = await scene(ctx, 320, "light", [rule]); await button("Edit https://example.org:443").click(); + const other = createBrainUiRoot({ storage: null, request: async url => String(url).endsWith("/agent-policy") + ? Response.json({ source: "default", hash: null, path: "context/policies/governance.md", errors: [], warnings: [], profiles: { interactive: "governed", voice: "strict" }, protectedPaths: [], workerLimits: null }) + : Response.json({ revision: "0", policyHash: null, error: null, rules: [], origins: [], repositories: [], instances: {}, mutationAllowed: true, + capabilities: { originRules: true, recipientRules: true, repositoryRules: false, repositoryIdentity: false, readOnlyReason: null } }) }); + ctx.onTestFinished(() => other.dispose()); const commits: string[] = []; + function Audit({ children }: { children: ReactNode }) { useLayoutEffect(() => { commits.push(s.host.textContent ?? ""); }); return children; } + s.draw(); + await expect.poll(() => s.host.textContent).toContain("Trust revision 0"); commits.length = 0; + s.draw(); + await expect.element(button("Add origin")).toBeEnabled(); + expect(commits.length).toBeGreaterThan(0); expect(commits.every(text => !text.includes("example.org"))).toBe(true); +}); + +for (const theme of ["dark", "light"]) test(`trust facts in the composed Security pane fit the document at 320 ${theme}`, async ctx => { + const s = await scene(ctx, 320, theme); + s.host.style.display = "flex"; s.host.style.flexDirection = "column"; + s.setRead({ policyHash: "a".repeat(64) }); + s.draw(
    {}} onRename={() => {}} onDelete={() => {}} onSignOut={() => {}} sections={} />
    ); + await expect.element(button("Add origin")).toBeVisible(); + await expect.poll(() => s.host.querySelector("[data-agent-policy]")?.textContent).toContain(`Enforcing version: ${"a".repeat(64)}`); + expect(document.documentElement.scrollWidth, "Security composition fits the document").toBeLessThanOrEqual(innerWidth); +}); + +for (const missing of ["capabilities", "originRules"] as const) test(`partial host response without ${missing} keeps Security readable and unsupported writes disabled`, async ctx => { + const s = await scene(ctx, 320, "dark", [rule]); + // Deliberate wire-level omission, including an otherwise asserted owner flag. + s.setRead({ capabilities: (missing === "capabilities" ? undefined : { recipientRules: true, repositoryRules: false, repositoryIdentity: false, readOnlyReason: null }) as TrustSettingsRead["capabilities"] }); + window.dispatchEvent(new Event("focus")); + await expect.element(button("Add origin")).toBeDisabled(); + await expect.element(page.getByText("Origin enforcement unavailable. Configured origins are not confirmed active.", { exact: true })).toBeVisible(); + await expect.element(button("Remove https://example.org:443")).toBeEnabled(); + expect(s.calls.filter(c => c.path.endsWith("/prepare") || c.path.endsWith("/commit"))).toHaveLength(0); +}); diff --git a/packages/ui-react/tests/browser/safety-review.layout.tsx b/packages/ui-react/tests/browser/safety-review.layout.tsx index b1d7cb8fd6..ddbfddfffe 100644 --- a/packages/ui-react/tests/browser/safety-review.layout.tsx +++ b/packages/ui-react/tests/browser/safety-review.layout.tsx @@ -1,5 +1,6 @@ /// import {afterAll,afterEach,beforeAll,expect,test} from 'vitest'; +import {watchdogMs} from '../../../../scripts/test-deadlines.js'; import {commands,page,userEvent} from 'vitest/browser'; import {createRoot,type Root} from 'react-dom/client'; import {flushSync} from 'react-dom'; @@ -10,24 +11,28 @@ import {createSafetyClient} from '../../src/lib/safety-client.js'; import {SessionSafety} from '../../src/components/chat/safety-indicator.js'; import {parseServerMessage} from '@schlessera/brain-ui-sdk/schemas'; import type {ChatMessage} from '../../src/stores/chat-store.js'; -import type {ClientMessage,SafetyPage} from '@schlessera/brain-ui-sdk/protocol'; +import type {ClientMessage,SafetyPage,SafetyRecord} from '@schlessera/brain-ui-sdk/protocol'; let fixture:{id:string;url:string}|undefined,ui:BrainUiRoot|undefined,socket:WebSocket|undefined,renderer:Root|undefined,host:HTMLDivElement|undefined; let safetyClient:ReturnType|undefined; let styles:HTMLStyleElement;const oldTheme=document.documentElement.dataset.theme,viewport={width:innerWidth,height:innerHeight}; beforeAll(async()=>{styles=document.createElement('style');styles.textContent=await commands.formConsumerStyles();document.head.append(styles);}); afterAll(async()=>{styles.remove();await page.viewport(viewport.width,viewport.height);}); async function disposeView(){safetyClient?.dispose();safetyClient=undefined;if(renderer)flushSync(()=>renderer!.unmount());renderer=undefined;ui?.dispose();ui=undefined;socket?.close();socket=undefined;host?.remove();host=undefined;} -afterEach(async()=>{await disposeView();if(fixture)await commands.safetyServer({op:'stop',id:fixture.id});fixture=undefined;if(oldTheme===undefined)delete document.documentElement.dataset.theme;else document.documentElement.dataset.theme=oldTheme;}); +afterEach(async()=>{statusBarrier=undefined;commitBarrier=undefined;await disposeView();if(fixture)await commands.safetyServer({op:'stop',id:fixture.id});fixture=undefined;if(oldTheme===undefined)delete document.documentElement.dataset.theme;else document.documentElement.dataset.theme=oldTheme;}); const patch=(patch:Record={})=>commands.safetyServer({op:'set',id:fixture!.id,patch}) as Promise<{page:SafetyPage;commits:number;prepares:number;decisions:Array<{occurrence_id:string}>}>; const noop=()=>{}; const message:ChatMessage={id:'odysseus-answer',turnId:'voyage',role:'assistant',content:'Voyage notes retained.',isStreaming:false,timestamp:Date.UTC(2026,6,12,10), toolCalls:[{id:'tool_a',name:'WebFetch',inputJson:'{}',input:{url:'https://example.com/odyssey'},output:'Odysseus voyage notes',status:'complete'},{id:'tool_c',name:'Read',inputJson:'{}',input:{file_path:'workspaces/ithaca/voyage.md'},output:'Penelope voyage notes',status:'complete'}], parts:[{kind:'tool',toolIndex:0},{kind:'tool',toolIndex:1},{kind:'text',text:'Voyage notes retained.'}]}; +let commitBarrier:((result:{status:number;body:unknown})=>Promise)|undefined; +let statusBarrier:((body:Record,result:{status:number;body:unknown})=>Promise)|undefined; async function view(independentSocket=false){ const f=fixture!; ui=createBrainUiRoot({storage:null,config:{backendUrl:f.url},request:async(url,init)=>{ if(!String(url).includes('/safety/reviews/'))return Response.json({providers:[]}); const result=await patch({action:'request',path:new URL(url).pathname,body:init?.body}) as unknown as {status:number;body:unknown}; + if(String(url).endsWith('/future/status')&&statusBarrier)await statusBarrier(JSON.parse(String(init?.body)),result); + if(String(url).endsWith('/commit')&&commitBarrier)await commitBarrier(result); if(init?.signal?.aborted)throw new DOMException('Aborted','AbortError');return Response.json(result.body,{status:result.status}); }}); const frames:unknown[]=[],sent:unknown[]=[];const current=ui;current.stores.chat.setState({activeSessionId:'ithaca',buffers:{ithaca:{messages:[message],isStreaming:false,askUser:null,lastTouched:message.timestamp}}}); @@ -162,6 +167,22 @@ test('two live owner views keep independent review scope and converge after ever } }); +for(const width of [320,1280])for(const theme of ['light','dark'])test(`${width} ${theme}: historical source admission is distinct from a human verdict`,async()=>{ + await scene(width,theme); + const initialWidth=document.documentElement.scrollWidth; + const records={...ui!.stores.safety.getState().records}; + for(const [id,r] of Object.entries(records))if(r.kind==='occurrence')records[id]={...r,admission:{trusted:true as const,ruleId:'ithaca-source',policyHash:'a'.repeat(64),trustRevision:'7',collectionRevision:'3'}}; + flushSync(()=>ui!.stores.safety.setState({records})); + const indicator=[...host!.querySelectorAll('[data-safety-indicator] button')].find(b=>b.getAttribute('aria-label')?.startsWith('Trusted at admission'))!; + expect(indicator,'SOURCE_DECISION_NEVER_READS_AS_UNRESOLVED_OR_HUMAN_VERDICT').toBeTruthy();await userEvent.click(indicator); + await expect.poll(()=>document.querySelector('[data-safety-details]')?.textContent).toContain('Source rule ithaca-source · trust revision 7'); + expect(document.querySelector('[data-safety-details]')?.textContent).toContain('grants no current recipient permission'); + expect([...document.querySelectorAll('[data-safety-details] button')].some(b=>b.textContent==='Mark as safe')).toBe(false); + const bounds=document.querySelector('[data-safety-details]')!.getBoundingClientRect(); + expect(bounds.left).toBeGreaterThanOrEqual(0);expect(bounds.right).toBeLessThanOrEqual(innerWidth); + expect(document.documentElement.scrollWidth,'ADMISSION_DETAILS_ADD_NO_PAGE_OVERFLOW').toBeLessThanOrEqual(initialWidth); +}); + for(const theme of ['light','dark'])test(`${theme}: a mixed reviewed group names its remaining unresolved source on hover and focus`,async()=>{ await scene(320,theme); const indicator=buttonForTool(); @@ -184,3 +205,162 @@ for(const theme of ['light','dark'])test(`${theme}: a mixed reviewed group names expect(document.querySelectorAll('[data-safety-trigger]')).toHaveLength(2); expect(document.querySelector('[data-safety-details]')!.textContent).toContain('Marked safe by you'); }); + +for(const width of [320,1280])for(const theme of ['light','dark'])for(const mode of ['reviewed','unresolved','both'] as const)test(`${width} ${theme}: mixed trusted history keeps each verdict kind (${mode})`,async()=>{ + await scene(width,theme);const state=ui!.stores.safety.getState(),rows=Object.values(state.records).filter(r=>r.kind==='occurrence');expect(rows.length).toBeGreaterThanOrEqual(3); + const at=Date.UTC(2026,6,12,10),hasReviewed=mode!=='unresolved',hasUnresolved=mode!=='reviewed'; + const base=(r:typeof rows[number])=>({...r,turnId:message.turnId!,entry:{kind:'tool' as const,toolUseId:'tool_a'},observedAt:at}); + const trusted={...base(rows[0]!),source:'web_fetch' as const,admission:{trusted:true as const,ruleId:'ithaca-source',policyHash:'a'.repeat(64),trustRevision:'7',collectionRevision:'3'}}; + const reviewed={...base(rows[1]!),source:'mcp_document' as const,admission:{trusted:false as const,policyHash:null,trustRevision:'0'}}; + const unresolved={...base(rows[2]!),source:'workspace_read' as const,admission:{trusted:false as const,policyHash:null,trustRevision:'0'}}; + const records:Record={[trusted.id]:trusted};if(hasReviewed){records[reviewed.id]=reviewed;const identity=state.identity;if(!identity||!('sessionId' in identity))throw new Error('Missing session');records.mixed_verdict={id:'mixed_verdict',sequence:'999999',observedAt:at,turnId:message.turnId!,bindingId:reviewed.bindingId,occurrenceId:reviewed.id,detailPruned:false,kind:'safe_decision',session:identity,requestId:'mixed_request',principalId:'odysseus',verdict:'safe',channel:'owner_history'};}if(hasUnresolved)records[unresolved.id]=unresolved; + flushSync(()=>ui!.stores.safety.setState({records,projection:{...state.projection!,unresolvedCount:hasUnresolved?1:0,earliestUnresolvedId:hasUnresolved?unresolved.id:null,restriction:hasUnresolved?'restricted':'normal',reasons:hasUnresolved?['unresolved']:[]},normal:!hasUnresolved&&state.projection?.coverage.state==='complete'})); + const indicator=[...host!.querySelectorAll('[data-safety-indicator] button')].find(b=>b.getClientRects().length>0)!;expect(indicator).toBeTruthy(); + if(hasUnresolved)expect(indicator.getAttribute('aria-label'),'MIXED_GROUP_NAMES_ONLY_ITS_UNRESOLVED_SOURCE').toContain('Workspace read · Only this trigger can be reviewed'); + if(hasReviewed)expect(indicator.getAttribute('aria-label'),'MIXED_HISTORY_NAMES_BOTH_TRUST_AND_HUMAN_VERDICT').toContain('1 marked safe by you'); + await userEvent.click(indicator);const panel=document.querySelector('[data-safety-details]')!;expect(panel.textContent).toContain('Trusted at admission');if(hasReviewed)expect(panel.textContent).toContain('Marked safe by you'); + const bounds=panel.getBoundingClientRect();expect(bounds.left).toBeGreaterThanOrEqual(0);expect(bounds.right).toBeLessThanOrEqual(innerWidth); +}); + +for(const width of [320,1280])for(const theme of ['light','dark'])for(const tunnel of [false,true])test(`${width} ${theme}: IPv6 safety authority stays unambiguous (tunnel ${tunnel})`,async()=>{ + await scene(width,theme);const records={...ui!.stores.safety.getState().records}; + for(const [id,r] of Object.entries(records))if(r.kind==='occurrence')records[id]={...r,admission:{trusted:true,ruleId:'ithaca-source',policyHash:'a'.repeat(64),trustRevision:'7',collectionRevision:'3'},provenance:tunnel?{kind:'tunnel_authority',authority:{host:'::1',port:443},verifiedBy:'host_proxy'}:{kind:'web_origin',origin:{scheme:'http',host:'::1',port:8080},verifiedBy:'host_transport'}}; + flushSync(()=>ui!.stores.safety.setState({records}));const indicator=[...host!.querySelectorAll('[data-safety-indicator] button')].find(b=>b.getAttribute('aria-label')?.startsWith('Trusted at admission'))!;await userEvent.click(indicator); + const expected=tunnel?'[::1]:443':'http://[::1]:8080';await expect.poll(()=>document.querySelector('[data-safety-details]')?.textContent,{message:'IPV6_HISTORY_BRACKETS_THE_EXACT_AUTHORITY'}).toContain(expected); +}); + +for(const width of [320,1280])for(const allow of [false,true])test(`${width}: future origin review, recipient ${allow}, exact bytes then A only and reload`,async()=>{ + await scene(width,'light');await patch({action:'add_verified'}); + await expect.poll(()=>ui!.stores.safety.getState().projection?.unresolvedCount).toBe(4); + await userEvent.click(host!.querySelector('[data-safety-turn-event] button')!); + const section=()=>[...document.querySelectorAll('[data-safety-trigger]')].find(e=>e.textContent?.includes('https://ithaca.invalid'))!; + const mark=section().querySelector('[role=button],button')!;await userEvent.click(mark); + const only=section().querySelector('input[type=radio]')!;expect(only.parentElement!.getBoundingClientRect().height).toBeGreaterThanOrEqual(44);expect(only.checked,'COMBINED_DEFAULT_ONLY_THIS_TRIGGER').toBe(true); + await userEvent.click(page.getByRole('radio',{name:'Trust this origin'})); + const recipient=page.getByRole('checkbox',{name:'Allow sending data while restricted'}); + await expect.element(recipient).not.toBeChecked(); + if(allow)await userEvent.click(recipient); + await userEvent.click(page.getByRole('button',{name:'Review future rule',exact:true})); + await expect.element(page.getByRole('group',{name:'Exact future rule review'})).toBeVisible(); + expect(section().textContent).toContain('ithaca.invalid');expect((await patch()).commits).toBe(0); + await userEvent.click(page.getByRole('button',{name:allow?'Save rule, allow sending while restricted, and mark this trigger safe':'Save future source rule and mark this trigger safe',exact:true})); + await expect.poll(()=>ui!.stores.safety.getState().projection?.unresolvedCount).toBe(3); + expect((await patch()).decisions).toHaveLength(1); + expect(document.body.textContent).not.toContain('Normal policy restored'); + await disposeView();await view(); + await userEvent.click(host!.querySelector('[data-safety-turn-event] button')!); + await expect.poll(()=>document.querySelector('[data-safety-details]')?.textContent).toContain('Future rule: present'); + expect((await patch()).commits,'COMBINED_RELOAD_STATUS_NEVER_REPLAYS').toBe(1); +}); + +async function futureReviewScene(width:number,partial=false){ + await scene(width,'light');await patch({action:'add_verified'}); + await expect.poll(()=>ui!.stores.safety.getState().projection?.unresolvedCount).toBe(4); + await userEvent.click(host!.querySelector('[data-safety-turn-event] button')!); + const section=()=>[...document.querySelectorAll('[data-safety-trigger]')].find(e=>e.textContent?.includes('https://ithaca.invalid'))!; + await userEvent.click(section().querySelector('[role=button],button')!); + await userEvent.click(page.getByRole('radio',{name:'Trust this origin'})); + await userEvent.click(page.getByRole('button',{name:'Review future rule',exact:true})); + await expect.element(page.getByRole('group',{name:'Exact future rule review'})).toBeVisible(); + if(partial)await patch({action:'fail_combined_verdict'}); + await userEvent.click(page.getByRole('button',{name:'Save future source rule and mark this trigger safe',exact:true})); + await expect.poll(()=>ui!.stores.safety.getState().status).toBe('ready'); + return section; +} +for(const width of [320,1280])test(`${width} review F3: focus refresh replaces commit-time rule presence`,async()=>{ + const section=await futureReviewScene(width); + await expect.poll(()=>ui!.stores.safety.getState().projection?.unresolvedCount).toBe(3); + await expect.poll(()=>section().textContent).toContain('Future rule: present'); + await patch({action:'remove_future_rule'});window.dispatchEvent(new Event('focus')); + await expect.poll(()=>section().textContent).toContain('Future rule: removed'); + expect(section().textContent,'F3_NO_STALE_COMMIT_TIME_PRESENCE').not.toContain('currently present'); + expect(section().textContent).not.toContain('Future rule: present'); +}); +for(const width of [320,1280])test(`${width} review F4: partial operation is distinct from another tab's safe verdict`,async()=>{ + const section=await futureReviewScene(width,true); + await expect.poll(()=>section().textContent).toContain('Rule publication proved'); + await patch({action:'individual_safe'}); + await expect.poll(()=>ui!.stores.safety.getState().projection?.unresolvedCount).toBe(3); + window.dispatchEvent(new Event('focus')); + await expect.poll(()=>section().textContent).toContain('Marked safe by you'); + expect(section().textContent,'F4_PARTIAL_RECEIPT_IS_NOT_CURRENT_TRIGGER_STATE').not.toContain('this trigger is still unresolved'); + expect(section().textContent).not.toContain('this trigger remains unresolved'); +}); + +for(const width of [320,1280])for(const older of ['success','error'] as const)test(`${width} matrix CS-O ${older}: an older focus response cannot overwrite newer revocation`,async()=>{ + const section=await futureReviewScene(width); + await expect.poll(()=>section().textContent).toContain('Future rule: present'); + const entered=Promise.withResolvers(),release=Promise.withResolvers(),returned=Promise.withResolvers();let held=false; + const occurrenceId=section().dataset.safetyTrigger; + statusBarrier=async body=>{if(!held&&body.occurrenceId===occurrenceId){held=true;entered.resolve();await release.promise;returned.resolve();if(older==='error')throw new Error('Older status read failed');}}; + try{ + window.dispatchEvent(new Event('focus'));await entered.promise; + await patch({action:'remove_future_rule'});window.dispatchEvent(new Event('focus')); + await expect.poll(()=>section().textContent).toContain('Future rule: removed'); + release.resolve();await returned.promise; + // The transport already holds a complete JSON body; drain its promise chain + // and React's render frames after releasing the deliberately older response. + await new Promise(resolve=>requestAnimationFrame(()=>requestAnimationFrame(()=>resolve()))); + expect(section().textContent,'R2F2_LATE_PRESENT_CANNOT_OVERWRITE_REMOVED').toContain('Future rule: removed'); + expect(section().textContent).not.toContain('Future rule: present'); + }finally{release.resolve();statusBarrier=undefined;} +}); + +for(const width of [320,1280])test(`${width} matrix CS-F initial / CS-R recovery: failed first read of a partial operation is not JSON null (round 3 F3)`,async()=>{ + const old=await futureReviewScene(width,true);await expect.poll(()=>old().textContent).toContain('Rule publication proved'); + const target=old().dataset.safetyTrigger;await disposeView();await view(); + const entered=Promise.withResolvers();statusBarrier=async body=>{if(body.occurrenceId===target){entered.resolve();throw new Error('Controlled first status-read loss');}}; + await userEvent.click(host!.querySelector('[data-safety-turn-event] button')!);await entered.promise; + const section=()=>document.querySelector(`[data-safety-trigger="${target}"]`)!; + await expect.poll(()=>section().textContent).toContain('Could not verify'); + expect(section().textContent).not.toContain('Future rule: present');expect(ui!.stores.safety.getState().projection?.unresolvedCount).toBe(4); + statusBarrier=undefined;window.dispatchEvent(new Event('focus')); + await expect.poll(()=>section().textContent).toContain('Future rule: present');expect(section().textContent).not.toContain('Could not verify'); +}); +for(const width of [320,1280])test(`${width} matrix CS-M: a status response for another target cannot set presence`,async()=>{ + const old=await futureReviewScene(width,true);await expect.poll(()=>old().textContent).toContain('Rule publication proved'); + const target=old().dataset.safetyTrigger;await disposeView();await view(); + statusBarrier=async(body,result)=>{if(body.occurrenceId===target)result.body={...(result.body as Record),occurrenceId:'wrong_occurrence'};}; + await userEvent.click(host!.querySelector('[data-safety-turn-event] button')!); + const section=()=>document.querySelector(`[data-safety-trigger="${target}"]`)!; + await expect.poll(()=>section().textContent).toContain('Could not verify');expect(section().textContent).not.toContain('Future rule: present'); +}); + +for(const width of [320,1280])test(`${width} matrix CS-F later / CS-E: expired receipt null clears display without hiding read failure`,async()=>{ + const section=await futureReviewScene(width,true);await expect.poll(()=>section().textContent).toContain('Future rule: present'); + const target=section().dataset.safetyTrigger; + statusBarrier=async body=>{if(body.occurrenceId===target)throw new Error('Later read failed');};window.dispatchEvent(new Event('focus')); + await expect.poll(()=>section().textContent).toContain('Could not verify'); + await patch({action:'expire_future_receipts'});statusBarrier=undefined;window.dispatchEvent(new Event('focus')); + await expect.poll(()=>section().textContent).not.toContain('Could not verify');expect(section().textContent).not.toContain('Future rule:');expect(ui!.stores.safety.getState().projection?.unresolvedCount).toBe(4); +}); + +for(const future of [false,true])test(`fable F1 browser: ${future?'combined':'individual'} live update precedes commit response`,async()=>{ + await page.viewport(320,900);fixture=await commands.safetyServer({op:'start'}) as typeof fixture;await view(); + await patch({action:'add_verified'});await expect.poll(()=>ui!.stores.safety.getState().projection?.unresolvedCount).toBe(4); + await userEvent.click(host!.querySelector('[data-safety-turn-event] button')!); + const section=()=>[...document.querySelectorAll('[data-safety-trigger]')].find(e=>e.textContent?.includes('https://ithaca.invalid'))!; + let responseObserved=false; + commitBarrier=async result=>{ + const receipt=result.body as {stage?:string;receipt?:{stage:string};currentProjection:{evidenceRevision:string}}; + expect(result.status).toBe(200);expect(receipt.stage??receipt.receipt?.stage).toBe('verdict_committed'); + await expect.poll(()=>ui!.stores.safety.getState().revision,{timeout:watchdogMs(5000)}).toBe(receipt.currentProjection.evidenceRevision); + responseObserved=true; + }; + await userEvent.click(section().querySelector('[role=button],button')!); + if(future){await userEvent.click(page.getByRole('radio',{name:'Trust this origin'}));await userEvent.click(page.getByRole('button',{name:'Review future rule',exact:true}));await expect.element(page.getByRole('group',{name:'Exact future rule review'})).toBeVisible();await userEvent.click(page.getByRole('button',{name:'Save future source rule and mark this trigger safe',exact:true}));} + else await userEvent.click(page.getByRole('button',{name:'Mark this trigger as safe',exact:true})); + // Protected publication and response delivery have no one-second product deadline. + // First await the real committed response with its own live update observed; + // then await React's acknowledgement. Both are bounded hang watchdogs. + await expect.poll(()=>responseObserved,{timeout:watchdogMs(5000)}).toBe(true); + await expect.poll(()=>section().textContent,{timeout:watchdogMs(5000)}).toContain(future?'This operation recorded a safe verdict':'Decision recorded');expect(section().textContent).not.toContain('Review cancelled'); +},watchdogMs(20000)); +test('fable F2 browser: cancel future preparation then individual review remains Decision recorded',async()=>{ + await page.viewport(320,900);fixture=await commands.safetyServer({op:'start'}) as typeof fixture;await view();await patch({action:'add_verified'});await expect.poll(()=>ui!.stores.safety.getState().projection?.unresolvedCount).toBe(4); + await userEvent.click(host!.querySelector('[data-safety-turn-event] button')!); + const section=()=>[...document.querySelectorAll('[data-safety-trigger]')].find(e=>e.textContent?.includes('https://ithaca.invalid'))!; + await userEvent.click(section().querySelector('[role=button],button')!);await userEvent.click(page.getByRole('radio',{name:'Trust this origin'}));await userEvent.click(page.getByRole('button',{name:'Review future rule',exact:true}));await expect.element(page.getByRole('group',{name:'Exact future rule review'})).toBeVisible();await userEvent.click(page.getByRole('button',{name:'Cancel future rule review',exact:true})); + await userEvent.click(section().querySelector('[role=button],button')!);await userEvent.click(page.getByRole('radio',{name:'Only this trigger',exact:true}));await userEvent.click(page.getByRole('button',{name:'Mark this trigger as safe',exact:true})); + await expect.poll(()=>section().textContent).toContain('Decision recorded');ui!.stores.safety.getState().refresh();await expect.poll(()=>ui!.stores.safety.getState().status).toBe('ready');expect(section().textContent).not.toContain('No decision was sent'); +}); diff --git a/packages/ui-react/tests/browser/settings-structure.layout.tsx b/packages/ui-react/tests/browser/settings-structure.layout.tsx index 76fa7fe8ea..2cd9bee092 100644 --- a/packages/ui-react/tests/browser/settings-structure.layout.tsx +++ b/packages/ui-react/tests/browser/settings-structure.layout.tsx @@ -4,8 +4,15 @@ import { createRoot } from "react-dom/client"; import { flushSync } from "react-dom"; import { BrainUiProvider, useRootStore } from "../../src/root-context.js"; import { createBrainUiRoot } from "../../src/root.js"; +import type { TrustSettingsRead } from "../../src/lib/trust-settings.js"; import { SettingsPanel } from "../../src/components/settings/settings-panel.js"; +// Every pane gets its own endpoint DTO; trust facts are not a models response. +const trustRead = { + revision: "0", policyHash: null, error: null, rules: [], origins: [], repositories: [], mutationAllowed: false, + capabilities: { originRules: true, recipientRules: true, repositoryRules: false, repositoryIdentity: false, readOnlyReason: null }, +} satisfies TrustSettingsRead; + const panes = ["Appearance & input", "Models", "Voice", "Accounts", "Skills", "Modules", "Storage", "Security", "Devices & agents"]; for (const width of [320, 768, 1280]) for (const theme of ["dark", "light"] as const) { test(`Settings pane identity and manual traversal at ${width} ${theme}`, async ctx => { @@ -18,6 +25,7 @@ for (const width of [320, 768, 1280]) for (const theme of ["dark", "light"] as c const requests: string[] = []; const ui = createBrainUiRoot({ storage: null, request: async url => { requests.push(String(url)); + if (String(url).endsWith("/trust-settings")) return Response.json(trustRead); if(String(url).includes("/storage"))return Response.json({error:"Not configured"},{status:503}); if (String(url).endsWith("/agent-policy")) return Response.json({ error: "Not configured" }, { status: 404 }); return Response.json({ models: Array.from({ length: 24 }, (_, i) => ({ id: `ithaca-${i}`, label: `Ithaca model ${i + 1}`, hidden: false })), customModels: [], discovery: { enabled: false }, providers: [], configured: false, tools: [], principals: [], credentials: [], skills: [], enabled: [], available: [] }); @@ -76,6 +84,10 @@ for (const width of [320, 768, 1280]) for (const theme of ["dark", "light"] as c if (module === "passkey-tab") await import("../../src/components/settings/passkey-tab.js"); if (module === "devices-agents-tab") await import("../../src/components/settings/devices-agents-tab.js"); await expect.poll(() => page.getByRole("tabpanel").element().textContent!.length).toBeGreaterThan(0); + if (module === "passkey-tab") { + await expect.element(page.getByRole("heading", { name: "Source trust and data sending", exact: true })).toBeVisible(); + await expect.poll(() => page.getByRole("tabpanel").element().textContent).toContain("No rules configured."); + } expect(page.getByRole("radiogroup", { name: "Theme" }).elements()).toHaveLength(0); const button = page.getByRole("tab", { name, exact: true }).element(); const b = button.getBoundingClientRect(); @@ -129,6 +141,8 @@ test("moved Accounts flows, Security revocation and device preferences retain th if (path === "/api/web-search") return Response.json({ configured: search, order: [], overriddenBy: null, appliesTo: [], providers: [{ id: "voyage", label: "Voyage search", enabled: searchEnabled, hasKeyField: true, keyConfigured, keyFromEnv: false, keyless: false, costNote: "Paid", blurb: "Find sailing notes" }] }); if (path === "/api/tool-permissions/web_search" && init?.method === "DELETE") { granted = false; return Response.json({ tools: [] }); } if (path === "/api/tool-permissions") return Response.json({ tools: granted ? ["web_search"] : [] }); + if (path === "/api/agent-policy") return Response.json({ error: "Not configured" }, { status: 404 }); + if (path === "/api/trust-settings") return Response.json(trustRead); if (path === "/api/auth/passkey/list") return Response.json({ credentials: [] }); return Response.json({ providers: [], models: [] }); }; diff --git a/packages/ui-react/tests/fixtures/safety-browser-server.ts b/packages/ui-react/tests/fixtures/safety-browser-server.ts index b0bc71824c..f920f5434c 100644 --- a/packages/ui-react/tests/fixtures/safety-browser-server.ts +++ b/packages/ui-react/tests/fixtures/safety-browser-server.ts @@ -1,3 +1,7 @@ +import {createTrustSettings} from '../../../ui-server/src/brain/trust-settings.js'; +import {createKeyedLock} from '@schlessera/brain-ui-sdk/server'; +import {CombinedSafetyReviews} from '../../../ui-server/src/governance/combined-safety-reviews.js'; +import {createOwnerSafetyReviewRoutes} from '../../../ui-server/src/routes/owner-safety-review.js'; /** Keyless loopback browser fixture: real writer, owner HTTP and WS sidecars. */ import {occurrence} from '../../../ui-server/src/governance/occurrence.js'; import {retireChat} from '../../../ui-server/src/ws/chat-lifecycle.js'; @@ -20,19 +24,44 @@ const app=new Hono(); // Test-only bootstrap supplies the fixture principal to a real WS host. HTTP // mutations below still traverse the actual cookie/Origin/owner route stack. app.get('/ws',async(c,next)=>{c.set('principal',f.principal);return next();},createWsUpgrade(f.host)); +const trust=createTrustSettings({root:f.root,db:f.db,writer:f.writer,lock:createKeyedLock(),originEnforcement:true, + authority:id=>id===f.principal.id&&f.reviews!.authorized(f.principal)?'owner-epoch':null,observe:async(_id,write)=>{await write();}}); +f.reviews!.enableFutureRules(trust); +let failVerdict=false,verifiedId:string|null=null; +const originalReview=f.reviews!.review.bind(f.reviews!); +f.reviews!.review=async(...args)=>{if(failVerdict&&args[2]!==null)throw new Error('fixture verdict unavailable');return originalReview(...args);}; +const combined=new CombinedSafetyReviews(f.db,f.reviews!,trust); +const futureApp=new Hono();futureApp.use('*',async(c,next)=>{c.set('principal',f.principal);await next();}); +futureApp.route('/api',createOwnerSafetyReviewRoutes(f.reviews!,false,combined)); const inner=f.url.replace('ws:','http:').replace('/ws','');let commits=0,prepares=0; app.post('/fixture',async c=>{ const input=await c.req.json(); if(input.action==='request'){ - if(typeof input.path!=='string'||!/^\/api\/sessions\/ithaca\/safety\/reviews\/(prepare|[A-Za-z0-9_-]+\/commit)$/.test(input.path))return c.json({error:'invalid fixture route'},400); - if(input.path.endsWith('/commit'))commits++;else prepares++; - const response=await fetch(inner+input.path,{method:'POST',headers:{cookie:f.cookie,origin:inner,'content-type':'application/json'},body:input.body}); + if(typeof input.path!=='string'||!/^\/api\/sessions\/ithaca\/safety\/reviews\/(prepare|future\/(prepare|commit|status)|[A-Za-z0-9_-]+\/commit)$/.test(input.path))return c.json({error:'invalid fixture route'},400); + if(input.path.endsWith('/commit'))commits++;else if(input.path.endsWith('/prepare'))prepares++; + const response=input.path.includes('/future/')?await futureApp.request(inner+input.path,{method:'POST',headers:{origin:inner,'content-type':'application/json'},body:input.body}):await fetch(inner+input.path,{method:'POST',headers:{cookie:f.cookie,origin:inner,'content-type':'application/json'},body:input.body}); return c.json({status:response.status,body:await response.json()}); } + if(input.action==='expire_future_receipts')f.db.query('UPDATE trust_settings_operations SET retain_until=0').run(); + if(input.action==='fail_combined_verdict')failVerdict=true; + if(input.action==='remove_future_rule'){ + const p=await trust.list(f.principal.id),rule=p.rules[0];if(!rule)throw new Error('Missing future rule'); + const prepared=await trust.prepare(f.principal.id,{version:1,expectedTrustRevision:p.revision,expectedPolicyHash:p.policyHash,change:{action:'remove',ruleId:rule.id}}); + await trust.commit(f.principal.id,{version:1,requestId:prepared.receipt.requestId,reviewId:prepared.review.reviewId,reviewedBytesHash:prepared.review.reviewedBytesHash}); + } + if(input.action==='individual_safe'){ + if(!verifiedId)throw new Error('Missing verified occurrence');failVerdict=false; + const p=f.writes.safety(null,'ithaca'),body={version:1 as const,session:p.session!,occurrenceId:verifiedId,expectedEvidenceRevision:p.evidenceRevision,verdict:'safe' as const}; + const prepared=await originalReview(f.principal,body,null);await originalReview(f.principal,body,prepared.receipt.requestId!); + } if(input.action==='retire'){ const result=retireChat(f.db,{operationId:'odysseus-retire',principalId:f.principal.id,target:{sessionId:'ithaca'},expected:{backendId:'claude',generation:1},removableBackends:['claude'],at:Date.now()}); if(result.status!=='retired')throw new Error('Fixture retirement failed');f.host.chatRetired(f.principal.id,result);return c.json({retired:true,commits,prepares}); } + if(input.action==='add_verified'){ + const o=occurrence(f.bindingId,'proxy_input',null,'finalized');verifiedId=o.id;o.provenance={kind:'web_origin',origin:{scheme:'https',host:'ithaca.invalid',port:443},verifiedBy:'host_transport'}; + await observedWrites.record({kind:'taint',sessionId:'ithaca',turnId:'voyage',actor:'interactive',model:null,profile:'governed',payload:{source:'egress_connection',tool:'shell',detail:null,occurrence:o}}); + } if(input.action==='add')await tool(input.id??'tool_d',input.finalized!==false); if(input.action==='prune')pruneSafetyDetail(f.db,Number.MAX_SAFE_INTEGER); if(input.action==='loss')await f.writes.safetyFail('voyage'); diff --git a/packages/ui-react/tests/render/slide-panel.test.tsx b/packages/ui-react/tests/render/slide-panel.test.tsx index 86e754210f..88dc193b97 100644 --- a/packages/ui-react/tests/render/slide-panel.test.tsx +++ b/packages/ui-react/tests/render/slide-panel.test.tsx @@ -284,7 +284,7 @@ describe("Settings drawer while a credential is protected", () => { const view = render(); await act(flushPromises); await act(async () => { await import("../../src/components/settings/devices-agents-tab.js"); await new Promise(resolve => setTimeout(resolve, 0)); }); - expect(view.getByText("Could not read this brain's enforcing policy. Open Settings again to check.")).toBeTruthy(); + expect(view.getByText("Could not read this brain's enforcing policy. Refresh Settings to check again.")).toBeTruthy(); fireEvent.pointerDown(backdropOf(view)); escape(); expect(onClose).toHaveBeenCalledTimes(0); diff --git a/packages/ui-react/tests/safety-client.test.ts b/packages/ui-react/tests/safety-client.test.ts index 6999ead275..8b763683f3 100644 --- a/packages/ui-react/tests/safety-client.test.ts +++ b/packages/ui-react/tests/safety-client.test.ts @@ -46,13 +46,14 @@ test("an old host receives no safety read or unsubscribe frames and remains expl }); test('entry correlation is requested only after the independent host capability',()=>{ - for(const entries of [false,true]){ + for(const entries of [false,true])for(const admissions of [false,true]){ const chat=createStore<{activeSessionId:string|null}>(()=>({activeSessionId:'ithaca'})),safety=createSafetyStore(),sent:ClientMessage[]=[]; const root={stores:{chat,safety}} as unknown as BrainUiServices,client=createSafetyClient(root,m=>{sent.push(m);return true;}); try{ - client.frame({type:'server_hello',protocolRev:5,capabilities:{sessionSafetyHistory:true,...(entries?{sessionSafetyEntryCorrelation:true}:{})},safetyCapabilities:{version:1,read:true,review:false,originRules:false,repositoryRules:false,recipientRules:false,readOnlyReason:'owner_required',detectorVersion:1,limits:{pageRecords:100,frameBytes:262144,cursorBytes:512,cursorLifetimeMs:300000}}}); + client.frame({type:'server_hello',protocolRev:5,capabilities:{sessionSafetyHistory:true,...(entries?{sessionSafetyEntryCorrelation:true}:{}),...(admissions?{sessionSafetyAdmissionEvidence:true}:{})},safetyCapabilities:{version:1,read:true,review:false,originRules:false,repositoryRules:false,recipientRules:false,readOnlyReason:'owner_required',detectorVersion:1,limits:{pageRecords:100,frameBytes:262144,cursorBytes:512,cursorLifetimeMs:300000}}}); const read=sent.find(m=>m.type==='safety_read');expect(read?.type).toBe('safety_read'); if(entries)expect(read).toHaveProperty('includeEntries',true);else expect(read,'OLD_HOST_NEVER_RECEIVES_UNKNOWN_READ_FIELD').not.toHaveProperty('includeEntries'); + if(admissions)expect(read).toHaveProperty("includeAdmissions",true);else expect(read,"OLD_HOST_NEVER_RECEIVES_ADMISSION_FIELD").not.toHaveProperty("includeAdmissions"); expect(safety.getState().capabilities?.review).toBe(false); safety.getState().refresh();expect(sent.filter(m=>m.type==='safety_read')).toHaveLength(2);expect(sent.every(m=>!m.type.includes('review'))).toBe(true); }finally{client.dispose();} @@ -289,3 +290,15 @@ test("a correlated capacity refusal terminates the active recovery page", () => expect(safety.getState(), "ACTIVE_READ_CAPACITY_REFUSAL_REMAINS_TERMINAL").toMatchObject({ status: "unavailable", requestId: null, reason: "capacity", normal: false }); } finally { client.dispose(); } }); + +test('review F2: future rules require the additive boolean offer and live review capability',()=>{ + for(const offered of [false,true])for(const review of [false,true]){ + const f=supportedClient('ithaca');try{ + f.client.frame({...hello,capabilities:{sessionSafetyHistory:true,sessionSafetyFutureRules:offered},safetyCapabilities:{...SAFETY_READ_CAPABILITIES,review,originRules:false,recipientRules:false}}); + expect(f.safety.getState().supported).toBe(true); + expect(f.safety.getState().capabilities?.originRules,'F2_BOOLEAN_OFFER_CONTROLS_NEW_UI').toBe(offered&&review); + expect(f.safety.getState().capabilities?.recipientRules).toBe(offered&&review); + expect(f.sent.some(m=>m.type==='safety_read')).toBe(true); + }finally{f.client.dispose();} + } +}); diff --git a/packages/ui-react/tests/safety-reviewer.test.ts b/packages/ui-react/tests/safety-reviewer.test.ts index 253aec9d0f..b5a7842b1e 100644 --- a/packages/ui-react/tests/safety-reviewer.test.ts +++ b/packages/ui-react/tests/safety-reviewer.test.ts @@ -6,18 +6,33 @@ import {createBrainApi} from '../src/lib/api-client'; import {createSafetyReviewer,type SafetyReviewProgress} from '../src/lib/safety-reviewer'; import type {BrainUiServices} from '../src/root'; -async function fixture(){ - const host=await safetyHistoryFixture(true,true),a=await host.add('A'),b=await host.add('B'),c=await host.add('C'); +async function fixture(future=false){ + const host=await safetyHistoryFixture(true,true); + const add=async(name:string)=>{ + if(!future)return host.add(name); + const {occurrence}=await import('../../ui-server/src/governance/occurrence'); + const o=occurrence(host.bindingId,'proxy_input',name,'finalized');o.provenance={kind:'web_origin',origin:{scheme:'https',host:'ithaca.invalid',port:443},verifiedBy:'host_transport'}; + await host.writes.record({kind:'taint',turnId:'voyage',sessionId:'ithaca',actor:'interactive',model:null,profile:'governed',payload:{source:'egress_connection',tool:'shell',detail:null,occurrence:o}});return o; + }; + const a=await add('A'),b=await add('B'),c=await add('C'); + let futureServer:ReturnType|undefined; + let futureSettings:ReturnType|undefined; + if(future){ + const {Hono}=await import('hono'),{createKeyedLock}=await import('@schlessera/brain-ui-sdk/server'),{createTrustSettings}=await import('../../ui-server/src/brain/trust-settings'),{CombinedSafetyReviews}=await import('../../ui-server/src/governance/combined-safety-reviews'),{createOwnerSafetyReviewRoutes}=await import('../../ui-server/src/routes/owner-safety-review'),{authGuard}=await import('../../ui-server/src/middleware/auth'); + futureSettings=createTrustSettings({root:host.root,db:host.db,writer:host.writer,lock:createKeyedLock(),originEnforcement:true,authority:id=>id===host.principal.id&&host.reviews!.authorized(host.principal)?'owner-epoch':null,observe:async(_id,write)=>{await write();}}); + const app=new Hono();app.use('/api/*',authGuard('password',host.auth,host.db));app.route('/api',createOwnerSafetyReviewRoutes(host.reviews!,false,new CombinedSafetyReviews(host.db,host.reviews!,futureSettings))); + futureServer=Bun.serve({hostname:'127.0.0.1',port:0,fetch:app.fetch}); + } const safety=createSafetyStore(),chat=createStore(()=>({activeSessionId:'ithaca' as string|null})),auth=createStore(()=>({phase:'active' as 'active'|'locked'})); - safety.getState().reset(true,host.reviews!.capabilities(host.principal)); + safety.getState().reset(true,{...host.reviews!.capabilities(host.principal),...(future?{originRules:true,recipientRules:true}:{})}); const page=await host.history.read(host.principal,{sessionId:'ithaca'}); safety.getState().begin('snapshot');safety.getState().page('snapshot',page); - const origin=host.url.replace('ws:','http:').replace('/ws',''),requests:string[]=[],progress:SafetyReviewProgress[]=[]; + const origin=futureServer?`http://127.0.0.1:${futureServer.port}`:host.url.replace('ws:','http:').replace('/ws',''),requests:string[]=[],progress:SafetyReviewProgress[]=[]; let epoch=0,transport:(url:string,init:RequestInit)=>Promise=(url,init)=>fetch(url,init); const api=createBrainApi(()=>origin+'/api',(url,init)=>{requests.push(url);return transport(url,{...init,headers:{...init?.headers,cookie:host.cookie,origin}});}); const root={api,stores:{safety,chat},authLock:{state:auth,epoch:()=>epoch}} as unknown as BrainUiServices; const reviewer=createSafetyReviewer(root,p=>progress.push(p)); - return {host,a,b,c,safety,chat,auth,requests,progress,root,reviewer,setTransport(next:typeof transport){transport=next;},revoke(){epoch++;auth.setState({phase:'locked'});},async close(){reviewer.dispose();await host.close();}}; + return {host,a,b,c,safety,chat,auth,requests,progress,root,reviewer,futureSettings,setTransport(next:typeof transport){transport=next;},revoke(){epoch++;auth.setState({phase:'locked'});},async close(){reviewer.dispose();futureServer?.stop(true);await host.close();}}; } const gate=()=>{let release!:(v:Response)=>void;const promise=new Promise(r=>{release=r;});let entered!:()=>void;const arrived=new Promise(r=>{entered=r;});return {release,promise,entered,arrived};}; @@ -103,3 +118,76 @@ test('disconnect after preparation discards authority and a fresh read never res expect(f.requests,'FRESH_READ_NEVER_REPLAYS_A_DECISION').toHaveLength(1);expect(f.host.db.query('SELECT COUNT(*) n FROM safety_decisions').get()).toEqual({n:0}); }finally{await f.close();} }); + +for(const field of ['occurrenceId','sessionId','historyOwnerId','historyGeneration'] as const)test(`matrix CP-M ${field}: prepared response must match the requested target`,async()=>{ + const f=await fixture(true);try{ + f.setTransport(async(url,init)=>{ + if(!url.endsWith('/future/prepare'))return fetch(url,init); + const body=JSON.parse(String(init.body)); + // The important same-session case uses a real, valid prepared B response. + const response=await fetch(url,{...init,body:JSON.stringify({...body,occurrenceId:f.b.id})});const value=await response.json(); + if(field!=='occurrenceId'){value.occurrenceId=f.a.id;value.session={...value.session,[field]:field==='historyGeneration'?'999':'wrong_target'};} + return Response.json(value,{status:response.status}); + }); + const result=await f.reviewer.prepareFuture(f.a.id,false); + expect(result,'R3F2_PREPARED_RESPONSE_MUST_MATCH_REQUEST').toBeNull(); + await f.reviewer.commitFuture();expect(f.requests.filter(url=>url.endsWith('/commit'))).toHaveLength(0); + expect(f.progress.at(-1)?.stage).toBe('refused');expect(f.host.db.query('SELECT count(*) n FROM safety_decisions').get()).toEqual({n:0}); + }finally{await f.close();} +}); + +const futureBody=(f:Awaited>)=>({version:1 as const,session:f.safety.getState().identity as import('@schlessera/brain-ui-sdk/protocol').SafetyReviewBody['session'],occurrenceId:f.a.id,expectedEvidenceRevision:f.safety.getState().revision,verdict:'safe' as const}); +test('matrix CP-R: explicit retry replaces the prepared handle; CB-R dispatch consumes it once',async()=>{ + const f=await fixture(true);try{ + const one=await f.reviewer.prepareFuture(f.a.id,false),two=await f.reviewer.prepareFuture(f.a.id,false);expect(two?.requestId).not.toBe(one?.requestId); + let sent:string|undefined;f.setTransport(async(url,init)=>{if(url.endsWith('/future/commit'))sent=JSON.parse(String(init.body)).requestId;return fetch(url,init);}); + await f.reviewer.commitFuture();await f.reviewer.commitFuture();expect(sent).toBe(two?.requestId);expect(f.requests.filter(u=>u.endsWith('/future/commit'))).toHaveLength(1);expect(f.progress.at(-1)?.stage).toBe('committed'); + }finally{await f.close();} +}); +for(const kind of ['pending','quota'] as const)test(`matrix CP-L ${kind}: no parallel preparation or quota bypass`,async()=>{ + const f=await fixture(true);let pressure:{close():Promise}|undefined;const hold=gate();try{ + if(kind==='quota'){const {holdOwnerReviews}=await import('../../ui-server/tests/helpers/held-owner-reviews');pressure=await holdOwnerReviews({...f.host,reviews:f.host.reviews!},futureBody(f));expect(await f.reviewer.prepareFuture(f.a.id,false)).toBeNull();expect(f.progress.at(-1)?.stage).toBe('refused');} + else{f.setTransport(async(url,init)=>{const response=await fetch(url,init);hold.entered();await hold.promise;return response;});const pending=f.reviewer.prepareFuture(f.a.id,false);await hold.arrived;expect(await f.reviewer.prepareFuture(f.a.id,false)).toBeNull();hold.release(new Response());await pending;expect(f.requests).toHaveLength(1);} + await f.reviewer.commitFuture();if(kind==='quota')expect(f.requests.filter(u=>u.endsWith('/future/commit'))).toHaveLength(0); + }finally{hold.release(new Response());await pressure?.close();await f.close();} +}); +for(const timing of ['pending','idle'] as const)for(const change of ['owner','evidence','selection','disconnect','capability'] as const)test(`matrix CP-E ${timing} ${change}: withdrawn context cannot commit`,async()=>{ + const f=await fixture(true),hold=gate();try{ + if(timing==='pending')f.setTransport(async(url,init)=>{const response=await fetch(url,init);hold.entered();await hold.promise;return response;}); + const pending=f.reviewer.prepareFuture(f.a.id,false);if(timing==='pending')await hold.arrived;else await pending; + if(change==='owner')f.revoke();else if(change==='selection')f.chat.setState({activeSessionId:'troy'});else if(change==='evidence')f.safety.setState({revision:'999'});else if(change==='disconnect')f.safety.setState({status:'unavailable'});else f.safety.setState({capabilities:{...f.safety.getState().capabilities!,review:false}}); + hold.release(new Response());await pending;await f.reviewer.commitFuture();expect(f.requests.filter(u=>u.endsWith('/future/commit'))).toHaveLength(0);expect(f.progress.at(-1)?.stage).toBe('refused'); + }finally{hold.release(new Response());await f.close();} +}); +test('matrix CP-F: failed explicit retry cannot reuse the old prepared handle',async()=>{ + const f=await fixture(true);try{expect(await f.reviewer.prepareFuture(f.a.id,false)).not.toBeNull();f.setTransport(async()=>{throw new Error('Prepare response lost');});expect(await f.reviewer.prepareFuture(f.a.id,false)).toBeNull();await f.reviewer.commitFuture();expect(f.requests.filter(u=>u.endsWith('/future/commit'))).toHaveLength(0);expect(f.progress.at(-1)?.stage).toBe('refused');}finally{await f.close();} +}); +test('matrix CB-L: real review quota yields partial without optimistic ledger replacement',async()=>{ + const f=await fixture(true);let pressure:{close():Promise}|undefined;try{await f.reviewer.prepareFuture(f.a.id,false);const {holdOwnerReviews}=await import('../../ui-server/tests/helpers/held-owner-reviews');pressure=await holdOwnerReviews({...f.host,reviews:f.host.reviews!},futureBody(f));await f.reviewer.commitFuture();expect(f.progress.at(-1)?.stage).toBe('partial');expect(f.safety.getState().projection?.unresolvedCount).toBe(3);}finally{await pressure?.close();await f.close();} +}); +test('matrix CB-E: expired publication review is unknown to the client and never replayed',async()=>{ + const f=await fixture(true);try{const p=await f.reviewer.prepareFuture(f.a.id,false);f.host.db.query('UPDATE trust_settings_operations SET expires_at=0 WHERE request_id=?').run(p!.requestId);await f.reviewer.commitFuture();await f.reviewer.commitFuture();expect(f.progress.at(-1)?.stage).toBe('unknown');expect(f.requests.filter(u=>u.endsWith('/future/commit'))).toHaveLength(1);expect(f.safety.getState().projection?.unresolvedCount).toBe(3);}finally{await f.close();} +}); +for(const field of ['requestId','session','occurrenceId','nestedSession','nestedOccurrence'] as const)test(`matrix CB-M ${field}: foreign commit receipt is never acknowledged`,async()=>{ + const f=await fixture(true);try{await f.reviewer.prepareFuture(f.a.id,false);f.setTransport(async(url,init)=>{const response=await fetch(url,init);if(!url.endsWith('/future/commit'))return response;const result=await response.json();if(field==='requestId')result.requestId='different_request';else if(field==='session')result.session.sessionId='troy';else if(field==='occurrenceId')result.occurrenceId=f.b.id;else if(field==='nestedSession')result.verdict.session.sessionId='troy';else result.verdict.occurrenceId=f.b.id;return Response.json(result);});await f.reviewer.commitFuture();expect(f.progress.at(-1)?.stage).toBe('unknown');expect(f.safety.getState().projection?.unresolvedCount).toBe(3);}finally{await f.close();} +}); +for(const boundary of ['before','after'] as const)test(`matrix CB-F ${boundary}: lost commit response is unknown with no replay`,async()=>{ + const f=await fixture(true);try{await f.reviewer.prepareFuture(f.a.id,false);f.setTransport(async(url,init)=>{if(boundary==='after')await fetch(url,init);throw new Error('Commit response lost');});await f.reviewer.commitFuture();await f.reviewer.commitFuture();expect(f.progress.at(-1)?.stage).toBe('unknown');expect(f.requests.filter(u=>u.endsWith('/future/commit'))).toHaveLength(1);expect(f.safety.getState().projection?.unresolvedCount).toBe(3);expect(f.host.db.query('SELECT count(*) n FROM safety_decisions').get()).toEqual({n:boundary==='after'?1:0});}finally{await f.close();} +}); + +for(const future of [false,true])test(`fable F1: ${future?'combined':'individual'} own live verdict update before HTTP response still commits`,async()=>{ + const f=await fixture(future);try{ + f.setTransport(async(url,init)=>{const response=await fetch(url,init);if(url.endsWith('/commit')){const result=await response.clone().json();const projection=result.currentProjection;f.safety.setState({revision:projection.evidenceRevision,projection});}return response;}); + if(future){await f.reviewer.prepareFuture(f.a.id,false);await f.reviewer.commitFuture();}else await f.reviewer.markSafe(f.a.id); + expect(f.progress.at(-1)?.stage,'OWN_LIVE_UPDATE_MUST_NOT_ABORT_COMMIT').toBe('committed'); + }finally{await f.close();} +}); +for(const cancel of [false,true])test(`fable F2: prepared future ${cancel?'cancel then ':''}individual review stays recorded after refresh`,async()=>{ + const f=await fixture(true);try{ + await f.reviewer.prepareFuture(f.a.id,false); + if(cancel)f.reviewer.cancelFuture(); + await f.reviewer.markSafe(f.a.id);expect(f.progress.at(-1)?.stage).toBe('committed'); + const page=await f.host.history.read(f.host.principal,{sessionId:'ithaca'});f.safety.setState({revision:page.highWater}); + expect(f.progress.at(-1)?.message,'UNUSED_FUTURE_HANDLE_CANNOT_RELABEL_COMMITTED_VERDICT').toContain('Decision recorded'); + }finally{await f.close();} +}); diff --git a/packages/ui-sdk/src/internal.ts b/packages/ui-sdk/src/internal.ts index adc04531c4..1260cef8b4 100644 --- a/packages/ui-sdk/src/internal.ts +++ b/packages/ui-sdk/src/internal.ts @@ -1,3 +1,4 @@ +export { safetyRecordSchema, safetyOccurrenceAdmissionSchema, safetyAdmissionSchema } from "./safety.js"; /** First-party implementation sharing. No compatibility guarantee; use the same lockstep version. */ export { BRAIN_INTERACTION_GUIDANCE, projectConversationGuidance, conversationOrientation, ORIENTATION_MAX_BYTES } from "./server/interaction-guidance.js"; export { prepareRecoveredWorkerFiles, recoveredWorkerFile, recoveredWorkerFiles } from "./server/worker-identity-reader.js"; @@ -22,10 +23,10 @@ export { execWrapperSpawnOptions, workerExecHelpers } from "./server/exec-wrappe export { assertScratchMaskAsync } from "./server/bridge-tools/mask.js"; export { startInferenceRelay, ANTHROPIC_INFERENCE_ROUTES, INFERENCE_PLACEHOLDER, WORKER_INFERENCE_SOCKET } from "./server/inference-relay.js"; export type { InferenceRelay, InferenceRelayEvent } from "./server/inference-relay.js"; -export { startEgressProxy, egressAddressRefusal, egressBootstrapEntry, EgressAdmissionRefused, WORKER_EGRESS_DIR, WORKER_EGRESS_TRANSPORT_ENV } from "./server/egress-proxy.js"; +export { startEgressProxy, canonicalEgressHost, validatedEgressProvenance, egressChargeRefusal, egressAddressRefusal, egressBootstrapEntry, EgressAdmissionRefused, WORKER_EGRESS_DIR, WORKER_EGRESS_TRANSPORT_ENV } from "./server/egress-proxy.js"; export { startProviderRelay, parseCliProviderOrigins, relayedProviderKeys, heldCustomProviderKeys, PROVIDER_RELAY_KEYS_NAME, FIRST_PARTY_PROVIDER_RECIPIENTS, PROVIDER_RELAY_SOCKET_NAME, type ProviderRelay, type ProviderRelayOptions, type ProviderRelayReceipt, type ProviderRelayRefusal } from "./server/provider-relay.js"; export { hostProviderCredential, hostComputeCredential } from "./config/env.js"; -export type { EgressDestinationPolicy, EgressRecord, EgressRefusal } from "./server/egress-proxy.js"; +export type { EgressDestinationPolicy, EgressRecord, EgressRefusal, EgressChargeResult, EgressChargeFailure, EgressFailureReason } from "./server/egress-proxy.js"; export { restrictedReadPaths } from "./server/worker-launcher.js"; export { prepareWorkerSandbox, prepareWorkerSandboxAsync } from "./server/worker-launcher.js"; export { workerProfile, workerSandboxNote, workerSandboxWarnings, mountPointsUnder, BRAIN_SCRATCH_DIR, BRAIN_WORKSPACES_DIR, WORKER_XDG_DIRS } from "./server/worker-sandbox.js"; diff --git a/packages/ui-sdk/src/protocol.ts b/packages/ui-sdk/src/protocol.ts index 59a6e0a114..50ddaaa00c 100644 --- a/packages/ui-sdk/src/protocol.ts +++ b/packages/ui-sdk/src/protocol.ts @@ -1,3 +1,4 @@ +export type { SafetyFuturePrepare, SafetyFutureCommit, SafetyFuturePrepared } from "./safety.js"; export { SESSION_SAFETY_CAPABILITY, SAFETY_READ_CAPABILITIES } from "./safety.js"; export type { SafetyReviewBody, SafetyReviewReceipt, SafetyReviewResponse, SafetySessionKey, SafetyTarget, SafetyIdentity, SafetyHistoryProjection, SafetyRecord, SafetyPage, SafetyUpdate, SafetyUnavailable, SafetyCapabilities, ClientSafetyRead, ClientSafetySubscribe, ClientSafetyUnsubscribe, ServerSafetyHistory, ServerSafetyUpdate, ServerSafetyUnavailable } from "./safety.js"; import type { ClientSafetyRead, ClientSafetySubscribe, ClientSafetyUnsubscribe, ServerSafetyHistory, ServerSafetyUpdate, ServerSafetyUnavailable, SafetyCapabilities } from "./safety.js"; diff --git a/packages/ui-sdk/src/safety.ts b/packages/ui-sdk/src/safety.ts index c17c415b6a..c53e9184de 100644 --- a/packages/ui-sdk/src/safety.ts +++ b/packages/ui-sdk/src/safety.ts @@ -19,10 +19,19 @@ const source = z.enum(["web_fetch", "web_search", "staged_share", "chat_attachme const exposure = z.enum(["open", "finalized", "interrupted_unknown"]); const provenance = z.union([z.null(), z.strictObject({ kind: z.literal("web_origin"), origin: z.strictObject({scheme:z.enum(["http","https"]),host:text(253),port:z.number().int().min(1).max(65535)}), verifiedBy:z.literal("host_transport") }), z.strictObject({kind:z.literal("tunnel_authority"),authority:z.strictObject({host:text(253),port:z.number().int().min(1).max(65535)}),verifiedBy:z.literal("host_proxy")})]); +export const safetyAdmissionSchema = z.discriminatedUnion("trusted",[ + z.strictObject({trusted:z.literal(false),policyHash:z.string().regex(/^[a-f0-9]{64}$/).nullable(),trustRevision:revision}), + z.strictObject({trusted:z.literal(true),ruleId:id,policyHash:z.string().regex(/^[a-f0-9]{64}$/),trustRevision:revision,collectionRevision:revision}), + ]); +/** Shared recorder/history evidence. Trusted input is only verified proxy content. */ +export const safetyOccurrenceAdmissionSchema = z.object({detector:id.nullable(),provenance, + admission:safetyAdmissionSchema.optional(), +}).refine(v=>!v.admission?.trusted || v.detector === "proxy_input" && v.provenance !== null, + {message:"Trusted admission requires verified proxy provenance"}); const common = { id, sequence: revision, observedAt: time, turnId: id, bindingId: id, occurrenceId: id, detailPruned: z.boolean() }; export const safetyRecordSchema = z.discriminatedUnion("kind", [ - z.strictObject({ ...common, kind:z.literal("occurrence"), epochId:id, detector:id.nullable(), source, operationId:id.nullable(), signalId:id.nullable(), exposureId:id.nullable(), exposure, - summary:text(2048), provenance, entry:z.strictObject({kind:z.literal("tool"),toolUseId:id}).optional() }), + safetyOccurrenceAdmissionSchema.safeExtend({ ...common, kind:z.literal("occurrence"), epochId:id, source, operationId:id.nullable(), signalId:id.nullable(), exposureId:id.nullable(), exposure, + summary:text(2048), entry:z.strictObject({kind:z.literal("tool"),toolUseId:id}).optional() }).strict(), z.strictObject({ ...common, kind:z.literal("exposure"), state:exposure }), z.strictObject({ ...common, kind:z.literal("safe_decision"), session:safetySessionKeySchema, requestId:id, principalId:id, verdict:z.literal("safe"), channel:z.enum(["owner_history","owner_settings"]) }), ]); @@ -31,7 +40,7 @@ export const safetyPageSchema = z.strictObject({ version:z.literal(1), identity: export const safetyUpdateSchema = z.strictObject({ version:z.literal(1), identity:safetyIdentitySchema, fromRevision:revision, toRevision:revision, projection:safetyProjectionSchema, records:z.array(safetyRecordSchema).max(100) }); export const safetyUnavailableSchema = z.strictObject({ version:z.literal(1), reason:z.enum(["unavailable","unauthorized","expired","capacity","generation_changed","gap"]) }); -export const safetyCapabilitiesSchema = z.strictObject({ version:z.literal(1), read:z.literal(true), review:z.boolean(), originRules:z.literal(false), repositoryRules:z.literal(false), recipientRules:z.literal(false), +export const safetyCapabilitiesSchema = z.strictObject({ version:z.literal(1), read:z.literal(true), review:z.boolean(), originRules:z.boolean(), repositoryRules:z.literal(false), recipientRules:z.boolean(), readOnlyReason:z.enum(["review_unavailable","owner_required"]).nullable(), detectorVersion:z.literal(1), limits:z.strictObject({ pageRecords:z.literal(100), frameBytes:z.literal(262144), cursorBytes:z.literal(512), cursorLifetimeMs:z.literal(300000), reviewBodyBytes:z.literal(16384).optional(), reviewLifetimeMs:z.literal(900000).optional(), receiptLifetimeMs:z.literal(86400000).optional() }) }); export const SESSION_SAFETY_CAPABILITY = "sessionSafetyHistory"; @@ -63,7 +72,7 @@ export type SafetyReviewBody = z.infer; export type SafetyReviewReceipt = z.infer; export type SafetyReviewResponse = z.infer; -export const clientSafetyReadSchema = z.strictObject({type:z.literal("safety_read"),requestId:id,version:z.literal(1),target:safetyTargetSchema,cursor:z.string().max(512).nullable().optional(),limit:z.number().int().min(1).max(100).optional(),includeEntries:z.literal(true).optional()}); +export const clientSafetyReadSchema = z.strictObject({type:z.literal("safety_read"),requestId:id,version:z.literal(1),target:safetyTargetSchema,cursor:z.string().max(512).nullable().optional(),limit:z.number().int().min(1).max(100).optional(),includeEntries:z.literal(true).optional(),includeAdmissions:z.literal(true).optional()}); export const clientSafetySubscribeSchema = z.strictObject({type:z.literal("safety_subscribe"),requestId:id,version:z.literal(1),identity:safetyIdentitySchema,afterRevision:revision,snapshotId:id}); export const clientSafetyUnsubscribeSchema = z.strictObject({type:z.literal("safety_unsubscribe"),version:z.literal(1)}); export const serverSafetyHistorySchema = z.strictObject({type:z.literal("safety_history"),requestId:id,page:safetyPageSchema}); @@ -75,3 +84,16 @@ export type ClientSafetyUnsubscribe = z.infer; export type ServerSafetyUpdate = z.infer; export type ServerSafetyUnavailable = z.infer; + +/** Optional prospective rule review. Repository identity remains unavailable. */ +export const safetyFuturePrepareSchema=safetyReviewBodySchema.extend({future:z.strictObject({incomingContent:z.literal(true),recipientWhileRestricted:z.boolean()})}); +export const safetyFutureCommitSchema=z.strictObject({version:z.literal(1),requestId:id,reviewId:id,reviewedBytesHash:z.string().regex(/^[a-f0-9]{64}$/u)}); +const futureRuleReceipt=z.strictObject({version:z.literal(1),requestId:id,operationId:id,stage:z.enum(["prepared","file_published","committed","partial","unknown","refused"]),publication:z.enum(["not_published","proved","unknown"]),ruleId:id,publishedTrustRevision:revision.nullable(),currentRule:z.enum(["present","removed","changed","unknown"]),enforcement:z.enum(["unavailable","enforced"]),reason:text(512).nullable()}); +export const safetyFuturePreparedSchema=z.strictObject({version:z.literal(1),requestId:id,session:safetySessionKeySchema,occurrenceId:id, + review:z.strictObject({reviewId:id,base:text(196608).nullable(),proposed:text(196608),diff:text(196608),reviewedBytesHash:z.string().regex(/^[a-f0-9]{64}$/u),expiresAt:time,repositoryIdentity:z.null(),includesFutureRepositories:z.boolean()}),rule:futureRuleReceipt,currentProjection:safetyProjectionSchema.nullable()}); +export const safetyFutureResultSchema=z.strictObject({version:z.literal(1),requestId:id,session:safetySessionKeySchema,occurrenceId:id,stage:z.enum(["prepared","verdict_committed","partial","unknown","refused"]),rule:futureRuleReceipt,verdict:safetyReviewReceiptSchema.nullable(),currentProjection:safetyProjectionSchema}); +export type SafetyFuturePrepare=z.infer; +export type SafetyFutureCommit=z.infer; +export type SafetyFuturePrepared=z.infer; + +export const safetyFutureStatusSchema=z.strictObject({version:z.literal(1),session:safetySessionKeySchema,occurrenceId:id}); diff --git a/packages/ui-sdk/src/schemas.ts b/packages/ui-sdk/src/schemas.ts index 452cd2e509..be6b207130 100644 --- a/packages/ui-sdk/src/schemas.ts +++ b/packages/ui-sdk/src/schemas.ts @@ -1,3 +1,4 @@ +export { safetyFutureStatusSchema, safetyFuturePrepareSchema, safetyFutureCommitSchema, safetyFuturePreparedSchema, safetyFutureResultSchema } from "./safety.js"; export { safetyProjectionSchema, safetyReviewBodySchema, safetyReviewReceiptSchema, safetyReviewResponseSchema, safetySessionKeySchema, safetyPageSchema, safetyUpdateSchema, safetyCapabilitiesSchema } from "./safety.js"; import { clientSafetyReadSchema, clientSafetySubscribeSchema, clientSafetyUnsubscribeSchema, serverSafetyHistorySchema, serverSafetyUpdateSchema, serverSafetyUnavailableSchema, safetyCapabilitiesSchema } from "./safety.js"; import { POLICY_CHANGE_REVIEW_SCHEMA } from "./tool-contracts/policy.js"; @@ -2293,3 +2294,6 @@ export const queueAddRequestSchema = z.strictObject({ export const queueAddResultSchema = z.looseObject({ queued: z.literal(true), created: z.boolean(), threadId: id, itemId: id, stagingId: id, }) satisfies z.ZodType; + +/** Canonical Settings inputs, shared with the protected policy writer. */ +export { parseTrustOrigin, parseTrustTunnel, parseTrustGithub, TrustRuleSchema, TrustedSourcesSchema } from "@schlessera/brain-common/internal/taint-trust"; diff --git a/packages/ui-sdk/src/server/admission-safety.ts b/packages/ui-sdk/src/server/admission-safety.ts index 5c9c8c6e60..25a31973ed 100644 --- a/packages/ui-sdk/src/server/admission-safety.ts +++ b/packages/ui-sdk/src/server/admission-safety.ts @@ -7,11 +7,14 @@ export interface AdmissionSafetySnapshot { readonly policyHash: string | null; readonly restricted: boolean; readonly recordingAvailable: boolean; + /** False only for this turn recorder; true distinguishes shared safety changes. */ + readonly operationRecordingAvailable?: boolean; readonly authorityCurrent: boolean; } export interface AdmissionSafety { - read(): AdmissionSafetySnapshot; + /** Host-owned reservations only; exclusions never alter retained evidence or recorder failures. */ + read(excludedPending?:readonly string[]): AdmissionSafetySnapshot; /** Invalidation is a hint; every commit still reads synchronously. */ subscribe(changed: () => void): () => void; } @@ -21,7 +24,7 @@ export const STALE_SAFETY_ADMISSION = "Safety or authority changed before admiss export function sameSafetyAdmission(a: AdmissionSafetySnapshot, b: AdmissionSafetySnapshot): boolean { return a.evidenceRevision === b.evidenceRevision && a.trustRevision === b.trustRevision && a.authorityEpoch === b.authorityEpoch && a.scope === b.scope && a.policyHash === b.policyHash && a.restricted === b.restricted - && a.recordingAvailable === b.recordingAvailable && a.authorityCurrent === b.authorityCurrent; + && a.operationRecordingAvailable === b.operationRecordingAvailable && a.recordingAvailable === b.recordingAvailable && a.authorityCurrent === b.authorityCurrent; } /** Call in the dispatching continuation, after its last await. */ diff --git a/packages/ui-sdk/src/server/egress-accounting.ts b/packages/ui-sdk/src/server/egress-accounting.ts new file mode 100644 index 0000000000..45e7c10133 --- /dev/null +++ b/packages/ui-sdk/src/server/egress-accounting.ts @@ -0,0 +1,23 @@ +import type { EgressChargeFailure, EgressChargeResult } from './egress-proxy.js'; + +/** Bytes already received consume the available allowance before excess is refused. */ +export function chargeReceivedBytes(count:number,options:{remaining():number;charge(count:number):EgressChargeFailure|undefined}):EgressChargeFailure|undefined { + if(!Number.isSafeInteger(count)||count<0)throw new RangeError('Received byte count must be a nonnegative safe integer'); + const available=options.remaining(); + if(count>available&&available>0){const failure=options.charge(available);if(failure)return failure;count-=available;} + return options.charge(count); +} + +/** Legacy operation-only routes retain a bounded per-request allowance. */ +export function relayAllowance(operation:{charge(count:number):EgressChargeResult;finish(outcome:"denied",reason:string):void}|undefined,reader:(()=>number)|undefined,limit:number) { + let charged=0; + const remaining=()=>operation ? reader?.() ?? Math.max(0,limit-charged) : Infinity; + const charge=(count:number):EgressChargeFailure|undefined=>{ + if(!Number.isSafeInteger(count)||count<0)throw new RangeError("Relay charge bytes must be a nonnegative safe integer"); + if(operation&&!reader&&count>remaining()){const live=operation.charge(0);if(!live.ok)return live;operation.finish("denied","max_bytes_per_turn");return {ok:false,reason:"budget"};} + const result=operation?.charge(count); + if(result&&!result.ok)return result; + charged+=count;return undefined; + }; + return {charge,remaining}; +} diff --git a/packages/ui-sdk/src/server/egress-operation.ts b/packages/ui-sdk/src/server/egress-operation.ts new file mode 100644 index 0000000000..4d3148d2d8 --- /dev/null +++ b/packages/ui-sdk/src/server/egress-operation.ts @@ -0,0 +1,96 @@ +/** Distinguishes a transport constructor/write failure from an admission refusal. */ +export class TransportHandoffFailed extends Error { + constructor(){super("Upstream transport handoff failed");this.name="TransportHandoffFailed";} +} +/** One concrete proxy operation's lifecycle; transport callbacks never advance state themselves. */ +export type EgressOperationState = 'pending' | 'admitted' | 'dispatched' | 'finished' | 'aborted'; +export interface EgressOperationTerminal { + outcome: 'completed' | 'denied' | 'failed' | 'cancelled'; + reason?: string; + dispatched: boolean; +} +export function createEgressOperation(options: { + decide(terminal: EgressOperationTerminal): void; + abort(): void; + observe(terminal: EgressOperationTerminal): void; +}) { + let state: EgressOperationState = 'pending'; + let terminal: EgressOperationTerminal | undefined, observed = false; + let admission: Promise | undefined, effectCount = 0, prepared=false; + const effects = new Set>(); + const cleanups=new Set<()=>void>(); + const active = () => state !== 'finished' && state !== 'aborted'; + const flush = () => { + if (!terminal || observed || effectCount) return; + observed = true; options.observe(terminal); + }; + const finish = (outcome: EgressOperationTerminal['outcome'], reason?: string) => { + if (!active()) return; + if (outcome === 'completed' && state !== 'dispatched') { outcome='cancelled';reason ??= 'not_dispatched'; } + terminal = { outcome, reason, dispatched: state === 'dispatched' }; + state = outcome === 'completed' ? 'finished' : 'aborted'; + options.decide(terminal); + for(const release of cleanups)try{release();}catch{/* One failed release cannot retain the others. */} + cleanups.clear();options.abort();flush(); + }; + const sendRefusal = (count:number,remaining:number) => { + if (!active()) return 'turn_cancelled' as const; + if (state !== 'admitted' && state !== 'dispatched') return 'call_not_admitted' as const; + if (count > remaining || count === 0 && state !== 'dispatched' && remaining <= 0) return 'max_bytes_per_turn' as const; + return undefined; + }; + return { + sendRefusal, + ownCleanup(release:()=>void) { if(active())cleanups.add(release);else release(); }, + state: () => state, active, + canCharge: () => state === 'admitted' || state === 'dispatched', + dispatched: () => state === 'dispatched' || terminal?.dispatched === true, + finish, + admit(run: () => Promise): Promise { + if (!active()) return Promise.resolve(false); + if (state !== 'pending') return Promise.resolve(true); + admission ??= (async () => { + try { + const allowed = await run(); + if (!allowed) { finish('denied','call_not_admitted');return false; } + if (!active()) return false; + state = 'admitted'; return true; + } catch { finish('failed', 'proxy_error'); return false; } + })(); + return admission; + }, + /** The sole admission side-effect boundary. Terminal observation joins it. */ + async effect(run: () => unknown): Promise { + if (!active() || state !== 'pending') return false; + effectCount++; + let result: Promise; + try { result = Promise.resolve(run()); } catch (error) { result = Promise.reject(error); } + const pending = result.finally(() => { effectCount--; effects.delete(pending); flush(); }); + effects.add(pending); + await pending; + return active(); + }, + prepare(notify:()=>void):boolean { + if(!active()||state==='pending')return false; + if(!prepared){prepared=true;notify();} + return active(); + }, + /** The send callback hands bytes to the transport; notification is a fact afterward. */ + dispatch(remaining:number,check:()=>boolean,send:()=>void,notify:()=>void=()=>{}):boolean { + if(!active())return false; + const refusal=sendRefusal(0,remaining); + if(refusal){finish(refusal==='turn_cancelled'?'cancelled':'denied',refusal);return false;} + if(!check())return false; + const first=state!=='dispatched'; + effectCount++; + try{ + let failed=false; + try{send();}catch{failed=true;} + if(failed)throw new TransportHandoffFailed(); + if(first){if(terminal)terminal.dispatched=true;else state='dispatched';notify();} + return true; + }finally{effectCount--;flush();} + }, + async settled(): Promise { while (effects.size) await Promise.allSettled([...effects]); }, + }; +} diff --git a/packages/ui-sdk/src/server/egress-proxy.ts b/packages/ui-sdk/src/server/egress-proxy.ts index 19bc72f529..9616535985 100644 --- a/packages/ui-sdk/src/server/egress-proxy.ts +++ b/packages/ui-sdk/src/server/egress-proxy.ts @@ -1,12 +1,16 @@ +import { readReceivedHead } from "./relay-response.js"; +import { chargeReceivedBytes } from "./egress-accounting.js"; /** Concrete host-owned HTTP/CONNECT transport for one turn; no TLS interception. */ import { createServer, request as httpRequest, type IncomingMessage } from "node:http"; import { BlockList, connect, isIP, type Socket } from "node:net"; import { lookup as dnsLookup } from "node:dns/promises"; import { chmodSync, chownSync, mkdtempSync, rmSync } from "node:fs"; import { tmpdir } from "node:os"; +import { safetyRecordSchema } from "../safety.js"; +import { createEgressOperation, TransportHandoffFailed } from "./egress-operation.js"; import { workerIdentityHelper } from "./worker-identity.js"; import { join } from "node:path"; -import { safetyAdmissionRefusal, type AdmissionSafety, type AdmissionSafetySnapshot } from "./admission-safety.js"; +import { safetySnapshotRefusal, type AdmissionSafety, type AdmissionSafetySnapshot } from "./admission-safety.js"; export const WORKER_EGRESS_DIR = "/run/brain-egress"; export const WORKER_EGRESS_SOCKET = `${WORKER_EGRESS_DIR}/proxy.sock`; @@ -15,6 +19,35 @@ export const WORKER_EGRESS_TRANSPORT_ENV = Object.freeze(["HTTP_PROXY", "HTTPS_P "http_proxy", "https_proxy", "all_proxy", "no_proxy", "GIT_SSH_COMMAND"]); /** The trusted in-namespace bootstrap that forwards loopback TCP to `WORKER_EGRESS_SOCKET`, then runs a command behind it. */ export function egressBootstrapEntry(): string { return Bun.resolveSync("./egress-worker-entry", import.meta.dir); } +export type EgressFailureReason = "budget" | "safety_changed" | "policy_denied" | "unavailable" | "cancelled"; +export type EgressChargeFailure = { ok: false; reason: EgressFailureReason }; +export type EgressChargeResult = { ok: true } | EgressChargeFailure; +const FAILURE_DETAILS = { + budget: { reason:"max_bytes_per_turn",status:403,message:"egress limit exceeded" }, + safety_changed: { reason:"safety_changed",status:403,message:"safety or authority changed" }, + policy_denied: { reason:"policy_denied",status:403,message:"network policy refused the request" }, + unavailable: { reason:"egress_unavailable",status:503,message:"egress unavailable" }, + cancelled: { reason:"cancelled",status:499,message:"request cancelled" }, +} as const; +export function egressChargeRefusal(failure: EgressChargeFailure, subject: string) { + const detail=FAILURE_DETAILS[failure.reason];return {...detail,message:`${subject} ${detail.message}`}; +} +/** Snapshot the failure site before finish() aborts its own operation signal. */ +export function captureEgressFailure(signal:AbortSignal,operation?:{failure():EgressChargeFailure|undefined}) { + const failure=operation?.failure() ?? (signal.aborted?{ok:false as const,reason:"cancelled" as const}:undefined); + return failure?{failure,outcome:"cancelled" as const,status:egressChargeRefusal(failure,"Network").status} + :{failure:undefined,outcome:"failed" as const,status:502 as const}; +} +/** Capture the category with the terminal audit decision, before abort listeners run. */ +function terminalFailure(outcome: EgressRecord["outcome"], reason?: string): EgressChargeFailure | undefined { + if (outcome === "completed") return undefined; + const category: EgressFailureReason = reason === "max_bytes_per_turn" || reason === "max_reference_wire_bytes" ? "budget" + : reason === "safety_changed" || reason === "source_trust_changed" ? "safety_changed" + : reason === "egress_unavailable" || reason === "session_binding_unavailable" || outcome === "failed" ? "unavailable" + : outcome === "cancelled" ? "cancelled" : "policy_denied"; + return Object.freeze({ok:false,reason:category}); +} +export type EgressRecipientAuthority = {kind:"rule";admission:{ruleId:string;policyHash:string;trustRevision:string;collectionRevision:string;instance:string}} | {kind:"approval"|"allowance"}; export interface EgressRecord { /** Host identity, shared with admission and terminal observation; never a tool correlation. */ connectionId?: string; @@ -24,6 +57,11 @@ export interface EgressRecord { provider?: true; /** Host-managed acquisition only; returned immutable content has its own read evidence. */ managedReference?: true; + /** Explicit Network card approval, independent of source trust. */ + recipientApproved?: true; + /** False for charged preparation that never crossed the dispatch boundary. */ + dispatched?: boolean; + failureReason?: EgressFailureReason; method: string; host: string; port: number; @@ -39,6 +77,10 @@ export interface EgressRecord { export interface EgressProxyOptions { /** Host-owned effective state. No request header or concurrent operation supplies authority. */ admissionSafety?: AdmissionSafety; + /** Exact host-owned write reservations of this connection's approved card peers. */ + pendingReservations?(connectionId:string):readonly string[]; + /** Host source decision remains valid before each delivered byte. */ + inputCurrent?(connectionId: string): boolean; mode: "record" | "allowlist"; /** Exact DNS names/IPs or *.suffix; deny always wins. */ allow: readonly string[]; @@ -59,7 +101,10 @@ export interface EgressProxyOptions { * anything but `true`, refuses. */ taint?: { allow: readonly string[]; tainted(connectionId?: string): boolean; contacted(host: string): boolean; - approve?(destination: { host: string; port: number; method: string }, signal: AbortSignal): Promise; + /** Immutable evidence/authority marker; excludes inputs admitted under this exact shared card. */ + approvalRevision?(connectionId?: string, kind?: "network" | "outward"): string; + recipient?(destination: { host: string; port: number; method: string; protocol: string; managedReference: boolean }): boolean | Extract["admission"]; + approve?(destination: { host: string; port: number; method: string; protocol: string; managedReference: boolean }, signal: AbortSignal, connectionId?: string): Promise; /** What tainted the session, as "it …" completes it, for a refusal's message (#3431). */ cause?(): string | null }; /** @@ -70,7 +115,8 @@ export interface EgressProxyOptions { */ admitted?(destination: { host: string; port: number; method: string; inference: boolean; provider: boolean; managedReference: boolean; connectionId: string; protocol?: string }): unknown; /** Synchronous notification only after final admission, immediately before dispatch. */ - committed?(destination: { host: string; connectionId: string; inference: boolean; provider: boolean; managedReference: boolean }): void; + preparing?(destination: { host: string; port: number; method: string; protocol: string; connectionId: string; inference: boolean; provider: boolean; managedReference: boolean; recipientApproved: boolean }): void; + committed?(destination: { host: string; port: number; method: string; protocol: string; connectionId: string; inference: boolean; provider: boolean; managedReference: boolean; recipientApproved: boolean; recipientAuthority: EgressRecipientAuthority }): void; signal?: AbortSignal; /** * Destination address policy (#3687). When set, the proxy resolves every @@ -125,10 +171,22 @@ export function egressAddressRefusal(address: string, allow?: BlockList): "metad if (NON_PUBLIC.check(value, family) && !allow?.check(value, family)) return "private_destination"; return null; } -const hostname = (value: string) => value.toLowerCase().replace(/\.$/, ""); +export const canonicalEgressHost = (value: string) => { + const normalized = value.toLowerCase().replace(/\.$/, ""); + const host = normalized.startsWith("[") && normalized.endsWith("]") ? normalized.slice(1, -1) : normalized; + return isIP(host) === 6 ? new URL(`http://[${host}]`).hostname.slice(1, -1) : host; +}; +/** The history wire schema is also the host's destination admission validator. */ +export function validatedEgressProvenance(destination:{method:string;protocol?:string;host:string;port:number}) { + const host=canonicalEgressHost(destination.host),port=destination.port; + if(destination.method!=="CONNECT"&&destination.protocol!=="http:"&&destination.protocol!=="https:")throw new Error("Invalid destination protocol"); + return safetyRecordSchema.options[0].shape.provenance.parse(destination.method==="CONNECT" + ? {kind:"tunnel_authority",authority:{host,port},verifiedBy:"host_proxy"} + : {kind:"web_origin",origin:{scheme:destination.protocol==="https:"?"https":"http",host,port},verifiedBy:"host_transport"}); +} function matches(host: string, patterns: readonly string[]): boolean { return patterns.some(value => { - const pattern = hostname(value); + const pattern = canonicalEgressHost(value); return pattern.startsWith("*.") ? host.endsWith(pattern.slice(1)) && host !== pattern.slice(2) : host === pattern; }); } @@ -141,11 +199,13 @@ function matches(host: string, patterns: readonly string[]): boolean { */ export interface EgressRefusal { cause: "denied_host" | "not_allowlisted" | "byte_cap" | "taint_allowlist" | "outward_not_approved" | "private_destination" | "destination_port" - | "call_not_admitted"; + | "call_not_admitted" | "safety_changed" | "egress_unavailable"; message: string; } function describeRefusal(reason: string | undefined, host: string, denied: boolean, tainted: string | null | undefined): EgressRefusal | undefined { switch (reason) { + case "safety_changed": case "source_trust_changed": return { cause: "safety_changed", message: "Blocked: this turn's safety or authority changed. A fresh request needs a fresh decision." }; + case "egress_unavailable": return { cause: "egress_unavailable", message: "Blocked: this turn's network admission is unavailable because safety recording could not be verified." }; case "taint_not_approved": return { cause: "taint_allowlist", message: "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." }; case "taint_not_allowed": return { cause: "taint_allowlist", @@ -174,6 +234,7 @@ const REFUSAL_STATUS: Readonly> = { outward_not_approved: "Forbidden - outward connection not approved", private_destination: "Forbidden - not a public web address", destination_port: "Forbidden - destination port not allowed", call_not_admitted: "Forbidden - not admitted for this call", + safety_changed: "Forbidden - safety or authority changed", egress_unavailable: "Service Unavailable - safety recording unavailable", }; /** @@ -182,13 +243,16 @@ const REFUSAL_STATUS: Readonly> = { * other failure of the hook is `failed` with `proxy_error`. */ export class EgressAdmissionRefused extends Error { - constructor(message = "The host did not admit this connection.") { super(message); this.name = "EgressAdmissionRefused"; } + constructor(message = "The host did not admit this connection.", readonly reason: "call_not_admitted" | "source_trust_changed" | "egress_unavailable" = "call_not_admitted") { super(message); this.name = "EgressAdmissionRefused"; } } /** One refused connection's 403, with its reason when it has one. */ -function refusalHead(refusal: EgressRefusal | undefined, reason: string | undefined): { status: string; body: string } | undefined { - if (!refusal) return undefined; +function refusalHead(refusal: EgressRefusal | undefined, reason: string | undefined, failure?: EgressChargeFailure): { code: number; status: string; body: string } | undefined { + if (!refusal) { + if (!failure) return undefined; const detail=egressChargeRefusal(failure,"Network"); + return {code:detail.status,status:detail.status===503?"Service Unavailable":detail.status===499?"Client Closed Request":"Forbidden",body:detail.message+"\n"}; + } const status = reason === "taint_not_approved" ? "Forbidden - declined by the user" : REFUSAL_STATUS[refusal.cause]; - return { status, body: `${refusal.message}\n` }; + return { code: refusal.cause === "egress_unavailable" ? 503 : 403, status, body: `${refusal.message}\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"]); @@ -200,7 +264,7 @@ function headers(message: IncomingMessage): Record { export async function startEgressProxy(options: EgressProxyOptions) { if (!Number.isSafeInteger(options.maxBytes) || options.maxBytes < 0) throw new Error("Egress maxBytes must be a finite nonnegative integer"); for (const pattern of [...options.allow, ...options.deny, ...options.outwardHosts, ...options.taint?.allow ?? []]) { - if (!/^(?:\*\.)?[a-zA-Z0-9.-]+$/.test(pattern) || pattern.includes("..")) throw new Error("Invalid egress host pattern"); + if ((!isIP(canonicalEgressHost(pattern)) && !/^(?:\*\.)?[a-zA-Z0-9.-]+$/.test(pattern)) || pattern.includes("..")) throw new Error("Invalid egress host pattern"); } const destinationPorts = options.destinations ? new Set(options.destinations.ports ?? [80, 443]) : undefined; const allowRanges = options.destinations ? rangeList(options.destinations.allowRanges ?? []) : undefined; @@ -215,8 +279,11 @@ export async function startEgressProxy(options: EgressProxyOptions) { chmodSync(dir, separateIdentity ? 0o750 : 0o700); } catch (error) { rmSync(dir, { recursive: true, force: true }); throw error; } const socketPath = join(dir, "proxy.sock"); + const inputCurrent = (id: string) => { try { return options.inputCurrent?.(id) !== false; } catch { return false; } }; const connections = new Set(); const controllers = new Set(); + const lifecycles = new Set>(); + const inputs = new Map void>(); let usedBytes = 0, stopped = false; const server = createServer(); server.maxHeadersCount = 100; @@ -234,30 +301,48 @@ export async function startEgressProxy(options: EgressProxyOptions) { let snapshot: AdmissionSafetySnapshot | undefined; const started = performance.now(); const controller = new AbortController(); controllers.add(controller); - const host = hostname(url.hostname), port = Number(url.port || (url.protocol === "https:" ? "443" : "80")); - let bytes = 0, finished = false; + // Matching may ignore a DNS root dot; resolution must preserve it. + const dialHost = url.hostname.startsWith("[") ? url.hostname.slice(1, -1) : url.hostname; + const host = canonicalEgressHost(dialHost), port = Number(url.port || (url.protocol === "https:" ? "443" : "80")); + let bytes = 0, granted = false; /** The checked address this connection is pinned to, under a destination policy. */ let pinned: { address: string; family: number } | undefined; let finalOutcome: EgressRecord["outcome"] | undefined, finalReason: string | undefined; - const finish = (outcome: EgressRecord["outcome"], reason?: string) => { - if (finished) return; - finished = true; finalOutcome = outcome; finalReason = reason; controllers.delete(controller); controller.abort(); - // Records never contain request headers, content, credentials or query strings. - try { options.observe({ connectionId, ...(inference ? { inference: true } : {}), ...(provider ? { provider: true } : {}), ...(managedReference ? { managedReference: true } : {}), method, host, port, ...(method === "CONNECT" ? {} : { path: url.pathname }), bytes, - accounting: method === "CONNECT" ? "opaque_bytes" : "http_wire_bound", - durationMs: performance.now() - started, outcome, ...(reason ? { reason } : {}) }); } catch { /* A recorder cannot keep a connection alive. */ } - }; + let failure: EgressChargeFailure | undefined; + const lifecycle = createEgressOperation({ + decide(terminal) { + finalOutcome=terminal.outcome;finalReason=terminal.reason;failure=terminalFailure(terminal.outcome,terminal.reason); + controllers.delete(controller);inputs.delete(connectionId); + }, + abort:()=>controller.abort(), + observe({outcome,reason,dispatched}) { + lifecycles.delete(lifecycle); + // Records never contain request headers, content, credentials or query strings. + try { options.observe({connectionId,...(inference?{inference:true}:{}),...(provider?{provider:true}:{}),...(managedReference?{managedReference:true}:{}),method,host,port,dispatched, + ...(failure?{failureReason:failure.reason}:{}),...(dispatched&&granted?{recipientApproved:true}:{}),...(method==="CONNECT"?{}:{path:url.pathname}),bytes, + accounting:method==="CONNECT"?"opaque_bytes":"http_wire_bound",durationMs:performance.now()-started,outcome,...(reason?{reason}:{})}); } catch { /* A recorder cannot keep a connection alive. */ } + }, + }); + lifecycles.add(lifecycle); + const finish=lifecycle.finish; + const revokeInput = () => { finish("cancelled", "source_trust_changed"); }; + inputs.set(connectionId, revokeInput); // Turn cleanup must observe final audit failures before it publishes its // terminal outcome; socket close callbacks run only after stop returns. - controller.signal.addEventListener("abort", () => finish("cancelled", "turn_cancelled"), { once: true }); - const charge = (count: number) => { - if (finished || stopped) return false; - if (count > options.maxBytes - usedBytes) { finish("denied", "max_bytes_per_turn"); return false; } - usedBytes += count; bytes += count; return true; + controller.signal.addEventListener("abort", () => { + const reason=controller.signal.reason; + if (reason instanceof EgressAdmissionRefused && reason.reason === "egress_unavailable") finish("denied","egress_unavailable"); + else finish("cancelled", "turn_cancelled"); + }, { once: true }); + const charge = (count: number): EgressChargeResult => { + if (!Number.isSafeInteger(count) || count < 0) throw new RangeError("Egress charge bytes must be a nonnegative safe integer"); + return maySendNow(count) ? { ok: true } : failure ?? {ok:false,reason:"cancelled"}; }; + const receive=(count:number):EgressChargeResult=>chargeReceivedBytes(count,{remaining:()=>Math.max(0,options.maxBytes-usedBytes),charge:bytes=>{const result=charge(bytes);return result.ok?undefined:result;}})??{ok:true}; + const receiveHead=(first:string,rawHeaders:readonly string[]):EgressChargeResult=>readReceivedHead(first,rawHeaders,{remaining:()=>Math.max(0,options.maxBytes-usedBytes),charge:bytes=>{const result=charge(bytes);return result.ok?undefined:result;}})??{ok: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; + const approval = async (ask: ((destination: { host: string; port: number; method: string; protocol: string; managedReference: boolean }, signal: AbortSignal) => Promise) | undefined) => { + if (!ask || !lifecycle.active()) return false; let approved = false; let cancelled: (() => void) | undefined; try { @@ -266,34 +351,68 @@ export async function startEgressProxy(options: EgressProxyOptions) { 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; + approved = await Promise.race([ask({ host, port, method, protocol: url.protocol, managedReference }, 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; + let outwardApproved = false, grantRevision: string | undefined, outwardRevision: string | undefined; + const readSafety=()=>options.admissionSafety?.read(options.pendingReservations?.(connectionId)); + const approvalRevision = (own = false, outward = false) => options.taint?.approvalRevision?.(own || !outward ? connectionId : undefined, outward ? "outward" : "network") ?? JSON.stringify(readSafety()); + const grantCurrent = (own = false) => { + if (!granted && !outwardApproved) return true; + try { + // After handoff, an explicit Network answer is the standing session grant. + const sessionGrant=granted&&lifecycle.dispatched()&&options.taint?.contacted(host); + return (!granted||sessionGrant||grantRevision===approvalRevision(own))&&(!outwardApproved||outwardRevision===approvalRevision(own,true)); + } catch { return false; } + }; + // A marker can change because recording or authority disappeared while a + // card was pending. Classify that live failure before a generic stale card. + const refuseStaleApproval = () => { + try { if (!refuseSafety(readSafety(),snapshot)) finish("denied","safety_changed"); } + catch { finish("denied","egress_unavailable"); } + }; + const recipient = { host, port, method, protocol: url.protocol, managedReference }; // Checked again after an approval wait, during which another connection may taint the session. // Inference/provider relays retain G5. Managed references retain ordinary // G6 recipient narrowing; repository trust never grants outbound authority. - const narrowed = (final = false) => !granted && !inference && !provider && options.taint?.tainted(final ? connectionId : undefined) && !matches(host, options.taint.allow) && !options.taint.contacted(host); + const recipientDecision = (final = false): EgressRecipientAuthority | null => { + if(granted)return {kind:"approval"}; + if(inference||provider)return {kind:"allowance"}; + const rule=options.taint?.recipient?.(recipient); + if(rule)return typeof rule === "object" ? {kind:"rule",admission:rule} : {kind:"allowance"}; + if(!options.taint?.tainted(final?connectionId:undefined)||matches(host,options.taint.allow)||options.taint.contacted(host))return {kind:"allowance"}; + return null; + }; + const narrowed = (final = false) => recipientDecision(final) === null; const narrowing = async () => { if (!narrowed()) return true; - if (options.taint?.approve) granted = await approval(options.taint.approve.bind(options.taint)); + if (options.taint?.approve) { grantRevision = approvalRevision(); granted = await approval((destination, signal) => options.taint!.approve!(destination, signal, connectionId)); + if (granted && !grantCurrent()) { refuseStaleApproval(); return false; } } if (!granted) finish(stopped ? "cancelled" : "denied", options.taint?.approve ? "taint_not_approved" : "taint_not_allowed"); return granted; }; - const admit = async () => { - snapshot = options.admissionSafety?.read(); - if (safetyAdmissionRefusal(options.admissionSafety, snapshot)) { finish("denied", "safety_changed"); return false; } + const refuseSafety = (current: AdmissionSafetySnapshot | undefined, before?: AdmissionSafetySnapshot) => { + const reason = current && !current.recordingAvailable && current.operationRecordingAvailable !== true ? "unavailable" : safetySnapshotRefusal(current,before) ? "safety_changed" : undefined; + if (!reason) return false; + finish("denied",egressChargeRefusal({ok:false,reason},"Network").reason); return true; + }; + const admit = () => lifecycle.admit(async () => { + if (!lifecycle.active()) return false; + try { snapshot = readSafety(); } + catch { finish("denied","egress_unavailable");return false; } + if (refuseSafety(snapshot,snapshot)) return false; 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; } if (usedBytes >= options.maxBytes) { finish("denied", "max_bytes_per_turn"); return false; } if (destinationPorts) { if (!destinationPorts.has(port)) { finish("denied", "destination_port"); return false; } let addresses: ReadonlyArray<{ address: string; family: number }>; - try { addresses = isIP(host) ? [{ address: host, family: isIP(host) }] : await resolve(host); } + try { addresses = isIP(dialHost) ? [{ address: dialHost, family: isIP(dialHost) }] : await resolve(dialHost); } catch { finish("denied", "unresolved_destination"); return false; } + if (!lifecycle.active()) return false; if (!addresses.length) { finish("denied", "unresolved_destination"); return false; } // Every address must pass: a mixed answer is refused, not narrowed. for (const entry of addresses) { @@ -302,120 +421,171 @@ export async function startEgressProxy(options: EgressProxyOptions) { } pinned = addresses[0]; } - if (!await narrowing()) return false; + if (!await narrowing() || !lifecycle.active()) return false; if (matches(host, options.outwardHosts) || options.outwardPorts?.includes(port)) { - if (!await approval(options.approveOutward)) { finish(stopped ? "cancelled" : "denied", "outward_not_approved"); return false; } + outwardRevision = approvalRevision(false,true); + const approveOutward=options.approveOutward; + if (!await approval(approveOutward ? ({host,port,method},signal)=>approveOutward({host,port,method},signal) : undefined)) { finish(stopped ? "cancelled" : "denied", "outward_not_approved"); return false; } + outwardApproved = true; + if (!grantCurrent()) { refuseStaleApproval(); return false; } } - if (!await narrowing()) return false; + if (!await narrowing() || !lifecycle.active()) return false; // A recorder failure aborts the turn through its own signal; it cannot admit. - try { await options.admitted?.({ host, port, method, inference, provider, managedReference, connectionId, protocol:url.protocol }); } - catch (error) { if (error instanceof EgressAdmissionRefused) finish("denied", "call_not_admitted"); else finish("failed", "proxy_error"); return false; } + try { if (!await lifecycle.effect(() => options.admitted?.({ host, port, method, inference, provider, managedReference, connectionId, protocol:url.protocol }))) return false; } + catch (error) { if (error instanceof EgressAdmissionRefused && error.reason === "source_trust_changed") revokeInput(); else if (error instanceof EgressAdmissionRefused) finish("denied", error.reason); else finish("failed", "proxy_error"); return false; } if (stopped || controller.signal.aborted) { finish("cancelled", "turn_cancelled"); return false; } return true; - }; + }); // No await may intervene between this check and connect/request/fetch. - const commit = () => { - if (stopped || controller.signal.aborted || safetyAdmissionRefusal(options.admissionSafety, snapshot)) { finish("denied", "safety_changed"); return false; } - if (usedBytes >= options.maxBytes) { finish("denied", "max_bytes_per_turn"); return false; } - if (narrowed(true)) { finish("denied", "taint_not_allowed"); return false; } - options.committed?.({ host, connectionId, inference, provider, managedReference }); - return true; + const maySendNow = (count: number): EgressRecipientAuthority | null => { + try { + if (!lifecycle.active() || stopped || controller.signal.aborted) { finish("cancelled", "turn_cancelled"); return null; } + const stateRefusal=lifecycle.sendRefusal(count,options.maxBytes-usedBytes); + if (stateRefusal) { finish(stateRefusal==="turn_cancelled"?"cancelled":"denied",stateRefusal);return null; } + const current = readSafety(); + if (refuseSafety(current,snapshot)) return null; + if (!grantCurrent(true)) { refuseStaleApproval(); return null; } + if (!inputCurrent(connectionId)) { revokeInput(); return null; } + const authority=recipientDecision(true); + if (!authority) { finish("denied", "taint_not_allowed"); return null; } + usedBytes += count; bytes += count; + return authority; + } catch { finish("denied", "egress_unavailable"); return null; } + }; + const prepare = (): EgressChargeResult => { + try{return lifecycle.prepare(()=>options.preparing?.({...recipient,connectionId,inference,provider,recipientApproved:granted}))?{ok:true}:failure??{ok:false,reason:"cancelled"};} + catch{finish("denied","egress_unavailable");return failure!;} + }; + const dispatch = (send:()=>void): EgressChargeResult => { + const prepared=prepare();if(!prepared.ok)return prepared; + let authority:EgressRecipientAuthority|null=null; + try{return lifecycle.dispatch(options.maxBytes-usedBytes,()=>Boolean(authority=maySendNow(0)),send,()=>options.committed?.({...recipient,connectionId,inference,provider,recipientApproved:granted,recipientAuthority:authority!}))?{ok:true}:failure??{ok:false,reason:"cancelled"};} + catch(error){if(error instanceof TransportHandoffFailed)throw error;finish("failed","upstream_unreachable");throw new Error("Egress transport could not start");} }; /** Why this connection was refused, for the tool that made it; undefined while admitted or for a bare refusal. */ const refusal = () => { - if (finalOutcome !== "denied") return undefined; + if (finalOutcome !== "denied" && finalReason !== "source_trust_changed") return undefined; let cause: string | null | undefined; if (finalReason === "taint_not_allowed") try { cause = options.taint?.cause?.(); } catch { /* The message names no cause. */ } return describeRefusal(finalReason, host, matches(host, options.deny), cause); }; - return { finish, charge, admit, commit, refusal, signal: controller.signal, outcome: () => finalOutcome, reason: () => finalReason, pinned: () => pinned }; + return { host, dialHost, finish, ownCleanup:lifecycle.ownCleanup, charge, receive, receiveHead, admit, prepare, dispatch, refusal, failure:()=>failure, signal: controller.signal, outcome: () => finalOutcome, reason: () => finalReason, pinned: () => pinned }; } server.on("connect", (request, client, head) => { client.on("error", () => {}); let target: URL; try { - if (!request.url || !/^[a-zA-Z0-9.-]+:[0-9]+$/.test(request.url)) throw new Error(); + if (!request.url || !/^(?:[a-zA-Z0-9.-]+|\[[0-9a-fA-F:.]+\]):[0-9]+$/.test(request.url)) throw new Error(); target = new URL(`http://${request.url}`); - if (!Number(target.port || 80)) throw new Error(); + validatedEgressProvenance({method:"CONNECT",protocol:target.protocol,host:target.hostname,port:Number(target.port||80)}); } catch { client.end("HTTP/1.1 400 Bad Request\r\nConnection: close\r\n\r\n"); return; } const op = operation("CONNECT", target); - let connected = false; + let connected = false, upstream: Socket | undefined; + op.signal.addEventListener("abort", () => { if (upstream) { if(connected||op.outcome()!=="failed")client.destroy();upstream.destroy(); } }, { once: true }); client.once("close", () => op.finish(stopped || !connected ? "cancelled" : "completed")); - void (async () => { - if (!await op.admit() || client.destroyed || !op.commit()) { - const declined = refusalHead(op.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}` + const upstreamFailed=()=>{ + const prior=op.outcome();op.finish("failed","upstream_unreachable"); + if(connected||(prior&&prior!=="failed")){client.destroy();return;} + client.end("HTTP/1.1 502 Bad Gateway\r\nConnection: close\r\nContent-Length: 0\r\n\r\n"); + }; + const refuseConnect=()=>{ + const declined = refusalHead(op.refusal(), op.reason(), op.failure()); + client.end(declined ? `HTTP/1.1 ${declined.code} ${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; + }; + void (async () => { + if (!await op.admit() || client.destroyed || !op.receive(head.length).ok || !op.prepare().ok) { + refuseConnect();return; } const address = op.pinned(); - const upstream = track(connect({ host: address?.address ?? target.hostname, port: Number(target.port || 80) })); - upstream.once("connect", () => { - if (stopped || client.destroyed) { upstream.destroy(); return; } + const sent=op.dispatch(()=>{upstream=track(connect({host:address?.address??op.dialHost,port:Number(target.port||80),signal:op.signal}));}); + if(!sent.ok){refuseConnect();return;} + const tunnel = upstream!; + tunnel.once("connect", () => { + if (stopped || op.signal.aborted || client.destroyed || !op.charge(0).ok) { tunnel.destroy(); return; } connected = true; client.write("HTTP/1.1 200 Connection Established\r\n\r\n"); - if (head.length) { if (!op.charge(head.length)) { client.destroy(); upstream.destroy(); return; } upstream.write(head); } - client.on("data", chunk => { if (!op.charge(chunk.length)) { client.destroy(); upstream.destroy(); return; } if (!upstream.write(chunk)) client.pause(); }); - upstream.on("data", chunk => { if (!op.charge(chunk.length)) { client.destroy(); upstream.destroy(); return; } if (!client.write(chunk)) upstream.pause(); }); - upstream.on("drain", () => client.resume()); client.on("drain", () => upstream.resume()); + if (head.length) tunnel.write(head); + client.on("data", chunk => { if (!op.receive(chunk.length).ok) { client.destroy(); tunnel.destroy(); return; } if (!tunnel.write(chunk)) client.pause(); }); + tunnel.on("data", chunk => { if (!op.receive(chunk.length).ok) { client.destroy(); tunnel.destroy(); return; } if (!client.write(chunk)) tunnel.pause(); }); + tunnel.on("drain", () => client.resume()); client.on("drain", () => tunnel.resume()); }); - upstream.once("error", () => { op.finish("failed", "upstream_unreachable"); client.destroy(); }); - upstream.once("end", () => client.end()); - client.once("end", () => upstream.end()); - client.once("close", () => upstream.destroy()); - upstream.once("close", () => client.destroy()); - })().catch(() => { op.finish("failed", "proxy_error"); client.destroy(); }); + tunnel.once("error",upstreamFailed); + tunnel.once("end", () => { if (!op.charge(0).ok) { client.destroy(); tunnel.destroy(); return; } client.end(); }); + client.once("end", () => { if (!op.charge(0).ok) { client.destroy(); tunnel.destroy(); return; } tunnel.end(); }); + client.once("close", () => tunnel.destroy()); + tunnel.once("close", () => {if(connected||op.outcome()!=="failed")client.destroy();}); + })().catch(error => {if(error instanceof TransportHandoffFailed)upstreamFailed();else{op.finish("failed","proxy_error");client.destroy();}}); }); server.on("request", (request, response) => { let target: URL; try { target = new URL(request.url!); if (target.protocol !== "http:" || target.username || target.password || target.hash) throw new Error(); + validatedEgressProvenance({method:request.method??"GET",protocol:target.protocol,host:target.hostname,port:Number(target.port||80)}); } catch { response.writeHead(400); response.end(); return; } const op = operation(request.method ?? "GET", target); + op.signal.addEventListener("abort", () => { if (response.headersSent) response.destroy(); }, { once: true }); response.once("close", () => op.finish(stopped ? "cancelled" : response.writableFinished ? "completed" : "cancelled")); const refuse = () => { - const declined = refusalHead(op.refusal(), op.reason()); - if (declined) response.writeHead(403, declined.status, { "content-type": "text/plain; charset=utf-8" }).end(declined.body); + if(response.destroyed||response.writableEnded)return; + if(response.headersSent){response.destroy();return;} + const declined = refusalHead(op.refusal(), op.reason(), op.failure()); + if (declined) response.writeHead(declined.code, declined.status, { "content-type": "text/plain; charset=utf-8" }).end(declined.body); else { response.writeHead(403); response.end(); } }; void (async () => { - if (!await op.admit() || response.destroyed || !op.commit()) { refuse(); return; } + if (!await op.admit() || response.destroyed) { refuse(); return; } + if(!op.receiveHead(`${request.method} ${request.url} HTTP/${request.httpVersion}`,request.rawHeaders).ok){refuse();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. - // The fixed allowance covers runtime-generated framing fields. Chunk - // accounting below additionally covers each HTTP chunk's framing. - const headerBytes = (first: string, values: Record) => Buffer.byteLength(first + "\r\n" - + Object.entries(values).flatMap(([name, value]) => (Array.isArray(value) ? value : [value]).map(item => `${name}: ${item}\r\n`)).join("") + "\r\n") + 64; - if (!op.charge(headerBytes(`${request.method} ${target.pathname}${target.search} HTTP/1.1`, outgoingHeaders))) { - refuse(); return; - } const address = op.pinned(); // Under a destination policy the request goes to the checked address; Host keeps the name. const upstreamTarget = new URL(target); if (address) upstreamTarget.hostname = address.family === 6 ? `[${address.address}]` : address.address; - const outgoing = httpRequest(upstreamTarget, { method: request.method, headers: outgoingHeaders }, incoming => { - if (!op.charge(headerBytes(`HTTP/1.1 ${incoming.statusCode} ${incoming.statusMessage}`, headers(incoming)))) { + if (!op.prepare().ok) { refuse(); return; } + let outgoing!:ReturnType; + const upstreamFailed=()=>{op.finish("failed","upstream_unreachable");if(!response.headersSent)response.writeHead(502);response.end();}; + const sendUpstream=(send:()=>void)=>{ + try{const decision=op.dispatch(send);if(decision.ok)return true;} + catch(error){if(error instanceof TransportHandoffFailed){upstreamFailed();return false;}} + outgoing?.destroy();if(!response.headersSent)refuse();else response.destroy();return false; + }; + const dispatched=sendUpstream(()=>{outgoing=httpRequest(upstreamTarget, { method: request.method, headers: outgoingHeaders,signal:op.signal, + // This operation owns its connection. A pooled socket can have an + // unread origin FIN when another independently fenced request takes it. + agent: false }, incoming => { + if (!op.receiveHead(`HTTP/${incoming.httpVersion} ${incoming.statusCode} ${incoming.statusMessage}`,incoming.rawHeaders).ok) { refuse(); incoming.destroy(); outgoing.destroy(); return; } const writeHeaders = () => { if (!response.headersSent) response.writeHead(incoming.statusCode ?? 502, headers(incoming)); }; incoming.on("data", chunk => { - if (!op.charge(chunk.length + 16)) { + if (!op.receive(chunk.length + 16).ok) { if (!response.headersSent) refuse(); else response.destroy(); incoming.destroy(); outgoing.destroy(); return; } writeHeaders(); if (!response.write(chunk)) incoming.pause(); }); response.on("drain", () => incoming.resume()); - incoming.once("end", () => { if (!response.destroyed && !response.writableEnded) { writeHeaders(); response.end(); } }); + incoming.once("end", () => { if (!response.destroyed && !response.writableEnded) { if (!op.charge(0).ok) { response.destroy(); return; } writeHeaders(); response.end(); } }); incoming.once("error", () => { op.finish("failed", "upstream_response_failed"); response.destroy(); }); + });}); + if(!dispatched)return; + outgoing.on("information",incoming=>{ + if(!op.receiveHead(`HTTP/${incoming.httpVersion} ${incoming.statusCode} ${incoming.statusMessage}`,incoming.rawHeaders).ok){refuse();outgoing.destroy();} + }); + // 101 uses upgrade rather than information; this HTTP path never tunnels it. + outgoing.once("upgrade",(incoming,socket,head)=>{ + socket.on("error",()=>{}); + const received=op.receiveHead(`HTTP/${incoming.httpVersion} ${incoming.statusCode} ${incoming.statusMessage}`,incoming.rawHeaders); + if(received.ok&&head.length)op.receive(head.length); + socket.destroy();if(op.failure())refuse();else upstreamFailed(); }); - outgoing.once("error", () => { op.finish("failed", "upstream_unreachable"); if (!response.headersSent) response.writeHead(502); response.end(); }); + op.signal.addEventListener("abort", () => { outgoing.destroy(); if (op.outcome() === "cancelled") response.destroy(); }, { once: true }); + outgoing.once("error",upstreamFailed); response.once("close", () => outgoing.destroy()); - request.on("data", chunk => { if (!op.charge(chunk.length + 16)) { outgoing.destroy(); response.destroy(); return; } if (!outgoing.write(chunk)) request.pause(); }); + request.on("data", chunk => { if (!op.receive(chunk.length + 16).ok) { outgoing.destroy(); if (!response.headersSent) refuse(); else response.destroy(); return; } let accepted=false;if(!sendUpstream(()=>{accepted=outgoing.write(chunk);}))return;if(!accepted)request.pause(); }); outgoing.on("drain", () => request.resume()); - request.once("end", () => outgoing.end()); + request.once("end", () => { if (!op.charge(0).ok) { outgoing.destroy(); if (!response.headersSent) refuse(); else response.destroy(); return; } sendUpstream(()=>{outgoing.end();}); }); request.once("error", () => { op.finish("cancelled", "client_disconnected"); outgoing.destroy(); }); })().catch(() => { op.finish("failed", "proxy_error"); response.destroy(); }); }); @@ -428,13 +598,17 @@ export async function startEgressProxy(options: EgressProxyOptions) { const stop = () => { if (stopped) return; stopped = true; options.signal?.removeEventListener("abort", stop); - for (const controller of controllers) controller.abort(); + for (const controller of controllers) controller.abort(options.signal?.reason); for (const socket of connections) socket.destroy(); server.close(); rmSync(dir, { recursive: true, force: true }); }; options.signal?.addEventListener("abort", stop, { once: true }); if (options.signal?.aborted) stop(); - return { dir, socketPath, stop, usedBytes: () => usedBytes, remainingBytes: () => Math.max(0, options.maxBytes - usedBytes), + return { dir, socketPath, stop, + async settled() { await Promise.all([...lifecycles].map(operation=>operation.settled())); }, + /** Fence only inputs whose host decision changed; unrelated traffic remains active. */ + invalidateInputs() { for (const [id, revoke] of inputs) if (!inputCurrent(id)) revoke(); }, + usedBytes: () => usedBytes, remainingBytes: () => Math.max(0, options.maxBytes - usedBytes), /** The existing inference relay shares this turn's admission, counter and audit. */ inference(method: string, target: URL, signal: AbortSignal) { return relayedOperation(method, target, signal, "inference"); }, /** @@ -454,17 +628,16 @@ export async function startEgressProxy(options: EgressProxyOptions) { }, }; function relayedOperation(method: string, target: URL, signal: AbortSignal, relay: "inference" | "provider" | "reference") { + validatedEgressProvenance({method,protocol:target.protocol,host:target.hostname,port:Number(target.port||(target.protocol==="https:"?443:80))}); const op = operation(method, new URL(target), relay); const abort = () => op.finish("cancelled", "client_disconnected"); signal.addEventListener("abort", abort, { once: true }); + op.ownCleanup(()=>signal.removeEventListener("abort",abort)); if (signal.aborted) abort(); - return { charge: op.charge, signal: op.signal, outcome: op.outcome, refusal: op.refusal, reason: op.reason, - admit: async () => !op.signal.aborted && await op.admit() && op.commit(), - /** The concrete relay calls this again after its own final async waits. */ - commit: op.commit, - finish(outcome: EgressRecord["outcome"], reason?: string) { - signal.removeEventListener("abort", abort); op.finish(outcome, reason); - }, + return { charge: op.charge, signal: op.signal, outcome: op.outcome, refusal: op.refusal, reason: op.reason, failure: op.failure, + admit: async () => !op.signal.aborted && await op.admit(), + prepare:op.prepare,dispatch:op.dispatch, + finish:op.finish, }; } } diff --git a/packages/ui-sdk/src/server/inference-relay.ts b/packages/ui-sdk/src/server/inference-relay.ts index d65bc465ca..88d3ee3e0b 100644 --- a/packages/ui-sdk/src/server/inference-relay.ts +++ b/packages/ui-sdk/src/server/inference-relay.ts @@ -1,3 +1,5 @@ +import { chargeReceivedBytes, relayAllowance } from "./egress-accounting.js"; +import { readRelayResponse, readRelayRequestHead } from "./relay-response.js"; /** * The one network path out of a restricted (autonomous) worker (#676). * @@ -14,7 +16,7 @@ import { chmodSync, mkdtempSync, rmSync } from "node:fs"; import { workerIdentityHelper } from "./worker-identity.js"; import { tmpdir } from "node:os"; import { join } from "node:path"; -import type { startEgressProxy } from "./egress-proxy.js"; +import { captureEgressFailure, egressChargeRefusal, type startEgressProxy, type EgressChargeFailure } from "./egress-proxy.js"; import { INFERENCE_RELAY_PLACEHOLDER } from "@schlessera/brain-common/internal/provider-unavailable"; /** Where the relay directory appears inside a restricted worker. */ @@ -25,6 +27,12 @@ export const INFERENCE_PLACEHOLDER = INFERENCE_RELAY_PLACEHOLDER; /** A request body larger than this is refused before anything is forwarded. */ export const MAX_INFERENCE_REQUEST_BYTES = 32 * 1024 * 1024; +/** These fixed messages also classify stored provider errors as host refusals. */ +function inferenceRefusalMessage(failure: EgressChargeFailure): string { + return failure.reason === "budget" ? "Inference egress limit exceeded" + : failure.reason === "cancelled" ? "Inference request cancelled" : "Inference network admission refused"; +} + export interface InferenceRelayOptions { /** Server-selected upstream base, e.g. `https://api.anthropic.com`. */ upstream: string; @@ -33,7 +41,7 @@ export interface InferenceRelayOptions { /** Server-held headers, resolved for each dispatch after inbound credentials are removed. */ credentials: Readonly> | ((signal: AbortSignal, target: URL) => Promise>>); /** Concrete turn proxy: share its destination admission, application-byte ceiling and audit. */ - egress?: Pick>, "inference">; + egress?: Pick>, "inference"> & Partial>, "remainingBytes">>; /** Called for every request, forwarded or refused. Values are never logged. */ observe?(event: InferenceRelayEvent): void; /** @@ -122,11 +130,17 @@ export function startInferenceRelay(options: InferenceRelayOptions): InferenceRe operation?.finish("denied", reason); return refuse(request.method, path, status, reason === "max_bytes_per_turn" ? "Inference egress limit exceeded" : "Inference request refused", operation?.reason?.() ?? reason); }; - if (operation && !await operation.admit()) { - const cancelled = request.signal.aborted || operation.outcome() === "cancelled"; - operation.finish(cancelled ? "cancelled" : "denied", "inference_admission_refused"); - return refuse(request.method, path, cancelled ? 499 : 403, "Inference network admission refused", operation.reason?.()); - } + const allowance=relayAllowance(operation,options.egress?.remainingBytes?.bind(options.egress),MAX_INFERENCE_REQUEST_BYTES); + const chargeFailure=allowance.charge; + const receivedFailure=(count:number)=>chargeReceivedBytes(count,{charge:chargeFailure,remaining:allowance.remaining}); + const chargeDenied = (failure: EgressChargeFailure) => { const detail = egressChargeRefusal(failure,"Inference"); return refuse(request.method,path,detail.status,inferenceRefusalMessage(failure),operation?.reason?.() ?? detail.reason); }; + const admitFailure = async ():Promise => operation && !await operation.admit() ? operation.failure() ?? {ok:false,reason:"unavailable"} : undefined; + const initialAdmissionFailure=await admitFailure(); + if (initialAdmissionFailure) return chargeDenied(initialAdmissionFailure); + const initialDecision = operation?.charge(0); + if (initialDecision && !initialDecision.ok) return chargeDenied(initialDecision); + const requestHead=readRelayRequestHead(`${request.method} ${url.pathname}${url.search} HTTP/1.1`,request.headers,{charge:chargeFailure,remaining:allowance.remaining}); + if(requestHead.failure)return chargeDenied(requestHead.failure); const declared = Number(request.headers.get("content-length") ?? "0"); if (declared > MAX_INFERENCE_REQUEST_BYTES) return denied("inference_request_too_large", 413); // Do not allocate an unbounded arrayBuffer before checking the ceiling. @@ -142,16 +156,17 @@ export function startInferenceRelay(options: InferenceRelayOptions): InferenceRe const next = await reader.read(); if (next.done) break; length += next.value.byteLength; - if (length > MAX_INFERENCE_REQUEST_BYTES || operation && !operation.charge(next.value.byteLength + 16)) { + const failure = receivedFailure(next.value.byteLength + 16); + if (length > MAX_INFERENCE_REQUEST_BYTES || failure) { await reader.cancel().catch(() => {}); - return denied(length > MAX_INFERENCE_REQUEST_BYTES ? "inference_request_too_large" : "max_bytes_per_turn", - length > MAX_INFERENCE_REQUEST_BYTES ? 413 : 403); + return failure ? chargeDenied(failure) : denied("inference_request_too_large",413); } chunks.push(next.value); } } catch { - operation?.finish("cancelled", "client_disconnected"); - return refuse(request.method, path, 499, "Inference request cancelled"); + const cause=captureEgressFailure(signal,operation); + operation?.finish(cause.outcome,"request_body_failed"); + return cause.failure?chargeDenied(cause.failure):refuse(request.method,path,cause.status,"Inference request interrupted"); } finally { signal.removeEventListener("abort", cancelBody); reader?.releaseLock(); } const body = new Uint8Array(length); let offset = 0; @@ -160,47 +175,52 @@ export function startInferenceRelay(options: InferenceRelayOptions): InferenceRe for (const [name, value] of request.headers) if (!STRIPPED.has(name.toLowerCase())) headers.set(name, value); let credentials: Readonly>; if (signal.aborted) { - operation?.finish("cancelled", "client_disconnected"); - return refuse(request.method, path, 499, "Inference request cancelled"); + const cause=captureEgressFailure(signal,operation); + operation?.finish(cause.outcome,"client_disconnected"); + return chargeDenied(cause.failure ?? {ok:false,reason:"cancelled"}); } try { credentials = typeof options.credentials === "function" ? await options.credentials(signal, new URL(target)) : options.credentials; validateCredentials(credentials); if (signal.aborted) { - operation?.finish("cancelled", "client_disconnected"); - return refuse(request.method, path, 499, "Inference request cancelled"); + const cause=captureEgressFailure(signal,operation); + operation?.finish(cause.outcome,"client_disconnected"); + return chargeDenied(cause.failure ?? {ok:false,reason:"cancelled"}); } for (const [name, value] of Object.entries(credentials)) headers.set(name, value); } catch { // A resolver error may carry a provider reply, credential or host path. - operation?.finish(signal.aborted ? "cancelled" : "failed", "inference_credentials_unavailable"); - return refuse(request.method, path, signal.aborted ? 499 : 503, - signal.aborted ? "Inference request cancelled" : "Inference credentials unavailable"); + const cause=captureEgressFailure(signal,operation); + operation?.finish(cause.outcome,"inference_credentials_unavailable"); + return cause.failure?chargeDenied(cause.failure):refuse(request.method,path,cause.status,"Inference credentials unavailable"); } // HTTP application framing before provider TLS: never describe this as // measured TLS ciphertext/handshake bytes. Include every observable // query/header byte plus a conservative runtime framing allowance. - const headerBytes = (first: string, values: Headers): number => { - let bytes = Buffer.byteLength(first) + 1028; - for (const [name, value] of values) bytes += Buffer.byteLength(name) + Buffer.byteLength(value) + 4; - return bytes; - }; - if (operation && !operation.charge(headerBytes(`${request.method} ${path}${url.search} HTTP/1.1`, headers))) { - return denied("max_bytes_per_turn"); - } + const requestChargeFailure = requestHead.forward(`${request.method} ${path}${url.search} HTTP/1.1`,headers); + if (requestChargeFailure) return chargeDenied(requestChargeFailure); // Body/credential waits may have crossed an input-recording failure. // Re-enter the concrete host admission at the last dispatch boundary. - if(operation&&!await operation.admit())return denied("inference_admission_refused"); - if(operation&&!operation.commit())return denied("inference_admission_refused"); + const finalAdmissionFailure=await admitFailure(); + if (finalAdmissionFailure) return chargeDenied(finalAdmissionFailure); + const dispatchDecision = operation?.prepare(); + if (dispatchDecision && !dispatchDecision.ok) return chargeDenied(dispatchDecision); let response: Response; try { // Never follow a redirect: the upstream must not choose another host. - response = await fetch(target, { method: "POST", headers, body, redirect: "manual", signal }); + signal.throwIfAborted(); + let pending!:Promise; + const send=()=>{pending=fetch(target,{method:"POST",headers,body,redirect:"manual",signal});}; + const decision=operation?operation.dispatch(send):(send(),{ok:true as const}); + if(!decision.ok)return chargeDenied(decision); + response=await pending; } catch { - operation?.finish(signal.aborted ? "cancelled" : "failed", "upstream_unreachable"); - return refuse(request.method, path, signal.aborted ? 499 : 502, - signal.aborted ? "Inference request cancelled" : "Inference upstream unreachable"); + const cause=captureEgressFailure(signal,operation); + operation?.finish(cause.outcome,"upstream_unreachable"); + return cause.failure?chargeDenied(cause.failure):refuse(request.method,path,cause.status,"Inference upstream unreachable"); } + const incoming=readRelayResponse(response,{charge:chargeFailure,remaining:allowance.remaining}); + if(incoming.headerFailure){await incoming.cancel().catch(()=>{});return chargeDenied(incoming.headerFailure);} if (response.status >= 300 && response.status < 400) { operation?.finish("failed", "upstream_redirected"); await response.body?.cancel().catch(() => {}); @@ -209,36 +229,31 @@ export function startInferenceRelay(options: InferenceRelayOptions): InferenceRe options.observe?.({ method: request.method, path, outcome: "forwarded", status: response.status }); const out = new Headers(); for (const [name, value] of response.headers) if (!RESPONSE_STRIPPED.has(name.toLowerCase())) out.set(name, value); - if (operation && !operation.charge(headerBytes(`HTTP/1.1 ${response.status} ${response.statusText}`, response.headers))) { - operation.finish("denied", "max_bytes_per_turn"); - await response.body?.cancel().catch(() => {}); - return refuse(request.method, path, 403, "Inference egress limit exceeded"); - } - if (!operation) return new Response(response.body, { status: response.status, headers: out }); if (!response.body) { - operation.finish("completed"); + const failure=incoming.fence();if(failure)return chargeDenied(failure); + operation?.finish("completed"); return new Response(null, { status: response.status, headers: out }); } - const upstreamReader = response.body.getReader(); + const upstreamReader = incoming; let released = false; - const release = () => { if (!released) { released = true; upstreamReader.releaseLock(); } }; + const release = () => { if (!released) { released = true; upstreamReader.release(); } }; const output = new ReadableStream({ async pull(controller) { - try { - const next = await upstreamReader.read(); - if (next.done) { operation.finish("completed"); release(); controller.close(); } - else if (!operation.charge(next.value.byteLength + 16)) { - operation.finish("denied", "max_bytes_per_turn"); - await upstreamReader.cancel().catch(() => {}); release(); - controller.error(new Error("Inference egress limit exceeded")); - } else controller.enqueue(next.value); - } catch { - operation.finish(signal.aborted ? "cancelled" : "failed", "upstream_response_failed"); - release(); controller.error(new Error("Inference response interrupted")); + let next:Awaited>; + try { next=await upstreamReader.read(); } + catch { + const cause=captureEgressFailure(signal,operation); + operation?.finish(cause.outcome,"upstream_response_failed"); + release();controller.error(new Error(cause.failure?inferenceRefusalMessage(cause.failure):"Inference response interrupted"));return; } + const failure=next.deliver(()=>{ + if(next.done){controller.close();operation?.finish("completed");release();} + else controller.enqueue(next.value); + }); + if(failure){release();controller.error(new Error(inferenceRefusalMessage(failure)));} }, async cancel() { - operation.finish("cancelled", "client_disconnected"); + operation?.finish("cancelled", "client_disconnected"); await upstreamReader.cancel().catch(() => {}); release(); }, }); diff --git a/packages/ui-sdk/src/server/provider-relay.ts b/packages/ui-sdk/src/server/provider-relay.ts index 832fb96657..c448ef32af 100644 --- a/packages/ui-sdk/src/server/provider-relay.ts +++ b/packages/ui-sdk/src/server/provider-relay.ts @@ -1,3 +1,5 @@ +import { chargeReceivedBytes, relayAllowance } from "./egress-accounting.js"; +import { readRelayResponse, readRelayRequestHead, relayHeaderBytes } from "./relay-response.js"; /** * The metered host relay for the `brain` CLI's paid providers (#1673). * @@ -37,7 +39,7 @@ import { PROVIDER_RELAY_FAMILY_HEADER, PROVIDER_RELAY_KEY_HEADER, PROVIDER_RELAY_ORIGIN_HEADER, type ProviderRelayFamily, } from "@schlessera/brain-common/internal/provider-relay"; import { workerIdentityHelper } from "./worker-identity.js"; -import { WORKER_EGRESS_DIR, type EgressRefusal, type startEgressProxy } from "./egress-proxy.js"; +import { captureEgressFailure, egressChargeRefusal, type EgressChargeFailure, WORKER_EGRESS_DIR, type EgressRefusal, type startEgressProxy } from "./egress-proxy.js"; import { hostProviderCredential } from "../config/env.js"; /** The relay's socket name inside the turn's egress directory. */ @@ -208,7 +210,7 @@ export interface ProviderRelayOptions { /** Host credential lookup by name. Default: the server's own environment. */ credential?(name: string): string | undefined; /** The concrete turn proxy: share its destination admission, byte ceiling and connection records. */ - egress?: Pick>, "relayed">; + egress?: Pick>, "relayed"> & Partial>, "remainingBytes">>; /** * Called before each dispatch, and awaited. A refusal is answered with * `budget_exceeded` and nothing is sent. @@ -216,6 +218,7 @@ export interface ProviderRelayOptions { admit?(): { allowed: true } | { allowed: false; message: string } | Promise<{ allowed: true } | { allowed: false; message: string }>; /** One receipt per dispatched attempt. A throw is reported through `failed`, never to the worker. */ observe?(receipt: ProviderRelayReceipt): void; + preparing?(attempt: Omit):void; refused?(refusal: ProviderRelayRefusal): void; } @@ -435,16 +438,20 @@ export function startProviderRelay(options: ProviderRelayOptions = {}): Provider if (!budget.allowed) return refuse(403, "budget_exceeded", budget.message); const operation = options.egress?.relayed(request.method, target, request.signal); const signal = operation ? AbortSignal.any([request.signal, operation.signal]) : request.signal; - if (operation && !await operation.admit()) { - const cancelled = request.signal.aborted || operation.outcome() === "cancelled"; - operation.finish(cancelled ? "cancelled" : "denied", "provider_admission_refused"); - return refuse(cancelled ? 499 : 403, cancelled ? "cancelled" : "egress_refused", "Provider network admission refused", cancelled ? undefined : operation.refusal()); - } + const allowance=relayAllowance(operation,options.egress?.remainingBytes?.bind(options.egress),MAX_PROVIDER_REQUEST_BYTES); + const chargeFailure=allowance.charge; + const receivedFailure=(count:number)=>chargeReceivedBytes(count,{charge:chargeFailure,remaining:allowance.remaining}); + const chargeDenied = (failure: EgressChargeFailure) => { const detail = egressChargeRefusal(failure,"Provider"); return refuse(detail.status,failure.reason==="cancelled"?"cancelled":"egress_refused",detail.message,operation?.refusal()); }; + if (operation && !await operation.admit()) return chargeDenied(operation.failure() ?? {ok:false,reason:"unavailable"}); + const initialDecision = operation?.charge(0); + if (initialDecision && !initialDecision.ok) return chargeDenied(initialDecision); const denied = (reason: string, status = 403): Response => { operation?.finish("denied", reason); return refuse(status, reason === "provider_request_too_large" ? "request_too_large" : "egress_refused", reason === "max_bytes_per_turn" ? "Provider egress limit exceeded" : "Provider request refused", operation?.refusal()); }; + const requestHead=readRelayRequestHead(`${request.method} ${url.pathname}${url.search} HTTP/1.1`,request.headers,{charge:chargeFailure,remaining:allowance.remaining}); + if(requestHead.failure)return chargeDenied(requestHead.failure); if (Number(request.headers.get("content-length") ?? "0") > MAX_PROVIDER_REQUEST_BYTES) return denied("provider_request_too_large", 413); // Charge each received chunk before retaining or forwarding it, against // this request's ceiling, the turn's byte ceiling and the relay's @@ -462,10 +469,10 @@ export function startProviderRelay(options: ProviderRelayOptions = {}): Provider const next = await reader.read(); if (next.done) break; length += next.value.byteLength; - if (length > MAX_PROVIDER_REQUEST_BYTES || operation && !operation.charge(next.value.byteLength + 16)) { + const failure = receivedFailure(next.value.byteLength + 16); + if (length > MAX_PROVIDER_REQUEST_BYTES || failure) { await reader.cancel().catch(() => {}); - return denied(length > MAX_PROVIDER_REQUEST_BYTES ? "provider_request_too_large" : "max_bytes_per_turn", - length > MAX_PROVIDER_REQUEST_BYTES ? 413 : 403); + return failure ? chargeDenied(failure) : denied("provider_request_too_large",413); } if (!reserve(next.value.byteLength)) { await reader.cancel().catch(() => {}); @@ -476,10 +483,10 @@ export function startProviderRelay(options: ProviderRelayOptions = {}): Provider } if (uploadDeadline.aborted) throw new Error("upload deadline"); } catch { - const late = uploadDeadline.aborted && !signal.aborted; - operation?.finish(late ? "denied" : "cancelled", late ? "provider_upload_timeout" : "client_disconnected"); - return late ? refuse(408, "upload_timeout", "Provider request body did not arrive in time") - : refuse(499, "cancelled", "Provider request cancelled"); + const late = uploadDeadline.aborted && !signal.aborted,cause=captureEgressFailure(signal,operation); + operation?.finish(late?"denied":cause.outcome,late?"provider_upload_timeout":"request_body_failed"); + if(late)return refuse(408,"upload_timeout","Provider request body did not arrive in time"); + return cause.failure?chargeDenied(cause.failure):refuse(cause.status,"upstream_unreachable","Provider request interrupted"); } finally { signal.removeEventListener("abort", cancelBody); uploadDeadline.removeEventListener("abort", cancelBody); reader?.releaseLock(); } @@ -503,46 +510,60 @@ export function startProviderRelay(options: ProviderRelayOptions = {}): Provider } const inlineMedia = family === "gemini" && !files && /"inlineData"|"inline_data"/.test(new TextDecoder().decode(body.subarray(0, Math.min(body.byteLength, 8 * 1024 * 1024)))); if (signal.aborted) { - operation?.finish("cancelled", "client_disconnected"); - return refuse(499, "cancelled", "Provider request cancelled"); + const cause=captureEgressFailure(signal,operation); + operation?.finish(cause.outcome,"client_disconnected"); + return chargeDenied(cause.failure ?? {ok:false,reason:"cancelled"}); } - if (operation && !operation.charge(headerBytes(`${request.method} ${target.pathname}${target.search} HTTP/1.1`, headers))) return denied("max_bytes_per_turn"); + const requestChargeFailure = requestHead.forward(`${request.method} ${target.pathname}${target.search} HTTP/1.1`,headers); + if (requestChargeFailure) return chargeDenied(requestChargeFailure); // Admission again, after every wait: a scope may have blocked meanwhile. const now = budgeted ? await options.admit?.() ?? { allowed: true as const } : { allowed: true as const }; if (!now.allowed) { operation?.finish("denied", "budget_exceeded"); return refuse(403, "budget_exceeded", now.message); } - if (operation && !operation.commit()) return denied("provider_admission_refused"); + const dispatchDecision = operation?.prepare(); + if (dispatchDecision && !dispatchDecision.ok) return chargeDenied(dispatchDecision); const attemptId = crypto.randomUUID(); let reported = false; - const observe = (outcome: ProviderRelayReceipt["outcome"], status: number, usage: ProviderUsage | null): void => { - try { options.observe?.({ attemptId, family, operation: route.operation, origin, key, model, outcome, status, usage, inlineMedia }); } + let upstreamStatus=0; + const observe = (outcome: ProviderRelayReceipt["outcome"], usage: ProviderUsage | null): void => { + try { options.observe?.({ attemptId, family, operation: route.operation, origin, key, model, outcome, status:upstreamStatus, usage, inlineMedia }); } catch { /* The host's own accounting reports its failure; the worker's answer is unaffected. */ } }; - const report = (outcome: Exclude, status: number, usage: ProviderUsage | null): void => { + const report = (outcome: Exclude, usage: ProviderUsage | null): void => { if (reported) return; reported = true; - observe(outcome, status, usage); + observe(outcome, usage); done(); }; - observe("dispatched", 0, null); + try{options.preparing?.({attemptId,family,operation:route.operation,origin,key,model,status:0,usage:null,inlineMedia});}catch{/* Diagnostics do not authorize a send. */} let response: Response; try { // Never follow a redirect: the upstream must not choose another host. - response = await fetch(target, { method: request.method, headers, ...(request.method === "POST" ? { body } : {}), redirect: "manual", signal }); + const finalFailure=chargeFailure(0) ?? captureEgressFailure(signal).failure; + if(finalFailure){report("cancelled",null);return chargeDenied(finalFailure);} + let pending!:Promise; + const send=()=>{pending=fetch(target,{method:request.method,headers,...(request.method==="POST"?{body}:{}),redirect:"manual",signal});}; + const decision=operation?operation.dispatch(send):(send(),{ok:true as const}); + if(!decision.ok){report("cancelled",null);return chargeDenied(decision);} + observe("dispatched",null); + response=await pending; + upstreamStatus=response.status; } catch { - operation?.finish(signal.aborted ? "cancelled" : "failed", "upstream_unreachable"); - // The request may have reached the provider: its spend is unknown, never zero. - report(signal.aborted ? "cancelled" : "failed", 0, null); - return refuse(signal.aborted ? 499 : 502, signal.aborted ? "cancelled" : "upstream_unreachable", - signal.aborted ? "Provider request cancelled" : "Provider upstream unreachable"); + const cause=captureEgressFailure(signal,operation); + operation?.finish(cause.outcome,"upstream_unreachable"); + // No upstream HTTP status or usage was observed for a transport failure. + report(cause.outcome,null); + return cause.failure?chargeDenied(cause.failure):refuse(cause.status,"upstream_unreachable","Provider upstream unreachable"); } free(); + const incoming=readRelayResponse(response,{charge:chargeFailure,remaining:allowance.remaining,maxBytes:files?MAX_FILES_RESPONSE_BYTES:undefined}); + if(incoming.headerFailure){await incoming.cancel().catch(()=>{});report("cancelled",null);return chargeDenied(incoming.headerFailure);} if (response.status >= 300 && response.status < 400) { operation?.finish("failed", "upstream_redirected"); await response.body?.cancel().catch(() => {}); - report("failed", response.status, null); + report("failed", null); return refuse(502, "upstream_redirected", "Provider upstream redirected; redirects are not followed"); } const out = new Headers(); @@ -552,44 +573,35 @@ export function startProviderRelay(options: ProviderRelayOptions = {}): Provider if (!RESPONSE_STRIPPED.has(name.toLowerCase()) && name.toLowerCase() !== "x-goog-upload-url" && !value.includes(secret)) out.set(name, value); } const scrub = keyScrubber(secret); - if (operation && !operation.charge(headerBytes(`HTTP/1.1 ${response.status} ${response.statusText}`, response.headers))) { - operation.finish("denied", "max_bytes_per_turn"); - await response.body?.cancel().catch(() => {}); - report("cancelled", response.status, null); - return refuse(403, "egress_refused", "Provider egress limit exceeded", operation?.refusal()); - } if (files) { // A Files answer is small JSON, read whole: whatever it registers is in // place before the worker sees the answer. const chunks: Uint8Array[] = []; - let size = 0, failure: "large" | "egress" | "read" | undefined; + let failure: "large" | EgressChargeFailure | "read" | undefined; + let readCause:ReturnType|undefined; try { - if (response.body) for await (const chunk of response.body) { - size += chunk.byteLength; - if (size > MAX_FILES_RESPONSE_BYTES) { failure = "large"; break; } - if (operation && !operation.charge(chunk.byteLength + 16)) { failure = "egress"; break; } - chunks.push(chunk); - } - } catch { failure = "read"; } + for(;;){const next=await incoming.read();if(next.done)break;chunks.push(next.value);} + } catch { readCause=captureEgressFailure(signal,operation);failure=readCause.failure??"read"; }finally{incoming.release();} if (failure) { + const cause=readCause??captureEgressFailure(signal,operation); await response.body?.cancel().catch(() => {}); - if (failure === "egress") { - operation?.finish("denied", "max_bytes_per_turn"); - report("cancelled", response.status, null); - return refuse(403, "egress_refused", "Provider egress limit exceeded", operation?.refusal()); + if (typeof failure === "object") { + report("cancelled", null); + return chargeDenied(failure); } - operation?.finish(signal.aborted ? "cancelled" : "failed", "upstream_response_failed"); - report(signal.aborted ? "cancelled" : "failed", response.status, null); - return refuse(signal.aborted ? 499 : 502, signal.aborted ? "cancelled" : "upstream_unreachable", "Provider response interrupted"); + operation?.finish(cause.outcome,"upstream_response_failed"); + report(cause.outcome,null); + return cause.failure?chargeDenied(cause.failure):refuse(cause.status,"upstream_unreachable","Provider response interrupted"); } - operation?.finish("completed"); - report(response.ok ? "completed" : "failed", response.status, null); + const finalFailure=incoming.fence(); + if(finalFailure){report("cancelled",null);return chargeDenied(finalFailure);} const answer = Buffer.concat(chunks); if (files.step === "start" && response.ok) { let issued: URL | undefined; try { issued = new URL(response.headers.get("x-goog-upload-url") ?? ""); } catch { issued = undefined; } // Only the authorized origin's own upload path, with no credentials of its own. if (!issued || issued.origin !== target.origin || !issued.pathname.startsWith("/upload/") || issued.username || issued.password) { + operation?.finish("failed","upload_url_rejected");report("failed",null); return refuse(502, "upload_url_rejected", "The provider named an upload URL the relay does not send bytes to"); } const token = crypto.randomUUID(); @@ -605,7 +617,10 @@ export function startProviderRelay(options: ProviderRelayOptions = {}): Provider if (response.ok && typeof name === "string" && FILE_HANDLE.test(`/v1beta/${name}`)) owned.set(ownedId(key, name), { key, origin, name }); } if (files.step === "delete" && (response.ok || response.status === 404)) owned.delete(ownedId(key, files.name)); - return new Response(scrub(new Uint8Array(answer), true) as Uint8Array, { status: response.status, headers: out }); + const result=new Response(scrub(new Uint8Array(answer), true) as Uint8Array, { status: response.status, headers: out }); + operation?.finish("completed"); + report(response.ok ? "completed" : "failed", null); + return result; } const json = /\bjson\b/i.test(response.headers.get("content-type") ?? ""); const captured: Uint8Array[] = []; @@ -616,84 +631,101 @@ export function startProviderRelay(options: ProviderRelayOptions = {}): Provider try { usage = providerUsage(family, route.operation, JSON.parse(Buffer.concat(captured).toString("utf8"))); } catch { usage = null; } } - report(response.ok ? "completed" : "failed", response.status, usage); + report(response.ok ? "completed" : "failed", usage); }; if (!response.body) { + const finalFailure=incoming.fence(); + if(finalFailure){report("cancelled",null);return chargeDenied(finalFailure);} operation?.finish("completed"); settle(); return new Response(null, { status: response.status, headers: out }); } - const upstreamReader = response.body.getReader(); + const upstreamReader = incoming; let released = false; - const release = () => { if (!released) { released = true; upstreamReader.releaseLock(); } }; + const release = () => { if (!released) { released = true; upstreamReader.release(); } }; const output = new ReadableStream({ async pull(controller) { // Read until something is enqueued, the upstream ends or fails: a chunk // the scrubber holds back whole must not leave this pull empty. - try { for (;;) { - const next = await upstreamReader.read(); - if (next.done) { - operation?.finish("completed"); settle(); release(); - const tail = scrub(new Uint8Array(0), true); - if (tail.byteLength) controller.enqueue(tail); - controller.close(); return; - } - if (operation && !operation.charge(next.value.byteLength + 16)) { - operation.finish("denied", "max_bytes_per_turn"); - report("cancelled", response.status, null); - await upstreamReader.cancel().catch(() => {}); release(); - controller.error(new Error("Provider egress limit exceeded")); - return; + for (;;) { + let next:Awaited>; + try { next=await upstreamReader.read(); } + catch { + const cause=captureEgressFailure(signal,operation); + operation?.finish(cause.outcome,"upstream_response_failed"); + report(cause.outcome,null); + release();controller.error(new Error(cause.failure?egressChargeRefusal(cause.failure,"Provider").message:"Provider response interrupted"));return; } - capturedBytes += next.value.byteLength; - if (capturing && capturedBytes <= MAX_USAGE_CAPTURE_BYTES) captured.push(next.value); - // Past the ceiling the usage stays unknown: release what was kept. - else if (capturing) { capturing = false; captured.length = 0; } - const clean = scrub(next.value, false); - if (clean.byteLength) { controller.enqueue(clean); return; } - } } catch { - operation?.finish(signal.aborted ? "cancelled" : "failed", "upstream_response_failed"); - report(signal.aborted ? "cancelled" : "failed", response.status, null); - release(); controller.error(new Error("Provider response interrupted")); + let delivered=false; + const failure=next.deliver(()=>{ + if(next.done){ + const tail=scrub(new Uint8Array(0),true); + if(tail.byteLength)controller.enqueue(tail); + controller.close();operation?.finish("completed");settle();release();return; + } + capturedBytes+=next.value.byteLength; + if(capturing&&capturedBytes<=MAX_USAGE_CAPTURE_BYTES)captured.push(next.value); + else if(capturing){capturing=false;captured.length=0;} + const clean=scrub(next.value,false); + if(clean.byteLength){controller.enqueue(clean);delivered=true;} + }); + if(failure){report("cancelled",null);release();controller.error(new Error(egressChargeRefusal(failure,"Provider").message));return;} + if(next.done||delivered)return; } }, async cancel() { operation?.finish("cancelled", "client_disconnected"); - report("cancelled", response.status, null); + report("cancelled", null); await upstreamReader.cancel().catch(() => {}); release(); }, }); return new Response(output, { status: response.status, headers: out }); } /** - * Delete one Files handle a turn left behind, with the host's key and a - * fresh deadline, recorded as its own attempt. A worker that was cancelled - * or killed before its own cleanup ran leaves nothing on the host's account. + * Delete one owned Files handle while the turn still authorizes it, with + * the host's key and a fresh deadline, recorded as its own attempt. + * Turn cancellation revokes that authority and interrupts the DELETE. */ async function cleanup(entry: { key: string; origin: string; name: string }): Promise { const secret = credential(entry.key)?.trim(); if (!secret || /[\r\n]/.test(secret)) return; const target = new URL(`/v1beta/${entry.name}`, entry.origin); - const signal = AbortSignal.timeout(FILES_CLEANUP_MS); - const operation = options.egress?.relayed("DELETE", target, signal); - if (operation && !await operation.admit()) { operation.finish("denied", "provider_admission_refused"); return; } - const headers = new Headers(PLACEMENT.gemini(secret)); - if (operation && !operation.charge(headerBytes(`DELETE ${target.pathname} HTTP/1.1`, headers))) { operation.finish("denied", "max_bytes_per_turn"); return; } + const timeout = AbortSignal.timeout(FILES_CLEANUP_MS); + const operation = options.egress?.relayed("DELETE", target, timeout); + const signal=operation?AbortSignal.any([timeout,operation.signal]):timeout; const attemptId = crypto.randomUUID(); - const observe = (outcome: ProviderRelayReceipt["outcome"], status: number): void => { - try { options.observe?.({ attemptId, family: "gemini", operation: "files", origin: entry.origin, key: entry.key, model: null, outcome, status, usage: null, inlineMedia: false }); } + let upstreamStatus=0; + const observe = (outcome: ProviderRelayReceipt["outcome"]): void => { + try { options.observe?.({ attemptId, family: "gemini", operation: "files", origin: entry.origin, key: entry.key, model: null, outcome, status:upstreamStatus, usage: null, inlineMedia: false }); } catch { /* The host's own accounting reports its failure. */ } }; - observe("dispatched", 0); - if (operation && !operation.commit()) return; + if (operation && !await operation.admit()) { + observe("cancelled"); return; + } + const headers = new Headers(PLACEMENT.gemini(secret)); + const allowance=relayAllowance(operation,options.egress?.remainingBytes?.bind(options.egress),MAX_PROVIDER_REQUEST_BYTES); + const cleanupCharge = allowance.charge(relayHeaderBytes(`DELETE ${target.pathname} HTTP/1.1`, headers)); + if (cleanupCharge) { observe("cancelled"); return; } + const cleanupDecision = operation?.prepare(); + if (cleanupDecision && !cleanupDecision.ok) { observe("cancelled"); return; } + try{options.preparing?.({attemptId,family:"gemini",operation:"files",origin:entry.origin,key:entry.key,model:null,status:0,usage:null,inlineMedia:false});}catch{/* Diagnostics only. */} try { - const response = await fetch(target, { method: "DELETE", headers, redirect: "manual", signal }); - await response.body?.cancel().catch(() => {}); - operation?.finish("completed"); - observe(response.ok ? "completed" : "failed", response.status); + const finalFailure=allowance.charge(0)??captureEgressFailure(signal).failure; + if(finalFailure){observe("cancelled");return;} + let pending!:Promise; + const send=()=>{pending=fetch(target,{method:"DELETE",headers,redirect:"manual",signal});}; + const decision=operation?operation.dispatch(send):(send(),{ok:true as const}); + if(!decision.ok){observe("cancelled");return;} + observe("dispatched"); + const response=await pending; + upstreamStatus=response.status; + const incoming=readRelayResponse(response,{charge:allowance.charge,remaining:allowance.remaining}); + if(incoming.headerFailure){await incoming.cancel().catch(()=>{});observe("cancelled");return;} + try{for(;;){const next=await incoming.read();if(next.done){const failure=next.deliver(()=>{operation?.finish("completed");observe(response.ok?"completed":"failed");});if(failure)observe("cancelled");break;}}}finally{incoming.release();} } catch { - operation?.finish(signal.aborted ? "cancelled" : "failed", "upstream_unreachable"); - observe("failed", 0); + const cause=captureEgressFailure(signal,operation); + operation?.finish(cause.outcome,"upstream_unreachable"); + observe(cause.outcome); } } chmodSync(socketPath, separateIdentity ? 0o660 : 0o600); @@ -720,12 +752,7 @@ export function startProviderRelay(options: ProviderRelayOptions = {}): Provider }; } -/** Bytes a request or response head costs against the turn's egress ceiling. */ -function headerBytes(first: string, values: Headers): number { - let bytes = Buffer.byteLength(first) + 1028; - for (const [name, value] of values) bytes += Buffer.byteLength(name) + Buffer.byteLength(value) + 4; - return bytes; -} + /** * Replace every occurrence of `secret` in a byte stream, including one split diff --git a/packages/ui-sdk/src/server/relay-response.ts b/packages/ui-sdk/src/server/relay-response.ts new file mode 100644 index 0000000000..74b54392e3 --- /dev/null +++ b/packages/ui-sdk/src/server/relay-response.ts @@ -0,0 +1,48 @@ +import { chargeReceivedBytes } from "./egress-accounting.js"; +import type { EgressChargeFailure } from './egress-proxy.js'; + +/** Counts every peer-supplied pair before any forwarding policy removes fields. */ +function receivedHeadBytes(first:string,rawHeaders:readonly string[],allowance:number):number { + let bytes=Buffer.byteLength(first+"\r\n")+2+allowance; + for(let i=0;i[1],allowance=64) { + return chargeReceivedBytes(receivedHeadBytes(first,rawHeaders,allowance),options); +} +/** One logical request head: retain received cost and cover any upstream growth. */ +export function readRelayRequestHead(first:string,headers:Headers,options:Parameters[1]) { + const receivedBytes=relayHeaderBytes(first,headers); + const failure=readReceivedHead(first,[...headers].flat(),options,1024); + return {failure,forward(first:string,headers:Headers){return failure??options.charge(Math.max(0,relayHeaderBytes(first,headers)-receivedBytes));}}; +} +export class RelayResponseRefused extends Error { + constructor(readonly failure:EgressChargeFailure){super('Relay response refused');} +} +/** Owns header-first accounting, charge-before-size ordering and the EOF fence. */ +export function readRelayResponse(response:Response,options:{charge(count:number):EgressChargeFailure|undefined;remaining():number;maxBytes?:number}) { + let reader:ReadableStreamDefaultReader|undefined,size=0; + const received=(count:number)=>chargeReceivedBytes(count,options); + const headerFailure=readReceivedHead(`HTTP/1.1 ${response.status} ${response.statusText}`,[...response.headers].flat(),options,1024); + const fence=()=>options.charge(0); + const deliver=(send:()=>void)=>{const failure=fence();if(failure)return failure;send();return undefined;}; + return { + headerFailure,fence,deliver, + async read():Promise&{deliver:typeof deliver}> { + if(headerFailure)throw new RelayResponseRefused(headerFailure); + reader??=response.body?.getReader(); + const next=reader?await reader.read():{done:true as const,value:undefined}; + const failure=next.done?fence():received(next.value.byteLength+16); + if(failure)throw new RelayResponseRefused(failure); + if(!next.done){size+=next.value.byteLength;if(options.maxBytes!==undefined&&size>options.maxBytes)throw new Error('Relay response too large');} + return next.done?{done:true,value:undefined,deliver}:{done:false,value:next.value,deliver}; + }, + async cancel(){try{if(reader)await reader.cancel();else await response.body?.cancel();}finally{reader?.releaseLock();reader=undefined;}}, + release(){reader?.releaseLock();reader=undefined;}, + }; +} diff --git a/packages/ui-sdk/src/tool-contracts/web.ts b/packages/ui-sdk/src/tool-contracts/web.ts index fa3a3db628..5c2aa29757 100644 --- a/packages/ui-sdk/src/tool-contracts/web.ts +++ b/packages/ui-sdk/src/tool-contracts/web.ts @@ -255,6 +255,8 @@ export interface WebModelEgress { * which hands it to its inference relay unchanged. */ inference(method: string, target: URL, signal: AbortSignal): unknown; + /** Additive reader for the shared allowance. Older routes retain the relay compatibility limit. */ + remainingBytes?():number; } /** What the executor is told about the relayed model: never a credential. */ diff --git a/packages/ui-sdk/tests/egress-charge-reasons.test.ts b/packages/ui-sdk/tests/egress-charge-reasons.test.ts new file mode 100644 index 0000000000..3d42238406 --- /dev/null +++ b/packages/ui-sdk/tests/egress-charge-reasons.test.ts @@ -0,0 +1,57 @@ +import { expect,test } from 'bun:test'; +import { request } from 'node:http'; +import { startEgressProxy } from '../src/server/egress-proxy'; +import { startInferenceRelay, type InferenceRelayEvent } from '../src/server/inference-relay'; +import { startProviderRelay } from '../src/server/provider-relay'; +for(const provider of [false,true])for(const recording of [false,true])for(const response of [false,true])test(`review10: ${provider?'provider':'inference'} ${response?'response':'upload'} reports ${recording?'recording loss':'authority change'} separately from bytes`,async()=>{ + const inference:InferenceRelayEvent[]=[];let current=true,hits=0,entered!:()=>void;const reached=new Promise(r=>{entered=r;});const authority=()=>({evidenceRevision:'1',trustRevision:'1',authorityEpoch:'1',scope:'ithaca',policyHash:null,restricted:false,recordingAvailable:recording?current:true,authorityCurrent:recording?true:current}); + const upstream=Bun.serve({hostname:'127.0.0.1',port:0,fetch(){hits++;if(response)current=false;return new Response('Ithaca');}}); + const proxy=await startEgressProxy({mode:'record',allow:[],deny:[],maxBytes:65536,outwardHosts:[],observe(){},admissionSafety:{read:authority,subscribe:()=>()=>{}},admitted:async()=>entered()}); + const relay=provider?startProviderRelay({origins:new Map([['ANTHROPIC_API_KEY',[upstream.url.origin]]]),credential:()=> 'odysseus-host-key',egress:proxy}):startInferenceRelay({upstream:upstream.url.origin,routes:['/v1/messages'],credentials:{'x-api-key':'odysseus-host-key'},egress:proxy,observe:event=>inference.push(event)}); + let outgoing:ReturnType|undefined; + try{const body=JSON.stringify({model:'odysseus-model',messages:[]});const result=new Promise<{status:number;body:string}>((resolve,reject)=>{outgoing=request({socketPath:relay.socketPath,method:'POST',path:'/v1/messages',headers:{'content-type':'application/json','content-length':Buffer.byteLength(body),...(provider?{'x-brain-provider':'anthropic','x-brain-provider-key':'ANTHROPIC_API_KEY','x-brain-provider-origin':upstream.url.origin}:{})}},res=>{let data='';res.on('data',b=>{data+=b;});res.once('end',()=>resolve({status:res.statusCode!,body:data}));res.once('error',reject);});outgoing.once('error',reject);outgoing.flushHeaders();}); + await reached;if(!response)current=false;outgoing!.end(body);const got=await result;expect(got.status).toBe(recording?503:403);expect(got.body,'SAFETY_OR_UNAVAILABLE_NEVER_REPORTS_BYTE_EXHAUSTION').toContain(provider?(recording?'unavailable':'safety'):'Inference network admission refused');if(!provider)expect(inference.at(-1)?.denialReason,'TYPED_REFUSAL_CAUSE_REMAINS_HOST_ONLY').toBe(recording?'egress_unavailable':'safety_changed');expect(got.body).not.toContain('egress limit exceeded');expect(hits).toBe(response?1:0);expect(proxy.remainingBytes()).toBeGreaterThan(0); + }finally{outgoing?.destroy();await relay.stop();proxy.stop();upstream.stop(true);} +}); + +for(const reason of ['budget','safety','unavailable'] as const)test(`review10: charge distinguishes ${reason}`,async()=>{ + let current=true;const snapshot=()=>({evidenceRevision:'1',trustRevision:'1',authorityEpoch:'1',scope:'ithaca',policyHash:null,restricted:false,recordingAvailable:reason==='unavailable'?current:true,authorityCurrent:reason==='safety'?current:true}); + const proxy=await startEgressProxy({mode:'record',allow:[],deny:[],maxBytes:8,outwardHosts:[],observe(){},admissionSafety:{read:snapshot,subscribe:()=>()=>{}}}); + try{const op=proxy.inference('POST',new URL('http://127.0.0.1/'),new AbortController().signal);expect(await op.admit()).toBe(true);current=false;expect(op.charge(reason==='budget'?9:1),'CHARGE_FAILURE_HAS_A_TYPED_REASON').toEqual({ok:false,reason:reason==='safety'?'safety_changed':reason});}finally{proxy.stop();} +}); + +for(const recording of [false,true])test(`review10: raw HTTP proxy reports ${recording?'unavailable recording':'changed safety'} before delayed bytes`,async()=>{ + let current=true,hits=0,entered!:()=>void;const reached=new Promise(r=>{entered=r;});const upstream=Bun.serve({hostname:'127.0.0.1',port:0,fetch(){hits++;return new Response('Ithaca');}}); + const proxy=await startEgressProxy({mode:'record',allow:[],deny:[],maxBytes:65536,outwardHosts:[],observe(){},preparing:()=>entered(),admissionSafety:{read:()=>({evidenceRevision:'1',trustRevision:'1',authorityEpoch:'1',scope:'ithaca',policyHash:null,restricted:false,recordingAvailable:recording?current:true,authorityCurrent:recording?true:current}),subscribe:()=>()=>{}}});let outgoing:ReturnType|undefined; + try{const result=new Promise<{status:number;body:string}>((resolve,reject)=>{outgoing=request({socketPath:proxy.socketPath,path:upstream.url.href,method:'POST',headers:{'content-length':'6'}},res=>{let body='';res.on('data',b=>{body+=b;});res.once('end',()=>resolve({status:res.statusCode!,body}));res.once('error',reject);});outgoing.once('error',reject);outgoing.flushHeaders();});await reached;current=false;outgoing!.end('Ithaca');const got=await result;expect(got.status).toBe(recording?503:403);expect(got.body,'RAW_PROXY_REPORTS_CHARGE_FAILURE_CLASS').toContain(recording?'unavailable':'safety');expect(hits).toBe(0); + }finally{outgoing?.destroy();proxy.stop();upstream.stop(true);} +}); + +for(const notified of [false,true])test(`review11: source revocation has one safety reason (notification first ${notified})`,async()=>{ + let current=true;const records:import('../src/server/egress-proxy').EgressRecord[]=[];const proxy=await startEgressProxy({mode:'record',allow:[],deny:[],maxBytes:32,outwardHosts:[],observe:r=>records.push(r),inputCurrent:()=>current}); + try{const op=proxy.managedReference(new URL('https://github.com/'),new AbortController().signal);expect(await op.admit()).toBe(true);expect(op.charge(3)).toEqual({ok:true});current=false;if(notified)proxy.invalidateInputs();expect(op.charge(1),'REVOCATION_IS_SAFETY_REGARDLESS_OF_FIRST_FENCE').toEqual({ok:false,reason:'safety_changed'});expect(records[0]).toMatchObject({outcome:'cancelled',reason:'source_trust_changed',bytes:3});expect(records).toHaveLength(1);expect(proxy.remainingBytes()).toBe(29);}finally{proxy.stop();} +}); +for(const count of [-1,-0.5,0.5,NaN,Infinity,-Infinity,Number.MAX_SAFE_INTEGER+1,'1' as unknown as number])test(`review11: invalid charge ${String(count)} leaves both counters intact`,async()=>{ + const records:Array<{bytes:number}>=[];const proxy=await startEgressProxy({mode:'record',allow:[],deny:[],maxBytes:32,outwardHosts:[],observe:r=>{records.push(r);}}); + try{const op=proxy.inference('POST',new URL('http://127.0.0.1/'),new AbortController().signal);expect(await op.admit()).toBe(true);expect(op.charge(8)).toEqual({ok:true});expect(()=>op.charge(count),'INVALID_CHARGE_NEVER_MUTATES_NETWORK_BUDGET').toThrow('nonnegative safe integer');expect(proxy.usedBytes()).toBe(8);expect(proxy.remainingBytes()).toBe(24);expect(op.charge(0)).toEqual({ok:true});expect(op.charge(24)).toEqual({ok:true});expect(proxy.usedBytes()).toBe(32);op.finish('completed');expect(records[0]?.bytes,'INVALID_CHARGE_NEVER_MUTATES_CONNECTION_BYTES').toBe(32);}finally{proxy.stop();} +}); + +for (const failure of ['safety','unavailable','source'] as const) test(`review13: zero-byte completion at the cap still checks ${failure}`, async () => { + let current=true; + const proxy=await startEgressProxy({mode:'record',allow:[],deny:[],maxBytes:8,outwardHosts:[],observe(){}, + inputCurrent:()=>failure!=='source'||current, + admissionSafety:{read:()=>({evidenceRevision:'1',trustRevision:'1',authorityEpoch:'1',scope:'ithaca',policyHash:null,restricted:false,recordingAvailable:failure!=='unavailable'||current,authorityCurrent:failure!=='safety'||current}),subscribe:()=>()=>{}}}); + try{const op=proxy.inference('POST',new URL('http://127.0.0.1/'),new AbortController().signal);expect(await op.admit()).toBe(true);expect(op.dispatch(()=>{})).toEqual({ok:true});expect(op.charge(8)).toEqual({ok:true});expect(op.charge(0),'ZERO_BYTE_TERMINAL_AT_CAP_IS_ALLOWED').toEqual({ok:true});current=false;expect(op.charge(0),'ZERO_BYTE_TERMINAL_REVALIDATES_SAFETY').toEqual({ok:false,reason:failure==='unavailable'?'unavailable':'safety_changed'});}finally{proxy.stop();} +}); + +for(const provider of [false,true])test(`review14: ${provider?'provider':'inference'} initial recording loss is unavailable`,async()=>{ + const upstream=Bun.serve({hostname:'127.0.0.1',port:0,fetch:()=>{throw new Error('No upstream dispatch');}}); + const proxy=await startEgressProxy({mode:'record',allow:[],deny:[],maxBytes:65536,outwardHosts:[],observe(){},admissionSafety:{read:()=>({evidenceRevision:'1',trustRevision:'1',authorityEpoch:'1',scope:'ithaca',policyHash:null,restricted:false,recordingAvailable:false,authorityCurrent:true}),subscribe:()=>()=>{}}}); + const relay=provider?startProviderRelay({origins:new Map([['ANTHROPIC_API_KEY',[upstream.url.origin]]]),credential:()=> 'odysseus-host-key',egress:proxy}):startInferenceRelay({upstream:upstream.url.origin,routes:['/v1/messages'],credentials:{'x-api-key':'odysseus-host-key'},egress:proxy}); + try{const result=await new Promise<{status:number;body:string}>((resolve,reject)=>{const r=request({socketPath:relay.socketPath,method:'POST',path:'/v1/messages',headers:{'content-type':'application/json',...(provider?{'x-brain-provider':'anthropic','x-brain-provider-key':'ANTHROPIC_API_KEY','x-brain-provider-origin':upstream.url.origin}:{})}},res=>{let body='';res.on('data',b=>{body+=b;});res.once('end',()=>resolve({status:res.statusCode!,body}));});r.on('error',reject);r.end(JSON.stringify({model:'odysseus-model',messages:[]}));});expect(result.status).toBe(503);expect(result.body).toContain(provider?'unavailable':'Inference network admission refused');}finally{await relay.stop();proxy.stop();upstream.stop(true);} +}); + +for(const outward of [false,true])test(`review15: stale ${outward?'outward':'Network'} approval keeps its safety refusal`,async()=>{ + let revision='1';const records:import('../src/server/egress-proxy').EgressRecord[]=[];const proxy=await startEgressProxy({mode:'record',allow:[],deny:[],maxBytes:1024,outwardHosts:outward?['github.com']:[],approveOutward:async()=>{revision='2';return true;},observe:r=>records.push(r),taint:{allow:[],tainted:()=>!outward,contacted:()=>false,approvalRevision:()=>revision,approve:async()=>{revision='2';return true;}}}); + try{const op=proxy.managedReference(new URL('https://github.com/'),new AbortController().signal);expect(await op.admit()).toBe(false);expect(op.charge(0),'STALE_APPROVAL_NEVER_BECOMES_UNAVAILABLE').toEqual({ok:false,reason:'safety_changed'});expect(records[0]).toMatchObject({reason:'safety_changed'});}finally{proxy.stop();} +}); diff --git a/packages/ui-sdk/tests/egress-operation-lifecycle.test.ts b/packages/ui-sdk/tests/egress-operation-lifecycle.test.ts new file mode 100644 index 0000000000..5f3bd39979 --- /dev/null +++ b/packages/ui-sdk/tests/egress-operation-lifecycle.test.ts @@ -0,0 +1,55 @@ +import { expect,test } from 'bun:test'; +import { createEgressOperation,type EgressOperationState,type EgressOperationTerminal } from '../src/server/egress-operation'; +const states:EgressOperationState[]=['pending','admitted','dispatched','finished','aborted']; +for(const initial of states)for(const event of ['approval wait','DNS wait','client close','concurrent budget exhaustion'])test(`lifecycle: ${event} at ${initial}`,async()=>{ + const rows:EgressOperationTerminal[]=[],order:string[]=[];let effects=0,dispatches=0; + const op=createEgressOperation({decide:()=>{order.push('decide');},abort:()=>{order.push('abort');},observe:t=>{rows.push(t);order.push('observe');}}); + if(initial!=='pending'&&initial!=='aborted')expect(await op.admit(async()=>true)).toBe(true); + if(initial==='dispatched'||initial==='finished')expect(op.dispatch(8,()=>true,()=>{},()=>{dispatches++;})).toBe(true); + if(initial==='finished')op.finish('completed');if(initial==='aborted')op.finish('cancelled','client_disconnected'); + expect(op.state()).toBe(initial); + if(event==='client close'){ + op.finish('cancelled','client_disconnected');expect(await op.admit(async()=>{effects++;return true;})).toBe(false);expect(await op.effect(()=>{effects++;})).toBe(false);expect(op.dispatch(8,()=>true,()=>{},()=>{dispatches++;})).toBe(false);expect(effects).toBe(0);expect(op.state()).toBe(initial==='finished'?'finished':'aborted'); + }else if(event==='concurrent budget exhaustion'){ + const sent=op.dispatch(0,()=>true,()=>{},()=>{dispatches++;});expect(sent).toBe(initial==='dispatched'); + expect(op.sendRefusal(0,0)).toBe(initial==='dispatched'?undefined:'turn_cancelled'); + expect(op.state()).toBe(initial==='finished'?'finished':initial==='dispatched'?'dispatched':'aborted'); + }else{ + let release!:()=>void;const gate=new Promise(r=>{release=r;});let started=0; + const pending=op.admit(async()=>{started++;await gate;return op.effect(()=>{effects++;});}); + if(initial==='pending'){expect(started).toBe(1);op.finish('cancelled','client_disconnected');release();expect(await pending).toBe(false);expect(effects,'RESUMED_WAIT_HAS_NO_EFFECT_AFTER_ABORT').toBe(0);} + else{release();expect(await pending).toBe(initial==='admitted'||initial==='dispatched');expect(started,'ADMISSION_IS_SINGLE_OWNER_AND_NEVER_RESTARTS').toBe(0);} + } + expect(dispatches).toBe(initial==='dispatched'||initial==='finished'?1:0);op.finish('cancelled','client_disconnected');op.finish('failed','proxy_error');await op.settled();expect(rows).toHaveLength(1);expect(order).toEqual(['decide','abort','observe']); +}); + +test('lifecycle: terminal observation joins an in-flight admission effect and releases once',async()=>{ + let release!:()=>void,entered!:()=>void,open=false;const gate=new Promise(r=>{release=r;}),reached=new Promise(r=>{entered=r;});const rows:EgressOperationTerminal[]=[]; + const op=createEgressOperation({decide(){},abort(){},observe:t=>{expect(open).toBe(true);open=false;rows.push(t);}}); + const pending=op.admit(()=>op.effect(async()=>{entered();await gate;open=true;}));await reached;op.finish('cancelled','client_disconnected');expect(rows).toHaveLength(0);let settled=false;const closing=op.settled().then(()=>{settled=true;});await Promise.resolve();expect(settled).toBe(false);release();expect(await pending).toBe(false);await closing;expect(open).toBe(false);expect(rows).toHaveLength(1);expect(await op.effect(()=>{open=true;})).toBe(false); +}); + +test('lifecycle: concurrent admissions share the same guarded transition',async()=>{ + let release!:()=>void,effects=0;const gate=new Promise(r=>{release=r;});const op=createEgressOperation({decide(){},abort(){},observe(){}}); + const first=op.admit(async()=>{effects++;await gate;return true;}),second=op.admit(async()=>{effects++;return true;});expect(first).toBe(second);release();expect(await first).toBe(true);expect(op.state()).toBe('admitted');expect(effects).toBe(1);expect(op.sendRefusal(0,0)).toBe('max_bytes_per_turn');expect(op.dispatch(0,()=>true,()=>{throw new Error('No dispatch');})).toBe(false);expect(op.state()).toBe('aborted'); +}); + + +test('lifecycle: a declined admission cannot remain live and pending',async()=>{ + const rows:EgressOperationTerminal[]=[];const op=createEgressOperation({decide(){},abort(){},observe:t=>{rows.push(t);}}); + expect(await op.admit(async()=>false)).toBe(false);expect(op.state()).toBe('aborted');expect(rows).toEqual([{outcome:'denied',reason:'call_not_admitted',dispatched:false}]); +}); + +test('lifecycle: terminal cleanup releases every owner once before abort, including a throwing release',()=>{ + const order:string[]=[];const op=createEgressOperation({decide:()=>{order.push('decide');},abort:()=>{order.push('abort');},observe:()=>{order.push('observe');}}); + op.ownCleanup(()=>{order.push('first');});op.ownCleanup(()=>{order.push('throw');throw new Error('Odysseus release failed');});op.ownCleanup(()=>{order.push('last');});op.finish('denied','call_not_admitted');op.finish('failed','proxy_error');op.ownCleanup(()=>{order.push('late');});expect(order).toEqual(['decide','first','throw','last','abort','observe','late']); +}); + +test('review22: final fence precedes send, dispatched state and notification',async()=>{ + const order:string[]=[],rows:EgressOperationTerminal[]=[];const op=createEgressOperation({decide(){},abort(){},observe:r=>rows.push(r)});expect(await op.admit(async()=>true)).toBe(true);op.prepare(()=>{order.push('prepare');}); + expect(op.dispatch(8,()=>{expect(op.dispatched(),'NO_DISPATCH_FACT_BEFORE_FINAL_FENCE').toBe(false);order.push('fence');return true;},()=>{expect(op.dispatched()).toBe(false);order.push('send');},()=>{expect(op.dispatched()).toBe(true);order.push('notify');})).toBe(true);op.finish('failed','upstream_unreachable');expect(order).toEqual(['prepare','fence','send','notify']);expect(rows).toMatchObject([{dispatched:true,outcome:'failed'}]); +}); + +test('review25: a synchronous handoff failure leaves classification to its caller',async()=>{ + const rows:EgressOperationTerminal[]=[];let grants=0;const op=createEgressOperation({decide(){},abort(){},observe:r=>rows.push(r)});expect(await op.admit(async()=>true)).toBe(true);expect(()=>op.dispatch(8,()=>true,()=>{throw new Error('Odysseus transport unavailable');},()=>{grants++;})).toThrow('Upstream transport handoff failed');expect(op.state(),'TRANSPORT_THROW_CANNOT_PREEMPT_CALLER_CLASSIFICATION').toBe('admitted');expect(rows).toEqual([]);expect(grants,'THROW_BEFORE_RETURN_PUBLISHES_NO_GRANT').toBe(0);op.finish('failed','upstream_unreachable');expect(rows).toEqual([{outcome:'failed',reason:'upstream_unreachable',dispatched:false}]); +}); diff --git a/packages/ui-sdk/tests/egress-proxy.test.ts b/packages/ui-sdk/tests/egress-proxy.test.ts index 767d586d51..b815f65d10 100644 --- a/packages/ui-sdk/tests/egress-proxy.test.ts +++ b/packages/ui-sdk/tests/egress-proxy.test.ts @@ -1,4 +1,6 @@ -import { expect, test } from "bun:test"; +import { expect, test, spyOn } from "bun:test"; +import * as nodeHttp from "node:http"; +import * as nodeNet from "node:net"; import { connect, createServer } from "node:net"; import { request } from "node:http"; import { existsSync } from "node:fs"; @@ -316,14 +318,14 @@ test("a tainted turn reaches only taint-allowed or already contacted hosts; the } 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 }> = []; + let calls = 0; const records: EgressRecord[] = [], asked: Array<{ host: string; port: number; method: string; protocol: string; managedReference: boolean }> = []; 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" }]); + expect(asked, "EGRESS_TAINT_APPROVE_NAMES_DESTINATION").toEqual([{ host: "127.0.0.1", port: origin.port!, method: "GET", protocol: "http:", managedReference: false }]); 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); @@ -345,7 +347,7 @@ test("taint narrowing never overrides deny or the ordinary allowlist, and its pa expect((await get(proxy.socketPath, origin.url.href)).status, "EGRESS_TAINT_IS_NARROWING_ONLY").toBe(403); expect(records[0]).toMatchObject({ reason: "destination_not_allowed" }); } finally { proxy.stop(); origin.stop(true); } - await expect(startEgressProxy({ ...defaults([]), taint: { allow: ["bad host"], tainted: () => true, contacted: () => false } })).rejects.toThrow("Invalid egress host pattern"); + for (const host of ["bad host", "[::1", "::1]"]) await expect(startEgressProxy({ ...defaults([]), taint: { allow: [host], tainted: () => true, contacted: () => false } })).rejects.toThrow("Invalid egress host pattern"); }); test("each refusal tells the tool why in its status line and body (#3431)", async () => { @@ -376,3 +378,152 @@ test("each refusal tells the tool why in its status line and body (#3431)", asyn expect(calls).toBe(0); } finally { origin.stop(true); } }); + +test("review: invalidation between TCP dispatch and connect closes both real tunnel sockets",async()=>{ + const {Socket}=await import('node:net');const {spyOn}=await import('bun:test');let accepted:InstanceType|undefined,release!:()=>void,entered!:()=>void;const reached=new Promise(r=>{entered=r;}); + let serverClosed!:()=>void;const upstreamClosed=new Promise(r=>{serverClosed=r;});const server=createServer(socket=>{accepted=socket;socket.once('close',serverClosed);});await new Promise(r=>server.listen(0,'127.0.0.1',r));const port=(server.address() as {port:number}).port; + const original=Socket.prototype.emit;const event=spyOn(Socket.prototype,'emit').mockImplementation(function(this:InstanceType,name:string|symbol,...args:any[]){if(name==='connect'&&this.remotePort===port){release=()=>{original.call(this,name,...args);};entered();return true;}return original.call(this,name,...args);}); + let current=true;const proxy=await startEgressProxy({...defaults([]),inputCurrent:()=>current});const client=connect(proxy.socketPath);const outcome=new Promise(r=>{client.once('data',b=>r(b.toString()));client.once('close',()=>r('closed'));});client.on('error',()=>{});client.once('connect',()=>client.write(`CONNECT 127.0.0.1:${port} HTTP/1.1\r\nHost: 127.0.0.1\r\n\r\n`)); + try{await reached;current=false;proxy.invalidateInputs();release();expect(await outcome,'CANCELLED_CONNECT_NEVER_RETURNS_200').toBe('closed');await upstreamClosed;expect(accepted?.destroyed).toBe(true);}finally{event.mockRestore();client.destroy();accepted?.destroy();proxy.stop();await new Promise(r=>server.close(()=>r()));} +}); + +test('review2: one successful real tunnel notifies committed exactly once',async()=>{ + let serverSocket:import('node:net').Socket|undefined;const server=createServer(s=>{serverSocket=s;});await new Promise(r=>server.listen(0,'127.0.0.1',r));const port=(server.address() as {port:number}).port;let commits=0;const proxy=await startEgressProxy({...defaults([]),committed:()=>{commits++;}}); + try{expect(await new Promise((resolve,reject)=>{const client=connect(proxy.socketPath);client.on('error',reject);client.once('connect',()=>client.write(`CONNECT 127.0.0.1:${port} HTTP/1.1\r\nHost: 127.0.0.1\r\n\r\n`));client.once('data',b=>{resolve(Number(/^HTTP\/1.1 (\d+)/.exec(b.toString())?.[1]));client.destroy();});})).toBe(200);expect(commits,'TUNNEL_COMMIT_NOTIFICATION_IS_EXACTLY_ONCE').toBe(1); + const op=proxy.relayed('GET',new URL(`http://127.0.0.1:${port}/`),new AbortController().signal);expect(await op.admit()).toBe(true);expect(op.dispatch(()=>{})).toEqual({ok:true});expect(op.dispatch(()=>{})).toEqual({ok:true});expect(commits,'RELAY_RECHECKS_DO_NOT_REPEAT_COMMIT_NOTIFICATION').toBe(2);op.finish('completed'); + }finally{proxy.stop();serverSocket?.destroy();await new Promise(r=>server.close(()=>r()));} +}); + +test('review4: bracketed IPv6 keeps canonical trust identity and dials a checked IP',async()=>{ + const server=createServer(socket=>socket.on('data',b=>socket.write(b.toString().toUpperCase())));await new Promise(r=>server.listen(0,'::1',r));const port=(server.address() as {port:number}).port;const records:EgressRecord[]=[]; + const proxy=await startEgressProxy({...defaults(records),destinations:{ports:[port],allowRanges:['::1/128'],lookup:async()=>{throw new Error('IPv6 literals must bypass DNS');}}}); + try{expect(await tunnel(proxy.socketPath,`[::1]:${port}`,'ithaca'),'CHECKED_IPV6_TUNNEL_REACHES_LOOPBACK').toContain('ITHACA');await recorded(records,1);expect(records[0]).toMatchObject({host:'::1',port,outcome:'completed'}); + for(const bad of ['::1:443','[::1]','[::1]:0','[::1]:65536','[::1]:443/path','[::1%25lo]:443'])expect(await tunnel(proxy.socketPath,bad,''),'MALFORMED_TUNNEL_REMAINS_BAD_REQUEST').toContain('400 Bad Request'); + }finally{proxy.stop();await new Promise(r=>server.close(()=>r()));} +}); + +for(const approval of [false,true])for(const body of [false,true])test(`review6: delayed HTTP ${body?'write':'end'} fences stale ${approval?'card':'recipient rule'}`,async()=>{ + let hits=0,current=true,revision='1',entered!:()=>void;const committed=new Promise(r=>{entered=r;});const origin=Bun.serve({hostname:'127.0.0.1',port:0,fetch(){hits++;return new Response('Ithaca');}}); + const proxy=await startEgressProxy({...defaults([]),preparing:()=>entered(),taint:{allow:[],tainted:()=>true,contacted:()=>false,recipient:()=>!approval&¤t,approvalRevision:()=>revision,approve:async()=>approval}});const client=connect(proxy.socketPath);client.on('error',()=>{});const closed=new Promise(r=>client.once('close',()=>r()));client.on('data',()=>client.end()); + try{client.write(`POST ${origin.url.href} HTTP/1.1\r\nHost: 127.0.0.1\r\nTransfer-Encoding: chunked\r\n\r\n`);await committed;current=false;revision='2';client.write(body?'4\r\nraft\r\n0\r\n\r\n':'0\r\n\r\n');await closed;expect(hits,'DELAYED_HTTP_NEVER_SENDS_UNDER_WITHDRAWN_AUTHORITY').toBe(0); + }finally{client.destroy();proxy.stop();origin.stop(true);} +}); + +for(const outward of [false,true])test(`review6: canonical IPv6 honors ${outward?'outward approval':'deny'} policies`,async()=>{ + let asks=0;const records:EgressRecord[]=[];const server=createServer(socket=>socket.on('data',b=>socket.write(b.toString().toUpperCase())));await new Promise(r=>server.listen(0,'::1',r));const port=(server.address() as {port:number}).port; + const proxy=await startEgressProxy({...defaults(records),...(outward?{outwardHosts:['0:0:0:0:0:0:0:1'],approveOutward:async()=>{asks++;return false;}}:{deny:['::1']})}); + try{expect(await tunnel(proxy.socketPath,`[::1]:${port}`,'ithaca'),'CANONICAL_IPV6_NEVER_BYPASSES_HOST_POLICY').toContain('403');expect(asks).toBe(outward?1:0);expect(records[0]?.host,'IPV6_RECEIPTS_USE_CANONICAL_BARE_HOST').toBe('::1');}finally{proxy.stop();await new Promise(r=>server.close(()=>r()));} +}); + +for(const approval of [false,true])test(`review6: tunnel chunks fence a withdrawn ${approval?'card':'recipient rule'}`,async()=>{ + let bytes=0,current=true,revision='1',closed!:()=>void;const upstreamClosed=new Promise(r=>{closed=r;});const server=createServer(socket=>{socket.on('data',b=>{bytes+=b.length;socket.end();});socket.once('close',closed);});await new Promise(r=>server.listen(0,'127.0.0.1',r));const port=(server.address() as {port:number}).port; + const proxy=await startEgressProxy({...defaults([]),taint:{allow:[],tainted:()=>true,contacted:()=>false,recipient:()=>!approval&¤t,approvalRevision:()=>revision,approve:async()=>approval}});const client=connect(proxy.socketPath);client.on('error',()=>{});const ended=new Promise(r=>client.once('close',()=>r())); + try{const ready=new Promise(r=>client.once('data',b=>{expect(b.toString()).toContain('200 Connection Established');r();}));client.write(`CONNECT 127.0.0.1:${port} HTTP/1.1\r\nHost: 127.0.0.1\r\n\r\n`);await ready;current=false;revision='2';client.write('ithaca');await ended;await upstreamClosed;expect(bytes,'TUNNEL_CHUNKS_NEVER_BYPASS_RECIPIENT_OR_CARD_FENCE').toBe(0); + }finally{client.destroy();proxy.stop();await new Promise(r=>server.close(()=>r()));} +}); + +test('review7: absent approvals never read approval history during a real HTTP exchange',async()=>{ + let reads=0;const origin=Bun.serve({hostname:'127.0.0.1',port:0,fetch:()=>new Response('Ithaca')});const proxy=await startEgressProxy({...defaults([]),taint:{allow:[],tainted:()=>false,contacted:()=>false,approvalRevision:()=>{reads++;return '1';}}}); + try{expect((await get(proxy.socketPath,origin.url.href)).status).toBe(200);expect(reads,'ABSENT_APPROVAL_NEVER_READS_REVISION').toBe(0);}finally{proxy.stop();origin.stop(true);} +}); + +for(const pinned of [false,true])test(`review9: absolute DNS authority survives ${pinned?'checked resolution':'unbound dialing'}`,async()=>{ + const {Socket}=await import('node:net');const {spyOn}=await import('bun:test');const server=createServer(socket=>socket.on('data',b=>socket.write(b.toString().toUpperCase())));await new Promise(r=>server.listen(0,'127.0.0.1',r));const port=(server.address() as {port:number}).port;const seen:string[]=[],records:EgressRecord[]=[]; + const original=Socket.prototype.connect;const spy=spyOn(Socket.prototype,'connect').mockImplementation(function(this:InstanceType,...args:any[]){const values=Array.isArray(args[0])?args[0]:args,options=values[0];if(!pinned&&options&&typeof options==='object'&&options.port===port){seen.push(options.host);values[0]={...options,host:'127.0.0.1'};return Reflect.apply(original,this,args);}return Reflect.apply(original,this,args);}); + const proxy=await startEgressProxy({...defaults(records),...(pinned?{destinations:{ports:[port],allowRanges:['127.0.0.0/8'],lookup:async(host:string)=>{seen.push(host);return [{address:'127.0.0.1',family:4}];}}}:{})}); + try{expect(await tunnel(proxy.socketPath,`ithaca.example.org.:${port}`,'ithaca')).toContain('ITHACA');expect(seen,'ABSOLUTE_DNS_AUTHORITY_NEVER_LOSES_ITS_DOT').toEqual(['ithaca.example.org.']);await recorded(records,1);expect(records[0]?.host).toBe('ithaca.example.org');}finally{spy.mockRestore();proxy.stop();await new Promise(r=>server.close(()=>r()));} +}); + +for (const over of [false, true]) test(`review13: real HTTP end ${over ? 'refuses one byte over' : 'completes at'} the exact cap`, async () => { + const origin = Bun.serve({ hostname: '127.0.0.1', port: 0, fetch: () => new Response('Ithaca') }); + const measured: EgressRecord[] = [], sample = await startEgressProxy({ ...defaults(measured), maxBytes: 4096 }); + try { + await get(sample.socketPath, origin.url.href); await recorded(measured, 1); + const cap = measured[0]!.bytes, records: EgressRecord[] = []; + const proxy = await startEgressProxy({ ...defaults(records), maxBytes: cap - Number(over) }); + try { + const result = await get(proxy.socketPath, origin.url.href).catch(() => null); + await recorded(records, 1); + if (over) { expect(result?.body).not.toBe('Ithaca'); expect(records[0]).toMatchObject({ outcome: 'denied', reason: 'max_bytes_per_turn' }); } + else { expect(result, 'HTTP_EXACT_CAP_END_COMPLETES').toEqual({ status: 200, body: 'Ithaca' }); expect(records[0]).toMatchObject({ outcome: 'completed', bytes: cap }); } + } finally { proxy.stop(); } + } finally { sample.stop(); origin.stop(true); } +}); + +for (const over of [false, true]) test(`review13: real tunnel close ${over ? 'refuses one byte over' : 'completes at'} the exact cap`, async () => { + const payload = 'Ithaca', records: EgressRecord[] = []; + const origin = createServer(socket => socket.end(payload)); + await new Promise(resolve => origin.listen(0, '127.0.0.1', resolve)); + const port = (origin.address() as { port: number }).port; + const proxy = await startEgressProxy({ ...defaults(records), maxBytes: Buffer.byteLength(payload) - Number(over) }); + const client = connect(proxy.socketPath); let text = ''; + try { + await new Promise((resolve, reject) => { + client.on('error', reject); client.on('data', bytes => { text += bytes; }); + client.once('connect', () => client.write(`CONNECT 127.0.0.1:${port} HTTP/1.1\r\nHost: 127.0.0.1:${port}\r\n\r\n`)); + client.once('end', () => client.end()); client.once('close', () => resolve()); + }); + await recorded(records, 1); + if (over) { expect(text).not.toContain(payload); expect(records[0]).toMatchObject({ outcome: 'denied', reason: 'max_bytes_per_turn' }); } + else { expect(text, 'TUNNEL_EXACT_CAP_CLOSE_COMPLETES').toContain(payload); expect(records[0]).toMatchObject({ outcome: 'completed', bytes: payload.length }); } + } finally { client.destroy(); proxy.stop(); await new Promise(resolve => origin.close(() => resolve())); } +}); + +test('review14: oversized HTTP headers never publish a contacted-host grant', async () => { + let dispatched=0,hits=0;const records:EgressRecord[]=[]; + const origin=Bun.serve({hostname:'127.0.0.1',port:0,fetch(){hits++;return new Response('Ithaca');}}); + const proxy=await startEgressProxy({...defaults(records),maxBytes:128,committed:()=>{dispatched++;}}); + try{expect((await get(proxy.socketPath,origin.url.href,'GET',undefined,{'x-odysseus':'x'.repeat(1024)})).status).toBe(403);expect(dispatched,'NO_CONTACTED_GRANT_BEFORE_HEADER_BUDGET_PASSES').toBe(0);expect(hits).toBe(0);}finally{proxy.stop();origin.stop(true);} +}); + +for(const method of ['GET','CONNECT'])test(`review14: initial recording loss is unavailable for ${method}`,async()=>{ + const records:EgressRecord[]=[];const proxy=await startEgressProxy({...defaults(records),admissionSafety:{read:()=>({evidenceRevision:'1',trustRevision:'1',authorityEpoch:'1',scope:'ithaca',policyHash:null,restricted:false,recordingAvailable:false,authorityCurrent:true}),subscribe:()=>()=>{}}}); + try{const status=method==='GET'?(await get(proxy.socketPath,'http://127.0.0.1:443/')).status:Number(/^HTTP\/1.1 (\d+)/.exec(await tunnel(proxy.socketPath,'127.0.0.1:443',''))?.[1]);expect(status,'INITIAL_RECORDING_LOSS_USES_SAME_503_CLASS').toBe(503);expect(records[0]).toMatchObject({outcome:'denied',reason:'egress_unavailable'});}finally{proxy.stop();} +}); + +test('review14: charged preparation does not commit until final dispatch',async()=>{ + let commits=0;const records:EgressRecord[]=[];const proxy=await startEgressProxy({...defaults(records),committed:()=>{commits++;}}); + try{const op=proxy.relayed('POST',new URL('http://127.0.0.1/'),new AbortController().signal);expect(await op.admit()).toBe(true);expect(op.charge(8)).toEqual({ok:true});expect(commits,'CHARGING_IS_NOT_DISPATCH').toBe(0);op.finish('denied','invalid_request');expect(records[0]).toMatchObject({bytes:8,dispatched:false});const sent=proxy.relayed('POST',new URL('http://127.0.0.1/'),new AbortController().signal);expect(await sent.admit()).toBe(true);expect(sent.charge(8)).toEqual({ok:true});expect(sent.dispatch(()=>{})).toEqual({ok:true});expect(sent.dispatch(()=>{})).toEqual({ok:true});expect(commits).toBe(1);sent.finish('completed');expect(records[1]).toMatchObject({dispatched:true});}finally{proxy.stop();} +}); + +test('review16: exhausted budget during approval cannot start an empty-head CONNECT',async()=>{ + let entered!:()=>void,release!:()=>void,accepted=0,commits=0;const reached=new Promise(r=>{entered=r;}),held=new Promise(r=>{release=r;});const records:EgressRecord[]=[];const origin=createServer(s=>{accepted++;s.end();});await new Promise(r=>origin.listen(0,'127.0.0.1',r));const port=(origin.address() as {port:number}).port; + const proxy=await startEgressProxy({...defaults(records),maxBytes:8,outwardHosts:['127.0.0.1'],approveOutward:async()=>{entered();await held;return true;},committed:d=>{if(!d.inference)commits++;}}); + try{const pending=tunnel(proxy.socketPath,`127.0.0.1:${port}`,'');await reached;const other=proxy.inference('POST',new URL('https://api.example.org/'),new AbortController().signal);expect(await other.admit()).toBe(true);expect(other.dispatch(()=>{})).toEqual({ok:true});expect(other.charge(8)).toEqual({ok:true});other.finish('completed');release();expect(await pending,'NEW_CONNECT_NEEDS_POSITIVE_REMAINING_BUDGET').toContain('403');expect(accepted).toBe(0);expect(commits).toBe(0);}finally{release();proxy.stop();await new Promise(r=>origin.close(()=>r()));} +}); + +test('review16: close during real CONNECT DNS wait never starts the admitted effect',async()=>{ + let entered!:()=>void,release!:()=>void,effects=0;const reached=new Promise(r=>{entered=r;}),held=new Promise(r=>{release=r;});const records:EgressRecord[]=[];const proxy=await startEgressProxy({...defaults(records),destinations:{ports:[443],allowRanges:['127.0.0.0/8'],lookup:async()=>{entered();await held;return [{address:'127.0.0.1',family:4}];}},admitted:async()=>{effects++;}});const client=connect(proxy.socketPath);client.on('error',()=>{}); + try{client.once('connect',()=>client.write('CONNECT ithaca.example.org:443 HTTP/1.1\r\nHost: ithaca.example.org\r\n\r\n'));await reached;client.destroy();await recorded(records,1);release();await Bun.sleep(20);expect(effects,'FINISHED_DNS_CONTINUATION_NEVER_CREATES_INPUT').toBe(0);expect(records).toHaveLength(1);expect(records[0]).toMatchObject({outcome:'cancelled',dispatched:false});}finally{release();client.destroy();proxy.stop();} +}); + +for(const unavailable of [false,true])test(`review23: HTTP construction is behind final fence (unavailable ${unavailable})`,async()=>{ + let current=true,accepted=0,grants=0;const records:EgressRecord[]=[];const origin=createServer(socket=>{accepted++;socket.end();});await new Promise(r=>origin.listen(0,'127.0.0.1',r));const port=(origin.address() as {port:number}).port; + const proxy=await startEgressProxy({...defaults(records),preparing:()=>{current=false;},committed:()=>{grants++;},admissionSafety:{read:()=>({evidenceRevision:'1',trustRevision:'1',authorityEpoch:'1',scope:'ithaca',policyHash:null,restricted:false,recordingAvailable:unavailable?current:true,authorityCurrent:unavailable?true:current}),subscribe:()=>()=>{}}}); + try{const answer=await get(proxy.socketPath,`http://127.0.0.1:${port}/`);expect(answer.status,'CONNECTION_CONSTRUCTION_REQUIRES_THE_FINAL_FENCE').toBe(unavailable?503:403);expect(accepted,'REFUSED_HTTP_NEVER_OPENS_AN_UPSTREAM_SOCKET').toBe(0);expect(grants).toBe(0);expect(records[0]).toMatchObject({dispatched:false,outcome:'denied'});}finally{proxy.stop();await new Promise(r=>origin.close(()=>r()));} +}); + +test('review23: HTTP connection attempt is recorded while client body is pending',async()=>{ + let entered!:()=>void,grants=0;const accepted=new Promise(r=>{entered=r;});const sockets:import('node:net').Socket[]=[];const origin=createServer(s=>{sockets.push(s);s.on('error',()=>{});entered();});await new Promise(r=>origin.listen(0,'127.0.0.1',r));const port=(origin.address() as {port:number}).port;const records:EgressRecord[]=[];const proxy=await startEgressProxy({...defaults(records),committed:()=>{grants++;}});const client=request({socketPath:proxy.socketPath,path:`http://127.0.0.1:${port}/`,method:'POST',headers:{'content-length':'4'}});client.on('error',()=>{}); + try{client.flushHeaders();await accepted;expect(grants,'CONNECTION_ATTEMPT_IS_ALREADY_A_DISPATCH_FACT').toBe(1);client.destroy();await recorded(records,1);expect(records[0]).toMatchObject({dispatched:true});}finally{client.destroy();proxy.stop();for(const s of sockets)s.destroy();await new Promise(r=>origin.close(()=>r()));} +}); + +for(const opaque of [false,true])test(`review24: received ${opaque?'CONNECT':'HTTP'} overflow consumes remaining allowance`,async()=>{ + const records:EgressRecord[]=[];const origin=createServer(socket=>{socket.on('error',()=>{});if(opaque)socket.end('Ithaca '.repeat(2048));else socket.once('data',()=>socket.end('HTTP/1.1 200 OK\r\nContent-Length: 14336\r\n\r\n'+'Ithaca '.repeat(2048)));});await new Promise(r=>origin.listen(0,'127.0.0.1',r));const port=(origin.address() as {port:number}).port;const proxy=await startEgressProxy({...defaults(records),maxBytes:4096}); + try{if(opaque)await tunnel(proxy.socketPath,`127.0.0.1:${port}`,'');else await get(proxy.socketPath,`http://127.0.0.1:${port}/`).catch(()=>undefined);await recorded(records,1);expect(proxy.remainingBytes(),'RECEIVED_PROXY_BYTES_CANNOT_LEAVE_LATER_ALLOWANCE').toBe(0);expect(records[0]).toMatchObject({outcome:'denied',failureReason:'budget',bytes:4096});}finally{proxy.stop();await new Promise(r=>origin.close(()=>r()));} +}); + + +for(const opaque of [false,true])for(const synchronous of [false,true])test(`review25: proxy ${opaque?'CONNECT':'HTTP'} ${synchronous?'sync throw':'async refusal'} is 502`,async()=>{ + const reserved=createServer();await new Promise(r=>reserved.listen(0,'127.0.0.1',r));const port=(reserved.address() as {port:number}).port;await new Promise(r=>reserved.close(()=>r()));const records:EgressRecord[]=[];const proxy=await startEgressProxy(defaults(records));const originalHttp=nodeHttp.request,originalConnect=nodeNet.connect; + const mocked=synchronous?(opaque?spyOn(nodeNet,'connect').mockImplementation(((...args:unknown[])=>{if(typeof args[0]==='object'&&args[0]!==null&&'port' in args[0]&&Number(args[0].port)===port)throw new Error('Odysseus dial unavailable');return Reflect.apply(originalConnect,nodeNet,args);}) as typeof nodeNet.connect):spyOn(nodeHttp,'request').mockImplementation(((...args:Parameters)=>{if(args[0] instanceof URL&&Number(args[0].port)===port)throw new Error('Odysseus HTTP unavailable');return Reflect.apply(originalHttp,nodeHttp,args);}) as typeof nodeHttp.request)):undefined; + try{const status=opaque?Number(/^HTTP\/1.1 (\d+)/.exec(await tunnel(proxy.socketPath,`127.0.0.1:${port}`,'').catch(()=>''))?.[1]??0):(await get(proxy.socketPath,`http://127.0.0.1:${port}/`).catch(()=>({status:0}))).status;expect(status,'PROXY_SYNC_AND_ASYNC_TRANSPORT_FAILURE_ARE_502').toBe(502);await recorded(records,1);expect(records[0]).toMatchObject({outcome:'failed',reason:'upstream_unreachable',dispatched:!synchronous});}finally{mocked?.mockRestore();proxy.stop();} +}); + + +for(const opaque of [false,true])test(`review27: failed ${opaque?'CONNECT':'HTTP'} construction grants no future recipient permission`,async()=>{ + const origin=createServer();await new Promise(r=>origin.listen(0,'127.0.0.1',r));const port=(origin.address() as {port:number}).port;const records:EgressRecord[]=[],contacted=new Set();let tainted=false,cards=0;const proxy=await startEgressProxy({...defaults(records),committed:d=>{contacted.add(d.host);},taint:{allow:[],tainted:()=>tainted,contacted:host=>contacted.has(host),approve:async()=>{cards++;return false;}}});const originalHttp=nodeHttp.request,originalConnect=nodeNet.connect; + const mocked=opaque?spyOn(nodeNet,'connect').mockImplementation(((...args:unknown[])=>{if(typeof args[0]==='object'&&args[0]!==null&&'port' in args[0]&&Number(args[0].port)===port)throw new Error('Odysseus dial cannot start');return Reflect.apply(originalConnect,nodeNet,args);}) as typeof nodeNet.connect):spyOn(nodeHttp,'request').mockImplementation(((...args:Parameters)=>{if(args[0] instanceof URL&&Number(args[0].port)===port)throw new Error('Odysseus HTTP cannot start');return Reflect.apply(originalHttp,nodeHttp,args);}) as typeof nodeHttp.request); + const attempt=async()=>opaque?Number(/^HTTP\/1.1 (\d+)/.exec(await tunnel(proxy.socketPath,`127.0.0.1:${port}`,''))?.[1]??0):(await get(proxy.socketPath,`http://127.0.0.1:${port}/`)).status; + try{expect(await attempt()).toBe(502);expect(contacted.size,'CONSTRUCTOR_THROW_NEVER_CREATES_CONTACTED_GRANT').toBe(0);expect(records[0]).toMatchObject({outcome:'failed',reason:'upstream_unreachable',dispatched:false});tainted=true;expect(await attempt(),'LATER_RESTRICTED_REQUEST_STILL_NEEDS_NETWORK_CARD').toBe(403);expect(cards).toBe(1);expect(contacted.size).toBe(0);}finally{mocked.mockRestore();proxy.stop();await new Promise(r=>origin.close(()=>r()));} +}); diff --git a/packages/ui-sdk/tests/egress-reference.test.ts b/packages/ui-sdk/tests/egress-reference.test.ts index 62c83c3254..8d6d88d4e7 100644 --- a/packages/ui-sdk/tests/egress-reference.test.ts +++ b/packages/ui-sdk/tests/egress-reference.test.ts @@ -9,9 +9,9 @@ test("managed reference shares the real turn counter with inference and refuses const records: EgressRecord[] = [], proxy = await startEgressProxy(options(records)), signal = new AbortController().signal; try { const inference = proxy.inference("POST", new URL("https://api.anthropic.com/v1/messages"), signal); - expect(await inference.admit()).toBe(true); expect(inference.charge(10)).toBe(true); inference.finish("completed"); + expect(await inference.admit()).toBe(true); expect(inference.dispatch(()=>{})).toEqual({ok:true}); expect(inference.charge(10).ok).toBe(true); inference.finish("completed"); const reference = proxy.managedReference(github, signal); - expect(await reference.admit()).toBe(true); expect(reference.charge(22)).toBe(true); reference.finish("completed"); + expect(await reference.admit()).toBe(true); expect(reference.dispatch(()=>{})).toEqual({ok:true}); expect(reference.charge(22).ok).toBe(true); reference.finish("completed"); expect(proxy.usedBytes(), "REFERENCE_SHARES_TURN_WIRE_COUNTER").toBe(32); const refused = proxy.managedReference(github, signal); expect(await refused.admit(), "REFERENCE_EXHAUSTED_TURN_REFUSED").toBe(false); @@ -40,7 +40,7 @@ test("managed reference rechecks narrowing after its own final wait and still ho taint: { allow: [], tainted: () => restricted, contacted: () => false } }); try { const ref = proxy.managedReference(github, new AbortController().signal); - if (mode === "final") { expect(await ref.admit()).toBe(true); restricted = true; expect(ref.commit(), "REFERENCE_FINAL_RECIPIENT_FENCE").toBe(false); } + if (mode === "final") { expect(await ref.admit()).toBe(true); restricted = true; expect(ref.dispatch(()=>{}), "REFERENCE_FINAL_RECIPIENT_FENCE").toEqual({ok:false,reason:"policy_denied"}); } else expect(await ref.admit(), "REFERENCE_ORDINARY_EGRESS_POLICY_RETAINS_AUTHORITY").toBe(false); expect(records.at(-1)?.outcome).toBe("denied"); } finally { proxy.stop(); } diff --git a/packages/ui-sdk/tests/egress-socket-ownership.test.ts b/packages/ui-sdk/tests/egress-socket-ownership.test.ts new file mode 100644 index 0000000000..cb03e55367 --- /dev/null +++ b/packages/ui-sdk/tests/egress-socket-ownership.test.ts @@ -0,0 +1,165 @@ +import { expect, spyOn, test } from "bun:test"; +import * as http from "node:http"; +import type { Socket } from "node:net"; +import { startEgressProxy, type EgressRecord } from "../src/server/egress-proxy.js"; + +function get(socketPath: string, target: string): Promise { + return new Promise((resolve, reject) => { + const request = http.request({ socketPath, path: target }, response => { + response.resume(); + response.once("end", () => resolve(response.statusCode!)); + response.once("error", reject); + }); + request.once("error", reject); request.end(); + }); +} + +// Delay only the first proxy response's close notification. Its upstream +// response has completed and the agent can lend the real socket to a peer. +test("completed HTTP cleanup cannot destroy a socket already lent to a same-origin peer", async () => { + const agent = new http.Agent({ keepAlive: true, maxSockets: 1 }); + const records: EgressRecord[] = []; + const closeReady = Promise.withResolvers(), peerEntered = Promise.withResolvers(), releasePeer = Promise.withResolvers(); + let delayedClose: (() => void) | undefined; + const sockets: Socket[] = []; + const origin = Bun.serve({ hostname: "127.0.0.1", port: 0, async fetch(request) { + if (new URL(request.url).pathname === "/peer") { peerEntered.resolve(); await releasePeer.promise; } + return new Response("Ithaca"); + } }); + const proxy = await startEgressProxy({ mode: "record", allow: [], deny: [], maxBytes: 8192, outwardHosts: [], observe: row => records.push(row) }); + const originalRequest = http.request, originalEmit = http.ServerResponse.prototype.emit; + const requestSpy = spyOn(http, "request").mockImplementation(((...args: Parameters) => { + if (args[0] instanceof URL && args[0].port === String(origin.port)) { + const options = args[1] as http.RequestOptions; + // Exercise actual pooling even on transports that honor Connection: close. + const request = originalRequest(args[0], { ...options, agent, headers: { ...options.headers, connection: "keep-alive" } }, args[2] as (response: http.IncomingMessage) => void); + request.once("socket", socket => sockets.push(socket)); + return request; + } + return Reflect.apply(originalRequest, http, args); + }) as typeof http.request); + const closeSpy = spyOn(http.ServerResponse.prototype, "emit").mockImplementation(function(this: http.ServerResponse, event: string | symbol, ...args: unknown[]) { + if (event === "close" && this.req.url === `${origin.url}first` && !delayedClose) { + let delivered = false; + delayedClose = () => { if (!delivered) { delivered = true; Reflect.apply(originalEmit, this, [event, ...args]); } }; + closeReady.resolve(); return true; + } + return Reflect.apply(originalEmit, this, [event, ...args]); + }); + let peer: Promise | undefined; + try { + expect(await get(proxy.socketPath, `${origin.url}first`)).toBe(200); + await closeReady.promise; + peer = get(proxy.socketPath, `${origin.url}peer`); + await peerEntered.promise; + expect(sockets).toHaveLength(2); + expect(sockets[1], "PEER_REUSES_THE_FIRST_REAL_TCP_SOCKET").toBe(sockets[0]); + delayedClose!(); + releasePeer.resolve(); + expect(await peer, "COMPLETED_OPERATION_NEVER_RESETS_REUSED_SOCKET").toBe(200); + expect(records[0]).toMatchObject({ outcome: "completed", dispatched: true }); + } finally { + releasePeer.resolve(); delayedClose?.(); proxy.stop(); + await peer?.catch(() => {}); + closeSpy.mockRestore(); requestSpy.mockRestore(); agent.destroy(); origin.stop(true); + } +}); + +test("cancelling HTTP still destroys the in-flight operation's owned socket", async () => { + const entered = Promise.withResolvers(), closed = Promise.withResolvers(), release = Promise.withResolvers(); + const records: EgressRecord[] = []; + const origin = Bun.serve({ hostname: "127.0.0.1", port: 0, async fetch() { entered.resolve(); await release.promise; return new Response("Ithaca"); } }); + const proxy = await startEgressProxy({ mode: "record", allow: [], deny: [], maxBytes: 8192, outwardHosts: [], observe: row => records.push(row) }); + const originalRequest = http.request; + let socket: Socket | undefined; + const requestSpy = spyOn(http, "request").mockImplementation(((...args: Parameters) => { + const request = Reflect.apply(originalRequest, http, args); + if (args[0] instanceof URL && args[0].port === String(origin.port)) request.once("socket", value => { socket = value; value.once("close", closed.resolve); }); + return request; + }) as typeof http.request); + const pending = get(proxy.socketPath, origin.url.href).catch(() => 0); + try { + await entered.promise; + proxy.stop(); await closed.promise; + expect(socket?.destroyed, "CANCELLATION_DESTROYS_ONLY_ITS_OWN_IN_FLIGHT_SOCKET").toBe(true); + expect(records).toHaveLength(1); + expect(records[0]).toMatchObject({ outcome: "cancelled", reason: "turn_cancelled", dispatched: true }); + } finally { release.resolve(); proxy.stop(); await pending; requestSpy.mockRestore(); origin.stop(true); } +}); + +test("a stale pooled upstream socket cannot turn the next same-origin operation into 502", async () => { + const { createServer } = await import("node:net"); + const agent = new http.Agent({ keepAlive: true, maxSockets: 1 }); + const free = Promise.withResolvers(), finSent = Promise.withResolvers(); + const peers = new Set(); + let firstPeer: Socket | undefined; + const origin = createServer(socket => { + peers.add(socket); socket.on("error", () => {}); socket.once("close", () => peers.delete(socket)); + socket.on("data", () => { + firstPeer ??= socket; + socket.write("HTTP/1.1 200 OK\r\nContent-Length: 6\r\n\r\nIthaca"); + }); + }); + await new Promise(resolve => origin.listen(0, "127.0.0.1", resolve)); + const port = (origin.address() as { port: number }).port; + const target = `http://127.0.0.1:${port}/`; + agent.once("free", socket => { + // Retain the writable half until the test delivers the real FIN event. + // This pins the scheduling gap between pooling and processing origin close. + socket.allowHalfOpen = true; free.resolve(socket); + }); + const records: EgressRecord[] = []; + const proxy = await startEgressProxy({ mode: "record", allow: [], deny: [], maxBytes: 8192, outwardHosts: [], observe: row => records.push(row) }); + const original = http.request; + let firstSocket: Socket | undefined, secondSocket: Socket | undefined, pooled = false, reused = false; + const assigned = Promise.withResolvers(), flushed = Promise.withResolvers(); + const requestSpy = spyOn(http, "request").mockImplementation(((...args: Parameters) => { + if (args[0] instanceof URL && args[0].port === String(port)) { + const options = args[1] as http.RequestOptions; + // Install a controlled global-pool equivalent only when the production + // request has not explicitly opted out. Preserve an explicit agent:false. + const chosen = options.agent === undefined ? agent : options.agent; + pooled = chosen === agent; + const request = original(args[0], { ...options, agent: chosen, + headers: pooled ? { ...options.headers, connection: "keep-alive" } : options.headers }, args[2] as (response: http.IncomingMessage) => void); + request.once("socket", socket => { + if (!firstSocket) firstSocket = socket; + else { secondSocket = socket; reused = request.reusedSocket; request.once("finish", flushed.resolve); assigned.resolve(); } + }); + return request; + } + return Reflect.apply(original, http, args); + }) as typeof http.request); + let second: Promise | undefined, restoreEnd: (() => void) | undefined; + try { + expect(await get(proxy.socketPath, `${target}first`)).toBe(200); + let deliverEnd: (() => void) | undefined; + if (pooled) { + const socket = await free.promise, ended = Promise.withResolvers(); + const descriptor = Object.getOwnPropertyDescriptor(socket, "emit"), emit = socket.emit; + restoreEnd = () => { if (descriptor) Object.defineProperty(socket, "emit", descriptor); else delete (socket as Partial).emit; }; + socket.emit = function(event: string | symbol, ...args: unknown[]) { + if (event === "end") { deliverEnd = () => { Reflect.apply(emit, socket, [event, ...args]); }; ended.resolve(); return true; } + return Reflect.apply(emit, socket, [event, ...args]); + }; + firstPeer!.end(finSent.resolve); await finSent.promise; await ended.promise; + } else if (!firstPeer!.destroyed) { + firstPeer!.end(finSent.resolve); await finSent.promise; + } + second = get(proxy.socketPath, `${target}peer`); + await assigned.promise; + if (pooled) { + expect(secondSocket === firstSocket, "STALE_PROBE_REUSES_EXACT_REAL_SOCKET").toBe(true); + expect(reused).toBe(true); + await flushed.promise; restoreEnd!(); deliverEnd!(); + } + expect(await second, "STALE_UPSTREAM_SOCKET_NEVER_BREAKS_NEXT_OPERATION").toBe(200); + expect(secondSocket === firstSocket, "INDEPENDENT_OPERATIONS_HAVE_DISTINCT_UPSTREAM_SOCKETS").toBe(false); + expect(reused).toBe(false); + } finally { + restoreEnd?.(); proxy.stop(); agent.destroy(); + await second?.catch(() => {}); requestSpy.mockRestore(); + for (const socket of peers) socket.destroy(); + await new Promise(resolve => origin.close(() => resolve())); + } +}); diff --git a/packages/ui-sdk/tests/inference-relay.test.ts b/packages/ui-sdk/tests/inference-relay.test.ts index 7ac8a0d16d..f59835bbe1 100644 --- a/packages/ui-sdk/tests/inference-relay.test.ts +++ b/packages/ui-sdk/tests/inference-relay.test.ts @@ -77,7 +77,7 @@ describe("inference relay", () => { for (const badHeader of [false, true]) { invalid = badHeader; const response = await send(r.socketPath, "POST", "/v1/messages", {}, "{}"); - expect(response.status).toBe(503); + expect(response.status).toBe(502); expect(response.body).not.toContain(KEY); expect(response.body).toContain("Inference credentials unavailable"); } diff --git a/packages/ui-sdk/tests/provider-relay-files.test.ts b/packages/ui-sdk/tests/provider-relay-files.test.ts index c5b61712f9..cf0599fdd0 100644 --- a/packages/ui-sdk/tests/provider-relay-files.test.ts +++ b/packages/ui-sdk/tests/provider-relay-files.test.ts @@ -6,7 +6,7 @@ * handle and a blocked budget are refused before contact; files a turn leaves * behind are deleted when its relay stops. */ -import { afterAll, beforeAll, beforeEach, describe, expect, test } from "bun:test"; +import { afterAll, beforeAll, beforeEach, describe, expect, test, spyOn } from "bun:test"; import { request as httpRequest } from "node:http"; import { startProviderRelay, type ProviderRelay, type ProviderRelayOptions, type ProviderRelayReceipt, type ProviderRelayRefusal } from "../src/server/provider-relay.js"; @@ -17,6 +17,7 @@ const seen: Seen[] = []; /** Where the fictional provider says the bytes go; a test may point it elsewhere. */ let uploadUrl: () => string; let fileCounter = 0; +let deleteHandler:((request:Request)=>Response|Promise)|undefined; beforeAll(() => { upstream = Bun.serve({ hostname: "127.0.0.1", port: 0, async fetch(request) { @@ -31,7 +32,7 @@ beforeAll(() => { } const handle = /^\/v1beta\/(files\/[a-z0-9-]+)$/.exec(url.pathname)?.[1]; if (handle && request.method === "GET") return Response.json({ name: handle, state: "ACTIVE" }); - if (handle && request.method === "DELETE") return Response.json({}); + if (handle && request.method === "DELETE") return deleteHandler?.(request) ?? Response.json({}); if (url.pathname.endsWith(":generateContent")) { return Response.json({ candidates: [{ content: { parts: [{ text: "00:10 The fleet leaves Troy." }] } }], usageMetadata: { promptTokenCount: 300, candidatesTokenCount: 12 } }); @@ -42,6 +43,7 @@ beforeAll(() => { afterAll(() => upstream.stop(true)); beforeEach(() => { seen.length = 0; + deleteHandler=undefined; uploadUrl = () => `${upstream.url.origin}/upload/v1beta/files?upload_id=ithaca-session&upload_protocol=resumable`; }); @@ -203,3 +205,32 @@ describe("the Files lifecycle a relayed brain video watch needs", () => { expect(receipts.at(-1), "STOP_CLEANUP_RECORDED").toMatchObject({ operation: "files", outcome: "completed", status: 200 }); }); }); + +for(const unavailable of [false,true])test(`review14: Files cleanup retains ${unavailable?'unavailable':'safety'} without a dispatch receipt`,async()=>{ + const {startEgressProxy}=await import('../src/server/egress-proxy');let current=true; + const proxy=await startEgressProxy({mode:'record',allow:[],deny:[],maxBytes:65536,outwardHosts:[],observe(){},admissionSafety:{read:()=>({evidenceRevision:'1',trustRevision:'1',authorityEpoch:'1',scope:'ithaca',policyHash:null,restricted:false,recordingAvailable:unavailable?current:true,authorityCurrent:unavailable?true:current}),subscribe:()=>()=>{}}}); + const all:ProviderRelayReceipt[]=[];const {relay,start,upload}=open({egress:proxy,observe:receipt=>all.push(receipt)}); + try{const started=await start();await upload(String(started.headers['x-goog-upload-url']));seen.length=0;all.length=0;current=false;await relay.stop();expect(seen).toEqual([]);expect(all,'REFUSED_CLEANUP_HAS_TYPED_STATUS_AND_NEVER_DISPATCHED').toMatchObject([{operation:'files',outcome:'cancelled',status:0}]);}finally{await relay.stop();proxy.stop();} +}); + +for(const allowlist of [false,true])test(`review15: Files cleanup policy ${allowlist?'omission':'denial'} is 403`,async()=>{ + const {startEgressProxy}=await import('../src/server/egress-proxy');const deny:string[]=[],allow=['127.0.0.1'];const records:import('../src/server/egress-proxy').EgressRecord[]=[];const proxy=await startEgressProxy({mode:allowlist?'allowlist':'record',allow,deny,maxBytes:65536,outwardHosts:[],observe:r=>records.push(r)});const all:ProviderRelayReceipt[]=[];const {relay,start,upload}=open({egress:proxy,observe:receipt=>all.push(receipt)}); + try{const started=await start();await upload(String(started.headers['x-goog-upload-url']));seen.length=0;all.length=0;if(allowlist)allow.length=0;else deny.push('127.0.0.1');await relay.stop();expect(seen).toEqual([]);expect(all,'POLICY_REFUSAL_NEVER_LOOKS_UNAVAILABLE').toMatchObject([{operation:'files',outcome:'cancelled',status:0}]);expect(records.at(-1)).toMatchObject({outcome:'denied',reason:'destination_not_allowed'});}finally{await relay.stop();proxy.stop();} +}); + +for(const during of [false,true])test(`review17: cleanup cancellation ${during?'during fetch':'from dispatch observer'} never escapes the operation`,async()=>{ + const {startEgressProxy}=await import('../src/server/egress-proxy');const root=new AbortController();const proxy=await startEgressProxy({mode:'record',allow:[],deny:[],maxBytes:65536,outwardHosts:[],signal:root.signal,observe(){}});let armed=false,entered!:()=>void,release!:()=>void;const reached=new Promise(r=>{entered=r;}),held=new Promise(r=>{release=r;});let sentSignal:AbortSignal|undefined;const original=globalThis.fetch;const fetchSpy=spyOn(globalThis,'fetch').mockImplementation(Object.assign((...args:Parameters)=>{if(args[1]?.method==='DELETE')sentSignal=args[1].signal??undefined;return original(...args);},{preconnect:original.preconnect}));const all:ProviderRelayReceipt[]=[];const {relay,start,upload}=open({egress:proxy,observe:r=>all.push(r),preparing:()=>{if(armed&&!during)root.abort();}}); + try{const started=await start();await upload(String(started.headers['x-goog-upload-url']));seen.length=0;all.length=0;armed=true;if(during)deleteHandler=async()=>{entered();await held;return Response.json({});};const pending=relay.stop();if(during){await reached;root.abort();expect(sentSignal?.aborted,'CLEANUP_FETCH_USES_OPERATION_CANCELLATION').toBe(true);}await pending;expect(seen.filter(r=>r.method==='DELETE'),'CANCELLED_OBSERVER_NEVER_DISPATCHES_DELETE').toHaveLength(during?1:0);expect(all.at(-1)).toMatchObject({outcome:'cancelled',status:0});}finally{release();await relay.stop();fetchSpy.mockRestore();deleteHandler=undefined;proxy.stop();} +}); + +for(const cleanup of [false,true])for(const unavailable of [false,true])test(`review19: final fence after observer (cleanup ${cleanup}, unavailable ${unavailable})`,async()=>{ + const {startEgressProxy}=await import('../src/server/egress-proxy');let current=true,armed=false;const rows:import('../src/server/egress-proxy').EgressRecord[]=[]; + const proxy=await startEgressProxy({mode:'record',allow:[],deny:[],maxBytes:65536,outwardHosts:[],observe:r=>rows.push(r),admissionSafety:{read:()=>({evidenceRevision:'1',trustRevision:'1',authorityEpoch:'1',scope:'ithaca',policyHash:null,restricted:false,recordingAvailable:unavailable?current:true,authorityCurrent:unavailable?true:current}),subscribe:()=>()=>{}}}); + const receipts:ProviderRelayReceipt[]=[];const {relay,start,upload,generate}=open({egress:proxy,observe:r=>receipts.push(r),preparing:()=>{if(armed)current=false;}}); + try{const started=await start();const uploaded=await upload(String(started.headers['x-goog-upload-url']));expect(uploaded.status).toBe(200);seen.length=0;receipts.length=0;armed=true;if(cleanup)await relay.stop();else{const uri=JSON.parse(uploaded.body).file.uri;expect((await generate(uri)).status).toBe(unavailable?503:403);}expect(seen,'OBSERVER_REVOCATION_CANNOT_SEND_CREDENTIALS').toEqual([]);expect(receipts.at(-1)).toMatchObject({outcome:'cancelled',status:0});expect(rows.at(-1)).toMatchObject({outcome:'denied',failureReason:unavailable?'unavailable':'safety_changed'});}finally{await relay.stop();proxy.stop();} +}); + +test('review19: cleanup response headers cannot escape shared byte ceiling',async()=>{ + const {startEgressProxy}=await import('../src/server/egress-proxy');const rows:import('../src/server/egress-proxy').EgressRecord[]=[];const proxy=await startEgressProxy({mode:'record',allow:[],deny:[],maxBytes:65536,outwardHosts:[],observe:r=>rows.push(r)});const {relay,start,upload,receipts}=open({egress:proxy}); + try{const started=await start();await upload(String(started.headers['x-goog-upload-url']));deleteHandler=()=>new Response(null,{status:204,headers:{'x-ithaca-receipt':'x'.repeat(8192)}});const competing=proxy.inference('POST',new URL(upstream.url),new AbortController().signal);expect(await competing.admit()).toBe(true);expect(competing.charge(proxy.remainingBytes()-4096).ok).toBe(true);expect(competing.dispatch(()=>{}).ok).toBe(true);competing.finish('completed');await relay.stop();expect(receipts.at(-1),'CLEANUP_RESPONSE_HEADERS_ARE_METERED').toMatchObject({outcome:'cancelled',status:204});expect(rows.at(-1)).toMatchObject({outcome:'denied',reason:'max_bytes_per_turn',failureReason:'budget'});}finally{await relay.stop();proxy.stop();} +}); diff --git a/packages/ui-sdk/tests/relay-failure-causes.test.ts b/packages/ui-sdk/tests/relay-failure-causes.test.ts new file mode 100644 index 0000000000..cc186a2846 --- /dev/null +++ b/packages/ui-sdk/tests/relay-failure-causes.test.ts @@ -0,0 +1,200 @@ +/** Controlled failures at the lowest fetch boundary; real Unix relay requests stay offline. */ +import { expect,spyOn,test } from 'bun:test'; +import { getEventListeners } from 'node:events'; +import {createServer} from 'node:net'; +import { request,type IncomingHttpHeaders } from 'node:http'; +import { startEgressProxy,type EgressRecord } from '../src/server/egress-proxy'; +import { startInferenceRelay,type InferenceRelayEvent } from '../src/server/inference-relay'; +import { startProviderRelay,type ProviderRelayRefusal,type ProviderRelayReceipt } from '../src/server/provider-relay'; +const origin='http://127.0.0.1:43107'; +const causes=['upstream','cancelled','safety_changed','policy_denied','unavailable','budget'] as const; +const paths=['credentials','credentials return','inference fetch','inference stream','provider fetch','Files response','provider stream','cleanup'] as const; +function send(socketPath:string,path:string,body:string,headers:Record,onData:()=>void=()=>{}) { + return new Promise<{status:number;interrupted:boolean;headers:IncomingHttpHeaders;body:string}>((resolve,reject)=>{ + const req=request({socketPath,path,method:'POST',headers:{'content-type':'application/json',...headers}},res=>{ + const chunks:Buffer[]=[];const done=(interrupted:boolean)=>resolve({status:res.statusCode!,interrupted,headers:res.headers,body:Buffer.concat(chunks).toString()});res.on('data',chunk=>{chunks.push(chunk);onData();});res.once('end',()=>done(false));res.once('aborted',()=>done(true));res.once('error',()=>done(true)); + });req.once('error',reject);req.end(body); + }); +} +for(const path of paths)for(const cause of causes)test(`failure cause: ${cause} × ${path}`,async()=>{ + const root=new AbortController();let authority=true,recording=true,armed=path!=='cleanup',recovering=false;let release!:()=>void; + const gate=new Promise(r=>{release=r;});const audits:EgressRecord[]=[],receipts:ProviderRelayReceipt[]=[],inference:InferenceRelayEvent[]=[],refusals:ProviderRelayRefusal[]=[]; + const proxy=await startEgressProxy({mode:'record',allow:[],deny:[],maxBytes:65536,outwardHosts:[],signal:root.signal,observe:r=>audits.push(r),admissionSafety:{read:()=>({evidenceRevision:'1',trustRevision:'1',authorityEpoch:'1',scope:'ithaca',policyHash:null,restricted:false,recordingAvailable:recording,authorityCurrent:authority}),subscribe:()=>()=>{}}}); + const operations:Array<{op:ReturnType;signal:AbortSignal;owned:Function[]}>=[]; + const capture=(kind:'inference'|'relayed',method:string,target:URL,signal:AbortSignal)=>{const before=getEventListeners(signal,'abort');const op=proxy[kind](method,target,signal);const owned=getEventListeners(signal,'abort').filter(f=>!before.includes(f));expect(owned).toHaveLength(1);operations.push({op,signal,owned});return op;}; + const egress={...proxy,inference:(method:string,target:URL,signal:AbortSignal)=>capture('inference',method,target,signal),relayed:(method:string,target:URL,signal:AbortSignal)=>capture('relayed',method,target,signal)}; + const trigger=()=>{const op=operations.at(-1)!.op;if(cause==='cancelled')root.abort();else if(cause==='policy_denied')op.finish('denied','destination_not_allowed');else if(cause==='budget')op.charge(proxy.remainingBytes()+1);else if(cause==='safety_changed'){authority=false;op.charge(0);}else if(cause==='unavailable'){recording=false;op.charge(0);}}; + const failureBody=()=>{let first=true;const streaming=path.endsWith('stream');return new ReadableStream({async pull(controller){if(streaming&&first){first=false;controller.enqueue(new TextEncoder().encode('Ithaca '.repeat(16)));return;}if(streaming)await gate;trigger();controller.error(new Error('Odysseus upstream interrupted'));}},{highWaterMark:0});}; + const original=globalThis.fetch; + const fetchSpy=spyOn(globalThis,'fetch').mockImplementation(Object.assign(async(input:Parameters[0],init?:RequestInit)=>{ + const url=new URL(input instanceof Request?input.url:String(input)); + if(recovering)return Response.json({}); + if(path==='cleanup'&&!armed){if(!url.search)return Response.json({},{headers:{'x-goog-upload-url':`${origin}/upload/v1beta/files?upload_id=ithaca&upload_protocol=resumable`}});return Response.json({file:{name:'files/ithaca',uri:`${origin}/v1beta/files/ithaca`,mimeType:'video/mp4',state:'ACTIVE'}},{headers:{'x-goog-upload-status':'final'}});} + expect(url.origin).toBe(origin);expect(init?.signal).toBeInstanceOf(AbortSignal); + if(path.endsWith('stream')||path==='Files response')return new Response(failureBody(),{headers:{'content-type':'application/octet-stream'}}); + trigger();throw new Error('Odysseus upstream unavailable'); + },{preconnect:original.preconnect})); + const isInference=path.startsWith('inference')||path.startsWith('credentials'); + const relay=isInference?startInferenceRelay({upstream:origin,routes:['/v1/messages'],egress,credentials:async()=>{if(path.startsWith('credentials')){trigger();if(path==='credentials')throw new Error('Odysseus credential resolver unavailable');}return {'x-api-key':'odysseus-key'};},observe:r=>inference.push(r)}):startProviderRelay({origins:new Map([['ANTHROPIC_API_KEY',[origin]],['GEMINI_API_KEY',[origin]]]),credential:()=> 'odysseus-key',get egress(){return path==='cleanup'&&!armed?undefined:egress;},observe:r=>receipts.push(r),refused:r=>refusals.push(r)}); + const gemini={'x-brain-provider':'gemini','x-brain-provider-key':'GEMINI_API_KEY','x-brain-provider-origin':origin}; + try{ + let result:{status:number;interrupted:boolean;body:string}|undefined; + if(path==='cleanup'){ + const started=await send(relay.socketPath,'/upload/v1beta/files',JSON.stringify({file:{mimeType:'video/mp4'}}),{...gemini,'x-goog-upload-protocol':'resumable','x-goog-upload-command':'start','x-goog-upload-header-content-length':'5','x-goog-upload-header-content-type':'video/mp4'}); + expect(started.status).toBe(200);const upload=new URL(String(started.headers['x-goog-upload-url'])); + expect((await send(relay.socketPath,upload.pathname+upload.search,'troy!',{...gemini,'x-goog-upload-command':'upload, finalize','x-goog-upload-offset':'0'})).status).toBe(200); + receipts.length=0;armed=true;await relay.stop(); + }else{ + const files=path==='Files response';const headers:Record=isInference?{}:files?{...gemini,'x-goog-upload-protocol':'resumable','x-goog-upload-command':'start','x-goog-upload-header-content-length':'5','x-goog-upload-header-content-type':'video/mp4'}:{'x-brain-provider':'anthropic','x-brain-provider-key':'ANTHROPIC_API_KEY','x-brain-provider-origin':origin}; + result=await send(relay.socketPath,files?'/upload/v1beta/files':'/v1/messages',JSON.stringify({model:'odysseus-model',messages:[]}),headers,release); + } + const streaming=path.endsWith('stream'),typed=cause!=='upstream',status=cause==='cancelled'?499:cause==='unavailable'?503:typed?403:502; + if(result){expect(result.status,'FAILURE_SITE_CAUSE_DETERMINES_STATUS').toBe(streaming?200:status);if(streaming)expect(result.interrupted).toBe(true);} + if(!isInference){ + if(!streaming&&path!=='cleanup'){ + const expected=cause==='cancelled'?'cancelled':cause==='upstream'?'upstream_unreachable':'egress_refused'; + expect(refusals.at(-1),'CALLER_REFUSAL_CALLBACK_PRESERVES_REASON').toMatchObject({reason:expected,status}); + const wireReason=cause==='policy_denied'?'not_allowlisted':cause==='budget'?'byte_cap':cause==='unavailable'?'egress_unavailable':cause==='safety_changed'?'safety_changed':expected; + expect(JSON.parse(result!.body).error.reason,'CALLER_ERROR_BODY_PRESERVES_REASON').toBe(wireReason); + }else expect(refusals,'NO_NEW_ERROR_ENVELOPE_AFTER_STREAM_OR_INTERNAL_CLEANUP').toEqual([]); + } + if(isInference&&!streaming){ + const detail=cause==='cancelled'?'Inference request cancelled':cause==='safety_changed'||cause==='policy_denied'||cause==='unavailable'?'Inference network admission refused':cause==='budget'?'Inference egress limit exceeded':path==='credentials'?'Inference credentials unavailable':'Inference upstream unreachable'; + expect(JSON.parse(result!.body).error).toMatchObject({type:'brain_inference_refused',message:detail}); + expect(JSON.parse(result!.body).error.reason).toBeUndefined(); + expect(inference.at(-1)).toMatchObject({outcome:'refused',status,reason:detail}); + if(typed)expect(inference.at(-1)?.denialReason,'TYPED_CAUSE_STAYS_HOST_ONLY').toBe(cause==='cancelled'?'turn_cancelled':cause==='budget'?'max_bytes_per_turn':cause==='unavailable'?'egress_unavailable':cause==='policy_denied'?'destination_not_allowed':'safety_changed'); + } + const outcome=typed?'cancelled':'failed'; + // HTTP contract: docs/integration-contract/http.md:1412-1413 — status is upstream evidence, never the local refusal. + if(!isInference)expect(receipts.at(-1),'FINISH_ABORT_CANNOT_RECLASSIFY_THE_PROVIDER_RECEIPT').toMatchObject({outcome,status:streaming||path==='Files response'?200:0}); + else expect(inference.at(-1)).toMatchObject({outcome:streaming?'forwarded':'refused',status:streaming?200:status}); + expect(audits.at(-1)?.dispatched,'FETCH_START_IS_THE_DISPATCH_FACT').toBe(!path.startsWith('credentials')||path==='credentials return'&&cause==='upstream'); + expect(audits.at(-1),'TERMINAL_AUDIT_PRESERVES_THE_ACTUAL_CAUSE').toMatchObject({outcome:cause==='upstream'?'failed':cause==='cancelled'?'cancelled':'denied',failureReason:typed?cause:'unavailable'}); + if(cause==='upstream'){ + expect(root.signal.aborted,'ONE_TRANSPORT_FAILURE_NEVER_ABORTS_THE_TURN').toBe(false);recovering=true; + const recovery=startInferenceRelay({upstream:origin,routes:['/v1/messages'],egress,credentials:{'x-api-key':'odysseus-key'}}); + try{expect((await send(recovery.socketPath,'/v1/messages','{}',{})).status,'ANOTHER_OPERATION_IN_THE_SAME_TURN_STAYS_USABLE').toBe(200);}finally{await recovery.stop();} + } + for(const {signal,owned} of operations)expect(getEventListeners(signal,'abort').filter(f=>owned.includes(f)),'TERMINAL_OPERATION_RELEASES_CALLER_LISTENERS').toHaveLength(0); + }finally{release();await relay.stop();proxy.stop();fetchSpy.mockRestore();} +}); + +for(const kind of ['inference','relayed','managedReference'] as const)for(const terminal of ['admit','charge','commit','finish','caller abort','turn abort'])test(`listener owner: ${terminal} × ${kind}`,async()=>{ + const caller=new AbortController(),root=new AbortController();let current=true;const rows:EgressRecord[]=[];const proxy=await startEgressProxy({mode:'record',allow:[],deny:terminal==='admit'?['ithaca.example.org','github.com']:[],maxBytes:8,outwardHosts:[],signal:root.signal,observe:r=>rows.push(r),admissionSafety:{read:()=>({evidenceRevision:'1',trustRevision:'1',authorityEpoch:'1',scope:'ithaca',policyHash:null,restricted:false,recordingAvailable:true,authorityCurrent:current}),subscribe:()=>()=>{}}}); + try{const op=kind==='managedReference'?proxy.managedReference(new URL('https://github.com/'),caller.signal):proxy[kind]('GET',new URL('http://ithaca.example.org/'),caller.signal);expect(getEventListeners(caller.signal,'abort')).toHaveLength(1);const admitted=await op.admit();if(terminal==='admit')expect(admitted).toBe(false);else{expect(admitted).toBe(true);if(terminal==='charge')op.charge(9);else if(terminal==='commit'){current=false;op.dispatch(()=>{});}else if(terminal==='finish'){op.dispatch(()=>{});op.finish('completed');}else if(terminal==='caller abort')caller.abort();else root.abort();}expect(rows).toHaveLength(1);expect(getEventListeners(caller.signal,'abort'),'ALL_TERMINAL_TRANSITIONS_RELEASE_THE_CALLER').toHaveLength(0);}finally{caller.abort();proxy.stop();} +}); + +for(const kind of ['inference','relayed','managedReference'] as const)test(`review19: commit observer cannot bypass final fence (${kind})`,async()=>{ + let current=true;const rows:EgressRecord[]=[];const proxy=await startEgressProxy({mode:'record',allow:[],deny:[],maxBytes:65536,outwardHosts:[],observe:r=>rows.push(r),preparing:()=>{current=false;},admissionSafety:{read:()=>({evidenceRevision:'1',trustRevision:'1',authorityEpoch:'1',scope:'ithaca',policyHash:null,restricted:false,recordingAvailable:true,authorityCurrent:current}),subscribe:()=>()=>{}}}); + try{const op=kind==='managedReference'?proxy.managedReference(new URL('https://github.com/'),new AbortController().signal):proxy[kind]('POST',new URL(origin),new AbortController().signal);expect(await op.admit()).toBe(true);expect(op.dispatch(()=>{}),'COMMIT_OBSERVER_MUST_NOT_BYPASS_FINAL_FENCE').toEqual({ok:false,reason:'safety_changed'});expect(rows.at(-1)).toMatchObject({outcome:'denied',failureReason:'safety_changed'});}finally{proxy.stop();} +}); + +for(const files of [false,true])for(const unavailable of [false,true])test(`review20: EOF fences held bytes and handles (Files ${files}, unavailable ${unavailable})`,async()=>{ + let current=true,reads=0;let release!:()=>void;const gate=new Promise(r=>{release=r;});const receipts:ProviderRelayReceipt[]=[],rows:EgressRecord[]=[];const proxy=await startEgressProxy({mode:'record',allow:[],deny:[],maxBytes:65536,outwardHosts:[],observe:r=>rows.push(r),admissionSafety:{read:()=>({evidenceRevision:'1',trustRevision:'1',authorityEpoch:'1',scope:'ithaca',policyHash:null,restricted:false,recordingAvailable:unavailable?current:true,authorityCurrent:unavailable?true:current}),subscribe:()=>()=>{}}}); + const original=globalThis.fetch;const fetchSpy=spyOn(globalThis,'fetch').mockImplementation(Object.assign(async()=>new Response(new ReadableStream({async pull(controller){if(reads++===0)controller.enqueue(new TextEncoder().encode(files?'{}':'Ithaca '.repeat(16)+'Troy'));else{if(!files)await gate;current=false;controller.close();}}},{highWaterMark:0}),{headers:files?{'x-goog-upload-url':`${origin}/upload/v1beta/files?upload_id=ithaca`}:{}}),{preconnect:original.preconnect})); + const relay=startProviderRelay({origins:new Map([['ANTHROPIC_API_KEY',[origin]],['GEMINI_API_KEY',[origin]]]),credential:()=> 'odysseus-key',egress:proxy,observe:r=>receipts.push(r)}); + try{const answer=await send(relay.socketPath,files?'/upload/v1beta/files':'/v1/messages','{}',files?{'x-brain-provider':'gemini','x-brain-provider-key':'GEMINI_API_KEY','x-brain-provider-origin':origin,'x-goog-upload-protocol':'resumable','x-goog-upload-command':'start','x-goog-upload-header-content-length':'5','x-goog-upload-header-content-type':'video/mp4'}:{'x-brain-provider':'anthropic','x-brain-provider-key':'ANTHROPIC_API_KEY','x-brain-provider-origin':origin},release); + expect(answer.status,'EOF_MUST_REVALIDATE_BEFORE_RELEASING_HELD_BYTES').toBe(files?(unavailable?503:403):200);if(files)expect(answer.headers['x-goog-upload-url'],'REVOKED_RESPONSE_CANNOT_REGISTER_UPLOAD').toBeUndefined();else{expect(answer.interrupted).toBe(true);expect(answer.body,'SCRUBBER_TAIL_NEVER_ESCAPES_REVOKED_AUTHORITY').toBe(('Ithaca '.repeat(16)+'Troy').slice(0,-11));} + expect(receipts.at(-1)).toMatchObject({outcome:'cancelled',status:200});expect(rows.at(-1)).toMatchObject({outcome:'denied',failureReason:unavailable?'unavailable':'safety_changed'}); + }finally{release();await relay.stop();proxy.stop();fetchSpy.mockRestore();} +}); + +for(const provider of [false,true])for(const scenario of ['redirect','EOF authority','EOF recording'] as const)test(`review21: ${scenario} × ${provider?'provider':'inference'}`,async()=>{ + let current=true,reads=0,release!:()=>void;const gate=new Promise(r=>{release=r;});const rows:EgressRecord[]=[];const proxy=await startEgressProxy({mode:'record',allow:[],deny:[],maxBytes:65536,outwardHosts:[],observe:r=>rows.push(r),admissionSafety:{read:()=>({evidenceRevision:'1',trustRevision:'1',authorityEpoch:'1',scope:'ithaca',policyHash:null,restricted:false,recordingAvailable:scenario==='EOF recording'?current:true,authorityCurrent:scenario==='EOF recording'?true:current}),subscribe:()=>()=>{}}}); + const original=globalThis.fetch;const fetchSpy=spyOn(globalThis,'fetch').mockImplementation(Object.assign(async()=>scenario==='redirect'?new Response(null,{status:302,headers:{location:'http://ithaca.example.org/','x-ithaca-receipt':'x'.repeat(8192)}}):new Response(new ReadableStream({async pull(controller){if(reads++===0)controller.enqueue(new TextEncoder().encode('Ithaca '.repeat(16)));else{await gate;current=false;controller.close();}}},{highWaterMark:0})),{preconnect:original.preconnect})); + const relay=provider?startProviderRelay({origins:new Map([['ANTHROPIC_API_KEY',[origin]]]),credential:()=> 'odysseus-key',egress:proxy}):startInferenceRelay({upstream:origin,routes:['/v1/messages'],credentials:{'x-api-key':'odysseus-key'},egress:proxy}); + try{const answer=await send(relay.socketPath,'/v1/messages','{}',provider?{'x-brain-provider':'anthropic','x-brain-provider-key':'ANTHROPIC_API_KEY','x-brain-provider-origin':origin}:{},release);if(scenario==='redirect'){expect(answer.status).toBe(502);expect(rows.at(-1)!.bytes,'REDIRECT_HEADERS_DEBIT_SHARED_ALLOWANCE').toBeGreaterThan(8192);}else{expect(answer.interrupted,'EOF_CANNOT_COMPLETE_REVOKED_ADMISSION').toBe(true);expect(rows.at(-1)).toMatchObject({failureReason:scenario==='EOF recording'?'unavailable':'safety_changed',outcome:'denied'});}}finally{release();await relay.stop();proxy.stop();fetchSpy.mockRestore();} +}); + +test('review21: overflowing Files chunk consumes remaining allowance before size refusal',async()=>{ + const rows:EgressRecord[]=[];const proxy=await startEgressProxy({mode:'record',allow:[],deny:[],maxBytes:65536,outwardHosts:[],observe:r=>rows.push(r)});const original=globalThis.fetch;const fetchSpy=spyOn(globalThis,'fetch').mockImplementation(Object.assign(async()=>new Response(new Uint8Array(1024*1024+1)),{preconnect:original.preconnect}));const relay=startProviderRelay({origins:new Map([['GEMINI_API_KEY',[origin]]]),credential:()=> 'odysseus-key',egress:proxy}); + try{const answer=await send(relay.socketPath,'/upload/v1beta/files','{}',{'x-brain-provider':'gemini','x-brain-provider-key':'GEMINI_API_KEY','x-brain-provider-origin':origin,'x-goog-upload-protocol':'resumable','x-goog-upload-command':'start','x-goog-upload-header-content-length':'5','x-goog-upload-header-content-type':'video/mp4'});expect(answer.status,'RECEIVED_BYTES_PRECEDE_FILES_SIZE_BRANCH').toBe(403);expect(proxy.remainingBytes(),'RECEIVED_OVERFLOW_CANNOT_RESTORE_ALLOWANCE').toBe(0);expect(rows.at(-1)).toMatchObject({failureReason:'budget',outcome:'denied'});}finally{await relay.stop();proxy.stop();fetchSpy.mockRestore();} +}); + +for(const kind of ['inference','relayed','managedReference'] as const)for(const stage of ['prepare','fence','started failure'])test(`review22: dispatch fact ${stage} × ${kind}`,async()=>{ + let current=true,sends=0,grants=0;const rows:EgressRecord[]=[];const proxy=await startEgressProxy({mode:'record',allow:[],deny:[],maxBytes:65536,outwardHosts:[],observe:r=>rows.push(r),preparing:()=>{if(stage==='prepare')current=false;},committed:()=>{grants++;},admissionSafety:{read:()=>({evidenceRevision:'1',trustRevision:'1',authorityEpoch:'1',scope:'ithaca',policyHash:null,restricted:false,recordingAvailable:true,authorityCurrent:current}),subscribe:()=>()=>{}}}); + try{const op=kind==='managedReference'?proxy.managedReference(new URL('https://github.com/'),new AbortController().signal):proxy[kind]('POST',new URL(origin),new AbortController().signal);expect(await op.admit()).toBe(true);expect(op.charge(8).ok).toBe(true);expect(op.prepare().ok).toBe(true);if(stage==='fence')current=false;const result=op.dispatch(()=>{sends++;op.finish('failed','upstream_unreachable');});expect(result.ok).toBe(stage==='started failure');expect(sends).toBe(stage==='started failure'?1:0);expect(grants,'ONLY_STARTED_SENDS_PUBLISH_CONTACT_PERMISSION').toBe(sends);expect(rows.at(-1),'DISPATCH_AUDIT_MATCHES_THE_ACTUAL_SEND').toMatchObject({dispatched:stage==='started failure',outcome:stage==='started failure'?'failed':'denied'});}finally{proxy.stop();} +}); + +for(const provider of [false,true])for(const eof of [false,true])for(const unavailable of [false,true])test(`review22: queued delivery revocation (provider ${provider}, EOF ${eof}, unavailable ${unavailable})`,async()=>{ + let current=true,queued=false,armed=false,reads=0,release!:()=>void;const gate=new Promise(r=>{release=r;});const rows:EgressRecord[]=[]; + const proxy=await startEgressProxy({mode:'record',allow:[],deny:[],maxBytes:65536,outwardHosts:[],observe:r=>rows.push(r),admissionSafety:{read:()=>{const snapshot={evidenceRevision:'1',trustRevision:'1',authorityEpoch:'1',scope:'ithaca',policyHash:null,restricted:false,recordingAvailable:unavailable?current:true,authorityCurrent:unavailable?true:current};if(armed&&!queued){queued=true;queueMicrotask(()=>{current=false;});}return snapshot;},subscribe:()=>()=>{}}}); + const original=globalThis.fetch;const fetchSpy=spyOn(globalThis,'fetch').mockImplementation(Object.assign(async()=>new Response(new ReadableStream({async pull(controller){if(reads++===0){controller.enqueue(new TextEncoder().encode('Ithaca '.repeat(16)));return;}await gate;armed=true;if(eof)controller.close();else controller.enqueue(new TextEncoder().encode('Troy'));}},{highWaterMark:0})),{preconnect:original.preconnect})); + const relay=provider?startProviderRelay({origins:new Map([['ANTHROPIC_API_KEY',[origin]]]),credential:()=> 'odysseus-key',egress:proxy}):startInferenceRelay({upstream:origin,routes:['/v1/messages'],credentials:{'x-api-key':'odysseus-key'},egress:proxy}); + try{const answer=await send(relay.socketPath,'/v1/messages','{}',provider?{'x-brain-provider':'anthropic','x-brain-provider-key':'ANTHROPIC_API_KEY','x-brain-provider-origin':origin}:{},release);expect(queued).toBe(true);expect(answer.interrupted,'NO_AWAIT_BETWEEN_FINAL_FENCE_AND_CLIENT_DELIVERY').toBe(true);expect(answer.body).not.toContain('Troy');expect(answer.body.length).toBe(provider?101:112);expect(rows.at(-1)).toMatchObject({outcome:'denied',failureReason:unavailable?'unavailable':'safety_changed'});}finally{release();await relay.stop();proxy.stop();fetchSpy.mockRestore();} +}); + +for(const provider of [false,true])test(`review24: received normal ${provider?'provider':'inference'} response exhausts allowance`,async()=>{ + const rows:EgressRecord[]=[];const proxy=await startEgressProxy({mode:'record',allow:[],deny:[],maxBytes:16384,outwardHosts:[],observe:r=>rows.push(r)});const original=globalThis.fetch;const fetchSpy=spyOn(globalThis,'fetch').mockImplementation(Object.assign(async()=>new Response(new Uint8Array(65536)),{preconnect:original.preconnect}));const relay=provider?startProviderRelay({origins:new Map([['ANTHROPIC_API_KEY',[origin]]]),credential:()=> 'odysseus-key',egress:proxy}):startInferenceRelay({upstream:origin,routes:['/v1/messages'],credentials:{'x-api-key':'odysseus-key'},egress:proxy}); + try{const result=await send(relay.socketPath,'/v1/messages','{}',provider?{'x-brain-provider':'anthropic','x-brain-provider-key':'ANTHROPIC_API_KEY','x-brain-provider-origin':origin}:{}).catch(()=>({interrupted:true}));expect(result.interrupted).toBe(true);expect(proxy.remainingBytes(),'RECEIVED_RELAY_BYTES_CANNOT_LEAVE_LATER_ALLOWANCE').toBe(0);expect(rows.at(-1)).toMatchObject({outcome:'denied',failureReason:'budget',bytes:16384});}finally{await relay.stop();proxy.stop();fetchSpy.mockRestore();} +}); + +for(const provider of [false,true])test(`review24: received ${provider?'provider':'inference'} upload exhausts allowance`,async()=>{ + let hits=0;const rows:EgressRecord[]=[];const proxy=await startEgressProxy({mode:'record',allow:[],deny:[],maxBytes:16384,outwardHosts:[],observe:r=>rows.push(r)});const original=globalThis.fetch;const fetchSpy=spyOn(globalThis,'fetch').mockImplementation(Object.assign(async()=>{hits++;return Response.json({});},{preconnect:original.preconnect}));const relay=provider?startProviderRelay({origins:new Map([['ANTHROPIC_API_KEY',[origin]]]),credential:()=> 'odysseus-key',egress:proxy}):startInferenceRelay({upstream:origin,routes:['/v1/messages'],credentials:{'x-api-key':'odysseus-key'},egress:proxy}); + try{const answer=await send(relay.socketPath,'/v1/messages',JSON.stringify({model:'odysseus-model',messages:[{role:'user',content:'Ithaca '.repeat(16384)}]}),provider?{'x-brain-provider':'anthropic','x-brain-provider-key':'ANTHROPIC_API_KEY','x-brain-provider-origin':origin}:{});expect(answer.status).toBe(403);expect(proxy.remainingBytes(),'RECEIVED_UPLOAD_BYTES_CANNOT_LEAVE_LATER_ALLOWANCE').toBe(0);expect(hits).toBe(0);expect(rows.at(-1)).toMatchObject({outcome:'denied',failureReason:'budget',bytes:16384,dispatched:false});}finally{await relay.stop();proxy.stop();fetchSpy.mockRestore();} +}); + +for(const path of ['inference','provider','cleanup'] as const)for(const synchronous of [false,true])test(`review25: ${synchronous?'sync throw':'promise rejection'} × ${path}`,async()=>{ + const rows:EgressRecord[]=[],receipts:ProviderRelayReceipt[]=[];let armed=path!=='cleanup';const proxy=await startEgressProxy({mode:'record',allow:[],deny:[],maxBytes:65536,outwardHosts:[],observe:r=>rows.push(r)});const original=globalThis.fetch; + const fetchSpy=spyOn(globalThis,'fetch').mockImplementation(Object.assign((input:Parameters[0])=>{ + const url=new URL(String(input));if(!armed)return Promise.resolve(!url.search?Response.json({},{headers:{'x-goog-upload-url':`${origin}/upload/v1beta/files?upload_id=ithaca`}}):Response.json({file:{name:'files/ithaca',uri:`${origin}/v1beta/files/ithaca`,mimeType:'video/mp4',state:'ACTIVE'}},{headers:{'x-goog-upload-status':'final'}})); + if(synchronous)throw new Error('Odysseus transport unavailable');return Promise.reject(new Error('Odysseus transport unavailable')); + },{preconnect:original.preconnect})); + const relay=path==='inference'?startInferenceRelay({upstream:origin,routes:['/v1/messages'],credentials:{'x-api-key':'odysseus-key'},egress:proxy}):startProviderRelay({origins:new Map([['ANTHROPIC_API_KEY',[origin]],['GEMINI_API_KEY',[origin]]]),credential:()=> 'odysseus-key',get egress(){return armed?proxy:undefined;},observe:r=>receipts.push(r)}); + try{if(path==='cleanup'){const headers={'x-brain-provider':'gemini','x-brain-provider-key':'GEMINI_API_KEY','x-brain-provider-origin':origin};const started=await send(relay.socketPath,'/upload/v1beta/files','{}',{...headers,'x-goog-upload-protocol':'resumable','x-goog-upload-command':'start','x-goog-upload-header-content-length':'5','x-goog-upload-header-content-type':'video/mp4'});const url=new URL(String(started.headers['x-goog-upload-url']));expect((await send(relay.socketPath,url.pathname+url.search,'troy!',{...headers,'x-goog-upload-command':'upload, finalize','x-goog-upload-offset':'0'})).status).toBe(200);receipts.length=0;armed=true;await relay.stop();} + else{const answer=await send(relay.socketPath,'/v1/messages','{}',path==='provider'?{'x-brain-provider':'anthropic','x-brain-provider-key':'ANTHROPIC_API_KEY','x-brain-provider-origin':origin}:{});expect(answer.status,'SYNC_AND_ASYNC_UPSTREAM_FAILURE_ARE_502').toBe(502);} + if(path!=='inference')expect(receipts.at(-1),'UPSTREAM_FAILURE_IS_FAILED_WITH_NO_OBSERVED_HTTP_STATUS').toMatchObject({outcome:'failed',status:0});expect(rows.at(-1),'ATTEMPTED_HANDOFF_RETAINS_UPSTREAM_FAILURE_EVIDENCE').toMatchObject({outcome:'failed',reason:'upstream_unreachable',dispatched:!synchronous}); + }finally{await relay.stop();proxy.stop();fetchSpy.mockRestore();} +}); + + +for(const path of ['proxy','proxy request','inference','provider','Files','cleanup'] as const)test(`review26: oversized Connection-nominated response header × ${path}`,async()=>{ + let contacts=0;const server=createServer(socket=>{contacts++;socket.on('error',()=>{});socket.once('data',()=>socket.end('HTTP/1.1 200 OK\r\nConnection: x-ithaca-hidden, close\r\nX-Ithaca-Hidden: '+'x'.repeat(path==='proxy request'?0:8192)+'\r\nContent-Length: 2\r\n\r\n{}'));});await new Promise(r=>server.listen(0,'127.0.0.1',r));const upstream=`http://127.0.0.1:${(server.address() as {port:number}).port}`;const rows:EgressRecord[]=[],receipts:ProviderRelayReceipt[]=[];let armed=path!=='cleanup';const proxy=await startEgressProxy({mode:'record',allow:[],deny:[],maxBytes:4096,outwardHosts:[],observe:r=>rows.push(r)});const original=globalThis.fetch; + const fetchSpy=path==='cleanup'?spyOn(globalThis,'fetch').mockImplementation(Object.assign((input:Parameters[0],init?:Parameters[1])=>{if(armed)return original(input,init);const url=new URL(String(input));return Promise.resolve(!url.search?Response.json({},{headers:{'x-goog-upload-url':`${upstream}/upload/v1beta/files?upload_id=ithaca`}}):Response.json({file:{name:'files/ithaca',uri:`${upstream}/v1beta/files/ithaca`,mimeType:'video/mp4',state:'ACTIVE'}},{headers:{'x-goog-upload-status':'final'}}));},{preconnect:original.preconnect})):undefined; + const relay=path.startsWith('proxy')?undefined:path==='inference'?startInferenceRelay({upstream,routes:['/v1/messages'],credentials:{'x-api-key':'odysseus-key'},egress:proxy}):startProviderRelay({origins:new Map([['ANTHROPIC_API_KEY',[upstream]],['GEMINI_API_KEY',[upstream]]]),credential:()=> 'odysseus-key',get egress(){return armed?proxy:undefined;},observe:r=>receipts.push(r)}); + const gemini={'x-brain-provider':'gemini','x-brain-provider-key':'GEMINI_API_KEY','x-brain-provider-origin':upstream},startHeaders={...gemini,'x-goog-upload-protocol':'resumable','x-goog-upload-command':'start','x-goog-upload-header-content-length':'5','x-goog-upload-header-content-type':'video/mp4'}; + try{if(path==='cleanup'){const started=await send(relay!.socketPath,'/upload/v1beta/files','{}',startHeaders);const url=new URL(String(started.headers['x-goog-upload-url']));expect((await send(relay!.socketPath,url.pathname+url.search,'troy!',{...gemini,'x-goog-upload-command':'upload, finalize','x-goog-upload-offset':'0'})).status).toBe(200);receipts.length=0;armed=true;await relay!.stop();}else{const result=await send(relay?.socketPath??proxy.socketPath,path.startsWith('proxy')?upstream+'/':path==='Files'?'/upload/v1beta/files':'/v1/messages','{}',path==='provider'?{'x-brain-provider':'anthropic','x-brain-provider-key':'ANTHROPIC_API_KEY','x-brain-provider-origin':upstream}:path==='Files'?startHeaders:path==='proxy request'?{'connection':'x-ithaca-inbound','x-ithaca-inbound':'x'.repeat(8192)}:{});expect(result.status,'RECEIVED_HOP_BY_HOP_BYTES_PRECEDE_FORWARD_FILTER').toBe(403);} + expect(proxy.remainingBytes(),'RECEIVED_HOP_BY_HOP_HEADERS_EXHAUST_ALLOWANCE').toBe(0);expect(rows.at(-1)).toMatchObject({outcome:'denied',reason:'max_bytes_per_turn',bytes:4096,dispatched:path!=='proxy request'});if(path==='proxy request')expect(contacts,'FILTERED_REQUEST_HEADERS_ARE_METERED_BEFORE_CONTACT').toBe(0);if(path==='provider'||path==='Files'||path==='cleanup')expect(receipts.at(-1)).toMatchObject({outcome:'cancelled',status:200}); + }finally{await relay?.stop();proxy.stop();fetchSpy?.mockRestore();await new Promise(r=>server.close(()=>r()));} +}); + +for(const provider of [false,true])test(`review29: stripped worker headers exhaust ${provider?'provider':'inference'} allowance before filtering`,async()=>{ + let contacts=0;const rows:EgressRecord[]=[];const proxy=await startEgressProxy({mode:'record',allow:[],deny:[],maxBytes:4096,outwardHosts:[],observe:r=>rows.push(r)});const original=globalThis.fetch;const spy=spyOn(globalThis,'fetch').mockImplementation(Object.assign(async()=>{contacts++;return Response.json({});},{preconnect:original.preconnect})); + const relay=provider?startProviderRelay({origins:new Map([['ANTHROPIC_API_KEY',[origin]]]),credential:()=> 'odysseus-key',egress:proxy}):startInferenceRelay({upstream:origin,routes:['/v1/messages'],credentials:{'x-api-key':'odysseus-key'},egress:proxy}); + try{const headers={authorization:'x'.repeat(8192),...(provider?{'x-brain-provider':'anthropic','x-brain-provider-key':'ANTHROPIC_API_KEY','x-brain-provider-origin':origin}:{})};const answer=await send(relay.socketPath,'/v1/messages','{}',headers);expect(answer.status,'STRIPPED_RECEIVED_HEADER_BYTES_STILL_DEBIT_ALLOWANCE').toBe(403);expect(proxy.remainingBytes()).toBe(0);expect(contacts).toBe(0);expect(rows.at(-1)).toMatchObject({reason:'max_bytes_per_turn',dispatched:false});}finally{await relay.stop();proxy.stop();spy.mockRestore();} +}); + +for(const provider of [false,true])test(`review29: injected credential head growth remains charged in ${provider?'provider':'inference'}`,async()=>{ + let contacts=0;const proxy=await startEgressProxy({mode:'record',allow:[],deny:[],maxBytes:4096,outwardHosts:[],observe(){}});const original=globalThis.fetch;const spy=spyOn(globalThis,'fetch').mockImplementation(Object.assign(async()=>{contacts++;return Response.json({});},{preconnect:original.preconnect}));const secret='x'.repeat(8192); + const relay=provider?startProviderRelay({origins:new Map([['ANTHROPIC_API_KEY',[origin]]]),credential:()=>secret,egress:proxy}):startInferenceRelay({upstream:origin,routes:['/v1/messages'],credentials:{'x-api-key':secret},egress:proxy}); + try{const answer=await send(relay.socketPath,'/v1/messages','{}',provider?{'x-brain-provider':'anthropic','x-brain-provider-key':'ANTHROPIC_API_KEY','x-brain-provider-origin':origin}:{});expect(answer.status,'UPSTREAM_HEAD_GROWTH_CANNOT_ESCAPE_RECEIVED_HEAD_BOUND').toBe(403);expect(contacts).toBe(0);}finally{await relay.stop();proxy.stop();spy.mockRestore();} +}); + +for(const status of [100,103])test(`review30: proxy meters informational ${status} head before final response`,async()=>{ + const rows:EgressRecord[]=[];const server=createServer(socket=>{socket.on('error',()=>{});socket.once('data',()=>socket.end(`HTTP/1.1 ${status} ${status===100?'Continue':'Early Hints'}\r\nX-Ithaca-Interim: ${'x'.repeat(8192)}\r\n\r\nHTTP/1.1 200 OK\r\nContent-Length: 2\r\nConnection: close\r\n\r\n{}`));});await new Promise(r=>server.listen(0,'127.0.0.1',r));const upstream=`http://127.0.0.1:${(server.address() as {port:number}).port}`;const proxy=await startEgressProxy({mode:'record',allow:[],deny:[],maxBytes:4096,outwardHosts:[],observe:r=>rows.push(r)}); + try{const answer=await send(proxy.socketPath,upstream+'/','{}',{});expect(answer.status,'INFORMATIONAL_HEAD_DEBITS_BEFORE_FINAL_RESPONSE').toBe(403);expect(proxy.remainingBytes()).toBe(0);expect(rows.at(-1)).toMatchObject({outcome:'denied',reason:'max_bytes_per_turn',bytes:4096,dispatched:true});}finally{proxy.stop();await new Promise(r=>server.close(()=>r()));} +}); + +for(const provider of [false,true])test(`review30: old-shape ${provider?'provider':'web inference'} egress route remains usable without remainingBytes`,async()=>{ + const proxy=await startEgressProxy({mode:'record',allow:[],deny:[],maxBytes:65536,outwardHosts:[],observe(){}});const route:import('../src/tool-contracts/web').WebModelEgress={dir:proxy.dir,inference:proxy.inference};const original=globalThis.fetch;const spy=spyOn(globalThis,'fetch').mockImplementation(Object.assign(async()=>Response.json({}),{preconnect:original.preconnect}));const relay=provider?startProviderRelay({origins:new Map([['ANTHROPIC_API_KEY',[origin]]]),credential:()=> 'odysseus-key',egress:{relayed:proxy.relayed}}):startInferenceRelay({upstream:origin,routes:['/v1/messages'],credentials:{'x-api-key':'odysseus-key'},egress:{inference:route.inference as typeof proxy.inference}}); + try{const answer=await send(relay.socketPath,'/v1/messages','{}',provider?{'x-brain-provider':'anthropic','x-brain-provider-key':'ANTHROPIC_API_KEY','x-brain-provider-origin':origin}:{});expect(answer.status,'OLD_ROUTE_WITHOUT_READER_RETAINS_RUNTIME_COMPATIBILITY').toBe(200);}finally{await relay.stop();proxy.stop();spy.mockRestore();} +}); + + +test('review30: legacy allowance is finite, cumulative and saturates received overflow',async()=>{ + const {relayAllowance,chargeReceivedBytes}=await import('../src/server/egress-accounting');const charged:number[]=[],terminal:string[]=[]; + const allowance=relayAllowance({charge:count=>{charged.push(count);return {ok:true};},finish:(_outcome,reason)=>{terminal.push(reason);}},undefined,10); + expect(chargeReceivedBytes(7,allowance)).toBeUndefined();expect(allowance.remaining()).toBe(3);expect(chargeReceivedBytes(7,allowance),'LEGACY_READER_FALLBACK_IS_A_FINITE_PER_REQUEST_LIMIT').toEqual({ok:false,reason:'budget'});expect(allowance.remaining()).toBe(0);expect(charged).toEqual([7,3,0]);expect(terminal).toEqual(['max_bytes_per_turn']); +}); + +for(const status of [100,103])test(`review30: bounded informational ${status} head adds its complete received cost`,async()=>{ + let calls=0;const rows:EgressRecord[]=[],interim=`HTTP/1.1 ${status} ${status===100?'Continue':'Early Hints'}\r\nX-Ithaca-Interim: Ithaca\r\n\r\n`;const final='HTTP/1.1 200 OK\r\nContent-Length: 2\r\nConnection: close\r\n\r\n{}';const server=createServer(socket=>{socket.on('error',()=>{});socket.once('data',()=>socket.end((calls++?interim:'')+final));});await new Promise(r=>server.listen(0,'127.0.0.1',r));const upstream=`http://127.0.0.1:${(server.address() as {port:number}).port}`;const proxy=await startEgressProxy({mode:'record',allow:[],deny:[],maxBytes:65536,outwardHosts:[],observe:r=>rows.push(r)}); + try{for(let i=0;i<2;i++)expect((await send(proxy.socketPath,upstream+'/','{}',{})).status).toBe(200);await proxy.settled();expect(rows).toHaveLength(2);expect(rows[1]!.bytes-rows[0]!.bytes,'INTERIM_AUDIT_COUNTS_RAW_HEAD_AND_FRAMING_ALLOWANCE').toBe(Buffer.byteLength(interim)+64);}finally{proxy.stop();await new Promise(r=>server.close(()=>r()));} +}); + + +for(const oversized of [false,true])test(`review30: unsupported 101 upgrade is metered before refusal (oversized ${oversized})`,async()=>{ + const rows:EgressRecord[]=[];const server=createServer(socket=>{socket.on('error',()=>{});socket.once('data',()=>socket.end(`HTTP/1.1 101 Switching Protocols\r\nConnection: Upgrade\r\nUpgrade: ithaca\r\nX-Ithaca-Interim: ${'x'.repeat(oversized?8192:8)}\r\n\r\n`));});await new Promise(r=>server.listen(0,'127.0.0.1',r));const upstream=`http://127.0.0.1:${(server.address() as {port:number}).port}`;const proxy=await startEgressProxy({mode:'record',allow:[],deny:[],maxBytes:4096,outwardHosts:[],observe:r=>rows.push(r)}); + try{const answer=await send(proxy.socketPath,upstream+'/','{}',{});expect(answer.status,'UPGRADE_HEAD_IS_METERED_WITHOUT_OPENING_A_TUNNEL').toBe(oversized?403:502);if(oversized){expect(proxy.remainingBytes()).toBe(0);expect(rows.at(-1)).toMatchObject({reason:'max_bytes_per_turn',bytes:4096});}else expect(rows.at(-1)).toMatchObject({outcome:'failed',reason:'upstream_unreachable'});}finally{proxy.stop();await new Promise(r=>server.close(()=>r()));} +}); diff --git a/packages/ui-sdk/tests/safety-admission-contract.test.ts b/packages/ui-sdk/tests/safety-admission-contract.test.ts new file mode 100644 index 0000000000..a2ea7a7559 --- /dev/null +++ b/packages/ui-sdk/tests/safety-admission-contract.test.ts @@ -0,0 +1,33 @@ +import { expect,test } from 'bun:test'; +import { safetyRecordSchema } from '../src/safety'; +const record={kind:'occurrence',id:'ithaca',sequence:'1',observedAt:1,turnId:'voyage',bindingId:'bound',occurrenceId:'ithaca',detailPruned:false,epochId:'epoch',detector:'proxy_input',source:'egress_connection',operationId:null,signalId:'signal',exposureId:'exposure',exposure:'finalized',summary:'Ithaca',provenance:{kind:'web_origin',origin:{scheme:'https',host:'ithaca.example.org',port:443},verifiedBy:'host_transport'}} as const; +test('review7: trusted wire admission requires complete immutable evidence',()=>{ + const trusted={trusted:true,ruleId:'ithaca',policyHash:'a'.repeat(64),trustRevision:'1',collectionRevision:'2'};expect(safetyRecordSchema.safeParse({...record,admission:trusted}).success).toBe(true); + for(const admission of [{...trusted,policyHash:null},{...trusted,ruleId:undefined},{...trusted,collectionRevision:undefined},{...trusted,trusted:false}])expect(safetyRecordSchema.safeParse({...record,admission}).success,'TRUSTED_WIRE_EVIDENCE_IS_COMPLETE_AND_DISCRIMINATED').toBe(false); + expect(safetyRecordSchema.safeParse({...record,admission:{trusted:false,policyHash:null,trustRevision:'1'}}).success).toBe(true);expect(safetyRecordSchema.safeParse(record).success).toBe(true); +}); + + +test('review9: version-one history retains arbitrary valid detector IDs without admissions',()=>{ + const prior={...record,detector:'prior_detector_v1'};expect(safetyRecordSchema.parse(prior),'OLDER_V1_DETECTOR_IDS_REMAIN_READABLE').toEqual(prior);expect(safetyRecordSchema.safeParse({...prior,detector:'invalid/id'}).success).toBe(false); +}); + +for(const method of ['GET','CONNECT'])for(const port of [0,1,65535,65536,-1,1.5,NaN])test(`review17: ${method} destination port ${port} shares wire validation`,async()=>{ + const {validatedEgressProvenance}=await import('../src/server/egress-proxy');const destination={method,protocol:'http:',host:'ithaca.example.org',port}; + if(port===1||port===65535)expect(()=>validatedEgressProvenance(destination)).not.toThrow();else expect(()=>validatedEgressProvenance(destination),'DESTINATION_AND_WIRE_PORT_BOUNDS_AGREE').toThrow(); +}); +for(const method of ['GET','CONNECT'])for(const host of ['a'.repeat(253),'a'.repeat(254),'λ'.repeat(126),'λ'.repeat(127)])test(`review17: ${method} hostname ${Buffer.byteLength(host)} bytes shares wire validation`,async()=>{ + const {validatedEgressProvenance}=await import('../src/server/egress-proxy');const destination={method,protocol:'http:',host,port:443}; + if(Buffer.byteLength(host)<=253)expect(()=>validatedEgressProvenance(destination)).not.toThrow();else expect(()=>validatedEgressProvenance(destination),'DESTINATION_AND_WIRE_HOST_BYTE_BOUNDS_AGREE').toThrow(); +}); + +test('review28: durable and wire admissions share verified provenance and bounded revisions',async()=>{ + const {OccurrenceSchema}=await import('../../ui-server/src/governance/occurrence'); + const admission={trusted:true,ruleId:'ithaca',policyHash:'a'.repeat(64),trustRevision:'1',collectionRevision:'2'}; + const verified={kind:'web_origin',origin:{scheme:'https',host:'ithaca.example.org',port:443},verifiedBy:'host_transport'}; + const durable={id:'ithaca',epochId:'epoch',operationId:null,signalId:'signal',exposureId:'exposure',detector:'proxy_input',exposure:'finalized',provenance:verified,admission}; + for(const schema of [OccurrenceSchema,safetyRecordSchema]){ + const base=schema===OccurrenceSchema?durable:{...record,provenance:verified,admission};expect(schema.safeParse(base).success).toBe(true); + for(const change of [{provenance:null},{detector:'tool_web_input'},{admission:{...admission,trustRevision:'18446744073709551616'}},{admission:{...admission,collectionRevision:'99999999999999999999'}}])expect(schema.safeParse({...base,...change}).success,'TRUSTED_ADMISSION_REQUIRES_VERIFIED_PROXY_AND_U64_REVISIONS').toBe(false); + } +}); diff --git a/packages/ui-server/migrations/095_trust_rule_instances.sql b/packages/ui-server/migrations/095_trust_rule_instances.sql new file mode 100644 index 0000000000..420bce345b --- /dev/null +++ b/packages/ui-server/migrations/095_trust_rule_instances.sql @@ -0,0 +1,7 @@ +-- Runtime source-grant lifetimes are projection metadata, never policy grants. +-- Existing streams do not survive migration/restart; seed current instances. +ALTER TABLE trust_settings_projection ADD COLUMN rule_instances TEXT NOT NULL DEFAULT '{}'; +UPDATE trust_settings_projection SET rule_instances = ( + SELECT coalesce(json_group_object(json_extract(value, '$.id'), trust_settings_projection.revision), '{}') + FROM json_each(trust_settings_projection.rules) +); diff --git a/packages/ui-server/src/app.ts b/packages/ui-server/src/app.ts index 0f47608805..3c9c7d769a 100644 --- a/packages/ui-server/src/app.ts +++ b/packages/ui-server/src/app.ts @@ -1,3 +1,5 @@ +import { CombinedSafetyReviews } from "./governance/combined-safety-reviews.js"; +import { createReferenceOwnerContinuity } from "./brain/reference-owner-resolution.js"; import { createTrustSettings } from "./brain/trust-settings.js"; import { createTrustSettingsRoutes } from "./routes/trust-settings.js"; import { createTrustGitHubIdentity } from "./brain/trust-github-identity.js"; @@ -438,6 +440,9 @@ export async function createApp(options: CreateAppOptions = {}): Promise { googleMasks.close(); if (ephemeralJournal) rmSync(journalRoot, { recursive: true, force: true }); throw error; }); const bootCleanup: (() => void | Promise)[] = [() => googleMasks.close()]; + const ownerContinuity = await createReferenceOwnerContinuity(config.brainPath, nativeReady) + .catch(error => { googleMasks.close(); throw error; }); + bootCleanup.push(() => ownerContinuity.close()); try { const nativeRecovery = await nativeLeases.recoverDeadOwners(); if (nativeRecovery.unknown.length || nativeRecovery.retainedUnverifiable) observability.logger("brain").emit({ severityText: "WARN", @@ -575,7 +580,7 @@ export async function createApp(options: CreateAppOptions = {}): Promise trustSettings.ownerPolicy(), brain: nativeReady.brainUuid, sources: referenceSources, pool: nativeManager, transport: referenceTransport }), log: brainLog }) : undefined; if (referenceWorktrees) { bootCleanup.push(() => referenceWorktrees.close()); @@ -782,7 +787,7 @@ export async function createApp(options: CreateAppOptions = {}): Promise journal.close()); // Startup recovery commits, or refuses boot, before any turn can run. await journal.ready; - const policyProposals = createPolicyProposals({ root: config.brainPath, db, writer, + const policyProposals = createPolicyProposals({ afterPublication: () => trustSettings.refreshLocked(), root: config.brainPath, db, writer, lock: { withLock: (key, fn, admission) => host.workerLock.withLock(key, fn, admission) }, observeUserPolicy: (turnId, write) => journal.observeUserPolicy(turnId, write), recordEvent: (review, turn) => activity.governanceWrites.record({ kind: "policy_change", actor: "user", turnId: turn.turnId, sessionId: turn.sessionId(), model: null, profile: null, @@ -1314,7 +1319,7 @@ export async function createApp(options: CreateAppOptions = {}): Promisehost.isPrincipalValid(principal))); - app.route("/api", createOwnerSafetyReviewRoutes(ownerSafetyReviews,auth.trustProxy)); + app.route("/api", createPolicyProposalRoutes(host)); app.route("/api", createAgentPolicyRoutes(host, () => activity.runtime.snapshot().workerHost?.limits ?? null)); app.route("/api", createDraftRoutes(drafts)); @@ -1360,7 +1365,7 @@ export async function createApp(options: CreateAppOptions = {}): Promise unavailableBackends.some(failure => failure.backendId === "pi"); app.route("/api", createPiAuthRoutes({ agent: config.agent, excluded: piExcluded })); app.route("/api", createWebSearchRoutes({ agent: config.agent, excluded: piExcluded })); - const trustSettings = createTrustSettings({ root: config.brainPath, db, writer, lock: workerLock, + const trustSettings = createTrustSettings({ root: config.brainPath, ownerRoot: ownerContinuity.root, db, writer, lock: workerLock, originEnforcement: true, github: createTrustGitHubIdentity({ root: config.brainPath, access: githubReferenceAccess }), authority: id => { if (authMode !== "password") return null; @@ -1368,6 +1373,11 @@ export async function createApp(options: CreateAppOptions = {}): Promise journal.observeSettingsPolicy(id, publish) }); + ownerSafetyReviews.enableFutureRules(trustSettings); + app.route("/api", createOwnerSafetyReviewRoutes(ownerSafetyReviews,auth.trustProxy,new CombinedSafetyReviews(db,ownerSafetyReviews,trustSettings))); + await trustSettings.snapshot(); + host.originTrust = trustSettings.live; + host.safetyTrust = trustSettings.live; app.route("/api", createTrustSettingsRoutes({ settings: trustSettings, trustProxy: auth.trustProxy })); const apifyOwner = (id: string) => { const principal = resolvePrincipal(db, id); return !!principal && ["owner", "ambient"].includes(principal.kind) && isUsablePrincipal(principal, Date.now()); }; // Settings edits (#3163) go through the existing policy proposals, the only policy writer, in a user journal window. @@ -1561,6 +1571,7 @@ export async function createApp(options: CreateAppOptions = {}): Promise writer.close()); await attempt(() => db.close()); + await attempt(() => ownerContinuity.close()); await attempt(() => googleMasks.close()); clearTimeout(grace); if (failures.length === 1) throw failures[0]; diff --git a/packages/ui-server/src/brain/github-reference-wire.ts b/packages/ui-server/src/brain/github-reference-wire.ts index e8d31b5064..dcdffa506d 100644 --- a/packages/ui-server/src/brain/github-reference-wire.ts +++ b/packages/ui-server/src/brain/github-reference-wire.ts @@ -6,13 +6,14 @@ import { Agent, request as httpsRequest } from "node:https"; import { connect, type Socket } from "node:net"; import { Duplex, Transform } from "node:stream"; import { connect as connectTls } from "node:tls"; -import { egressAddressRefusal } from "@schlessera/brain-ui-sdk/internal"; +import { egressAddressRefusal, egressChargeRefusal, type EgressChargeFailure } from "@schlessera/brain-ui-sdk/internal"; import { githubReferenceOwner, githubReferenceRepository, type GitHubReferenceRepository } from "./github-reference-identity.js"; import { ReferenceTransportError } from "./reference-transport.js"; import type { prepareTurnEgress } from "./turn-egress.js"; type Egress = Pick>, "managedReference" | "remainingBytes">; type Recipient = "git" | "metadata"; +const chargeError = (failure:EgressChargeFailure) => new ReferenceTransportError(failure.reason === "budget" ? "capacity" : failure.reason === "safety_changed" || failure.reason === "policy_denied" ? "denied" : "unavailable",egressChargeRefusal(failure,"Reference").message); const MAX_METADATA_BYTES = 65536; /** One acquisition owns this budget across metadata, discovery, auth retries and Git fetch. */ @@ -91,8 +92,10 @@ export async function createGitHubReferenceWire(options: ({ repository: unknown; const operationStopped = () => { if (operation.outcome() === "completed") return; upstream?.destroy(); client.destroy(); - if (operation.outcome() === "cancelled" && !controller.signal.aborted) - fail(new ReferenceTransportError("unavailable", "reference turn ended during acquisition")); + if (operation.outcome() === "cancelled" && !controller.signal.aborted) { + const decision = operation.failure(); + if (decision) fail(chargeError(decision)); + } }; operation.signal.addEventListener("abort", operationStopped, { once: true }); const finish = (outcome: "completed" | "failed" | "cancelled") => { @@ -100,15 +103,17 @@ export async function createGitHubReferenceWire(options: ({ repository: unknown; }; client.once("close", () => { upstream?.destroy(); finish(controller.signal.aborted ? "cancelled" : "completed"); }); try { - if (!await operation.admit()) throw new ReferenceTransportError("denied", "reference recipient was not admitted"); + if (!await operation.admit()) throw chargeError(operation.failure() ?? {ok:false,reason:"unavailable"}); const addresses = options.lookup ? await options.lookup(target.hostname, { all: true, verbatim: true }) : await lookupHost(target.hostname, { all: true, verbatim: true }); if (!addresses.length || addresses.some(value => egressAddressRefusal(value.address))) throw new ReferenceTransportError("denied", "reference recipient did not resolve to public addresses"); check(recipient, capability.credentialed); - if (!operation.commit() || client.destroyed) throw new ReferenceTransportError("denied", "reference authority changed before connection"); - upstream = track((options.connect ?? connect)({ host: addresses[0]!.address, port: 443 })); - const heldUpstream = upstream; upstreams.add(heldUpstream); + const beforeConnection = operation.prepare(); if (!beforeConnection.ok) throw chargeError(beforeConnection); + if (client.destroyed) throw new ReferenceTransportError("unavailable", "reference client closed before connection"); + const dispatched=operation.dispatch(()=>{upstream=track((options.connect??connect)({host:addresses[0]!.address,port:443,signal:AbortSignal.any([controller.signal,operation.signal])}));}); + if(!dispatched.ok)throw chargeError(dispatched); + const heldUpstream = upstream!; upstreams.add(heldUpstream); heldUpstream.once("close", () => { upstreams.delete(heldUpstream); outgoingWireBytes += heldUpstream.bytesWritten; incomingWireBytes += heldUpstream.bytesRead; }); @@ -126,35 +131,35 @@ export async function createGitHubReferenceWire(options: ({ repository: unknown; if (controller.signal.aborted) cancel(); }); check(recipient, capability.credentialed); - if (!operation.commit() || client.destroyed) throw new ReferenceTransportError("denied", "reference authority changed after connection"); + const afterConnection = operation.charge(0); if (!afterConnection.ok) throw chargeError(afterConnection); + if (client.destroyed) throw new ReferenceTransportError("unavailable", "reference client closed after connection"); const meter = (incoming: boolean) => new Transform({ transform(chunk: Buffer, _encoding, done) { if (incoming) observedIncomingBytes += chunk.length; try { check(recipient, capability.credentialed); - if (!operation.commit()) throw new ReferenceTransportError("denied", "reference authority changed during transfer"); const remaining = Math.min(options.maxBytes - chargedBytes, options.egress.remainingBytes()); if (chunk.length > remaining) { // Charge received wire up to the ceiling, then close every channel. // A rejected outbound chunk never reaches the upstream. - if (incoming && remaining > 0) { operation.charge(remaining); chargedBytes += remaining; } + if (incoming && remaining > 0) { const charged = operation.charge(remaining); if (!charged.ok) throw chargeError(charged); chargedBytes += remaining; } operation.finish("denied", "max_reference_wire_bytes"); throw new ReferenceTransportError("capacity", "reference acquisition exhausted its network byte allowance"); } - if (!operation.charge(chunk.length)) throw new ReferenceTransportError("capacity", "reference turn exhausted its network byte allowance"); + const charged = operation.charge(chunk.length); if (!charged.ok) throw chargeError(charged); chargedBytes += chunk.length; done(null, chunk); } catch (error) { fail(error as Error); done(error as Error); } } }); const outgoing = meter(false), incoming = meter(true); outgoing.on("error", () => { upstream?.destroy(); client.destroy(); }); incoming.on("error", () => { upstream?.destroy(); client.destroy(); }); - upstream.once("error", () => { finish("failed"); client.destroy(); }); - upstream.once("close", () => { + heldUpstream.once("error", () => { finish("failed"); client.destroy(); }); + heldUpstream.once("close", () => { finish(controller.signal.aborted ? "cancelled" : upstream?.readableEnded ? "completed" : "failed"); if (!upstream?.readableEnded) client.destroy(); }); client.write("HTTP/1.1 200 Connection Established\r\n\r\n"); if (head.length) outgoing.write(head); - client.pipe(outgoing).pipe(upstream); upstream.pipe(incoming).pipe(client); + client.pipe(outgoing).pipe(heldUpstream); heldUpstream.pipe(incoming).pipe(client); client.resume(); } catch (error) { finish(controller.signal.aborted ? "cancelled" : "failed"); diff --git a/packages/ui-server/src/brain/origin-trust.ts b/packages/ui-server/src/brain/origin-trust.ts new file mode 100644 index 0000000000..dfe79b1441 --- /dev/null +++ b/packages/ui-server/src/brain/origin-trust.ts @@ -0,0 +1,28 @@ +/** Host-only prospective origin decisions. Repository proof belongs to its own collector. */ +import { matchTrustRules, type TrustMatch, type TrustProvenance, type TrustRule } from "@schlessera/brain-common/internal/governance-policy"; +import type { LiveTrustRevision } from "../governance/effective-safety.js"; + +export interface OriginTrust extends LiveTrustRevision { + refresh?(signal?: AbortSignal): Promise; + read(): { revision: string; rules: TrustRule[]; policyHash: string | null; readonly ruleInstances: Readonly> }; +} +export interface OriginDestination { host: string; port: number; method: string; protocol?: string; managedReference?: boolean } +function originProvenance(destination: OriginDestination): TrustProvenance | null { + // Selectors encode IPv6 with URL brackets; transport identity is bare. + const host = destination.host.includes(":") && !destination.host.startsWith("[") ? `[${destination.host}]` : destination.host; + if (destination.managedReference && destination.protocol !== "https:") return null; + if (destination.method === "CONNECT" && !destination.managedReference) return { kind: "tunnel_authority", authority: { kind: "tunnel_authority", host, port: destination.port }, verifiedBy: "host_proxy" }; + if (destination.protocol === "http:" || destination.protocol === "https:") return { kind: "web_origin", origin: { kind: "web_origin", scheme: destination.protocol === "http:" ? "http" : "https", host, port: destination.port }, verifiedBy: "host_transport" }; + return null; +} +export function originTrustMatch(trust: OriginTrust | undefined, destination: OriginDestination, capability: TrustMatch["capability"], collectionRevision: string): TrustMatch | null { + return originTrustMatchSnapshot(trust?.read(), destination, capability, collectionRevision); +} +/** All admission evidence, including an unmatched verdict, uses this same snapshot. */ +export function originTrustMatchSnapshot(p: ReturnType | undefined, destination: OriginDestination, capability: TrustMatch["capability"], collectionRevision: string): TrustMatch | null { + if (!p) return null; + const provenance = originProvenance(destination); + if (!p.policyHash || !provenance) return null; + return matchTrustRules(p.rules, provenance, capability, { phase: "prospective_admission", trustRevision: p.revision, policyHash: p.policyHash, collectionRevision }, + value => value.kind === "web_origin" ? { kind: "host_transport" } : value.kind === "tunnel_authority" ? { kind: "host_proxy" } : { kind: "unknown" }); +} diff --git a/packages/ui-server/src/brain/policy-proposal.ts b/packages/ui-server/src/brain/policy-proposal.ts index c149d7a02f..861cacd525 100644 --- a/packages/ui-server/src/brain/policy-proposal.ts +++ b/packages/ui-server/src/brain/policy-proposal.ts @@ -106,6 +106,8 @@ export function createPolicyProposals(options: { recordEvent(review: PolicyChangeReview, turn: PolicyProposalTurn): unknown; /** Where a proposal's writes commit: the app's write worker (#2850). Absent: on `db`, at once. */ writer?: SqliteWriter; + /** Join the live trust-only projection while this publisher owns the brain lock. */ + afterPublication?(): Promise; /** Deterministic race/revalidation fixtures, never wired to a worker. */ beforeCommit?(): void; validate?: typeof parseGovernancePolicy; @@ -232,6 +234,7 @@ export function createPolicyProposals(options: { // Nothing was published and the observation, its hold and (on // unwinding) the lock are released: wait out the pause and retry. if (unpublished) throw new AuthorityHeld(); + await options.afterPublication?.(); review.state = "updated"; review.message = "Policy updated. Applies from the next turn."; await options.recordEvent(review, turn); } finally { diff --git a/packages/ui-server/src/brain/reference-owner-native-root.ts b/packages/ui-server/src/brain/reference-owner-native-root.ts new file mode 100644 index 0000000000..489cf4c760 --- /dev/null +++ b/packages/ui-server/src/brain/reference-owner-native-root.ts @@ -0,0 +1,30 @@ +/** Existing Linux/Btrfs native identity, read from the actual held descriptor. */ +import { constants, openSync, closeSync, fstatSync, lstatSync, realpathSync } from "node:fs"; +import * as kernel from "./reference-owner-root-kernel.js"; +interface ReferenceOwnerNativeIdentity { fsid: string; uuid: string } +export interface ReferenceOwnerRoot { path: string; device: number; inode: number; native: ReferenceOwnerNativeIdentity } +type ReferenceOwnerExpectedRoot = { fsid: string; brainUuid: string }; +const unavailable = () => ({ root: undefined, close() {} }); +/** Qualification is host configuration, never a model-selected identity. */ +export async function createReferenceOwnerContinuity(path: string, expected?: ReferenceOwnerExpectedRoot): Promise<{ root: Readonly | undefined; close(): void }> { + if (!expected || !/^[a-f0-9-]{36}$/u.test(expected.fsid) || !/^[a-f0-9]{32}$/u.test(expected.brainUuid)) return unavailable(); + let fd: number | undefined; + try { + const canonical = realpathSync(path); + fd = openSync(canonical, constants.O_RDONLY | constants.O_DIRECTORY | constants.O_NOFOLLOW); + const held = fstatSync(fd); + const unchanged = () => { + const named = lstatSync(canonical), current = fstatSync(fd!); + return realpathSync(path) === canonical && named.isDirectory() && named.dev === held.dev && named.ino === held.ino + && current.dev === held.dev && current.ino === held.ino; + }; + if (!unchanged()) throw Error("Changed policy root"); + // Open precedes the lazy native-library wait; only this descriptor is inspected. + const actual = await kernel.inspectPinnedReferenceRoot(fd); + if (!unchanged() || actual.fsid !== expected.fsid || actual.uuid !== expected.brainUuid || actual.readOnly + || actual.receivedUuid !== "0".repeat(32) || actual.devices !== 1) throw Error("Unqualified native policy root"); + const root = Object.freeze({ path: canonical, device: held.dev, inode: held.ino, + native: Object.freeze({ fsid: actual.fsid, uuid: actual.uuid }) }); + return { root, close() { if (fd !== undefined) { closeSync(fd); fd = undefined; } } }; + } catch { if (fd !== undefined) closeSync(fd); return unavailable(); } +} diff --git a/packages/ui-server/src/brain/reference-owner-resolution.ts b/packages/ui-server/src/brain/reference-owner-resolution.ts new file mode 100644 index 0000000000..6b032b96f0 --- /dev/null +++ b/packages/ui-server/src/brain/reference-owner-resolution.ts @@ -0,0 +1,94 @@ +import { lstatSync } from "node:fs"; +import { trustPolicyGeneration } from "./trust-policy-generation.js"; +/** Read-only owner qualification. This records historical evidence, never a source-trust admission. */ +import { createHash } from "node:crypto"; +import type { Database } from "bun:sqlite"; +import { z } from "zod"; +import { TrustedSourcesSchema, TrustSelectorSchema, type TrustSelector } from "@schlessera/brain-common/internal/governance-policy"; +import type { ReferenceIdentityObservation } from "./reference-acquisition.js"; + +const hash = (value: string | Uint8Array) => createHash("sha256").update(value).digest("hex"); +const digest = z.string().regex(/^[a-f0-9]{64}$/u); +const id = z.string().regex(/^[A-Za-z0-9_-]{1,128}$/u); +const providerId = z.string().regex(/^[1-9][0-9]{0,19}$/u); +const revision = z.string().regex(/^(0|[1-9][0-9]{0,19})$/u).refine(value => BigInt(value) <= 18446744073709551615n); +const identitySchema = z.strictObject({ selector: TrustSelectorSchema, ownerId: providerId, private: z.boolean().nullable() }); +const proofSchema = z.strictObject({ operationId: id, principal: z.string().min(1).max(128), brain: digest, + authority: z.string().min(1).max(4096), + policyRoot: z.strictObject({ fsid: z.string().uuid(), uuid: z.string().regex(/^[a-f0-9]{32}$/u) }), baseHash: digest.nullable(), expectedTrustRevision: revision, + publishedTrustRevision: revision, reviewedBytesHash: digest, githubIdentity: identitySchema }); + +export { createReferenceOwnerContinuity } from "./reference-owner-native-root.js"; +import type { ReferenceOwnerRoot } from "./reference-owner-native-root.js"; +export type { ReferenceOwnerRoot } from "./reference-owner-native-root.js"; + +export interface ReferenceOwnerPolicy { + rules: import("@schlessera/brain-common/internal/governance-policy").TrustRule[]; + revision: string; policyHash: string | null; error: string | null; generation: string; +} +const policySchema = z.strictObject({ rules: TrustedSourcesSchema, revision, policyHash: digest.nullable(), + error: z.string().nullable(), generation: z.string().min(1).max(4096) }); + +type GitHubSelector = Extract; +export interface ReferenceOwnerResolution { + version: 1; + operationId: string; + state: "available" | "unavailable"; + policyHash: string | null; + trustRevision: string | null; + policyError: string | null; + /** At most one repository and one owner rule can match a validated policy. */ + bindings: { ruleId: string; selector: GitHubSelector; approvedOwnerId: string; sameOwnerRenameRevalidated: boolean; + publicationOperationId: string; publicationProofHash: string }[]; +} + +/** + * Called only after the read's real transport observation and immutable blob + * have been checked. `root` is host configuration, never model input. A valid + * policy and its exact durable projection must agree; equal bytes cannot create + * approval. The publisher's retained boundary survives operation pruning. + */ +export function resolveReferenceOwners(db: Database, root: Readonly | undefined, observation: Readonly, policy?: ReferenceOwnerPolicy): ReferenceOwnerResolution { + const unavailable = (): ReferenceOwnerResolution => ({ version: 1, operationId: observation.operationId, + state: "unavailable", policyHash: null, trustRevision: null, policyError: null, bindings: [] }); + if (!root) return unavailable(); + try { + const brain = hash(root.path), selected = policySchema.parse(policy); + const named = lstatSync(root.path); + if (!named.isDirectory() || named.dev !== root.device || named.ino !== root.inode) return unavailable(); + if (trustPolicyGeneration(root.path) !== selected.generation) return unavailable(); + const { policyHash, rules } = selected; + const projection = db.query("SELECT revision,rules,policy_hash,error FROM trust_settings_projection WHERE brain_id=?").get(brain) as { + revision: string; rules: string; policy_hash: string | null; error: string | null; + } | null; + if (!projection || projection.revision !== selected.revision || !revision.safeParse(projection.revision).success + || JSON.stringify(TrustedSourcesSchema.parse(JSON.parse(projection.rules))) !== JSON.stringify(rules) + || selected.error !== null && projection.policy_hash !== policyHash) return unavailable(); + const bindings: ReferenceOwnerResolution["bindings"] = []; + for (const rule of rules) { + const selector = rule.selector; + if (selector.kind !== "github_repository" && selector.kind !== "github_owner") continue; + const current = observation.identity; + if (selector.owner !== current.owner || (selector.kind === "github_repository" ? selector.repositoryId !== current.repositoryId : selector.ownerId !== current.ownerId)) continue; + const row = db.query("SELECT selector,identity,proof FROM trust_settings_github_boundaries WHERE brain_id=? AND rule_id=?").get(brain, rule.id) as { + selector: string; identity: string; proof: string; + } | null; + if (!row || row.selector !== JSON.stringify(selector)) continue; + try { + const identity = identitySchema.parse(JSON.parse(row.identity)), proof = proofSchema.parse(JSON.parse(row.proof)); + if (JSON.stringify(identity.selector) !== JSON.stringify(selector) || JSON.stringify(proof.githubIdentity) !== JSON.stringify(identity) + || proof.brain !== brain || proof.policyRoot.fsid !== root.native.fsid || proof.policyRoot.uuid !== root.native.uuid || BigInt(proof.publishedTrustRevision) !== BigInt(proof.expectedTrustRevision) + 1n + || BigInt(proof.publishedTrustRevision) > BigInt(projection.revision) + || identity.ownerId !== current.ownerId + || (selector.kind === "github_owner" ? identity.private !== null || identity.ownerId !== selector.ownerId : typeof identity.private !== "boolean")) continue; + bindings.push({ ruleId: rule.id, selector, approvedOwnerId: identity.ownerId, + sameOwnerRenameRevalidated: selector.kind === "github_repository" && selector.repository !== current.repository, + publicationOperationId: proof.operationId, publicationProofHash: hash(row.proof) }); + } catch { /* Malformed or incomplete publication evidence qualifies no rule. */ } + } + // Detect descriptor/name/content changes while synchronous database reads ran. + if (trustPolicyGeneration(root.path) !== selected.generation) return unavailable(); + return { version: 1, operationId: observation.operationId, state: bindings.length ? "available" : "unavailable", + policyHash, trustRevision: projection.revision, policyError: selected.error, bindings }; + } catch { return unavailable(); } +} diff --git a/packages/ui-server/src/brain/reference-owner-root-kernel.ts b/packages/ui-server/src/brain/reference-owner-root-kernel.ts new file mode 100644 index 0000000000..29dad13a2e --- /dev/null +++ b/packages/ui-server/src/brain/reference-owner-root-kernel.ts @@ -0,0 +1,24 @@ +/** Same fixed kernel UAPI as the native manager and retained startup guard. */ +import { fstatSync } from "node:fs"; +async function load() { + if (process.platform !== "linux") throw Error("Native root identity unavailable"); + const { dlopen } = await import("bun:ffi"); + return dlopen("libc.so.6", { ioctl: { args: ["i32", "u64", "ptr"], returns: "i32" } }); +} +let pending: ReturnType | undefined; +export async function inspectPinnedReferenceRoot(fd: number) { + const selected = pending ??= load(); + let libc: Awaited; + try { libc = await selected; } catch (error) { if (pending === selected) pending = undefined; throw error; } + const held = fstatSync(fd, { bigint: true }); + if (!held.isDirectory() || held.ino !== 256n) throw Error("Policy root is not a native subvolume root"); + const subvolume = Buffer.alloc(504), filesystem = Buffer.alloc(1024); + if (libc.symbols.ioctl(fd, 0x81f8943c, subvolume) < 0 || libc.symbols.ioctl(fd, 0x8400941f, filesystem) < 0) + throw Error("Policy root kernel identity unavailable"); + const current = fstatSync(fd, { bigint: true }); + if (current.dev !== held.dev || current.ino !== held.ino) throw Error("Changed policy root descriptor"); + const hex = filesystem.subarray(16, 32).toString("hex"); + return { fsid: `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`, + uuid: subvolume.subarray(296, 312).toString("hex"), receivedUuid: subvolume.subarray(328, 344).toString("hex"), + readOnly: !!(subvolume.readBigUInt64LE(288) & 1n), devices: Number(filesystem.readBigUInt64LE(8)) }; +} diff --git a/packages/ui-server/src/brain/reference-read-writes.ts b/packages/ui-server/src/brain/reference-read-writes.ts index dcbde1daf3..2bc3dc4bee 100644 --- a/packages/ui-server/src/brain/reference-read-writes.ts +++ b/packages/ui-server/src/brain/reference-read-writes.ts @@ -1,4 +1,5 @@ /** Read evidence shares the reference writer FIFO; it never grants source trust. */ +import { resolveReferenceOwners, type ReferenceOwnerPolicy, type ReferenceOwnerRoot } from "./reference-owner-resolution.js"; import { referenceIdentityObservationMatches, type ReferenceIdentityObservation } from "./reference-acquisition.js"; import type { Database } from "bun:sqlite"; import { isLiveReferenceGrant } from "../db/reference-grants.js"; @@ -6,6 +7,8 @@ import { sourceAuthorityCurrent, type SourceAuthority } from "./reference-source interface ReferenceReadRecord { id: string; + ownerRoot?: ReferenceOwnerRoot; + ownerPolicy?: ReferenceOwnerPolicy; operationId: string; turnId: string; toolCallId: string; @@ -24,16 +27,19 @@ export function readWrites(db: Database) { const source = db.query("SELECT 1 FROM reference_sources WHERE root_id = ? AND validated_at > 0").get(rootId); if (!source || JSON.stringify(acquisition) !== record.acquisition || !sourceAuthorityCurrent(db, authority) || grantId !== null && !isLiveReferenceGrant(db, grantId, Date.now())) throw new Error("Reference read authority changed before recording"); - const evidence = JSON.parse(record.evidence) as { identityObservation?: ReferenceIdentityObservation }; + const evidence = JSON.parse(record.evidence) as { identityObservation?: ReferenceIdentityObservation; ownerResolution?: ReturnType }; const acquired = acquisition as Parameters[1]; if (!referenceIdentityObservationMatches(evidence.identityObservation, acquired, { operationId: record.operationId, brain: acquired.brain, principalId: record.principalId, turnId: record.turnId, rootId, })) throw new Error("Reference read transport identity changed before recording"); + // Resolve inside the acquired writer transaction, after queued waits. + // The result is historical qualification evidence, never a trust decision. + evidence.ownerResolution = resolveReferenceOwners(db, record.ownerRoot, evidence.identityObservation!, record.ownerPolicy); const count = db.query("SELECT COUNT(*) AS n FROM reference_reads WHERE turn_id = ?").get(record.turnId) as { n: number }; if (count.n >= 2000) throw new Error("Reference read record capacity exceeded"); db.query(`INSERT INTO reference_reads (id, turn_id, tool_call_id, principal_id, acquisition, evidence, response_digest, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?)`).run(record.id, record.turnId, record.toolCallId, record.principalId, - record.acquisition, record.evidence, record.responseDigest, record.at); + record.acquisition, JSON.stringify(evidence), record.responseDigest, record.at); }).immediate(); }, referenceReadObserve(turnId: string, toolCallId: string, digest: string | null, finalized: boolean) { diff --git a/packages/ui-server/src/brain/reference-read.ts b/packages/ui-server/src/brain/reference-read.ts index 7446f206db..d9fbecb3a6 100644 --- a/packages/ui-server/src/brain/reference-read.ts +++ b/packages/ui-server/src/brain/reference-read.ts @@ -1,4 +1,5 @@ /** Immutable reference content returned through one authenticated turn and actual backend call. */ +import { type ReferenceOwnerPolicy, type ReferenceOwnerRoot, resolveReferenceOwners } from "./reference-owner-resolution.js"; import { createHash, randomUUID } from "node:crypto"; import type { Database } from "bun:sqlite"; import { REFERENCE_READ_INPUT_SCHEMA, type ReferenceReadInput, type ReferenceToolResult } from "@schlessera/brain-ui-sdk/tool-contracts"; @@ -30,10 +31,13 @@ function finalReadText(output: string, segments?: readonly string[]): string | n } export function createReferenceReads(options: { + /** Served protected policy root; absent hosts report owner qualification unavailable. */ + ownerRoot?: Readonly; + ownerPolicy?(): ReferenceOwnerPolicy | undefined; db: Database; brain: string; sources: Pick; pool: Pick; transport: Pick; }) { - const { db } = options, write = referenceWrites(db); + const { db } = options, write = referenceWrites(db), ownerRoot = options.ownerRoot; const calls = new Map>(); return { end(turnId: string) { calls.delete(turnId); }, @@ -109,10 +113,13 @@ export function createReferenceReads(options: { const result: ReferenceToolResult = { ok: true, read: { repository: location.canonical, revision: request.revision, commit: lease.commit, path: request.path, offset: blob.offset, length: blob.length, totalBytes: blob.totalBytes, encoding: utf8 ? "utf8" : "base64", content: utf8 ? text : bytes.toString("base64") }, guidance }; - await write("referenceReadPrepare", { id: randomUUID(), operationId, turnId, toolCallId, principalId, acquisition: acquisitionSnapshot, + const ownerPolicy = options.ownerPolicy?.(); + await write("referenceReadPrepare", { id: randomUUID(), ownerRoot, ownerPolicy, operationId, turnId, toolCallId, principalId, acquisition: acquisitionSnapshot, evidence: JSON.stringify({ version: 1, path: request.path, blob: blob.blob, mode: blob.mode, tree: blob.tree, offset: blob.offset, length: blob.length, totalBytes: blob.totalBytes, digest: blob.digest, grantId: lease.readGrantId, detectorVersion: 1, - trusted: false, trustRevision: "0", identityObservation }), responseDigest: digest(JSON.stringify(result)), at: Date.now() }, lease.rootId, lease.readGrantId, authority); + trusted: false, trustRevision: "0", identityObservation, + // Provisional only: the writer resolves again after its queue wait. + ownerResolution: resolveReferenceOwners(db, ownerRoot, identityObservation!, ownerPolicy) }), responseDigest: digest(JSON.stringify(result)), at: Date.now() }, lease.rootId, lease.readGrantId, authority); assertAuthority(); return result; } catch (error) { diff --git a/packages/ui-server/src/brain/trust-policy-generation.ts b/packages/ui-server/src/brain/trust-policy-generation.ts new file mode 100644 index 0000000000..df449d3107 --- /dev/null +++ b/packages/ui-server/src/brain/trust-policy-generation.ts @@ -0,0 +1,11 @@ +/** Metadata fence shared with Settings' single live-policy interpretation. No cache. */ +import { lstatSync } from "node:fs"; +import { join } from "node:path"; +export function trustPolicyGeneration(root: string): string { + return [root, join(root, "context"), join(root, "context/policies"), join(root, "context/policies/governance.md")].map((path, index) => { + try { + const info = lstatSync(path, { bigint: true }); + return [info.dev, info.ino, info.mode, info.nlink, ...(index === 3 ? [info.size, info.mtimeNs, info.ctimeNs] : [])].map(String).join(":"); + } catch (error) { if ((error as NodeJS.ErrnoException).code === "ENOENT") return "missing"; throw error; } + }).join("|"); +} diff --git a/packages/ui-server/src/brain/trust-settings-writes.ts b/packages/ui-server/src/brain/trust-settings-writes.ts index effd311c14..4880b4e895 100644 --- a/packages/ui-server/src/brain/trust-settings-writes.ts +++ b/packages/ui-server/src/brain/trust-settings-writes.ts @@ -29,7 +29,17 @@ export function setup(db: Database): WriteProcedures { }, projection(brain: string, revision: string, rules: string, hash: string | null, error: string | null) { return db.transaction(() => { - db.query("INSERT INTO trust_settings_projection VALUES (?,?,?,?,?) ON CONFLICT(brain_id) DO UPDATE SET revision=excluded.revision,rules=excluded.rules,policy_hash=excluded.policy_hash,error=excluded.error").run(brain, revision, rules, hash, error); + const prior = db.query("SELECT rules,rule_instances FROM trust_settings_projection WHERE brain_id=?").get(brain) as { rules:string;rule_instances:string } | null; + const oldRules = new Map((JSON.parse(prior?.rules ?? "[]") as {id:string;selector:unknown;incomingContent:boolean}[]).map(rule=>[rule.id,JSON.stringify([rule.selector,rule.incomingContent])])); + const oldInstances = JSON.parse(prior?.rule_instances ?? "{}") as Record; + const instances:Record = Object.create(null); + for (const rule of JSON.parse(rules) as {id:string;selector:unknown;incomingContent:boolean}[]) { + const same = oldRules.get(rule.id) === JSON.stringify([rule.selector,rule.incomingContent]); + instances[rule.id] = (error || same) && typeof oldInstances[rule.id] === "string" ? oldInstances[rule.id]! : revision; + } + db.query(`INSERT INTO trust_settings_projection (brain_id,revision,rules,policy_hash,error,rule_instances) VALUES (?,?,?,?,?,?) + ON CONFLICT(brain_id) DO UPDATE SET revision=excluded.revision,rules=excluded.rules,policy_hash=excluded.policy_hash,error=excluded.error,rule_instances=excluded.rule_instances`) + .run(brain, revision, rules, hash, error, JSON.stringify(instances)); // At most one retained boundary per current rule; equal file bytes // alone never create one. Invalid policy retains last-valid facts. if (!error) { @@ -38,6 +48,7 @@ export function setup(db: Database): WriteProcedures { for (const row of boundaries) if (current.get(row.rule_id) !== row.selector) db.query("DELETE FROM trust_settings_github_boundaries WHERE brain_id=? AND rule_id=?").run(brain, row.rule_id); } + return instances; }).immediate(); }, }; diff --git a/packages/ui-server/src/brain/trust-settings.ts b/packages/ui-server/src/brain/trust-settings.ts index 00bbcf2e25..d8a2beb1c8 100644 --- a/packages/ui-server/src/brain/trust-settings.ts +++ b/packages/ui-server/src/brain/trust-settings.ts @@ -1,3 +1,5 @@ +import { trustPolicyGeneration } from "./trust-policy-generation.js"; +import type { ReferenceOwnerPolicy, ReferenceOwnerRoot } from "./reference-owner-resolution.js"; /** Human Settings operations. Markdown is authoritative; these rows are bounded * request/audit receipts, never a second policy source or an agent turn. */ import { createHash, randomBytes } from "node:crypto"; @@ -7,13 +9,14 @@ import type { Database } from "bun:sqlite"; import { z } from "zod"; import { parseFrontmatter } from "@schlessera/brain-common/internal/frontmatter"; import { openGovernancePolicyAnchored, verifyGovernancePolicyAnchored, parseGovernancePolicy, TrustedSourcesSchema, TrustRuleSchema, - TRUST_RUNTIME_CAPABILITIES, type TrustRule, type AnchoredGovernancePolicy } from "@schlessera/brain-common/internal/governance-policy"; + TRUST_RUNTIME_CAPABILITIES, GovernancePolicyReadError, type TrustRule, type AnchoredGovernancePolicy } from "@schlessera/brain-common/internal/governance-policy"; import { BRAIN_LOCK_KEY, type KeyedLock } from "@schlessera/brain-ui-sdk/server"; import { procedureCaller, type SqliteWriter } from "../db/write-worker.js"; import { publishProtectedPolicy } from "./policy-publication.js"; import * as writes from "./trust-settings-writes.js"; import type { createTrustGitHubIdentity, TrustGitHubIdentity } from "./trust-github-identity.js"; import { ReferenceTransportError } from "./reference-transport.js"; +import { resolvePrincipal, isUsablePrincipal } from "../db/principals.js"; const hash = (s: string | Uint8Array) => createHash("sha256").update(s).digest("hex"); const id = () => randomBytes(24).toString("base64url"); const exactDiff = (before: string | null, after: string) => (before ?? "").split("\n").map(line => `- ${line}`).concat(after.split("\n").map(line => `+ ${line}`)).join("\n"); @@ -35,12 +38,16 @@ export class TrustSettingsError extends Error { constructor(readonly code: string, readonly status: 400 | 403 | 404 | 409 | 503 = 409) { super(code); } } interface Projection { revision: string; rules: TrustRule[]; policyHash: string | null; error: string | null } -interface Receipt { +type LiveProjection = Projection & { readonly ruleInstances: Readonly> }; +/** Kept off every strict Settings JSON response; captured atomically with its projection. */ +const withInstances = (projection:Projection,instances:Readonly>):LiveProjection => + Object.defineProperty(projection,"ruleInstances",{value:Object.freeze(instances),enumerable:false}) as LiveProjection; +export interface Receipt { version: 1; requestId: string; operationId: string; stage: "prepared" | "file_published" | "committed" | "partial" | "unknown" | "refused"; publication: "not_published" | "proved" | "unknown"; ruleId: string; publishedTrustRevision: string | null; - currentRule: "present" | "removed" | "changed" | "unknown"; enforcement: "unavailable"; reason: string | null; + currentRule: "present" | "removed" | "changed" | "unknown"; enforcement: "unavailable" | "enforced"; reason: string | null; } -interface Payload { input: Prepare; reviewId: string; proposed: string; proposedHash: string; base: string | null; topology: string; rule: TrustRule | null; githubIdentity?: TrustGitHubIdentity } +interface Payload { input: Prepare; reviewId: string; proposed: string; proposedHash: string; base: string | null; topology: string; rule: TrustRule | null; githubIdentity?: TrustGitHubIdentity; safetyReview?: { body: import("@schlessera/brain-ui-sdk/protocol").SafetyReviewBody; requestId: string } } interface Row { principal_id: string; brain_id: string; authority: string; expires_at: number; retain_until: number; payload: string; stage: string; proof: string | null; receipt: string } const topology = (root: string) => [root, join(root, "context"), join(root, "context/policies"), join(root, "context/policies/governance.md")].map((path, i) => { const stat = lstatSync(path, { throwIfNoEntry: false }); @@ -80,6 +87,9 @@ export function createTrustSettings(options: { * fingerprint includes credential/lifetime identity, never a body/channel claim. */ authority(principalId: string): string | null; observe(operationId: string, operation: (publish?: (write: () => void) => Promise) => void | Promise): Promise; + ownerRoot?: Readonly; + /** The composed host has installed the origin admission and stream fences. */ + originEnforcement?: true; github?: ReturnType; now?: () => number; /** Host-only deterministic crash/race injection, never wired from HTTP. */ @@ -89,34 +99,92 @@ export function createTrustSettings(options: { try { root = realpathSync(options.root); } catch (error) { if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error; root = resolve(options.root); } const brain = hash(root); const capabilities = { ...TRUST_RUNTIME_CAPABILITIES, repositoryIdentity: !!options.github, - readOnlyReason: "Runtime trust enforcement is unavailable" }; + originRules: options.originEnforcement === true, recipientRules: options.originEnforcement === true, readOnlyReason: options.originEnforcement ? null : "Runtime trust enforcement is unavailable" }; const call = procedureCaller(options.db, writes, undefined, options.writer), now = options.now ?? Date.now; const authority = (principal: string, expected?: string) => { const value = options.authority(principal); if (!value || (expected !== undefined && expected !== value)) throw new TrustSettingsError("unauthorized", 403); return value; }; - const projection = (): Projection => { - const row = options.db.query("SELECT * FROM trust_settings_projection WHERE brain_id=?").get(brain) as { revision: string; rules: string; policy_hash: string | null; error: string | null } | null; - return row ? { revision: row.revision, rules: JSON.parse(row.rules), policyHash: row.policy_hash, error: row.error } : { revision: "0", rules: [], policyHash: null, error: null }; + const projection = (): LiveProjection => { + const row = options.db.query("SELECT * FROM trust_settings_projection WHERE brain_id=?").get(brain) as { revision: string; rules: string; policy_hash: string | null; error: string | null; rule_instances:string } | null; + return row ? withInstances({ revision: row.revision, rules: JSON.parse(row.rules), policyHash: row.policy_hash, error: row.error },JSON.parse(row.rule_instances)) + : withInstances({ revision: "0", rules: [], policyHash: null, error: null },{}); }; - const refresh = async (): Promise => { - const old = projection(); let target: AnchoredGovernancePolicy | undefined; - let rules: TrustRule[], policyHash: string | null; + const listeners = new Set<() => void>(); + type Observation = { kind: "valid"; rules: TrustRule[]; policyHash: string | null } | { kind: "unavailable" }; + let observed: { generation: string; value: Observation } | undefined; + let retained: LiveProjection | undefined, retainedFor: Observation | undefined; + let liveCache: { observation: Observation; base: LiveProjection; value: LiveProjection } | undefined; + // Metadata is the per-chunk fence. Include every ancestry identity and the + // file's nanosecond change identity, without reading policy bytes or SQLite. + const generation = () => trustPolicyGeneration(root); + /** One state machine for live reads and durable refresh. Changed verification + * always fences; stable invalid/unreadable bytes retain last-valid evidence. */ + const observePolicy = (): Observation => { + let before: string; + try { before = generation(); } catch { return { kind: "unavailable" }; } + if (observed?.generation === before) return observed.value; + let target: AnchoredGovernancePolicy | undefined, value: Observation; try { target = openGovernancePolicyAnchored(root); - policyHash = target.bytes === null ? null : hash(target.bytes); verifyGovernancePolicyAnchored(target, policyHash); + const policyHash = target.bytes === null ? null : hash(target.bytes); + verifyGovernancePolicyAnchored(target, policyHash); const checked = target.bytes === null ? null : parseGovernancePolicy(target.bytes); - if (checked && !checked.ok) throw new Error("invalid"); - rules = checked?.effective.taint.trusted_sources ?? []; + value = checked && !checked.ok ? { kind: "unavailable" } + : { kind: "valid", rules: checked?.effective.taint.trusted_sources ?? [], policyHash }; } catch (error) { - if ((error as NodeJS.ErrnoException).code === "ENOENT") { rules = []; policyHash = null; } - else { await call("projection", brain, old.revision, JSON.stringify(old.rules), old.policyHash, "policy_unavailable"); return { ...old, error: "policy_unavailable" }; } + if (error instanceof GovernancePolicyReadError && ["changed", "mismatch", "ancestry"].includes(error.refusal)) + throw new TrustSettingsError("stale_revision"); + value = (error as NodeJS.ErrnoException).code === "ENOENT" ? { kind: "valid", rules: [], policyHash: null } : { kind: "unavailable" }; } finally { target?.close(); } + // Also catch replacement around an unreadable/invalid snapshot or after + // the anchored verification. Never memoize a raced observation as stable. + let after: string; + try { after = generation(); } catch { throw new TrustSettingsError("stale_revision"); } + if (after !== before) throw new TrustSettingsError("stale_revision"); + observed = { generation: after, value }; return value; + }; + const freshProjection = (): LiveProjection => { + const observation = observePolicy(); + if (observation.kind === "unavailable") { const p = projection(); return withInstances({ ...p, error: "policy_unavailable" },p.ruleInstances); } + // An unverified projection is never cached: another reader may be seeing + // the published file while its writer is still committing the projection. + const base = retained && retainedFor === observation ? retained : projection(); + if (liveCache?.observation === observation && liveCache.base === base) return liveCache.value; + if (observation.kind === "valid" && JSON.stringify(observation.rules) !== JSON.stringify(base.rules)) throw new TrustSettingsError("stale_revision"); + retained = base; retainedFor = observation; + const value = withInstances({ ...base, policyHash: observation.policyHash, error: null },base.ruleInstances); + liveCache = { observation, base, value }; return value; + }; + const live = { read: freshProjection, revision: () => freshProjection().revision, + refresh: async (signal?: AbortSignal) => { + signal?.throwIfAborted(); + try { + const value = observePolicy(), row = projection(); + // A missing row's synthetic empty projection is not durable proof. + const exists = options.db.query("SELECT 1 FROM trust_settings_projection WHERE brain_id=?").get(brain) !== null; + if (value.kind === "valid" && exists && row.error === null && row.policyHash === value.policyHash) return freshProjection(); + } catch (error) { + if (!(error instanceof TrustSettingsError) || error.code !== "stale_revision") throw error; + } + return options.lock.withLock(BRAIN_LOCK_KEY, () => { signal?.throwIfAborted(); return refresh(); }, { signal }); + }, subscribe(changed: () => void) { listeners.add(changed); return () => { listeners.delete(changed); }; } }; + const refresh = async (): Promise => { + const old = projection(), value = observePolicy(); + if (value.kind === "unavailable") { + const instances = await call>("projection", brain, old.revision, JSON.stringify(old.rules), old.policyHash, "policy_unavailable"); + const next = withInstances({ ...old, error: "policy_unavailable" },instances); + retained = next; retainedFor = value; return freshProjection(); + } + const { rules, policyHash } = value; const changed = JSON.stringify(old.rules) !== JSON.stringify(rules); if (changed && BigInt(old.revision) >= MAX_TRUST_REVISION) throw new TrustSettingsError("capacity", 503); const next = { revision: changed ? String(BigInt(old.revision) + 1n) : old.revision, rules, policyHash, error: null }; - await call("projection", brain, next.revision, JSON.stringify(rules), policyHash, null); return next; + const instances = await call>("projection", brain, next.revision, JSON.stringify(rules), policyHash, null); + retained = withInstances(next,instances); retainedFor = value; + if (changed) for (const listener of listeners) listener(); + return freshProjection(); }; const row = (principal: string, request: string): Row => { authority(principal); @@ -128,21 +196,70 @@ export function createTrustSettings(options: { const rule = p.rules.find(rule => rule.id === receipt.ruleId); return { ...receipt, currentRule: p.error ? "unknown" : !rule ? "removed" : JSON.stringify(rule) === JSON.stringify(payload.rule) ? "present" : "changed" }; }; + const readCurrent = (principal: string, request: string, p: Projection) => { + const r = row(principal, request), payload = JSON.parse(r.payload) as Payload; + let receipt = JSON.parse(r.receipt) as Receipt; + if (r.stage === "writing") receipt = { ...receipt, stage: "unknown", publication: "unknown", reason: "publication_completion_unknown" }; + if (r.stage === "file_published") receipt = { ...receipt, stage: "partial", publication: r.proof ? "proved" : "unknown", reason: "publication_recorded_completion_incomplete" }; + return { receipt: current(receipt, payload, p), review: { reviewId: payload.reviewId, base: payload.base, proposed: payload.proposed, + diff: exactDiff(payload.base, payload.proposed), reviewedBytesHash: payload.proposedHash, expiresAt: r.expires_at, + repositoryIdentity: payload.githubIdentity ?? null, + includesFutureRepositories: payload.rule?.selector.kind === "github_owner" }, policy: p, capabilities }; + }; const read = async (principal: string, request: string) => { row(principal, request); - return options.lock.withLock(BRAIN_LOCK_KEY, async () => { - const p = await refresh(); - const r = row(principal, request), payload = JSON.parse(r.payload) as Payload; - let receipt = JSON.parse(r.receipt) as Receipt; - if (r.stage === "writing") receipt = { ...receipt, stage: "unknown", publication: "unknown", reason: "publication_completion_unknown" }; - if (r.stage === "file_published") receipt = { ...receipt, stage: "partial", publication: r.proof ? "proved" : "unknown", reason: "publication_recorded_completion_incomplete" }; - return { receipt: current(receipt, payload, p), review: { reviewId: payload.reviewId, base: payload.base, proposed: payload.proposed, - diff: exactDiff(payload.base, payload.proposed), reviewedBytesHash: payload.proposedHash, expiresAt: r.expires_at, - repositoryIdentity: payload.githubIdentity ?? null, - includesFutureRepositories: payload.rule?.selector.kind === "github_owner" }, policy: p, capabilities }; - }); + return options.lock.withLock(BRAIN_LOCK_KEY, async () => readCurrent(principal,request,await refresh())); }; return { + /** Snapshot the existing live interpretation; writers fence its generation after waits. */ + ownerPolicy(): ReferenceOwnerPolicy | undefined { + try { + const before = generation(), p = live.read(); + if (generation() !== before) return; + return { rules: p.rules, revision: p.revision, policyHash: p.policyHash, error: p.error, generation: before }; + } catch { return; } + }, + live, + /** Recovery uses durable completion/publication evidence, never preparation + * expiry as a proxy for publication order. Scope and retention share read's + * authority, served brain and clock, including expiry during the lock wait. */ + async safetyStatus(principal: string, session: import("@schlessera/brain-ui-sdk/protocol").SafetySessionKey, occurrenceId: string) { + authority(principal); + return options.lock.withLock(BRAIN_LOCK_KEY, async () => { + authority(principal); + const select = (present: string[] = []) => options.db.query(`SELECT o.request_id FROM trust_settings_operations o + LEFT JOIN safety_decisions d ON d.request_id=json_extract(o.payload,'$.safetyReview.requestId') + WHERE o.brain_id=? AND o.principal_id=? AND o.retain_until>=? + AND json_extract(o.payload,'$.safetyReview.body.occurrenceId')=? + AND json_extract(o.payload,'$.safetyReview.body.session.sessionId')=? + AND json_extract(o.payload,'$.safetyReview.body.session.historyOwnerId')=? + AND json_extract(o.payload,'$.safetyReview.body.session.historyGeneration')=? + ORDER BY (d.id IS NOT NULL) DESC, + EXISTS(SELECT 1 FROM json_each(?) present_rule WHERE present_rule.value=json_extract(o.receipt,'$.ruleId')) DESC, + CASE WHEN o.proof IS NOT NULL THEN 0 WHEN o.stage='writing' OR json_extract(o.receipt,'$.publication')='unknown' THEN 1 ELSE 2 END, + length(coalesce(json_extract(o.proof,'$.publishedTrustRevision'),'')) DESC, + coalesce(json_extract(o.proof,'$.publishedTrustRevision'),'') DESC,o.rowid DESC LIMIT 1`) + .get(brain,principal,now(),occurrenceId,session.sessionId,session.historyOwnerId,session.historyGeneration,JSON.stringify(present)) as {request_id:string}|null; + if (!select()) return null; + const p = await refresh(); + return options.db.transaction(() => { + const selected = select(p.error ? [] : p.rules.map(rule=>rule.id)); + if (!selected) { authority(principal); return null; } + try { + const binding = (JSON.parse(row(principal,selected.request_id).payload) as Payload).safetyReview; + if (!binding) throw new TrustSettingsError("request_conflict"); + return {requestId:selected.request_id,binding,receipt:readCurrent(principal,selected.request_id,p).receipt}; + } catch (error) { + if (!(error instanceof TrustSettingsError) || error.code !== "unavailable" || error.status !== 404) throw error; + authority(principal); return null; + } + }).deferred(); + }); + }, + /** Internal binding; ordinary Settings commits cannot publish a combined review. */ + safetyReview(principal: string, request: string) { return (JSON.parse(row(principal, request).payload) as Payload).safetyReview; }, + /** The other protected publisher already owns the shared brain lock. */ + refreshLocked: refresh, /** Live trust-only projection for future admissions. Ordinary policy snapshots * remain owned by their admitted turn; this never mutates them. */ async snapshot() { return options.lock.withLock(BRAIN_LOCK_KEY, refresh); }, @@ -155,10 +272,27 @@ export function createTrustSettings(options: { const row = options.db.query("SELECT selector,identity,proof FROM trust_settings_github_boundaries WHERE brain_id=? AND rule_id=?").get(brain, ruleId) as { selector: string; identity: string; proof: string } | null; return row && row.selector === JSON.stringify(rule.selector) ? { identity: JSON.parse(row.identity) as TrustGitHubIdentity, proof: JSON.parse(row.proof) as unknown } : null; }); }, - async list(principal: string) { authority(principal); const p = await options.lock.withLock(BRAIN_LOCK_KEY, refresh); authority(principal); - return { ...p, origins: p.rules.filter(r => !r.selector.kind.startsWith("github_")), repositories: p.rules.filter(r => r.selector.kind.startsWith("github_")), capabilities }; }, + async list(principal: string) { + const access = () => { + const mutationAllowed = !!options.authority(principal); + if (!mutationAllowed) { + const reader = resolvePrincipal(options.db, principal); + if (!reader || !["owner", "agent", "ambient"].includes(reader.kind) || !isUsablePrincipal(reader, now())) + throw new TrustSettingsError("unauthorized", 403); + } + return mutationAllowed; + }; + access(); + const p = await options.lock.withLock(BRAIN_LOCK_KEY, async () => { + const snapshot = await refresh(); + // Observation-only incarnation tokens, captured with the same policy. + // The internal stream-fence projection remains non-enumerable. + return { ...snapshot, instances: { ...(snapshot as LiveProjection).ruleInstances } }; + }); + const mutationAllowed = access(); + return { ...p, mutationAllowed, origins: p.rules.filter(r => !r.selector.kind.startsWith("github_")), repositories: p.rules.filter(r => r.selector.kind.startsWith("github_")), capabilities }; }, read, - async prepare(principal: string, raw: unknown, signal?: AbortSignal) { + async prepare(principal: string, raw: unknown, signal?: AbortSignal, safetyReview?: Payload["safetyReview"]) { const auth = authority(principal), input = TrustPrepareSchema.parse(raw); if (process.platform !== "linux") throw new TrustSettingsError("unavailable", 503); // Names/IDs supplied by browsers cannot create repository identity proof. @@ -191,7 +325,7 @@ export function createTrustSettings(options: { } if (Buffer.byteLength(JSON.stringify({ base, proposed, diff: exactDiff(base, proposed) })) > 196608) throw new TrustSettingsError("capacity", 503); const payload: Payload = { input, reviewId: id(), proposed, proposedHash: hash(proposed), base, topology: identity, - rule: change.action === "remove" ? null : change.rule, ...(githubIdentity ? { githubIdentity } : {}) }; + rule: change.action === "remove" ? null : change.rule, ...(safetyReview ? { safetyReview } : {}), ...(githubIdentity ? { githubIdentity } : {}) }; const receipt: Receipt = { version: 1, requestId, operationId, stage: "prepared", publication: "not_published", ruleId, publishedTrustRevision: null, currentRule: "unknown", enforcement: "unavailable", reason: null }; const inserted = await call("insert", { requestId, brainId: brain, principalId: principal, authority: auth, expires: now() + 900000, retain: now() + 86400000, @@ -201,10 +335,11 @@ export function createTrustSettings(options: { }); return read(principal, request); }, - async commit(principal: string, raw: unknown, signal?: AbortSignal) { + async commit(principal: string, raw: unknown, signal?: AbortSignal, safety?: { binding: NonNullable; check(): void }) { const input: Commit = TrustCommitSchema.parse(raw); row(principal, input.requestId); await options.lock.withLock(BRAIN_LOCK_KEY, async () => { const r = row(principal, input.requestId), payload = JSON.parse(r.payload) as Payload; + if (JSON.stringify(payload.safetyReview) !== JSON.stringify(safety?.binding)) throw new TrustSettingsError("request_conflict"); if (payload.reviewId !== input.reviewId || payload.proposedHash !== input.reviewedBytesHash) throw new TrustSettingsError("request_conflict"); if (r.stage !== "prepared") return; // Readback only, including uncertain writes. if (r.expires_at < now()) throw new TrustSettingsError("request_expired"); @@ -225,6 +360,7 @@ export function createTrustSettings(options: { let identityAuthority: (() => void) | undefined; const check = () => { signal?.throwIfAborted(); if (!publicationOpen) throw new TrustSettingsError("publication_failed"); + safety?.check(); row(principal, input.requestId); identityAuthority?.(); if (r.expires_at < now()) throw new TrustSettingsError("request_expired"); if (!matchesTopology(root, payload.topology, true)) throw new TrustSettingsError("stale_base"); verifyGovernancePolicyAnchored(target!, p.policyHash); }; @@ -261,14 +397,19 @@ export function createTrustSettings(options: { receipt.stage = "file_published"; receipt.publication = "proved"; receipt.publishedTrustRevision = String(BigInt(p.revision) + 1n); await save("file_published", JSON.stringify({ operationId: receipt.operationId, principal, brain, authority: r.authority, + policyRoot: options.ownerRoot?.path === root && options.ownerRoot.device === target.directories[0]!.dev && options.ownerRoot.inode === target.directories[0]!.ino + ? options.ownerRoot.native : null, baseHash: p.policyHash, expectedTrustRevision: p.revision, publishedTrustRevision: receipt.publishedTrustRevision, reviewedBytesHash: payload.proposedHash, ...(payload.githubIdentity ? { githubIdentity: payload.githubIdentity } : {}) }), payload.githubIdentity && payload.rule ? { brain, ruleId: payload.rule.id, selector: JSON.stringify(payload.rule.selector), identity: JSON.stringify(payload.githubIdentity) } : undefined); proved = true; await options.checkpoint?.("file_published"); const latest = await refresh(); row(principal, input.requestId); if (latest.policyHash === payload.proposedHash) receipt.publishedTrustRevision = latest.revision; - // No runtime source/recipient enforcement exists in this slice (#3609). - receipt.stage = "partial"; receipt.reason = "policy_saved_runtime_enforcement_unavailable"; + const changedRule = payload.rule ?? p.rules.find(rule => rule.id === receipt.ruleId); + const supported = options.originEnforcement === true && !latest.error && latest.policyHash === payload.proposedHash && (changedRule?.selector.kind === "web_origin" || changedRule?.selector.kind === "tunnel_authority"); + receipt.enforcement = supported ? "enforced" : "unavailable"; + receipt.stage = supported ? "committed" : "partial"; + receipt.reason = supported ? null : "policy_saved_runtime_enforcement_unavailable"; await save("committed"); await options.checkpoint?.("committed"); } catch (error) { publicationOpen = false; diff --git a/packages/ui-server/src/brain/turn-egress.ts b/packages/ui-server/src/brain/turn-egress.ts index eafa0f96cb..6281430669 100644 --- a/packages/ui-server/src/brain/turn-egress.ts +++ b/packages/ui-server/src/brain/turn-egress.ts @@ -1,14 +1,16 @@ /** One admitted turn's concrete proxy, approval surface and durable records. */ -import type { EffectiveGovernancePolicy } from "@schlessera/brain-common/internal/governance-policy"; -import { startEgressProxy, type EgressRecord } from "@schlessera/brain-ui-sdk/internal"; +import { originTrustMatchSnapshot, type OriginTrust, type OriginDestination } from "./origin-trust.js"; +import type { EffectiveGovernancePolicy, TrustMatch } from "@schlessera/brain-common/internal/governance-policy"; +import { startEgressProxy, canonicalEgressHost, validatedEgressProvenance, EgressAdmissionRefused, type EgressRecord } from "@schlessera/brain-ui-sdk/internal"; import { requestToolPermission, type BackendActivityEvent, type BackendBridge } from "@schlessera/brain-ui-sdk/server"; import type { Database } from "bun:sqlite"; import { occurrence, type Occurrence } from "../governance/occurrence.js"; 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"; +import { safetyQueue, safetyReadVersion } from "../governance/safety-queue.js"; +import { safetyProjection, safetyEvidenceSequence } from "../governance/safety-store.js"; +import { settleTurnSessionBinding, type SessionBindingRefusal } from "../ws/bridge-session-binding.js"; import { isMarkedUntrusted } from "../files/untrusted-marks.js"; import { createTurnExtraction } from "./turn-extraction.js"; import type { ExtractionJudge } from "../governance/extraction-judge.js"; @@ -34,6 +36,8 @@ const TAINT_SOURCE_WORDING: Readonly> = { chat_attachment: "opened a chat attachment", apify_result: "received Apify results", github_result: "read GitHub issues or pull requests", compute_output: "collected an external compute job's output", }; +const networkAuthority = (destination: {host:string;port:number}) => `${destination.host.includes(":") ? `[${destination.host}]` : destination.host}:${destination.port}`; + /** * The card a tainted interactive session raises for a destination outside its * taint allow-list (#3430): the destination, what tainted the session, and @@ -42,7 +46,7 @@ const TAINT_SOURCE_WORDING: Readonly> = { 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}? ` + return `${cause} Allow it to connect to ${networkAuthority(destination)}? ` + `Allowing lets it send data to ${destination.host} for the rest of this session without asking again.`; } @@ -62,9 +66,11 @@ function actionHosts(action: Classification["actions"][number]): readonly string */ export function createOutwardCalls() { const calls = new Map(); + let generation=0n; return { activity(event: BackendActivityEvent): void { if (event.kind !== "outward_classification") return; + generation++; // A refused or declined call never runs. if (event.decision !== "allow") { calls.delete(event.toolUseId); return; } const classification = event.classification; @@ -73,8 +79,9 @@ export function createOutwardCalls() { : classification.kind === "outward" ? { read: false, hosts: classification.actions.flatMap(actionHosts) } : null); }, emitted(message: Parameters[0]): void { - if (message.type === "tool_result") calls.delete(message.toolUseId); + if (message.type === "tool_result" && calls.delete(message.toolUseId)) generation++; }, + generation:()=>generation.toString(), covers(host: string): boolean { const active = [...calls.values()]; // Every call in progress must be a read or name this host: another @@ -85,6 +92,7 @@ export function createOutwardCalls() { } export async function prepareTurnEgress(options: { + trust?: OriginTrust; policy: EffectiveGovernancePolicy; policyHash?:string|null; bridge: BackendBridge; controller: AbortController; turnId: string; sessionId: () => string | null; model: () => string | null; profile: "governed" | "strict"; origin: "interactive" | "voice"; @@ -118,40 +126,91 @@ export async function prepareTurnEgress(options: { const record = options.record; const writes: typeof options.governanceWrites = options.governanceWrites ?? (db && record ? { taint: (turnId: string | null, sessionId: string | null) => sessionTaint(db, turnId, sessionId), - firstTaint: (event: GovernanceEventInput<"taint">) => { recordFirstTaint(db, event, record); return Promise.resolve(true); }, + firstTaint: async (event: GovernanceEventInput<"taint">) => { + let pending:unknown; + recordFirstTaint(db,event,input=>{pending=record(input);}); + const result=await pending; + if(typeof result === "boolean")return result; + if(result&&typeof result === "object"&&"recorded" in result)return result.recorded === true; + const input=event.payload.occurrence; + return !input?.admission?.trusted || db.query("SELECT id FROM safety_records WHERE id=? AND kind='occurrence'").get(input.id) !== null; + }, } : undefined); const recording = new Set>(); // Hosts earlier turns of the session reached, then every host this turn admits. const contacted = new Set(db ? contactedHosts(db, options.sessionId()) : []); const collectionEpoch = (db?.query("SELECT id FROM safety_collections WHERE turn_id=?").get(options.turnId) as {id:string}|null)?.id??crypto.randomUUID(); const exposures = new Map(); + const ownCollectionStarts = new Map(); + // Each card owns its peer inputs until its last connection terminates. Keep + // their immutable ids after a peer finishes so a slower peer sees the same + // reviewed context; independent cards and independent input remain evidence. + type ApprovalGroup = { members:Set; occurrences:Set; starts:Set;pending?:{generation:bigint;size:number;ids:readonly string[]} }; + const approvalGroups = new Map(); + const pendingReservations = (connectionId?:string):readonly string[] => { + const group=connectionId?approvalGroups.get(connectionId):undefined;if(!db||!group)return []; + const queue=safetyQueue(db); + if(group.pending?.generation===queue.generation&&group.pending.size===group.occurrences.size)return group.pending.ids; + const ids=Object.freeze([...queue.pending].filter(p=>p.occurrenceId!==null&&group.occurrences.has(p.occurrenceId)).map(p=>p.id)); + group.pending={generation:queue.generation,size:group.occurrences.size,ids};return ids; + }; + const exposureCommits = new Map>(); const normalBefore = new Set(); + const standingRecipients = new Map>(); + const trustedInputs = new Map(); + const inputCurrent = (connectionId: string) => { + const input = trustedInputs.get(connectionId); if (!input) return true; + let current:ReturnType | undefined; + try { current = options.trust?.read(); } catch { return false; } + if (!current || current.ruleInstances[input.ruleId] !== input.instance) return false; + if (current.revision === input.revision) return true; + // Revalidate this admission's own source rule, never borrow a replacement + // rule or rewrite the historical admission. Recipient-only edits are independent. + const match = originTrustMatchSnapshot({ ...current, ruleInstances:current.ruleInstances, rules: current.rules.filter(rule => rule.id === input.ruleId) }, input.destination, "incomingContent", "0"); + if (!match) return false; + input.revision = current.revision; return true; + }; + let releaseTrust: (() => void) | undefined; const base = () => ({ turnId: options.turnId, sessionId: options.sessionId(), model: options.model(), actor: options.origin, profile: options.profile }); const fail = () => { - recordingFailure ??= new Error("Turn egress recording is unavailable"); + recordingFailure ??= new EgressAdmissionRefused("Turn egress recording is unavailable","egress_unavailable"); options.controller.abort(recordingFailure); }; const track = (committed: unknown) => { - if (!(committed instanceof Promise)) return; - const pending = committed.catch(fail).finally(() => recording.delete(pending)); + const confirm=(result:unknown)=>{ + // A positive existing id is a durable replay, not a lost write. + if(result===false||result&&typeof result === "object"&&"recorded" in result&&result.recorded===false&&(!("id" in result)||typeof result.id !== "number"||result.id<=0))throw new Error("Egress audit was not durably recorded"); + }; + if (!(committed instanceof Promise)) {try{confirm(committed);}catch{fail();}return;} + const pending = committed.then(confirm).catch(fail).finally(() => recording.delete(pending)); recording.add(pending); }; + const releaseConnection = (connectionId?: string) => { + if (!connectionId) return; + trustedInputs.delete(connectionId);standingRecipients.delete(connectionId); + exposures.delete(connectionId);ownCollectionStarts.delete(connectionId);exposureCommits.delete(connectionId);normalBefore.delete(connectionId); + approvalGroups.get(connectionId)?.members.delete(connectionId);approvalGroups.delete(connectionId); + approvalMarkers.delete(`${connectionId}:network`);approvalMarkers.delete(`${connectionId}:outward`); + }; const report = (record: EgressRecord): void => { - if (!options.record) return; try { - track(options.record({ ...base(), kind: "egress_connection", payload: record })); + if (!options.record) return; + const trustedSource = record.connectionId ? trustedInputs.has(record.connectionId) : false; + track(options.record({ ...base(), kind: "egress_connection", payload: { ...record, ...(trustedSource ? { trustedSource: true } : {}), ...(record.connectionId && standingRecipients.has(record.connectionId) ? { standingRecipient: true, recipientAdmission: standingRecipients.get(record.connectionId) } : {}) } })); const exposure = record.connectionId ? exposures.get(record.connectionId) : undefined; if (exposure) { - exposures.delete(record.connectionId!); - normalBefore.delete(record.connectionId!); // A clean HTTP completion proves bounded input ended. A tunnel close // or cancellation alone cannot prove all opaque delivery completed. - track(options.record({ ...base(), kind: "taint_exposure", dedupeKey: exposure.id, - payload: { occurrenceId: exposure.id, state: record.method !== "CONNECT" && record.outcome === "completed" ? "finalized" : "interrupted_unknown" } })); + const terminal = () => options.record!({ ...base(), kind: "taint_exposure", dedupeKey: exposure.id, + payload: { occurrenceId: exposure.id, state: record.method !== "CONNECT" && record.outcome === "completed" ? "finalized" : "interrupted_unknown" } }); + // Removal can close the transport while its initial occurrence is + // still committing. Terminal evidence must join that exact write. + const initial = exposureCommits.get(record.connectionId!); + track(initial ? initial.then(recorded=>recorded===true?terminal():undefined,()=>undefined) : terminal()); } const denied = options.policy.egress.deny.some(pattern => { - const normalized = pattern.toLowerCase().replace(/\.$/, ""); + const normalized = canonicalEgressHost(pattern); 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" @@ -160,32 +219,70 @@ export async function prepareTurnEgress(options: { if (reason) track(options.record({ ...base(), kind: "egress_denial", payload: { host: record.host, port: record.port, method: record.method, reason, bytes: record.bytes, } })); - } catch { fail(); } + } catch { fail(); } finally { releaseConnection(record.connectionId); } }; /** * Any admitted connection other than a host relay taints the session (G6), * recorded before its first byte. Each connection keeps independent evidence. */ // 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; + let taintRead: { version:string; value:ReturnType } | undefined; + const firstTaint = () => { + if (!db) return null; + const sessionId = options.sessionId(), version = JSON.stringify([safetyReadVersion(db),sessionId]); + if (taintRead?.version === version) return taintRead.value; + const value = writes ? writes.taint(options.turnId,sessionId) : sessionTaint(db,options.turnId,sessionId); + taintRead = {version,value}; return value; + }; + let projectionRead: {version:string;value:ReturnType} | undefined; + const currentProjection = () => { + const sessionId = options.sessionId(), version = JSON.stringify([safetyReadVersion(db!),sessionId]); + if (projectionRead?.version === version) return projectionRead.value; + const value = writes?.safety?.(options.turnId,sessionId) ?? safetyProjection(db!,options.turnId,sessionId); + projectionRead = {version,value}; return value; + }; /** - * One card per destination host at a time: concurrent connections to the - * same new host share its answer. An allowed connection's admission adds + * One card per exact destination and live approval revision: concurrent + * connections share only the same reviewed context. 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); + const approvalMarkers = new Map(); + const approvalRevision = (connectionId?: string,kind: "network" | "outward" = "network") => { + const callGeneration=kind==="outward"?calls.generation():"0"; + if (!db) return `unrecorded:${callGeneration}`; + const excludedPending=kind==="network"?pendingReservations(connectionId):[]; + const safety = options.bridge.admissionSafety?.read(excludedPending); + const key = `${connectionId ?? "global"}:${kind}`, version = JSON.stringify([safety?.evidenceRevision ?? safetyReadVersion(db), safety?.scope, safety?.authorityEpoch, safety?.authorityCurrent, safety?.recordingAvailable, options.trust?.revision() ?? "0", safetyQueue(db).generation.toString(),callGeneration]); + const cached = approvalMarkers.get(key); if (cached?.version === version) return cached.marker; + const state = options.governanceWrites?.safety?.(options.turnId, options.sessionId(),excludedPending) ?? safetyProjection(db, options.turnId, options.sessionId(),excludedPending); + const group=connectionId&&kind==="network"?approvalGroups.get(connectionId):undefined; + const ownStart=connectionId?ownCollectionStarts.get(connectionId):undefined; + const starts=new Set(group?.starts);if(ownStart)starts.add(ownStart); + const inputs=new Set(group?.occurrences);const ownInput=connectionId?exposures.get(connectionId)?.id:undefined;if(ownInput)inputs.add(ownInput); + // An uninstrumented turn was already unknown before its first record. + // Creating its sole incomplete epoch is metadata of this same input. + const coverage=state.coverage.epochs.length===1&&starts.has(state.coverage.epochs[0]!.id)&&state.coverage.state==="incomplete"?"unknown":state.coverage.state; + const marker = JSON.stringify([state.pendingCount, coverage, state.reasons.filter(reason => reason !== "unresolved"), safetyEvidenceSequence(db, options.turnId, options.sessionId(), [...inputs],[...starts]), + options.trust?.revision() ?? "0", safety?.scope, safety?.authorityEpoch, safety?.authorityCurrent, + writes?.recordingAvailable?.(options.turnId, options.sessionId(),excludedPending) ?? safety?.recordingAvailable,callGeneration]); + approvalMarkers.set(key,{version,marker}); return marker; + }; + const asking = new Map;group:ApprovalGroup}>(); + const approveTainted = async (destination: { host: string; port: number; method: string; protocol: string; managedReference: boolean }, signal: AbortSignal, connectionId?:string): Promise => { + const key = JSON.stringify([destination.host, destination.port, destination.method, destination.protocol, destination.managedReference, approvalRevision()]); + let pending = asking.get(key); if (!pending) { - pending = requestToolPermission(options.bridge, { toolUseId: crypto.randomUUID(), toolName: "Network", kind: "command", - input: { ...destination, target: `${destination.host}:${destination.port}` }, + const decision = requestToolPermission(options.bridge, { toolUseId: crypto.randomUUID(), toolName: "Network", kind: "command", + input: { ...destination, target: networkAuthority(destination) }, description: taintedDestinationDescription(destination, firstTaint()?.source ?? null), - }).then(decision => decision.behavior === "allow", () => false).finally(() => asking.delete(destination.host)); - asking.set(destination.host, pending); + }).then(decision => decision.behavior === "allow", () => false).finally(() => asking.delete(key)); + pending={decision,group:{members:new Set(),occurrences:new Set(),starts:new Set()}}; + asking.set(key, pending); } - const allowed = await pending; + if(connectionId){pending.group.members.add(connectionId);approvalGroups.set(connectionId,pending.group);} + const allowed = await pending.decision; return allowed && !signal.aborted; }; // The extraction classifier (#4088), off unless the policy turns it on. It @@ -197,9 +294,17 @@ export async function prepareTurnEgress(options: { ...(options.policy.taint.judge.mode === "jev" && options.extractionJudge ? { judge: options.extractionJudge } : {}) }) : null; const taint = db ? { allow: options.policy.taint.egress.allow, + approvalRevision, + recipient: (destination: OriginDestination) => { + const snapshot=options.trust?.read(); + const match=originTrustMatchSnapshot(snapshot,destination,"recipientWhileRestricted",options.bridge.admissionSafety?.read().evidenceRevision ?? "0"); + if(!match||!snapshot?.ruleInstances[match.ruleId])return false; + const {ruleId,policyHash,trustRevision,collectionRevision}=match; + return {ruleId,policyHash,trustRevision,collectionRevision,instance:snapshot.ruleInstances[ruleId]!}; + }, tainted: (connectionId?: string) => { if (connectionId && normalBefore.has(connectionId)) { - const projection = options.governanceWrites?.safety?.(options.turnId, options.sessionId()) ?? safetyProjection(db, options.turnId, options.sessionId()); + const projection = currentProjection(); // Only this request's own newly recorded input may be excluded from // its first-byte check. A second connection gets no such authority. if (projection.coverage.state === "complete" && projection.unresolvedCount === 1 && @@ -222,6 +327,8 @@ export async function prepareTurnEgress(options: { * moment it is submitted. */ const admitted = async (destination: { host: string; port: number; method: string; inference: boolean; provider: boolean; managedReference: boolean; connectionId: string; protocol?:string }): Promise => { + let provenance:ReturnType; + try { provenance=validatedEgressProvenance(destination); } catch { throw new EgressAdmissionRefused("Invalid egress destination"); } // A host relay's operation neither taints the session nor makes its host // one the worker's own traffic may reach once tainted (G6, #3246). // A managed acquisition has not delivered source content to the model. @@ -233,35 +340,60 @@ export async function prepareTurnEgress(options: { if (firstTaint() === null) normalBefore.add(destination.connectionId); if (!writes) return; const exposure = occurrence(collectionEpoch, "proxy_input", destination.connectionId, "open"); - exposure.admission={trusted:false,policyHash:options.policyHash??null,trustRevision:"0"}; - exposure.provenance=destination.method==="CONNECT" - ? {kind:"tunnel_authority",authority:{host:destination.host,port:destination.port},verifiedBy:"host_proxy"} - : destination.protocol==="http:"||destination.protocol==="https:" - ? {kind:"web_origin",origin:{scheme:destination.protocol==="http:"?"http":"https",host:destination.host,port:destination.port},verifiedBy:"host_transport"}:null; + const trustSnapshot = options.trust?.read(); + const candidate = originTrustMatchSnapshot(trustSnapshot, destination, "incomingContent", options.bridge.admissionSafety?.read().evidenceRevision ?? "0"); + const instance = candidate ? trustSnapshot?.ruleInstances[candidate.ruleId] : undefined; + const match = typeof instance === "string" ? candidate : null; + exposure.admission = match ? { trusted: true, ruleId: match.ruleId, policyHash: match.policyHash, trustRevision: match.trustRevision, collectionRevision: match.collectionRevision } + : { trusted: false, policyHash: trustSnapshot ? trustSnapshot.policyHash : options.policyHash ?? null, trustRevision: trustSnapshot?.revision ?? "0" }; + exposure.provenance=provenance; exposures.set(destination.connectionId, exposure); + const group=approvalGroups.get(destination.connectionId); + if(group){group.occurrences.add(exposure.id);for(const peer of group.members)approvalMarkers.delete(`${peer}:network`);} + const hadCollection=db?.query("SELECT id FROM safety_collections WHERE turn_id=?").get(options.turnId); try { - await writes.firstTaint({ ...base(), kind: "taint", payload: { source: "egress_connection", tool: null, + const initial = writes.firstTaint({ ...base(), kind: "taint", payload: { source: "egress_connection", tool: null, detail: `${destination.method} ${destination.host}:${destination.port}`, occurrence: exposure } }); - } catch (error) { fail(); throw error; } + exposureCommits.set(destination.connectionId, initial); + if(await initial !== true)throw new EgressAdmissionRefused("Input occurrence was not durably recorded","egress_unavailable"); + } catch { + // No occurrence means no trusted fact and no terminal exposure to append. + exposures.delete(destination.connectionId); + throw new EgressAdmissionRefused("Input occurrence recording unavailable","egress_unavailable"); + } + finally { exposureCommits.delete(destination.connectionId); } + if(db&&!hadCollection){ + const created=db.query("SELECT c.id FROM safety_collections c WHERE c.turn_id=? AND (SELECT r.id FROM safety_records r WHERE r.collection_id=c.id AND r.kind='occurrence' ORDER BY length(r.sequence),r.sequence LIMIT 1)=?").get(options.turnId,exposure.id) as {id:string}|null; + if(created){ownCollectionStarts.set(destination.connectionId,created.id);if(group){group.starts.add(created.id);for(const peer of group.members)approvalMarkers.delete(`${peer}:network`);}} + } + if(match)trustedInputs.set(destination.connectionId,{destination,revision:match.trustRevision,ruleId:match.ruleId,instance:instance!}); + if (match && !inputCurrent(destination.connectionId)) throw new EgressAdmissionRefused("Source trust changed before dispatch","source_trust_changed"); }; /** Settles once every record submitted so far has committed or failed; `recordingFailure()` is final after it. */ - const settled = async () => { while (recording.size) await Promise.all([...recording]); }; - const proxy = await startEgressProxy({ mode: options.policy.egress.mode, allow: options.policy.egress.allow, + const settled = async () => { await proxy.settled(); while (recording.size) await Promise.all([...recording]); }; + const proxy = await startEgressProxy({ pendingReservations, mode: options.policy.egress.mode, allow: options.policy.egress.allow, ...(options.bridge.admissionSafety ? { admissionSafety: options.bridge.admissionSafety } : {}), deny: options.policy.egress.deny, maxBytes: options.policy.egress.max_bytes_per_turn ?? Number.MAX_SAFE_INTEGER, outwardHosts: [...new Set([...GITHUB_API_HOSTS, ...MAIL_SUBMISSION_HOSTS, ...options.policy.outward.hosts])], outwardPorts: MAIL_SUBMISSION_PORTS, signal: options.controller.signal, observe: report, admitted, - committed: destination => { if (!destination.inference && !destination.provider && !destination.managedReference) contacted.add(destination.host); }, ...(taint ? { taint } : {}), + inputCurrent, + committed:destination=>{ + if(destination.inference||destination.provider)return; + if(destination.recipientAuthority.kind === "rule")standingRecipients.set(destination.connectionId,destination.recipientAuthority.admission); + if (!destination.managedReference && (destination.recipientApproved || !trustedInputs.has(destination.connectionId) && !standingRecipients.has(destination.connectionId))) contacted.add(destination.host); + }, ...(taint ? { taint } : {}), approveOutward: async (destination, signal) => { if (calls.covers(destination.host)) return !signal.aborted; const decision = await requestToolPermission(options.bridge, { toolUseId: crypto.randomUUID(), toolName: "Network", kind: "command", input: destination, - description: `${destination.method} to ${destination.host}:${destination.port}`, + description: `${destination.method} to ${networkAuthority(destination)}`, }, { noGrantSurface: options.origin === "voice" }); return !signal.aborted && decision.behavior === "allow"; }, }); + releaseTrust = options.trust?.subscribe(() => proxy.invalidateInputs()); + options.controller.signal.addEventListener("abort", () => releaseTrust?.(), { once: true }); const original = options.bridge; /** The bridge the backend receives, so its classifications and results open and close each call. */ const bridge: BackendBridge = { ...original, @@ -292,17 +424,17 @@ export async function prepareTurnEgress(options: { if (operation.signal.aborted) return false; let abort: (() => void) | undefined; try { - const ready = await Promise.race([settled().then(() => settleTurnSessionBinding(original, operation.signal)).catch(() => false), new Promise(resolve => { - abort = () => resolve(false); + const refusal = await Promise.race([settled().then(() => settleTurnSessionBinding(original, operation.signal)).catch(() => "session_binding_unavailable" as const), new Promise(resolve => { + abort = () => resolve("turn_cancelled"); operation.signal.addEventListener("abort", abort, { once: true }); - if (operation.signal.aborted) resolve(false); + if (operation.signal.aborted) resolve("turn_cancelled"); })]); - if (!ready) { operation.finish("denied", "session_binding_unavailable"); return false; } + if (refusal !== null) { operation.finish(refusal === "turn_cancelled" ? "cancelled" : "denied", refusal); return false; } return !operation.signal.aborted && await operation.admit(); } finally { if (abort) operation.signal.removeEventListener("abort", abort); } } }; }; - return { ...proxy, bridge, recordingFailure: () => recordingFailure, settled, + return { ...proxy, stop() { releaseTrust?.(); proxy.stop(); }, bridge, recordingFailure: () => recordingFailure, settled, inference: (method: string, target: URL, signal: AbortSignal) => relayOperation("inference", method, target, signal), relayed: (method: string, target: URL, signal: AbortSignal) => relayOperation("relayed", method, target, signal), managedReference: (target: URL, signal: AbortSignal) => settleOperation(proxy.managedReference(target, signal)) }; diff --git a/packages/ui-server/src/governance/combined-safety-reviews.ts b/packages/ui-server/src/governance/combined-safety-reviews.ts new file mode 100644 index 0000000000..62f107a061 --- /dev/null +++ b/packages/ui-server/src/governance/combined-safety-reviews.ts @@ -0,0 +1,73 @@ +/** Ordered cross-authority review. The Settings payload durably binds the exact + * single-verdict request before publication; neither authority claims atomicity. */ +import type { Database } from "bun:sqlite"; +import { z } from "zod"; +import { safetyReviewBodySchema, safetyFuturePrepareSchema, safetyFutureCommitSchema, safetyFutureStatusSchema } from "@schlessera/brain-ui-sdk/schemas"; +import type { Principal } from "../db/principals.js"; +import { TrustSettingsError, type TrustSettings, type Receipt } from "../brain/trust-settings.js"; +import { OwnerSafetyReviews } from "./owner-safety-reviews.js"; +import { eligible } from "./safety-reviews.js"; +export const combinedPrepareSchema=safetyFuturePrepareSchema; +export const combinedCommitSchema=safetyFutureCommitSchema; +export class CombinedSafetyReviews { + constructor(private readonly db:Database,private readonly reviews:OwnerSafetyReviews,private readonly settings:TrustSettings){} + private check(principal:Principal,body:z.infer){ + const projection=this.reviews.delivery(principal,body); + const reason=eligible(this.db,body,{principalId:principal.id,channel:"owner_history"}); + if(reason)throw new TrustSettingsError(reason); + if(projection.evidenceRevision!==body.expectedEvidenceRevision)throw new TrustSettingsError("stale_revision"); + if(projection.pendingCount||projection.reasons.some(r=>r==="recording_failed"||r==="capacity"))throw new TrustSettingsError("recording_pending"); + } + async prepare(principal:Principal,raw:unknown,signal?:AbortSignal){ + const {future,...body}=combinedPrepareSchema.parse(raw);this.check(principal,body); + const row=this.db.query("SELECT payload,detector FROM safety_records WHERE id=? AND kind='occurrence'").get(body.occurrenceId) as {payload:string;detector:string}|null; + const payload=row?JSON.parse(row.payload):null,provenance=payload?.occurrence?.provenance??payload?.provenance; + // Only transport-attested inputs qualify. Browser targets and display URLs + // never establish provenance, nor does a mutable repository name. + if(row?.detector!=="proxy_input"||!provenance||!(provenance.kind==="web_origin"&&provenance.verifiedBy==="host_transport"||provenance.kind==="tunnel_authority"&&provenance.verifiedBy==="host_proxy"))throw new TrustSettingsError("provenance_unavailable"); + const selector=provenance.kind==="web_origin"?{kind:"web_origin",...provenance.origin}:{kind:"tunnel_authority",...provenance.authority}; + const policy=await this.settings.list(principal.id);this.check(principal,body); + if(!policy.capabilities.originRules||future.recipientWhileRestricted&&!policy.capabilities.recipientRules)throw new TrustSettingsError("enforcement_unavailable"); + const verdict=await this.reviews.review(principal,body,null); + if(verdict.receipt.stage!=="prepared"||!verdict.receipt.requestId)throw new TrustSettingsError(verdict.receipt.reason??"unavailable"); + const prepared=await this.settings.prepare(principal.id,{version:1,expectedTrustRevision:policy.revision,expectedPolicyHash:policy.policyHash, + change:{action:"create",rule:{id:crypto.randomUUID(),label:"Reviewed source",selector,...future}}},signal,{body,requestId:verdict.receipt.requestId}); + const currentProjection=this.reviews.delivery(principal,body); + return {version:1 as const,requestId:prepared.receipt.requestId,session:body.session,occurrenceId:body.occurrenceId,review:prepared.review,rule:prepared.receipt,currentProjection}; + } + async status(principal:Principal,raw:unknown){ + const input=safetyFutureStatusSchema.parse(raw),body={...input,expectedEvidenceRevision:"0",verdict:"safe" as const}; + this.reviews.delivery(principal,body); + const selected=await this.settings.safetyStatus(principal.id,input.session,input.occurrenceId); + if(!selected){this.reviews.delivery(principal,body);return null;} + const {binding}=selected,rule:Receipt=selected.receipt; + return this.response(principal,selected.requestId,binding,rule); + } + private committed(binding:NonNullable>){ + const {body}=binding; + return !!this.db.query("SELECT 1 FROM safety_decisions WHERE request_id=? AND occurrence_id=? AND session_id=? AND history_owner_id=? AND generation=?").get(binding.requestId,body.occurrenceId,body.session.sessionId,body.session.historyOwnerId,body.session.historyGeneration); + } + private response(principal:Principal,requestId:string,binding:NonNullable>,rule:Receipt){ + const stored=this.db.query("SELECT receipt FROM safety_review_requests WHERE id=?").get(binding.requestId) as {receipt:string}|null; + const verdict=stored?JSON.parse(stored.receipt):null,committed=this.committed(binding); + const currentProjection=this.reviews.delivery(principal,binding.body); + return {version:1 as const,requestId,session:binding.body.session,occurrenceId:binding.body.occurrenceId, + stage:committed?"verdict_committed":rule.publication==="proved"?"partial":rule.publication==="unknown"?"unknown":rule.stage==="prepared"?"prepared":"refused", + rule,verdict:verdict&&!committed?{...verdict,requestId:null,operationId:null}:verdict,currentProjection}; + } + + async commit(principal:Principal,raw:unknown,signal?:AbortSignal,sessionId?:string){ + const input=combinedCommitSchema.parse(raw),binding=this.settings.safetyReview(principal.id,input.requestId); + if(!binding || sessionId !== undefined && binding.body.session.sessionId !== sessionId)throw new TrustSettingsError("request_conflict"); + this.reviews.delivery(principal,binding.body); + const published=await this.settings.commit(principal.id,input,signal,{binding,check:()=>this.check(principal,binding.body)}); + if(published.receipt.publication==="proved"&&!this.committed(binding)){ + // A retry uses the ORIGINAL verdict handle. Already-committed replay is + // immutable; a refused/expired request never becomes a fresh clear. + try { await this.reviews.review(principal,binding.body,binding.requestId); } + catch { /* Publication remains proved; delivery below still fences revoked authority. */ } + } + const current=await this.settings.read(principal.id,input.requestId); + return this.response(principal,input.requestId,binding,current.receipt); + } +} diff --git a/packages/ui-server/src/governance/effective-safety.ts b/packages/ui-server/src/governance/effective-safety.ts index 4874feb74d..c74cc4cf8f 100644 --- a/packages/ui-server/src/governance/effective-safety.ts +++ b/packages/ui-server/src/governance/effective-safety.ts @@ -3,7 +3,7 @@ import type { AdmissionSafety } from "@schlessera/brain-ui-sdk/internal"; import { Database } from "bun:sqlite"; import type { GovernanceWrites } from "./event-writes.js"; import { safetyEvidenceSequence, safetyProjection, safetyScopeTurns } from "./safety-store.js"; -import { safetyQueue } from "./safety-queue.js"; +import { safetyQueue, safetyReadVersion } from "./safety-queue.js"; /** Concrete input from the host's future trust publisher, not a policy loader or matcher. */ export interface LiveTrustRevision { @@ -20,12 +20,15 @@ export function createEffectiveSafety(db: Database, options: { signal?: AbortSignal; }): AdmissionSafety { let observed: string | undefined, evidenceRevision = "0", lastGlobalRevision = 0n; - const read = () => { - const sessionId = options.sessionId(); + let cached: { key:string; value:ReturnType } | undefined; + let pendingRead:{value:ReturnType;available:WeakMap}|undefined; + const read = (cacheAllowed = true) => { + const sessionId = options.sessionId(), authority = options.authority(), trustRevision = options.trust?.revision() ?? "0"; + const key = JSON.stringify([safetyReadVersion(db),sessionId,authority.current,authority.epoch,trustRevision]); + if (cacheAllowed && cached?.key === key) return cached.value; const projection = options.writes?.safety(options.turnId, sessionId) ?? safetyProjection(db, options.turnId, sessionId); const sequence = safetyEvidenceSequence(db, options.turnId, sessionId); const membership = safetyScopeTurns(db, options.turnId, sessionId).size; - const authority = options.authority(), trustRevision = options.trust?.revision() ?? "0"; for (const revision of [projection.evidenceRevision, sequence, trustRevision, authority.epoch]) { if (!/^(0|[1-9][0-9]{0,19})$/.test(revision) || BigInt(revision) > 18446744073709551615n) throw new Error("Invalid live safety revision"); } @@ -46,19 +49,37 @@ export function createEffectiveSafety(db: Database, options: { evidenceRevision = next.toString(); observed = marker; } lastGlobalRevision = global; - return { evidenceRevision, trustRevision, authorityEpoch: authority.epoch, + const value = { evidenceRevision, trustRevision, authorityEpoch: authority.epoch, scope: JSON.stringify([options.brain ?? db.filename, options.turnId, projection.session]), policyHash: options.policyHash, restricted: projection.restriction === "restricted", // The facade also knows a turn begun restricted: its permanent gap // covers anything it loses, so it runs under its tainted policy (#3812). recordingAvailable: options.writes?.recordingAvailable ? options.writes.recordingAvailable(options.turnId, sessionId) : !projection.reasons.some(reason => ["recording_pending", "recording_failed", "capacity"].includes(reason)), + operationRecordingAvailable: !safetyQueue(db).lostTurns.has(options.turnId) && + !db.query("SELECT 1 FROM safety_collections WHERE turn_id=? AND failure IS NOT NULL AND ended=0").get(options.turnId), authorityCurrent: authority.current }; + if (cacheAllowed) cached = { key, value }; return value; }; return { - read() { + read(excludedPending=[]) { // Projection and immutable sequence must describe one SQLite snapshot. - return db.inTransaction ? read() : Database.prototype.transaction.call(db, read).deferred() as ReturnType; + const cacheAllowed=!db.inTransaction; + const snapshot=()=>{ + const value=read(cacheAllowed);if(!excludedPending.length)return value; + // Keep the global counter, scope, taint and every failure. Only these + // exact pending reservations stop blocking their own approved peers. + if(pendingRead?.value!==value)pendingRead={value,available:new WeakMap()}; + const immutable=Object.isFrozen(excludedPending); + let recordingAvailable=immutable?pendingRead.available.get(excludedPending):undefined; + if(recordingAvailable===undefined){ + recordingAvailable=options.writes?.recordingAvailable?.(options.turnId,options.sessionId(),excludedPending) + ?? !safetyProjection(db,options.turnId,options.sessionId(),excludedPending).reasons.some(reason=>["recording_pending","recording_failed","capacity"].includes(reason)); + if(immutable)pendingRead.available.set(excludedPending,recordingAvailable); + } + return {...value,recordingAvailable}; + }; + return db.inTransaction ? snapshot() : Database.prototype.transaction.call(db,snapshot).deferred() as ReturnType; }, subscribe(changed) { const listeners = safetyQueue(db).listeners; diff --git a/packages/ui-server/src/governance/event-writes.ts b/packages/ui-server/src/governance/event-writes.ts index e264867072..6256ccdb86 100644 --- a/packages/ui-server/src/governance/event-writes.ts +++ b/packages/ui-server/src/governance/event-writes.ts @@ -102,9 +102,9 @@ export interface GovernanceWrites { safetyEnd(turnId:string):Promise; /** Marks the turn's chat failed (`cause` is error text only); the brain only when that cannot commit. */ safetyFail(turnId:string,cause?:unknown):Promise; - safety(turnId:string|null,sessionId:string|null):SafetyProjection; + safety(turnId:string|null,sessionId:string|null,excludedPending?:readonly string[]):SafetyProjection; /** Input recording must be settled and healthy before any provider delivery. */ - recordingAvailable(turnId:string|null,sessionId:string|null):boolean; + recordingAvailable(turnId:string|null,sessionId:string|null,excludedPending?:readonly string[]):boolean; /** * Validates now, throwing `GovernanceEventError` as the synchronous writer * did; the returned promise settles once the row commits, or with the @@ -226,10 +226,12 @@ export function createGovernanceWrites(db: Database, writer?: SqliteWriter): Gov void safetyFail(row.turnId,new SafetyCapacityExhausted("Safety occurrence write capacity exceeded","turn")).catch(()=>{}); throw new Error("Safety occurrence write capacity exceeded; ingestion must stop"); } - const pending = { turnId: row.turnId, sessionId: row.sessionId, source: input.kind==="taint"?(input as GovernanceEventInput<"taint">).payload.source:"legacy_unknown" as const, bytes }; + const reservation=crypto.randomUUID(); + const payload=JSON.parse(row.payload); + const pending = {id:reservation,occurrenceId:input.kind==="taint"?payload.occurrence?.id??null:payload.occurrenceId??null, turnId: row.turnId, sessionId: row.sessionId, source: input.kind==="taint"?(input as GovernanceEventInput<"taint">).payload.source:"legacy_unknown" as const, bytes }; pendingTaints.add(pending); shared.bytes += bytes; notifySafetyChanged(db); - const reservation=crypto.randomUUID();let reserved=false; + let reserved=false; const stored = call("safetyReserve",row,reservation,bytes,!!options.beforeDelivery) .then(()=>{reserved=true;return call<{id:number;recorded:boolean;discharged?:boolean}>("safetyCommit",row,reservation,options.discharge??null);}); return stored.catch(error => { @@ -291,19 +293,19 @@ export function createGovernanceWrites(db: Database, writer?: SqliteWriter): Gov await call("safetyEnd",turnId,shared.unscopedLoss||shared.lostTurns.has(turnId)); }, safetyFail, - safety: (turnId,sessionId)=>snapshot(()=>{ - const projection=safetyProjection(db,turnId,sessionId); - const local=pendingInScope(turnId,sessionId).length,lost=shared.failed||lostInScope(turnId,sessionId); + safety: (turnId,sessionId,excludedPending=[])=>snapshot(()=>{ + const projection=safetyProjection(db,turnId,sessionId,excludedPending); + const local=pendingInScope(turnId,sessionId).filter(p=>!excludedPending.includes(p.id)).length,lost=shared.failed||lostInScope(turnId,sessionId); if(local||lost){projection.restriction="restricted";projection.pendingCount=Math.max(local,projection.pendingCount); if(local&&!projection.reasons.includes("recording_pending"))projection.reasons.push("recording_pending"); if(lost){projection.coverage.state="incomplete";if(!projection.reasons.includes("recording_failed"))projection.reasons.push("recording_failed");}} return projection; }), - recordingAvailable(turnId,sessionId){ + recordingAvailable(turnId,sessionId,excludedPending=[]){ return snapshot(()=>{ if(covered(turnId))return true; - if(shared.failed||lostInScope(turnId,sessionId)||pendingInScope(turnId,sessionId).length)return false; - const state=safetyProjection(db,turnId,sessionId); + if(shared.failed||lostInScope(turnId,sessionId)||pendingInScope(turnId,sessionId).some(p=>!excludedPending.includes(p.id)))return false; + const state=safetyProjection(db,turnId,sessionId,excludedPending); return !state.reasons.some(reason=>["recording_failed","recording_pending","capacity"].includes(reason)); }); }, diff --git a/packages/ui-server/src/governance/events.ts b/packages/ui-server/src/governance/events.ts index 88735a6d9d..b8607a1862 100644 --- a/packages/ui-server/src/governance/events.ts +++ b/packages/ui-server/src/governance/events.ts @@ -1,3 +1,4 @@ +import { safetyAdmissionSchema } from "@schlessera/brain-ui-sdk/internal"; import type { Database } from "bun:sqlite"; import { z } from "zod"; import { appendSafetyEvent, bindSafetyCollection } from "./safety-store.js"; @@ -78,7 +79,7 @@ export const GOVERNANCE_EVENT_SCHEMAS = { method: z.string().min(1).max(20), path: z.string().max(16384).optional(), bytes: count, accounting: z.enum(["http_wire_bound", "opaque_bytes"]), durationMs: amount, outcome: z.enum(["completed", "denied", "failed", "cancelled"]), - inference: z.literal(true).optional(), provider: z.literal(true).optional(), managedReference: z.literal(true).optional(), reason: z.string().max(200).optional(), + inference: z.literal(true).optional(), provider: z.literal(true).optional(), managedReference: z.literal(true).optional(), trustedSource: z.literal(true).optional(), recipientApproved: z.literal(true).optional(), dispatched: z.boolean().optional(), failureReason: z.enum(["budget","safety_changed","policy_denied","unavailable","cancelled"]).optional(), standingRecipient: z.literal(true).optional(), recipientAdmission: safetyAdmissionSchema.options[1].omit({trusted:true}).extend({instance:safetyAdmissionSchema.options[1].shape.trustRevision.optional()}).optional(), reason: z.string().max(200).optional(), })), steering_change: kind(1, z.strictObject({ path, sequence: count, tainted: z.literal(true).optional(), diff --git a/packages/ui-server/src/governance/occurrence.ts b/packages/ui-server/src/governance/occurrence.ts index e4f49c8e97..6377319c6f 100644 --- a/packages/ui-server/src/governance/occurrence.ts +++ b/packages/ui-server/src/governance/occurrence.ts @@ -1,8 +1,9 @@ /** Host collection metadata. No trust matching or human verdict authority lives here. */ import { z } from "zod"; +import { safetyOccurrenceAdmissionSchema } from "@schlessera/brain-ui-sdk/internal"; const id = z.string().regex(/^[A-Za-z0-9_-]{1,128}$/); -export const OccurrenceSchema = z.strictObject({ +export const OccurrenceSchema = safetyOccurrenceAdmissionSchema.safeExtend({ id, epochId: id, operationId: id.nullable(), signalId: id, exposureId: id, /** Captured by the host collector, never inferred from display content. */ entry: z.strictObject({kind:z.literal("tool"),toolUseId:id}).optional(), @@ -10,12 +11,7 @@ export const OccurrenceSchema = z.strictObject({ "compute_input", "unproxied_shell_input", "proxy_input", "explicit_untrusted_input"]), // Observation of a result is not proof that input delivery has ended. exposure: z.enum(["open", "finalized", "interrupted_unknown"]), - provenance: z.union([z.null(), - z.strictObject({kind:z.literal("web_origin"),origin:z.strictObject({scheme:z.enum(["http","https"]),host:z.string().max(253),port:z.number().int().min(1).max(65535)}),verifiedBy:z.literal("host_transport")}), - z.strictObject({kind:z.literal("tunnel_authority"),authority:z.strictObject({host:z.string().max(253),port:z.number().int().min(1).max(65535)}),verifiedBy:z.literal("host_proxy")}), - ]), - admission: z.strictObject({trusted:z.literal(false),policyHash:z.string().regex(/^[a-f0-9]{64}$/).nullable(),trustRevision:z.literal("0")}).optional(), -}); +}).strict(); export type Occurrence = z.infer; export function occurrence(epochId: string, detector: Occurrence["detector"], operationId: string | null, diff --git a/packages/ui-server/src/governance/owner-safety-reviews.ts b/packages/ui-server/src/governance/owner-safety-reviews.ts index e69c4d213d..8219496a40 100644 --- a/packages/ui-server/src/governance/owner-safety-reviews.ts +++ b/packages/ui-server/src/governance/owner-safety-reviews.ts @@ -15,6 +15,8 @@ function epoch(p: Principal, brainKey: string): SafetyReviewAuthority { } export class OwnerSafetyReviews { + private trust?: import("../brain/trust-settings.js").TrustSettings; + enableFutureRules(trust: import("../brain/trust-settings.js").TrustSettings) { this.trust = trust; } private readonly pending = new Map(); constructor(private readonly db: Database, private readonly writes: GovernanceWrites, private readonly mode: AuthMode, private readonly brainKey: string) {} @@ -23,9 +25,11 @@ export class OwnerSafetyReviews { const current = resolvePrincipal(this.db, principal.id); return !!current && JSON.stringify(epoch(current,this.brainKey)) === JSON.stringify(epoch(principal,this.brainKey)) && isUsablePrincipal(current, Date.now()); } + /** Standing-rule support is offered outside the legacy strict DTO. */ + futureRules(principal: Principal): boolean { return this.authorized(principal) && !!this.trust; } capabilities(principal: Principal): SafetyCapabilities { const review = this.authorized(principal); - return { ...SAFETY_READ_CAPABILITIES, review, readOnlyReason:review ? null : "owner_required", + return { ...SAFETY_READ_CAPABILITIES, review, originRules: false, recipientRules: false, readOnlyReason:review ? null : "owner_required", limits:{ ...SAFETY_READ_CAPABILITIES.limits, reviewBodyBytes:16384, reviewLifetimeMs:900000, receiptLifetimeMs:86400000 } }; } private current(principal: Principal, body: SafetyReviewBody) { diff --git a/packages/ui-server/src/governance/safety-history.ts b/packages/ui-server/src/governance/safety-history.ts index c229b4d2a5..3dd2e2d237 100644 --- a/packages/ui-server/src/governance/safety-history.ts +++ b/packages/ui-server/src/governance/safety-history.ts @@ -13,7 +13,7 @@ export class SafetyReadUnavailable extends Error { constructor(readonly reason: Reason = "unavailable") { super(reason); } } interface Snapshot { id:string; principalId:string; target:SafetyTarget; identity:SafetyIdentity; highWater:string; - projection:SafetyPage["projection"]; membership:string; expiresAt:number; pruned:number; bytes:number; entries:boolean } + projection:SafetyPage["projection"]; membership:string; expiresAt:number; pruned:number; bytes:number; entries:boolean; admissions:boolean } interface Row { id:string; sequence:string; observed_at:number; kind:string; occurrence_id:string; source:string|null; detector:string|null; state:string|null; payload:string; detail_pruned:number; turn_id:string; collection_id:string } const same = (a:unknown,b:unknown) => JSON.stringify(a)===JSON.stringify(b); @@ -26,7 +26,7 @@ const wireId = (value:string) => { export class SafetyHistory { private readonly subscriptions = new Mapboolean; - send:(value:SafetyUpdate|Unavailable)=>void; busy:boolean; entries:boolean }>(); + send:(value:SafetyUpdate|Unavailable)=>void; busy:boolean; entries:boolean; admissions:boolean }>(); private readonly snapshots = new Map(); private readonly cursors = new Map(); private retainedBytes = 0; @@ -104,7 +104,7 @@ export class SafetyHistory { if(failed){p.coverage.state="incomplete";if(!p.reasons.includes("recording_failed"))p.reasons.push("recording_failed");}} return p as SafetyPage["projection"]; } - private records(identity:SafetyIdentity,after:string,through:string,limit:number,entries:boolean):SafetyRecord[] { + private records(identity:SafetyIdentity,after:string,through:string,limit:number,entries:boolean,admissions:boolean):SafetyRecord[] { const {sql,args}=this.scope(identity); const rows=this.db.query(`SELECT * FROM ( SELECT r.*,c.turn_id FROM safety_records r JOIN safety_collections c ON c.id=r.collection_id WHERE ${sql} @@ -125,7 +125,7 @@ export class SafetyHistory { // model text, prompt or page body cross this read boundary. return {...common,kind:"occurrence",epochId:o?.epochId??r.collection_id,detector:r.detector,source:r.source??"legacy_unknown",operationId:o?.operationId??null, signalId:o?.signalId??null,exposureId:o?.exposureId??null,exposure:r.state??"interrupted_unknown",summary:r.source==="egress_connection"?"Network input; operation attribution unavailable":"Recorded input exposure", - provenance:o?.provenance??null,...(entries&&(o?.entry??p.entry)?{entry:o?.entry??p.entry}:{})} as SafetyRecord; + provenance:o?.provenance??p.provenance??null,...(admissions&&(o?.admission??p.admission)?{admission:o?.admission??p.admission}:{}),...(entries&&(o?.entry??p.entry)?{entry:o?.entry??p.entry}:{})} as SafetyRecord; }); } private drop(id:string):void { @@ -141,7 +141,7 @@ export class SafetyHistory { return ()=>{const left=this.pendingReads.get(principal.id)!-1;if(left)this.pendingReads.set(principal.id,left);else this.pendingReads.delete(principal.id);}; } /** Every await precedes fresh authority, identity and clock checks. */ - async read(principal:Principal,target:SafetyTarget,cursor:string|null=null,limit:number=50,entries=false):Promise { + async read(principal:Principal,target:SafetyTarget,cursor:string|null=null,limit:number=50,entries=false,admissions=false):Promise { if(!Number.isInteger(limit)||limit<1||limit>100||cursor!==null&&cursor.length>512)throw new SafetyReadUnavailable(); this.authorize(principal,target); const release=this.reserveRead(principal); @@ -151,7 +151,7 @@ export class SafetyHistory { let snapshot:Snapshot,after="0"; if(cursor!==null){ const position=this.cursors.get(cursor),s=position&&this.snapshots.get(position.snapshotId); - if(!s||s.principalId!==principal.id||!same(s.target,target)||s.entries!==entries)throw new SafetyReadUnavailable("expired"); + if(!s||s.principalId!==principal.id||!same(s.target,target)||s.entries!==entries||s.admissions!==admissions)throw new SafetyReadUnavailable("expired"); snapshot=s;after=position!.after; if(!same(identity,s.identity))throw new SafetyReadUnavailable("generation_changed"); if(this.membership(identity,s.highWater)!==s.membership)throw new SafetyReadUnavailable("gap"); @@ -160,10 +160,10 @@ export class SafetyHistory { if(this.snapshots.size>=256||[...this.snapshots.values()].filter(s=>s.principalId===principal.id).length>=32)throw new SafetyReadUnavailable("capacity"); const projection=this.projection(identity),size=bytes(projection)+2048; if(this.retainedBytes+size>4194304)throw new SafetyReadUnavailable("capacity"); - snapshot={id:crypto.randomUUID(),principalId:principal.id,target,identity,projection,highWater:projection.evidenceRevision,membership:this.membership(identity,projection.evidenceRevision),expiresAt:this.clock()+300000,pruned:this.pruned(identity),bytes:size,entries}; + snapshot={id:crypto.randomUUID(),principalId:principal.id,target,identity,projection,highWater:projection.evidenceRevision,membership:this.membership(identity,projection.evidenceRevision),expiresAt:this.clock()+300000,pruned:this.pruned(identity),bytes:size,entries,admissions}; this.snapshots.set(snapshot.id,snapshot);this.retainedBytes+=size; } - const fetched=this.records(identity,after,snapshot.highWater,limit+1,snapshot.entries),records:SafetyRecord[]=[]; + const fetched=this.records(identity,after,snapshot.highWater,limit+1,snapshot.entries,snapshot.admissions),records:SafetyRecord[]=[]; const page:SafetyPage={version:1,identity,snapshotId:snapshot.id,cursor,highWater:snapshot.highWater,projection:snapshot.projection,records,nextCursor:null,snapshotComplete:false,detailPruned:snapshot.pruned>0}; for(const record of fetched.slice(0,limit)){if(bytes({...page,records:[...records,record]})>261000)break;records.push(record);} if(fetched.length&&!records.length)throw new SafetyReadUnavailable("capacity"); @@ -184,13 +184,13 @@ export class SafetyHistory { } async delta(principal:Principal,identity:SafetyIdentity,after:string,snapshotId:string):Promise { const anchor=this.anchor(principal,identity,after,snapshotId); - const result=await this.readDelta(principal,identity,after,anchor.membership,anchor.entries); + const result=await this.readDelta(principal,identity,after,anchor.membership,anchor.entries,anchor.admissions); this.anchor(principal,identity,after,snapshotId); this.delivery(principal,identity,snapshotId,result.update.projection); if(this.membership(identity,result.update.toRevision)!==result.membership)throw new SafetyReadUnavailable("gap"); return result.update; } - private async readDelta(principal:Principal,identity:SafetyIdentity,after:string,membership:string,entries:boolean):Promise<{update:SafetyUpdate;membership:string}> { + private async readDelta(principal:Principal,identity:SafetyIdentity,after:string,membership:string,entries:boolean,admissions:boolean):Promise<{update:SafetyUpdate;membership:string}> { const target:SafetyTarget="sessionId" in identity?{sessionId:identity.sessionId}:identity; this.authorize(principal,target);const release=this.reserveRead(principal); try{await this.settled(); @@ -199,7 +199,7 @@ export class SafetyHistory { if(this.membership(identity,after)!==membership)throw new SafetyReadUnavailable("gap"); const projection=this.projection(identity); if(BigInt(after)>BigInt(projection.evidenceRevision))throw new SafetyReadUnavailable("gap"); - const records=this.records(identity,after,projection.evidenceRevision,101,entries); + const records=this.records(identity,after,projection.evidenceRevision,101,entries,admissions); const update:SafetyUpdate={version:1,identity,fromRevision:after,toRevision:projection.evidenceRevision,projection,records}; if(records.length>100||bytes(update)>262000)throw new SafetyReadUnavailable("capacity"); this.authorize(principal,target);this.clock(); @@ -210,7 +210,7 @@ export class SafetyHistory { subscribe(key:object,principal:Principal,identity:SafetyIdentity,revision:string,snapshotId:string,valid:()=>boolean,send:(value:SafetyUpdate|Unavailable)=>void):void { if(!this.subscriptions.has(key)&&this.subscriptions.size>=256)throw new SafetyReadUnavailable("capacity"); const anchor=this.anchor(principal,identity,revision,snapshotId); - this.subscriptions.set(key,{principal,identity,revision,membership:anchor.membership,projectionHash:fingerprint(anchor.projection),valid,send,busy:false,entries:anchor.entries});this.poll(); + this.subscriptions.set(key,{principal,identity,revision,membership:anchor.membership,projectionHash:fingerprint(anchor.projection),valid,send,busy:false,entries:anchor.entries,admissions:anchor.admissions});this.poll(); } unsubscribe(key:object):void {this.subscriptions.delete(key);} revoke(principalIds:readonly string[]):void { @@ -242,7 +242,7 @@ export class SafetyHistory { for(const [key,s] of this.subscriptions){ if(!s.valid()||!this.valid(s.principal)){this.subscriptions.delete(key);continue;} if(s.busy)continue;s.busy=true; - void this.readDelta(s.principal,s.identity,s.revision,s.membership,s.entries).then(({update,membership})=>{ + void this.readDelta(s.principal,s.identity,s.revision,s.membership,s.entries,s.admissions).then(({update,membership})=>{ if(this.subscriptions.get(key)!==s||!s.valid()||!this.valid(s.principal))return; try{this.delivery(s.principal,s.identity,undefined,update.projection); if(this.membership(s.identity,update.toRevision)!==membership)throw new SafetyReadUnavailable("gap"); diff --git a/packages/ui-server/src/governance/safety-queue.ts b/packages/ui-server/src/governance/safety-queue.ts index 5114c982f6..7bab1cdd92 100644 --- a/packages/ui-server/src/governance/safety-queue.ts +++ b/packages/ui-server/src/governance/safety-queue.ts @@ -1,8 +1,8 @@ /** Connection-local ingestion state shared by every facade and host recovery. */ import type { Database } from "bun:sqlite"; import type { SessionTaint } from "./session-taint.js"; -type PendingSafety = {turnId:string|null;sessionId:string|null;source:SessionTaint["source"];bytes:number}; -const queues=new WeakMap;bytes:number;failed:boolean;inflight:number; +type PendingSafety = {id:string;occurrenceId:string|null;turnId:string|null;sessionId:string|null;source:SessionTaint["source"];bytes:number}; +const queues=new WeakMap;bytes:number;failed:boolean;inflight:number; /** The safety revision when this process latched in memory; null when unreadable. */ latchRevision:string|null; lostTurns:Set;unscopedLoss:boolean;listeners:Set<()=>void>;recovery:{timer:ReturnType|null;attempt:number}; @@ -12,11 +12,18 @@ const queues=new WeakMap;bytes:number;faile recording:Map>>}>(); export function safetyQueue(db:Database){ let queue=queues.get(db); - if(!queue){queue={pending:new Set(),bytes:0,failed:false,inflight:0,latchRevision:null,lostTurns:new Set(),unscopedLoss:false,listeners:new Set(),recovery:{timer:null,attempt:0},lossCause:null,recording:new Map()};queues.set(db,queue);} + if(!queue){queue={generation:0n,pending:new Set(),bytes:0,failed:false,inflight:0,latchRevision:null,lostTurns:new Set(),unscopedLoss:false,listeners:new Set(),recovery:{timer:null,attempt:0},lossCause:null,recording:new Map()};queues.set(db,queue);} return queue; } +/** Constant-size cache identity across local writes, FULL writers and local pending/loss overlays. */ +export function safetyReadVersion(db:Database):string { + const row=db.query("SELECT revision,total_changes() AS changes FROM safety_meta WHERE singleton=1").get() as {revision:string;changes:number}; + const external=db.query("PRAGMA data_version").get() as {data_version:number}; + return JSON.stringify([row.revision,row.changes,external.data_version,db.inTransaction,safetyQueue(db).generation.toString()]); +} export function notifySafetyChanged(db:Database):void { + safetyQueue(db).generation++; for(const listener of [...safetyQueue(db).listeners]) { try { listener(); } catch { /* The synchronous dispatch read still fails closed. */ } } diff --git a/packages/ui-server/src/governance/safety-reviews.ts b/packages/ui-server/src/governance/safety-reviews.ts index 7bae539cce..de08fe73f7 100644 --- a/packages/ui-server/src/governance/safety-reviews.ts +++ b/packages/ui-server/src/governance/safety-reviews.ts @@ -74,16 +74,17 @@ export function safetyReviewTarget(db: Database, body: SafetyReviewBody, princip || !sameAccount(db, { principalId: owner.principal_id, account: owner.principal_account }, principalId))) return "unavailable"; return null; } -function eligible(db: Database, body: SafetyReviewBody, actor: SafetyReviewer): string | null { - const r = db.query(`SELECT c.turn_id,c.principal_id,c.principal_account,c.generation,r.state,COALESCE((SELECT x.state FROM safety_records x +export function eligible(db: Database, body: SafetyReviewBody, actor: SafetyReviewer): string | null { + const r = db.query(`SELECT c.turn_id,c.principal_id,c.principal_account,c.generation,r.state,coalesce(json_extract(r.payload,'$.occurrence.admission.trusted'),json_extract(r.payload,'$.admission.trusted'),0) trusted,COALESCE((SELECT x.state FROM safety_records x WHERE x.occurrence_id=r.id AND x.kind='exposure' ORDER BY length(x.sequence) DESC,x.sequence DESC LIMIT 1),r.state) final_state FROM safety_records r JOIN safety_collections c ON c.id=r.collection_id WHERE r.id=? AND r.kind='occurrence'`) - .get(body.occurrenceId) as { turn_id: string; principal_id: string | null; principal_account: string | null; generation: string; final_state: string } | null; + .get(body.occurrenceId) as { turn_id: string; principal_id: string | null; principal_account: string | null; generation: string; final_state: string; trusted: number } | null; // The aggregate also includes adopted provisional collections. Use its // canonical membership; a direct session_id filter strands those events. if (!r || !sameAccount(db, { principalId: r.principal_id, account: r.principal_account }, actor.principalId) || r.generation !== body.session.historyGeneration || !safetyScopeTurns(db, null, body.session.sessionId).has(r.turn_id) || db.query("SELECT 1 FROM safety_retired_turns WHERE turn_id=?").get(r.turn_id)) return "unavailable"; + if (r.trusted) return "already_resolved"; if (db.query("SELECT 1 FROM safety_decisions WHERE occurrence_id=?").get(body.occurrenceId)) return "already_resolved"; return r.final_state === "finalized" ? null : "not_finalized"; } @@ -135,6 +136,23 @@ export function commitSafetyReview(db: Database, requestId: string, value: Safet if (!row || row.principal_id !== actor.principalId || row.channel !== actor.channel) return receipt(body, requestId, null, "unavailable", null); if (row.body_hash !== fingerprint(body, actor)) return receipt(body, requestId, row.operation_id, "request_conflict", null); + // A combined handle cannot bypass publication through the individual HTTP + // endpoint or another caller of this FULL worker procedure. Check on the + // acquired write connection, before committing OR replaying its verdict. + const publication = db.query(`SELECT proof,payload,receipt,brain_id,principal_id,authority + FROM trust_settings_operations WHERE json_extract(payload,'$.safetyReview.requestId')=?`).get(requestId) as + {proof:string|null;payload:string;receipt:string;brain_id:string;principal_id:string;authority:string}|null; + if (publication) { + const proof = publication.proof ? JSON.parse(publication.proof) : null; + const rule = JSON.parse(publication.receipt), payload = JSON.parse(publication.payload); + if (!proof || rule.publication !== "proved" || proof.operationId !== rule.operationId + || proof.reviewedBytesHash !== payload.proposedHash || proof.brain !== publication.brain_id + || proof.principal !== actor.principalId || publication.principal_id !== actor.principalId + || proof.authority !== publication.authority) + return receipt(body,requestId,row.operation_id,"publication_unproven",null); + // Refusal above is non-terminal: only THIS still-valid handle may finish + // after the protected publisher durably records its own publication proof. + } if (row.terminal_at !== null) { if (clock(now) >= row.terminal_at + RECEIPT_MS) return receipt(body, requestId, row.operation_id, "request_expired", null); return JSON.parse(row.receipt) as SafetyReviewReceipt; diff --git a/packages/ui-server/src/governance/safety-store.ts b/packages/ui-server/src/governance/safety-store.ts index 6bdbfa967a..5d9d99e099 100644 --- a/packages/ui-server/src/governance/safety-store.ts +++ b/packages/ui-server/src/governance/safety-store.ts @@ -2,7 +2,7 @@ import { Database } from "bun:sqlite"; import { safetyQueue } from "./safety-queue.js"; import { assertLive,ChatRetiredError } from "../ws/chat-lifecycle.js"; -import { occurrence, type Occurrence } from "./occurrence.js"; +import { occurrence, OccurrenceSchema, type Occurrence } from "./occurrence.js"; import type { GovernanceEventRow } from "./events.js"; import { principalAccount, sameAccount } from "../middleware/account-partition.js"; @@ -247,7 +247,7 @@ export function beginSafetyCollection(db:Database,input:SafetyCollectionInput):s safetyProjection(db,null,input.sourceSessionId); // Also validates retirement. db.query("UPDATE safety_collections SET gap=CASE WHEN restricted_begin=1 THEN gap ELSE 'inherited_history_not_reconstructed' END WHERE id=?").run(input.bindingId); const records=db.query(`SELECT r.* FROM safety_records r JOIN safety_collections c ON c.id=r.collection_id - WHERE c.session_id=? AND r.kind='occurrence' AND NOT EXISTS(SELECT 1 FROM safety_decisions d WHERE d.occurrence_id=r.id)`).iterate(input.sourceSessionId); + WHERE c.session_id=? AND r.kind='occurrence' AND coalesce(json_extract(r.payload,'$.occurrence.admission.trusted'),json_extract(r.payload,'$.admission.trusted'),0) != 1 AND NOT EXISTS(SELECT 1 FROM safety_decisions d WHERE d.occurrence_id=r.id)`).iterate(input.sourceSessionId); for(const r of records){const payload=JSON.parse(r.payload);payload.occurrence=occurrence(input.bindingId,(r.detector??"tool_file_input") as Occurrence["detector"],null,"interrupted_unknown"); appendRecord(db,collection(db,input.turnId)!,payload.occurrence.id,"occurrence",payload.occurrence.id,r.source,r.detector,"interrupted_unknown",payload,input.at);} } @@ -345,7 +345,7 @@ export function appendSafetyEvent(db:Database,row:GovernanceEventRow,reserved=fa } live(db,c,reserved); if(row.kind==="taint"){ - const observed=payload.occurrence as Occurrence|undefined; + const observed=payload.occurrence === undefined ? undefined : OccurrenceSchema.parse(payload.occurrence); if(!observed)db.query("UPDATE safety_collections SET gap=COALESCE(gap,'uninstrumented_backend_input') WHERE id=?").run(c.id); if(observed&&JSON.parse(c.acknowledged).length&&observed.epochId!==c.id)throw new SafetyUnavailable("Safety occurrence epoch mismatch"); const id=observed?.id??row.dedupeKey??crypto.randomUUID(); @@ -426,11 +426,11 @@ export interface SafetyProjection { session:SafetySessionKey|null;evidenceRevisi pendingCount:number;restriction:"normal"|"restricted";reasons:string[]; coverage:{detectorVersion:1;state:"complete"|"incomplete"|"unknown";epochs:{id:string;backendId:string;startSequence:string;endSequence:string|null;mandatory:readonly string[];acknowledged:string[];status:string;reason:string|null}[];exclusions:string[]} } /** Count is derived from all compact identities, never a detail page or Activity. */ -export function safetyProjection(db:Database,turnId:string|null,sessionId:string|null):SafetyProjection { +export function safetyProjection(db:Database,turnId:string|null,sessionId:string|null,excludedPending:readonly string[]=[]):SafetyProjection { // This callback only reads. Use a native deferred snapshot so a held write // worker does not block pending-input admission on the event loop. - if(db.inTransaction)return readSafetyProjection(db,turnId,sessionId); - return Database.prototype.transaction.call(db,()=>readSafetyProjection(db,turnId,sessionId)).deferred() as SafetyProjection; + if(db.inTransaction)return readSafetyProjection(db,turnId,sessionId,excludedPending); + return Database.prototype.transaction.call(db,()=>readSafetyProjection(db,turnId,sessionId,excludedPending)).deferred() as SafetyProjection; } function safetyScope(db:Database,turnId:string|null,sessionId:string|null) { const s=sessionId?one(db,"SELECT * FROM safety_sessions WHERE session_id=?",sessionId):null; @@ -452,18 +452,19 @@ export function safetyScopeTurns(db:Database,turnId:string|null,sessionId:string return turns; } /** Last immutable append in the same canonical scope as the aggregate. */ -export function safetyEvidenceSequence(db:Database,turnId:string|null,sessionId:string|null):string { +export function safetyEvidenceSequence(db:Database,turnId:string|null,sessionId:string|null,excludedOccurrenceId:string|readonly string[]|null=null,excludedCollectionStart:string|readonly string[]|null=null):string { const {scope,args}=safetyScope(db,turnId,sessionId); + const excluded = (value:string|readonly string[]|null) => JSON.stringify(value===null?[]:typeof value==="string"?[value]:value); return one<{sequence:string}|null>(db,`SELECT sequence FROM ( - SELECT r.sequence FROM safety_records r JOIN safety_collections c ON c.id=r.collection_id WHERE ${scope} + SELECT r.sequence FROM safety_records r JOIN safety_collections c ON c.id=r.collection_id WHERE ${scope} AND (r.occurrence_id IS NULL OR r.occurrence_id NOT IN (SELECT value FROM json_each(?))) UNION ALL SELECT d.sequence FROM safety_decisions d JOIN safety_records r ON r.id=d.occurrence_id JOIN safety_collections c ON c.id=r.collection_id WHERE ${scope} UNION ALL SELECT b.sequence FROM safety_bindings b JOIN safety_collections c ON c.id=b.binding_id WHERE ${scope} - UNION ALL SELECT c.start_revision FROM safety_collections c WHERE ${scope} + UNION ALL SELECT c.start_revision FROM safety_collections c WHERE ${scope} AND c.id NOT IN (SELECT value FROM json_each(?)) UNION ALL SELECT c.end_revision FROM safety_collections c WHERE ${scope} AND c.end_revision IS NOT NULL - ) ORDER BY length(sequence) DESC,sequence DESC LIMIT 1`,...args,...args,...args,...args,...args)?.sequence??"0"; + ) ORDER BY length(sequence) DESC,sequence DESC LIMIT 1`,...args,excluded(excludedOccurrenceId),...args,...args,...args,excluded(excludedCollectionStart),...args)?.sequence??"0"; } -function readSafetyProjection(db:Database,turnId:string|null,sessionId:string|null):SafetyProjection { +function readSafetyProjection(db:Database,turnId:string|null,sessionId:string|null,excludedPending:readonly string[]):SafetyProjection { const {s,scope,args}=safetyScope(db,turnId,sessionId); const cs=db.query(`SELECT c.* FROM safety_collections c WHERE ${scope} ORDER BY c.rowid`).all(...args) as Collection[]; const epochs=cs.slice(0,128).map(c=>{ @@ -475,11 +476,11 @@ function readSafetyProjection(db:Database,turnId:string|null,sessionId:string|nu const unknown=cs.length===0||cs.length>128||cs.some(c=>c.gap||c.failure||JSON.parse(c.acknowledged).length(db,`SELECT COUNT(*) n FROM safety_records r JOIN safety_collections c ON c.id=r.collection_id - WHERE r.kind='occurrence' AND ${scope} AND NOT EXISTS(SELECT 1 FROM safety_decisions d WHERE d.occurrence_id=r.id)`,...args); + WHERE r.kind='occurrence' AND coalesce(json_extract(r.payload,'$.occurrence.admission.trusted'),json_extract(r.payload,'$.admission.trusted'),0) != 1 AND ${scope} AND NOT EXISTS(SELECT 1 FROM safety_decisions d WHERE d.occurrence_id=r.id)`,...args); const first=one<{id:string}|null>(db,`SELECT r.id FROM safety_records r JOIN safety_collections c ON c.id=r.collection_id - WHERE r.kind='occurrence' AND ${scope} AND NOT EXISTS(SELECT 1 FROM safety_decisions d WHERE d.occurrence_id=r.id) + WHERE r.kind='occurrence' AND coalesce(json_extract(r.payload,'$.occurrence.admission.trusted'),json_extract(r.payload,'$.admission.trusted'),0) != 1 AND ${scope} AND NOT EXISTS(SELECT 1 FROM safety_decisions d WHERE d.occurrence_id=r.id) ORDER BY length(r.sequence),r.sequence LIMIT 1`,...args); - const pending=one<{n:number}>(db,`SELECT COUNT(*) n FROM safety_pending p JOIN safety_collections c ON c.id=p.collection_id WHERE ${scope}`,...args).n; + const pending=one<{n:number}>(db,`SELECT COUNT(*) n FROM safety_pending p JOIN safety_collections c ON c.id=p.collection_id WHERE ${scope} AND NOT EXISTS (SELECT 1 FROM json_each(?) excluded WHERE excluded.value=p.id)`,...args,JSON.stringify(excludedPending)).n; const reasons:string[]=[]; if(aggregate.n)reasons.push("unresolved");if(unknown)reasons.push("coverage_unknown");if(pending)reasons.push("recording_pending"); // Ended failures remain in epoch coverage forever. Once explicit quiescent @@ -513,8 +514,9 @@ export function pruneSafetyDetail(db:Database,before:number):number { return db.transaction(()=>{ const rows=db.query("SELECT id,payload FROM safety_records WHERE observed_at 0 + AND coalesce(json_extract(payload, '$.dispatched'), 1) = 1 AND json_extract(payload, '$.inference') IS NULL AND json_extract(payload, '$.provider') IS NULL - AND json_extract(payload, '$.managedReference') IS NULL`).all(sessionId) as { host: string }[]; - return rows.map(row => row.host); + AND json_extract(payload, '$.managedReference') IS NULL + AND (json_extract(payload, '$.recipientApproved') = 1 OR + (json_extract(payload, '$.trustedSource') IS NULL AND json_extract(payload, '$.standingRecipient') IS NULL))`).all(sessionId) as { host: string }[]; + return [...new Set(rows.map(row => canonicalEgressHost(row.host)))]; } diff --git a/packages/ui-server/src/routes/owner-safety-review.ts b/packages/ui-server/src/routes/owner-safety-review.ts index 0dc47a337b..4dce795ec8 100644 --- a/packages/ui-server/src/routes/owner-safety-review.ts +++ b/packages/ui-server/src/routes/owner-safety-review.ts @@ -1,5 +1,7 @@ +import { CombinedSafetyReviews, combinedPrepareSchema, combinedCommitSchema } from "../governance/combined-safety-reviews.js"; +import { TrustSettingsError } from "../brain/trust-settings.js"; import { Hono } from "hono"; -import { safetyReviewBodySchema } from "@schlessera/brain-ui-sdk/schemas"; +import { safetyReviewBodySchema, safetyFutureStatusSchema } from "@schlessera/brain-ui-sdk/schemas"; import type { AppEnv } from "../app-env.js"; import { OwnerSafetyReviews, OwnerSafetyUnavailable } from "../governance/owner-safety-reviews.js"; import { readJsonBody } from "../middleware/body-limit.js"; @@ -8,7 +10,7 @@ import { requireOwner } from "../middleware/require-owner.js"; /** These browser mutations require a present exact Origin, even for clients * claiming same-origin fetch metadata. Unrelated routes keep their policy. */ -export function createOwnerSafetyReviewRoutes(reviews: OwnerSafetyReviews, trustProxy: boolean): Hono { +export function createOwnerSafetyReviewRoutes(reviews: OwnerSafetyReviews, trustProxy: boolean, combined?: CombinedSafetyReviews): Hono { const app = new Hono(); const prefix = "/sessions/:id/safety/reviews"; app.use(`${prefix}/*`, async (c,next)=>{ @@ -25,6 +27,30 @@ export function createOwnerSafetyReviewRoutes(reviews: OwnerSafetyReviews, trust } catch { return c.json({code:"unauthorized",reason:"cross_origin_rejected",retryable:false},403); } return next(); }, requireOwner(), requireJson()); + if (combined) app.post(`${prefix}/future/status`, async c => { + try { + const raw=await readJsonBody(c,16384); + if(raw instanceof Response)return raw; + const input=safetyFutureStatusSchema.parse(raw); + if(input.session.sessionId!==c.req.param("id")||new URL(c.req.url).search)return c.json({code:"unavailable"},400); + return c.json(await combined.status(c.get("principal")!,input)); + }catch{return c.json({code:"unavailable",retryable:false},404);} + }); + if (combined) for (const action of ["prepare", "commit"] as const) app.post(`${prefix}/future/${action}`, async c => { + try { + const raw = await readJsonBody(c, 16384); + if (raw instanceof Response) return c.json({code:"capacity",reason:"request_too_large",retryable:false},413); + const input = (action === "prepare" ? combinedPrepareSchema : combinedCommitSchema).parse(raw); + if (new URL(c.req.url).search || action === "prepare" && (input as import("@schlessera/brain-ui-sdk/protocol").SafetyReviewBody).session.sessionId !== c.req.param("id")) + return c.json({code:"unavailable",reason:"invalid_request",retryable:false},400); + const value = action === "prepare" ? await combined.prepare(c.get("principal")!,input,c.req.raw.signal) : await combined.commit(c.get("principal")!,input,c.req.raw.signal,c.req.param("id")); + if (value.session.sessionId !== c.req.param("id")) return c.json({code:"unavailable",reason:"invalid_request",retryable:false},400); + return c.json(value); + } catch (error) { + const status = error instanceof TrustSettingsError ? error.status : error instanceof OwnerSafetyUnavailable ? 403 : 400; + return c.json({code:"unavailable",reason:error instanceof TrustSettingsError ? error.code : "invalid_request",retryable:false},status); + } + }); for (const action of ["prepare","commit"] as const) { app.post(action === "prepare" ? `${prefix}/prepare` : `${prefix}/:requestId/commit`, async c=>{ try { diff --git a/packages/ui-server/src/routes/session-safety.ts b/packages/ui-server/src/routes/session-safety.ts index 0579a3168e..8fbca2e7e2 100644 --- a/packages/ui-server/src/routes/session-safety.ts +++ b/packages/ui-server/src/routes/session-safety.ts @@ -9,11 +9,11 @@ export function createSessionSafetyRoutes(history:SafetyHistory,valid:(principal c.header("Cache-Control","no-store"); const principal=c.get("principal"); if(!principal||!valid(principal))return c.json({version:1,reason:"unauthorized"},401); - if(Buffer.byteLength(c.req.url)>8192||Object.keys(c.req.query()).some(k=>!["cursor","limit","entries"].includes(k))||Object.values(c.req.queries()).some(values=>values.length!==1)||c.req.query("entries")!==undefined&&c.req.query("entries")!=="1")return c.json({version:1,reason:"unavailable"},400); + if(Buffer.byteLength(c.req.url)>8192||Object.keys(c.req.query()).some(k=>!["cursor","limit","entries","admissions"].includes(k))||Object.values(c.req.queries()).some(values=>values.length!==1)||c.req.query("entries")!==undefined&&c.req.query("entries")!=="1"||c.req.query("admissions")!==undefined&&c.req.query("admissions")!=="1")return c.json({version:1,reason:"unavailable"},400); const target={sessionId:c.req.param("id")},cursor=c.req.query("cursor")??null,raw=c.req.query("limit"); if(!/^[A-Za-z0-9_-]{1,128}$/.test(target.sessionId)||cursor!==null&&(!cursor||cursor.length>512)||raw!==undefined&&(!/^[1-9][0-9]{0,2}$/.test(raw)||Number(raw)>100))return c.json({version:1,reason:"unavailable"},400); try{ - const page=await history.read(principal,target,cursor,raw?Number(raw):50,c.req.query("entries")==="1"); + const page=await history.read(principal,target,cursor,raw?Number(raw):50,c.req.query("entries")==="1",c.req.query("admissions")==="1"); if(!valid(principal))return c.json({version:1,reason:"unauthorized"},401); history.delivery(principal,page.identity,page.snapshotId); return c.json(page); diff --git a/packages/ui-server/src/routes/trust-settings.ts b/packages/ui-server/src/routes/trust-settings.ts index 5c52ed3b23..737bd8408f 100644 --- a/packages/ui-server/src/routes/trust-settings.ts +++ b/packages/ui-server/src/routes/trust-settings.ts @@ -11,7 +11,7 @@ export function createTrustSettingsRoutes(deps: { settings: TrustSettings; trust routes.use("/trust-settings*", async (c, next) => { c.header("Cache-Control", "private, no-store"); if (!c.get("principal")) return c.json({ code: "unauthorized", reason: "Authentication required", retryable: false }, 401); - if (c.req.method !== "GET") { + if (c.req.method !== "GET" && c.req.method !== "HEAD") { // Require the actual Origin, independent of spoofed fetch metadata and // the broader legacy API allowlist. Reverse-proxy TLS uses trusted proto. let expected: string; diff --git a/packages/ui-server/src/web-tools/host.ts b/packages/ui-server/src/web-tools/host.ts index e1e025f8ae..1a0061f9a6 100644 --- a/packages/ui-server/src/web-tools/host.ts +++ b/packages/ui-server/src/web-tools/host.ts @@ -122,8 +122,10 @@ export async function admitConnection(broker: WebBroker, owner: { principalId: s call.authority.attempt({ recipient, host, callId: call.callId }); } +type HostWebModelEgress = WebModelEgress & { remainingBytes():number }; + /** One session's lent model relay (#3688): one turn's model at a time, stopped with that turn's last call. */ -function modelLender(egress: WebModelEgress) { +function modelLender(egress: HostWebModelEgress) { let lent: { key: string; users: number; ready: Promise<{ grant: WebModelGrant; stop(): void }> } | undefined; const release = (current: NonNullable) => { if (--current.users > 0 || lent !== current) return; @@ -155,7 +157,7 @@ export function createHostWebTools(options: HostWebToolsOptions): WebBroker { const credentialEnv = Object.fromEntries(Object.entries(options.env).filter(([name]) => !["PI_CODING_AGENT_DIR", "XDG_CONFIG_HOME", "HOME"].includes(name))); const ownerKey = (owner: { principalId: string; sessionId: string }) => `${owner.principalId}\0${owner.sessionId}`; // Each launching session's egress route, until its executor has opened. - const routes = new Map(); + const routes = new Map(); const child = createChildWebExecutor({ launch: async owner => { const configPath = options.hostConfigPath(); @@ -172,7 +174,7 @@ export function createHostWebTools(options: HostWebToolsOptions): WebBroker { if (record.connectionId) counted.delete(record.connectionId); try { options.onEgress?.(record); } catch { /* A recorder cannot hold a connection open. */ } } }); - routes.set(ownerKey(owner), { dir: egress.dir, inference: egress.inference }); + routes.set(ownerKey(owner), { dir: egress.dir, inference: egress.inference,remainingBytes:egress.remainingBytes }); try { const state = options.module.prepareWebExecutorState({ root: options.root, hostConfigPath: configPath, credentialEnv, path: options.path }); const cleanup = () => { egress.stop(); state.cleanup(); }; @@ -186,7 +188,7 @@ export function createHostWebTools(options: HostWebToolsOptions): WebBroker { }); const executor: WebExecutor = { async open(owner, signal) { - let session: Awaited>, route: WebModelEgress | undefined; + let session: Awaited>, route: HostWebModelEgress | undefined; try { session = await child.open(owner, signal); } finally { route = routes.get(ownerKey(owner)); routes.delete(ownerKey(owner)); } const lender = route ? modelLender(route) : undefined; diff --git a/packages/ui-server/src/ws/bridge-session-binding.ts b/packages/ui-server/src/ws/bridge-session-binding.ts index 4256545589..2ec9f79563 100644 --- a/packages/ui-server/src/ws/bridge-session-binding.ts +++ b/packages/ui-server/src/ws/bridge-session-binding.ts @@ -5,24 +5,28 @@ import { STORAGE_SETTLEMENT_MS } from "../db/settlement.js"; import type { BridgeContext } from "./bridge-capabilities/context.js"; const contexts = new WeakMap(); +export type SessionBindingRefusal = "safety_changed" | "turn_cancelled" | "session_binding_unavailable"; 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 { +export async function settleTurnSessionBinding(bridge: BackendBridge, signal: AbortSignal): Promise { + if (signal.aborted) return "turn_cancelled"; const ctx = contexts.get(bridge); - if (!ctx) return true; + if (!ctx) return null; 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; + if (signal.aborted) return "turn_cancelled"; + if (!ctx.current()) return "safety_changed"; + if (!settled || ctx.sessionBinding.pending || ctx.sessionBinding.failed) return "session_binding_unavailable"; 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 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) ? null : "session_binding_unavailable"; } - return true; + return null; } diff --git a/packages/ui-server/src/ws/connection.ts b/packages/ui-server/src/ws/connection.ts index 1ee41ea33b..aa6e6ef226 100644 --- a/packages/ui-server/src/ws/connection.ts +++ b/packages/ui-server/src/ws/connection.ts @@ -91,7 +91,7 @@ export function createWsHandlers(host: WsHost, principal: Principal) { principalKey: answerQueueKey(principal.id), ...(host.safetyHistory ? {safetyCapabilities: host.ownerSafetyReviews?.capabilities(principal) ?? SAFETY_READ_CAPABILITIES} : {}), capabilities: { - ...(host.safetyHistory ? {sessionSafetyHistory:true,sessionSafetyEntryCorrelation:true} : {}), + ...(host.safetyHistory ? {sessionSafetyHistory:true,sessionSafetyEntryCorrelation:true,sessionSafetyAdmissionEvidence:true,sessionSafetyFutureRules:host.ownerSafetyReviews?.futureRules(principal)??false} : {}), multiSession: true, askUser: true, askUserList: true, diff --git a/packages/ui-server/src/ws/handlers/safety.ts b/packages/ui-server/src/ws/handlers/safety.ts index f382ea04aa..7b7613c525 100644 --- a/packages/ui-server/src/ws/handlers/safety.ts +++ b/packages/ui-server/src/ws/handlers/safety.ts @@ -6,7 +6,7 @@ export const handleSafetyRead:ClientMessageHandler<"safety_read">=async({host,ws if(!connection.capabilities?.sessionSafetyHistory||!live())return; try{ if(!host.safetyHistory)throw new SafetyReadUnavailable(); - const page=await host.safetyHistory.read(connection.principal,msg.target,msg.cursor??null,msg.limit,msg.includeEntries===true); + const page=await host.safetyHistory.read(connection.principal,msg.target,msg.cursor??null,msg.limit,msg.includeEntries===true,msg.includeAdmissions===true); host.safetyHistory.delivery(connection.principal,page.identity,page.snapshotId); if(live())host.sendMessage(ws,{type:"safety_history",requestId:msg.requestId,page}); }catch(error){if(live())host.sendMessage(ws,{type:"safety_unavailable",requestId:msg.requestId,version:1,reason:error instanceof SafetyReadUnavailable?error.reason:"unavailable"});} diff --git a/packages/ui-server/src/ws/host.ts b/packages/ui-server/src/ws/host.ts index 3339f1a728..0b7e3def06 100644 --- a/packages/ui-server/src/ws/host.ts +++ b/packages/ui-server/src/ws/host.ts @@ -73,6 +73,8 @@ export { export interface WsHostOptions { /** @internal Live trust publication input; no matching or publication authority. */ + originTrust?: import("../brain/origin-trust.js").OriginTrust; + /** @internal Live trust publication revision and invalidation. */ safetyTrust?: import("../governance/effective-safety.js").LiveTrustRevision; /** @internal Concrete read-only host evidence reader. */ safetyHistory?: import("../governance/safety-history.js").SafetyHistory; @@ -275,7 +277,9 @@ export interface ToolPermissions { */ export class WsHost { /** @internal Live trust revision supplied by the concrete host publisher. */ - readonly safetyTrust?: import("../governance/effective-safety.js").LiveTrustRevision; + originTrust?: import("../brain/origin-trust.js").OriginTrust; + /** @internal Live trust publication revision and invalidation. */ + safetyTrust?: import("../governance/effective-safety.js").LiveTrustRevision; /** @internal Concrete user history service mounted by this host, not agent authority. */ readonly turnReverts?: import("../brain/turn-revert.js").TurnReverts; /** Explicit local chat deletion (#3230); present when the host answers `POST /api/chat-deletions`. */ @@ -411,6 +415,7 @@ export class WsHost { constructor(options: WsHostOptions) { this.safetyTrust = options.safetyTrust; + this.originTrust = options.originTrust; this.safetyHistory = options.safetyHistory; this.ownerSafetyReviews = options.ownerSafetyReviews; this.turnReverts = options.turnReverts; 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 09bb8588eb..7355430ab9 100644 --- a/packages/ui-server/src/ws/session-run/backend-entry.ts +++ b/packages/ui-server/src/ws/session-run/backend-entry.ts @@ -173,8 +173,11 @@ export async function prepareRelayedEgress(run: TurnRun, bridge: BackendBridge, sessionId: () => turn.sessionId ?? null, ...(host.governedTurns ? { exposures: ids => host.governedTurns!.exposures(ids) } : {}), ...(governedHold.typeFolders ? { typeFolders: governedHold.typeFolders } : {}), budgets: host.budgets, observe: observeAttempt, stopped: () => abortController.signal.aborted ? "The turn was stopped." : (stops.budget as Error | undefined)?.message ?? null }); + await host.originTrust?.refresh?.(abortController.signal); + abortController.signal.throwIfAborted(); held.turnEgress = await prepareTurnEgress({ policy: governedHold.policy.policy, bridge, controller: abortController, turnId: turn.turnId, sessionId: () => turn.sessionId ?? null, model: () => run.mainModel, + trust: host.originTrust, profile: heldProfile(run), origin,policyHash:governedHold.policy.hash, brainPath: host.brainPath, // A record's commit failure stops the turn, as a synchronous one did (#2850). ...(governanceWrites ? { record: (event: Parameters[0]) => governanceWrites.record(event), governanceWrites } diff --git a/packages/ui-server/tests/combined-safety-review.test.ts b/packages/ui-server/tests/combined-safety-review.test.ts new file mode 100644 index 0000000000..77c78c7221 --- /dev/null +++ b/packages/ui-server/tests/combined-safety-review.test.ts @@ -0,0 +1,375 @@ +import { expect, test } from "bun:test"; +import { BRAIN_LOCK_KEY, createKeyedLock } from "@schlessera/brain-ui-sdk/server"; +import { createTrustSettings } from "../src/brain/trust-settings"; +import { CombinedSafetyReviews } from "../src/governance/combined-safety-reviews"; +import { safetyHistoryFixture } from "./helpers/safety-history-fixture"; +import { occurrence } from "../src/governance/occurrence"; + +async function fixture(checkpoint?: (stage: string) => void | Promise, now?:()=>number) { + const f = await safetyHistoryFixture(true, true); + const options = {root:f.root,db:f.db,writer:f.writer,lock:createKeyedLock(),originEnforcement:true as const, + authority:(id:string)=>id===f.principal.id&&f.reviews!.authorized(f.principal)?"owner-epoch":null, + observe:async (_id:string, write:()=>void|Promise)=>{await write();},checkpoint,...(now?{now}:{})}; + const settings=createTrustSettings(options),combined=new CombinedSafetyReviews(f.db,f.reviews!,settings); + const add=async (name:string,verified=true,state:"finalized"|"open"|"interrupted_unknown"="finalized")=>{ + const o=occurrence(f.bindingId,"proxy_input",name,state); + if(verified)o.provenance={kind:"web_origin",origin:{scheme:"https",host:"ithaca.invalid",port:443},verifiedBy:"host_transport"}; + await f.writes.record({kind:"taint",turnId:"voyage",sessionId:"ithaca",actor:"interactive",model:null,profile:"governed",payload:{source:"egress_connection",tool:"shell",detail:null,occurrence:o}});return o; + }; + const body=(id:string)=>({version:1 as const,session:f.writes.safety(null,"ithaca").session!,occurrenceId:id,expectedEvidenceRevision:f.writes.safety(null,"ithaca").evidenceRevision,verdict:"safe" as const, future:{incomingContent:true as const,recipientWhileRestricted:false}}); + return {...f,settings,options,combined,add,body}; +} +test("combined review publishes exact future rule then resolves only A; replay observes removal",async()=>{ + const f=await fixture();try{ + const a=await f.add("A");await f.add("B");await f.add("C"); + const body=f.body(a.id),p=await f.combined.prepare(f.principal,body); + expect(p.review.proposed).toContain("ithaca.invalid"); + expect(f.writes.safety(null,"ithaca").unresolvedCount).toBe(3); + const input={version:1 as const,requestId:p.requestId,reviewId:p.review.reviewId,reviewedBytesHash:p.review.reviewedBytesHash}; + const saved=await f.combined.commit(f.principal,input); + expect(saved.stage,"COMBINED_VERDICT_AFTER_PROVED_PUBLICATION").toBe("verdict_committed"); + expect(saved.currentProjection.unresolvedCount,"COMBINED_A_NEVER_CLEARS_B_C").toBe(2); + expect(saved.rule.currentRule).toBe("present");expect((await f.settings.list(f.principal.id)).rules[0]!.recipientWhileRestricted).toBe(false); + const current=await f.settings.list(f.principal.id),remove=await f.settings.prepare(f.principal.id,{version:1,expectedTrustRevision:current.revision,expectedPolicyHash:current.policyHash,change:{action:"remove",ruleId:saved.rule.ruleId}}); + await f.settings.commit(f.principal.id,{version:1,requestId:remove.receipt.requestId,reviewId:remove.review.reviewId,reviewedBytesHash:remove.review.reviewedBytesHash}); + const restarted=new CombinedSafetyReviews(f.db,f.reviews!,createTrustSettings(f.options)); + const replay=await restarted.commit(f.principal,input); + expect((await restarted.status(f.principal,{version:1,session:body.session,occurrenceId:a.id}))?.rule.currentRule,"COMBINED_RESTART_READ_WITHOUT_MUTATION").toBe("removed"); + expect(replay.rule.currentRule,"COMBINED_RETRY_NEVER_REPUBLISHES_REMOVED_RULE").toBe("removed"); + expect(replay.currentProjection.unresolvedCount).toBe(2); + }finally{await f.close();} +}); +for(const state of ["open","interrupted_unknown"] as const)test(`combined review refuses ${state} and unverified provenance`,async()=>{ + const f=await fixture();try{const a=await f.add("A",true,state);await expect(f.combined.prepare(f.principal,f.body(a.id))).rejects.toThrow(); + const b=await f.add("B",false);await expect(f.combined.prepare(f.principal,f.body(b.id))).rejects.toThrow("provenance_unavailable"); + expect((await f.settings.list(f.principal.id)).rules).toEqual([]);}finally{await f.close();} +}); +test("publication proof survives partial failure; retry cannot publish twice or clear stale evidence",async()=>{ + const f=await fixture();try{ + const a=await f.add("A"),p=await f.combined.prepare(f.principal,f.body(a.id));await f.add("B"); + const result=await f.combined.commit(f.principal,{version:1,requestId:p.requestId,reviewId:p.review.reviewId,reviewedBytesHash:p.review.reviewedBytesHash}); + expect(result.stage).toBe("refused");expect(result.rule.publication).toBe("not_published");expect(f.writes.safety(null,"ithaca").unresolvedCount).toBe(2); + }finally{await f.close();} +}); + +test("proved publication with verdict failure stays restrictive; durable binding resumes without republishing",async()=>{ + const f=await fixture();try{ + const a=await f.add("A"),p=await f.combined.prepare(f.principal,f.body(a.id)); + const input={version:1 as const,requestId:p.requestId,reviewId:p.review.reviewId,reviewedBytesHash:p.review.reviewedBytesHash}; + const original=f.reviews!.review.bind(f.reviews!); + f.reviews!.review=async()=>{throw new Error("simulated verdict outage");}; + const partial=await f.combined.commit(f.principal,input); + expect((await new CombinedSafetyReviews(f.db,f.reviews!,createTrustSettings(f.options)).status(f.principal,{version:1,session:f.body(a.id).session,occurrenceId:a.id}))?.stage,"COMBINED_PARTIAL_SURVIVES_SERVICE_RESTART_READ").toBe("partial"); + expect(partial.stage,"COMBINED_VERDICT_OUTAGE_RETURNS_PARTIAL_RECEIPT").toBe("partial"); + expect(f.writes.safety(null,"ithaca").unresolvedCount,"COMBINED_PUBLICATION_ALONE_NEVER_CLEARS_A").toBe(1); + expect((await f.settings.read(f.principal.id,p.requestId)).receipt.publication).toBe("proved"); + f.reviews!.review=original; + const result=await new CombinedSafetyReviews(f.db,f.reviews!,createTrustSettings(f.options)).commit(f.principal,input); + expect(result.stage).toBe("verdict_committed"); + expect(f.db.query('SELECT count(*) n FROM trust_settings_operations').get()).toEqual({n:1}); + }finally{await f.close();} +}); +test("unproved rename crash requires fresh review and never commits the verdict on retry",async()=>{ + let publications=0;const f=await fixture(stage=>{if(stage==="renamed"){publications++;throw new Error("crash before proof");}});try{ + const a=await f.add("A"),p=await f.combined.prepare(f.principal,f.body(a.id)); + const input={version:1 as const,requestId:p.requestId,reviewId:p.review.reviewId,reviewedBytesHash:p.review.reviewedBytesHash}; + for(let i=0;i<2;i++){ + const result=await new CombinedSafetyReviews(f.db,f.reviews!,createTrustSettings(f.options)).commit(f.principal,input); + expect(result.stage,"COMBINED_UNKNOWN_PUBLICATION_NEVER_BLESSED_BY_EQUAL_BYTES").toBe("unknown");expect(result.verdict?.verdict).toBe("unresolved");expect(result.verdict?.requestId).toBeNull();expect(result.verdict?.operationId).toBeNull(); + } + expect(publications).toBe(1);expect(f.writes.safety(null,"ithaca").unresolvedCount).toBe(1); + }finally{await f.close();} +}); +test("rule removed between authorities does not return; the selected verdict can still commit",async()=>{ + const f=await fixture();try{ + const a=await f.add("A"),p=await f.combined.prepare(f.principal,f.body(a.id)); + const original=f.reviews!.review.bind(f.reviews!);f.reviews!.review=async(...args)=>{ + const policy=await f.settings.list(f.principal.id),remove=await f.settings.prepare(f.principal.id,{version:1,expectedTrustRevision:policy.revision,expectedPolicyHash:policy.policyHash,change:{action:"remove",ruleId:p.rule.ruleId}}); + await f.settings.commit(f.principal.id,{version:1,requestId:remove.receipt.requestId,reviewId:remove.review.reviewId,reviewedBytesHash:remove.review.reviewedBytesHash});return original(...args);}; + const result=await f.combined.commit(f.principal,{version:1,requestId:p.requestId,reviewId:p.review.reviewId,reviewedBytesHash:p.review.reviewedBytesHash}); + expect(result.stage).toBe("verdict_committed");expect(result.rule.currentRule,"COMBINED_CURRENT_RULE_ABSENCE_IS_HONEST").toBe("removed");expect((await f.settings.list(f.principal.id)).rules).toEqual([]); + }finally{await f.close();} +}); +test("generic Settings commit and wrong-session route cannot consume a combined binding",async()=>{ + const f=await fixture();try{const a=await f.add("A"),p=await f.combined.prepare(f.principal,f.body(a.id)); + const input={version:1 as const,requestId:p.requestId,reviewId:p.review.reviewId,reviewedBytesHash:p.review.reviewedBytesHash}; + expect(await f.settings.commit(f.principal.id,input).then(()=>"published",error=>error.message),"COMBINED_GENERIC_SETTINGS_CANNOT_PUBLISH_BOUND_REVIEW").toBe("request_conflict"); + await expect(f.combined.commit(f.principal,input,undefined,"troy")).rejects.toThrow("request_conflict"); + expect((await f.settings.list(f.principal.id)).rules).toEqual([]); + }finally{await f.close();} +}); + +test("combined real HTTP/WS owner, Origin, provenance and session fences",async()=>{ + const {Hono}=await import('hono'),{authGuard}=await import('../src/middleware/auth'),{createOwnerSafetyReviewRoutes}=await import('../src/routes/owner-safety-review'); + const f=await fixture(),app=new Hono(); + f.reviews!.enableFutureRules(f.settings); + app.use('/api/*',authGuard('password',f.auth,f.db));app.route('/api',createOwnerSafetyReviewRoutes(f.reviews!,false,f.combined)); + const server=Bun.serve({hostname:'127.0.0.1',port:0,fetch:app.fetch}),origin=`http://127.0.0.1:${server.port}`; + const post=(action:string,body:unknown,headers:Record={})=>fetch(`${origin}/api/sessions/ithaca/safety/reviews/future/${action}`,{method:'POST',headers:{cookie:f.cookie,origin,'content-type':'application/json',...headers},body:JSON.stringify(body)}); + try{ + const a=await f.add('A'),body=f.body(a.id); + expect((await f.connect()).hello).toMatchObject({safetyCapabilities:{review:true,originRules:false,recipientRules:false,repositoryRules:false},capabilities:{sessionSafetyFutureRules:true}}); + expect((await post('prepare',body,{origin:'https://troy.invalid'})).status).toBe(403); + expect((await post('prepare',{...body,future:{...body.future,selector:{kind:'web_origin',host:'troy.invalid'}}})).status).toBe(400); + const prepared=await post('prepare',body);expect(prepared.status,'COMBINED_HTTP_PREPARE_REQUIRES_IMPLEMENTED_ROUTE').toBe(200); + const p=await prepared.json(); + const response=await post('commit',{version:1,requestId:p.requestId,reviewId:p.review.reviewId,reviewedBytesHash:p.review.reviewedBytesHash}); + expect(response.status).toBe(200);expect((await response.json()).stage).toBe('verdict_committed'); + expect(f.starts()).toBe(0); + }finally{server.stop(true);await f.close();} +}); + +test("closing and reopening both DB authorities recovers a partial combined operation without publication replay",async()=>{ + const {createUiDb}=await import('../src/db/client'),{openSqliteWriter}=await import('../src/db/write-worker'),{createGovernanceWrites}=await import('../src/governance/event-writes'),{OwnerSafetyReviews}=await import('../src/governance/owner-safety-reviews'),{rmSync}=await import('node:fs'); + const f=await fixture();let closed=false; + try{ + const a=await f.add('A'),body=f.body(a.id),p=await f.combined.prepare(f.principal,body); + const input={version:1 as const,requestId:p.requestId,reviewId:p.review.reviewId,reviewedBytesHash:p.review.reviewedBytesHash}; + f.reviews!.review=async()=>{throw new Error('verdict unavailable');}; + expect((await f.combined.commit(f.principal,input)).stage).toBe('partial'); + await f.close(true);closed=true; + const db=createUiDb(f.path),writer=openSqliteWriter(db),writes=createGovernanceWrites(db,writer),reviews=new OwnerSafetyReviews(db,writes,'password',f.brainKey); + let publications=0; + const settings=createTrustSettings({...f.options,db,writer,lock:createKeyedLock(),authority:id=>id===f.principal.id&&reviews.authorized(f.principal)?'owner-epoch':null,observe:async(_id,write)=>{publications++;await write();}}); + const service=new CombinedSafetyReviews(db,reviews,settings); + try{ + expect((await service.status(f.principal,{version:1,session:body.session,occurrenceId:a.id}))?.stage,'COMBINED_REOPENED_DB_READS_PARTIAL').toBe('partial'); + expect(writes.safety(null,'ithaca').unresolvedCount).toBe(1); + const retried=await service.commit(f.principal,input); + expect(retried.stage,'COMBINED_RESTART_RECOVERY_PRESERVES_LIFECYCLE_FENCE').toBe('partial'); + expect(retried.verdict?.reason).toBe('stale_revision'); + expect(writes.safety(null,'ithaca').unresolvedCount).toBe(1); + expect(publications,'COMBINED_REOPENED_DB_NEVER_REPUBLISHES').toBe(0); + }finally{await writer.close();db.close();} + }finally{if(!closed)await f.close();else rmSync(f.root,{recursive:true,force:true});} +}); + +test("explicit tunnel provenance remains a tunnel and recipient permission is independently reviewed",async()=>{ + const f=await fixture();try{ + const a=occurrence(f.bindingId,'proxy_input',null,'finalized');a.provenance={kind:'tunnel_authority',authority:{host:'ithaca.invalid',port:8443},verifiedBy:'host_proxy'}; + await f.writes.record({kind:'taint',turnId:'voyage',sessionId:'ithaca',actor:'interactive',model:null,profile:'governed',payload:{source:'egress_connection',tool:'shell',detail:null,occurrence:a}}); + const p=await f.combined.prepare(f.principal,{...f.body(a.id),future:{incomingContent:true,recipientWhileRestricted:true}}); + const result=await f.combined.commit(f.principal,{version:1,requestId:p.requestId,reviewId:p.review.reviewId,reviewedBytesHash:p.review.reviewedBytesHash}); + expect(result.stage).toBe('verdict_committed'); + expect((await f.settings.list(f.principal.id)).rules[0]).toMatchObject({selector:{kind:'tunnel_authority',host:'ithaca.invalid',port:8443},incomingContent:true,recipientWhileRestricted:true}); + }finally{await f.close();} +}); + +test("historical JSON without the host provenance attestation cannot offer a standing rule",async()=>{ + const f=await fixture();try{ + const a=await f.add('A'); + const row=f.db.query('SELECT payload FROM safety_records WHERE id=?').get(a.id) as {payload:string}; + const payload=JSON.parse(row.payload);delete payload.occurrence.provenance.verifiedBy; + f.db.query('UPDATE safety_records SET payload=? WHERE id=?').run(JSON.stringify(payload),a.id); + expect(await f.combined.prepare(f.principal,f.body(a.id)).then(()=>"prepared",error=>error.message),'COMBINED_REQUIRES_HOST_ATTESTATION').toBe('provenance_unavailable'); + expect((await f.settings.list(f.principal.id)).rules).toEqual([]); + }finally{await f.close();} +}); + +for(const crash of [false,true])test(`review F1: individual endpoint cannot consume a combined handle before proved publication (crash ${crash})`,async()=>{ + const f=await fixture(crash?stage=>{if(stage==='renamed')throw new Error('unproved publication');}:undefined);try{ + const a=await f.add('A'),{future,...body}=f.body(a.id),p=await f.combined.prepare(f.principal,{...body,future}); + if(crash)expect((await f.combined.commit(f.principal,{version:1,requestId:p.requestId,reviewId:p.review.reviewId,reviewedBytesHash:p.review.reviewedBytesHash})).stage).toBe('unknown'); + const handle=f.settings.safetyReview(f.principal.id,p.requestId)!.requestId; + const origin=f.url.replace('ws:','http:').replace('/ws',''); + const response=await fetch(`${origin}/api/sessions/ithaca/safety/reviews/${handle}/commit`,{method:'POST',headers:{cookie:f.cookie,origin,'content-type':'application/json'},body:JSON.stringify(body)}); + expect(response.status,'F1_INDIVIDUAL_ENDPOINT_REQUIRES_COMBINED_PUBLICATION_PROOF').toBe(409); + expect((await response.json()).receipt.reason).toBe('publication_unproven'); + expect((await f.reviews!.review(f.principal,body,handle)).receipt.verdict).toBe('unresolved'); + expect(f.writes.safety(null,'ithaca').unresolvedCount).toBe(1); + if(!crash)expect((await f.combined.commit(f.principal,{version:1,requestId:p.requestId,reviewId:p.review.reviewId,reviewedBytesHash:p.review.reviewedBytesHash})).stage).toBe('verdict_committed'); + }finally{await f.close();} +}); +test('review F1: prepared status never exposes the unpublished verdict handle',async()=>{ + const f=await fixture();try{const a=await f.add('A'),body=f.body(a.id);await f.combined.prepare(f.principal,body); + const status=await f.combined.status(f.principal,{version:1,session:body.session,occurrenceId:a.id}); + expect(status?.verdict?.requestId,'F1_NO_EARLY_VERDICT_HANDLE').toBeNull(); + }finally{await f.close();} +}); +test('review F2: legacy SDK can parse the real owner hello and retains individual review',async()=>{ + const {z}=await import('zod'),{safetyCapabilitiesSchema}=await import('@schlessera/brain-ui-sdk/schemas'); + const f=await fixture();try{f.reviews!.enableFutureRules(f.settings);const socket=await f.connect(); + if(socket.hello.type!=='server_hello')throw new Error('Missing hello'); + const legacy=safetyCapabilitiesSchema.extend({originRules:z.literal(false),recipientRules:z.literal(false)}).safeParse(socket.hello.safetyCapabilities); + expect(legacy.success,'F2_OLD_SDK_RETAINS_SAFETY_CAPABILITIES').toBe(true); + if(!legacy.success)throw legacy.error;expect(legacy.data).toMatchObject({read:true,review:true}); + expect(socket.hello.capabilities?.sessionSafetyFutureRules).toBe(true); + const a=await f.add('A'),{future:_,...body}=f.body(a.id),prepared=await f.reviews!.review(f.principal,body,null); + expect((await f.reviews!.review(f.principal,body,prepared.receipt.requestId!)).receipt.verdict).toBe('committed'); + }finally{await f.close();} +}); + +test('round 2 F1: the committed earlier preparation outranks a later unpublished tab',async()=>{ + let clock=Date.now();const f=await fixture(undefined,()=>clock);try{ + const a=await f.add('A'),body=f.body(a.id),first=await f.combined.prepare(f.principal,body);clock++; + const later=await f.combined.prepare(f.principal,body);expect(later.requestId).not.toBe(first.requestId); + expect((await f.combined.commit(f.principal,{version:1,requestId:first.requestId,reviewId:first.review.reviewId,reviewedBytesHash:first.review.reviewedBytesHash})).stage).toBe('verdict_committed'); + const status=await f.combined.status(f.principal,{version:1,session:body.session,occurrenceId:a.id}); + expect(status?.requestId,'R2F1_COMMITTED_OPERATION_OWNS_RECOVERY').toBe(first.requestId); + expect(status?.stage).toBe('verdict_committed');expect(status?.rule.currentRule).toBe('present'); + }finally{await f.close();} +}); +test('round 2 F3: expired receipt read returns JSON null without another insert',async()=>{ + const {Hono}=await import('hono'),{authGuard}=await import('../src/middleware/auth'),{createOwnerSafetyReviewRoutes}=await import('../src/routes/owner-safety-review'); + let clock=Date.now();const f=await fixture(undefined,()=>clock),app=new Hono(); + app.use('/api/*',authGuard('password',f.auth,f.db));app.route('/api',createOwnerSafetyReviewRoutes(f.reviews!,false,f.combined)); + const server=Bun.serve({hostname:'127.0.0.1',port:0,fetch:app.fetch}),origin=`http://127.0.0.1:${server.port}`; + try{ + const a=await f.add('A'),body=f.body(a.id);await f.combined.prepare(f.principal,body); + clock+=86400001; + expect(f.db.query('SELECT count(*) n FROM trust_settings_operations').get()).toEqual({n:1}); + const response=await fetch(`${origin}/api/sessions/ithaca/safety/reviews/future/status`,{method:'POST',headers:{cookie:f.cookie,origin,'content-type':'application/json'},body:JSON.stringify({version:1,session:body.session,occurrenceId:a.id})}); + expect(response.status,'R2F3_EXPIRED_RECEIPT_IS_NOT_HTTP_UNAVAILABLE').toBe(200);expect(await response.json()).toBeNull(); + expect(f.writes.safety(null,'ithaca').unresolvedCount).toBe(1); + expect(f.db.query('SELECT count(*) n FROM trust_settings_operations').get()).toEqual({n:1}); + }finally{server.stop(true);await f.close();} +}); + +test('round 2 F1: status selects after a queued publisher, not before the lock wait',async()=>{ + const f=await fixture();let release:(()=>void)|undefined;try{ + const a=await f.add('A'),body=f.body(a.id),first=await f.combined.prepare(f.principal,body);await f.combined.prepare(f.principal,body); + release=await f.options.lock.acquire(BRAIN_LOCK_KEY); + const commit=f.combined.commit(f.principal,{version:1,requestId:first.requestId,reviewId:first.review.reviewId,reviewedBytesHash:first.review.reviewedBytesHash}); + const read=f.combined.status(f.principal,{version:1,session:body.session,occurrenceId:a.id}); + release();release=undefined; + const [saved,status]=await Promise.all([commit,read]);expect(saved.stage).toBe('verdict_committed'); + expect(status?.requestId,'R2F1_SELECTION_RECHECKS_AFTER_PUBLICATION_WAIT').toBe(first.requestId);expect(status?.rule.currentRule).toBe('present'); + }finally{release?.();await f.close();} +}); + +test('round 2 F1: a current unknown publication is not hidden by an older removed proof',async()=>{ + let crash=false;const f=await fixture(stage=>{if(crash&&stage==='renamed')throw new Error('publication unknown');});try{ + const a=await f.add('A'),body=f.body(a.id),first=await f.combined.prepare(f.principal,body),original=f.reviews!.review.bind(f.reviews!); + f.reviews!.review=async()=>{throw new Error('verdict unavailable');}; + expect((await f.combined.commit(f.principal,{version:1,requestId:first.requestId,reviewId:first.review.reviewId,reviewedBytesHash:first.review.reviewedBytesHash})).stage).toBe('partial');f.reviews!.review=original; + const p=await f.settings.list(f.principal.id),remove=await f.settings.prepare(f.principal.id,{version:1,expectedTrustRevision:p.revision,expectedPolicyHash:p.policyHash,change:{action:'remove',ruleId:first.rule.ruleId}}); + await f.settings.commit(f.principal.id,{version:1,requestId:remove.receipt.requestId,reviewId:remove.review.reviewId,reviewedBytesHash:remove.review.reviewedBytesHash}); + const newer=await f.combined.prepare(f.principal,f.body(a.id));crash=true; + expect((await f.combined.commit(f.principal,{version:1,requestId:newer.requestId,reviewId:newer.review.reviewId,reviewedBytesHash:newer.review.reviewedBytesHash})).stage).toBe('unknown'); + const status=await f.combined.status(f.principal,{version:1,session:body.session,occurrenceId:a.id}); + expect(status?.requestId,'R2F1_CURRENT_RULE_KEEPS_ITS_UNKNOWN_RECEIPT_VISIBLE').toBe(newer.requestId); + expect(status?.stage).toBe('unknown');expect(status?.rule.currentRule).toBe('present');expect(f.writes.safety(null,'ithaca').unresolvedCount).toBe(1); + }finally{await f.close();} +}); + +test('matrix SV-L committed: pending limit cannot downgrade the durable verdict (round 3 F1)',async()=>{ + const {holdOwnerReviews}=await import('./helpers/held-owner-reviews');const f=await fixture();let pressure:Awaited>|undefined;try{ + const a=await f.add('A'),{future,...body}=f.body(a.id),p=await f.combined.prepare(f.principal,{...body,future}); + const input={version:1 as const,requestId:p.requestId,reviewId:p.review.reviewId,reviewedBytesHash:p.review.reviewedBytesHash}; + expect((await f.combined.commit(f.principal,input)).stage).toBe('verdict_committed'); + pressure=await holdOwnerReviews({reviews:f.reviews!,writes:f.writes,principal:f.principal},body); + const replay=await f.combined.commit(f.principal,input),status=await f.combined.status(f.principal,{version:1,session:body.session,occurrenceId:a.id}); + expect(replay.stage,'R3F1_LIMIT_CANNOT_DOWNGRADE_COMMITTED_FACT').toBe('verdict_committed');expect(replay.stage).toBe(status!.stage); + expect(f.db.query('SELECT count(*) n FROM safety_decisions').get()).toEqual({n:1}); + }finally{await pressure?.close();await f.close();} +}); +test('matrix SV-F after: lost acknowledgement still reports the durable committed verdict',async()=>{ + const f=await fixture();try{ + const a=await f.add('A'),body=f.body(a.id),p=await f.combined.prepare(f.principal,body),original=f.writes.safetyCommitReview; + f.writes.safetyCommitReview=async(...args)=>{await original(...args);throw new Error('Lost worker acknowledgement');}; + const result=await f.combined.commit(f.principal,{version:1,requestId:p.requestId,reviewId:p.review.reviewId,reviewedBytesHash:p.review.reviewedBytesHash}); + expect(result.stage,'R3F1_ACK_LOSS_DOES_NOT_ERASE_COMMIT').toBe('verdict_committed'); + expect(result.stage).toBe((await f.combined.status(f.principal,{version:1,session:body.session,occurrenceId:a.id}))!.stage); + }finally{await f.close();} +}); + +// The full boundary matrix is recorded in #4428 before the round-3 patches. +async function matrixOperation(f:Awaited>){ + const a=await f.add('A'),{future,...body}=f.body(a.id),prepared=await f.combined.prepare(f.principal,{...body,future}); + const input={version:1 as const,requestId:prepared.requestId,reviewId:prepared.review.reviewId,reviewedBytesHash:prepared.review.reviewedBytesHash}; + return {a,body,prepared,input}; +} +const rejected=async(p:Promise)=>p.then(()=>"accepted",error=>error.code??error.message); +for(const id of ['SP-L','SP-E','SP-M','SP-F'] as const)test(`matrix ${id}: preparation cannot create authority through a failed boundary`,async()=>{ + const {holdOwnerReviews}=await import('./helpers/held-owner-reviews');const f=await fixture();let pressure:Awaited>|undefined;try{ + const a=await f.add('A'),{future,...body}=f.body(a.id); + let expected:string; + if(id==='SP-L'){pressure=await holdOwnerReviews({reviews:f.reviews!,writes:f.writes,principal:f.principal},body);expected='capacity';} + else if(id==='SP-E'){f.db.query('UPDATE principals SET expires_at=0 WHERE id=?').run(f.principal.id);expected='unauthorized';} + else if(id==='SP-M'){body.session={...body.session,historyGeneration:'999'};expected='unavailable';} + else{f.writes.safetyPrepareReview=async()=>{throw new Error('Controlled prepare read failure');};expected='Controlled prepare read failure';} + expect(await rejected(f.combined.prepare(f.principal,{...body,future}))).toBe(expected); + expect(f.db.query('SELECT count(*) n FROM trust_settings_operations').get()).toEqual({n:0});expect(f.db.query('SELECT count(*) n FROM safety_decisions').get()).toEqual({n:0}); + }finally{await pressure?.close();await f.close();} +}); +for(const id of ['SB-L','SV-L partial','SS-L'] as const)test(`matrix ${id}: pending quota does not invent a verdict or block status`,async()=>{ + const {holdOwnerReviews}=await import('./helpers/held-owner-reviews');const f=await fixture();let pressure:Awaited>|undefined;try{ + const op=await matrixOperation(f); + if(id!=='SB-L'){const original=f.writes.safetyCommitReview;f.writes.safetyCommitReview=async()=>{throw new Error('Before verdict');};expect((await f.combined.commit(f.principal,op.input)).stage).toBe('partial');f.writes.safetyCommitReview=original;} + pressure=await holdOwnerReviews({reviews:f.reviews!,writes:f.writes,principal:f.principal},op.body); + const result=id==='SS-L'?await f.combined.status(f.principal,{version:1,session:op.body.session,occurrenceId:op.a.id}):await f.combined.commit(f.principal,op.input); + expect(result?.stage).toBe('partial');expect(result?.rule.publication).toBe('proved');expect(f.db.query('SELECT count(*) n FROM safety_decisions').get()).toEqual({n:0}); + }finally{await pressure?.close();await f.close();} +}); +test('matrix SB-E: an expired publication review cannot publish',async()=>{ + const f=await fixture();try{const op=await matrixOperation(f);f.db.query('UPDATE trust_settings_operations SET expires_at=0 WHERE request_id=?').run(op.input.requestId); + expect(await rejected(f.combined.commit(f.principal,op.input))).toBe('request_expired');expect((await f.settings.list(f.principal.id)).rules).toEqual([]);expect(f.writes.safety(null,'ithaca').unresolvedCount).toBe(1); + }finally{await f.close();} +}); +for(const mismatch of ['hash','review','session'] as const)test(`matrix SB-M ${mismatch}: publication is bound to its exact review`,async()=>{ + const f=await fixture();try{const op=await matrixOperation(f),input={...op.input}; + if(mismatch==='hash')input.reviewedBytesHash=(input.reviewedBytesHash[0]==='a'?'b':'a')+input.reviewedBytesHash.slice(1); + if(mismatch==='review')input.reviewId='wrong_review'; + expect(await rejected(f.combined.commit(f.principal,input,undefined,mismatch==='session'?'troy':undefined))).toBe('request_conflict'); + expect((await f.settings.list(f.principal.id)).rules).toEqual([]);expect(f.db.query('SELECT count(*) n FROM safety_decisions').get()).toEqual({n:0}); + }finally{await f.close();} +}); +for(const boundary of ['before','rename','proof'] as const)test(`matrix SB-F ${boundary}: publication failure reports only proved facts`,async()=>{ + const f=await fixture();try{const op=await matrixOperation(f); + if(boundary==='before')f.options.observe=async()=>{throw new Error('Observation read failed');}; + else f.options.checkpoint=stage=>{if(stage===(boundary==='rename'?'renamed':'file_published'))throw new Error('Controlled publication interruption');}; + const result=await f.combined.commit(f.principal,op.input); + expect(result.rule.publication).toBe(boundary==='before'?'not_published':boundary==='rename'?'unknown':'proved'); + expect(result.stage).toBe(boundary==='before'?'refused':boundary==='rename'?'unknown':'verdict_committed'); + expect(f.writes.safety(null,'ithaca').unresolvedCount).toBe(boundary==='proof'?0:1); + }finally{await f.close();} +}); +test('matrix SV-E: an expired original verdict cannot become a fresh request',async()=>{ + const f=await fixture();try{const op=await matrixOperation(f),original=f.writes.safetyCommitReview; + f.writes.safetyCommitReview=async()=>{throw new Error('Verdict unavailable');};expect((await f.combined.commit(f.principal,op.input)).stage).toBe('partial');f.writes.safetyCommitReview=original; + const {commitSafetyReview}=await import('../src/governance/safety-reviews'); + f.writes.safetyCommitReview=async(id,body,actor)=>commitSafetyReview(f.db,id,body,actor,false,false,()=>Date.now()+900001); + const result=await f.combined.commit(f.principal,op.input);expect(result.stage).toBe('partial');expect(result.verdict?.reason).toBe('request_expired');expect(f.db.query('SELECT count(*) n FROM safety_decisions').get()).toEqual({n:0}); + }finally{await f.close();} +}); +test('matrix SV-M: evidence added after publication prevents the selected verdict',async()=>{ + const f=await fixture();try{const op=await matrixOperation(f);f.options.checkpoint=async stage=>{if(stage==='committed')await f.add('B');}; + const result=await f.combined.commit(f.principal,op.input);expect(result.rule.publication).toBe('proved');expect(result.stage).toBe('partial');expect(result.verdict?.reason).toBe('stale_revision');expect(result.currentProjection.unresolvedCount).toBe(2); + }finally{await f.close();} +}); +test('matrix SV-F before: failed verdict call leaves a durable partial operation',async()=>{ + const f=await fixture();try{const op=await matrixOperation(f);f.writes.safetyCommitReview=async()=>{throw new Error('Worker read unavailable');}; + const result=await f.combined.commit(f.principal,op.input),status=await f.combined.status(f.principal,{version:1,session:op.body.session,occurrenceId:op.a.id}); + expect(result.stage).toBe('partial');expect(status?.stage).toBe(result.stage);expect(f.db.query('SELECT count(*) n FROM safety_decisions').get()).toEqual({n:0}); + }finally{await f.close();} +}); +for(const stage of ['prepared','unknown','partial','verdict_committed'] as const)test(`matrix SS-R ${stage}: status retries are read-only durable views`,async()=>{ + const f=await fixture();try{const op=await matrixOperation(f); + if(stage==='unknown')f.options.checkpoint=value=>{if(value==='renamed')throw new Error('Unproved rename');}; + if(stage==='partial')f.writes.safetyCommitReview=async()=>{throw new Error('No verdict');}; + if(stage!=='prepared')await f.combined.commit(f.principal,op.input); + const body={version:1,session:op.body.session,occurrenceId:op.a.id},one=await f.combined.status(f.principal,body),two=await f.combined.status(f.principal,body); + expect(one?.stage).toBe(stage);expect(two?.stage).toBe(stage);expect(one?.requestId).toBe(two?.requestId); + if(stage!=='verdict_committed')expect(two?.verdict?.requestId??null).toBeNull(); + expect(f.db.query('SELECT count(*) n FROM safety_decisions').get()).toEqual({n:stage==='verdict_committed'?1:0}); + }finally{await f.close();} +}); +test('matrix SS-M: status cannot read another history generation',async()=>{ + const f=await fixture();try{const op=await matrixOperation(f); + expect(await rejected(f.combined.status(f.principal,{version:1,session:{...op.body.session,historyGeneration:'999'},occurrenceId:op.a.id}))).toBe('unavailable'); + }finally{await f.close();} +}); +test('matrix SS-F: a storage read failure is not a null receipt',async()=>{ + const {spyOn}=await import('bun:test');const f=await fixture();let spy:ReturnType|undefined;try{const op=await matrixOperation(f),query=f.db.query.bind(f.db); + spy=spyOn(f.db,'query').mockImplementation(((sql:string)=>{if(sql.includes('FROM trust_settings_operations o'))throw new Error('Controlled status storage read failure');return query(sql);}) as typeof f.db.query); + expect(await rejected(f.combined.status(f.principal,{version:1,session:op.body.session,occurrenceId:op.a.id}))).toBe('Controlled status storage read failure'); + }finally{spy?.mockRestore();await f.close();} +}); + +test('matrix SS-R retained operation: pruning its verdict receipt cannot erase the durable decision',async()=>{ + const f=await fixture();try{const op=await matrixOperation(f);await f.combined.commit(f.principal,op.input); + const binding=f.settings.safetyReview(f.principal.id,op.input.requestId)!;f.db.query('DELETE FROM safety_review_requests WHERE id=?').run(binding.requestId); + const status=await f.combined.status(f.principal,{version:1,session:op.body.session,occurrenceId:op.a.id}); + expect(status?.stage).toBe('verdict_committed');expect(status?.verdict).toBeNull();expect((await f.combined.commit(f.principal,op.input)).stage).toBe('verdict_committed');expect(f.db.query('SELECT count(*) n FROM safety_decisions').get()).toEqual({n:1}); + }finally{await f.close();} +}); diff --git a/packages/ui-server/tests/egress-refusal-matrix.test.ts b/packages/ui-server/tests/egress-refusal-matrix.test.ts new file mode 100644 index 0000000000..e84861c22b --- /dev/null +++ b/packages/ui-server/tests/egress-refusal-matrix.test.ts @@ -0,0 +1,117 @@ +/** Every operation refusal enters the same stored decision before any caller observes abort. */ +import { expect, test } from 'bun:test'; +import { request } from 'node:http'; +import { connect } from 'node:net'; +import { startEgressProxy, EgressAdmissionRefused, type EgressProxyOptions, type EgressRecord, type EgressFailureReason } from '../../ui-sdk/src/server/egress-proxy'; +import { startInferenceRelay } from '../../ui-sdk/src/server/inference-relay'; +import { startProviderRelay, type ProviderRelayOptions, type ProviderRelayReceipt } from '../../ui-sdk/src/server/provider-relay'; +import { createGitHubReferenceWire } from '../src/brain/github-reference-wire'; + +const callers=['HTTP','CONNECT','inference','provider','cleanup','reference'] as const; +const sources=[ + {name:'budget',category:'budget',detail:'max_bytes_per_turn'}, + {name:'deny',category:'policy_denied',detail:'destination_not_allowed'}, + {name:'allowlist',category:'policy_denied',detail:'destination_not_allowed'}, + {name:'port',category:'policy_denied',detail:'destination_port'}, + {name:'dns',category:'policy_denied',detail:'unresolved_destination'}, + {name:'private',category:'policy_denied',detail:'private_destination'}, + {name:'metadata',category:'policy_denied',detail:'metadata_destination'}, + {name:'late taint',category:'policy_denied',detail:'taint_not_allowed',g6:true}, + {name:'taint',category:'policy_denied',detail:'taint_not_allowed',g6:true}, + {name:'declined Network',category:'policy_denied',detail:'taint_not_approved',g6:true}, + {name:'stale Network',category:'safety_changed',detail:'safety_changed',g6:true}, + {name:'declined outward',category:'policy_denied',detail:'outward_not_approved'}, + {name:'stale outward',category:'safety_changed',detail:'safety_changed'}, + {name:'card recording',category:'unavailable',detail:'egress_unavailable'}, + {name:'card authority',category:'safety_changed',detail:'safety_changed'}, + {name:'card read error',category:'unavailable',detail:'egress_unavailable'}, + {name:'initial authority',category:'safety_changed',detail:'safety_changed'}, + {name:'late authority',category:'safety_changed',detail:'safety_changed'}, + {name:'initial recording',category:'unavailable',detail:'egress_unavailable'}, + {name:'late recording',category:'unavailable',detail:'egress_unavailable'}, + {name:'initial read error',category:'unavailable',detail:'egress_unavailable'}, + {name:'late read error',category:'unavailable',detail:'egress_unavailable'}, + {name:'host refusal',category:'policy_denied',detail:'call_not_admitted'}, + {name:'recording abort',category:'unavailable',detail:'egress_unavailable'}, + {name:'host error',category:'unavailable',detail:'proxy_error'}, + {name:'source removal',category:'safety_changed',detail:'source_trust_changed'}, + {name:'turn cancellation',category:'cancelled',detail:'turn_cancelled'}, +] satisfies {name:string;category:EgressFailureReason;detail:string;g6?:boolean}[]; + +function http(socketPath:string,path:string,headers:Record={},body?:string,method=body?'POST':'GET') { + return new Promise<{status:number;body:string;headers:Record}>((resolve,reject)=>{ + const req=request({socketPath,path,method,headers},res=>{let text='';res.on('data',b=>{text+=b;});res.on('end',()=>resolve({status:res.statusCode!,body:text,headers:res.headers}));res.on('error',reject);});req.on('error',reject);req.end(body); + }); +} +function tunnel(socketPath:string,target:string) { + return new Promise((resolve,reject)=>{const s=connect(socketPath);let text='';s.on('error',reject);s.on('connect',()=>s.write(`CONNECT ${target} HTTP/1.1\r\nHost: ${target}\r\n\r\n`));s.on('data',b=>{text+=b;s.end();});s.on('close',()=>resolve(Number(/^HTTP\/1.1 (\d+)/.exec(text)?.[1]??0)));}); +} + +for(const source of sources)for(const caller of callers)test(`refusal matrix: ${source.name} × ${caller}`,async()=>{ + let phase=false,revision='1',hits=0,armed=false,origin=''; + const records:EgressRecord[]=[],receipts:ProviderRelayReceipt[]=[]; + const root=new AbortController(); + const upstream=Bun.serve({hostname:'127.0.0.1',port:0,async fetch(req){ + hits++;await req.arrayBuffer();const u=new URL(req.url); + if(u.pathname==='/upload/v1beta/files'&&!u.search)return Response.json({},{headers:{'x-goog-upload-url':`${origin}/upload/v1beta/files?upload_id=ithaca&upload_protocol=resumable`}}); + if(u.pathname==='/upload/v1beta/files')return Response.json({file:{name:'files/ithaca',uri:`${origin}/v1beta/files/ithaca`,mimeType:'video/mp4',state:'ACTIVE'}},{headers:{'x-goog-upload-status':'final'}}); + return Response.json({}); + }}); + const host=caller==='reference'?'github.com':['dns','private','metadata'].includes(source.name)?'localhost':'127.0.0.1'; + origin=`http://${host}:${upstream.port}`; + const options:EgressProxyOptions={mode:source.name==='allowlist'?'allowlist':'record',allow:[],deny:source.name==='deny'?[host]:[],maxBytes:source.name==='budget'?0:65536, + signal:root.signal,outwardHosts:source.name.includes('outward')||source.name.startsWith('card ')?[host]:[], + approveOutward:async()=>{if(source.name.startsWith('card '))phase=true;if(source.name==='stale outward')revision='2';return source.name!=='declined outward';}, + observe:r=>records.push(r),inputCurrent:()=>source.name!=='source removal', + admissionSafety:{read:()=>{ + if(source.name==='initial read error'||(source.name==='late read error'||source.name==='card read error')&&phase)throw new Error('Athena cannot verify recording'); + return {evidenceRevision:'1',trustRevision:'1',authorityEpoch:'1',scope:'ithaca',policyHash:null,restricted:false, + recordingAvailable:!(source.name==='initial recording'||(source.name==='late recording'||source.name==='card recording')&&phase), + authorityCurrent:!(source.name==='initial authority'||(source.name==='late authority'||source.name==='card authority')&&phase)}; + },subscribe:()=>()=>{}}, + taint:{allow:[],tainted:()=>!!('g6' in source&&source.g6)&&(source.name!=='late taint'||phase),contacted:()=>false,approvalRevision:()=>source.name.startsWith('card ')?JSON.stringify([revision,phase]):revision, + ...(source.name==='declined Network'||source.name==='stale Network'?{approve:async()=>{if(source.name==='stale Network')revision='2';return source.name!=='declined Network';}}:{})}, + admitted:async()=>{phase=true;if(source.name==='host refusal')throw new EgressAdmissionRefused();if(source.name==='host error')throw new Error('Athena cannot record');if(source.name==='turn cancellation')root.abort();if(source.name==='recording abort')root.abort(new EgressAdmissionRefused('Recording failed','egress_unavailable'));}, + ...(['port','dns','private','metadata'].includes(source.name)?{destinations:{ports:source.name==='port'?[]:[upstream.port!,443],allowRanges:['127.0.0.0/8'],lookup:async()=>{if(source.name==='dns')throw new Error('No DNS');return [{address:source.name==='private'?'10.0.0.1':source.name==='metadata'?'169.254.169.254':'127.0.0.1',family:4}];}}}:{}), + }; + const egress=await startEgressProxy(options); + let relay:ReturnType|ReturnType|undefined; + let wire:Awaited>|undefined; + const exemption='g6' in source&&source.g6&&['inference','provider','cleanup'].includes(caller); + let status=0; + try{ + if(caller==='HTTP')status=(await http(egress.socketPath,origin+'/').catch(()=>({status:0}))).status; + else if(caller==='CONNECT')status=await tunnel(egress.socketPath,`${host}:${upstream.port}`).catch(()=>0); + else if(caller==='inference'){ + relay=startInferenceRelay({upstream:origin,routes:['/v1/messages'],credentials:{'x-api-key':'odysseus-key'},egress}); + status=(await http(relay.socketPath,'/v1/messages',{'content-type':'application/json'},JSON.stringify({model:'odysseus-model',messages:[]})).catch(()=>({status:0}))).status; + }else if(caller==='provider'||caller==='cleanup'){ + const family=caller==='cleanup'?'gemini':'anthropic',key=caller==='cleanup'?'GEMINI_API_KEY':'ANTHROPIC_API_KEY'; + const relayOptions:ProviderRelayOptions={origins:new Map([[key,[origin]]]),credential:()=> 'odysseus-key',observe:r=>receipts.push(r),get egress(){return caller==='cleanup'&&!armed?undefined:egress;}}; + relay=startProviderRelay(relayOptions); + const headers={'x-brain-provider':family,'x-brain-provider-key':key,'x-brain-provider-origin':origin,'content-type':'application/json'}; + if(caller==='provider')status=(await http(relay.socketPath,'/v1/messages',headers,JSON.stringify({model:'odysseus-model',messages:[]})).catch(()=>({status:0}))).status; + else{ + const start=await http(relay.socketPath,'/upload/v1beta/files',{...headers,'x-goog-upload-protocol':'resumable','x-goog-upload-command':'start','x-goog-upload-header-content-length':'5','x-goog-upload-header-content-type':'video/mp4'},JSON.stringify({file:{mimeType:'video/mp4'}})); + expect(start.status,'CLEANUP_MATRIX_HAS_A_REAL_OWNED_FILE').toBe(200); + const url=new URL(String(start.headers['x-goog-upload-url'])); + const upload=await http(relay.socketPath,url.pathname+url.search,{...headers,'x-goog-upload-command':'upload, finalize','x-goog-upload-offset':'0'},'troy!');expect(upload.status).toBe(200); + hits=0;receipts.length=0;armed=true;await relay.stop();status=receipts.at(-1)?.status??0; + } + }else{ + wire=await createGitHubReferenceWire({repository:'odysseus/ithaca',egress,maxBytes:65536,authorize(){},lookup:async()=>[{address:'93.184.216.34',family:4}],connect:()=>connect({host:'127.0.0.1',port:upstream.port!})}); + const url=new URL(wire.gitProxyUrl(false));await new Promise((resolve,reject)=>{const s=connect({host:url.hostname,port:Number(url.port)});s.on('error',reject);s.on('connect',()=>s.write(`CONNECT github.com:443 HTTP/1.1\r\nHost: github.com:443\r\nProxy-Authorization: Basic ${Buffer.from(`${url.username}:${url.password}`).toString('base64')}\r\n\r\n`));s.on('data',()=>{});s.on('close',resolve);}); + const reason=(wire.failure() as {reason?:string}|null)?.reason; + expect(reason,'REFERENCE_PRESERVES_STORED_REFUSAL').toBe(source.category==='budget'?'capacity':source.category==='unavailable'||source.category==='cancelled'?'unavailable':'denied'); + } + for(let i=0;!records.length&&i<100;i++)await Bun.sleep(1); + const record=records.at(-1); + if(exemption){expect(status,'HOST_RELAYS_RETAIN_G5_EXEMPTION').toBe(200);expect(record?.failureReason).toBeUndefined();} + else{ + if(caller==='cleanup')expect(status,'RECEIPT_HAS_NO_UPSTREAM_STATUS_BEFORE_RESPONSE').toBe(0); + else if(caller!=='reference')expect(status,'CALLER_PRESERVES_REFUSAL_STATUS').toBe((source.category==='cancelled'||source.name==='recording abort')&&['HTTP','CONNECT'].includes(caller)?0:source.category==='unavailable'?503:source.category==='cancelled'?499:403); + expect(record,'CALLER_PRESERVES_TERMINAL_AUDIT').toMatchObject({reason:source.detail,failureReason:source.category,outcome:source.category==='cancelled'||source.name==='source removal'?'cancelled':source.name==='host error'?'failed':'denied'}); + expect(hits,'REFUSED_OPERATION_NEVER_DISPATCHES').toBe(0); + } + }finally{await wire?.close();await relay?.stop();egress.stop();upstream.stop(true);} +}); diff --git a/packages/ui-server/tests/fixtures/pending-safety-writer.ts b/packages/ui-server/tests/fixtures/pending-safety-writer.ts new file mode 100644 index 0000000000..10c06af122 --- /dev/null +++ b/packages/ui-server/tests/fixtures/pending-safety-writer.ts @@ -0,0 +1,8 @@ +/** Holds one real writer's procedure without a SQLite lock, leaving peer writers usable. */ +export const url = import.meta.url; +export function setup() { + return { hold(entered:Int32Array,release:Int32Array,watchdog:number) { + Atomics.store(entered,0,1);Atomics.notify(entered,0); + if(Atomics.wait(release,0,0,watchdog)==="timed-out")throw new Error("Pending safety writer fixture was not released"); + } }; +} diff --git a/packages/ui-server/tests/github-reference-wire.test.ts b/packages/ui-server/tests/github-reference-wire.test.ts index cd17f1f6bd..f1afad011a 100644 --- a/packages/ui-server/tests/github-reference-wire.test.ts +++ b/packages/ui-server/tests/github-reference-wire.test.ts @@ -13,9 +13,10 @@ afterAll(() => rmSync(root, { recursive: true, force: true })); const publicAddress = "93.184.216.34"; const metadata = { id: 101, owner: { id: 201, login: "Odysseus" }, name: "Ithaca", private: false }; async function fixture(port: number, options: { owner?: string; maxBytes?: number; turnBytes?: number; timeoutMs?: number; signal?: AbortSignal; authorize?: (recipient: "git" | "metadata", credentialed: boolean) => void; + recordingAvailable?: () => boolean; lookup?: (host: string, options: { all: true; verbatim: true }) => Promise<{ address: string; family: number }[]> } = {}) { const records: EgressRecord[] = [], destinations: unknown[] = []; - const egress = await startEgressProxy({ mode: "record", allow: [], deny: [], outwardHosts: [], maxBytes: options.turnBytes ?? 1048576, observe: r => records.push(r) }); + const egress = await startEgressProxy({ mode: "record", allow: [], deny: [], outwardHosts: [], maxBytes: options.turnBytes ?? 1048576, observe: r => records.push(r),...(options.recordingAvailable?{admissionSafety:{read:()=>({evidenceRevision:"1",trustRevision:"1",authorityEpoch:"1",scope:"ithaca",policyHash:null,restricted:false,recordingAvailable:options.recordingAvailable!(),authorityCurrent:true}),subscribe:()=>()=>{}}}:{}) }); try { const wire = await createGitHubReferenceWire({ ...(options.owner ? { owner: options.owner } : { repository: "odysseus/ithaca" }), egress, maxBytes: options.maxBytes ?? 1048576, authorize: options.authorize ?? (() => {}), timeoutMs: options.timeoutMs, signal: options.signal, ca: readFileSync(tls.ca, "utf8"), @@ -51,7 +52,7 @@ test("fixed metadata GET meters actual TLS, HTTP framing and both anonymous and expect(authority).toContainEqual(["metadata", false]); expect(authority).toContainEqual(["metadata", true]); expect(f.wire.bytes().chargedBytes, "REFERENCE_TLS_AND_METADATA_WIRE_ACCOUNTED").toBeGreaterThan(JSON.stringify(metadata).length * 2); expect(f.egress.usedBytes()).toBe(f.wire.bytes().chargedBytes); - expect(f.destinations).toEqual([{ host: publicAddress, port: 443 }, { host: publicAddress, port: 443 }]); + expect(f.destinations).toEqual([{ host: publicAddress, port: 443,signal:expect.any(AbortSignal) }, { host: publicAddress, port: 443,signal:expect.any(AbortSignal) }]); } finally { await f.close(); server.stop(true); } }); @@ -178,3 +179,10 @@ for (const kind of ["cancel", "deadline", "turn-stop"] as const) test(`reference expect(f.wire.bytes().chargedBytes).toBe(0); } finally { release(); await pending.catch(() => {}); await f.close(); } }); + + +for(const unavailable of [false,true])test(`review12: managed chunks preserve ${unavailable?'unavailable':'capacity'} after an independent change`,async()=>{ + let available=true,received!:()=>void;const reached=new Promise(r=>{received=r;});const server=createServer(socket=>socket.on('data',b=>socket.write(b.toString().toUpperCase())));await new Promise(r=>server.listen(0,'127.0.0.1',r));const f=await fixture((server.address() as {port:number}).port,{turnBytes:64,...(unavailable?{recordingAvailable:()=>available}:{})});const url=new URL(f.wire.gitProxyUrl(false)),client=connect({host:url.hostname,port:Number(url.port)});client.on('error',()=>{});let text='';const closed=new Promise(r=>client.once('close',()=>r())); + try{client.on('data',b=>{text+=b;if(text.includes('FIRST'))received();});client.once('connect',()=>client.write(`CONNECT github.com:443 HTTP/1.1\r\nHost: github.com:443\r\nProxy-Authorization: Basic ${Buffer.from(`${url.username}:${url.password}`).toString('base64')}\r\n\r\nfirst`));await reached;if(unavailable)available=false;else{const other=f.egress.inference('POST',new URL('https://api.example.org/'),new AbortController().signal);expect(await other.admit()).toBe(true);expect(other.charge(f.egress.remainingBytes()).ok).toBe(true);other.finish('completed');}client.write('second');await closed;expect(f.wire.failure(),'MANAGED_CHUNKS_PRESERVE_TYPED_SEND_FAILURE').toMatchObject({reason:unavailable?'unavailable':'capacity'});expect(text).not.toContain('SECOND'); + }finally{client.destroy();await f.close();await new Promise(r=>server.close(()=>r()));} +}); diff --git a/packages/ui-server/tests/helpers/held-owner-reviews.ts b/packages/ui-server/tests/helpers/held-owner-reviews.ts new file mode 100644 index 0000000000..ba52ca29f2 --- /dev/null +++ b/packages/ui-server/tests/helpers/held-owner-reviews.ts @@ -0,0 +1,22 @@ +import type { SafetyReviewBody } from "@schlessera/brain-ui-sdk/protocol"; +import type { Principal } from "../../src/db/principals"; +import type { GovernanceWrites } from "../../src/governance/event-writes"; +import type { OwnerSafetyReviews } from "../../src/governance/owner-safety-reviews"; + +/** Fill the real owner service's pending quota while holding only its lowest + * preparation RPC. The DB writer remains available to publication and reads. */ +export async function holdOwnerReviews(host: { reviews: OwnerSafetyReviews; writes: GovernanceWrites; principal: Principal }, body: SafetyReviewBody) { + const released = Promise.withResolvers(), original = host.writes.safetyPrepareReview; + let entered = 0; + host.writes.safetyPrepareReview = async (...args) => { entered++; await released.promise; return original(...args); }; + const pending = Array.from({ length: 32 }, () => host.reviews.review(host.principal,body,null)); + host.writes.safetyPrepareReview = original; + const drain = async () => { + released.resolve(); + const results = await Promise.allSettled(pending); + const errors = results.filter(result=>result.status==="rejected").map(result=>result.reason); + if (errors.length) throw new AggregateError(errors,"Held owner reviews failed to drain"); + }; + if (entered !== 32) { await drain(); throw new Error(`Expected 32 admitted owner reviews, got ${entered}`); } + return { close:drain }; +} diff --git a/packages/ui-server/tests/helpers/http-mount-lifetimes.ts b/packages/ui-server/tests/helpers/http-mount-lifetimes.ts index 3a0d663ac0..0ab325a629 100644 --- a/packages/ui-server/tests/helpers/http-mount-lifetimes.ts +++ b/packages/ui-server/tests/helpers/http-mount-lifetimes.ts @@ -96,6 +96,9 @@ export const mountLifetimes: Record = { body: { code: "unavailable", reason: "unavailable", retryable: false }, verify: unavailableSafetyReview }, "POST /api/sessions/:id/safety/reviews/:requestId/commit": { path: "/api/sessions/fixture-session/safety/reviews/missing-request/commit", init: json("POST", safetyReviewBody), status: 404, body: { code: "unavailable", reason: "unavailable", retryable: false }, verify: unavailableSafetyReview }, + "POST /api/sessions/:id/safety/reviews/future/prepare": { path: "/api/sessions/fixture-session/safety/reviews/future/prepare", init: json("POST", {...safetyReviewBody,future:{incomingContent:true,recipientWhileRestricted:false}}), status: 403, + body: { code: "unavailable", reason: "invalid_request", retryable: false }, verify: unavailableSafetyReview }, + "POST /api/sessions/:id/safety/reviews/future/commit": { path: "/api/sessions/fixture-session/safety/reviews/future/commit", init: json("POST", {version:1,requestId:"missing-request",reviewId:"missing-review",reviewedBytesHash:"a".repeat(64)}), status: 404, + body: { code: "unavailable", reason: "unavailable", retryable: false }, verify: unavailableSafetyReview }, + "POST /api/sessions/:id/safety/reviews/future/status": { path: "/api/sessions/fixture-session/safety/reviews/future/status", init: json("POST", {version:1,session:safetyReviewBody.session,occurrenceId:safetyReviewBody.occurrenceId}), status: 404, + body: { code: "unavailable", retryable: false }, verify: unavailableSafetyReview }, "GET /api/sessions/:id/attachment-reads": { path: "/api/sessions/fixture-session/attachment-reads", body: { sessionId: "fixture-session", reads: [] }, verify: async (r) => { expect(r.headers.get("cache-control")).toBe("no-store"); } }, "GET /api/sessions/:id/recovery": { path: "/api/sessions/fixture-session/recovery", body: { sessionId: "fixture-session", revision: 0, latest: { requestId: null, turnId: null, state: "unknown", outcome: null }, pending: [] }, verify: async (r) => { expect(r.headers.get("cache-control")).toBe("no-store"); } }, "GET /api/push/public-key": { verify: async (r) => { const b = await r.json(); expect(b.publicKey.length).toBeGreaterThan(0); expect(Object.keys(b)).toEqual(["publicKey"]); } }, diff --git a/packages/ui-server/tests/origin-trust.test.ts b/packages/ui-server/tests/origin-trust.test.ts new file mode 100644 index 0000000000..46eb0fc1f2 --- /dev/null +++ b/packages/ui-server/tests/origin-trust.test.ts @@ -0,0 +1,338 @@ +import { createEffectiveSafety } from "../src/governance/effective-safety.js"; +import { Database } from "bun:sqlite"; +import { watchdogMs } from "../../../scripts/test-deadlines.js"; +import { expect, test, spyOn } from "bun:test"; +import { mkdtempSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { openSqliteWriter } from "../src/db/write-worker.js"; +import { connect } from "node:net"; +import { request } from "node:http"; +import { resolveGovernancePolicy, type TrustRule, type GovernancePolicyInput } from "@schlessera/brain-common/internal/governance-policy"; +import type { BackendBridge, PermissionDecision } from "@schlessera/brain-ui-sdk/server"; +import { createUiDb } from "../src/db/client.js"; +import { createGovernanceWrites } from "../src/governance/event-writes.js"; +import { queryGovernanceEvents } from "../src/governance/events.js"; +import { occurrence } from "../src/governance/occurrence.js"; +import { safetyProjection, pruneSafetyDetail } from "../src/governance/safety-store.js"; +import { prepareTurnEgress } from "../src/brain/turn-egress.js"; +import { originTrustMatch, type OriginTrust } from "../src/brain/origin-trust.js"; +import { connectedSafetySession } from "./helpers/connected-safety.js"; +function get(socketPath: string, target: string): Promise { + return new Promise((resolve, reject) => { const r = request({ socketPath, path: target }, response => { + response.resume(); response.once("end", () => resolve(response.statusCode!)); response.once("error", reject); + }); r.once("error", reject); r.end(); }); +} +function trust(rule: TrustRule) { + let revision = "1", rules = [rule], policyHash="a".repeat(64),ruleInstances:Record={[rule.id]:"1"}; const listeners = new Set<() => void>(); + const live: OriginTrust = { revision: () => revision, read: () => ({revision,rules,policyHash,ruleInstances}), subscribe: cb => {listeners.add(cb);return () => {listeners.delete(cb);};} }; + return { live, publish(next:TrustRule[]) {const old=new Map(rules.map(r=>[r.id,JSON.stringify([r.selector,r.incomingContent])]));revision=String(BigInt(revision)+1n);ruleInstances=Object.fromEntries(next.map(r=>[r.id,old.get(r.id)===JSON.stringify([r.selector,r.incomingContent])?ruleInstances[r.id]??revision:revision]));rules=next;policyHash=revision.padStart(64,"0");for(const cb of listeners)cb();}, remove(notify=true) { rules=[];ruleInstances={};revision=String(BigInt(revision)+1n);policyHash="b".repeat(64);if(notify)for(const cb of listeners)cb(); } }; +} +async function fixture(recipient = false, policy: GovernancePolicyInput = {schema_version:1}, response?: () => Response, full = false, listenHost = "127.0.0.1", legacy = false) { + const root=full?mkdtempSync(join(tmpdir(),"odysseus-origin-trust-")):null; + const db = createUiDb(root?join(root,"ui.db"):":memory:"); connectedSafetySession(db,"voyage","turn-voyage"); + const writer=full?openSqliteWriter(db):undefined; + const writes = createGovernanceWrites(db,writer); let asks = 0, hits = 0; + let decide: BackendBridge["requestPermission"] = async () => ({behavior:"deny",message:"Athena declines"}); + const origin = Bun.serve({hostname:listenHost,port:0,fetch(){hits++;return response?.() ?? new Response("Ithaca");}}); + const rule: TrustRule = {id:"ithaca",label:"Ithaca",incomingContent:true,recipientWhileRestricted:recipient, + selector:{kind:"web_origin",scheme:"http",host:origin.url.hostname,port:origin.port!}}; + const t=trust(rule);const controller=new AbortController(); + const bridge={emit(){},requestPermission:async(...args: Parameters)=>{asks++;return decide(...args);},admissionSafety:createEffectiveSafety(db,{turnId:"turn-voyage",sessionId:()=>"voyage",policyHash:null,writes,trust:t.live,authority:()=>({current:true,epoch:"0"})})} as unknown as BackendBridge; + const proxy=await prepareTurnEgress({policy:resolveGovernancePolicy(policy),trust:t.live,controller,turnId:"turn-voyage",sessionId:()=>"voyage",model:()=>null,profile:"governed",origin:"interactive",governanceDb:db,governanceWrites:legacy?undefined:writes,record:legacy?event=>writes.record(event):writes.record, + bridge}); + const epoch=(db.query("SELECT id FROM safety_collections WHERE turn_id='turn-voyage'").get() as {id:string}).id; + const taint=()=>writes.firstTaint({kind:"taint",turnId:"turn-voyage",sessionId:"voyage",actor:"interactive",profile:"governed",model:null,payload:{source:"web_search",tool:null,detail:null,occurrence:occurrence(epoch,"tool_web_input",crypto.randomUUID(),"finalized")}}); + return {db,writes,writer,origin,proxy,t,taint,controller,bridge,decide(value: BackendBridge["requestPermission"]) { decide=value; },asks:()=>asks,hits:()=>hits,async close(){proxy.stop();origin.stop(true);await proxy.settled();await writer?.close();db.close();if(root)rmSync(root,{recursive:true,force:true});}}; +} +test("verified future input retains its decision without creating an unresolved trigger or recipient grant",async()=>{ + const f=await fixture();try{ + expect(await get(f.proxy.socketPath,f.origin.url.href)).toBe(200);await f.proxy.settled(); + expect(safetyProjection(f.db,"turn-voyage","voyage").unresolvedCount,"ORIGIN_TRUST_NO_UNRESOLVED").toBe(0); + const events=queryGovernanceEvents(f.db,{kinds:["taint"],limit:10});expect(events[0]?.payload).toMatchObject({occurrence:{admission:{trusted:true,ruleId:"ithaca",trustRevision:"1",policyHash:"a".repeat(64)}}}); + await f.taint();expect(await get(f.proxy.socketPath,f.origin.url.href),"SOURCE_ONLY_STILL_ASKS").toBe(403);expect(f.asks()).toBe(1);expect(f.hits()).toBe(1); + }finally{await f.close();} +}); +test("explicit exact recipient permits only the taint card while unrelated triggers remain",async()=>{ + const f=await fixture(true);try{await f.taint();expect(await get(f.proxy.socketPath,f.origin.url.href),"EXPLICIT_RECIPIENT_ADMITTED").toBe(200);expect(f.asks()).toBe(0);await f.proxy.settled();expect(f.proxy.recordingFailure()).toBeUndefined();expect(queryGovernanceEvents(f.db,{kinds:["egress_connection"],limit:10})[0]?.payload).toMatchObject({recipientAdmission:{ruleId:"ithaca",trustRevision:"1"}});expect(safetyProjection(f.db,"turn-voyage","voyage").unresolvedCount).toBe(1); + }finally{await f.close();} +}); +test("removal fences future admissions and preserves historical trust",async()=>{ + const f=await fixture();try{expect(await get(f.proxy.socketPath,f.origin.url.href)).toBe(200);await f.proxy.settled();f.t.remove(); + await f.taint();expect(await get(f.proxy.socketPath,f.origin.url.href)).toBe(403); + const events=queryGovernanceEvents(f.db,{kinds:["taint"],limit:10});expect(events.some(e=>(e.payload as any).occurrence?.admission?.trusted)).toBe(true); + }finally{await f.close();} +}); + +test("exact recipients cannot cover another port, a subdomain or opaque CONNECT",async()=>{ + const f=await fixture(true);const other=Bun.serve({hostname:"127.0.0.1",port:0,fetch:()=>new Response("Troy")}); + try{await f.taint();expect(await get(f.proxy.socketPath,other.url.href)).toBe(403); + f.t.live.read().rules[0]!.selector={kind:"web_origin",scheme:"http",host:"localhost",port:f.origin.port!}; + expect(await get(f.proxy.socketPath,`http://sub.localhost:${f.origin.port}/`)).toBe(403); + expect(f.asks(),"SUBDOMAIN_REQUIRES_ITS_OWN_CARD").toBe(2); + const status=await new Promise((resolve,reject)=>{const c=connect(f.proxy.socketPath);c.on("error",reject);c.on("connect",()=>c.write(`CONNECT 127.0.0.1:${f.origin.port} HTTP/1.1\r\nHost: 127.0.0.1\r\n\r\n`));c.on("data",b=>{resolve(Number(/^HTTP\/1.1 (\d+)/.exec(b.toString())?.[1]));c.destroy();});}); + expect(status,"HTTPS_RULE_NEVER_COVERS_OPAQUE_TUNNEL").toBe(403);expect(f.asks()).toBe(3);expect(f.hits()).toBe(0); + }finally{other.stop(true);await f.close();} +}); +for(const policy of [{schema_version:1,egress:{deny:["127.0.0.1"]}},{schema_version:1,egress:{mode:"allowlist",allow:["ithaca.invalid"]}},{schema_version:1,egress:{max_bytes_per_turn:1}},{schema_version:1,outward:{hosts:["127.0.0.1"]}}] satisfies GovernancePolicyInput[])test(`trust retains independent controls ${JSON.stringify(policy)}`,async()=>{ + const f=await fixture(true,policy);try{await f.taint();expect(await get(f.proxy.socketPath,f.origin.url.href)).toBe(403);expect(f.hits()).toBe(0);}finally{await f.close();} +}); +test("source removal during durable admission refuses the actual upstream dispatch",async()=>{ + const f=await fixture(false,{schema_version:1},undefined,true);let entered!:()=>void,release!:()=>void;const reached=new Promise(r=>{entered=r;}),held=new Promise(r=>{release=r;});const original=f.writes.firstTaint; + f.writes.firstTaint=async(...args)=>{entered();await held;return original(...args);}; + try{const pending=get(f.proxy.socketPath,f.origin.url.href).catch(()=>0);await reached;f.t.remove();release();await pending;await f.proxy.settled();expect(f.hits(),"REMOVAL_AFTER_WRITE_WAIT_PREVENTS_DISPATCH").toBe(0);expect(f.proxy.recordingFailure(),"REMOVAL_DURING_WRITE_KEEPS_RECORDER_HEALTHY").toBeUndefined();expect(f.controller.signal.aborted).toBe(false);}finally{release();await f.close();} +}); +test("removal interrupts an actual open trusted response before later input",async()=>{ + let stream!:ReadableStreamDefaultController; + const f=await fixture(false,{schema_version:1},()=>new Response(new ReadableStream({start(c){stream=c;c.enqueue(new TextEncoder().encode("first"));}}))); + const other=Bun.serve({hostname:"127.0.0.1",port:0,fetch:()=>new Response("Troy")}); + let first!:()=>void;const received=new Promise(r=>{first=r;});let text=""; + const closed=new Promise((resolve,reject)=>{const r=request({socketPath:f.proxy.socketPath,path:f.origin.url.href},response=>{response.on("data",b=>{text+=b;first();});response.on("close",resolve);response.on("error",()=>resolve());});r.on("error",reject);r.end();}); + try{await received;expect(await get(f.proxy.socketPath,other.url.href)).toBe(200);f.t.remove();await f.proxy.settled();expect(queryGovernanceEvents(f.db,{kinds:["egress_connection"],limit:10}).find(e=>(e.payload as any).port===f.origin.port)?.payload,"REMOVAL_SYNCHRONOUSLY_STOPS_STREAM").toMatchObject({outcome:"cancelled"});expect(f.controller.signal.aborted).toBe(false);try{stream.enqueue(new TextEncoder().encode("later"));}catch{}await closed;expect(text).toBe("first");expect(await get(f.proxy.socketPath,other.url.href),"TRUST_REMOVAL_LEAVES_UNRELATED_TURN_TRAFFIC_USABLE").toBe(200);await f.proxy.settled();expect(queryGovernanceEvents(f.db,{kinds:["taint_exposure"],limit:10}).some(e=>(e.payload as any).state==="interrupted_unknown")).toBe(true);}finally{other.stop(true);await f.close();} +}); +test("pruning retains historical admission facts without turning trusted input unresolved",async()=>{ + const f=await fixture();try{expect(await get(f.proxy.socketPath,f.origin.url.href)).toBe(200);await f.proxy.settled();pruneSafetyDetail(f.db,Date.now()+1);expect(safetyProjection(f.db,"turn-voyage","voyage").unresolvedCount).toBe(0);const rows=f.db.query("SELECT payload FROM safety_records WHERE kind='occurrence'").all() as {payload:string}[];expect(JSON.parse(rows[0]!.payload).admission).toMatchObject({trusted:true,ruleId:"ithaca"});}finally{await f.close();} +}); +test("recipient-only permission never turns into a legacy hostname grant after removal",async()=>{ + const f=await fixture(true);try{f.t.live.read().rules[0]!.incomingContent=false;await f.taint();expect(await get(f.proxy.socketPath,f.origin.url.href)).toBe(200);await f.proxy.settled();f.t.remove();expect(await get(f.proxy.socketPath,f.origin.url.href),"RECIPIENT_REMOVAL_NO_LEGACY_GRANT").toBe(403);expect(f.asks()).toBe(1);expect(f.hits()).toBe(1);}finally{await f.close();} +}); +test("a redirect destination and concurrent unrelated traffic cannot borrow an exact rule",async()=>{ + const other=Bun.serve({hostname:"127.0.0.1",port:0,fetch:()=>new Response("Troy")}); + const f=await fixture(true,{schema_version:1},()=>Response.redirect(other.url.href));try{await f.taint();const results=await Promise.all([get(f.proxy.socketPath,f.origin.url.href),get(f.proxy.socketPath,other.url.href)]);expect(results).toEqual([302,403]);expect(f.asks()).toBe(1);expect(safetyProjection(f.db,"turn-voyage","voyage").unresolvedCount).toBe(1);}finally{other.stop(true);await f.close();} +}); +test("an explicitly reviewed tunnel matches its opaque authority without asserting HTTPS",async()=>{ + const f=await fixture(true);try{f.t.live.read().rules[0]!.selector={kind:"tunnel_authority",host:"127.0.0.1",port:f.origin.port!};await f.taint(); + const status=await new Promise((resolve,reject)=>{const c=connect(f.proxy.socketPath);c.on("error",reject);c.on("connect",()=>c.write(`CONNECT 127.0.0.1:${f.origin.port} HTTP/1.1\r\nHost: 127.0.0.1\r\n\r\n`));c.on("data",b=>{resolve(Number(/^HTTP\/1.1 (\d+)/.exec(b.toString())?.[1]));c.destroy();});});expect(status).toBe(200);expect(f.asks()).toBe(0); + const event=queryGovernanceEvents(f.db,{kinds:["taint"],limit:10}).find(e=>(e.payload as any).source==="egress_connection");expect(event?.payload).toMatchObject({occurrence:{provenance:{kind:"tunnel_authority"},admission:{trusted:true}}}); + expect(await get(f.proxy.socketPath,f.origin.url.href)).toBe(403);expect(f.asks()).toBe(1); + }finally{await f.close();} +}); + +test("recipient removal during outward approval cannot carry the old rule across the wait",async()=>{ + const f=await fixture(true,{schema_version:1,outward:{hosts:["127.0.0.1"]}});let entered!:()=>void,release!:()=>void;const reached=new Promise(r=>{entered=r;}),held=new Promise(r=>{release=r;}); + try{f.t.live.read().rules[0]!.incomingContent=false;await f.taint();let asks=0;f.decide(async()=>{if(++asks===1){entered();await held;return {behavior:"allow"};}return {behavior:"deny",message:"Athena declines the new taint card"};}); + const pending=get(f.proxy.socketPath,f.origin.url.href);await reached;f.t.remove();release();expect(await pending,"RECIPIENT_REMOVAL_REVALIDATES_AFTER_OUTWARD_WAIT").toBe(403);expect(asks,"STALE_OUTWARD_CARD_TERMINATES_WITHOUT_AUTOMATIC_REPROMPT").toBe(1);expect(f.hits()).toBe(0); + }finally{release();await f.close();} +}); +test("removing incoming trust leaves its historical decision and makes a later input independently unresolved",async()=>{ + const f=await fixture();try{expect(await get(f.proxy.socketPath,f.origin.url.href)).toBe(200);await f.proxy.settled();f.t.remove();expect(await get(f.proxy.socketPath,f.origin.url.href)).toBe(200);await f.proxy.settled();expect(safetyProjection(f.db,"turn-voyage","voyage").unresolvedCount,"REMOVAL_APPLIES_ONLY_TO_FUTURE_INPUT").toBe(1);const rows=queryGovernanceEvents(f.db,{kinds:["taint"],limit:10});expect(rows.map(e=>(e.payload as any).occurrence.admission.trusted).sort()).toEqual([false,true]);}finally{await f.close();} +}); + +test("review: an approved card cannot survive independent input during its occurrence write",async()=>{ + const f=await fixture(false,{schema_version:1},undefined,true);let entered!:()=>void,release!:()=>void;const reached=new Promise(r=>{entered=r;}),held=new Promise(r=>{release=r;});const original=f.writes.firstTaint; + try{await f.taint();f.decide(async()=>({behavior:"allow"}));f.writes.firstTaint=async(...args)=>{if(args[0].payload.source==="egress_connection"){entered();await held;}return original(...args);}; + const pending=get(f.proxy.socketPath,f.origin.url.href);await reached;await f.taint();release();expect(await pending,"STALE_APPROVAL_AFTER_INDEPENDENT_WRITE_REFUSES_DISPATCH").toBe(403);expect(f.hits()).toBe(0); + }finally{release();await f.close();} +}); +for(const trusted of [false,true])test(`review: a card remains usable across only its own durable occurrence write (trusted ${trusted})`,async()=>{ + const f=await fixture(false,{schema_version:1},undefined,true);try{if(!trusted)f.t.live.read().rules[0]!.selector={kind:"web_origin",scheme:"http",host:"ithaca.invalid",port:f.origin.port!};await f.taint();f.decide(async()=>({behavior:"allow"}));expect(await get(f.proxy.socketPath,f.origin.url.href),"OWN_OCCURRENCE_DOES_NOT_WITHDRAW_APPROVAL").toBe(200);}finally{await f.close();} +}); +for(const tunnel of [false,true])test(`review: managed HTTPS recipient uses actual transport identity (tunnel ${tunnel})`,async()=>{ + const f=await fixture(true);try{await f.taint();f.t.live.read().rules[0]!.selector=tunnel?{kind:"tunnel_authority",host:"github.com",port:443}:{kind:"web_origin",scheme:"https",host:"github.com",port:443}; + const op=f.proxy.managedReference(new URL("https://github.com/"),new AbortController().signal);const allowed=await op.admit();if(allowed)expect(op.dispatch(()=>{})).toEqual({ok:true});expect(allowed,"MANAGED_HTTPS_NEVER_BORROWS_OPAQUE_TUNNEL_PERMISSION").toBe(!tunnel);op.finish(allowed?"completed":"denied");await f.proxy.settled();if(allowed)expect(queryGovernanceEvents(f.db,{kinds:["egress_connection"],limit:10})[0]?.payload,"MANAGED_RECIPIENT_DECISION_RETAINS_AUDIT").toMatchObject({managedReference:true,standingRecipient:true,recipientAdmission:{ruleId:"ithaca"}}); + }finally{await f.close();} +}); +test("review: outward cards cannot survive independent input even on a taint-allowlisted host",async()=>{ + const f=await fixture(false,{schema_version:1,taint:{egress:{allow:["127.0.0.1"]}},outward:{hosts:["127.0.0.1"]}},undefined,true);let entered!:()=>void,release!:()=>void;const reached=new Promise(r=>{entered=r;}),held=new Promise(r=>{release=r;});const original=f.writes.firstTaint; + try{await f.taint();f.decide(async()=>({behavior:"allow"}));f.writes.firstTaint=async(...args)=>{if(args[0].payload.source==="egress_connection"){entered();await held;}return original(...args);};const pending=get(f.proxy.socketPath,f.origin.url.href);await reached;await f.taint();release();expect(await pending,"STALE_OUTWARD_CARD_CANNOT_BORROW_TAINT_ALLOWLIST").toBe(403);expect(f.hits()).toBe(0);}finally{release();await f.close();} +}); +test("review: independent pending input also withdraws a card on a permanently restricted turn",async()=>{ + const f=await fixture(false,{schema_version:1},undefined,true);let entered!:()=>void,release!:()=>void;const reached=new Promise(r=>{entered=r;}),held=new Promise(r=>{release=r;});const original=f.writes.firstTaint;let slow:Promise|undefined,pendingTaint:Promise|undefined; + try{f.db.query("UPDATE safety_collections SET restricted_begin=1,gap='uninstrumented_backend_input' WHERE turn_id='turn-voyage'").run();await f.taint();f.decide(async()=>({behavior:"allow"})); + f.writes.firstTaint=async(...args)=>{const result=await original(...args);if(args[0].payload.source==="egress_connection"){entered();await held;}return result;}; + const pending=get(f.proxy.socketPath,f.origin.url.href);await reached;const probe=await import('./fixtures/write-worker-probe');const channel=f.writer!.channel(probe,{table:'origin_pending_hold'});await channel.ready;const active=new Int32Array(new SharedArrayBuffer(4));slow=channel.call('slow','Calypso',400,active);await Atomics.waitAsync(active,0,0).value; + pendingTaint=f.taint();expect(f.writes.safety('turn-voyage','voyage').pendingCount).toBeGreaterThan(0);release();expect(await pending,'PENDING_INPUT_WITHDRAWS_CARD_WITHOUT_NORMALIZING_AWAY_OTHER_SIGNALS').toBe(403);expect(f.hits()).toBe(0); + }finally{release();await slow;await pendingTaint;await f.close();} +}); +test("review2: a later revision cannot join a hostname's earlier pending Network card",async()=>{ + const f=await fixture();const answers:Array<(v:PermissionDecision)=>void>=[];let firstReady!:()=>void,secondReady!:()=>void;const firstCard=new Promise(r=>{firstReady=r;}),secondRequest=new Promise(r=>{secondReady=r;});let first:Promise|undefined,second:Promise|undefined;const safety=f.bridge.admissionSafety!,read=safety.read; + try{delete f.bridge.admissionSafety;await f.taint();f.decide(()=>new Promise(r=>{answers.push(r);firstReady();}));first=get(f.proxy.socketPath,f.origin.url.href);await firstCard;await f.taint();let announced=false;safety.read=()=>{const value=read();if(!announced){announced=true;queueMicrotask(secondReady);}return value;};second=get(f.proxy.socketPath,f.origin.url.href);await secondRequest; + const cards=f.asks();answers[0]!({behavior:'allow'});expect(await first).toBe(403);if(cards===1){expect(await second,'OLDER_CARD_ANSWER_CANNOT_DISPATCH_A_LATER_CONTEXT').toBe(403);}else{expect(f.hits()).toBe(0);answers[1]!({behavior:'deny',message:'Athena declines the new context'});expect(await second).toBe(403);}expect(cards,'NEW_EVIDENCE_REQUIRES_A_NEW_NETWORK_CARD').toBe(2); + }finally{f.bridge.admissionSafety=safety;safety.read=read;for(const answer of answers)answer({behavior:'deny',message:'Closed'});await Promise.allSettled([first,second]);await f.close();} +}); +for(const pruned of [false,true])test(`review2: forks inherit unresolved input only, regardless of pruning (${pruned})`,async()=>{ + const f=await fixture();try{expect(await get(f.proxy.socketPath,f.origin.url.href)).toBe(200);await f.proxy.settled();if(pruned)pruneSafetyDetail(f.db,Number.MAX_SAFE_INTEGER);expect(f.writes.safety(null,'voyage').unresolvedCount).toBe(0); + await f.writes.safetyBegin({turnId:'fork-trusted',bindingId:crypto.randomUUID(),sessionId:null,principalId:'odysseus',backendId:'claude',sourceSessionId:'voyage',at:2});expect(f.writes.safety('fork-trusted',null).unresolvedCount,'FORK_NEVER_TURNS_TRUSTED_INPUT_INTO_AN_UNRESOLVED_SIGNAL').toBe(0);expect(f.writes.safety('fork-trusted',null).restriction).toBe('restricted'); + await f.taint();if(pruned)pruneSafetyDetail(f.db,Number.MAX_SAFE_INTEGER);await f.writes.safetyBegin({turnId:'fork-unresolved',bindingId:crypto.randomUUID(),sessionId:null,principalId:'odysseus',backendId:'claude',sourceSessionId:'voyage',at:3});expect(f.writes.safety('fork-unresolved',null).unresolvedCount).toBe(1); + }finally{await f.close();} +}); +test('review2: unchanged context still shares one pending destination card',async()=>{ + const f=await fixture();const answers:Array<(v:PermissionDecision)=>void>=[];let firstReady!:()=>void,secondReady!:()=>void;const firstCard=new Promise(r=>{firstReady=r;}),secondRequest=new Promise(r=>{secondReady=r;});let first:Promise|undefined,second:Promise|undefined;const safety=f.bridge.admissionSafety!,read=safety.read; + try{await f.taint();f.decide(()=>new Promise(r=>{answers.push(r);firstReady();}));first=get(f.proxy.socketPath,f.origin.url.href);await firstCard;let announced=false;safety.read=()=>{const value=read();if(!announced){announced=true;queueMicrotask(secondReady);}return value;};second=get(f.proxy.socketPath,f.origin.url.href);await secondRequest;expect(f.asks(),'UNCHANGED_CONTEXT_COALESCES_ONE_PENDING_CARD').toBe(1);answers[0]!({behavior:'deny',message:'Athena declines'});expect(await first).toBe(403);expect(await second).toBe(403); + }finally{safety.read=read;for(const answer of answers)answer({behavior:'deny',message:'Closed'});await Promise.allSettled([first,second]);await f.close();} +}); + +for(const phase of ['none','card','commit'] as const)test(`shared Network card with real FULL writer excludes only peer reservations (independent ${phase})`,async()=>{ + const f=await fixture(false,{schema_version:1},undefined,true);const independent=phase!=='none'; + const committed=Promise.withResolvers(),releaseAdmissions=Promise.withResolvers();let commits=0; + const card=Promise.withResolvers(),answer=Promise.withResolvers(),secondEntered=Promise.withResolvers(); + const safety=f.bridge.admissionSafety!,read=safety.read.bind(safety),firstTaint=f.writes.firstTaint; + const otherDb=new Database(f.db.filename),otherWriter=openSqliteWriter(otherDb),otherWrites=createGovernanceWrites(f.db,otherWriter); + const gate=new Int32Array(new SharedArrayBuffer(4)),entered=new Int32Array(new SharedArrayBuffer(4)); + let held:Promise|undefined,pendingInput:Promise|undefined,first:Promise|undefined,second:Promise|undefined,peak=0; + try{ + await f.taint(); + f.writes.firstTaint=(...args)=>{const pending=firstTaint(...args);peak=Math.max(peak,f.writes.safety('turn-voyage','voyage').pendingCount);return phase==='commit'?pending.then(async result=>{if(++commits===2)committed.resolve();await releaseAdmissions.promise;return result;}):pending;}; + f.decide(()=>{card.resolve();return answer.promise;});first=get(f.proxy.socketPath,f.origin.url.href);await card.promise; + let announced=false;safety.read=(...args)=>{const state=read(...args);if(!announced){announced=true;queueMicrotask(secondEntered.resolve);}return state;}; + second=get(f.proxy.socketPath,`${f.origin.url.href}again`);await secondEntered.promise;safety.read=read; + expect(f.asks(),'REAL_WRITER_PEERS_SHARE_EXACTLY_ONE_CARD').toBe(1); + if(phase==='commit'){answer.resolve({behavior:'allow'});await committed.promise;} + if(independent){ + const probe=await import('./fixtures/pending-safety-writer');const channel=otherWriter.channel(probe,undefined);await channel.ready; + held=channel.call('hold',entered,gate,watchdogMs(15000)); + if(!Atomics.load(entered,0))await Atomics.waitAsync(entered,0,0,watchdogMs(15000)).value; + expect(Atomics.load(entered,0),'INDEPENDENT_WRITER_IS_HELD_WITHOUT_BLOCKING_PEERS').toBe(1); + pendingInput=otherWrites.firstTaint({kind:'taint',turnId:'turn-voyage',sessionId:'voyage',actor:'interactive',profile:'governed',model:null,payload:{source:'web_search',tool:null,detail:'Odysseus reads a separate harbour notice'}}); + expect(f.writes.safety('turn-voyage','voyage').pendingCount).toBe(1); + } + answer.resolve({behavior:'allow'});releaseAdmissions.resolve(); + expect(await Promise.all([first,second]),independent?'INDEPENDENT_PENDING_INPUT_IS_NOT_A_CARD_PEER':'APPROVED_FULL_WRITER_PEERS_BOTH_DISPATCH').toEqual(independent?[403,403]:[200,200]); + expect(f.hits()).toBe(independent?0:2); + if(!independent)expect(peak,'REAL_PEER_WRITE_RESERVATIONS_OVERLAPPED').toBeGreaterThanOrEqual(2); + await f.proxy.settled(); + const rows=queryGovernanceEvents(f.db,{kinds:['egress_connection'],limit:10});expect(rows).toHaveLength(2); + for(const row of rows)expect(row.payload).toMatchObject(independent?{outcome:'denied',dispatched:false}:{outcome:'completed',dispatched:true}); + }finally{ + safety.read=read;answer.resolve({behavior:'deny',message:'Athena closes the fixture'});releaseAdmissions.resolve();Atomics.store(gate,0,1);Atomics.notify(gate,0); + await Promise.allSettled([held,pendingInput,first,second]);await otherWriter.close();otherDb.close();await f.close(); + } +}); + +test('review3: managed HTTPS and opaque CONNECT never share a pending Network card',async()=>{ + const f=await fixture();const answers:Array<(v:PermissionDecision)=>void>=[];let firstReady!:()=>void,secondReady!:()=>void;const firstCard=new Promise(r=>{firstReady=r;}),secondRequest=new Promise(r=>{secondReady=r;});const safety=f.bridge.admissionSafety!,read=safety.read; + let socket:ReturnType|undefined,managed:Promise|undefined,tunnel:Promise|undefined; + try{await f.taint();f.decide(()=>new Promise(r=>{answers.push(r);firstReady();}));const op=f.proxy.managedReference(new URL("https://github.com/"),new AbortController().signal);managed=op.admit();await firstCard; + let announced=false;safety.read=()=>{const value=read();if(!announced){announced=true;queueMicrotask(secondReady);}return value;}; + tunnel=new Promise((resolve,reject)=>{socket=connect(f.proxy.socketPath);socket.on('error',reject);socket.on('connect',()=>socket!.write(`CONNECT github.com:443 HTTP/1.1\r\nHost: github.com\r\n\r\n`));socket.on('data',b=>{resolve(Number(/^HTTP\/1.1 (\d+)/.exec(b.toString())?.[1]));socket!.destroy();});});await secondRequest; + const cards=f.asks();for(const answer of answers)answer({behavior:'deny',message:'Athena declines'});expect(await managed).toBe(false);op.finish('denied');expect(await tunnel).toBe(403);expect(cards,'MANAGED_AND_OPAQUE_TRANSPORTS_REQUIRE_DISTINCT_CARDS').toBe(2); + }finally{safety.read=read;for(const answer of answers)answer({behavior:'deny',message:'Closed'});socket?.destroy();await Promise.allSettled([managed,tunnel]);await f.close();} +}); + + +test('review4: IPv6 Settings selector reaches an exact real opaque tunnel',async()=>{ + const f=await fixture(true,{schema_version:1},undefined,false,'::1');try{await f.taint();f.t.live.read().rules[0]!.selector={kind:'tunnel_authority',host:'[::1]',port:f.origin.port!}; + const status=await new Promise((resolve,reject)=>{const c=connect(f.proxy.socketPath);c.on('error',reject);c.on('connect',()=>c.write(`CONNECT [::1]:${f.origin.port} HTTP/1.1\r\nHost: [::1]\r\n\r\n`));c.on('data',b=>{resolve(Number(/^HTTP\/1.1 (\d+)/.exec(b.toString())?.[1]));c.destroy();});});expect(status,'EXPLICIT_IPV6_TUNNEL_IS_ENFORCED').toBe(200);expect(f.asks()).toBe(0); + }finally{await f.close();} +}); +test('review4: exact DNS parent never authorizes its subdomain',()=>{ + const t=trust({id:'ithaca',label:'Ithaca',incomingContent:true,recipientWhileRestricted:true,selector:{kind:'web_origin',scheme:'https',host:'ithaca.example.org',port:443}}); + const destination={host:'ithaca.example.org',port:443,method:'GET',protocol:'https:'}; + expect(originTrustMatch(t.live,destination,'recipientWhileRestricted','0')).not.toBeNull(); + expect(originTrustMatch(t.live,{...destination,host:'sub.ithaca.example.org'},'recipientWhileRestricted','0'),'DNS_SUBDOMAIN_NEVER_INHERITS_PARENT_TRUST').toBeNull(); +}); + +test('review6: explicit recipient approval survives independently of a source-only rule',async()=>{ + const f=await fixture();try{await f.taint();f.decide(async()=>({behavior:'allow'}));expect(await get(f.proxy.socketPath,f.origin.url.href)).toBe(200);await f.proxy.settled();f.decide(async()=>({behavior:'deny',message:'No second card should appear'})); + expect(await get(f.proxy.socketPath,f.origin.url.href),'EXPLICIT_RECIPIENT_APPROVAL_SURVIVES_SOURCE_TRUST').toBe(200);expect(f.asks()).toBe(1);const {contactedHosts}=await import('../src/governance/session-taint');expect(contactedHosts(f.db,'voyage'),'EXPLICIT_RECIPIENT_APPROVAL_IS_DURABLE').toContain('127.0.0.1'); + }finally{await f.close();} +}); + + +for(const restricted of [false,true])test(`review7: streaming counters avoid history scans (restricted ${restricted})`,async()=>{ + const f=await fixture();try{if(restricted)await f.taint();f.decide(async()=>({behavior:'allow'}));const op=f.proxy.managedReference(new URL('https://github.com/'),new AbortController().signal);expect(await op.admit()).toBe(true); + const query=f.db.query.bind(f.db);let scans=0;const spy=spyOn(f.db,'query').mockImplementation(((...args:Parameters)=>{if(String(args[0]).includes('FROM safety_records'))scans++;return Reflect.apply(query,f.db,args);}) as typeof f.db.query); + try{expect(op.charge(1).ok).toBe(true);scans=0;for(let i=0;i<32;i++)expect(op.charge(1).ok).toBe(true);expect(scans,'STABLE_APPROVED_CHUNKS_NEVER_SCAN_HISTORY').toBe(0);await f.taint();expect(op.charge(1).ok,'NEW_INPUT_STILL_WITHDRAWS_CACHED_APPROVAL').toBe(false);}finally{spy.mockRestore();op.finish('cancelled');} + }finally{await f.close();} +}); + + +test('review7: provisional safety reads never survive a rolled-back transaction',async()=>{ + const f=await fixture();try{await f.taint();const safety=f.bridge.admissionSafety!;expect(safety.read().restricted).toBe(true); + expect(()=>f.db.transaction(()=>{f.db.exec('DELETE FROM safety_records');expect(safety.read().restricted).toBe(false);throw new Error('Odysseus rolls back');})()).toThrow('Odysseus rolls back'); + expect(safety.read().restricted,'ROLLED_BACK_INPUT_NEVER_REUSES_PROVISIONAL_SAFETY').toBe(true); + }finally{await f.close();} +}); + + +test('review8: unmatched input after removal records the current policy hash and revision',async()=>{ + const f=await fixture();try{f.t.remove();expect(await get(f.proxy.socketPath,f.origin.url.href)).toBe(200);await f.proxy.settled();const events=queryGovernanceEvents(f.db,{kinds:['taint'],limit:10});expect(events[0]?.payload,'UNMATCHED_ADMISSION_USES_ONE_LIVE_POLICY_SNAPSHOT').toMatchObject({occurrence:{admission:{trusted:false,policyHash:'b'.repeat(64),trustRevision:'2'}}});}finally{await f.close();} +}); + + +for(const change of ['remove','replace','disable'] as const)test(`review11: an unrelated recipient edit keeps a real trusted source stream until ${change}`,async()=>{ + let stream!:ReadableStreamDefaultController;const f=await fixture(false,{schema_version:1},()=>new Response(new ReadableStream({start(c){stream=c;c.enqueue(new TextEncoder().encode('first'));}})));let first!:()=>void,second!:()=>void;const received=new Promise(r=>{first=r;}),later=new Promise(r=>{second=r;});let text=''; + const closed=new Promise((resolve,reject)=>{const r=request({socketPath:f.proxy.socketPath,path:f.origin.url.href},response=>{response.on('data',b=>{text+=b;first();if(text.includes('second'))second();});response.on('close',resolve);response.on('error',()=>resolve());});r.on('error',reject);r.end();}); + try{await received;const source=f.t.live.read().rules[0]!;f.t.publish([source,{...source,id:'troy-recipient',incomingContent:false,recipientWhileRestricted:true,selector:{kind:'web_origin',scheme:'https',host:'troy.example.org',port:443}}]);try{stream.enqueue(new TextEncoder().encode('second'));}catch{} + expect(await Promise.race([later.then(()=>true),closed.then(()=>false)]),'UNRELATED_RECIPIENT_EDIT_NEVER_REVOKES_SOURCE_INPUT').toBe(true);if(change==='remove')f.t.remove();else f.t.publish([{...source,...(change==='replace'?{id:'replacement-source'}:{incomingContent:false,recipientWhileRestricted:true})}]);await f.proxy.settled();expect(queryGovernanceEvents(f.db,{kinds:['egress_connection'],limit:10})[0]?.payload,'SOURCE_RULE_REPLACEMENT_NEVER_BORROWS_TRUST').toMatchObject({reason:'source_trust_changed'});await closed;expect(text).toBe('firstsecond');expect(f.controller.signal.aborted).toBe(false);expect(queryGovernanceEvents(f.db,{kinds:['taint'],limit:10})[0]?.payload).toMatchObject({occurrence:{admission:{trusted:true,ruleId:'ithaca',trustRevision:'1',policyHash:'a'.repeat(64)}}}); + }finally{await f.close();} +}); + + +test('review11: unrelated trust publication during occurrence COMMIT keeps the same source admission',async()=>{ + const f=await fixture(false,{schema_version:1},undefined,true);const original=f.writes.firstTaint;let entered!:()=>void,release!:()=>void;const reached=new Promise(r=>{entered=r;}),held=new Promise(r=>{release=r;});f.writes.firstTaint=async(...args)=>{entered();await held;return original(...args);}; + try{const pending=get(f.proxy.socketPath,f.origin.url.href);await reached;const source=f.t.live.read().rules[0]!;f.t.publish([source,{...source,id:'troy-recipient',incomingContent:false,recipientWhileRestricted:true,selector:{kind:'web_origin',scheme:'https',host:'troy.example.org',port:443}}]);release();expect(await pending,'UNRELATED_REVISION_DURING_COMMIT_KEEPS_SOURCE').toBe(200);expect(f.hits()).toBe(1);expect(f.proxy.recordingFailure()).toBeUndefined();}finally{release();await f.close();} +}); + + +for(const order of ['notification','chunk','post-write'] as const)test(`review12: source removal audit is identical when first detected by ${order}`,async()=>{ + let stream:ReadableStreamDefaultController|undefined,first!:()=>void,release!:()=>void;const received=new Promise(r=>{first=r;});const f=await fixture(false,{schema_version:1},order==='post-write'?undefined:()=>new Response(new ReadableStream({start(c){stream=c;c.enqueue(new TextEncoder().encode('first'));}})),order==='post-write'); + let pending:Promise|undefined; + try{if(order==='post-write'){const original=f.writes.firstTaint,held=new Promise(r=>{release=r;});f.writes.firstTaint=async(...args)=>{first();await held;return original(...args);};pending=get(f.proxy.socketPath,f.origin.url.href).catch(()=>0);await received;f.t.remove(false);release();await pending;}else{pending=new Promise((resolve,reject)=>{const r=request({socketPath:f.proxy.socketPath,path:f.origin.url.href},response=>{response.on('data',()=>first());response.on('close',resolve);response.on('error',()=>resolve());});r.on('error',reject);r.end();});await received;f.t.remove(order==='notification');if(order==='chunk')try{stream!.enqueue(new TextEncoder().encode('second'));}catch{}await pending;} + await f.proxy.settled();expect(queryGovernanceEvents(f.db,{kinds:['egress_connection'],limit:10})[0]?.payload,'EVERY_SOURCE_REMOVAL_ORDER_HAS_ONE_AUDIT_CLASS').toMatchObject({outcome:'cancelled',reason:'source_trust_changed',trustedSource:true,method:'GET'});expect(f.controller.signal.aborted).toBe(false); + }finally{release?.();f.proxy.stop();await pending;await f.close();} +}); + +for(const change of ['end','opaque'] as const)test(`review15: outward covering-call ${change} during occurrence write fences dispatch`,async()=>{ + const f=await fixture(false,{schema_version:1,outward:{hosts:['127.0.0.1']}},undefined,true);let entered!:()=>void,release!:()=>void;const reached=new Promise(r=>{entered=r;}),held=new Promise(r=>{release=r;});const original=f.writes.firstTaint; + try{f.proxy.bridge.activity?.({kind:'outward_classification',toolUseId:'voyage',classification:{kind:'read',actions:[]},decision:'allow'});f.writes.firstTaint=async(...args)=>{entered();await held;return original(...args);};const pending=get(f.proxy.socketPath,f.origin.url.href);await reached;if(change==='end')f.proxy.bridge.emit({type:'tool_result',toolUseId:'voyage',output:'Ithaca',isError:false});else f.proxy.bridge.activity?.({kind:'outward_classification',toolUseId:'opaque',classification:{kind:'unknown',actions:[],opaque:true},decision:'allow'});release();expect(await pending,'EXPIRED_OUTWARD_COVERAGE_NEVER_DISPATCHES').toBe(403);expect(f.hits()).toBe(0);}finally{release();await f.close();} +}); + +test('review15: unrelated call changes do not withdraw an explicit Network card',async()=>{ + const f=await fixture(false,{schema_version:1},undefined,true);let entered!:()=>void,release!:()=>void;const reached=new Promise(r=>{entered=r;}),held=new Promise(r=>{release=r;});const original=f.writes.firstTaint; + try{await f.taint();f.decide(async()=>({behavior:'allow'}));f.proxy.bridge.activity?.({kind:'outward_classification',toolUseId:'voyage',classification:{kind:'read',actions:[]},decision:'allow'});f.writes.firstTaint=async(...args)=>{entered();await held;return original(...args);};const pending=get(f.proxy.socketPath,f.origin.url.href);await reached;f.proxy.bridge.emit({type:'tool_result',toolUseId:'voyage',output:'Ithaca',isError:false});release();expect(await pending,'NETWORK_APPROVAL_IS_INDEPENDENT_OF_OUTWARD_CALL_LIFETIME').toBe(200);expect(f.hits()).toBe(1);}finally{release();await f.close();} +}); + +test('review16: terminal cleanup releases both suffixed per-connection approval keys',async()=>{ + const seen:Array<{map:Map;key:string}>=[];const original=Map.prototype.set;const spy=spyOn(Map.prototype,'set').mockImplementation(function(this:Map,key:unknown,value:unknown){if(typeof key==='string'&&/^[a-f0-9-]+:(network|outward)$/.test(key)&&typeof value==='object'&&value!==null&&'marker' in value)seen.push({map:this,key});return original.call(this,key,value);});const f=await fixture(false,{schema_version:1,outward:{hosts:['127.0.0.1']}}); + try{await f.taint();f.decide(async()=>({behavior:'allow'}));for(let i=0;i<8;i++){expect(await get(f.proxy.socketPath,f.origin.url.href)).toBe(200);await f.proxy.settled();}for(const kind of ['network','outward']){const keys=seen.filter(({key})=>key.endsWith(':'+kind));expect(keys.length,'APPROVAL_KEY_EXERCISED_'+kind).toBeGreaterThan(0);for(const {map,key} of keys)expect(map.has(key),'TERMINAL_OWNER_RELEASES_'+kind+'_APPROVAL_KEY').toBe(false);}}finally{spy.mockRestore();await f.close();} +}); + +test('review16: terminal owner joins the real occurrence write before cleanup',async()=>{ + const f=await fixture(false,{schema_version:1},undefined,true);let entered!:()=>void,release!:()=>void;const reached=new Promise(r=>{entered=r;}),held=new Promise(r=>{release=r;});const original=f.writes.firstTaint; + try{f.t.remove();f.writes.firstTaint=async(...args)=>{entered();await held;return original(...args);};const pending=get(f.proxy.socketPath,f.origin.url.href).catch(()=>0);await reached;f.proxy.stop();release();await pending;await f.proxy.settled();const rows=f.db.query("SELECT state FROM safety_records WHERE kind='exposure'").all() as {state:string}[];expect(rows,'CANCELLED_OCCURRENCE_HAS_DURABLE_TERMINAL_EVIDENCE').toEqual([{state:'interrupted_unknown'}]);expect(queryGovernanceEvents(f.db,{kinds:['egress_connection'],limit:10})).toHaveLength(1);}finally{release();await f.close();} +}); + +for(const invalid of ['zero port','long host'] as const)test(`review17: ${invalid} cannot poison durable safety history`,async()=>{ + const f=await fixture();const {SafetyHistory}=await import('../src/governance/safety-history');const {safetyPageSchema}=await import('@schlessera/brain-ui-sdk/schemas');const history=new SafetyHistory(f.db,()=>true,()=>f.proxy.settled()); + try{const target=invalid==='zero port'?'http://127.0.0.1:0/':`http://${'ithaca.'.repeat(37)}example.org/`;expect(await get(f.proxy.socketPath,target).catch(()=>0),'INVALID_DESTINATION_IS_REFUSED_LOCALLY').toBe(400);await f.proxy.settled();expect(f.db.query("SELECT count(*) AS n FROM safety_records WHERE kind='occurrence'").get(),'INVALID_DESTINATION_NEVER_ENTERS_DURABLE_HISTORY').toEqual({n:0});expect(await get(f.proxy.socketPath,f.origin.url.href)).toBe(200);await f.proxy.settled();const page=await history.read({id:'odysseus'} as import('../src/db/principals').Principal,{sessionId:'voyage'},null,50,false,true);expect(safetyPageSchema.safeParse(page).success,'STRICT_HISTORY_REMAINS_READABLE_AFTER_BAD_DESTINATION').toBe(true);}finally{history.close();await f.close();} +}); + +for(const second of [false,true])test(`review17: inference binding loss on ${second?'second':'first'} admission stays unavailable`,async()=>{ + const f=await fixture();const {retainTurnSessionBinding}=await import('../src/ws/bridge-session-binding');const {startInferenceRelay}=await import('../../ui-sdk/src/server/inference-relay');let entered!:()=>void,release!:()=>void;const reached=new Promise(r=>{entered=r;}),held=new Promise(r=>{release=r;});const binding:{pending?:Promise;failed:boolean}={failed:!second};retainTurnSessionBinding(f.bridge,{sessionBinding:binding,current:()=>{if(binding.pending)entered();return true;},host:{},turn:{sessionId:'voyage'},turnId:'turn-voyage'} as unknown as Parameters[1]);const relay=startInferenceRelay({upstream:f.origin.url.origin,routes:['/v1/messages'],egress:f.proxy,credentials:async()=>{binding.pending=held;return {'x-api-key':'odysseus-key'};}}); + try{const response=new Promise<{status:number;body:string}>((resolve,reject)=>{const r=request({socketPath:relay.socketPath,path:'/v1/messages',method:'POST',headers:{'content-type':'application/json'}},res=>{let body='';res.on('data',b=>{body+=b;});res.on('end',()=>resolve({status:res.statusCode!,body}));});r.on('error',reject);r.end(JSON.stringify({model:'odysseus-model',messages:[]}));});if(second){await reached;binding.failed=true;binding.pending=undefined;release();}const got=await response;expect(got.status,'EVERY_BINDING_ADMISSION_USES_THE_STORED_UNAVAILABLE_REASON').toBe(503);expect(JSON.parse(got.body).error.message,'BINDING_FAILURE_KEEPS_COMPATIBLE_HOST_REFUSAL_TEXT').toBe('Inference network admission refused');expect(f.hits()).toBe(0);}finally{release();await relay.stop();await f.close();} +}); + +for(const tunnel of [false,true])for(const valid of [false,true])test(`review17: server ${tunnel?'tunnel':'origin'} provenance uses UTF-8 bounds (valid ${valid})`,async()=>{ + const {OccurrenceSchema}=await import('../src/governance/occurrence');const input=occurrence('voyage','proxy_input','odysseus');const host='λ'.repeat(valid?126:127);input.provenance=tunnel?{kind:'tunnel_authority',authority:{host,port:443},verifiedBy:'host_proxy'}:{kind:'web_origin',origin:{scheme:'https',host,port:443},verifiedBy:'host_transport'};expect(OccurrenceSchema.safeParse(input).success,'SERVER_AND_WIRE_PROVENANCE_USE_IDENTICAL_BYTE_LIMITS').toBe(valid); +}); + +test('review28: recipient receipt uses final dispatch authority after preparation',async()=>{ + const f=await fixture(true,{schema_version:1,taint:{egress:{allow:['github.com']}}});try{ + f.t.publish([{id:'ithaca',label:'Ithaca',incomingContent:false,recipientWhileRestricted:true,selector:{kind:'web_origin',scheme:'https',host:'github.com',port:443}}]);await f.taint(); + const op=f.proxy.managedReference(new URL('https://github.com/'),new AbortController().signal);expect(await op.admit()).toBe(true);expect(op.prepare()).toEqual({ok:true});f.t.remove();expect(op.dispatch(()=>{})).toEqual({ok:true});op.finish('completed');await f.proxy.settled();const payload=queryGovernanceEvents(f.db,{kinds:['egress_connection'],limit:10})[0]?.payload;expect(payload,'REMOVED_RECIPIENT_RULE_NEVER_APPEARS_IN_DISPATCH_RECEIPT').not.toHaveProperty('standingRecipient');expect(payload).not.toHaveProperty('recipientAdmission'); + }finally{await f.close();} +}); + +test('review31: a permanent gap never substitutes for a durable trusted occurrence',async()=>{ + const f=await fixture(true,{schema_version:1},undefined,true);const outcomes:boolean[]=[];const original=f.writes.firstTaint; + try{f.db.query("UPDATE safety_collections SET restricted_begin=1,gap='uninstrumented_backend_input' WHERE turn_id='turn-voyage'").run();f.db.exec("CREATE TRIGGER ithaca_missing_source BEFORE INSERT ON governance_events WHEN NEW.kind='taint' AND json_extract(NEW.payload,'$.source')='egress_connection' BEGIN SELECT RAISE(FAIL,'Odysseus source write unavailable'); END");f.writes.firstTaint=async(...args)=>{const result=await original(...args);outcomes.push(result);return result;};expect(f.writes.recordingAvailable('turn-voyage','voyage')).toBe(true); + expect(await get(f.proxy.socketPath,f.origin.url.href).catch(()=>0),'TRUST_REQUIRES_CONFIRMED_DURABLE_OCCURRENCE').toBe(503);expect(outcomes).toEqual([false]);expect(f.hits()).toBe(0);await f.proxy.settled();const denied=queryGovernanceEvents(f.db,{kinds:['egress_connection'],limit:10})[0]?.payload;expect(denied).toMatchObject({reason:'egress_unavailable',failureReason:'unavailable',dispatched:false});expect(denied).not.toHaveProperty('trustedSource');expect(queryGovernanceEvents(f.db,{kinds:['taint_exposure'],limit:10})).toHaveLength(0);expect(f.controller.signal.aborted).toBe(false);expect(f.writes.recordingAvailable('turn-voyage','voyage')).toBe(true); + f.db.exec('DROP TRIGGER ithaca_missing_source'); + }finally{await f.close();} +}); +for(const result of ['false','reject'] as const)test(`review31: ${result} occurrence write refuses only its operation as unavailable`,async()=>{ + const f=await fixture(true);const original=f.writes.firstTaint; + try{f.writes.firstTaint=async()=>{if(result==='reject')throw new Error('Odysseus write unavailable');return false;};expect(f.writes.recordingAvailable('turn-voyage','voyage')).toBe(true);expect(await get(f.proxy.socketPath,f.origin.url.href).catch(()=>0),'EVERY_FAILED_OCCURRENCE_WRITE_IS_503').toBe(503);expect(f.hits()).toBe(0);expect(f.controller.signal.aborted).toBe(false);f.writes.firstTaint=original;expect(await get(f.proxy.socketPath,f.origin.url.href)).toBe(200);}finally{await f.close();} +}); + + +test('review31: the legacy recorder adapter awaits and preserves a negative commit result',async()=>{ + const f=await fixture(true,{schema_version:1},undefined,false,'127.0.0.1',true);const original=f.writes.record;let entered!:()=>void,release!:()=>void;const reached=new Promise(r=>{entered=r;}),gate=new Promise(r=>{release=r;}); + try{f.writes.record=async(...args)=>{if(args[0].kind==='taint'){entered();await gate;return {id:0,recorded:false};}return original(...args);};const attempt=get(f.proxy.socketPath,f.origin.url.href).catch(()=>0);await reached;expect(f.hits(),'LEGACY_COMMIT_WAIT_PRECEDES_TRUSTED_DISPATCH').toBe(0);release();expect(await attempt,'LEGACY_NEGATIVE_COMMIT_IS_UNAVAILABLE').toBe(503);expect(f.hits()).toBe(0);f.writes.record=original;expect(await get(f.proxy.socketPath,f.origin.url.href)).toBe(200);}finally{release();await f.close();} +}); + +for(const outcome of ['missing','rejected','replay'] as const)test(`review31: egress audit commit ${outcome} preserves truthful recording health`,async()=>{ + const f=await fixture(true,{schema_version:1},undefined,false,'127.0.0.1',true);const original=f.writes.record; + try{f.writes.record=async(...args)=>{if(args[0].kind==='egress_connection'){if(outcome==='missing')return {id:0,recorded:false};if(outcome==='rejected')throw new Error('Odysseus audit unavailable');const result=await original(...args);return {...result,recorded:false};}return original(...args);};await get(f.proxy.socketPath,f.origin.url.href).catch(()=>0);await f.proxy.settled();expect(f.controller.signal.aborted,'AUDIT_NEGATIVE_RESULTS_ARE_NOT_SUCCESSFUL_COMMITS').toBe(outcome!=='replay');expect(Boolean(f.proxy.recordingFailure())).toBe(outcome!=='replay');}finally{await f.close();} +}); diff --git a/packages/ui-server/tests/policy-proposal.test.ts b/packages/ui-server/tests/policy-proposal.test.ts index 0b0726e5df..66669f0438 100644 --- a/packages/ui-server/tests/policy-proposal.test.ts +++ b/packages/ui-server/tests/policy-proposal.test.ts @@ -331,3 +331,11 @@ test("publication rechecks strict boundaries after schema validation (#3666)", a expect(result.state).toBe("invalid"); expect(result.message).toContain("standalone ---"); expect(readFileSync(f.path, "utf8")).toBe(original); expect(f.edits).toEqual([]); expect(f.events).toEqual([]); }); + +test("review: another policy publisher joins the trust refresh before reporting updated",async()=>{ + let entered!:()=>void,release!:()=>void,refreshed=false;const reached=new Promise(r=>{entered=r;}),held=new Promise(r=>{release=r;}); + const f=fixture({afterPublication:async()=>{entered();await held;refreshed=true;}});const pending=f.service.propose(f.turn,"live-trust",input);await f.answer(true); + // A missing callback must fail the named assertion without waiting forever. + const state=await Promise.race([reached.then(()=>"refresh"),pending.then(()=>"returned")]); + try{expect(state,"POLICY_PUBLISHER_JOINS_TRUST_REFRESH").toBe("refresh");expect(refreshed).toBe(false);release();expect((await pending).state).toBe("updated");expect(refreshed).toBe(true);}finally{release();} +}); diff --git a/packages/ui-server/tests/reference-egress.test.ts b/packages/ui-server/tests/reference-egress.test.ts index c3a01f1914..b77febb556 100644 --- a/packages/ui-server/tests/reference-egress.test.ts +++ b/packages/ui-server/tests/reference-egress.test.ts @@ -19,7 +19,7 @@ test("managed reference audit never gives worker traffic a contacted-host grant const proxy = await prepareTurnEgress(input(db)); try { const acquisition = proxy.managedReference(repository, new AbortController().signal); - expect(await acquisition.admit()).toBe(true); expect(acquisition.charge(12)).toBe(true); acquisition.finish("completed"); await proxy.settled(); + expect(await acquisition.admit()).toBe(true); expect(acquisition.dispatch(()=>{})).toEqual({ok:true}); expect(acquisition.charge(12).ok).toBe(true); acquisition.finish("completed"); await proxy.settled(); expect(sessionTaint(db, "turn-ithaca", "ithaca"), "REFERENCE_ACQUISITION_IS_NOT_A_MODEL_READ").toBeNull(); expect(queryGovernanceEvents(db, { sessionId: "ithaca", kinds: ["egress_connection"], limit: 10 })[0]?.payload) .toMatchObject({ managedReference: true, bytes: 12, host: "github.com" }); @@ -42,10 +42,20 @@ test("managed reference uses the final recorder-health fence after its transport const acquisition = proxy.managedReference(repository, new AbortController().signal); expect(await acquisition.admit()).toBe(true); available = false; - expect(acquisition.commit(), "REFERENCE_FINAL_RECORDING_HEALTH_RECHECKED").toBe(false); - expect(acquisition.charge(1)).toBe(false); + expect(acquisition.dispatch(()=>{}), "REFERENCE_FINAL_RECORDING_HEALTH_RECHECKED").toEqual({ok:false,reason:"unavailable"}); + expect(acquisition.charge(1)).toEqual({ok:false,reason:"unavailable"}); await proxy.settled(); expect(queryGovernanceEvents(db, { sessionId: "ithaca", kinds: ["egress_connection"], limit: 10 })[0]?.payload) - .toMatchObject({ managedReference: true, bytes: 0, outcome: "denied", reason: "safety_changed" }); + .toMatchObject({ managedReference: true, bytes: 0, outcome: "denied", reason: "egress_unavailable" }); } finally { proxy.stop(); db.close(); } }); + +test('review14: pre-upgrade IPv6 session grants use the canonical lookup host',()=>{ + const db=createUiDb(':memory:');connectedSafetySession(db,'ithaca','turn-ithaca'); + try{recordGovernanceEvent(db,{kind:'egress_connection',turnId:'turn-ithaca',sessionId:'ithaca',actor:'interactive',profile:'governed',model:null,payload:{method:'CONNECT',host:'[0:0:0:0:0:0:0:1]',port:443,bytes:8,accounting:'opaque_bytes',outcome:'completed',durationMs:1}});expect(contactedHosts(db,'ithaca'),'PRE_UPGRADE_IPV6_GRANT_STILL_MATCHES').toEqual(['::1']);}finally{db.close();} +}); + +test('review14: charged preparation never becomes a durable session grant',()=>{ + const db=createUiDb(':memory:');connectedSafetySession(db,'ithaca','turn-ithaca'); + try{recordGovernanceEvent(db,{kind:'egress_connection',turnId:'turn-ithaca',sessionId:'ithaca',actor:'interactive',profile:'governed',model:null,payload:{method:'POST',host:'ithaca.example.org',port:80,bytes:8,accounting:'http_wire_bound',outcome:'denied',reason:'invalid_request',durationMs:1,dispatched:false}});expect(contactedHosts(db,'ithaca'),'UNDISPATCHED_PREPARATION_NEVER_GRANTS_LATER_TURNS').toEqual([]);}finally{db.close();} +}); diff --git a/packages/ui-server/tests/reference-owner-lifecycle.test.ts b/packages/ui-server/tests/reference-owner-lifecycle.test.ts new file mode 100644 index 0000000000..75b50cb82f --- /dev/null +++ b/packages/ui-server/tests/reference-owner-lifecycle.test.ts @@ -0,0 +1,22 @@ +import * as rootKernel from "../src/brain/reference-owner-root-kernel"; +import { expect, test, spyOn } from "bun:test"; +import { readdirSync, readlinkSync } from "node:fs"; +import { httpContractApp } from "./helpers/http-contract-app"; + +function rootDescriptors(root: string): string[] { + return readdirSync("/proc/self/fd").filter(fd => { + try { return readlinkSync(`/proc/self/fd/${fd}`) === root; } catch { return false; } + }); +} + +test("normal app shutdown releases the policy-root continuity descriptor on every create/close cycle", async () => { + const native = spyOn(rootKernel, "inspectPinnedReferenceRoot").mockImplementation(async () => ({ fsid: "11111111-1111-4111-8111-111111111790", uuid: "11".repeat(16), receivedUuid: "0".repeat(32), readOnly: false, devices: 1 })); + try { for (let cycle = 0; cycle < 2; cycle++) { + const t = await httpContractApp(); + try { + expect(rootDescriptors(t.brainPath).length, "RUNNING_APP_HOLDS_POLICY_ROOT_CONTINUITY").toBeGreaterThan(0); + await t.app.close(); + expect(rootDescriptors(t.brainPath), "NORMAL_APP_CLOSE_RELEASES_POLICY_ROOT_CONTINUITY").toEqual([]); + } finally { await t.close(); } + } } finally { native.mockRestore(); } +}); diff --git a/packages/ui-server/tests/reference-owner-native-root.test.ts b/packages/ui-server/tests/reference-owner-native-root.test.ts new file mode 100644 index 0000000000..8a08f73104 --- /dev/null +++ b/packages/ui-server/tests/reference-owner-native-root.test.ts @@ -0,0 +1,40 @@ +import { afterEach, expect, spyOn, test } from "bun:test"; +import { fstatSync, mkdirSync, mkdtempSync, readlinkSync, renameSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import * as kernel from "../src/brain/reference-owner-root-kernel"; +import { createReferenceOwnerContinuity } from "../src/brain/reference-owner-native-root"; +const expected = { fsid: "11111111-1111-4111-8111-111111111790", brainUuid: "11".repeat(16) }; +const identity = { fsid: expected.fsid, uuid: expected.brainUuid, readOnly: false, receivedUuid: "0".repeat(32), devices: 1 }; +const cleanup: (() => void)[] = []; +afterEach(() => { for (const close of cleanup.splice(0).reverse()) close(); }); +function root() { const path = mkdtempSync(join(tmpdir(), "odysseus-owner-native-")); cleanup.push(() => rmSync(path, { recursive: true, force: true })); return path; } + +for (const field of ["fsid", "uuid", "readOnly", "receivedUuid", "devices"] as const) test(`actual pinned-root identity refuses mismatched ${field}`, async () => { + const path = root(); let fd = -1; + const wrong = { ...identity, [field]: field === "readOnly" ? true : field === "devices" ? 2 : "22".repeat(16) }; + const spy = spyOn(kernel, "inspectPinnedReferenceRoot").mockImplementation(async value => { fd = value; return wrong; }); cleanup.push(() => spy.mockRestore()); + const context = await createReferenceOwnerContinuity(path, expected); cleanup.push(() => context.close()); + expect(context.root, "ONLY_QUALIFIED_NATIVE_ROOT_CAN_BIND_APPROVAL").toBeUndefined(); + expect(() => fstatSync(fd), "REFUSED_NATIVE_ROOT_DESCRIPTOR_IS_CLOSED").toThrow(); +}); + +test("startup attests the already held descriptor and refuses replacement during the inspection wait", async () => { + const path = root(), previous = path + "-previous"; cleanup.push(() => rmSync(previous, { recursive: true, force: true })); + let fd = -1; + const spy = spyOn(kernel, "inspectPinnedReferenceRoot").mockImplementation(async value => { + fd = value; const held = fstatSync(value); renameSync(path, previous); mkdirSync(path); + expect(readlinkSync(`/proc/self/fd/${value}`), "NATIVE_ATTESTATION_INSPECTS_ORIGINAL_PINNED_ROOT").toBe(previous); + expect(fstatSync(value).ino).toBe(held.ino); + return identity; + }); cleanup.push(() => spy.mockRestore()); + const context = await createReferenceOwnerContinuity(path, expected); cleanup.push(() => context.close()); + expect(context.root, "STARTUP_REPLACEMENT_NEVER_ADOPTS_QUALIFIED_ROOT").toBeUndefined(); + expect(() => fstatSync(fd)).toThrow(); +}); + +test("unsupported real filesystem withholds qualification without a native stand-in", async () => { + // This fixture is an ordinary temporary directory, never a Btrfs subvolume. + const context = await createReferenceOwnerContinuity(root(), expected); cleanup.push(() => context.close()); + expect(context.root, "ORDINARY_DIRECTORY_IS_NOT_NATIVE_QUALIFICATION").toBeUndefined(); +}); diff --git a/packages/ui-server/tests/reference-owner-resolution.test.ts b/packages/ui-server/tests/reference-owner-resolution.test.ts new file mode 100644 index 0000000000..56b1d70e88 --- /dev/null +++ b/packages/ui-server/tests/reference-owner-resolution.test.ts @@ -0,0 +1,364 @@ +import * as rootKernel from "../src/brain/reference-owner-root-kernel"; +import { afterEach, expect, test, spyOn } from "bun:test"; +import { createHash } from "node:crypto"; +import { mkdtempSync, mkdirSync, readFileSync, rmSync, writeFileSync, renameSync } from "node:fs"; +import { connect } from "node:net"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { createKeyedLock } from "@schlessera/brain-ui-sdk/server"; +import { startEgressProxy } from "@schlessera/brain-ui-sdk/internal"; +import type { TrustRule } from "@schlessera/brain-common/internal/governance-policy"; +import { createUiDb } from "../src/db/client"; +import { createReferenceGrant, revokeReferenceGrant } from "../src/db/reference-grants"; +import { createPrincipal } from "../src/db/principals"; +import { openSqliteWriter } from "../src/db/write-worker"; +import { createGitHubReferenceAccess } from "../src/brain/github-reference-access"; +import { createTrustGitHubIdentity } from "../src/brain/trust-github-identity"; +import { createTrustSettings } from "../src/brain/trust-settings"; +import { createReferenceSources } from "../src/brain/reference-source"; +import { createReferenceReads } from "../src/brain/reference-read"; +import { registerReferenceWrites } from "../src/brain/reference-writes"; +import { createReferenceOwnerContinuity, resolveReferenceOwners, type ReferenceOwnerResolution } from "../src/brain/reference-owner-resolution"; +import type { ReferenceIdentityObservation } from "../src/brain/reference-acquisition"; +import { heldWriter } from "./helpers/held-writer"; +import type { ReferenceTransport } from "../src/brain/reference-transport"; +import { referencePoolDouble } from "./helpers/reference-pool-double"; +import { fixtureTls } from "./fixtures/fixture-tls"; + +const cleanup: (() => void | Promise)[] = []; +afterEach(async () => { for (const close of cleanup.splice(0).reverse()) await close(); }); +const nativeExpected = { fsid: "11111111-1111-4111-8111-111111111790", brainUuid: "11".repeat(16) }; +const captureReferenceOwnerRoot = async (path: string, expected = nativeExpected) => { const c = await createReferenceOwnerContinuity(path, expected); cleanup.push(() => c.close()); return c.root; }; +const brain = "ithaca-brain", commit = "a".repeat(40), tree = "b".repeat(40); +const repositoryRule: TrustRule = { id: "ithaca", label: "Ithaca", incomingContent: true, recipientWhileRestricted: false, + selector: { kind: "github_repository", host: "github.com", owner: "odysseus", repository: "ithaca", repositoryId: "101" } }; +const ownerRule: TrustRule = { ...repositoryRule, id: "odysseus", selector: { kind: "github_owner", host: "github.com", owner: "odysseus", ownerId: "201" } }; + +async function fixture(worker = false) { + const root = mkdtempSync(join(tmpdir(), "odysseus-owner-resolution-")); cleanup.push(() => rmSync(root, { recursive: true, force: true })); + const nativeState = { uuid: nativeExpected.brainUuid }; + const nativeSpy = spyOn(rootKernel, "inspectPinnedReferenceRoot").mockImplementation(async () => ({ fsid: nativeExpected.fsid, uuid: nativeState.uuid, readOnly: false, receivedUuid: "0".repeat(32), devices: 1 })); + cleanup.push(() => nativeSpy.mockRestore()); + const continuity = await createReferenceOwnerContinuity(root, nativeExpected); cleanup.push(() => continuity.close()); + const policyPath = join(root, "context/policies/governance.md"); mkdirSync(join(root, "context/policies"), { recursive: true }); + writeFileSync(policyPath, "---\nschema_version: 1\n---\nThe voyage policy.\n"); + const db = createUiDb(join(root, "ui.db")), writer = worker ? openSqliteWriter(db) : undefined; + if (writer) registerReferenceWrites(db, writer); + cleanup.push(async () => { await writer?.close(); db.close(); }); + const owner = createPrincipal(db, { authMethod: "password", label: "Penelope", ttlSeconds: 3600 }); + const other = createPrincipal(db, { authMethod: "password", label: "Telemachus", ttlSeconds: 3600 }); + const state = { owner: "odysseus", repository: "ithaca", ownerId: "201", repositoryId: "101", status: 200, private: false, + afterBlob: async () => {}, current: true }; + const tls = fixtureTls(join(root, "tls"), ["api.github.com"]); + const requests: string[] = []; + const server = Bun.serve({ hostname: "127.0.0.1", port: 0, tls: { cert: tls.cert, key: tls.key }, fetch(request) { + const path = new URL(request.url).pathname; requests.push(path); + if (state.status !== 200) return new Response(null, { status: state.status }); + if (path.startsWith("/users/")) return Response.json({ id: state.ownerId, login: state.owner, type: "User", + url: `https://api.github.com/users/${state.owner}`, html_url: `https://github.com/${state.owner}` }); + if (state.private && request.headers.get("authorization") !== "Bearer odysseus-fixture-token") return new Response(null, { status: 404 }); + return Response.json({ id: state.repositoryId, owner: { id: state.ownerId, login: state.owner }, name: state.repository, + full_name: `${state.owner}/${state.repository}`, clone_url: `https://github.com/${state.owner}/${state.repository}.git`, + url: `https://api.github.com/repos/${state.owner}/${state.repository}`, private: state.private }); + } }); cleanup.push(() => server.stop(true)); + const bytes = Buffer.from("Odysseus charts Ithaca on 2026-07-12.\n"); + const transport: ReferenceTransport = { + async resolve() { return { ok: true, commit, ref: "refs/heads/main" }; }, + async fetch(input) { writeFileSync(join(input.root, "README.md"), bytes); writeFileSync(join(input.root, ".reference-commit"), commit); return { commit }; }, + async checkout() {}, async tree() { return tree; }, + async readBlob(input) { const range = bytes.subarray(input.offset, input.offset + input.maximum); await state.afterBlob(); + return { bytes: range, blob: "c".repeat(40), mode: "100644", tree, offset: input.offset, length: range.length, + totalBytes: bytes.length, digest: createHash("sha256").update(range).digest("hex") }; }, + }; + const access = createGitHubReferenceAccess({ db, brain, credentials: { GITHUB_TOKEN: "odysseus-fixture-token" }, transport, + wireTransport: { ca: readFileSync(tls.ca, "utf8"), lookup: async () => [{ address: "93.184.216.34", family: 4 }], + connect: (() => connect({ host: "127.0.0.1", port: server.port! })) as typeof connect } }); + const settingsOptions = { root, ownerRoot: continuity.root, db, writer, lock: createKeyedLock(), github: createTrustGitHubIdentity({ root, access }), + authority: (id: string) => id === owner.id ? "owner-epoch" : null, observe: async (_id: string, publish: () => void | Promise) => { await publish(); } }; + const settings = createTrustSettings(settingsOptions); + const change = async (change: unknown) => { + const p = await settings.list(owner.id); + return settings.prepare(owner.id, { version: 1, expectedTrustRevision: p.revision, expectedPolicyHash: p.policyHash, change }); + }; + const save = (draft: Awaited>) => settings.commit(owner.id, { version: 1, requestId: draft.receipt.requestId, + reviewId: draft.review.reviewId, reviewedBytesHash: draft.review.reviewedBytesHash }); + const approve = async (rule = repositoryRule) => { + const result = await save(await change({ action: "create", rule })); expect(result.receipt.publication).toBe("proved"); return result; + }; + const pool = referencePoolDouble(join(root, "pool")), sources = createReferenceSources({ db, brain, pool, transport, github: access, credentials: { GITHUB_TOKEN: "odysseus-fixture-token" } }); + cleanup.push(() => sources.close()); + const egress = await startEgressProxy({ mode: "record", allow: [], deny: [], outwardHosts: [], maxBytes: 16 * 1048576, observe() {} }); cleanup.push(() => egress.stop()); + const reads = createReferenceReads({ db, brain, ownerRoot: continuity.root, ownerPolicy: () => settings.ownerPolicy(), pool, sources, transport }); + let call = 0; + const read = async (principalId = other.id) => { + const toolCallId = `read-${++call}`; + const result = await reads.read({ principalId, turnId: "reading-turn", toolCallId, + request: { repository: `https://github.com/${state.owner}/${state.repository}.git`, revision: "main", path: "README.md", offset: 9, maximum: 13 }, + acquisition: { turnId: "reading-turn", egress, current: () => state.current } }); + const row = db.query("SELECT evidence,acquisition FROM reference_reads WHERE tool_call_id=?").get(toolCallId) as { evidence: string; acquisition: string }; + return { result, row, evidence: JSON.parse(row.evidence) as { trusted: false; ownerResolution: ReferenceOwnerResolution; identityObservation: ReferenceIdentityObservation } }; + }; + return { root, nativeState, ownerRoot: continuity.root, continuity, db, writer, owner, other, state, settings, settingsOptions, change, save, approve, read, reads, requests, policyPath, sources }; +} + +for (const worker of [false, true]) test(`protected publication binds an actual fresh managed read; writer=${worker}`, async () => { + const f = await fixture(worker); await f.approve(); + const r = await f.read(); + expect(r.evidence.ownerResolution, "READ_BINDS_PUBLISHED_APPROVED_OWNER").toMatchObject({ version: 1, state: "available", + operationId: r.evidence.identityObservation.operationId, bindings: [{ ruleId: "ithaca", selector: repositoryRule.selector, + approvedOwnerId: "201", sameOwnerRenameRevalidated: false }] }); + expect(r.evidence.ownerResolution.bindings[0]!.publicationProofHash).toMatch(/^[a-f0-9]{64}$/); + expect(r.evidence.trusted).toBe(false); + expect(JSON.stringify(r.result)).not.toContain("ownerResolution"); +}); + +for (const scenario of ["rename", "transfer", "name-reuse", "namespace-reuse"]) test(`fresh metadata handles ${scenario} under the approved owner`, async () => { + const f = await fixture(); await f.approve(); const original = await f.read(); + if (scenario === "rename") f.state.repository = "nostos"; + if (scenario === "transfer") { f.state.owner = "circe"; f.state.ownerId = "202"; } + if (scenario === "name-reuse") f.state.repositoryId = "102"; + if (scenario === "namespace-reuse") f.state.ownerId = "202"; + const r = await f.read(); + expect(r.evidence.ownerResolution.state, "APPROVED_OWNER_FENCES_TRANSFER_AND_REUSE").toBe(scenario === "rename" ? "available" : "unavailable"); + expect(r.evidence.ownerResolution.bindings).toHaveLength(scenario === "rename" ? 1 : 0); + if (scenario === "rename") expect(r.evidence.ownerResolution.bindings[0]!.sameOwnerRenameRevalidated).toBe(true); + expect(JSON.parse(original.row.evidence).ownerResolution.bindings[0].selector).toEqual(repositoryRule.selector); +}); + +test("owner approval includes future repositories only in the same current namespace and stable owner", async () => { + const f = await fixture(); await f.approve(ownerRule); + f.state.repository = "fleet"; f.state.repositoryId = "103"; + expect((await f.read()).evidence.ownerResolution.bindings[0]!.ruleId).toBe("odysseus"); + f.state.ownerId = "202"; + expect((await f.read()).evidence.ownerResolution.bindings).toEqual([]); +}); + +test("equal bytes and prepared metadata cannot create approved-owner evidence", async () => { + const f = await fixture(), draft = await f.change({ action: "create", rule: repositoryRule }); + writeFileSync(f.policyPath, draft.review.proposed); await f.settings.snapshot(); + expect((await f.read()).evidence.ownerResolution.bindings, "PREPARED_IDENTITY_IS_NOT_OWNER_APPROVAL").toEqual([]); +}); + +for (const failure of ["missing", "malformed", "wrong-brain", "changed-identity", "future-revision", "legacy-root", "wrong-device", "wrong-inode"]) test(`a ${failure} publication proof stays unavailable`, async () => { + const f = await fixture(); await f.approve(); + const row = f.db.query("SELECT proof FROM trust_settings_github_boundaries").get() as { proof: string }; + const proof = JSON.parse(row.proof); + if (failure === "missing") f.db.exec("DELETE FROM trust_settings_github_boundaries"); + else { + if (failure === "legacy-root") delete proof.policyRoot; + if (failure === "wrong-device") proof.policyRoot.fsid = "22222222-2222-4222-8222-222222222222"; + if (failure === "wrong-inode") proof.policyRoot.uuid = "22".repeat(16); + if (failure === "wrong-brain") proof.brain = "a".repeat(64); + if (failure === "changed-identity") proof.githubIdentity.ownerId = "202"; + if (failure === "future-revision") { proof.expectedTrustRevision = "99"; proof.publishedTrustRevision = "100"; } + f.db.query("UPDATE trust_settings_github_boundaries SET proof=?").run(failure === "malformed" ? "{}" : JSON.stringify(proof)); + } + expect((await f.read()).evidence.ownerResolution.bindings, "UNPROVED_OWNER_BOUNDARY_NEVER_QUALIFIES").toEqual([]); +}); + +test("receipt pruning and a fresh settings reader preserve durable approval; removal affects only later reads", async () => { + const f = await fixture(true); await f.approve(); const earlier = await f.read(); + f.db.exec("DELETE FROM trust_settings_operations"); + const restarted = createTrustSettings(f.settingsOptions); await restarted.snapshot(); + expect((await f.read()).evidence.ownerResolution.bindings).toHaveLength(1); + await f.save(await f.change({ action: "remove", ruleId: "ithaca" })); + expect((await f.read()).evidence.ownerResolution.bindings).toEqual([]); + const historical = f.db.query("SELECT evidence FROM reference_reads WHERE tool_call_id='read-1'").get() as { evidence: string }; + expect(JSON.parse(historical.evidence).ownerResolution).toEqual(earlier.evidence.ownerResolution); +}); + +test("a policy removal while the blob reader waits cannot retain owner qualification", async () => { + const f = await fixture(true); await f.approve(); + f.state.afterBlob = async () => { await f.save(await f.change({ action: "remove", ruleId: "ithaca" })); }; + const r = await f.read(); + expect(r.result.ok).toBe(true); + expect(r.evidence.ownerResolution.bindings, "OWNER_RESOLUTION_RECHECKS_AFTER_READ_WAITS").toEqual([]); +}); + +test("failed fresh metadata withholds new reads rather than borrowing approved cached identity", async () => { + const f = await fixture(); await f.approve(); await f.read(); + f.state.status = 500; + await expect(f.read()).rejects.toBeInstanceOf(Error); + expect(f.db.query("SELECT count(*) n FROM reference_reads").get()).toEqual({ n: 1 }); +}); + + +test("independent owner and repository publications retain both bounded bindings after other policy edits", async () => { + const f = await fixture(); await f.approve(); const first = await f.read(); await f.approve(ownerRule); + const r = await f.read(); + expect(r.evidence.ownerResolution.bindings.map(b => b.ruleId).sort()).toEqual(["ithaca", "odysseus"]); + expect(r.evidence.ownerResolution.policyHash).not.toBe(first.evidence.ownerResolution.policyHash); + expect(r.evidence.ownerResolution.bindings.find(b => b.ruleId === "ithaca")!.publicationProofHash) + .toBe(first.evidence.ownerResolution.bindings[0]!.publicationProofHash); +}); + +for (const change of ["invalid", "symlink", "selector", "projection"]) test(`a ${change} policy boundary follows the Settings live interpretation`, async () => { + const f = await fixture(); await f.approve(); + const previous = readFileSync(f.policyPath, "utf8"); + if (change === "invalid") writeFileSync(f.policyPath, "---\nschema_version: 9000\n---\n"); + if (change === "selector") { writeFileSync(f.policyPath, previous.replace('"repositoryId":"101"', '"repositoryId":"102"')); await f.settings.snapshot(); } + if (change === "projection") f.db.query("UPDATE trust_settings_projection SET rules='[]'").run(); + if (change === "symlink") { + renameSync(f.policyPath, f.policyPath + ".saved"); + const { symlinkSync } = await import("node:fs"); symlinkSync(f.policyPath + ".saved", f.policyPath); + } + const resolution = (await f.read()).evidence.ownerResolution; + expect(resolution.state, "POLICY_BOUNDARY_USES_SETTINGS_LIVE_INTERPRETATION").toBe(change === "invalid" || change === "symlink" ? "available" : "unavailable"); + if (change === "invalid" || change === "symlink") expect(resolution.policyError).toBe("policy_unavailable"); +}); + +test("replacing the configured policy root cannot borrow the previous directory's approval", async () => { + const f = await fixture(); await f.approve(); const r = await f.read(), bound = f.ownerRoot; + expect(resolveReferenceOwners(f.db, bound, r.evidence.identityObservation, f.settings.ownerPolicy()).bindings, "LIVE_ORIGINAL_ROOT_HAS_APPROVED_BINDING").toHaveLength(1); + const policy = readFileSync(f.policyPath), backup = f.root + "-old"; + renameSync(f.root, backup); + try { + mkdirSync(join(f.root, "context/policies"), { recursive: true }); writeFileSync(f.policyPath, policy); + expect(resolveReferenceOwners(f.db, bound, r.evidence.identityObservation, f.settings.ownerPolicy()).bindings, "OWNER_APPROVAL_IS_BOUND_TO_HOST_BRAIN_ROOT").toEqual([]); + } finally { rmSync(f.root, { recursive: true, force: true }); renameSync(backup, f.root); } +}); + +test("a queued writer resolves current approval rather than a pre-wait snapshot", async () => { + const f = await fixture(true); await f.approve(); + const control = await heldWriter(f.writer!, join(f.root, "ui.db")); + let observed = false; + f.state.afterBlob = async () => { await control.hold(); observed = true; }; + const posted = control.posted("referenceReadPrepare"), pending = f.read(); + try { + await posted; expect(observed).toBe(true); + // Simulate the already committed projection/boundary side of a concurrent + // protected removal while this writer waits. The policy changes too. + const current = readFileSync(f.policyPath, "utf8"); + const removed = current.replace(/"trusted_sources":\s*\[[^\n]*\]/u, '"trusted_sources":[]'); + writeFileSync(f.policyPath, removed); + control.elsewhere(db => { db.exec("DELETE FROM trust_settings_github_boundaries"); }); + control.release(); + expect((await pending).evidence.ownerResolution.bindings, "OWNER_APPROVAL_RECHECKS_IN_ACQUIRED_WRITER").toEqual([]); + } finally { await control.close(); await pending.catch(() => {}); } +}); + + +test("a reviewed label edit retains approval and approval does not depend on a retained owner login", async () => { + const f = await fixture(); await f.approve(); + await f.save(await f.change({ action: "edit", rule: { ...repositoryRule, label: "The home harbor" } })); + f.db.query("DELETE FROM principals WHERE id=?").run(f.owner.id); + expect((await f.read()).evidence.ownerResolution.bindings).toHaveLength(1); +}); + +test("a reopened database reconstructs qualification from retained boundary evidence", async () => { + const f = await fixture(); await f.approve(); const observed = await f.read(); + f.db.exec("DELETE FROM trust_settings_operations"); + const reopened = createUiDb(join(f.root, "ui.db")); + try { + const resolved = resolveReferenceOwners(reopened, f.ownerRoot, observed.evidence.identityObservation, f.settings.ownerPolicy()); + expect(resolved, "OWNER_RESOLUTION_SURVIVES_DATABASE_REOPEN").toEqual(observed.evidence.ownerResolution); + const history = reopened.query("SELECT evidence FROM reference_reads").get() as { evidence: string }; + expect(JSON.parse(history.evidence).ownerResolution).toEqual(resolved); + } finally { reopened.close(); } +}); + + +test("approved ownership grants no private access and cannot outlive private-grant revocation", async () => { + const f = await fixture(true); await f.approve(); await f.read(); + f.state.private = true; + const denied = await f.read().then(() => null, error => error); + expect(denied, "OWNER_APPROVAL_NEVER_GRANTS_PRIVATE_CREDENTIAL_ACCESS").toBeInstanceOf(Error); + const grant = createReferenceGrant(f.db, { brain, principalId: f.other.id, createdBy: f.owner.id, + repositoryPrefix: "https://github.com/odysseus/ithaca", credential: "GITHUB_TOKEN", + metadataCredentialRecipient: "https://api.github.com", now: Date.now() }); + expect((await f.read()).evidence.ownerResolution.bindings).toHaveLength(1); + f.state.afterBlob = async () => { revokeReferenceGrant(f.db, { brain, principalId: f.other.id, id: grant.id, now: Date.now() }); }; + const revoked = await f.read().then(() => null, error => error); + expect(revoked, "OWNER_APPROVAL_CANNOT_OVERRIDE_LIVE_PRIVATE_REVOCATION").toBeInstanceOf(Error); + expect(f.db.query("SELECT count(*) n FROM reference_reads").get()).toEqual({ n: 2 }); +}); + +test("restart cannot apply retained approval to a replacement policy root with identical bytes", async () => { + const f = await fixture(); await f.approve(); const observed = await f.read(); + const policy = readFileSync(f.policyPath), backup = f.root + "-before-restart"; + renameSync(f.root, backup); + try { + mkdirSync(join(f.root, "context/policies"), { recursive: true }); writeFileSync(f.policyPath, policy); + // Retain the authoritative UI database, but construct both readers anew as + // startup does. Equal path/policy bytes must not resurrect old approval. + f.nativeState.uuid = "22".repeat(16); + const reopened = createUiDb(join(backup, "ui.db")); + try { + expect(resolveReferenceOwners(reopened, await captureReferenceOwnerRoot(f.root, { ...nativeExpected, brainUuid: "22".repeat(16) }), observed.evidence.identityObservation, f.settings.ownerPolicy()).bindings, + "RESTART_REJECTS_APPROVAL_FROM_REPLACED_PUBLISHED_ROOT").toEqual([]); + } finally { reopened.close(); } + } finally { rmSync(f.root, { recursive: true, force: true }); renameSync(backup, f.root); } +}); + +test("deleted root replacement cannot inherit approval even when the filesystem reuses its identity", async () => { + const f = await fixture(); await f.approve(); const observed = await f.read(), policy = readFileSync(f.policyPath); + const retained = mkdtempSync(join(tmpdir(), "odysseus-retained-owner-db-")); + try { + writeFileSync(join(retained, "ui.db"), f.db.serialize()); + writeFileSync(join(retained, "ui.db.journal.db"), f.db.serialize("journal")); + f.continuity.close(); // Simulate shutdown: no descriptor pins the deleted root. + rmSync(f.root, { recursive: true }); + mkdirSync(join(f.root, "context/policies"), { recursive: true }); writeFileSync(f.policyPath, policy); + const reopened = createUiDb(join(retained, "ui.db")); + try { + f.nativeState.uuid = "22".repeat(16); + const replacement = await captureReferenceOwnerRoot(f.root, { ...nativeExpected, brainUuid: f.nativeState.uuid }); + // The previous weak path/device/inode proof is gone. Native root identity + // remains different even when a Btrfs replacement reuses root inode 256. + expect(resolveReferenceOwners(reopened, replacement, observed.evidence.identityObservation, f.settings.ownerPolicy()).bindings, + "DELETED_ROOT_REUSE_REQUIRES_NEW_REVIEWED_APPROVAL").toEqual([]); + } finally { reopened.close(); } + } finally { rmSync(retained, { recursive: true, force: true }); } +}); + +test("ordinary host restart retains approval for the same qualified native brain", async () => { + const f = await fixture(); await f.approve(); const observed = await f.read(); + f.continuity.close(); + const next = await createReferenceOwnerContinuity(f.root, nativeExpected); + const restartedSettings = createTrustSettings({ ...f.settingsOptions, ownerRoot: next.root }); + try { + expect(resolveReferenceOwners(f.db, next.root, observed.evidence.identityObservation, restartedSettings.ownerPolicy()).bindings, + "ORDINARY_NATIVE_RESTART_PRESERVES_APPROVED_OWNER").toHaveLength(1); + } finally { next.close(); } +}); + +test("an unqualified host withholds retained owner approval", async () => { + const f = await fixture(); await f.approve(); const observed = await f.read(); + const next = await createReferenceOwnerContinuity(f.root); + try { expect(resolveReferenceOwners(f.db, next.root, observed.evidence.identityObservation, f.settings.ownerPolicy()).bindings, + "UNQUALIFIED_NATIVE_HOST_WITHHOLDS_OWNER_APPROVAL").toEqual([]); } finally { next.close(); } +}); + +test("owner qualification retains the Settings last-valid rules with an honest error and clears it on recovery", async () => { + const f = await fixture(); await f.approve(); const policy = readFileSync(f.policyPath); + writeFileSync(f.policyPath, "---\nschema_version: 9000\n---\n"); + const restricted = await f.read(); + expect(restricted.evidence.ownerResolution, "OWNER_QUALIFICATION_SHARES_LIVE_LAST_VALID_POLICY").toMatchObject({ state: "available", policyError: "policy_unavailable" }); + expect(restricted.evidence.trusted).toBe(false); + writeFileSync(f.policyPath, policy); + expect((await f.read()).evidence.ownerResolution).toMatchObject({ state: "available", policyError: null }); +}); + +test("an unrelated policy edit binds owner evidence to the live verified hash without a second projection cache", async () => { + const f = await fixture(); await f.approve(); const first = await f.read(); + writeFileSync(f.policyPath, readFileSync(f.policyPath, "utf8") + "\nThe fleet reviews the harbor.\n"); + const live = f.settings.live.read(), current = await f.read(); + expect(current.evidence.ownerResolution.policyHash, "OWNER_EVIDENCE_USES_VERIFIED_LIVE_POLICY_HASH").toBe(live.policyHash); + expect(current.evidence.ownerResolution.policyHash).not.toBe(first.evidence.ownerResolution.policyHash); + expect(current.evidence.ownerResolution.state).toBe("available"); +}); + +test("the queued owner writer fences a changed live generation even when projection and boundary remain unchanged", async () => { + const f = await fixture(true); await f.approve(); + const control = await heldWriter(f.writer!, join(f.root, "ui.db")); + f.state.afterBlob = async () => { await control.hold(); }; + const posted = control.posted("referenceReadPrepare"), pending = f.read(); + try { + await posted; + writeFileSync(f.policyPath, readFileSync(f.policyPath, "utf8") + "\nThe fleet reviews the harbor.\n"); + control.release(); + expect((await pending).evidence.ownerResolution.state, "OWNER_WRITER_FENCES_LIVE_GENERATION_AFTER_QUEUE").toBe("unavailable"); + f.state.afterBlob = async () => {}; + expect((await f.read()).evidence.ownerResolution.state, "NEXT_READ_RECOVERS_WITH_FRESH_SETTINGS_LIVE_SNAPSHOT").toBe("available"); + } finally { await control.close(); await pending.catch(() => {}); } +}); diff --git a/packages/ui-server/tests/reference-read.test.ts b/packages/ui-server/tests/reference-read.test.ts index b8034ed814..30621e81cb 100644 --- a/packages/ui-server/tests/reference-read.test.ts +++ b/packages/ui-server/tests/reference-read.test.ts @@ -482,3 +482,12 @@ test("another call in the same turn cannot substitute an earlier transport opera f.state.reuseObservation = true; await expect(f.call({ toolCallId: "read-2" }), "READ_REQUIRES_ITS_OWN_TRANSPORT_OPERATION").rejects.toThrow(/transport identity/); }); + +test("read evidence explicitly withholds owner qualification without protected approval", async () => { + const f = await fixture(); + await f.call(); + const row = f.db.query("SELECT evidence FROM reference_reads").get() as { evidence: string }; + expect(JSON.parse(row.evidence).ownerResolution, "READ_OWNER_RESOLUTION_IS_EXPLICITLY_UNAVAILABLE").toMatchObject({ + version: 1, state: "unavailable", bindings: [], + }); +}); diff --git a/packages/ui-server/tests/relay-session-binding.test.ts b/packages/ui-server/tests/relay-session-binding.test.ts index c07fedbd11..f3711949eb 100644 --- a/packages/ui-server/tests/relay-session-binding.test.ts +++ b/packages/ui-server/tests/relay-session-binding.test.ts @@ -67,9 +67,9 @@ for (const kind of ["inference", "provider"] as const) for (const releaseAt of [ } }); 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)) } }) + egress: { remainingBytes:()=>proxy!.remainingBytes(),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)) } }); + egress: { remainingBytes:()=>proxy!.remainingBytes(),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); @@ -135,12 +135,12 @@ async function adverseFixture(kind: "inference" | "provider", finalWait = false) ? 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)) } }) + }, egress: { remainingBytes:()=>proxy!.remainingBytes(),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)) } }); + }, egress: { remainingBytes:()=>proxy!.remainingBytes(),relayed: (...args) => observeOperation(proxy.relayed(...args)) } }); return { db, writer, writes, turn, bridge, catalog, controller, reads, proxy, hold, host, enteredAdmission: enteredAdmission.promise, finalReached: finalReached.promise, releaseFinal: releaseFinal.resolve, @@ -183,7 +183,10 @@ for (const kind of ["inference", "provider"] as const) { 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); + // A revoked authority is403; an actually failed or unsettled binding stays503. + expect(result.status, "FAILED_BINDING_NEVER_DISPATCHES").toBe(mode === "cancelled" ? 499 : mode === "authority-revoked" ? 403 : 503); + if(kind === "inference") expect(JSON.parse(result.body).error.message).toBe(mode === "cancelled" ? "Inference request cancelled" : "Inference network admission refused"); + else expect(result.body).toContain(mode === "cancelled" ? "cancelled" : mode === "authority-revoked" ? "safety_changed" : "unavailable"); 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(); } @@ -200,6 +203,8 @@ for (const kind of ["inference", "provider"] as const) { expect(f.writes.recordingAvailable("voyage", "ithaca")).toBe(false); const result = await f.send(); expect(result.status).toBe(403); + if(kind === "inference") expect(JSON.parse(result.body).error.message).toBe("Inference network admission refused"); + else expect(result.body).toContain("safety"); expect(f.requests(), "INDEPENDENT_PENDING_INPUT_NEVER_REACHES_PROVIDER").toBe(0); expect(f.reads.some(value => !value.recordingAvailable)).toBe(true); held.release(); @@ -231,7 +236,7 @@ for (const kind of ["inference", "provider"] as const) { await f.catalog.settled!(); } f.releaseFinal(); - expect((await response).status).toBe(403); + expect((await response).status).toBe(mode === "own-recording-loss" ? 503 : 403); expect(f.requests(), "FINAL_SAFETY_CHANGE_NEVER_REACHES_PROVIDER").toBe(0); await f.proxy.settled(); if (mode === "changed-scope") { @@ -241,7 +246,7 @@ for (const kind of ["inference", "provider"] as const) { 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"; + const reason = mode === "own-recording-loss" ? "egress_unavailable" : "safety_changed"; expect(f.db.query("SELECT json_extract(payload,'$.reason') reason FROM governance_events WHERE kind='egress_connection'").all()) .toEqual([{ reason }]); } @@ -285,7 +290,7 @@ for (const kind of ["inference", "provider"] as const) test(`${kind} own-binding const refused = f.send(); await f.enteredAdmission; await new Promise(resolve => setImmediate(resolve)); Object.defineProperty(Date, "now", { ...clock, value: () => now() + 10001 }); - expect((await refused).status, "OWN_BINDING_DEADLINE_REFUSES_ONLY_ITS_REQUEST").toBe(403); + expect((await refused).status, "OWN_BINDING_DEADLINE_REFUSES_ONLY_ITS_REQUEST").toBe(503); Object.defineProperty(Date, "now", clock); held.release(); await held.committed; await f.catalog.settled!(); await f.proxy.settled(); const controller = new AbortController(); diff --git a/packages/ui-server/tests/safety-entry-correlation.test.ts b/packages/ui-server/tests/safety-entry-correlation.test.ts index 7a80a686df..5c40231a1e 100644 --- a/packages/ui-server/tests/safety-entry-correlation.test.ts +++ b/packages/ui-server/tests/safety-entry-correlation.test.ts @@ -58,3 +58,22 @@ test('opaque and unsupported tool identities never acquire a guessed entry',asyn for(const r of page.records.filter(r=>r.kind==='occurrence'))expect(r,'NO_NAME_OR_TIMING_ATTRIBUTION').not.toHaveProperty('entry'); }finally{await f.close();} }); + +test('admission evidence is independently negotiated and pinned across pages, deltas and pruning',async()=>{ + const f=await safetyHistoryFixture(true,true);try{ + const {occurrence}=await import('../src/governance/occurrence'); + const add=async()=>{const o=occurrence(f.bindingId,'proxy_input',crypto.randomUUID(),'finalized');o.provenance={kind:'web_origin',origin:{scheme:'http',host:'127.0.0.1',port:80},verifiedBy:'host_transport'};o.admission={trusted:true,ruleId:'ithaca-source',policyHash:'a'.repeat(64),trustRevision:'7',collectionRevision:'3'}; + await f.writes.record({kind:'taint',sessionId:'ithaca',turnId:'voyage',at:0,actor:'interactive',model:null,profile:'governed',payload:{source:'egress_connection',tool:null,detail:null,occurrence:o}});return o.id;}; + await add();await add(); + const old=await f.history.read(f.principal,{sessionId:'ithaca'},null,50,true); + expect(old.records.every(r=>!('admission' in r)),'OLD_READERS_RETAIN_STRICT_ADMISSION_SHAPE').toBe(true); + const opted=await f.history.read(f.principal,{sessionId:'ithaca'},null,1,false,true);expect(opted.records[0]).toHaveProperty('admission.trusted',true);expect(opted.nextCursor).not.toBeNull(); + let refused:unknown;try{await f.history.read(f.principal,{sessionId:'ithaca'},opted.nextCursor,1,false,false);}catch(error){refused=error;}expect(refused,'CURSOR_PINS_ADMISSION_SHAPE').toHaveProperty('reason','expired'); + const ws=await f.connect();expect(ws.hello.type==='server_hello'&&ws.hello.capabilities?.sessionSafetyAdmissionEvidence).toBe(true); + ws.send({type:'safety_read',version:1,requestId:'admissions',target:{sessionId:'ithaca'},includeAdmissions:true});const frame=await ws.until(m=>m.type==='safety_history');if(frame.type!=='safety_history')throw new Error('Missing page'); + expect(frame.page.records[0]).toHaveProperty('admission.ruleId','ithaca-source');ws.send({type:'safety_subscribe',version:1,requestId:'admissions',identity:frame.page.identity,afterRevision:frame.page.highWater,snapshotId:frame.page.snapshotId}); + const id=await add();f.history.poll();const update=await ws.until(m=>m.type==='safety_update'&&m.update.records.some(r=>r.id===id));expect(update.type==='safety_update'&&update.update.records.some(r=>r.kind==='occurrence'&&r.admission?.trusted),'SUBSCRIPTION_PINS_ADMISSION_EVIDENCE').toBe(true); + pruneSafetyDetail(f.db,Number.MAX_SAFE_INTEGER);const page=await f.history.read(f.principal,{sessionId:'ithaca'},null,50,false,true);expect(page.records[0]).toHaveProperty('admission.ruleId','ithaca-source');const {safetyRecordSchema}=await import('@schlessera/brain-ui-sdk/internal');for(const record of page.records)expect(safetyRecordSchema.safeParse(record).success,'PRUNED_TRUSTED_ADMISSION_RETAINS_VERIFIED_PROVENANCE').toBe(true); + const http=await f.get('?admissions=1');expect(http.status).toBe(200);expect((await http.json() as any).records[0]).toHaveProperty('admission.trusted',true);expect((await f.get('?admissions=0')).status).toBe(400); + }finally{await f.close();} +}); diff --git a/packages/ui-server/tests/trust-settings.test.ts b/packages/ui-server/tests/trust-settings.test.ts index b531899344..a9d2de9498 100644 --- a/packages/ui-server/tests/trust-settings.test.ts +++ b/packages/ui-server/tests/trust-settings.test.ts @@ -1,7 +1,8 @@ import { createGovernancePolicyReader } from "../src/brain/governance-policy.js"; import { createTurnJournal } from "../src/brain/turn-journal.js"; import { createNativeJournalFixture } from "./helpers/native-journal-fixture.js"; -import { afterEach, expect, test } from "bun:test"; +import * as fs from "node:fs"; +import { afterEach, expect, test, spyOn } from "bun:test"; import { mkdtempSync, mkdirSync, readFileSync, writeFileSync, rmSync, renameSync, symlinkSync, openSync, closeSync, constants } from "node:fs"; import { join } from "node:path"; import { createHash } from "node:crypto"; @@ -181,8 +182,14 @@ test("real HTTP login/owner/CSRF boundary rejects ambient, agent, forged-card an const preparedResponse = await request("/prepare", body); expect(preparedResponse.status).toBe(200); const draft = await preparedResponse.json() as Awaited>; const commit = { version: 1, requestId: draft.receipt.requestId, reviewId: draft.review.reviewId, reviewedBytesHash: draft.review.reviewedBytesHash }; - mode = "none"; expect((await request("/commit", commit)).status).toBe(403); mode = "password"; - f.db.exec("UPDATE principals SET kind='agent'"); expect((await request("/commit", commit)).status).toBe(403); + mode = "none"; + const ambient = await request(""); expect(ambient.status).toBe(200); expect((await ambient.json() as { mutationAllowed: boolean }).mutationAllowed).toBe(false); + expect((await request("/ithaca-review")).status).toBe(403); + expect((await request("/commit", commit)).status).toBe(403); mode = "password"; + f.db.exec("UPDATE principals SET kind='agent'"); + const agentView = await request(""); expect(agentView.status).toBe(200); expect((await agentView.json() as { mutationAllowed: boolean }).mutationAllowed).toBe(false); + expect((await request("/prepare", body)).status).toBe(403); + expect((await request("/commit", commit)).status).toBe(403); f.db.exec("UPDATE principals SET kind='owner',revoked_at=1"); expect((await request("/commit", commit)).status).toBe(401); expect(readFileSync(f.path, "utf8")).toBe(initial); expect(p.policyHash).toBe(hash(initial)); }); @@ -435,3 +442,224 @@ test("Settings HTTP admission bounds queued lock waiters and recovers when reque expect((await app.request("http://localhost/api/trust-settings")).status, "SETTINGS_HTTP_BUSY_CLEARS_WHEN_WAITERS_DRAIN").toBe(200); expect(f.requests).toEqual([]); }); + +test("qualified origin removal notifies live fences at the durable revision before its enforced receipt", async () => { + const f=await fixture({originEnforcement:true});const draft=await f.prepare(); + const added=await f.commit(draft);expect(added.receipt).toMatchObject({stage:"committed",enforcement:"enforced"}); + const removing=await f.prepare({action:"remove",ruleId:rule.id});let fenced=false; + const release=f.settings.live.subscribe(()=>{fenced=true;expect(f.settings.live.read().rules).toEqual([]);expect(f.settings.live.revision()).toBe("2");}); + try {const removed=await f.commit(removing);expect(fenced,"ENFORCED_REMOVAL_JOINS_LIVE_FENCE").toBe(true);expect(removed.receipt).toMatchObject({stage:"committed",enforcement:"enforced",currentRule:"removed"});expect(removed.capabilities).toMatchObject({originRules:true,recipientRules:true,repositoryRules:false});}finally{release();} +}); + +test("post-publication invalid policy cannot claim an enforced origin removal",async()=>{ + let invalidate=false,target=""; + const f=await fixture({originEnforcement:true,checkpoint:stage=>{if(invalidate&&stage==="file_published")writeFileSync(target,"---\nschema_version: invalid\n---\n");}});target=f.path; + await f.commit(await f.prepare());const removal=await f.prepare({action:"remove",ruleId:rule.id});invalidate=true; + const saved=await f.commit(removal);expect(saved.receipt,"INVALID_CURRENT_POLICY_NEVER_CLAIMS_REMOVAL_ENFORCED").toMatchObject({publication:"proved",stage:"partial",enforcement:"unavailable",currentRule:"unknown"}); + expect(f.settings.live.read().rules[0]?.id).toBe(rule.id); +}); + +test("review: valid trust edits outside Settings cannot remain silently active",async()=>{ + const f=await fixture({originEnforcement:true});await f.commit(await f.prepare());writeFileSync(f.path,initial); + expect(()=>f.settings.live.read(),"OUTSIDE_PUBLICATION_FENCES_STALE_TRUST").toThrow(); + await f.settings.live.refresh();expect(f.settings.live.read().rules).toEqual([]); +}); + +test("review: real alternate policy publication refreshes durable trust under the same brain lock",async()=>{ + const f=await fixture({originEnforcement:true});await f.commit(await f.prepare());const {createPolicyProposals}=await import('../src/brain/policy-proposal.js'); + const service=createPolicyProposals({root:f.root,db:f.db,writer:f.writer,lock:f.lock,observeUserPolicy:(_id,write)=>write(),recordEvent:()=>{},afterPublication:()=>f.settings.refreshLocked()}); + const result=await service.propose({principalId:'odysseus',turnId:'alternate-policy',sessionId:()=>null,signal:new AbortController().signal,isAuthorized:()=>true,isAvailable:()=>true,approve:async()=>true,emit(){}},'remove-origin',{content:initial,rationale:'Remove future source trust.'}); + expect(result.state).toBe('updated');expect(f.settings.live.read().rules,'ALTERNATE_POLICY_WRITER_REMOVAL_IS_LIVE').toEqual([]);expect(f.settings.live.revision()).toBe('2'); +}); + +test('review3: live trust evidence uses verified bytes after an unrelated policy edit',async()=>{ + const f=await fixture({originEnforcement:true});await f.commit(await f.prepare());const before=f.settings.live.read(); + const changed=readFileSync(f.path,'utf8').replace('block_usd: 17','block_usd: 19');writeFileSync(f.path,changed); + const current=f.settings.live.read();expect(current.rules).toEqual(before.rules);expect(current.revision).toBe(before.revision); + expect(current.policyHash,'LIVE_ADMISSION_HASH_NAMES_VERIFIED_POLICY_BYTES').toBe(hash(changed));expect(current.policyHash).not.toBe(before.policyHash); +}); + + +test('review4: oversized policy retains last-valid live trust with honest error',async()=>{ + const f=await fixture({originEnforcement:true});await f.commit(await f.prepare());const before=f.settings.live.read();writeFileSync(f.path,'x'.repeat(1024*1024+1)); + await f.settings.live.refresh();expect(f.settings.live.read(),'UNREADABLE_POLICY_RETAINS_LAST_VALID_TRUST').toMatchObject({...before,error:'policy_unavailable'});expect(f.settings.live.revision()).toBe(before.revision); +}); + +for(const host of ['example.org','127.0.0.1','[::1]','xn--bcher-kva.example'])for(const kind of ['web_origin','tunnel_authority'] as const)test(`review4: Settings accepts enforced canonical ${kind} ${host}`,async()=>{ + const f=await fixture({originEnforcement:true});const selector=kind==='web_origin'?{kind,scheme:'https' as const,host,port:443}:{kind,host,port:443};const draft=await f.prepare({action:'create',rule:{...rule,selector}});const saved=await f.commit(draft);expect(saved.receipt).toMatchObject({enforcement:'enforced'});expect(f.settings.live.read().rules[0]?.selector).toEqual(selector); +}); + + +test('review5: malformed live policy reports an error before any refresh',async()=>{ + const f=await fixture({originEnforcement:true});await f.commit(await f.prepare());const before=f.settings.live.read(),valid=readFileSync(f.path,'utf8');writeFileSync(f.path,'---\nschema_version: [\n---\n'); + expect(f.settings.live.read(),'MALFORMED_LIVE_POLICY_REPORTS_ERROR').toMatchObject({...before,error:'policy_unavailable'}); + writeFileSync(f.path,valid);expect(f.settings.live.read()).toMatchObject({...before,error:null}); +}); +for(const refreshing of [false,true])test(`review5: removal during anchored verification fences ${refreshing?'refresh':'read'}`,async()=>{ + const f=await fixture({originEnforcement:true});await f.commit(await f.prepare());writeFileSync(f.path,readFileSync(f.path,'utf8')+'\n');const read=fs.readSync;let swapped=false; + const spy=spyOn(fs,'readSync').mockImplementation(((...args:Parameters)=>{const n=Reflect.apply(read,fs,args);if(n>0&&!swapped){swapped=true;renameSync(f.path,f.path+'.old');writeFileSync(f.path,initial);}return n;}) as typeof fs.readSync); + try{if(refreshing){const current=await f.settings.live.refresh();expect(current.rules,'LOCKED_RETRY_NEVER_RETAINS_REMOVED_RULE').toEqual([]);expect(current.revision).toBe('2');}else expect(()=>f.settings.live.read(),'CHANGED_DURING_VERIFICATION_NEVER_RETAINS_RULE').toThrow();expect(swapped).toBe(true);}finally{spy.mockRestore();} +}); +test('review5: unchanged large policy uses a cheap per-chunk revision fence',async()=>{ + const f=await fixture({originEnforcement:true});await f.commit(await f.prepare());writeFileSync(f.path,readFileSync(f.path,'utf8')+'\n'+ 'Ithaca. '.repeat(12000));const p=f.settings.live.read();const read=fs.readSync;let reads=0; + const spy=spyOn(fs,'readSync').mockImplementation(((...args:Parameters)=>{reads++;return Reflect.apply(read,fs,args);}) as typeof fs.readSync); + try{for(let i=0;i<16;i++)expect(f.settings.live.revision()).toBe(p.revision);expect(reads,'UNCHANGED_CHUNKS_NEVER_REREAD_POLICY').toBe(0); + writeFileSync(f.path,initial);expect(()=>f.settings.live.revision(),'CHEAP_FENCE_STILL_DETECTS_REMOVAL').toThrow();expect(reads).toBeGreaterThan(0); + }finally{spy.mockRestore();} +}); + +test('review5: refresh rechecks current generation after its durable projection wait',async()=>{ + const f=await fixture({originEnforcement:true});await f.commit(await f.prepare());writeFileSync(f.path,readFileSync(f.path,'utf8')+'\nIthaca.'); + const probe=await import('./fixtures/write-worker-probe');const channel=f.writer.channel(probe,{table:'trust_refresh_wait'});await channel.ready;const active=new Int32Array(new SharedArrayBuffer(4));const slow=channel.call('slow','Calypso',100,active);await Atomics.waitAsync(active,0,0).value; + let entered!:()=>void;const reached=new Promise(r=>{entered=r;});const read=fs.readSync;const spy=spyOn(fs,'readSync').mockImplementation(((...args:Parameters)=>{const n=Reflect.apply(read,fs,args);if(n>0)queueMicrotask(entered);return n;}) as typeof fs.readSync); + const pending=f.settings.live.refresh();try{await reached;}finally{spy.mockRestore();}writeFileSync(f.path,'---\nschema_version: [\n---\n');await slow; + expect((await pending).error,'REFRESH_NEVER_REPORTS_HEALTHY_AFTER_POLICY_CHANGES_DURING_COMMIT').toBe('policy_unavailable'); +}); + +test('review7: a second reader recovers after the writer commits the same file generation',async()=>{ + const f=await fixture({originEnforcement:true});await f.commit(await f.prepare());const second=createTrustSettings({...f.options,originEnforcement:true});expect(second.live.read().rules).toHaveLength(1); + writeFileSync(f.path,initial);expect(()=>second.live.read()).toThrow();await f.settings.live.refresh(); + expect(second.live.read().rules,'SECOND_READER_RECOVERS_WITHOUT_EXPLICIT_REFRESH').toEqual([]);expect(second.live.revision()).toBe('2'); +}); + +test("unchanged durable trust refresh does not queue the held brain lock", async () => { + const f = await fixture({ originEnforcement: true }); + await f.commit(await f.prepare()); + const committed = f.settings.live.read(); + const release = await f.lock.acquire(BRAIN_LOCK_KEY); + const original = f.lock.withLock.bind(f.lock); + let calls = 0; + f.lock.withLock = (key, fn, options) => { if (key === BRAIN_LOCK_KEY) calls++; return original(key, fn, options); }; + let pending: ReturnType | undefined; + try { + pending = f.settings.live.refresh(); + expect(calls, "UNCHANGED_REFRESH_NEVER_QUEUES_BRAIN_LOCK").toBe(0); + expect(await pending).toEqual(committed); + expect(f.lock.heldKeys).toContain(BRAIN_LOCK_KEY); + } finally { release(); await pending; } +}); + +test("diverged trust refresh queues the held brain lock and publishes a new revision after release", async () => { + const f = await fixture({ originEnforcement: true }); + await f.commit(await f.prepare()); + const before = f.settings.live.read(); + writeFileSync(f.path, initial); + const release = await f.lock.acquire(BRAIN_LOCK_KEY); + const original = f.lock.withLock.bind(f.lock); + let calls = 0, completed = false; + f.lock.withLock = (key, fn, options) => { if (key === BRAIN_LOCK_KEY) calls++; return original(key, fn, options); }; + const pending = f.settings.live.refresh().then(value => { completed = true; return value; }); + try { + expect(calls, "CHANGED_POLICY_STILL_QUEUES_BRAIN_LOCK").toBe(1); + await Promise.resolve(); + expect(completed).toBe(false); + expect(f.lock.heldKeys).toContain(BRAIN_LOCK_KEY); + } finally { release(); } + const after = await pending; + expect(after.rules).toEqual([]); + expect(BigInt(after.revision)).toBe(BigInt(before.revision) + 1n); +}); + +test("ADMISSION_NEVER_WAITS_ON_HELD_INDEX_LOCK", async () => { + const f = await fixture({ originEnforcement: true }); + await f.commit(await f.prepare()); + const { WsHost } = await import("../src/ws/host"); + const { runSession } = await import("../src/ws/run-session"); + const { createSessionCatalog } = await import("../src/ws/session-catalog"); + const { createStaticBackendRegistry } = await import("../src/agent/backend"); + const { makeFakeBackend } = await import("./helpers/fake-backend"); + const { testAuthorization } = await import("./helpers/principal"); + let started = 0, queued!: () => void; + const blocked = new Promise(resolve => { queued = resolve; }); + const original = f.lock.withLock.bind(f.lock); + f.lock.withLock = (key, fn, options) => { if (key === BRAIN_LOCK_KEY) queued(); return original(key, fn, options); }; + const policy = createGovernancePolicyReader(f.root).load(); + const backend = makeFakeBackend({ id: "pi", async startTurn() { started++; } }); + const host = new WsHost({ registry: createStaticBackendRegistry([backend], "pi"), catalog: createSessionCatalog(() => f.db), originTrust: f.settings.live, + governedTurns: { async begin() { return { sandbox: { profile: "strict", noteFacts: {} }, policy, async end() { return null; } }; }, refresh() {}, async close() {}, async bindSession() {}, async exposures() { return []; }, facts() { return { policyProfile: "strict", policy }; } } as never }); + const release = await f.lock.acquire(BRAIN_LOCK_KEY); + const running = runSession(host, { authorization: testAuthorization(), text: "Plan Ithaca", attachments: [] }); + try { + const finished = await Promise.race([running.then(() => true), blocked.then(() => false)]); + expect(started, "ADMISSION_NEVER_WAITS_ON_HELD_INDEX_LOCK").toBe(1); + expect(finished, "SESSION_FINISHES_BEFORE_INDEX_LOCK_RELEASE").toBe(true); + expect(f.lock.heldKeys).toContain(BRAIN_LOCK_KEY); + } finally { release(); await running; host.close(); } +}); + +for(const timeout of [false,true])test(`review10: turn trust refresh releases governed resources before the lock holder on ${timeout?'timeout':'cancel'}`,async()=>{ + const f=await fixture({originEnforcement:true});const {WsHost}=await import('../src/ws/host');const {runSession}=await import('../src/ws/run-session');const {createSessionCatalog}=await import('../src/ws/session-catalog');const {createStaticBackendRegistry}=await import('../src/agent/backend');const {makeFakeBackend}=await import('./helpers/fake-backend');const {testAuthorization}=await import('./helpers/principal'); + await f.commit(await f.prepare());writeFileSync(f.path,initial); + let held=0,entered!:()=>void,started=0;const reached=new Promise(r=>{entered=r;});const original=f.lock.withLock.bind(f.lock);f.lock.withLock=(key,fn,opts)=>{if(key===BRAIN_LOCK_KEY)entered();return original(key,fn,opts);}; + const policy=createGovernancePolicyReader(f.root).load();const backend=makeFakeBackend({id:'pi',async startTurn(){started++;}});const host=new WsHost({registry:createStaticBackendRegistry([backend],'pi'),catalog:createSessionCatalog(()=>f.db),turnTimeoutMs:5000,originTrust:f.settings.live,governedTurns:{async begin(){held++;return {sandbox:{profile:'strict',noteFacts:{}},policy,async end(){held--;return null;}};},refresh(){},async close(){},async bindSession(){},async exposures(){return [];},facts(){return {policyProfile:'strict',policy};}} as never}); + const release=await f.lock.acquire(BRAIN_LOCK_KEY);let running:Promise|undefined; + try{running=runSession(host,{authorization:testAuthorization(),text:'Plan Ithaca',attachments:[]});await reached;if(!timeout)host.coordinator.cancelAll('Odysseus cancels');const done=await Promise.race([running.then(()=>true),Bun.sleep(timeout?6000:200).then(()=>false)]); + expect(done,'CANCELLED_REFRESH_NEVER_WAITS_FOR_UNRELATED_HOLDER').toBe(true);expect(held).toBe(0);expect(host.coordinator.isTurnActive()).toBe(false);expect(started).toBe(0);expect(f.lock.heldKeys).toContain(BRAIN_LOCK_KEY); + }finally{release();await running;host.close();} +}); + +for(const transition of ['remove','disable','retarget'] as const)test(`review12: two publishers retire source instances across ${transition}`,async()=>{ + const f=await fixture({originEnforcement:true});const {request}=await import('node:http');const {prepareTurnEgress}=await import('../src/brain/turn-egress');const {createGovernanceWrites}=await import('../src/governance/event-writes');const {connectedSafetySession}=await import('./helpers/connected-safety');const {createEffectiveSafety}=await import('../src/governance/effective-safety');const {resolveGovernancePolicy}=await import('@schlessera/brain-common/internal/governance-policy'); + let stream!:ReadableStreamDefaultController,first!:()=>void,second!:()=>void;const received=new Promise(r=>{first=r;}),later=new Promise(r=>{second=r;});const origin=Bun.serve({hostname:'127.0.0.1',port:0,fetch:()=>new Response(new ReadableStream({start(c){stream=c;c.enqueue(new TextEncoder().encode('first'));}}))}); + const source={...rule,selector:{kind:'web_origin' as const,scheme:'http' as const,host:'127.0.0.1',port:origin.port!}};await f.commit(await f.prepare({action:'create',rule:source}));const publisher=createTrustSettings({...f.options,originEnforcement:true});connectedSafetySession(f.db,'voyage','turn-voyage');const writes=createGovernanceWrites(f.db,f.writer),controller=new AbortController(),safety=createEffectiveSafety(f.db,{turnId:'turn-voyage',sessionId:()=> 'voyage',policyHash:null,writes,trust:f.settings.live,authority:()=>({current:true,epoch:'1'})}); + const proxy=await prepareTurnEgress({policy:resolveGovernancePolicy({schema_version:1}),trust:f.settings.live,controller,turnId:'turn-voyage',sessionId:()=> 'voyage',model:()=>null,profile:'governed',origin:'interactive',governanceDb:f.db,governanceWrites:writes,record:writes.record,bridge:{emit(){},requestPermission:async()=>({behavior:'deny',message:'Athena declines'}),admissionSafety:safety}}); + const closed=new Promise((resolve,reject)=>{const req=request({socketPath:proxy.socketPath,path:origin.url.href},res=>{res.on('data',b=>{first();if(b.toString().includes('second'))second();});res.on('close',resolve);res.on('error',()=>resolve());});req.on('error',reject);req.end();}); + const publish=async(change:unknown)=>{const p=await publisher.list('odysseus'),draft=await publisher.prepare('odysseus',{version:1,expectedTrustRevision:p.revision,expectedPolicyHash:p.policyHash,change});return publisher.commit('odysseus',{version:1,requestId:draft.receipt.requestId,reviewId:draft.review.reviewId,reviewedBytesHash:draft.review.reviewedBytesHash});}; + try{await received;const birth=f.settings.live.read().ruleInstances[source.id];expect((await publish({action:'edit',rule:{...source,recipientWhileRestricted:true}})).receipt.enforcement).toBe('enforced');expect(f.settings.live.read().ruleInstances[source.id],'RECIPIENT_ONLY_EDIT_PRESERVES_SOURCE_INSTANCE').toBe(birth);if(transition==='retarget'){ + // Settings intentionally requires remove/add for retargeting. Another valid policy + // writer can edit the same descriptor in place; no remove/create masks this case. + const edit=(host:string)=>writeFileSync(f.path,`---\n${JSON.stringify({schema_version:1,taint:{trusted_sources:[{...source,selector:{...source.selector,host}}]}})}\n---\nThe voyage policy.\n`); + edit('troy.example.org');await publisher.live.refresh(); + const retargeted=f.settings.live.read();expect(retargeted.rules.map(r=>r.id)).toEqual([source.id]);expect(retargeted.rules[0]!.selector).toMatchObject({host:'troy.example.org'});expect(retargeted.ruleInstances[source.id],'SELECTOR_EDIT_RETIRES_OLD_INSTANCE_IN_PLACE').not.toBe(birth); + edit(source.selector.host);await publisher.live.refresh(); + }else{const retired=transition==='remove'?{action:'remove',ruleId:source.id}:{action:'edit',rule:{...source,incomingContent:false,recipientWhileRestricted:true}};expect((await publish(retired)).receipt.enforcement).toBe('enforced');expect((await publish({action:transition==='remove'?'create':'edit',rule:source})).receipt.enforcement).toBe('enforced');}expect(f.settings.live.read().ruleInstances[source.id],'RESTORED_SOURCE_IS_A_NEW_INSTANCE').not.toBe(birth);try{stream.enqueue(new TextEncoder().encode('second'));}catch{}expect(await Promise.race([later.then(()=>true),closed.then(()=>false)]),'RECREATED_ID_NEVER_RESUMES_OLD_SOURCE_INSTANCE').toBe(false);expect(controller.signal.aborted).toBe(false);expect(JSON.stringify(await publisher.list('odysseus'))).not.toContain('ruleInstances'); + }finally{proxy.stop();await closed;await proxy.settled();origin.stop(true);} +}); + +test("authenticated read-only callers can inspect sanitized trust lists without publication authority", async () => { + const f = await fixture(); + const owner = createPrincipal(f.db, { authMethod: "password", label: "Odysseus", ttlSeconds: 3600 }); + const reader = createPrincipal(f.db, { authMethod: "delegated", label: "Eumaeus", createdBy: owner.id, ttlSeconds: 3600 }); + const view = await f.settings.list(reader.id); + expect(view.mutationAllowed).toBe(false); + expect(view.rules).toEqual([]); + expect((await f.settings.list("odysseus")).mutationAllowed).toBe(true); + await expect(f.settings.prepare(reader.id, { version: 1, expectedTrustRevision: view.revision, expectedPolicyHash: view.policyHash, change: { action: "create", rule } })).rejects.toThrow("unauthorized"); +}); + +for (const transition of ["revoke-owner", "revoke-agent", "expire-owner", "delete-owner"] as const) test(`F1 list refuses ${transition} while waiting on the brain lock`, async () => { + const root = mkdtempSync(join(import.meta.dir, "../../../tmp/trust-settings-tests/read-race-")); + const db = createUiDb(":memory:"), lock = createKeyedLock(); + cleanup.push(() => { db.close(); rmSync(root, { recursive: true, force: true }); }); + mkdirSync(join(root, "context/policies"), { recursive: true }); + writeFileSync(join(root, "context/policies/governance.md"), `---\nschema_version: 1\ntaint: ${JSON.stringify({ trusted_sources: [rule] })}\n---\nThe voyage policy.\n`); + const owner = createPrincipal(db, { authMethod: "password", label: "Odysseus", ttlSeconds: 3600 }); + const reader = transition === "revoke-agent" ? createPrincipal(db, { authMethod: "delegated", label: "Eumaeus", createdBy: owner.id, ttlSeconds: 3600 }) : owner; + const settings = createTrustSettings({ root, db, lock, observe: async (_id, publish) => { await publish(); }, authority: id => { + const p = resolvePrincipal(db, id); return p?.kind === "owner" && isUsablePrincipal(p, Date.now()) ? p.id : null; + } }); + expect((await settings.list(reader.id)).rules).toHaveLength(1); + const release = await lock.acquire(BRAIN_LOCK_KEY); + const pending = settings.list(reader.id); + try { + if (transition === "delete-owner") db.query("DELETE FROM principals WHERE id=?").run(reader.id); + else if (transition === "expire-owner") db.query("UPDATE principals SET expires_at=0 WHERE id=?").run(reader.id); + else expect(revokePrincipal(db, reader.id, Date.now())).toEqual([reader.id]); + const current = resolvePrincipal(db, reader.id); + expect(current !== null && isUsablePrincipal(current, Date.now())).toBe(false); + } finally { release(); } + let refusal: string | null = null; + try { await pending; } catch (error) { refusal = (error as Error).message; } + expect(refusal).toBe("unauthorized"); +}); + +test("round2 F4 list exposes stable observation instances and retires reused IDs", async () => { + const f = await fixture(); await f.commit(await f.prepare()); + const first = await f.settings.list("odysseus"); expect("instances" in first).toBe(true); + const birth = first.instances[rule.id]; expect(typeof birth).toBe("string"); + await f.commit(await f.prepare({ action: "create", rule: { ...rule, id: "argo", selector: { ...rule.selector, host: "troy.example.org" } } })); + expect((await f.settings.list("odysseus")).instances[rule.id]).toBe(birth); + await f.commit(await f.prepare({ action: "remove", ruleId: rule.id })); + await f.commit(await f.prepare()); + expect((await f.settings.list("odysseus")).instances[rule.id]).not.toBe(birth); +}); diff --git a/packages/ui-server/tests/turn-egress.test.ts b/packages/ui-server/tests/turn-egress.test.ts index d05d44d5fb..2770e82f64 100644 --- a/packages/ui-server/tests/turn-egress.test.ts +++ b/packages/ui-server/tests/turn-egress.test.ts @@ -93,7 +93,7 @@ for (const [reason, egress] of refusalCases) test(`a real turn refusal durably r expect(await get(proxy.socketPath, origin.url.href)).toBe(403); expect(calls, "TURN_EGRESS_REFUSAL_BEFORE_CONTACT").toBe(0); expect(queryGovernanceEvents(db, { kinds: ["egress_denial"], limit: 10 }), "TURN_EGRESS_DURABLE_DENIAL").toMatchObject([ - { payload: { host: "127.0.0.1", port: origin.port, method: "GET", reason, bytes: 0 } }, + { payload: { host: "127.0.0.1", port: origin.port, method: "GET", reason, bytes: reason === "byte_cap" ? 1 : 0 } }, ]); expect(proxy.recordingFailure()).toBeUndefined(); } finally { proxy.stop(); origin.stop(true); db.close(); } diff --git a/packages/ui-server/tests/web-pi-subscription.test.ts b/packages/ui-server/tests/web-pi-subscription.test.ts index de1c05d135..0dfbc150b5 100644 --- a/packages/ui-server/tests/web-pi-subscription.test.ts +++ b/packages/ui-server/tests/web-pi-subscription.test.ts @@ -30,6 +30,7 @@ const MODEL = "gpt-6-luna"; let root: string, brain: string, agentDir: string, hostConfig: string, stateRoot: string, broker: WebBroker | undefined; let upstream: ReturnType, nativeFetch: typeof fetch; let refreshes: number, refreshFails: boolean, slow: boolean, aborted: number; +let largeResponse=false; let requests: Array<{ path: string; authorization: string | null; account: string | null; model: unknown }>; let receipts: WebReceipt[], egress: import("@schlessera/brain-ui-sdk/internal").EgressRecord[]; /** Everything the executor process could hold while it served a request: its files, environment and argv. */ @@ -64,7 +65,7 @@ beforeEach(() => { root = mkdtempSync(join(tmpdir(), "odysseus-web-subscription-")); brain = join(root, "brain"); agentDir = join(root, "agent"); stateRoot = join(root, "executor-state"); mkdirSync(join(brain, "notes"), { recursive: true }); mkdirSync(agentDir); mkdirSync(join(root, "host")); - refreshes = 0; refreshFails = false; slow = false; aborted = 0; requests = []; receipts = []; egress = []; executorView = []; lentInto = []; + largeResponse=false;refreshes = 0; refreshFails = false; slow = false; aborted = 0; requests = []; receipts = []; egress = []; executorView = []; lentInto = []; writeLogin(login(1)); hostConfig = join(root, "host", "web-search.json"); writeFileSync(hostConfig, JSON.stringify({ searchRouting: { providers: ["openai"], fallbackOn: ["transient"] }, ssrf: { allowRanges: ["127.0.0.0/8"] } })); @@ -87,7 +88,7 @@ beforeEach(() => { } return Response.json({ output: [ { type: "web_search_call", id: "ws_1", status: "completed", action: { type: "search", query: "Odysseus raft", sources: [{ type: "url", url: "https://ithaca.example/log" }] } }, - { type: "message", role: "assistant", content: [{ type: "output_text", text: "The raft reaches Ithaca at dawn.", + { type: "message", role: "assistant", content: [{ type: "output_text", text: largeResponse?"Ithaca ".repeat(16000):"The raft reaches Ithaca at dawn.", annotations: [{ type: "url_citation", url: "https://ithaca.example/log", title: "Ithaca harbour log", start_index: 0, end_index: 31 }] }] }, ] }); } }); @@ -107,12 +108,12 @@ afterEach(async () => { rmSync(root, { recursive: true, force: true }); }); -function startBroker(): WebBroker { +function startBroker(extra: Partial[0]> = {}): WebBroker { return broker = createHostWebTools({ module: piInternal, root: stateRoot, hostConfigPath: () => hostConfig, env: {}, runtime: process.execPath, path: process.env.PATH!, onReceipt: receipt => receipts.push(receipt), limits: { callDeadlineMs: 25_000 }, // The relayed endpoint is admitted at its own name; the fixture answers for it on loopback. lookup: async host => { if (host === "chatgpt.com") return [{ address: "127.0.0.1", family: 4 }]; throw new Error(`ENOTFOUND ${host}`); }, - egressPorts: [443], onEgress: record => egress.push(record) }); + egressPorts: [443], onEgress: record => egress.push(record),...extra }); } /** The egress directories the turn's model was lent into, to see its relay stop. */ @@ -234,3 +235,10 @@ test("a cancelled subscription search stops the relayed request and stops the re for (let wait = 0; wait < 100 && existsSync(link); wait++) await Bun.sleep(20); expect(existsSync(link), "WEB_SUBSCRIPTION_RELAY_STOPPED").toBe(false); }, 60_000); + + +test("review24: web model route carries and exhausts its real remaining allowance",async()=>{ + largeResponse=true;writeLogin(login(Date.now()+3600000));startBroker({maxEgressBytes:8192});const access=turnModel();let remaining:(()=>number)|undefined; + const model:WebModelAccess={...access,open:(route,signal)=>{remaining=route.remainingBytes;return access.open(route,signal);}}; + const envelope=await search(model);expect(envelope.ok).toBe(false);expect(typeof remaining,"WEB_ROUTE_NEVER_DROPS_REMAINING_BYTES").toBe("function");expect(requests.length,"OVERFLOW_IS_AN_OBSERVED_PROVIDER_RESPONSE").toBeGreaterThan(0);expect(remaining!(),"RECEIVED_WEB_RESPONSE_EXHAUSTS_EXECUTOR_ALLOWANCE").toBe(0);expect(egress.at(-1)).toMatchObject({outcome:"denied",failureReason:"budget"});const attempts=requests.length;expect((await search(model)).ok).toBe(false);expect(requests.length,"RECEIVED_OVERFLOW_CANNOT_FINANCE_ANOTHER_REQUEST").toBe(attempts); +},60000); diff --git a/scripts/native-proof/managed-reference-source.ts b/scripts/native-proof/managed-reference-source.ts index 7bb3db8e01..54aedb4dc0 100644 --- a/scripts/native-proof/managed-reference-source.ts +++ b/scripts/native-proof/managed-reference-source.ts @@ -1,5 +1,11 @@ +import { proveReferenceOwnerRoot } from "./reference-owner-root.js"; +import { resolveReferenceOwners } from "../../packages/ui-server/src/brain/reference-owner-resolution.js"; +import { createReferenceOwnerContinuity } from "../../packages/ui-server/src/brain/reference-owner-resolution.js"; /** Actual managed Git/TLS acquisition, maintenance workers and native Btrfs publication. No read-trust exemption. */ import { expect } from "bun:test"; +import { createKeyedLock } from "@schlessera/brain-ui-sdk/server"; +import { createTrustSettings } from "../../packages/ui-server/src/brain/trust-settings.js"; +import { createTrustGitHubIdentity } from "../../packages/ui-server/src/brain/trust-github-identity.js"; import { mkdirSync, readFileSync, writeFileSync } from "node:fs"; import { connect } from "node:net"; import { join } from "node:path"; @@ -40,6 +46,7 @@ export async function proveManagedReferenceSource(client: ReturnType id === principal.id ? "fixture-owner-epoch" : null, + observe: async (_id, publish) => { await publish(); } }); + const beforePolicy = await settings.list(principal.id); + const rule = { id: "ithaca-native", label: "Ithaca", incomingContent: true, recipientWhileRestricted: false, + selector: { kind: "github_repository" as const, host: "github.com" as const, owner: "odysseus", repository: "ithaca", repositoryId: "101" } }; + const preparedApproval = await settings.prepare(principal.id, { version: 1, expectedTrustRevision: beforePolicy.revision, + expectedPolicyHash: beforePolicy.policyHash, change: { action: "create", rule } }); + const approved = await settings.commit(principal.id, { version: 1, requestId: preparedApproval.receipt.requestId, + reviewId: preparedApproval.review.reviewId, reviewedBytesHash: preparedApproval.review.reviewedBytesHash }); + expect(approved.receipt.publication, "MANAGED_NATIVE_OWNER_APPROVAL_IS_REAL_PUBLICATION").toBe("proved"); + const reads = createReferenceReads({ db, ownerRoot: ownerContinuity.root, ownerPolicy: () => settings.ownerPolicy(), brain: servedBrain, sources, pool: client, transport }); const tools = createReferenceTools({ sources, reads }), turnId = "odysseus-native-read"; await tools.begin(turnId, { principalId: principal.id, posture: "interactive", generation: null }); tools.attachEgress(turnId, principal.id, { egress, current: () => true }); @@ -126,10 +144,29 @@ export async function proveManagedReferenceSource(client: ReturnType) => void) { + const path = join(dirname(brain), "odysseus-owner-recreated"), policy = "---\nschema_version: 1\n---\nThe voyage policy.\n"; + const btrfs = (...args: string[]) => { const p = Bun.spawnSync(["/usr/bin/btrfs", ...args], { stdout: "pipe", stderr: "pipe" }); + expect(p.exitCode, `OWNER_NATIVE_BTRFS: ${p.stderr}`).toBe(0); }; + let exists = false; + const inspect = async () => { const fd = openSync(path, constants.O_RDONLY | constants.O_DIRECTORY | constants.O_NOFOLLOW); + try { return { identity: await inspectPinnedReferenceRoot(fd), inode: fstatSync(fd).ino }; } finally { closeSync(fd); } }; + try { + btrfs("subvolume", "create", path); exists = true; writeFileSync(join(path, "governance.md"), policy); + const original = await inspect(), expected = { fsid: original.identity.fsid, brainUuid: original.identity.uuid }; + const first = await createReferenceOwnerContinuity(path, expected); + try { expect(first.root, "NATIVE_ORIGINAL_ROOT_QUALIFIES").toBeDefined(); } finally { first.close(); } + const restart = await createReferenceOwnerContinuity(path, expected); + try { expect(restart.root?.native, "NATIVE_ORDINARY_RESTART_PRESERVES_IDENTITY").toEqual(first.root!.native); } finally { restart.close(); } + rmSync(join(path, "governance.md")); btrfs("subvolume", "delete", path); exists = false; + btrfs("subvolume", "create", path); exists = true; writeFileSync(join(path, "governance.md"), policy); + const replacement = await inspect(); + expect(replacement.inode, "NATIVE_REPLACEMENT_REUSES_SUBVOLUME_ROOT_INODE").toBe(original.inode); + expect(replacement.identity.fsid).toBe(original.identity.fsid); + expect(replacement.identity.uuid).not.toBe(original.identity.uuid); + expect(readFileSync(join(path, "governance.md"), "utf8")).toBe(policy); + const refused = await createReferenceOwnerContinuity(path, expected); + try { expect(refused.root, "NATIVE_RECREATED_ROOT_CANNOT_INHERIT_APPROVAL").toBeUndefined(); } finally { refused.close(); } + note("managed-source-owner-native-root-recreation", { original: original.identity, replacement: replacement.identity, + originalInode: original.inode, replacementInode: replacement.inode, samePolicyBytes: true, restartQualified: true, replacementRefused: true }); + } finally { if (exists) { rmSync(join(path, "governance.md"), { force: true }); btrfs("subvolume", "delete", path); } } +}