diff --git a/.changeset/durable-human-trust-settings.md b/.changeset/durable-human-trust-settings.md new file mode 100644 index 0000000000..c301400878 --- /dev/null +++ b/.changeset/durable-human-trust-settings.md @@ -0,0 +1,6 @@ +--- +"@schlessera/brain-ui-server": minor +--- + +Add password-owner Settings trust publication with exact-byte reviews, descriptor-bound writes, bounded durable operation receipts and crash-safe readback. Verify GitHub repository and owner identities through the bounded host transport and retain approved-owner evidence only with proved publication. Runtime trust enforcement remains unavailable; saving policy never clears historical taint or grants runtime permission. +Refuse exhausted trust revisions before creating reviews or publishing protected policy bytes. diff --git a/api-report/ui-server.txt b/api-report/ui-server.txt index 6fb09c1c7d..f0ea66c3d4 100644 --- a/api-report/ui-server.txt +++ b/api-report/ui-server.txt @@ -2658,7 +2658,8 @@ signatures (every public export and the types it is made of) isHeld(): boolean; maintain: () => Promise; observe(): Promise; - observeUserPolicy(turnId: string, approvedWrite: () => Promise | void): Promise; + observeSettingsPolicy(_operationId: string, operation: (publish?: (write: () => void) => Promise) => Promise | void): Promise; + observeUserPolicy(turnId: string, approvedWrite: () => void): Promise; onObservation(observer: (turnId: string, facts: { changedPaths: number; observedBytes: number; diff --git a/docs/decisions/bounded-multi-read.md b/docs/decisions/bounded-multi-read.md index b5cbc9ec2f..231d9ce4ca 100644 --- a/docs/decisions/bounded-multi-read.md +++ b/docs/decisions/bounded-multi-read.md @@ -151,7 +151,7 @@ parallel default, with concurrency 1. proves only `read_file`, `write_file` and `edit_file`. So (`toolObservation`, `packages/ui-server/src/brain/tool-observation.ts:37-42`) calls it `unproven`, and - (`toolEnded`, `packages/ui-server/src/brain/turn-journal.ts:584-591`) + (`toolEnded`, `packages/ui-server/src/brain/turn-journal.ts:614-621`) observes every result and marks the turn lasting. Four reads made four observations, sequential or parallel. One batch call made one. That is a real host-side saving, small in time (8.3 ms against 1.4 ms on the fixture). diff --git a/docs/decisions/claude-code-runtime.md b/docs/decisions/claude-code-runtime.md index 78a25de3b7..6af13c6e44 100644 --- a/docs/decisions/claude-code-runtime.md +++ b/docs/decisions/claude-code-runtime.md @@ -64,7 +64,7 @@ next to it. of this binary. The only version probe in the server is for the `brain` CLI (`Probe the selected content CLI`, `packages/ui-server/src/brain/client.ts:180-248`, called at - `probeBrainCliVersion(config.brainPath`, `packages/ui-server/src/app.ts:510`). + `probeBrainCliVersion(config.brainPath`, `packages/ui-server/src/app.ts:513`). `brain doctor` runs `claude mcp list` from `PATH` (`which("claude")`, `packages/core/src/cli/commands/doctor.ts:507-511`) — the user's own Claude Code on their own machine, to check the MCP registration, not the server's diff --git a/docs/decisions/governed-writable-workers.md b/docs/decisions/governed-writable-workers.md index f346e70e15..08e7d87cc5 100644 --- a/docs/decisions/governed-writable-workers.md +++ b/docs/decisions/governed-writable-workers.md @@ -1258,7 +1258,7 @@ replacement and the deadline publish nothing and record no policy-updated event; a no-publication attempt records none either. Real observation and storage failures keep their existing handling, and a publication that committed before its report failed stays `unknown` and is never retried -(`const held`, `packages/ui-server/src/brain/policy-proposal.ts:159-254`). +(`const held`, `packages/ui-server/src/brain/policy-proposal.ts:160-252`). Every retained turn has one initially collapsed receipt. Known no-change is zero; legacy/unknown detail and unknown cost/limits remain explicitly unknown. @@ -1274,7 +1274,7 @@ principal authority remain the caller's responsibility. The policy publisher creates, writes, fsyncs and removes its operation-owned staging name entirely inside that synchronous callback, between the two serialized observations (`await options.observeUserPolicy`, -`packages/ui-server/src/brain/policy-proposal.ts:217-251`). First publication +`packages/ui-server/src/brain/policy-proposal.ts:218-232`). First publication also removes the temporary hardlink before the final observation. No filename prefix is ignored; a similarly named real agent change is still retained. Failed staging preserves the original policy, while failed recording after @@ -1533,7 +1533,7 @@ starts one per result and carries on (`void host.journal?.toolEnded`, `packages/ui-server/src/ws/bridge-capabilities/emission.ts:273`). The wait is the observation's hold. `held` takes it synchronously, before it queues the capture -(`function held`, `packages/ui-server/src/brain/turn-journal.ts:279-300`), +(`function held`, `packages/ui-server/src/brain/turn-journal.ts:293-314`), and the scope monitor's hold freezes every active turn's productive workers until the capture completes (`before() {`, `packages/ui-server/src/brain/turn-scope.ts:158-166`). Pi's agent loop runs in @@ -1545,7 +1545,7 @@ tracked the hold, not the bridge call. proven read-only, no other call of an active turn is still running, and no active turn has run a call whose effects may outlast it (`toolEnded(turnId: string, toolUseId: string)`, -`packages/ui-server/src/brain/turn-journal.ts:584-591`). Admission, turn end, +`packages/ui-server/src/brain/turn-journal.ts:614-621`). Admission, turn end, the 15-second timer, scope-limit observations, approved policy writes and removal coverage observe exactly as before. @@ -1804,7 +1804,7 @@ these versions as metadata-only and never open them for retention kind, mode, size and its ignored flag, carries `metadataOnly: true` and records its opaque change stamp, with no content hash and no symlink target. Two versions of equal size are told apart by that stamp, as ignored ones are -(`const identity`, `packages/ui-server/src/brain/turn-journal.ts:83`), +(`const identity`, `packages/ui-server/src/brain/turn-journal.ts:84`), so every observed refresh remains a recorded change. A metadata-only version is an intentional observation state: it adds no `missing` entry and does not make the turn partial. Removal coverage never treats the family as eligible, and history @@ -1816,7 +1816,7 @@ stays now counts its largest size once too, rather than each version. **History.** History presents every index-family version as metadata-only however it was recorded, so a version an earlier release retained is no longer read -(`const presented`, `packages/ui-server/src/brain/turn-journal.ts:76-81`). +(`const presented`, `packages/ui-server/src/brain/turn-journal.ts:77-82`). The reader groups these entries as the search index, recorded by size and timestamps only, with no review action. Preview reports `metadata_only` and download has nothing to serve. History revert and Undo read that same @@ -1873,7 +1873,7 @@ keeps its bytes. **The purge.** It runs once, on the journal's write worker, when the journal opens, after interrupted turns have been ended -(`while (await ledger.call`, `packages/ui-server/src/brain/turn-journal.ts:129`), +(`while (await ledger.call`, `packages/ui-server/src/brain/turn-journal.ts:144`), in at most two accounted commits whose progress is recorded in `turn_journal_allocation.index_purge` (`purgeIndexVersions(): IndexPurgeResult`, @@ -4744,7 +4744,7 @@ attribution. If an existing same-session/turn taint event precedes an agent observation, the journal retains its source ID with that change. Replay never infers taint from a later event, and absence of evidence does not assert complete untrusted-input detection. User history operations are not tainted agent writes -(`async function observe`, `packages/ui-server/src/brain/turn-journal.ts:413-478`). +(`async function observe`, `packages/ui-server/src/brain/turn-journal.ts:430-495`). Claude auto-memory persists outside the authoritative brain. Its validated native copy-out wraps each changed direct `.md` note in host journal retention: @@ -4767,7 +4767,7 @@ memory completion of the earlier 0.42.0 steering slice, not a widening of memory providers or a claim of capturing intervening external writes. The copy-out boundary is `const write`, `packages/ui-backend-claude/src/worker-state.ts:210-224`; retention/finalization is `persistClaudeMemory`, -`packages/ui-server/src/brain/turn-journal.ts:698-728`; destination-bound recovery +`packages/ui-server/src/brain/turn-journal.ts:763-793`; destination-bound recovery is `const target`, `packages/ui-server/src/brain/turn-revert.ts:113-123`. ### Concurrent edits diff --git a/docs/decisions/http-api-boundary.md b/docs/decisions/http-api-boundary.md index 86362d84c0..8673144d74 100644 --- a/docs/decisions/http-api-boundary.md +++ b/docs/decisions/http-api-boundary.md @@ -46,11 +46,11 @@ explicit supported rows, not silently excluded by this distinction. The source audit on 2026-09-30 used `e0875269b21b707482545be9e94901acb897893b`. The public health mount precedes auth -(`createHealthRoutes`, `packages/ui-server/src/app.ts:1102`), the API guard follows -public ceremonies (`authGuard`, `packages/ui-server/src/app.ts:1123`), and the -WebSocket admission is separate (`"/ws"`, `packages/ui-server/src/app.ts:1364`). +(`createHealthRoutes`, `packages/ui-server/src/app.ts:1107`), the API guard follows +public ceremonies (`authGuard`, `packages/ui-server/src/app.ts:1128`), and the +WebSocket admission is separate (`"/ws"`, `packages/ui-server/src/app.ts:1378`). Static serving is conditional (`if (options.staticRoot)`, -`packages/ui-server/src/app.ts:1384-1405`). That order establishes access; +`packages/ui-server/src/app.ts:1398-1419`). That order establishes access; it does not select compatibility status. A hermetic real-app launch, with temporary brain root, in-memory database, diff --git a/docs/decisions/journal-database.md b/docs/decisions/journal-database.md index 3d0f6bc01f..67a2ac912c 100644 --- a/docs/decisions/journal-database.md +++ b/docs/decisions/journal-database.md @@ -97,7 +97,7 @@ that no pre-charge covers. The evidence is on the issue. readers understand the arrays until then, and an empty legacy array stays "no set recorded". The brain's current set is the one the most recent complete, inventoried turn recorded - (`configurationCoverage(): ConfigurationCoverageRead`, `packages/ui-server/src/brain/turn-journal.ts:779-785`). + (`configurationCoverage(): ConfigurationCoverageRead`, `packages/ui-server/src/brain/turn-journal.ts:844-850`). The sets table is an ordinary rowid table, as every journal table is: the operational backup copies and compares journal rows in rowid order. diff --git a/docs/decisions/scheduled-tasks.md b/docs/decisions/scheduled-tasks.md index 0de2fee2e7..ef752abfb8 100644 --- a/docs/decisions/scheduled-tasks.md +++ b/docs/decisions/scheduled-tasks.md @@ -23,7 +23,7 @@ Source inspected at `b5c30c180df5584584f261b446c4d440380d2441`: (`else if (item.status === "scheduled"`, `packages/ui-server/src/inbox/actions.ts:196-197`). The runtime ticks every minute (`INBOX_TICK_MS`, `packages/ui-server/src/inbox/runtime.ts:11-13`). - Production app wiring supplies recovery and budgets, without a dispatcher - (`// Recovery/heartbeat only.`, `packages/ui-server/src/app.ts:592-608`). + (`// Recovery/heartbeat only.`, `packages/ui-server/src/app.ts:597-613`). A scripted nonempty ready-item test still reports no claim, attempt or Activity root. That proves disabled wiring, not safe execution of a schedule. - Headless plumbing checks backend support, a usable principal, lifetime and diff --git a/docs/decisions/session-principals.md b/docs/decisions/session-principals.md index 01ade27e3f..b4c90f5548 100644 --- a/docs/decisions/session-principals.md +++ b/docs/decisions/session-principals.md @@ -96,9 +96,9 @@ Both reviewers verified every row below against the source. | Cookie verify | `auth.ts:265-296` | strict `^(\d+)\.(\d+)$`, safe integers, future/expired rejection, `cookieEpoch === sessionsEpoch(db)` | | Global epoch | `auth.ts:302-318` | `settings` row; missing = 0; non-integer **throws** | | Global revoke | `auth.ts:321-330` | `setSetting` (overflow-guarded) + `clients.closeAll(1008, …)` | -| Auth routes | `authRoutes`, `app.ts:1108` | mounted **before** the guard at `authGuard(authMode`, `app.ts:1124`; logout guards itself (`resolveCookiePrincipal(c, auth, deps.db)`, `auth.ts:798`) | -| Passkey management | `passkeyManagementRoutes`, `app.ts:1132` | mounted **after** the guard ("Mount AFTER the auth guard") | -| WS guard | `"/ws"`, `app.ts:1364-1381` | origin → `isWsAuthorized` (returns a boolean, `auth.ts:221-237`) → capacity → upgrade | +| Auth routes | `authRoutes`, `app.ts:1113` | mounted **before** the guard at `authGuard(authMode`, `app.ts:1128`; logout guards itself (`resolveCookiePrincipal(c, auth, deps.db)`, `auth.ts:798`) | +| Passkey management | `passkeyManagementRoutes`, `app.ts:1137` | mounted **after** the guard ("Mount AFTER the auth guard") | +| WS guard | `"/ws"`, `app.ts:1378-1395` | origin → `isWsAuthorized` (returns a boolean, `auth.ts:221-237`) → capacity → upgrade | | WS upgrade | `ws/connection.ts:262-264` | `createWsUpgrade` ignores the request context | | WS admission | `ws/connection.ts:84` | `clients.add(ws)` — the socket's identity is unknown | | Turn record | `ws/run-session.ts:136-144` | recorder built from `{turnId, sessionId, billing}`; `RunningTurn` (`ws/turns.ts:55-77`) has no actor | diff --git a/docs/decisions/session-safety-reviews.md b/docs/decisions/session-safety-reviews.md index 58627d516b..c4e7adff74 100644 --- a/docs/decisions/session-safety-reviews.md +++ b/docs/decisions/session-safety-reviews.md @@ -219,6 +219,17 @@ and no fabricated agent turn. A human Settings operation has its own host audit identity and exact reviewed policy bytes/base hash. No personal accounts, configuration or real deployment details belong in the public tree. +The v1 repository selector keeps its stable repository ID and canonical owner +name. The independent provider owner ID is retained as host publication +evidence, preserving that policy format. A prepared metadata observation or +matching current file bytes cannot create an approved-owner boundary: the +operation's descriptor-bound write and directory sync precede the FULL durable +transaction that records its proof and owner identity together. Current boundary +facts survive bounded operation-receipt pruning, and removal or selector change +retires them. They establish the owner's historical reviewed choice, not current +repository identity, private access or runtime permission. Every later qualified +read still needs independently verified immutable provenance and fresh identity. + Source trust and recipient permission are distinct. Incoming trust never silently permits sending data while another trigger restricts the chat. Recipient permission defaults off and needs its own explicit review. Exact diff --git a/docs/http-api.md b/docs/http-api.md index 0490e30f89..8bb9812427 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 routes (whose `/api/settings/voice` also carries the live-service default) mounted by `createApp`: 191 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 safety-review, safety-recording recovery, GitHub detail-page, live-persona and markup-upload and human trust Settings routes (whose `/api/settings/voice` also carries the live-service default) mounted by `createApp`: 195 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,6 +158,10 @@ 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/: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. | | 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). | @@ -224,7 +228,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 191 declared endpoints are mounted regardless of backend, renderer or +All 195 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. @@ -2375,3 +2379,25 @@ current retained-checkpoint counts and bytes, plus `lastFailure`, a durable historical cause even when cleanup failed before the first turn. The historical record survives successful cleanup; current retained charges are reported separately. It is never part of public `/health`. + +## Human trust Settings publication + +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 +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; +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. +Removal/readback remain available for existing rules. Revision exhaustion refuses +before protected publication. No historical trigger is resolved by these routes. diff --git a/docs/integration-contract/package-api.md b/docs/integration-contract/package-api.md index cfdc823a44..3e829dc991 100644 --- a/docs/integration-contract/package-api.md +++ b/docs/integration-contract/package-api.md @@ -5579,6 +5579,89 @@ helpers remain on the existing brain-common internal governance-policy entry point and establish no new extension seam or runtime authority. No SDK safety 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 +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. +`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 +request/operation/review IDs and retains exact base/proposed UTF-8 policy text, +reviewed SHA-256 and a 15-minute expiry. A selector change requires remove/add. +Repository creates/edits use the concrete fixed host metadata path. Browser +stable IDs must match independently observed provider IDs. The review retains +`repositoryIdentity` (or null) and `includesFutureRepositories`; owner rules +explicitly include future repositories currently owned by that namespace. +Every commit obtains fresh metadata inside the journal observation window, +compares repository/owner IDs, canonical names and privacy with the reviewed +identity, and checks its exact selected grant/credential authority at the final +synchronous publication boundary. Unknown metadata, changed identity, missing +private grants and lost API recipient permission withhold publication. No agent +turn or generic relay is created. Existing repository rules can still be read +and removed when metadata is unavailable. + +Each metadata operation has a 30-second deadline and a 1 MiB charged-wire +allowance further bounded by the ordinary policy's egress byte limit. Host +allow/deny rules remain effective; public metadata stays anonymous. HTTP +cancellation ends that operation. The lookup establishes no incoming source +trust, general recipient permission or Git acquisition/write capability. + +`POST /api/trust-settings/commit` accepts only `{version:1,requestId,reviewId, +reviewedBytesHash}`; `GET /api/trust-settings/:request` only reads that caller's +receipt/review and current policy. Both mutation routes require a present exact +same-origin Origin and JSON, at most 65536 bytes, plus a live password-mode +password/passkey owner. Agent, ambient, voice and body-supplied identity/channel +fields supply no authority. Authority is checked after waits and at publication. + +Receipts bind principal/credential lifetime, served brain, operation, request, +exact base/topology and reviewed hash. Prepared state precedes any write; the +shared privileged publisher syncs staging bytes and the containing directory. +Only a FULL durable proof written after this operation's publication establishes +`publication:proved`. The same transaction retains a bounded current GitHub +owner-boundary fact tied to the operation, principal, authority, exact reviewed +bytes and selector. It survives bounded operation-receipt pruning, while rule +removal/target change retires it. Equal current policy bytes and prepared +metadata cannot create this evidence. It is historical publication evidence; +a future source-rule verifier must still qualify the actual read and fresh +current identity independently. The internal `repositoryApproval` reader is +host-only and grants no runtime capability. The original v1 selector format is +unchanged. A crash in writing/rename before that proof returns +`unknown`, even if current file bytes match. Retries with identical commit data +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. +`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. +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 +entering the synchronous approved write, and a failed lookup or a callback that +publishes nothing cannot grant user-policy attribution. A missing publication +callback cannot produce proof. +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 HTTP boundary admits at most 32 concurrent requests per principal and 256 +for the served brain, including lock waiters; excess requests return retryable +`busy` (503) before joining another wait and recover as earlier requests finish. +There are at most 32 outstanding reviews per principal, 256 per brain, 10000 +receipts and 16 MiB reserved payload/receipt storage. New requests fail at +capacity; live receipts are not evicted. Terminal receipts survive at least +24 hours. Unknown writes are never replayed, including after pruning. Settings +migration 080 has no dependency on occurrence-ledger migration 079/081+; +migration 094 adds the owner-boundary evidence without changing earlier applied +migrations. The +loader applies each unapplied filename in sorted order on every startup. ## Extraction classifier setting (additive, 0.45.0, #4088) The governance policy types reachable through ui-server's public signatures diff --git a/docs/integration-contract/wire.md b/docs/integration-contract/wire.md index 924af4b6af..f855f99514 100644 --- a/docs/integration-contract/wire.md +++ b/docs/integration-contract/wire.md @@ -55,7 +55,7 @@ reports the paths observed so far, a lower bound, and an empty partial reports summary retained before this field, or sent by an older server, omits it or reports `null`: the count is unknown, never zero, and a client names the `changedFiles` figure as recorded entries rather than files. The count is -(`const KEPT_CHANGE`, `packages/ui-server/src/brain/turn-journal.ts:54-57`). +(`const KEPT_CHANGE`, `packages/ui-server/src/brain/turn-journal.ts:55-58`). **Configuration coverage set (additive, #3257).** Untraced configuration inputs are a property of the brain's configuration, so the host stores each distinct diff --git a/docs/plans/async-collaboration-requirements.md b/docs/plans/async-collaboration-requirements.md index d49fa30511..63eb3dfda3 100644 --- a/docs/plans/async-collaboration-requirements.md +++ b/docs/plans/async-collaboration-requirements.md @@ -226,7 +226,7 @@ Stated before the requirements because five of them derive from it. that is the shape to copy, including its `close()` lifecycle. - R19. **The cron backstop has independent authorization before the general guard.** Mount it on the existing listener before - (`app.use("/api/*", authGuard(`, `packages/ui-server/src/app.ts:1123`). + (`app.use("/api/*", authGuard(`, `packages/ui-server/src/app.ts:1128`). Authorize a boot-minted ephemeral token, rotated each boot and stored in a 0600 runtime file, with the actual socket address as an additional check. Proxy headers cannot authorize it. The poke succeeds in every auth mode diff --git a/docs/plans/async-collaboration.md b/docs/plans/async-collaboration.md index 5cd82b5ed0..2925d2ac39 100644 --- a/docs/plans/async-collaboration.md +++ b/docs/plans/async-collaboration.md @@ -131,7 +131,7 @@ system gate. It is not a prerequisite to rebuild or a new independent package. owns manual triggers/history; it does not tick the inbox. - **Two connections:** (`export function createUiDb(`, `packages/ui-server/src/db/client.ts:28-45`) sets WAL, foreign keys and a 5-second busy timeout. Claims are immediate transactions. -- **Auth mounting:** (`app.use("/api/*", authGuard(`, `packages/ui-server/src/app.ts:1123`) follows public routes; +- **Auth mounting:** (`app.use("/api/*", authGuard(`, `packages/ui-server/src/app.ts:1128`) follows public routes; (`export function authGuard(`, `packages/ui-server/src/middleware/auth.ts:184-244`) binds principals in each auth mode. An internal poke needs independent token authorization before this guard. - **Permission parking:** (`const requestPermission`, `packages/ui-server/src/ws/bridge-capabilities/permissions.ts:19-188`). Timeout unwind is diff --git a/docs/plans/chat-history-deletion.md b/docs/plans/chat-history-deletion.md index c9b0e0195d..e1f61f8818 100644 --- a/docs/plans/chat-history-deletion.md +++ b/docs/plans/chat-history-deletion.md @@ -337,7 +337,7 @@ Preserve the existing bounded-wait ownership distinction during that drain. writers; rejection retains the original cleanup continuation, writer and reader until genuine settlement, rather than authorizing their replacement (`guardSqliteCleanup`, `packages/ui-server/src/db/write-worker.ts:206-234`; -`close: () => closing ??= guardSqliteCleanup`, `packages/ui-server/src/app.ts:1474-1524`). +`close: () => closing ??= guardSqliteCleanup`, `packages/ui-server/src/app.ts:1488-1538`). The native lease manager retains its own pending operations and durable unknown root outcomes through close (`return { client, writer, recoverDeadOwners`, `packages/ui-server/src/brain/native-brain-leases.ts:320-333`). A caller deadline diff --git a/docs/plans/reviewable-session-safety.md b/docs/plans/reviewable-session-safety.md index 89839a6541..5f57f1cc9e 100644 --- a/docs/plans/reviewable-session-safety.md +++ b/docs/plans/reviewable-session-safety.md @@ -50,7 +50,7 @@ public design or its fixtures. Fictional examples use the Odysseus world. (`GovernancePolicySchema`, `packages/common/src/governance-policy.ts:132-161`). The privileged proposal writer already provides exact-base review, descriptor-bound publication, authority rechecks and crash receipts - (`createPolicyProposals`, `packages/ui-server/src/brain/policy-proposal.ts:100-275`). + (`createPolicyProposals`, `packages/ui-server/src/brain/policy-proposal.ts:101-254`). - Private reference access already matches canonical repository prefixes and live principal grants; that is access authority, not content trust ([reference-source grants](../decisions/reference-source-grants.md)). Its diff --git a/packages/ui-server/migrations/080_trust_settings.sql b/packages/ui-server/migrations/080_trust_settings.sql new file mode 100644 index 0000000000..6ed2e894f7 --- /dev/null +++ b/packages/ui-server/migrations/080_trust_settings.sql @@ -0,0 +1,22 @@ +-- Independent of occurrence-ledger migrations 079 and 081+; no ledger objects. +CREATE TABLE trust_settings_operations ( + request_id TEXT PRIMARY KEY, + brain_id TEXT NOT NULL, + principal_id TEXT NOT NULL, + authority TEXT NOT NULL, + expires_at INTEGER NOT NULL, + retain_until INTEGER NOT NULL, + payload TEXT NOT NULL, + payload_bytes INTEGER NOT NULL, + stage TEXT NOT NULL, + proof TEXT, + receipt TEXT NOT NULL +); +CREATE INDEX trust_settings_owner ON trust_settings_operations(brain_id, principal_id); +CREATE TABLE trust_settings_projection ( + brain_id TEXT PRIMARY KEY, + revision TEXT NOT NULL, + rules TEXT NOT NULL, + policy_hash TEXT, + error TEXT +); diff --git a/packages/ui-server/migrations/094_trust_github_boundaries.sql b/packages/ui-server/migrations/094_trust_github_boundaries.sql new file mode 100644 index 0000000000..6928695180 --- /dev/null +++ b/packages/ui-server/migrations/094_trust_github_boundaries.sql @@ -0,0 +1,10 @@ +-- Current approved-owner evidence, derived only from a proved Settings +-- publication. It is never a second source of policy or runtime permission. +CREATE TABLE trust_settings_github_boundaries ( + brain_id TEXT NOT NULL, + rule_id TEXT NOT NULL, + selector TEXT NOT NULL, + identity TEXT NOT NULL, + proof TEXT NOT NULL, + PRIMARY KEY (brain_id, rule_id) +); diff --git a/packages/ui-server/src/app.ts b/packages/ui-server/src/app.ts index eca09a8ba6..0dba58ebf5 100644 --- a/packages/ui-server/src/app.ts +++ b/packages/ui-server/src/app.ts @@ -1,3 +1,6 @@ +import { createTrustSettings } from "./brain/trust-settings.js"; +import { createTrustSettingsRoutes } from "./routes/trust-settings.js"; +import { createTrustGitHubIdentity } from "./brain/trust-github-identity.js"; import { SafetyHistory } from "./governance/safety-history.js"; import { createSessionSafetyRoutes } from "./routes/session-safety.js"; import { createOwnerSafetyReviewRoutes } from "./routes/owner-safety-review.js"; @@ -542,8 +545,9 @@ export async function createApp(options: CreateAppOptions = {}): Promise referenceWorktreeDependents(db, rootId) }) : undefined; @@ -1330,6 +1334,15 @@ 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, + github: createTrustGitHubIdentity({ root: config.brainPath, access: githubReferenceAccess }), + authority: id => { + if (authMode !== "password") return null; + const p = resolvePrincipal(db, id); + return p?.kind === "owner" && ["password", "passkey"].includes(p.authMethod) && isUsablePrincipal(p, Date.now()) + ? JSON.stringify([p.id, p.authMethod, p.credentialId, p.createdAt, p.expiresAt]) : null; + }, observe: (id, publish) => journal.observeSettingsPolicy(id, publish) }); + 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. const apifyEdits = createApifyPolicyEdits({ root: config.brainPath, proposals: policyProposals, journal, authorized: apifyOwner }); diff --git a/packages/ui-server/src/brain/policy-proposal.ts b/packages/ui-server/src/brain/policy-proposal.ts index 640a3304a2..c149d7a02f 100644 --- a/packages/ui-server/src/brain/policy-proposal.ts +++ b/packages/ui-server/src/brain/policy-proposal.ts @@ -1,5 +1,6 @@ /** The only privileged policy writer. Worker input is never approval authority. */ -import { closeSync, constants, fchmodSync, fsyncSync, linkSync, openSync, realpathSync, renameSync, rmdirSync, unlinkSync, writeFileSync } from "node:fs"; +import { realpathSync, rmdirSync } from "node:fs"; +import { publishProtectedPolicy } from "./policy-publication.js"; import { createHash } from "node:crypto"; import type { SessionHistoryMessage } from "@schlessera/brain-ui-sdk/protocol"; import type { Database } from "bun:sqlite"; @@ -209,7 +210,7 @@ export function createPolicyProposals(options: { const currentValidation = validate(bytes); if (!currentValidation.ok || currentValidation.status !== "valid") throw new Refusal("invalid", `This proposal no longer passes validation: ${currentValidation.errors.join("; ")}. Nothing was written. A fresh proposal is required.`); const created: string[] = []; - let target: Target | undefined, temp: string | undefined, unpublished = false; + let target: Target | undefined, unpublished = false; try { target = open(root, review.baseHash === null, created); verify(target, review.baseHash); options.beforeCommit?.(); authority(); verify(target, review.baseHash); @@ -223,31 +224,10 @@ export function createPolicyProposals(options: { // The operation owns the staging inode for this synchronous // callback only. Both journal observations are outside its // lifetime; no path/prefix ignore can hide real worker files. - const staging = `/proc/self/fd/${target!.directories.at(-1)!.fd}/.brain-policy-${crypto.randomUUID()}`; - let publicationFailed = false, publicationError: unknown; - try { - const fd = openSync(staging, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW, target!.mode ?? 0o644); - temp = staging; // Only a successfully created inode belongs to this operation. - try { writeFileSync(fd, bytes); if (target!.mode !== undefined) fchmodSync(fd, target!.mode); fsyncSync(fd); } finally { closeSync(fd); } - if (held()) unpublished = true; - else { - authority(false); verify(target!, review.baseHash); - if (review.baseHash === null) linkSync(temp, target!.at); else renameSync(temp, target!.at); - committed = true; - } - } catch (error) { publicationFailed = true; publicationError = error; } - // First publication uses link rather than an overwriting - // rename; unlink its remaining name before observation. - if (temp) { - try { unlinkSync(temp); temp = undefined; } - catch (error) { - if ((error as NodeJS.ErrnoException).code === "ENOENT") temp = undefined; - else { if (!publicationFailed) publicationError = error; publicationFailed = true; } - } - } - if (publicationFailed) throw publicationError; - if (unpublished) return; - fsyncSync(target!.directories.at(-1)!.fd); + publishProtectedPolicy(target!, bytes, review.baseHash, () => { + if (held()) throw new AuthorityHeld(); + authority(false); verify(target!, review.baseHash); + }, () => { committed = true; }); }); // Nothing was published and the observation, its hold and (on // unwinding) the lock are released: wait out the pause and retry. @@ -255,7 +235,6 @@ export function createPolicyProposals(options: { review.state = "updated"; review.message = "Policy updated. Applies from the next turn."; await options.recordEvent(review, turn); } finally { - if (temp) { try { unlinkSync(temp); } catch { /* Rename consumed it. */ } } if (target) close(target); if (!committed) for (const directory of created.reverse()) { try { rmdirSync(directory); } catch { /* Preserve concurrent files. */ } } } diff --git a/packages/ui-server/src/brain/policy-publication.ts b/packages/ui-server/src/brain/policy-publication.ts new file mode 100644 index 0000000000..499f253c9b --- /dev/null +++ b/packages/ui-server/src/brain/policy-publication.ts @@ -0,0 +1,26 @@ +/** Shared descriptor-bound privileged file publisher. Callers own the brain lock, + * observation window and durable operation/turn identity. Never exported to workers. */ +import { closeSync, constants, fchmodSync, fsyncSync, linkSync, openSync, renameSync, unlinkSync, writeFileSync } from "node:fs"; +import { verifyGovernancePolicyAnchored, type AnchoredGovernancePolicy } from "@schlessera/brain-common/internal/governance-policy"; + +export function publishProtectedPolicy(target: AnchoredGovernancePolicy, bytes: Uint8Array, baseHash: string | null, + check: () => void, published: () => void): void { + let temp: string | undefined; + try { + check(); verifyGovernancePolicyAnchored(target, baseHash); + const staging = `/proc/self/fd/${target.directories.at(-1)!.fd}/.brain-policy-${crypto.randomUUID()}`; + const fd = openSync(staging, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW, target.mode ?? 0o644); + temp = staging; + try { writeFileSync(fd, bytes); if (target.mode !== undefined) fchmodSync(fd, target.mode); fsyncSync(fd); } + finally { closeSync(fd); } + // No await between the last authority/topology/base check and the atomic publication. + check(); verifyGovernancePolicyAnchored(target, baseHash); + if (baseHash === null) linkSync(temp, target.at); else renameSync(temp, target.at); + published(); + try { unlinkSync(temp); } catch (error) { if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error; } + temp = undefined; + // Include newly created ancestors: a durable name in the leaf alone does + // not make its parent names durable after a power loss. + for (const directory of [...target.directories].reverse()) fsyncSync(directory.fd); + } finally { if (temp) { try { unlinkSync(temp); } catch { /* Only our staging name. */ } } } +} diff --git a/packages/ui-server/src/brain/trust-github-identity.ts b/packages/ui-server/src/brain/trust-github-identity.ts new file mode 100644 index 0000000000..8abbecfeb6 --- /dev/null +++ b/packages/ui-server/src/brain/trust-github-identity.ts @@ -0,0 +1,59 @@ +/** Fixed host metadata for one human Settings operation, independent of an agent turn. */ +import type { TrustSelector } from "@schlessera/brain-common/internal/governance-policy"; +import { startEgressProxy } from "@schlessera/brain-ui-sdk/internal"; +import type { createGitHubReferenceAccess } from "./github-reference-access.js"; +import { createGovernancePolicyReader } from "./governance-policy.js"; +import { ReferenceTransportError } from "./reference-transport.js"; + +type GitHubSelector = Extract; +export interface TrustGitHubIdentity { + selector: GitHubSelector; + ownerId: string; + private: boolean | null; +} + +/** Identity data is retained with the reviewed bytes; the callback is host-only and ephemeral. */ +export function createTrustGitHubIdentity(options: { + root: string; + access: Pick, "owner" | "repository">; +}) { + const reader = createGovernancePolicyReader(options.root); + return { + async resolve(input: { principalId: string; selector: GitHubSelector; policyHash: string | null; + current(): boolean; signal?: AbortSignal }) { + const { principalId, current, signal, policyHash } = input, selector = structuredClone(input.selector); + const check = () => { + signal?.throwIfAborted(); + if (!current()) throw new ReferenceTransportError("denied", "The Settings owner operation ended."); + }; + check(); + const loaded = reader.load(); + if (loaded.errors.length || loaded.hash !== policyHash) throw new ReferenceTransportError("denied", "The reviewed policy base changed."); + // Metadata is a fixed read initiated by the human, outside any model + // conversation. Ordinary host allow/deny and byte controls still apply. + const maxBytes = Math.min(1048576, loaded.policy.egress.max_bytes_per_turn ?? 1048576); + const egress = await startEgressProxy({ mode: loaded.policy.egress.mode, allow: loaded.policy.egress.allow, + deny: loaded.policy.egress.deny, maxBytes, outwardHosts: [], signal, observe() {} }); + try { + check(); + const bounds = { principalId, egress, maxBytes, timeoutMs: 30000, current, signal }; + let identity: TrustGitHubIdentity, assertAuthority: () => void; + if (selector.kind === "github_owner") { + const observed = await options.access.owner({ ...bounds, owner: selector.owner }); + if (observed.ownerId !== selector.ownerId) throw new ReferenceTransportError("denied", "The requested owner identity differs from current metadata."); + identity = { selector, ownerId: observed.ownerId, private: null }; + assertAuthority = check; + } else { + // A selector already contains a canonical name: add the clone suffix + // exactly once so a literal repository suffix remains literal. + const observed = await options.access.repository({ ...bounds, repository: `https://github.com/${selector.owner}/${selector.repository}.git` }); + if (observed.repositoryId !== selector.repositoryId) throw new ReferenceTransportError("denied", "The requested repository identity differs from current metadata."); + identity = { selector, ownerId: observed.ownerId, private: observed.private }; + assertAuthority = () => { check(); observed.assertAuthority(); }; + } + assertAuthority(); + return { identity, networkBytes: maxBytes - egress.remainingBytes(), assertAuthority }; + } finally { egress.stop(); } + }, + }; +} diff --git a/packages/ui-server/src/brain/trust-settings-writes.ts b/packages/ui-server/src/brain/trust-settings-writes.ts new file mode 100644 index 0000000000..effd311c14 --- /dev/null +++ b/packages/ui-server/src/brain/trust-settings-writes.ts @@ -0,0 +1,44 @@ +/** FULL write-worker commits for Settings identities and operation-bound publication proofs. */ +import type { Database } from "bun:sqlite"; +import type { WriteProcedures } from "../db/write-worker.js"; +export const url = import.meta.url; +export function setup(db: Database): WriteProcedures { + return { + insert(row: { requestId: string; brainId: string; principalId: string; authority: string; expires: number; retain: number; payload: string; receipt: string }, now: number) { + return db.transaction(() => { + db.query("DELETE FROM trust_settings_operations WHERE retain_until < ?").run(now); + const total = db.query("SELECT count(*) n, coalesce(sum(payload_bytes + 16384),0) bytes FROM trust_settings_operations").get() as { n: number; bytes: number }; + const pending = db.query("SELECT count(*) n, coalesce(sum(principal_id = ?),0) own FROM trust_settings_operations WHERE brain_id = ? AND stage = 'prepared' AND expires_at >= ?").get(row.principalId, row.brainId, now) as { n: number; own: number }; + // Reserve terminal/proof capacity for every admitted request, never evict live receipts. + if (total.n >= 10000 || total.bytes + Buffer.byteLength(row.payload) + 16384 > 16777216 || pending.n >= 256 || pending.own >= 32) return "capacity"; + db.query("INSERT INTO trust_settings_operations VALUES (?,?,?,?,?,?,?,?,? ,NULL,?)").run(row.requestId, row.brainId, row.principalId, row.authority, row.expires, row.retain, row.payload, Buffer.byteLength(row.payload), "prepared", row.receipt); + return "prepared"; + }).immediate(); + }, + stage(id: string, stage: string, receipt: string, proof: string | null, now: number, + boundary?: { brain: string; ruleId: string; selector: string; identity: string }) { + return db.transaction(() => { + db.query("UPDATE trust_settings_operations SET stage=?, receipt=?, proof=coalesce(?,proof), retain_until=max(retain_until,?) WHERE request_id=?").run(stage, receipt, proof, now + 86400000, id); + if (boundary) { + if (stage !== "file_published" || !proof) throw new Error("A GitHub boundary requires this operation's durable publication proof"); + db.query(`INSERT INTO trust_settings_github_boundaries VALUES (?,?,?,?,?) + ON CONFLICT(brain_id,rule_id) DO UPDATE SET selector=excluded.selector,identity=excluded.identity,proof=excluded.proof`) + .run(boundary.brain, boundary.ruleId, boundary.selector, boundary.identity, proof); + } + }).immediate(); + }, + 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); + // At most one retained boundary per current rule; equal file bytes + // alone never create one. Invalid policy retains last-valid facts. + if (!error) { + const current = new Map((JSON.parse(rules) as { id: string; selector: unknown }[]).map(rule => [rule.id, JSON.stringify(rule.selector)])); + const boundaries = db.query("SELECT rule_id,selector FROM trust_settings_github_boundaries WHERE brain_id=?").all(brain) as { rule_id: string; selector: string }[]; + 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); + } + }).immediate(); + }, + }; +} diff --git a/packages/ui-server/src/brain/trust-settings.ts b/packages/ui-server/src/brain/trust-settings.ts new file mode 100644 index 0000000000..00bbcf2e25 --- /dev/null +++ b/packages/ui-server/src/brain/trust-settings.ts @@ -0,0 +1,286 @@ +/** 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"; +import { lstatSync, realpathSync, rmdirSync } from "node:fs"; +import { resolve, join } from "node:path"; +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"; +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"; +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"); +const digest = z.string().regex(/^[a-f0-9]{64}$/u); +const MAX_TRUST_REVISION = 18446744073709551615n; +const revision = z.string().regex(/^(0|[1-9][0-9]{0,19})$/u) + .refine(value => /^(0|[1-9][0-9]{0,19})$/u.test(value) && BigInt(value) <= MAX_TRUST_REVISION, "Revision exhausted"); +const ruleId = z.string().regex(/^[A-Za-z0-9_-]{1,128}$/u); +const TrustPrepareSchema = z.strictObject({ version: z.literal(1), expectedTrustRevision: revision, + expectedPolicyHash: digest.nullable(), change: z.discriminatedUnion("action", [ + z.strictObject({ action: z.literal("create"), rule: TrustRuleSchema }), + z.strictObject({ action: z.literal("edit"), rule: TrustRuleSchema }), + z.strictObject({ action: z.literal("remove"), ruleId }), + ]) }); +const TrustCommitSchema = z.strictObject({ version: z.literal(1), requestId: ruleId, reviewId: ruleId, reviewedBytesHash: digest }); +type Prepare = z.output; +type Commit = z.output; +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 { + 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; +} +interface Payload { input: Prepare; reviewId: string; proposed: string; proposedHash: string; base: string | null; topology: string; rule: TrustRule | null; githubIdentity?: TrustGitHubIdentity } +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 }); + if (!stat) return null; + if (i < 3 && !stat.isDirectory()) throw new TrustSettingsError("stale_base"); + return i < 3 ? [stat.dev, stat.ino] : [stat.dev, stat.ino, stat.ctimeMs]; +}); +const matchesTopology = (root: string, expected: string, created: boolean) => { + const a = JSON.parse(expected) as unknown[], b = topology(root); + return a.every((entry, i) => created && i < 3 && entry === null || JSON.stringify(entry) === JSON.stringify(b[i])); +}; +/** Only the taint block changes. Parse-back equality refuses aliases, merge keys + * or exotic layouts that would alter any unrelated setting. Review shows exact bytes. */ +function edit(text: string | null, rules: TrustRule[]): string { + const before = text ?? "---\nschema_version: 1\n---\n"; + const m = /^(\uFEFF?---[ \t]*\r?\n)([\s\S]*?\r?\n)?((?:---|\.\.\.)[ \t]*(?:\r?\n|$))/u.exec(before); + if (!m) throw new TrustSettingsError("unsupported_layout"); + const data = parseFrontmatter(before, { dataOnly: true }).data; + const taint = { ...data.taint, trusted_sources: rules }; + const lines = (m[2] ?? "").split(/\r?\n/u); if (lines.at(-1) === "") lines.pop(); + const start = lines.findIndex(line => /^taint[ \t]*:/u.test(line)); + const block = `taint: ${JSON.stringify(taint)}`; + if (start < 0) lines.push(block); + else { let end = start + 1; while (end < lines.length && !/^[^\s#]/u.test(lines[end]!)) end++; + while (end > start + 1 && /^\s*(?:#.*)?$/u.test(lines[end - 1]!)) end--; + lines.splice(start, end - start, block); } + const newline = before.includes("\r\n") ? "\r\n" : "\n"; + const after = m[1] + lines.join(newline) + newline + m[3] + before.slice(m[0].length); + const expected = { ...data, taint }; + if (JSON.stringify(parseFrontmatter(after, { dataOnly: true }).data) !== JSON.stringify(expected) || !parseGovernancePolicy(Buffer.from(after)).ok) + throw new TrustSettingsError("unsupported_layout"); + return after; +} +export function createTrustSettings(options: { + root: string; db: Database; writer?: SqliteWriter; lock: Pick; + /** Null unless the current password-mode human principal remains usable. The + * 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; + github?: ReturnType; + now?: () => number; + /** Host-only deterministic crash/race injection, never wired from HTTP. */ + checkpoint?(stage: string): void | Promise; +}) { + let root: string; + 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" }; + 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 refresh = async (): Promise => { + const old = projection(); let target: AnchoredGovernancePolicy | undefined; + let rules: TrustRule[], policyHash: string | null; + try { + target = openGovernancePolicyAnchored(root); + 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 ?? []; + } 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" }; } + } finally { target?.close(); } + 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 row = (principal: string, request: string): Row => { + authority(principal); + const r = options.db.query("SELECT * FROM trust_settings_operations WHERE request_id=? AND brain_id=? AND principal_id=?").get(request, brain, principal) as Row | null; + if (!r || r.retain_until < now()) throw new TrustSettingsError("unavailable", 404); + authority(principal, r.authority); return r; + }; + const current = (receipt: Receipt, payload: Payload, p: Projection): Receipt => { + 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 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 { + /** 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); }, + /** Historical host publication evidence, not a current identity or source-trust grant. */ + async repositoryApproval(ruleId: string) { return options.lock.withLock(BRAIN_LOCK_KEY, async () => { + const p = await refresh(); + if (p.error) return null; + const rule = p.rules.find(value => value.id === ruleId); + if (!rule || (rule.selector.kind !== "github_owner" && rule.selector.kind !== "github_repository")) return null; + 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 }; }, + read, + async prepare(principal: string, raw: unknown, signal?: AbortSignal) { + 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. + // Removal remains possible even while repository qualification is unavailable. + if (input.change.action !== "remove" && input.change.rule.selector.kind.startsWith("github_") && !options.github) throw new TrustSettingsError("repository_identity_unavailable", 503); + const request = await options.lock.withLock(BRAIN_LOCK_KEY, async () => { + authority(principal, auth); const p = await refresh(); authority(principal, auth); + if (p.error) throw new TrustSettingsError("unavailable", 503); + if (BigInt(p.revision) >= MAX_TRUST_REVISION) throw new TrustSettingsError("capacity", 503); + if (p.revision !== input.expectedTrustRevision) throw new TrustSettingsError("stale_revision"); + if (p.policyHash !== input.expectedPolicyHash) throw new TrustSettingsError("stale_base"); + const change = input.change, ruleId = change.action === "remove" ? change.ruleId : change.rule.id; + const existing = p.rules.find(rule => rule.id === ruleId); + if ((change.action === "create") === !!existing) throw new TrustSettingsError("request_conflict"); + if (change.action === "edit" && JSON.stringify(existing!.selector) !== JSON.stringify(change.rule.selector)) throw new TrustSettingsError("target_requires_remove_add"); + if (change.action === "edit" && JSON.stringify(existing) === JSON.stringify(change.rule)) throw new TrustSettingsError("request_conflict"); + const rules = TrustedSourcesSchema.parse(change.action === "create" ? [...p.rules, change.rule] : change.action === "remove" ? p.rules.filter(r => r.id !== ruleId) : p.rules.map(r => r.id === ruleId ? change.rule : r)); + let target: AnchoredGovernancePolicy | undefined; let base: string | null = null; const identity = JSON.stringify(topology(root)); + try { target = openGovernancePolicyAnchored(root); verifyGovernancePolicyAnchored(target, p.policyHash); base = target.bytes?.toString("utf8") ?? null; } + catch (error) { if ((error as NodeJS.ErrnoException).code !== "ENOENT" || p.policyHash !== null) throw error; } + finally { target?.close(); } + const proposed = edit(base, rules), requestId = id(), operationId = id(); + let githubIdentity: TrustGitHubIdentity | undefined; + if (change.action !== "remove" && (change.rule.selector.kind === "github_repository" || change.rule.selector.kind === "github_owner")) { + try { + const observed = await options.github!.resolve({ principalId: principal, selector: change.rule.selector, policyHash: p.policyHash, signal, + current: () => options.authority(principal) === auth }); + authority(principal, auth); observed.assertAuthority(); githubIdentity = observed.identity; + } catch { throw new TrustSettingsError("repository_identity_unavailable", 503); } + } + 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 } : {}) }; + 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, + payload: JSON.stringify(payload), receipt: JSON.stringify(receipt) }, now()); + if (inserted === "capacity") throw new TrustSettingsError("capacity", 503); + await options.checkpoint?.("prepared"); return requestId; + }); + return read(principal, request); + }, + async commit(principal: string, raw: unknown, signal?: AbortSignal) { + 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 (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"); + const receipt = JSON.parse(r.receipt) as Receipt; + let published = false, proved = false, publicationOpen = true; + const created: string[] = []; let target: AnchoredGovernancePolicy | undefined; + const save = (stage: string, proof: string | null = null, + boundary?: { brain: string; ruleId: string; selector: string; identity: string }) => + call("stage", input.requestId, stage, JSON.stringify(receipt), proof, now(), boundary); + try { + const p = await refresh(); row(principal, input.requestId); + if (p.error || p.revision !== payload.input.expectedTrustRevision) throw new TrustSettingsError("stale_revision"); + if (p.policyHash !== payload.input.expectedPolicyHash) throw new TrustSettingsError("stale_base"); + if (BigInt(p.revision) >= MAX_TRUST_REVISION) throw new TrustSettingsError("capacity", 503); + await save("writing"); await options.checkpoint?.("writing"); + if (!matchesTopology(root, payload.topology, false)) throw new TrustSettingsError("stale_base"); + target = openGovernancePolicyAnchored(root, { create: p.policyHash === null, created }); + let identityAuthority: (() => void) | undefined; + const check = () => { signal?.throwIfAborted(); + if (!publicationOpen) throw new TrustSettingsError("publication_failed"); + 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); }; + let publication: Promise | undefined; + await options.observe(receipt.operationId, (publish = async write => { write(); }) => { + if (publication || !publicationOpen) throw new TrustSettingsError("request_conflict"); + publication = (async () => { + // The journal's own queue/observation waits precede the fresh + // metadata read. Journal attribution then checkpoints intervening + // edits before the synchronous authority/publication fence. + if (payload.rule && (payload.rule.selector.kind === "github_repository" || payload.rule.selector.kind === "github_owner")) { + if (!payload.githubIdentity || !options.github) throw new TrustSettingsError("repository_identity_unavailable", 503); + const observed = await options.github.resolve({ principalId: principal, selector: payload.rule.selector, policyHash: p.policyHash, signal, + current: () => publicationOpen && options.authority(principal) === r.authority && r.expires_at >= now() }); + if (JSON.stringify(observed.identity) !== JSON.stringify(payload.githubIdentity)) throw new TrustSettingsError("repository_identity_changed"); + identityAuthority = observed.assertAuthority; + } + await publish(() => { + identityAuthority?.(); + publishProtectedPolicy(target!, Buffer.from(payload.proposed), p.policyHash, check, () => { published = true; }); + }); + })(); + // Preserve a rejected callback even if an older host observer + // forgets to await it; this invocation still joins it below. + void publication.catch(() => {}); + return publication; + }); + if (!publication) throw new TrustSettingsError("publication_failed"); + await publication; + if (!published) throw new TrustSettingsError("publication_failed"); + await options.checkpoint?.("renamed"); + // The proof is written only after THIS invocation's atomic publication + // and directory fsync, never inferred by comparing current bytes. + 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, + 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"; + await save("committed"); await options.checkpoint?.("committed"); + } catch (error) { + publicationOpen = false; + receipt.stage = proved ? "partial" : published ? "unknown" : "refused"; + receipt.publication = proved ? "proved" : published ? "unknown" : "not_published"; + receipt.reason = error instanceof TrustSettingsError ? error.code : error instanceof ReferenceTransportError && !published + ? "repository_identity_unavailable" : published ? "recording_failed" : "publication_failed"; + await save(receipt.stage); + } finally { publicationOpen = false; target?.close(); if (!published) for (const path of created.reverse()) { try { rmdirSync(path); } catch { /* Concurrent content remains. */ } } } + }); + return read(principal, input.requestId); + }, + }; +} +export type TrustSettings = ReturnType; diff --git a/packages/ui-server/src/brain/turn-journal.ts b/packages/ui-server/src/brain/turn-journal.ts index 20174a2f3a..6342fb7640 100644 --- a/packages/ui-server/src/brain/turn-journal.ts +++ b/packages/ui-server/src/brain/turn-journal.ts @@ -672,12 +672,40 @@ export function createTurnJournal(db: Database, options: TurnJournalOptions) { const turn=active.get(turnId); if(!turn)throw new JournalStorageUnavailable("history coverage requires an active observation window"); turn.policy.cover(paths); }, + /** Host Settings audit identity is retained by its durable operation store. + * Observe user policy changes across existing turns without minting a turn. */ + observeSettingsPolicy(_operationId: string, operation: (publish?: (write: () => void) => Promise) => void | Promise): Promise { return held(async () => { + await observe(); + let open = true, publication: Promise | undefined; + try { + await operation(write => { + if (!open || publication) throw new JournalStorageUnavailable("Settings publication window is no longer available"); + publication = (async () => { + // Metadata waits are not approved writes. Attribute their changes + // before entering the synchronous descriptor publication boundary. + await observe(); + if (!open) throw new JournalStorageUnavailable("Settings publication window ended"); + let completed = false; + try { write(); completed = true; } + finally { await observe(completed); } + })(); + void publication.catch(() => {}); + return publication; + }); + await publication; + } finally { + open = false; + await publication?.catch(() => {}); + await observe(); + } + }); }, /** The caller retains approval/current-principal authority; this never revives a completed turn. */ - observeUserPolicy(turnId: string, approvedWrite: () => void | Promise): Promise { return held(async () => { + observeUserPolicy(turnId: string, approvedWrite: () => void): Promise { return held(async () => { if (!active.has(turnId) || summary(turnId).state !== "recording") throw new JournalStorageUnavailable("approved policy write requires an active complete observation window"); await observe(); if (summary(turnId).state !== "recording") throw new JournalStorageUnavailable("policy observation became incomplete before the approved write"); - try { await approvedWrite(); } finally { await observe(true); } + let completed = false; + try { approvedWrite(); completed = true; } finally { await observe(completed); } }); }, finish(turnId: string) { return held(async timing => { if (!active.has(turnId)) { if (failedAdmissions.has(turnId)) await finalizeRefusedAdmission(turnId); return; } diff --git a/packages/ui-server/src/routes/trust-settings.ts b/packages/ui-server/src/routes/trust-settings.ts new file mode 100644 index 0000000000..5c52ed3b23 --- /dev/null +++ b/packages/ui-server/src/routes/trust-settings.ts @@ -0,0 +1,40 @@ +/** Password-owner browser boundary; no model, voice or body-supplied authority. */ +import { Hono } from "hono"; +import { ZodError } from "zod"; +import type { AppEnv } from "../app-env.js"; +import { requireJson } from "../middleware/origin.js"; +import { readJsonBody } from "../middleware/body-limit.js"; +import { TrustSettingsError, type TrustSettings } from "../brain/trust-settings.js"; +export function createTrustSettingsRoutes(deps: { settings: TrustSettings; trustProxy: boolean }) { + const routes = new Hono(); + const active = new Map(); let total = 0; + 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") { + // Require the actual Origin, independent of spoofed fetch metadata and + // the broader legacy API allowlist. Reverse-proxy TLS uses trusted proto. + let expected: string; + try { + const proto = deps.trustProxy ? c.req.header("x-forwarded-proto")?.split(",")[0]?.trim() : undefined; + expected = new URL(`${proto ? `${proto}:` : new URL(c.req.url).protocol}//${c.req.header("host") ?? new URL(c.req.url).host}`).origin; + } catch { return c.json({ code: "unauthorized", reason: "Same-origin request required", retryable: false }, 403); } + if (c.req.header("origin") !== expected) return c.json({ code: "unauthorized", reason: "Same-origin request required", retryable: false }, 403); + } + const principal = c.get("principal")!.id, count = active.get(principal) ?? 0; + if (count >= 32 || total >= 256) return c.json({ code: "busy", reason: "Too many Settings requests are active. Try again when one finishes.", retryable: true }, 503); + active.set(principal, count + 1); total++; + try { await next(); } + finally { total--; const remaining = active.get(principal)! - 1; if (remaining) active.set(principal, remaining); else active.delete(principal); } + }); + routes.onError((error, c) => error instanceof TrustSettingsError ? c.json({ code: error.code, reason: error.message, retryable: false }, error.status) + : error instanceof ZodError ? c.json({ code: "request_conflict", reason: "Invalid request", retryable: false }, 400) + : c.json({ code: "unavailable", reason: "Settings unavailable", retryable: false }, 503)); + routes.get("/trust-settings", async c => c.json(await deps.settings.list(c.get("principal")!.id))); + routes.get("/trust-settings/:request", async c => c.json(await deps.settings.read(c.get("principal")!.id, c.req.param("request")))); + for (const action of ["prepare", "commit"] as const) routes.post(`/trust-settings/${action}`, requireJson(), async c => { + const body = await readJsonBody(c, 65536).catch(() => null); if (body instanceof Response) return body; + return c.json(await deps.settings[action](c.get("principal")!.id, body, c.req.raw.signal)); + }); + return routes; +} diff --git a/packages/ui-server/tests/fixtures/trust-settings-crash.ts b/packages/ui-server/tests/fixtures/trust-settings-crash.ts new file mode 100644 index 0000000000..36e6eb0dbd --- /dev/null +++ b/packages/ui-server/tests/fixtures/trust-settings-crash.ts @@ -0,0 +1,24 @@ +/** Process-death fixture: durable worker writes, real descriptors and publication. */ +import { join } from "node:path"; +import { createUiDb } from "../../src/db/client.js"; +import { openSqliteWriter } from "../../src/db/write-worker.js"; +import { createTrustSettings } from "../../src/brain/trust-settings.js"; +import { createKeyedLock } from "@schlessera/brain-ui-sdk/server"; +import { connect } from "node:net"; +import { createGitHubReferenceAccess } from "../../src/brain/github-reference-access.js"; +import { createTrustGitHubIdentity } from "../../src/brain/trust-github-identity.js"; +const [root, at, request] = process.argv.slice(2) as [string, string, string]; +const db = createUiDb(join(root, "ui.db")), writer = openSqliteWriter(db); +const fixtureFile = Bun.file(join(root, "github-fixture.json")); +const metadata = await fixtureFile.exists() ? await fixtureFile.json() as { principalId: string; port: number; ca: string } : null; +const github = metadata ? createTrustGitHubIdentity({ root, access: createGitHubReferenceAccess({ db, brain: "ithaca-brain", + credentials: {}, transport: { async resolve() { throw new Error("No Git in Settings"); }, async fetch() { throw new Error("No Git in Settings"); }, async checkout() { throw new Error("No Git in Settings"); } }, + wireTransport: { ca: await Bun.file(metadata.ca).text(), lookup: async () => [{ address: "93.184.216.34", family: 4 }], + connect: (() => connect({ host: "127.0.0.1", port: metadata.port })) as typeof connect } }) }) : undefined; +const settings = createTrustSettings({ root, db, writer, lock: createKeyedLock(), authority: () => "owner-epoch", + ...(github ? { github } : {}), + observe: async (_id, publish) => publish(), checkpoint: stage => { if (stage === at) process.exit(77); } }); +const review = JSON.parse(await Bun.file(join(root, "request.json")).text()); +if (at === "prepared") await settings.prepare(metadata?.principalId ?? "odysseus", review.input); +else await settings.commit(metadata?.principalId ?? "odysseus", { version: 1, requestId: request, reviewId: review.reviewId, reviewedBytesHash: review.reviewedBytesHash }); +await writer.close(); db.close(); diff --git a/packages/ui-server/tests/http-inventory.test.ts b/packages/ui-server/tests/http-inventory.test.ts index c1d2df1af0..e286c8f12d 100644 --- a/packages/ui-server/tests/http-inventory.test.ts +++ b/packages/ui-server/tests/http-inventory.test.ts @@ -20,7 +20,7 @@ test("real app method/path inventory equals the complete classified HTTP specifi expect(proseCounts).toEqual([declared.length, declared.length]); } const middleware = [...new Set(t.routes.filter((r) => r.method === "ALL").map((r) => r.path))].sort(); - expect(middleware).toEqual(["/*", "/api/*", "/api/apify*", "/api/auth/passkey/*", "/api/auth/principals/*", "/api/brain/briefing", "/api/brain/list", "/api/brain/search", "/api/brain/stats", "/api/brain/stats/history", "/api/graph/*", "/api/internal/inbox/poke", "/api/sessions/:id/safety/reviews/*", "/api/sessions/:sessionId/turns/:turnId/revert*", "/api/storage*", "/api/storage/maintenance*", "/api/storage/removals*"]); + expect(middleware).toEqual(["/*", "/api/*", "/api/apify*", "/api/auth/passkey/*", "/api/auth/principals/*", "/api/brain/briefing", "/api/brain/list", "/api/brain/search", "/api/brain/stats", "/api/brain/stats/history", "/api/graph/*", "/api/internal/inbox/poke", "/api/sessions/:id/safety/reviews/*", "/api/sessions/:sessionId/turns/:turnId/revert*", "/api/storage*", "/api/storage/maintenance*", "/api/storage/removals*", "/api/trust-settings*"]); expect(t.routes.filter((r) => r.method === "ALL" && r.path === "/*")).toHaveLength(staticRoot ? 3 : 2); expect(t.routes.some((r) => r.method === "HEAD" || r.method === "OPTIONS")).toBe(false); } finally { await t.close(); } diff --git a/packages/ui-server/tests/trust-settings.test.ts b/packages/ui-server/tests/trust-settings.test.ts new file mode 100644 index 0000000000..b531899344 --- /dev/null +++ b/packages/ui-server/tests/trust-settings.test.ts @@ -0,0 +1,437 @@ +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 { mkdtempSync, mkdirSync, readFileSync, writeFileSync, rmSync, renameSync, symlinkSync, openSync, closeSync, constants } from "node:fs"; +import { join } from "node:path"; +import { createHash } from "node:crypto"; +import { Hono } from "hono"; +import { createKeyedLock, BRAIN_LOCK_KEY } from "@schlessera/brain-ui-sdk/server"; +import { createTrustSettings } from "../src/brain/trust-settings.js"; +import { createTrustSettingsRoutes } from "../src/routes/trust-settings.js"; +import { createUiDb } from "../src/db/client.js"; +import { openSqliteWriter } from "../src/db/write-worker.js"; +import { authGuard, authRoutes, type AuthRuntime } from "../src/middleware/auth.js"; +import { resolveServerConfig } from "../src/config/env.js"; +import { resolvePrincipal, isUsablePrincipal } from "../src/db/principals.js"; +import type { AppEnv } from "../src/app-env.js"; +import { connect } from "node:net"; +import { fixtureTls } from "./fixtures/fixture-tls.js"; +import { createGitHubReferenceAccess } from "../src/brain/github-reference-access.js"; +import { createTrustGitHubIdentity } from "../src/brain/trust-github-identity.js"; +import { createPrincipal, revokePrincipal } from "../src/db/principals.js"; +import { createReferenceGrant, revokeReferenceGrant } from "../src/db/reference-grants.js"; +const cleanup: (() => void | Promise)[] = []; +afterEach(async () => { for (const f of cleanup.splice(0).reverse()) await f(); }); +const initial = "---\nschema_version: 1\n# Keep ordinary configuration\nprofiles: {interactive: governed}\nbudgets: {turn: {block_usd: 17}}\n---\nThe voyage policy.\n"; +const rule = { id: "ithaca", label: "Ithaca", incomingContent: true, recipientWhileRestricted: false, + selector: { kind: "web_origin" as const, scheme: "https" as const, host: "example.org", port: 443 } }; +const hash = (text: string) => createHash("sha256").update(text).digest("hex"); +async function fixture(patch: Partial[0]> = {}) { + const scratch = join(import.meta.dir, "../../../tmp/trust-settings-tests"); mkdirSync(scratch, { recursive: true }); + const root = mkdtempSync(join(scratch, "case-")); cleanup.push(() => rmSync(root, { recursive: true, force: true })); + mkdirSync(join(root, "context/policies"), { recursive: true }); const path = join(root, "context/policies/governance.md"); writeFileSync(path, initial); + const db = createUiDb(join(root, "ui.db")), writer = openSqliteWriter(db); cleanup.push(async () => { await writer.close(); db.close(); }); + const lock = createKeyedLock(); let auth: string | null = "owner-epoch"; const observations: string[] = []; + const options = { root, db, writer, lock, authority: (id: string) => id === "odysseus" ? auth : null, + observe: async (id: string, publish: () => void | Promise) => { observations.push(id); await publish(); }, ...patch }; + const settings = createTrustSettings(options); + const prepare = async (change: unknown = { action: "create", rule }) => { const p = await settings.list("odysseus"); + return settings.prepare("odysseus", { version: 1, expectedTrustRevision: p.revision, expectedPolicyHash: p.policyHash, change }); }; + const commit = (p: Awaited>, change = {}) => settings.commit("odysseus", { version: 1, requestId: p.receipt.requestId, + reviewId: p.review.reviewId, reviewedBytesHash: p.review.reviewedBytesHash, ...change }); + return { root, path, db, writer, lock, settings, options, prepare, commit, observations, revoke: () => { auth = null; } }; +} +test("real descriptor CRUD is exact, durable and creates no agent turn; readback reflects another device removal", async () => { + const f = await fixture(), draft = await f.prepare(); + expect(draft.review.base).toBe(initial); expect(draft.review.proposed).toContain("# Keep ordinary configuration"); + const saved = await f.commit(draft); expect(saved.receipt.publication).toBe("proved"); expect(saved.receipt.enforcement).toBe("unavailable"); + expect(saved.receipt.currentRule).toBe("present"); expect(readFileSync(f.path, "utf8")).toBe(draft.review.proposed); + const edit = await f.prepare({ action: "edit", rule: { ...rule, label: "The home harbor", recipientWhileRestricted: true } }); await f.commit(edit); + expect((await f.settings.list("odysseus")).origins[0]!.recipientWhileRestricted).toBe(true); + const remove = await f.prepare({ action: "remove", ruleId: rule.id }); await f.commit(remove); + expect((await f.settings.read("odysseus", draft.receipt.requestId)).receipt.currentRule).toBe("removed"); + expect((await f.commit(draft)).receipt.currentRule).toBe("removed"); expect(f.observations).toHaveLength(3); + expect(f.db.query("SELECT count(*) n FROM sessions").get()).toEqual({ n: 0 }); + expect(f.db.query("SELECT count(*) n FROM policy_proposals").get()).toEqual({ n: 0 }); + expect((await f.settings.list("odysseus")).capabilities.repositoryRules).toBe(false); +}); +for (const stage of ["writing", "file_published"]) test(`readback waiting on a ${stage} commit returns its completed durable receipt`, async () => { + let ready!: () => void, release!: () => void; + const reached = new Promise(resolve => { ready = resolve; }), held = new Promise(resolve => { release = resolve; }); + const f = await fixture({ checkpoint: async value => { if (value === stage) { ready(); await held; } } }), draft = await f.prepare(); + const pendingCommit = f.commit(draft); + try { + await reached; + const pendingRead = f.settings.read("odysseus", draft.receipt.requestId); + release(); + const [read, committed] = await Promise.all([pendingRead, pendingCommit]); + expect(read.receipt, "SETTINGS_READ_AFTER_LOCK_USES_COMPLETED_DURABLE_RECEIPT").toEqual(committed.receipt); + expect(read.receipt.publication).toBe("proved"); + } finally { release(); await pendingCommit.catch(() => {}); } +}); + +test("changed request, foreign principal, arbitrary handles and expired reviews cannot replay", async () => { + let now = 1000; const f = await fixture({ now: () => now }), draft = await f.prepare(); + await expect(f.commit(draft, { reviewedBytesHash: "a".repeat(64) })).rejects.toThrow("request_conflict"); + await expect(f.settings.read("telemachus", draft.receipt.requestId)).rejects.toThrow("unauthorized"); + await expect(f.commit(draft, { requestId: "forged" })).rejects.toThrow("unavailable"); + now += 900001; await expect(f.commit(draft)).rejects.toThrow("request_expired"); + expect((await f.settings.read("odysseus", draft.receipt.requestId)).review.proposed).toBe(draft.review.proposed); + expect(readFileSync(f.path, "utf8")).toBe(initial); +}); +for (const race of ["bytes", "symlink", "ancestor", "inode", "revoke"] as const) test(`last publication check refuses ${race} after an async observation wait`, async () => { + let mutate = () => {}; const f = await fixture({ observe: async (_id, publish) => { await Promise.resolve(); mutate(); publish(); } }); + const draft = await f.prepare(); let held: number | undefined; + mutate = () => { + if (race === "revoke") f.revoke(); + else if (race === "bytes") writeFileSync(f.path, initial + "Other tab.\n"); + else if (race === "ancestor") { renameSync(join(f.root, "context"), join(f.root, "previous")); symlinkSync(join(f.root, "previous"), join(f.root, "context")); } + else { held = openSync(f.path, constants.O_RDONLY); renameSync(f.path, join(f.root, "previous.md")); + if (race === "symlink") symlinkSync(join(f.root, "previous.md"), f.path); else writeFileSync(f.path, initial); } + }; + try { const result = race === "revoke" ? await f.commit(draft).catch(e => e) : await f.commit(draft); + if (race !== "revoke") expect(result.receipt.publication).toBe("not_published"); + else expect(result.message).toBe("unauthorized"); + expect(readFileSync(f.path, "utf8")).toBe(race === "bytes" ? initial + "Other tab.\n" : initial); + } finally { if (held !== undefined) closeSync(held); } +}); +test("lock waits recheck authority and base; competing drafts retain exact diffs", async () => { + const f = await fixture(), a = await f.prepare(), b = await f.prepare({ action: "create", rule: { ...rule, id: "troy", selector: { ...rule.selector, host: "example.net" } } }); + const release = await f.lock.acquire(BRAIN_LOCK_KEY); const pending = f.commit(a); writeFileSync(f.path, initial + "Outside edit.\n"); release(); + expect((await pending).receipt.reason).toBe("stale_base"); expect((await f.commit(b)).receipt.publication).toBe("not_published"); + expect((await f.settings.read("odysseus", b.receipt.requestId)).review.proposed).toBe(b.review.proposed); +}); +test("only trust revision is live; ordinary policy and invalid last-valid trust remain honest", async () => { + const f = await fixture(), reader = createGovernancePolicyReader(f.root), ordinary = reader.load(), admitted = structuredClone(await f.settings.snapshot()), draft = await f.prepare(); await f.commit(draft); + const next = await f.settings.snapshot(); expect(next.revision).not.toBe(admitted.revision); expect(admitted.rules).toEqual([]); + writeFileSync(f.path, readFileSync(f.path, "utf8").replace("block_usd: 17", "block_usd: 19")); + expect((await f.settings.snapshot()).revision).toBe(next.revision); + expect(ordinary.policy.budgets.turn.block_usd).toBe(17); expect(reader.load().policy.budgets.turn.block_usd).toBe(19); + writeFileSync(f.path, "invalid"); const invalid = await f.settings.snapshot(); expect(invalid.rules).toEqual(next.rules); expect(invalid.error).toBe("policy_unavailable"); +}); +test("exhausted trust revisions refuse new reviews before reserving or publishing policy", async () => { + const f = await fixture(); await f.settings.snapshot(); + f.db.exec("UPDATE trust_settings_projection SET revision='18446744073709551615'"); + let error: unknown; try { await f.prepare(); } catch (caught) { error = caught; } + expect((error as Error)?.message, "TRUST_REVISION_EXHAUSTION_BEFORE_REVIEW").toBe("capacity"); + expect(f.db.query("SELECT count(*) n FROM trust_settings_operations").get()).toEqual({ n: 0 }); + expect(f.observations).toEqual([]); expect(readFileSync(f.path, "utf8")).toBe(initial); +}); +test("a previously prepared exhausted-revision review cannot publish before failing capacity", async () => { + const f = await fixture(), draft = await f.prepare(); + const row = f.db.query("SELECT payload FROM trust_settings_operations WHERE request_id=?").get(draft.receipt.requestId) as { payload: string }; + const payload = JSON.parse(row.payload); payload.input.expectedTrustRevision = "18446744073709551615"; + f.db.query("UPDATE trust_settings_operations SET payload=? WHERE request_id=?").run(JSON.stringify(payload), draft.receipt.requestId); + f.db.exec("UPDATE trust_settings_projection SET revision='18446744073709551615'"); + const result = await f.commit(draft).catch(error => ({ error })); + expect(readFileSync(f.path, "utf8"), "TRUST_REVISION_EXHAUSTION_BEFORE_PUBLICATION").toBe(initial); + expect(f.observations).toEqual([]); + expect("receipt" in result && result.receipt.publication).toBe("not_published"); + expect("receipt" in result && result.receipt.reason).toBe("capacity"); +}); +for (const stage of ["writing", "renamed", "file_published", "committed"]) test(`real process death at ${stage} never guesses publication or republishes`, async () => { + const f = await fixture(), draft = await f.prepare(); await Bun.write(join(f.root, "request.json"), JSON.stringify(draft.review)); + const child = Bun.spawn([process.execPath, join(import.meta.dir, "fixtures/trust-settings-crash.ts"), f.root, stage, draft.receipt.requestId], { stdout: "pipe", stderr: "pipe" }); + const [code, stderr] = await Promise.all([child.exited, new Response(child.stderr).text()]); expect({ code, stderr }).toEqual({ code: 77, stderr: "" }); + const recovered = createTrustSettings(f.options), result = await recovered.read("odysseus", draft.receipt.requestId); + expect(result.receipt.publication).toBe(["writing", "renamed"].includes(stage) ? "unknown" : "proved"); + // Equal bytes planted after a pre-publication death cannot establish its proof. + writeFileSync(f.path, draft.review.proposed); + const replay = await recovered.commit("odysseus", { version: 1, requestId: draft.receipt.requestId, reviewId: draft.review.reviewId, reviewedBytesHash: draft.review.reviewedBytesHash }); + expect(replay.receipt.publication).toBe(result.receipt.publication); expect(f.observations).toHaveLength(0); +}); +test("prepare and terminal write failures publish nothing or retain unknown, never replay", async () => { + const f = await fixture(); f.db.exec("CREATE TRIGGER reject_prepare BEFORE INSERT ON trust_settings_operations BEGIN SELECT RAISE(ABORT,'write failed'); END"); + await expect(f.prepare()).rejects.toThrow("write failed"); expect(readFileSync(f.path, "utf8")).toBe(initial); + f.db.exec("DROP TRIGGER reject_prepare"); const draft = await f.prepare(); + f.db.exec("CREATE TRIGGER reject_proof BEFORE UPDATE ON trust_settings_operations WHEN NEW.proof IS NOT NULL BEGIN SELECT RAISE(ABORT,'proof failed'); END"); + expect((await f.commit(draft)).receipt.publication).toBe("unknown"); expect((await f.commit(draft)).receipt.publication).toBe("unknown"); expect(f.observations).toHaveLength(1); +}); +test("outstanding capacity and unsupported repository identities refuse before publication", async () => { + const f = await fixture(); + for (let n = 0; n < 32; n++) await f.prepare(); + let capacity: unknown; try { await f.prepare(); } catch (error) { capacity = error; } expect((capacity as Error)?.message).toBe("capacity"); expect(f.observations).toEqual([]); + let unavailable: unknown; try { await f.prepare({ action: "create", rule: { ...rule, selector: { kind: "github_owner", host: "github.com", owner: "odysseus", ownerId: "1" } } }); } catch (error) { unavailable = error; } + expect((unavailable as Error)?.message).toBe("repository_identity_unavailable"); +}); +test("real HTTP login/owner/CSRF boundary rejects ambient, agent, forged-card and revoked commits", async () => { + const f = await fixture(), password = "ithaca-harbor-test", secret = "fictional-cookie-secret-for-ithaca-tests"; + const config = resolveServerConfig({ AUTH_MODE: "password", BRAIN_UI_PASSWORD_HASH: await Bun.password.hash(password), COOKIE_SECRET: secret }); + const auth: AuthRuntime = { ...config.auth, host: "127.0.0.1" }; + let mode: "password" | "none" = "password"; + const settings = createTrustSettings({ ...f.options, authority: id => { + const p = resolvePrincipal(f.db, id); + return mode === "password" && p?.kind === "owner" && isUsablePrincipal(p, Date.now()) ? JSON.stringify([p.id, p.createdAt, p.expiresAt]) : null; + } }); + const app = new Hono(); app.route("/api", authRoutes("password", auth, { db: f.db, revoker: { revokePrincipals() {} } })); + app.use("/api/*", async (c, next) => authGuard(mode, auth, f.db)(c, next)); + app.route("/api", createTrustSettingsRoutes({ settings, trustProxy: false })); + const server = Bun.serve({ hostname: "127.0.0.1", port: 0, fetch: app.fetch }); cleanup.push(() => server.stop(true)); + const base = `http://127.0.0.1:${server.port}`; + const response = await fetch(`${base}/api/auth/login`, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ password }) }); + expect(response.status).toBe(200); const cookie = response.headers.get("set-cookie")!.split(";")[0]!; + const request = (path: string, body?: unknown, extra: Record = {}) => fetch(`${base}/api/trust-settings${path}`, { + method: body === undefined ? "GET" : "POST", headers: { cookie, "content-type": "application/json", origin: base, ...extra }, ...(body === undefined ? {} : { body: JSON.stringify(body) }) }); + const p = await (await request("")).json() as { revision: string; policyHash: string | null }; + const body = { version: 1, expectedTrustRevision: p.revision, expectedPolicyHash: p.policyHash, change: { action: "create", rule } }; + expect((await request("/prepare", body, { origin: "" })).status).toBe(403); + expect((await request("/prepare", body, { origin: "https://example.net", "sec-fetch-site": "same-origin" })).status).toBe(403); + expect((await request("/prepare", { ...body, principalId: "odysseus", channel: "card" })).status).toBe(400); + 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); + 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)); +}); +test("real journal observes a Settings operation as user policy without fabricating a turn", async () => { + const f = await fixture(), objects = mkdtempSync(join(f.root, "../objects-")); cleanup.push(() => rmSync(objects, { recursive: true, force: true })); + const native = createNativeJournalFixture(f.root, objects); cleanup.push(() => native.close()); + const journal = createTurnJournal(f.db, { nativeManager: native.manager, brainPath: f.root, dbPath: join(f.root, "ui.db"), objectsRoot: objects }); cleanup.push(() => journal.close()); + const settings = createTrustSettings({ ...f.options, observe: (id, write) => journal.observeSettingsPolicy(id, write) }); + const p = await settings.list("odysseus"); + const draft = await settings.prepare("odysseus", { version: 1, expectedTrustRevision: p.revision, expectedPolicyHash: p.policyHash, change: { action: "create", rule } }); + const saved = await settings.commit("odysseus", { version: 1, requestId: draft.receipt.requestId, reviewId: draft.review.reviewId, reviewedBytesHash: draft.review.reviewedBytesHash }); + expect(saved.receipt.publication).toBe("proved"); + expect(f.db.query("SELECT count(*) n FROM turn_journal_turns").get()).toEqual({ n: 0 }); + expect(f.db.query("SELECT count(*) n FROM policy_proposals").get()).toEqual({ n: 0 }); +}); +test("empty defaults prepare without side effects and publish missing policy ancestors", async () => { + const f = await fixture(); rmSync(join(f.root, "context"), { recursive: true }); + const p = await f.settings.list("odysseus"); expect(p.rules).toEqual([]); expect(p.policyHash).toBeNull(); + const draft = await f.prepare(); expect(draft.review.base).toBeNull(); + expect(() => readFileSync(f.path)).toThrow(); + const recovered = createTrustSettings(f.options); expect((await recovered.read("odysseus", draft.receipt.requestId)).receipt.stage).toBe("prepared"); + expect((await f.commit(draft)).receipt.publication).toBe("proved"); +}); + +test("real process death after prepared commit retains a readable draft and no file effect", async () => { + const f = await fixture(), p = await f.settings.list("odysseus"); + await Bun.write(join(f.root, "request.json"), JSON.stringify({ input: { version: 1, expectedTrustRevision: p.revision, expectedPolicyHash: p.policyHash, change: { action: "create", rule } } })); + const child = Bun.spawn([process.execPath, join(import.meta.dir, "fixtures/trust-settings-crash.ts"), f.root, "prepared", "unused"], { stdout: "pipe", stderr: "pipe" }); + const [code, stderr] = await Promise.all([child.exited, new Response(child.stderr).text()]); expect({ code, stderr }).toEqual({ code: 77, stderr: "" }); + const row = f.db.query("SELECT request_id FROM trust_settings_operations").get() as { request_id: string }; + expect((await f.settings.read("odysseus", row.request_id)).receipt.stage).toBe("prepared"); + expect(readFileSync(f.path, "utf8")).toBe(initial); +}); + +const repositoryRule = { ...rule, id: "ithaca-source", selector: { kind: "github_repository" as const, host: "github.com" as const, + owner: "odysseus", repository: "ithaca", repositoryId: "101" } }; +const ownerRule = { ...rule, id: "ithaca-owner", selector: { kind: "github_owner" as const, host: "github.com" as const, owner: "odysseus", ownerId: "201" } }; + +async function githubFixture(patch: Partial[0]> = {}) { + const f = await fixture(), owner = createPrincipal(f.db, { authMethod: "password", label: "Penelope", ttlSeconds: 3600 }); + const state = { owner: "odysseus", ownerId: "201", repository: "ithaca", repositoryId: "101", private: false, status: 200 }; + const requests: { path: string; authorization: string | null }[] = []; + const tls = fixtureTls(join(f.root, "tls"), ["api.github.com"]); + 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, authorization = request.headers.get("authorization"); + requests.push({ path, authorization }); + 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 && !authorization) 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 access = createGitHubReferenceAccess({ db: f.db, brain: "ithaca-brain", credentials: { GITHUB_TOKEN: "odysseus-fixture-token" }, + transport: { async resolve() { throw new Error("Settings cannot discover Git refs"); }, async fetch() { throw new Error("Settings cannot fetch Git"); }, + async checkout() { throw new Error("Settings cannot check out source"); } }, + 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 github = createTrustGitHubIdentity({ root: f.root, access }); + const options = { ...f.options, github, authority: (id: string) => { + const p = resolvePrincipal(f.db, id); + return id === owner.id && p?.kind === "owner" && isUsablePrincipal(p, Date.now()) ? "owner-epoch" : null; + }, ...patch }; + const settings = createTrustSettings(options); + const prepare = async (change: unknown = { action: "create", rule: repositoryRule }) => { + const p = await settings.list(owner.id); + return settings.prepare(owner.id, { version: 1, expectedTrustRevision: p.revision, expectedPolicyHash: p.policyHash, change }); + }; + const commit = (draft: Awaited>) => settings.commit(owner.id, { version: 1, requestId: draft.receipt.requestId, + reviewId: draft.review.reviewId, reviewedBytesHash: draft.review.reviewedBytesHash }); + const grant = () => createReferenceGrant(f.db, { brain: "ithaca-brain", principalId: owner.id, createdBy: owner.id, + repositoryPrefix: "https://github.com/odysseus", credential: "GITHUB_TOKEN", metadataCredentialRecipient: "https://api.github.com", now: Date.now() }); + return { ...f, owner, options, settings, github, state, requests, prepare, commit, grant, + childMetadata: { principalId: owner.id, port: server.port!, ca: tls.ca } }; +} + +for (const selected of [repositoryRule, ownerRule]) test(`actual TLS metadata and protected publication support ${selected.selector.kind} CRUD without a turn`, async () => { + const f = await githubFixture(); + const pending = f.prepare({ action: "create", rule: selected }).then(draft => f.commit(draft)); + await expect(pending, "SETTINGS_GITHUB_CRUD_USES_HOST_METADATA_AND_REAL_PUBLICATION").resolves.toMatchObject({ receipt: { publication: "proved", currentRule: "present", enforcement: "unavailable" } }); + const saved = await pending, approval = await f.settings.repositoryApproval(selected.id); + expect(approval, "SETTINGS_APPROVED_OWNER_COMES_FROM_PROVED_PUBLICATION").toMatchObject({ + identity: { selector: selected.selector, ownerId: "201" }, proof: { reviewedBytesHash: saved.review.reviewedBytesHash, principal: f.owner.id } }); + expect(saved.review.includesFutureRepositories).toBe(selected.selector.kind === "github_owner"); + expect(f.requests).toHaveLength(2); expect(f.requests.every(request => request.authorization === null)).toBe(true); + const edited = await f.prepare({ action: "edit", rule: { ...selected, label: "The home harbor" } }); + expect((await f.commit(edited)).receipt.publication).toBe("proved"); + expect((await f.settings.read(f.owner.id, saved.receipt.requestId)).receipt.currentRule).toBe("changed"); + const observed = f.requests.length; f.state.status = 500; + await f.commit(await f.prepare({ action: "remove", ruleId: selected.id })); + expect(f.requests).toHaveLength(observed); expect(await f.settings.repositoryApproval(selected.id)).toBeNull(); + expect((await f.settings.read(f.owner.id, saved.receipt.requestId)).receipt.currentRule).toBe("removed"); + expect(f.db.query("SELECT count(*) n FROM sessions").get()).toEqual({ n: 0 }); + expect(f.db.query("SELECT count(*) n FROM policy_proposals").get()).toEqual({ n: 0 }); +}); + +for (const change of ["repository_id", "owner_id", "rename", "transfer", "unavailable"] as const) + test(`a reviewed repository cannot publish after ${change} metadata changes`, async () => { + const f = await githubFixture(), draft = await f.prepare(); + expect(await f.settings.repositoryApproval(repositoryRule.id)).toBeNull(); + if (change === "repository_id") f.state.repositoryId = "102"; + else if (change === "owner_id") f.state.ownerId = "202"; + else if (change === "rename") f.state.repository = "fleet"; + else if (change === "transfer") f.state.owner = "penelope"; + else f.state.status = 500; + const result = await f.commit(draft); + expect(result.receipt.publication, "SETTINGS_METADATA_CHANGE_CANNOT_INHERIT_REVIEW").toBe("not_published"); + expect(readFileSync(f.path, "utf8")).toBe(initial); expect(await f.settings.repositoryApproval(repositoryRule.id)).toBeNull(); + expect(result.review.proposed).toBe(draft.review.proposed); + }); + +test("a private Settings publication retains the actual selected grant through its final fence", async () => { + const f = await githubFixture(); f.state.private = true; const grant = f.grant(); + const draft = await f.prepare(); + const settings = createTrustSettings({ ...f.options, github: { async resolve(input) { + const observed = await f.github.resolve(input); + revokeReferenceGrant(f.db, { brain: "ithaca-brain", principalId: f.owner.id, id: grant.id, now: Date.now() }); + return observed; + } } }); + const result = await settings.commit(f.owner.id, { version: 1, requestId: draft.receipt.requestId, reviewId: draft.review.reviewId, + reviewedBytesHash: draft.review.reviewedBytesHash }); + expect(result.receipt.publication, "SETTINGS_FINAL_GRANT_FENCE_PRECEDES_PROTECTED_PUBLICATION").toBe("not_published"); + expect(readFileSync(f.path, "utf8")).toBe(initial); expect(await f.settings.repositoryApproval(repositoryRule.id)).toBeNull(); + expect(f.requests.map(request => request.authorization)).toEqual([null, "Bearer odysseus-fixture-token", null, "Bearer odysseus-fixture-token"]); +}); + +test("equal policy bytes and prepared metadata are not approved-owner publication evidence", async () => { + const f = await githubFixture(), draft = await f.prepare(); + writeFileSync(f.path, draft.review.proposed); + expect((await f.settings.snapshot()).rules).toEqual([repositoryRule]); + expect(await f.settings.repositoryApproval(repositoryRule.id), "SETTINGS_EQUAL_BYTES_DO_NOT_PROVE_OWNER_APPROVAL").toBeNull(); + expect((await f.commit(draft)).receipt.publication).toBe("not_published"); +}); + +test("publication proof and owner-boundary recording commit atomically and survive operation pruning", async () => { + const f = await githubFixture(), draft = await f.prepare(); + f.db.exec("CREATE TRIGGER reject_boundary BEFORE INSERT ON trust_settings_github_boundaries BEGIN SELECT RAISE(ABORT,'boundary failed'); END"); + const result = await f.commit(draft); + expect(result.receipt.publication, "SETTINGS_BOUNDARY_FAILURE_RETAINS_UNKNOWN_PUBLICATION").toBe("unknown"); + expect(await f.settings.repositoryApproval(repositoryRule.id)).toBeNull(); + expect((await f.commit(draft)).receipt.publication).toBe("unknown"); + f.db.exec("DROP TRIGGER reject_boundary"); + const corrected = await f.prepare({ action: "edit", rule: { ...repositoryRule, label: "The home harbor" } }); + expect((await f.commit(corrected)).receipt.publication).toBe("proved"); + const before = await f.settings.repositoryApproval(repositoryRule.id); expect(before).not.toBeNull(); + f.db.exec("DELETE FROM trust_settings_operations"); + const restarted = createTrustSettings(f.options); + expect(await restarted.repositoryApproval(repositoryRule.id), "SETTINGS_OWNER_APPROVAL_SURVIVES_BOUNDED_RECEIPT_PRUNING").toEqual(before); +}); + +test("an observer that never invokes its publication callback cannot manufacture proof", async () => { + const f = await fixture({ observe: async () => {} }), draft = await f.prepare(); + expect((await f.commit(draft)).receipt.publication, "SETTINGS_MISSING_PUBLICATION_CALLBACK_IS_NOT_PROOF").toBe("not_published"); + expect(readFileSync(f.path, "utf8")).toBe(initial); +}); + +for (const stage of ["writing", "renamed", "file_published", "committed"]) + test(`GitHub owner-boundary recovery after real process death at ${stage} uses durable publication proof`, async () => { + const f = await githubFixture(), draft = await f.prepare(); + writeFileSync(join(f.root, "request.json"), JSON.stringify(draft.review)); + writeFileSync(join(f.root, "github-fixture.json"), JSON.stringify(f.childMetadata)); + const child = Bun.spawn([process.execPath, join(import.meta.dir, "fixtures/trust-settings-crash.ts"), f.root, stage, draft.receipt.requestId], { stdout: "pipe", stderr: "pipe" }); + const [code, stderr] = await Promise.all([child.exited, new Response(child.stderr).text()]); + expect({ code, stderr }).toEqual({ code: 77, stderr: "" }); + const recovered = createTrustSettings(f.options), result = await recovered.read(f.owner.id, draft.receipt.requestId); + const proved = stage === "file_published" || stage === "committed"; + expect(result.receipt.publication).toBe(proved ? "proved" : "unknown"); + const approval = await recovered.repositoryApproval(repositoryRule.id); + expect(approval !== null, "SETTINGS_CRASH_OWNER_APPROVAL_REQUIRES_DURABLE_PROOF").toBe(proved); + if (proved) expect(approval).toMatchObject({ identity: { ownerId: "201", selector: repositoryRule.selector }, + proof: { reviewedBytesHash: draft.review.reviewedBytesHash, principal: f.owner.id } }); + const count = f.requests.length; + expect((await f.commit(draft)).receipt.publication).toBe(result.receipt.publication); + expect(f.requests, "SETTINGS_CRASH_REPLAY_NEVER_REPEATS_METADATA_OR_PUBLICATION").toHaveLength(count); + }); + +test("metadata after a journal wait rechecks the live owner before touching the policy", async () => { + let ready!: () => void, release!: () => void; + const reached = new Promise(resolve => { ready = resolve; }), held = new Promise(resolve => { release = resolve; }); + const f = await githubFixture({ observe: async (_id, publish) => { ready(); await held; await publish(); } }), draft = await f.prepare(); + const pending = f.commit(draft); + try { + await reached; revokePrincipal(f.db, f.owner.id, Date.now()); release(); + const rejected = await pending.then(() => null, error => error); + expect(rejected, "SETTINGS_REVOKED_OWNER_AFTER_JOURNAL_WAIT_CANNOT_PUBLISH").toMatchObject({ message: "unauthorized" }); + expect(f.requests).toHaveLength(1); expect(readFileSync(f.path, "utf8")).toBe(initial); + expect(f.db.query("SELECT count(*) n FROM trust_settings_github_boundaries").get()).toEqual({ n: 0 }); + } finally { release(); await pending.catch(() => {}); } +}); + +test("real HTTP GitHub Settings CRUD compares browser IDs with fresh host metadata", async () => { + const f = await githubFixture(), password = "ithaca-settings-test", secret = "fictional-cookie-secret-for-ithaca-tests"; + const config = resolveServerConfig({ AUTH_MODE: "password", BRAIN_UI_PASSWORD_HASH: await Bun.password.hash(password), COOKIE_SECRET: secret }); + const auth: AuthRuntime = { ...config.auth, host: "127.0.0.1" }; + const settings = createTrustSettings({ ...f.options, authority: id => { + const p = resolvePrincipal(f.db, id); + return p?.kind === "owner" && isUsablePrincipal(p, Date.now()) ? "owner-epoch" : null; + } }); + const app = new Hono(); app.route("/api", authRoutes("password", auth, { db: f.db, revoker: { revokePrincipals() {} } })); + app.use("/api/*", authGuard("password", auth, f.db)); + app.route("/api", createTrustSettingsRoutes({ settings, trustProxy: false })); + const server = Bun.serve({ hostname: "127.0.0.1", port: 0, fetch: app.fetch }); cleanup.push(() => server.stop(true)); + const base = `http://127.0.0.1:${server.port}`; + const login = await fetch(`${base}/api/auth/login`, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ password }) }); + expect(login.status).toBe(200); const cookie = login.headers.get("set-cookie")!.split(";")[0]!; + const request = (path: string, body?: unknown) => fetch(`${base}/api/trust-settings${path}`, { method: body ? "POST" : "GET", + headers: { cookie, "content-type": "application/json", origin: base }, ...(body ? { body: JSON.stringify(body) } : {}) }); + const p = await (await request("")).json() as { revision: string; policyHash: string | null }; + const body = { version: 1, expectedTrustRevision: p.revision, expectedPolicyHash: p.policyHash, change: { action: "create", rule: repositoryRule } }; + const forged = await request("/prepare", { ...body, change: { action: "create", rule: { ...repositoryRule, selector: { ...repositoryRule.selector, repositoryId: "999" } } } }); + expect(forged.status, "SETTINGS_HTTP_BROWSER_ID_CANNOT_SELF_VERIFY").toBe(503); + const prepared = await request("/prepare", body); expect(prepared.status).toBe(200); + const draft = await prepared.json() as Awaited>; + expect(draft.review.repositoryIdentity).toMatchObject({ ownerId: "201", selector: repositoryRule.selector }); + const committed = await request("/commit", { version: 1, requestId: draft.receipt.requestId, reviewId: draft.review.reviewId, reviewedBytesHash: draft.review.reviewedBytesHash }); + expect(committed.status).toBe(200); expect((await committed.json() as typeof draft).receipt.publication).toBe("proved"); + expect(f.requests).toHaveLength(3); +}); + +test("the actual journal retains its Settings window through asynchronous publication", async () => { + const f = await fixture(), objects = mkdtempSync(join(f.root, "../objects-")); cleanup.push(() => rmSync(objects, { recursive: true, force: true })); + const native = createNativeJournalFixture(f.root, objects); cleanup.push(() => native.close()); + const journal = createTurnJournal(f.db, { nativeManager: native.manager, brainPath: f.root, dbPath: join(f.root, "ui.db"), objectsRoot: objects }); cleanup.push(() => journal.close()); + let ready!: () => void, release!: () => void, timer: ReturnType | undefined; + const reached = new Promise(resolve => { ready = resolve; }), held = new Promise(resolve => { release = resolve; }); + const first = journal.observeSettingsPolicy("ithaca-first", async () => { ready(); await held; }); + await reached; + const second = journal.observeSettingsPolicy("ithaca-second", () => {}); + try { + const result = await Promise.race([second.then(() => "advanced"), new Promise(resolve => { timer = setTimeout(() => resolve("held"), 1000); })]); + expect(result, "SETTINGS_JOURNAL_WINDOW_INCLUDES_ASYNC_PUBLICATION").toBe("held"); + } finally { if (timer) clearTimeout(timer); release(); await Promise.allSettled([first, second]); } +}); + +test("Settings HTTP admission bounds queued lock waiters and recovers when requests finish", async () => { + const f = await githubFixture(), app = new Hono(); + app.use("*", async (c, next) => { c.set("principal", f.owner); await next(); }); + app.route("/api", createTrustSettingsRoutes({ settings: f.settings, trustProxy: false })); + const release = await f.lock.acquire(BRAIN_LOCK_KEY); + const pending = Array.from({ length: 32 }, () => app.request("http://localhost/api/trust-settings")); + let timer: ReturnType | undefined; + const excess = app.request("http://localhost/api/trust-settings"); + try { + const result = await Promise.race([Promise.resolve(excess).then(response => response.status), new Promise(resolve => { timer = setTimeout(() => resolve(null), 1000); })]); + expect(result, "SETTINGS_HTTP_QUEUE_REFUSES_BEFORE_ANOTHER_LOCK_WAIT").toBe(503); + expect(await (await excess).json()).toMatchObject({ code: "busy", retryable: true }); + } finally { if (timer) clearTimeout(timer); release(); await Promise.allSettled([...pending, excess]); } + expect((await app.request("http://localhost/api/trust-settings")).status, "SETTINGS_HTTP_BUSY_CLEARS_WHEN_WAITERS_DRAIN").toBe(200); + expect(f.requests).toEqual([]); +}); diff --git a/packages/ui-server/tests/turn-journal.test.ts b/packages/ui-server/tests/turn-journal.test.ts index 7e578168f2..67e6554388 100644 --- a/packages/ui-server/tests/turn-journal.test.ts +++ b/packages/ui-server/tests/turn-journal.test.ts @@ -432,6 +432,49 @@ test("approved policy writes retain user attribution in the original active wind } finally { await f.close(); } }); +test("a failed asynchronous Settings operation cannot approve concurrent policy edits", async () => { + const f = fixture(); + try { + mkdirSync(join(f.brain, "context/policies"), { recursive: true }); + const policy = join(f.brain, "context/policies/governance.md"); + writeFileSync(policy, "Athena's original policy\n"); + await f.begin("odysseus"); + let ready!: () => void, release!: () => void; + const reached = new Promise(resolve => { ready = resolve; }), held = new Promise(resolve => { release = resolve; }); + const pending = f.journal.observeSettingsPolicy("ithaca-rejected", async () => { ready(); await held; throw new Error("metadata unavailable"); }); + await reached; + writeFileSync(policy, "Unapproved policy during metadata lookup\n"); release(); + await expectRejection(pending, "metadata unavailable"); + const change = f.journal.details("ithaca", "odysseus")!.changes.find(change => change.path === "context/policies/governance.md"); + expect(change, "SETTINGS_FAILED_ASYNC_LOOKUP_CANNOT_APPROVE_CONCURRENT_EDIT").toMatchObject({ class: "content", actor: "agent" }); + expect(queryGovernanceEvents(f.db, { turnId: "odysseus", kinds: ["steering_change"], limit: 100 })).toHaveLength(0); + await f.journal.finish("odysseus"); + } finally { await f.close(); } +}); + +for (const publishPolicy of [false, true]) test(`Settings metadata waits retain normal attribution before publication=${publishPolicy}`, async () => { + const f = fixture(); + try { + mkdirSync(join(f.brain, "context/policies"), { recursive: true }); + const policy = join(f.brain, "context/policies/governance.md"); + writeFileSync(policy, "Athena's original policy\n"); + await f.begin("odysseus"); + let ready!: () => void, release!: () => void; + const reached = new Promise(resolve => { ready = resolve; }), held = new Promise(resolve => { release = resolve; }); + const pending = f.journal.observeSettingsPolicy("ithaca-reviewed", async publish => { + ready(); await held; + if (publishPolicy) await publish!(() => writeFileSync(policy, "Odysseus approves this policy\n")); + }); + await reached; writeFileSync(policy, "Unapproved edit during metadata lookup\n"); release(); await pending; + const changes = f.journal.details("ithaca", "odysseus")!.changes.filter(change => change.path === "context/policies/governance.md"); + expect(changes.map(change => ({ actor: change.actor, class: change.class })), "SETTINGS_ONLY_SYNCHRONOUS_PUBLICATION_IS_USER_POLICY").toEqual([ + { actor: "agent", class: "content" }, ...(publishPolicy ? [{ actor: "user" as const, class: "policy" as const }] : []), + ]); + expect(queryGovernanceEvents(f.db, { turnId: "odysseus", kinds: ["steering_change"], limit: 100 })).toHaveLength(0); + await f.journal.finish("odysseus"); + } finally { await f.close(); } +}); + test("actual journal classifies steering and local transitive configuration separately from content and policy", async () => { const f = fixture(); try {