Skip to content

CONTRACT: fix(ui-server): bind a chat's safety history to the account, not the login (#3952) - #3965

Merged
schlessera merged 3 commits into
mainfrom
fix/3952-safety-account-partition
Nov 11, 2026
Merged

schlessera merged 3 commits into
mainfrom
fix/3952-safety-account-partition

Conversation

@schlessera

@schlessera schlessera commented Nov 11, 2026 •

Copy link
Copy Markdown
Owner

Closes #3952

What changed

Every owner sign-in mints its own principal, but a chat's safety record was bound to the exact principal that started it. So when the owner continued a chat from another device (or after their login renewed), every turn was refused as Safety principal mismatch (or Safety history ownership mismatch once the chat had a dialogue owner). That is a refusal of the turn since #3812; before #3812 it latched the whole brain on a hosted instance. Following the maintainer's ruling on #3952 (option A), a chat's safety history now belongs to its account. Any owner login continues the chat, and its turns join the same safety history and taint. It can also read that history and review its occurrences. An agent, a proxy user, a system principal, or a principal whose row no longer exists is still refused, exactly as before. Stored rows keep the principal that wrote them; nothing is rewritten.

sameAccount(db, bound, principal) (packages/ui-server/src/middleware/account-partition.ts) decides it from the existing partition notion. Two principals are one account only when accountScope puts them in the same partition in every auth mode. A record keeps who made it, not the auth mode it was made under. Today that means the same principal, or two owner logins. An ambient principal shares the owner's partition only in some modes, and agent and system principals hold none, so each stays bound to itself. An unresolvable principal is unknown, never the same account.

Check Where Now
Safety principal mismatch beginSafetyCollection same account
Safety history ownership mismatch (dialogue owner) beginSafetyCollection same account
Safety fork history ownership mismatch beginSafetyCollection (handoff source) same account
Safety binding owner mismatch bindSafetyCollection (runs inside begin for a resumed chat) same account
Safety retained owner mismatch bindSafetyCollection same account
session, turn and dialogue-owner reads SafetyHistory.authorize same account
review target and eligibility safetyReviewTarget, eligible same account
safety_decision_identity trigger (session, collection, dialogue owner) migration 087_safety_account_partition.sql same account, in SQL
same turn re-begin (Conflicting safety collection), catalog creation, read snapshots/cursors, review handles and receipts, per-principal limits, the verdict's principalId unchanged exact principal

Without the bind and retained-owner changes the turn still fails: begin calls bindSafetyCollection for a resumed chat, which compared the turn's principal to the chat's exactly. The mutation table shows it.

Why this shape

Reviews get the same treatment. A verdict already needs a live password-mode owner epoch: owner kind, password or passkey, rechecked in the acquired transaction (authorized, safety-reviews.ts). Every owner login is that same human, so letting one review a chat another login started grants no authority the reviewer lacks. Leaving reviews exact would break option A in practice. The device continuing the chat could not clear occurrences its own turns raised, because the review target compares against the chat's starting principal. And once that login expires, nobody could review the chat at all. What belongs to one login stays exact: the prepared handle (commit requires the preparing principal), its fingerprint over the authority epoch, receipts, the per-principal pending limit, and the principalId the verdict records. The DB trigger is the backstop, so it is updated to the same rule. Reads follow for the same reason: the ruling says owner principals share a chat's safety history, and the review body comes from a read.

Partition from the principal row, not stored on safety rows. The acceptance criterion forbids rewriting history, and the existing rows hold principal ids, so the comparison maps a stored principal to its account at check time. The write worker does not know the auth mode, hence "same partition in every mode" rather than calling accountScope with the current mode. Within those cases this is narrower than the browser partition, never wider. The cost: a principal row pruned 30 days after expiry leaves an id nobody can vouch for, and that chat is refused for good. Filed as #3962 (needs: decision).

Not taken: passing the auth mode into the write worker (it is created in five places that do not know it) and recording the partition on every safety row (a schema change plus a backfill question). Both belong to #3962's options.

Security properties kept

  • Another account's principal reads or extends nothing: agent, proxy user, system principal, unknown id and null are each refused at begin, fork, read, review and in the trigger. A refused begin leaves no collection.
  • A chat bound to an agent or a proxy user is never taken over by an owner login.
  • No taint is lost: the new turn joins the same history_owner_id and generation, inherits the chat's unresolved occurrences and restriction, and extends the same ledger.
  • No row is rewritten: safety_sessions.principal_id and earlier records are byte-identical after another login's turn.

Review follow-up

Independent security review (gpt-6-astra) at a34d07125

