Repository navigation
caller separation: close four cross-tenant holes and the windows around the ownership decision - #753
Merged
Merged
Conversation
WHAT: reserve NUL from both components of a verified owner identity, at the
three construction seams (PrincipalFromClaims, WithPrincipal, RestoreLabels) and
inside PrincipalScopeHash itself.
WHY: owner scope keys are sha256("issuer" + NUL + "subject"). With NUL
admissible inside a component, (iss="a", sub="b\0c") and (iss="a\0b", sub="c")
hash identically. Both were obtainable from a real token, so two distinct
authenticated callers could share one memory and schedule namespace.
IMPROVEMENT: closes a cross-tenant read/write path in OIDC deployments. Before,
an IdP that permitted NUL in sub — or an attacker who could influence it — could
land in another caller's namespace; after, such an identity is refused at every
seam that mints one.
The hash guard is HARDENING, not a second exploit fix, and should not be read as
one: an unsafe identity could never alias a VALID owner (a valid pair hashes
exactly one NUL, an unsafe one two or more), only another unsafe identity, and
those are inadmissible everywhere except the raw-driver wire path that is
unauthenticated anyway (issue #452 / ADR-0213). Its value is that the invariant
now holds at the function that DEPENDS on it, so a Principal built from a struct
literal cannot reintroduce aliasing, and the doc comment's claim of "validated"
becomes true. Unsafe framing gets a domain-separated sentinel scope no valid
principal can produce.
PRESERVES: non-NUL identity bytes exactly; ownerless behaviour; and the
byte-for-byte storage contract — valid digests are unchanged, so no persisted
owner-scoped key moves and no migration is required.
PROOF: TestPrincipalScopeHashLegacyBytesUnchanged (digests unchanged),
TestPrincipalScopeHashQuarantinesUnsafeFraming,
TestRestoreLabelsRejectsInvalidOwnerAtomically.
Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
WHAT: add port.SessionCreator, an optional SessionStore capability whose Create publishes a session only when no snapshot exists under its id, as ONE backend-atomic operation, wrapping ErrSessionAlreadyExists otherwise. Implemented for jsonlstore and redisstore, with memstore as the reference. WHY: SessionStore offered only Save, an upsert. There was no way to express "publish only if absent", so every new-session path was structurally last-write-wins and no caller could do better. IMPROVEMENT: this commit alone changes no behaviour — it is the seam the next commit needs. Its value is that the contract is enforceable rather than conventional: a shared conformance suite pins that a collision must NOT mutate the existing snapshot, its derivative metadata, event log, or tool-call sidecar, and that the check-and-write is atomic across handles sharing a backend. A Load-then-Save imitation fails the suite. So a future fourth backend cannot satisfy the interface while quietly reintroducing the overwrite. PRESERVES: the capability is OPTIONAL, so a store that does not implement it behaves exactly as before; Save remains the update path once Create succeeded. PROOF: engine/adapter/storeconformance (SessionCreator suite), run by the jsonlstore, redisstore and memstore conformance tests. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
WHAT: route every new-session publication through the atomic SessionCreator seam instead of Save — caller-selected create, fork destinations, adoption targets, and the durable subagent, parallel-branch and team-member snapshots — and classify a collision once, in one place. WHY: Save is an upsert, so publishing was last-write-wins. A session id that already existed was silently overwritten, including one owned by someone else. Delegation ids are the sharp edge: they derive from provider tool-call ids, a value the model influences and the API does not guarantee unique across conversations or owners. IMPROVEMENT: this is the branch's largest security delta. Before, a caller who could cause an id collision could destroy another tenant's persisted session or child transcript — data loss across an ownership boundary, with no error raised. After, the loser of a collision cannot mutate the winner's snapshot, derivative metadata, event log, or tool-call sidecar; a same-owner retry of an identical request stays idempotent, and a foreign id is absence. Ownership enforcement now REQUIRES a store with the capability, checked at build time, so a deployment cannot silently degrade to upsert. PRESERVES: the ownerless compatibility path (no verifier wired) keeps its historical behaviour; retries remain idempotent for the legitimate case. SCOPE LIMIT worth knowing at review time: publishing durable child sessions EARLIER, at enrolment, opened a window in which a team member was durably visible but not yet leased. That window is closed later in this branch by "fix(server): lease team members before publishing them" — the two commits should be read together. PROOF: engine/agent/delegation_id_collision_test.go (all three delegation families), the adoption and fork scenario tests, and the SessionCreator conformance suite over memstore, jsonlstore and redisstore. TestSubagentResumeDoesNotRepublishTheChild additionally pins the one `if !resuming` guard that keeps this publication OFF the resume path: a resume loads an existing snapshot, so re-publishing it would fail a legitimate path with ErrSessionAlreadyExists. Verified by mutation — with both guards removed the test fails on the foreground and background paths, and passes with them restored. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
WHAT: prove the caller owns a session BEFORE entering its run-entry mutex, then reload and reauthorize UNDER the lock. WHY: a prompt start took the caller-selected per-session lock first and authorized after. The lock is keyed by an id the caller supplies. IMPROVEMENT: closes two things a foreign caller could previously do to another tenant's session. They could contend on its run-entry mutex — a denial of service against a session they cannot otherwise touch — and they could time that contention to learn whether the id exists, an existence oracle that the absence-shaped error responses were specifically designed to deny. The authorization decision itself was already correct; what was wrong was that it ran after a caller-visible side effect. The under-lock reload is not redundant: the session can be deleted or its owner replaced between the preflight and the lock, so only the second load is authoritative. A preflight is never a durable grant. PRESERVES: the ownership-disabled compatibility path keeps its historical single load, so a non-OIDC deployment is byte-identical. PROOF: TestCallerSeparation_ForeignPromptDoesNotContendOnOwnerRunEntry, plus the deterministic deletion and owner-replacement race tests in run_entry_atomic_test.go. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
WHAT: apply the same preflight-then-reload discipline to rename, delete, fork and adoption — with a third reload after lease acquisition for adoption. WHY: these verbs had the same exposure as prompt entry: each took the caller-selected per-session lock, and adoption additionally the cross-process mutation lease, before proving ownership. IMPROVEMENT: extends the foreign-contention and existence-oracle fix to every management surface, so the property holds for the whole caller-facing API rather than just the prompt path. Delete keeps absence and foreign ownership indistinguishable, so it cannot become an ownership oracle in the opposite direction — a caller must not learn that an id exists by observing that deleting it was refused rather than silently accepted. Three phases, not two, because state can change at each boundary: neither the preflight nor the pre-lease read is authoritative for the mutation that follows. PRESERVES: the ownership-disabled path is unchanged on every verb. PROOF: one non-contention test per verb — TestCallerSeparation_ForeignRenameDoesNotContendOnOwnerCoordination, ...ForeignDeleteDoesNotContendOnOwnerCoordination, ...ForeignForkDoesNotContendOnOwnerCoordination, ...ForeignAdoptionPreflightDoesNotContendOnOwnerCoordination, ...ForeignAdoptDoesNotContendOnOwnerCoordination — plus the pre-lock and post-lease owner-replacement races in session_management_test.go and adoption_scenario_test.go, on both the enforced and compatibility paths. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
WHAT: prove the schedule's stored origin session belongs to the schedule's owner immediately before delivery, under the origin's run-entry lock, with the enqueue inside that authorized scope — and report a refusal to the operator without naming the target. WHY: a schedule carries a caller-supplied OriginSessionID. Delivery rendered the note and enqueued it into that origin's durable queue, and only afterwards checked ownership as part of the state-aware delivery decision. IMPROVEMENT: before, a caller who knew another tenant's session id could create a schedule pointing at it and have scheduled content queued into that session — content injection across an ownership boundary, landing in a durable queue the victim's client drains. After, an origin that is missing, ownerless, or foreign produces no enqueue, no queue mark, and no run, and the three cases stay indistinguishable to the caller. An ownerless persisted schedule no longer inherits the scheduler's system identity when enforcement is on. Second improvement, operational rather than security: these refusals used to be completely silent, so an owned schedule whose origin had been deleted looked exactly like a healthy schedule that never fired — undiagnosable. Both arms now warn. The target is withheld (no schedule name, no origin id, no owner) because naming it would correlate one owner's schedule with another owner's session id; an operator who needs the specific stranded records reads them by name from GetStorageHealth's ownerless inventory, which is management-authorized. The three delivery tests moved from asserting "no diagnostics at all" to asserting non-correlation AND presence. Two of them already said "target-correlated" in their failure text while checking emptiness, so this encodes what they meant; the new form fails on silence, which the old one passed. PRESERVES: the no-verifier path renders and enqueues exactly as before. PROOF: TestScheduleDeliveryAuthorizesOriginBeforeEnqueue, TestScheduleDeliveryReauthorizesImmediatelyBeforeEnqueue, TestScheduleDeliveryRejectsOwnerlessScheduleUnderSystemContext, and TestScheduleDeliveryMissingOriginPreservesNoVerifierCompatibility. TestScheduleDeliveryAuthorizesOriginBeforeEnqueue is table-driven over all three refused origin shapes — missing, ownerless and foreign — asserting no enqueue, no queue mark, no run and no event for each. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
WHAT: replace the hand-maintained list of model-facing tool names with classification captured at the real composition registration sites, compared against Catalog.Tools() at assembly time. WHY: the guard that is supposed to prove no owned-access path ships unclassified depended on a literal list a human had to keep in step with registrations it could not see. It had already drifted: Parallel, BashStatus and FetchMcpResource were registered and absent from it. IMPROVEMENT: converts a convention into a structural check. Before, a new model-facing tool reaching a caller-owned resource could ship with nobody noticing, and the guard would still pass — the failure mode was silent and had already happened three times. After, a tool registered during assembly must carry a classification or assembly FAILS naming it, and a raw registration cannot bypass the comparison because the final check is against the catalog itself, not against what the registrar claims. The check runs for full-session, no-fs, explorer, specialist and member catalogs. This is the only commit in the branch that makes a whole CLASS of mistake impossible rather than fixing an instance of it. PROOF: TestCallerSeparation_RealCatalogClassifiesAllMemoryLifecycleTools, TestCallerSeparation_ClassificationKindsMatchRealRegistrationContext, and the negative proof TestCallerSeparation_RegisteredUnclassifiedToolFailsRealCatalogGuard, which registers a real extra tool and requires assembly to fail naming it. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
WHAT: refuse GrantTypeSystem at the memory CallerStore boundary. WHY: CallerStore derives its namespace from whatever principal the context carries. A background worker running under a syscaller system root therefore got a valid memory namespace and could read and write as though it were an ordinary caller. IMPROVEMENT: enforces that system principals are narrow infrastructure identities rather than a universal bypass (ADR 0204 decision 5). Before, any system worker — the child GC, the dream consolidators, the scheduler — had implicit access to caller-scoped memory it has no business touching, and a future worker would inherit that access silently. After, the attempt fails loudly. No legitimate system worker needs caller memory; each reaches its data through operations classified as shared-infrastructure. PROOF: namespaced_store_test.go, and TestCallerSeparation_Scenario4_InternalWorkersUseOnlyClassifiedAccess. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
WHAT: compute a schedule's caller-visible name from the authoritative stored owner, stripping only the namespace that owner's identity actually produces, instead of inferring provenance from the string's shape. WHY: the physical-to-presentation mapping matched a GRAMMAR — anything shaped like "schedule/<64 hex>\0..." had that prefix removed. A schedule name is caller-chosen. IMPROVEMENT: removes a case of authority derived from attacker-controlled input. Before, a caller could name a schedule to look like another owner's physical store key and have the prefix stripped wherever the literal name is used: fire ids, model-facing prompts, lifecycle events, metric labels. After, a name is only ever de-namespaced against the exact prefix its own stored owner generates, and anything else is refused rather than partially trusted. Ownerless records keep their literal names byte-for-byte. The impact was presentation-level rather than access-level — it did not grant access to another owner's schedule — but it let one caller's chosen string masquerade as another's derived key in output the model and operators read. PROOF: schedule_name_test.go, including the crafted physical-looking literal that previously had its prefix stripped. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
WHAT: refuse the check-then-Save fallback for schedule creation when ownership is enforced — at the manager boundary and again at build time. WHY: when the store did not implement ScheduleCreator, creation checked for an existing name and then saved, as two separate calls. Concurrent creates of the same name could both pass the check. IMPROVEMENT: with ownership on, that race is a cross-owner overwrite rather than a lost update: schedule keys are owner-namespaced, so the loser's write can land on a record belonging to a different tenant. Refusing at build time is the part that matters for deployment — an operator cannot accidentally run an identity-enforcing server on a backend that silently degrades to upsert, because the process will not start. PRESERVES: the ownerless compatibility path keeps check-then-Save, where the residual race is a lost update on a low-frequency human action and no ownership boundary is crossed. PROOF: TestCreateScheduleRejectsNonAtomicStoreWhenOwnershipEnforced, TestCreateScheduleUsesAtomicCreateWhenAvailable, TestCreateScheduleFallsBackToCheckThenSaveWithoutCreator. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
WHAT: expose a content-free preflight on the authenticated storage-health projection — per-family counts plus a bounded id/name sample of the ownerless sessions and schedules that enabling OIDC will strand. WHY: turning identity on makes every pre-existing ownerless record permanently invisible to every caller. There is no adoption path and no migration. An operator had no way to see what they were about to lose. IMPROVEMENT: makes an irreversible, data-losing configuration change observable BEFORE it is made, which is the difference between a planned cutover and a support incident. It also stops background workers from repeatedly retrying records they can never resolve, and filters ownerless rows out of cleanup planning under enforcement so a sweep cannot act on what it cannot authorize. Gated on the storage-management principal allowlist, not ordinary callers: this is deliberately the one surface that DOES name ownerless targets, because an operator performing a cutover is the correct audience for exactly the identifiers that delivery diagnostics withhold from everyone else. Hardened against a metadata pager that restarts its cursor or makes no progress, so the preflight cannot loop or double-count on a large store. PROOF: storage_health_test.go, cleanup_scenario_test.go, and TestCallerSeparation_Scenario4_OwnerlessCutoverIsObservableAndSafe (AC4.6). Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
WHAT: give the stale-session reconciler a registered system root and a purpose-built seam — a metadata-only enumeration of owned, running, non-scheduled candidates that accepts only that root — and gate the settle path on the same identity. WHY: the sweep called Service.ListSessions from a background goroutine holding a bare context. That listing scopes to the context's caller, so with no principal it filtered out every row. Separately, SettleIfStale was reachable with no authorization at all. IMPROVEMENT: two distinct wins. Security: SettleIfStale could previously be driven by anything holding a Service reference, with no identity check, on any session id — now it accepts one specific system root and rejects everything else, and skips ownerless records under enforcement rather than adopting them. Correctness: the crash-orphan repair this sweep exists for was SILENTLY DOING NOTHING in every OIDC deployment — it enumerated zero candidates every tick and logged nothing, so a crash-orphaned session stayed "running" forever with no signal. That is a bug the ownership work introduced upstream and this commit repairs. Reclassifies SessionStale and SettleIfStale from exempt to shared-infrastructure, which is what they now honestly are. PROOF: stale_maintenance_test.go, session_reconcile_test.go, and TestCallerSeparation_Scenario4_SystemPrincipalIsNotUniversalBypass. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
WHAT: acquire each team member's cross-process lease BEFORE AddMember publishes its durable snapshot, in both enrolment paths, unwinding partial acquisitions on failure; and release those leases in CleanupTeam. WHY: two defects, one introduced by this branch and one pre-existing. (1) Publishing at enrolment (see "publish every new session create-only") put a retention-eligible SessionKindTeamMember record in the shared store while the lease was still taken later, in RunTeam. Initial members are enrolled during CreateTeam, so the gap is unbounded — and infinite for a team that is never run. A peer replica's retention could delete a live team's member session. (2) CleanupTeam never released member leases at all, so each ran team leaked a lease and a renewer goroutine until process exit, and kept member ids claimed against peers entitled to take them over. IMPROVEMENT: closes a cross-replica data-loss window in multi-replica deployments (mecak8s, or two mecated replicas sharing a store and lease directory), and stops an unbounded per-team resource leak in any long-lived server. Ordering the lease first also means a refused lease writes nothing, so the abandon path no longer strands an orphaned member snapshot with no team. COSTS, deliberately accepted and flagged for review: CreateTeam now performs N lease round trips, can fail with ErrSessionLeasedElsewhere, and is drain-gated — during a rolling deploy a draining replica refuses new teams. I judged all three correct; they are behaviour changes a reviewer should agree with explicitly. RunTeam's existing acquire loop is untouched and becomes an idempotent backstop. The CleanupTeam release runs OUTSIDE s.mu because releaseLease re-takes it and sync.Mutex is not reentrant; the obvious defer refactor reintroduces that deadlock, since defers run LIFO. PROOF: TestBuildChildLeaseBlocksRemoteRetention — 9 failures in 20 runs without -race before this change, 0 in 20 after. -race perturbs the timing enough to usually hide it, which is why CI stayed green. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
WHAT: route GetTranscript through the same load-and-authorize funnel as GetSession when ownership is enforced, and give that funnel an operator diagnostic that names no target. WHY: GetTranscript distinguished a decode failure from an absence, returning an actionable storage error for a malformed record. A failed decode also leaves no trustworthy owner to compare against, so there is nothing to authorize with. IMPROVEMENT: removes an existence oracle. Before, a caller could tell that a session id EXISTS but is unreadable, versus does not exist — precisely the distinction absence-shaping is meant to deny, and reachable by probing ids. After, absence, foreign ownership and an unreadable record are one answer. Second improvement, and the reason this is not purely a subtraction: that funnel logged nothing, so extending it to transcripts would have extended the silence — a storage outage and mass deletion become indistinguishable from BOTH sides at once, which is an operability failure rather than a security one. Concealment is owed to the caller, not the operator log. A genuine not-found stays silent so probing cannot generate log volume; a real store failure now warns, carrying neither the id nor the store's error (which routinely embeds the record path), so its RATE is the outage signal and nothing correlates. PRESERVES: the ownerless path keeps full detail, where no concealment is owed. PROOF: TestTranscriptOwnershipModeConcealsLoadFailure (unmodified — it forbids target-correlated content, which this respects) and TestStoreFailureIsVisibleToTheOperatorButNotCorrelated. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
WHAT: close the application-isolation scope of issue #368 — reconcile the acceptance plan with what the implementation actually proves, restore a deleted acceptance criterion, and align the deployment docs with it. WHY: the plan had been marked landed by DELETING AC4.5, the criterion requiring a concrete raw-driver boundary, while leaving its test in the tree still commented as pinning an AC that no longer existed. Item 12's own AC12.4 asked for that boundary to be PROVEN rather than asserted, which deleting the criterion cannot satisfy. IMPROVEMENT: the plan now claims exactly what is true, no more and no less — which on a security capability is the difference between documentation and misinformation. AC4.5 is restored, scoped to what its test genuinely establishes: rendered with oidc.enabled=true the mecak8s chart produces a NetworkPolicy restricting raw-driver ingress to the agent workload, and the default render produces none. That is a MANIFEST-level deployment control, not caller enforcement and not a runtime proof — effectiveness depends on a policy-enforcing CNI, and #368's tenant is an OIDC subject holding a token, who is not a cluster peer at all. The test is renamed from RawDriverIsTenantInaccessible, which claimed a property it never checked, to RawDriverIngressIsRestrictedToTheAgent. mecak8s.md told operators raw-driver enforcement was handled "deployment-boundary only" by that policy while the plan disclaimed its sufficiency; an operator reads the deployment doc, not the acceptance plan, so the two now agree. The stale accumulator pointer is corrected: acc/caller-separation landed as f25a494 and is superseded. Raw-driver caller enforcement remains deferred to issue #452 / ADR-0213, recorded as a known residual with an owner rather than an unowned gap. PROOF: task ac-trace-strict (30 ACs, 0 failures), task docs. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
WHAT: the two metadata-pager walks added by this branch detect a stalled pager with page.NextCursor.ModifiedAt.Equal(cursor.ModifiedAt) && ID equality, instead of struct equality on the cursor. WHY: port.SessionMetadataCursor embeds a time.Time, and == on a time.Time compares the monotonic reading and the location POINTER, not the instant. Two cursors denoting the same position can therefore compare unequal, so the guard silently never fires and a backend that stops making progress loops instead of erroring. IMPROVEMENT: restores the bound these walks were written to have. Without it the stale-session reconciler and the ownerless cutover inventory can spin against a misbehaving or buggy pager — the inventory being the one an operator runs before flipping enforcement, i.e. exactly when a hang is least welcome. PRESERVES: behaviour against a well-behaved pager is unchanged; this only makes the escape hatch reachable. Matches the two older copies of the same walk, internal/app/childgc.go and internal/adapter/server/cleanup.go, which already compare the key. Found by external panel review. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
fmt.Errorf with a constant string and no format verb. errors imported already. Found by external panel review. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
The "Named tests landing in this plan" index still named TestADR_0102_IssuerSubjectPairIsOwnerIdentity and TestCallerSeparation_Scenario1_CreationBindsVerifiedOwner. Both were renamed on their verify: lines in this branch but not in the index, and ac-trace reads verify: lines only — so DoD item 4 passed green while the index pointed at dead names. Corrected to TestADR_0212_VerifiedIssuerSubjectPairIsOwnerIdentity and TestCallerSeparation_Scenario1_AtomicCreationBindsVerifiedOwner. Swept every Test* name in the document against every func Test* in internal/ and engine/: these two were the only dead ones, and none remain. Found by external panel review. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
.matlatlignore already excludes root-level review-*, handoff-* and handover-* working notes from the documentation graph. Root-level report*.md is the same kind of thing — an external review artifact, not product documentation — and an untracked one currently makes task docs:check fail with an orphan. llms.txt is regenerated for the plan-index test-name correction. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
WHAT: add agent.WithTeamOwner, a SupervisorOption carrying the verified caller, and wire it from Service.CreateTeam so AddMember stamps the owner on members of a directly server-created team. WHY: CreateTeam builds its supervisor with ZERO parent caps — deliberately, so a member's unresolved permission ask headless-auto-denies instead of reaching a human who isn't there. Owner attribution rode in that same parentCaps struct, so inheritOwner no-opped and the member snapshot was published with Owner == nil, even though the Service holds the caller and stores it on teamState. IMPROVEMENT: closes an authenticated storage leak that this branch made unbounded. Reads already failed closed for everyone — including the team's own owner, who could not read its members — so this was never a cross-tenant read. The damage was durability: every retention path in this branch deliberately skips ownerless rows, so these records could never be GC'd, cleaned or settled, and publishing at enrolment (see "publish every new session create-only") meant any authenticated caller could mint them in a loop without ever running a team. It also corrupted StorageHealth.Ownerless, the operator's pre-cutover drain gate added in this same branch, by making it grow under normal use — so "inventory reached zero" stopped being a usable signal to flip enforcement. The ownerless behaviour itself predates this branch; publishing at enrolment is what turned it from "a run leaves one snapshot" into an unbounded mint. PRESERVES: the zero-caps posture — WithTeamOwner supplies the OWNER ONLY, never surfaceAsk or the child-ask adjudicator, and must not become a general caps channel. A team created from a parent run is unaffected: caps.owner wins, the same split WithRootAuthority already documents. An ownerless deployment stamps nothing and is byte-identical. SpawnTeammate inherits the fix through the same supervisor. RESIDUAL: ownerless member snapshots already written by an existing deployment stay unreadable and unreapable. That is the stranded-legacy population the ownerless cutover inventory exists to surface, so no migration is added here. Engine API: WithTeamOwner is additive (Added = minor); engine/api/agent.txt regenerated and engine/CHANGELOG.md classified per COMPATIBILITY.md. PROOF: TestCallerSeparation_GRPCTeamMembersAreOwnerStamped — fails before this change with an ownerless snapshot, and additionally asserts the owner can read its own member back through GetSession. Found by external panel review. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
WHAT: add the NUL-framing clause to admissiblePrincipal, the edge's
re-validation of an already-verified principal, backed by a new exported
session.Principal.IdentityWellFramed.
WHY: owner scope keys are derived as hash(issuer + NUL + subject), so a NUL
inside either component makes distinct principals collide on ONE namespace —
("a","b\0c") and ("a\0b","c") produce the same key. PrincipalFromClaims already
refuses such claims, but that is the SHIPPED validator's guarantee, not the
edge's: cfg.Validator is an injection seam, and a deployment supplying its own
validator could hand the edge a colliding pair that every downstream owner-key
derivation would then honour.
IMPROVEMENT: moves the rule from "the one constructor we ship happens to enforce
it" to "the edge enforces it for every validator". This is defence in depth, NOT
a live exploit fix: on a stock deployment PrincipalFromClaims is the only
constructor in play and already refuses these, so nothing reachable changes
today. Its value is that the guarantee stops depending on which validator is
wired.
SCOPE, stated plainly: ~11 owner-key derivation sites still concatenate identity
components themselves rather than routing through one helper — memory
namespacing, schedule namespacing, storage-management, the two migrations,
skills lifecycle, retention planning, and four unhashed identity comparisons.
This commit does not touch them. They are unreachable behind this clause for any
principal arriving through the edge, but the rule still has more than one home;
consolidating them is follow-up work, deliberately not bundled here.
PRESERVES: PrincipalScopeHash returns identical digests for every well-framed
principal, so no persisted owner-scoped key moves. The well-framed control in
the test guards against the clause becoming a blanket deny.
Engine API: IdentityWellFramed is additive (Added = minor); engine/api/session.txt
regenerated and engine/CHANGELOG.md classified per COMPATIBILITY.md.
PROOF: TestAdmissiblePrincipalRefusesReservedOwnerKeySeparator — verified by
mutation: with the clause removed both NUL cases are admitted and the test goes
red, while the well-framed control still passes.
TestAdmissibleFramingMatchesTheOwnerKeyDerivation states the reason the rule
exists, asserting the refused pair is exactly a pair that collides on one key.
Found by external panel review (four reviewers, independently).
Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
WHAT: reserve a MaxTeams registry slot BEFORE CreateTeam enrols its initial roster, and unwind published member snapshots as well as acquired leases on every enrolment failure path. WHY: enrolment acquires each member's cross-process lease and publishes a durable member snapshot. The capacity check ran AFTER that loop, so a refused create returned ErrTooManyTeams having already written both. The comment above the loop promised the opposite — "we return without inserting it into s.teams, so it neither leaks nor counts against the cap" — and that promise stopped being true when this branch moved publication to enrolment and added leases; I edited that very comment without noticing the check below it. IMPROVEMENT: a refused create now leaves nothing behind. Before, each rejection stranded (1) member session snapshots no team references, which retention will reap but only after the fact, and (2) cross-process leases that no peer replica could take until expiry or shutdown. A caller could drive both in a loop simply by creating teams against a full registry — the cap, whose whole job is to bound what one caller can consume, was the thing being used to consume it. Two failure paths existed, both now covered: capacity (removed entirely — the slot is claimed before any lease or write) and a mid-loop lease/AddMember failure, which previously released leases but left earlier members' snapshots published. COST, accepted and flagged for review: an in-flight CreateTeam now OCCUPIES a registry slot. Two concurrent creates against a nearly-full registry previously both enrolled and one lost at registration; now the second is refused immediately — the same outcome in the common case, and cheaper. But if the first create subsequently fails, the second caller was refused a slot that then became free. That transient over-refusal is unavoidable if the cap is to be claimed before any lease or durable write, which is the point of this commit; it is recorded here rather than left to be discovered in production. PRESERVES: the cap semantics are unchanged — reservations count toward it, so concurrent creates cannot together exceed MaxTeams, and the reservation is released on every failure path via defer. Snapshot cleanup is best-effort and quiet: a store with no port.PrunableStore leaves the records for retention, which can reach them because they now carry the creating caller's owner. PROOF: TestCreateTeamRefusedAtCapacityLeavesNothingBehind — verified by mutation: with the check moved back after enrolment the refused create publishes a stranded member snapshot and the test names it. Found by external review. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
jhrozek
force-pushed
the
acc/caller-separation-hardening
branch
from
August 25, 2026 08:53
740b8b9 to
7fde597
Compare
17 tasks
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Follow-up hardening for issue #368 /
ADR-0212, from an audit of the
caller-separation landing (
f25a4947) plus two rounds of external review.Twenty-two commits, each closing one hole, each with its own proof.
Refs #368
What this is NOT
It does not create a single authorization choke point.
ownsResource/authorizeSessionalready existed and this branch does not touchinternal/adapter/server/ownership.goat all. What it does is make that existingdecision reach the paths that were skipping it, stop it consuming
attacker-influenced input, and close the windows around it.
Saying so up front because the branch name implies otherwise, and a reviewer looking
for a new authorization system will not find one.
The holes closed
Live wherever OIDC is enabled (
cmd/mecated,cmd/mecak8s); inert otherwise.Saveis an upsert, so an id collision silently destroyed another tenant's session or child transcript. Delegation ids derive from provider tool-call ids — model-influenced.(iss="a", sub="b\0c")and(iss="a\0b", sub="c")hashed to one namespace; both obtainable from a real token.SettleIfStalePlus two pre-existing bugs found on the way: a per-team lease + goroutine leak in
CleanupTeam, and operator blindness during a storage outage (absence and a brokenstore were indistinguishable from both sides).
Read these two together
fix(server): publish every new session create-onlymoves durable child publicationearlier, which opened a window where a team member was visible but unleased.
fix(server): lease team members before publishing themcloses it. Commit 3 is thelargest security delta in the branch; commit 13 is its correction. Neither reads
correctly alone, and both messages say so.
Found by external review, after the branch was otherwise green
Two ship-blockers, both in code this branch's own verification passed clean, both
rooted in the same change —
publish every new session create-onlymoved durablechild publication to enrolment time, and the guards around it were not updated to
match:
CreateTeamruns withzero parent caps by design, so
inheritOwnerno-opped. Reads failed closed foreveryone including the team's own owner, retention skipped the records, and any
authenticated caller could mint unreapable storage in a loop — corrupting
StorageHealth.Ownerless, the cutover gate this same branch adds.MaxTeamswaschecked after enrolment had already acquired leases and published durable
records. The cap that exists to bound one caller's consumption was the thing
being used to consume.
Both are fixed with mutation-verified tests. They are the reason the review
guidance below is specific rather than even.
Where to spend review time
Not evenly.
git range-diffagainst the pre-rebase branch shows the rebase changed171 lines in commit 3 — it contains six hand-resolved conflicts in delegation
code, because upstream landed delegated-authority on the exact lines this branch
touches. Everything else absorbed ≤110 lines, five commits came through untouched.
The single riskiest resolution: in
subagent.go, create-only must stay insideif !resuming— a resume loads an existing snapshot, so re-creating it would fail alegitimate path with
ErrSessionAlreadyExists. Pinned byTestSubagentResumeDoesNotRepublishTheChild, mutation-verified.Second: read
CreateTeam/AddMemberas a whole, not guard by guard. Bothexternal blockers landed there, and both were the same shape — publishing a
durable, owned, leased record at enrolment interacts with every later check in
that function. Those checks were updated one at a time as each was pointed out;
the function has not been audited end to end, and a third guard nobody has
thought of is a live possibility.
Behaviour changes needing explicit agreement
CreateTeamis now drain-gated: a draining replica refuses new teams during rolling deploys.CreateTeamcan now failErrSessionLeasedElsewhere, and performs N lease round trips.CleanupTeamreleases member leases (previously leaked until process exit).I judged all three correct. They are not visible in a diff and should be agreed, not discovered.
Honest scope limits
PrincipalScopeHashis hardening, not an exploit fix. An unsafe identity couldnever alias a valid owner — a valid pair hashes exactly one NUL, an unsafe one two
or more. Its value is moving the invariant to the function that depends on it.
owner identity off its own wire unverified. AC4.5 is restored scoped to what its test
actually proves — a Helm-rendered NetworkPolicy is a manifest-level deployment
control, not caller enforcement.
branch-introduced; the fix needs a new cross-layer seam and its own discussion.
Verification
lint,test,ac-trace-strict(30 ACs, 0 failures),docs,api:check.