No blocking finding. These all passed: every auth mode, taint retention, the login-bound handles, cursors and receipts, migration 087, and the review widening. Two wording findings, both fixed in the same CONTRACT: commit (amended):

  • P2, fixed: the detailed "Session safety sidecars" section of docs/http-api.md still said separate owner logins have no equivalence. It now states the account rule, and keeps that a cursor stays with the one login that read it (another login's cursor is refused as expired, 409).
  • P3, fixed: docs/integration-contract/http.md said a missing principal shares with nobody. But sameAccount returns true for two equal ids before resolving them, and migration 087 keeps the same exact-id exception; both are the existing exact-comparison behaviour, kept as is. The section now says: a principal id always matches itself; two different ids match only when both resolve to the same account partition; a missing or unresolvable principal matches no other id. The same imprecise wording was also corrected in the decision record (session-safety-reviews.md), the comment in migration 087, and the sameAccount JSDoc. Code is unchanged, and git diff shows only comment lines in those two source files.

Collisions

bun scripts/collisions.ts --json --pr 3965 at a34d07125: one textual collision, with draft #3622 (durable owner trust Settings publication) in docs/http-api.md. git merge-tree of #3622's head 6a814ee73 gives four three-way conflict hunks in docs/http-api.md, at the same places both against origin/main and against this branch. So they exist against main already, and this PR adds none:

  1. the inventory summary sentence (~line 13);
  2. the supported-route table rows (~163): this PR's GET /api/sessions/:id/safety row next to CONTRACT: feat(ui-server): add durable owner trust Settings publication #3622's /api/trust-settings rows;
  3. the declared-endpoint count (~234);
  4. the "Session safety sidecars" section (~2063), which carries this PR's account wording.

To resolve: keep both route families and the account wording, and recount the endpoints. #3622 also conflicts with main in packages/ui-server/src/app.ts and packages/ui-server/tests/http-inventory.test.ts; this PR touches neither.

At 0838eea7d the same command also reports draft #3662 (review individual safety triggers in chat) in docs/http-api.md. Merged against origin/main it has no conflicts. Against this branch it has one hunk, created by the P2 fix: #3662 inserts its entries=1 paragraph directly above the old "exact live principal… no equivalence" paragraph that this PR rewrites. To resolve: keep #3662's entries=1 paragraph followed by this PR's account paragraph, and drop the old one. #3662's only new principal comparison is a snapshot/cursor check (s.principalId!==principal.id), which correctly stays bound to one login.

Proportionate-containment checklist

  • What triggers it, what does it not cover? The safety binding guards above refuse a turn, read or review whose principal is not the same account as the principal the chat's safety records name. This PR narrows who counts as that account. It does not cover voice/dialogue ownership (dialogue-storage.ts, filed as ui-server: an owner continuing a chat by voice from another device is refused as a dialogue ownership mismatch #3963) or chat deletion, which chat-history-deletion.md binds to the exact principal by decision.
  • What does it restrict, and why nothing narrower? Unchanged scope: the one turn (refused before delivery, nothing latches, since ui-server: contain a safety-recording failure to what it puts at risk and recover automatically #3812), the one read, the one review. A foreign principal must not extend another account's history, so there is no restricted mode in which it may.
  • Restricted mode considered before refusing? Running the foreign turn restricted was rejected: restriction limits what a turn may do, not whose history it extends. The ruling requires refusal for another account.
  • How does it clear? No state to clear: each attempt is decided fresh. Another login of the same account now passes. A chat whose starting login was pruned stays refused (ui-server: a chat whose starting owner login was pruned can never be continued #3962).
  • Where is the cause recorded, and how does the owner see it? As before: the refused begin logs one structured safety recording refused one turn before delivery line naming the check (error.message), and the client gets SAFETY_RECORDING_UNAVAILABLE.
  • Which test shows one scope failing leaves another usable? safety-account-partition.test.ts "a principal of another account is still refused…" refuses each foreign principal, leaving the chat's history untouched. "an owner login never takes over a chat bound to an agent or to another proxy user" refuses the owner login and then continues the chat with its exact principal.

Proof

New file packages/ui-server/tests/safety-account-partition.test.ts (10 tests, real FULL write worker, Odysseus world).

Failing-first, with only sameAccount and the test file added, on the origin/main guards (60d7967): exit 1, 7 fail, 2 pass. Each refusal's cause, from the structured refusal lines:

  • "another owner login continues a chat…", "a chat's rows keep the principal…": Safety principal mismatch
  • "…whose history already has a dialogue owner": Safety history ownership mismatch
  • "another owner login forks a chat…": Safety fork history ownership mismatch
  • "another owner login reads…": SafetyReadUnavailable("unavailable")
  • "another owner login reviews…": SAFETY_SECOND_OWNER_REVIEW_TARGET received "unavailable"
  • the refusal cases also failed then, but only on a turn id with a space in the test, which was fixed. They pin behaviour that already held: foreign principals refused.

Fix: 10 pass, 0 fail, exit 0.

Mutations, each applied to the fix, the file re-run, then restored with git checkout --. The tree was clean afterwards. Every one exits 1:

Mutation Fails
sameAccount returns true ("any principal") 6 tests: foreign refused (expected a rejection, but the promise resolved), no takeover, pruned owner unknown, foreign fork, foreign read, SAFETY_FOREIGN_REVIEW_TARGET_REFUSED
sameAccount true for any two resolvable principals 6 tests: foreign refused, no takeover, foreign fork, foreign read, foreign review, the pair table
begin's session check exact again 3 tests, Safety principal mismatch
begin's dialogue-owner check exact again dialogue-owner continuation, Safety history ownership mismatch
bind's owner check exact again 3 tests, Safety binding owner mismatch
bind's retained-owner check exact again dialogue-owner continuation, Safety retained owner mismatch
fork check exact again fork, Safety fork history ownership mismatch
read: session / turn / dialogue-owner check exact again read test (unavailable, unavailable, generation_changed)
review target / dialogue owner / eligibility exact again review test (SAFETY_SECOND_OWNER_REVIEW_TARGET ×2, SAFETY_SECOND_OWNER_PREPARES_A_REVIEW received refused)
trigger: session / collection / dialogue-owner predicate dropped SAFETY_DECISION_TRIGGER_CHECKS_THE_SESSION / _COLLECTION / _DIALOGUE OWNER (did not throw)
trigger: owner sharing removed (exact only) review commit, safety decision identity or exposure mismatch

The trigger case has a control: each crafted row set refuses the agent's verdict only because of the named record. Setting that record to the agent too admits the same insert.

Two existing tests changed with the rule. Both treated a second password login as a "foreign owner". In the principals model a password login can only be the one owner, and the #3952 ruling makes that login the same account. Each test now asserts the new rule and keeps a genuine other-account refusal:

  • safety-history.test.ts "cursor scope…": another owner login using the first login's cursor gets 409 expired, because the cursor stays with one login (CURSOR_SCOPE_IS_ONE_LOGIN; it was 404). An agent gets 404 (CURSOR_SCOPE_FOREIGN_ACCOUNT).
  • owner-safety-review.test.ts "signed delegated cookies and owner cookies on another account's history cannot mutate it": the agent cookie still gets 403. Another owner login prepares a review (200, OWNER_REVIEW_ANOTHER_LOGIN_IS_THE_SAME_ACCOUNT). A history bound to another account gives 404 unavailable to both owner logins (OWNER_REVIEW_FOREIGN_ACCOUNT_HISTORY).
  • Mutations against these two files, each exit 1: sameAccount returns true fails both (CURSOR_SCOPE_FOREIGN_ACCOUNT received 409, OWNER_REVIEW_FOREIGN_ACCOUNT_HISTORY received 200). An exact session read fails CURSOR_SCOPE_IS_ONE_LOGIN (received 404). An exact review target fails OWNER_REVIEW_ANOTHER_LOGIN_IS_THE_SAME_ACCOUNT (received 404).

Full local proof. Real exit codes, read from each run's own exit line.

Check Head Result
bun run check:pr --base origin/main 0838eea7d (on a875fa5f9) exit 0, receipt below
NODE_OPTIONS=--max-old-space-size=16384 bun run typecheck 0838eea7d exit 0
bun run api-report 0838eea7d exit 0, no drift (sameAccount is not on a public entry point)
provider-history guards (Claude + Pi) and ui-server/tests/no-console.test.ts 0838eea7d 36 pass, 0 fail, exit 0
safety-account-partition.test.ts + http-inventory.test.ts d3e1a7053 (the review fixes, before the rebase onto a875fa5f9) 15 pass, 0 fail, exit 0
bun run test ./packages/ui-server/tests (every ui-server test file) a34d07125 (on 067d1904b) 5790 pass, 0 fail, exit 0
bun run test ./tests (root suite) a34d07125 2239 pass, 0 fail, exit 0
bun run lint 0838eea7d, inside check:pr passed

Between a34d07125 and 0838eea7d only two things changed: the review follow-up below (wording only: docs, plus comments in migration 087 and account-partition.ts, no code) and the rebase onto a875fa5f9, which touches none of this PR's paths. An earlier full ui-server run at the pre-rebase head 4e9ce1667 had 2 failures (5737 pass, exit 1): the two rewritten tests above. The root suite passed there too (2239 pass, exit 0).

bun run check:pr --base origin/main
{
  "version": 1,
  "kind": "brain-check-pr-receipt",
  "head": "4776acc93c5cb7ed9beeda5be62273c94ef6b820",
  "base": "origin/main",
  "mode": "focused",
  "startedAt": "2026-11-11T03:35:29.998Z",
  "finishedAt": "2026-11-11T03:36:36.882Z",
  "checks": [
    {
      "name": "all lint and leakage gates",
      "categories": [
        "changeset"
      ],
      "outcome": "passed",
      "elapsedMs": 10566.588164
    },
    {
      "name": "environment documentation",
      "categories": [
        "changeset"
      ],
      "outcome": "passed",
      "elapsedMs": 118.49214500000016
    },
    {
      "name": "pending changeset package names",
      "categories": [
        "changeset"
      ],
      "outcome": "passed",
      "elapsedMs": 123.35830999999962
    },
    {
      "name": "contribution changeset",
      "categories": [
        "changeset"
      ],
      "outcome": "passed",
      "elapsedMs": 22.57850099999996
    },
    {
      "name": "affected fast invariants",
      "categories": [
        "verify",
        "unit"
      ],
      "outcome": "passed",
      "elapsedMs": 55966.46769199999
    }
  ]
}

Checklist

  • Focused local preflight/behavioral receipts and complete selected hosted proof passed; actual head/base/job checkout evidence is in Proof. (Local proof above; hosted proof runs on confirmation.)
  • Acceptance criteria from the issue are all met, or the gap is named below.
  • The PR and completed/advanced issues have verified release milestones under docs/process/github.md.
  • A changeset is included, or this changes nothing a consumer can see.
  • No personal data anywhere in the diff — the leakage gate covers the whole tree.
  • The integration contract index or relevant component is updated in this same commit, or nothing in the machine surface moved. (http.md, additive)
  • Docs under docs/ reflect the change, or nothing documented moved. (session-safety-reviews.md, http-api.md)
  • A fail-closed guard added or changed answers the proportionate-containment checklist in this body, or no guard changed.
  • Provider history stays append-only (docs/decisions/provider-history.md): the provider-history guard passes, or nothing on a turn's path changed.

Anything left open

🤖 Generated with Claude Code

@schlessera schlessera added this to the 0.45.0 milestone Nov 11, 2026
@schlessera schlessera added type: fix Something is broken and must behave the way it is documented. area: ui-server Hono app factory: turn coordinator, auth, session catalog, routes, cron. contract Touches the integration contract: CONTRACT: commit, contract doc updated in the same commit. labels Nov 11, 2026
…, not the login (#3952)

Every owner sign-in mints its own principal, but a chat's safety record
was bound to the exact principal that started it, so continuing a chat
from another device was refused as a safety principal mismatch. Under
the maintainer's ruling (option A), the history belongs to the account.

`sameAccount` (account-partition.ts) treats two principals as one
account only when `accountScope` puts them in the same partition in
every auth mode: today the same principal, or two owner logins. An
unresolvable principal is unknown and shares with nobody.

It replaces the exact comparisons in collection begin (session, dialogue
owner, fork source), collection binding (binding and retained owner),
safety reads and review target/eligibility. Migration 087 applies the
same rule in the safety_decision_identity trigger. Read snapshots,
cursors, review handles, receipts and the verdict's principal stay bound
to the exact login, and no stored row is rewritten.

Two existing tests treated a second password login as a foreign owner;
they now assert the new rule and keep a real other-account refusal.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@schlessera
schlessera force-pushed the fix/3952-safety-account-partition branch from a34d071 to 0838eea Compare November 11, 2026 03:02
@schlessera
schlessera marked this pull request as ready for review November 11, 2026 03:04
@schlessera
schlessera marked this pull request as draft November 11, 2026 03:37
@schlessera
schlessera marked this pull request as ready for review November 11, 2026 03:37
@schlessera
schlessera merged commit 2b547ef into main Nov 11, 2026
39 of 50 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area: ui-server Hono app factory: turn coordinator, auth, session catalog, routes, cron. contract Touches the integration contract: CONTRACT: commit, contract doc updated in the same commit. type: fix Something is broken and must behave the way it is documented.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

ui-server: an owner continuing a chat from another device is refused as a safety principal mismatch

1 participant