Skip to content

fix(auth): a shared-pid token must name a session the pid still hosts - #15529

Merged
iamwhatever merged 1 commit into
mainfrom
fix/token-bound-to-tenancy
Sep 30, 2026
Merged

iamwhatever merged 1 commit into
mainfrom
fix/token-bound-to-tenancy

Conversation

@chenmingwei23

Copy link
Copy Markdown
Contributor

Problem / Motivation

Goal: make a shared-pid session token unusable by a neighbour who lifted it, by requiring the key it names to be a session the process still hosts.

On a shared runtime one kiro-cli process hosts several ACP sessions, so the peer's pid names none of them. The dashboard's unix-socket peer check closes that with two facts: the pid's published roster records the declared X-Session-Key, and an X-Session-Token verifies to exactly that key.

The token is a bearer credential living in the runtime's environment. Any same-uid process that can read /proc/<pid>/environ lifts it and satisfies the name check with it — the token proves which session the caller claims to be, never that the session is on the process the call arrived from. The roster it is compared against does not close the gap either: it is a snapshot written to disk once per turn, in a directory the agent sandbox can write, so a session it lists may be long gone.

Why it matters to the user

The key admitted on this arm is what derive_caller_app derives app confinement from. A neighbour that borrows a session's token inherits that session's reach over the internal API — its sessions, its crons, its memory — and every one of those calls is attributed to the borrowed name in the audit trail, so the owner appears to have made them.

Not a goal

  • The bearer shape itself. A token remains a bearer credential; this narrows who can spend a stolen one from "any session whose environment is readable" to "a session this process actually hosts". The recycled-ancestor-pid half is #14646.
  • The degrade arm. A caller whose ancestry resolves to nothing still proceeds under today's semantics. That arm exists for warm-pool runtimes before their claim, cron scripts and pooled MCP backends, and denying there would break callers that work today.
  • 1:1 pids. Not one byte. A pid hosting one session never reaches the shared arm, so the unpooled path is untouched.
  • A cancelled turn's in-flight tool call. A sub-agent's tenancy is scoped to the turn (D10), so a tool call already dispatched by kiro-cli can land after a cancelled or timed-out turn released it, and that call is now refused where it was admitted. Accepted deliberately: that turn is already being destroyed, and a caller handling 403 there is in the same position as one handling the AcpProcessDied the same teardown produces. Widening the window would mean a binding that outlives the turn, which is the stale-binding shape D10 rejects.
  • The reconciler and #15325's files. Untouched.

What changed

Symptom: a same-uid neighbour makes internal API calls as another session.
→ It declares that session's key and presents that session's token.
→ Both checks pass, because a token is readable from the environment and the roster is a per-turn file.
→ Neither check asks the one question the neighbour cannot answer: is that session on this process?
→ Root cause: nothing in the check reads the gateway's own record of where it placed each session.

The gateway has exactly that record, in memory, in this process, in two tables an agent cannot edit:

table who is in it why it alone is not enough
RUNTIME_OWNERSHIP (leases) a session that owns its runtime a sharing sub-agent holds no lease
RUNTIME_TENANCY (tenancies) a sharing sub-agent, a task run, the OAuth mint child a chat session holds no tenancy
  • runtime_ownership.py — RuntimeOwnership.lease_keys_on_pid and RuntimeTenancy.tenant_keys_on_pid answer which sessions, beside the counts the kill gate already reads; session_keys_bound_to_pid unions them. Live entries only, the same rule the gate's counts follow: a dead runtime names nobody.
  • _Claim carries a session_key, and claim() / claim_runtime_tenancy() take it as an additive keyword. Not parsed back out of holder: that is a label written for a human reading a refusal log and free to reword, and an auth decision must not rest on a log format. A claimer with no session — the mint child — passes nothing and binds nothing, while still being defended by the gate exactly as before.
  • acp/session_provider.py — _claim_shared_turn passes session_key=self._session_key, the same key this session's stubs declare in X-Session-Key. For a sharing sub-agent that claim is the only record naming it: it holds no lease, and SessionManager.runtime_pids() never registers it.
  • dashboard/token_auth.py — _bound_session_keys_on_chain walks the peer's ancestry peer-first and the nearest pid either table knows decides. The peer is an MCP stub whose kiro-cli ancestor is the process sessions are placed on, so the answer is never on the peer pid itself. _attest_shared consults it after the token resolves: a non-empty answer that omits the declared key is 403 peer_session_unbound + SEL dashboard.peer-session-unbound; an empty answer is no evidence and changes nothing. The admitted record now carries binding=confirmed or binding=no evidence, so the trail separates the hardened path from the one that fell open.

Fail-open is the direction on purpose, and the tests pin it: the tables describe runtimes this gateway placed sessions on, so a warm-pool runtime before its claim, a pooled MCP backend, a cron script and anything from another install are all absent from them while being entirely legitimate. An empty answer that denied would 403 every one of those. The token check is untouched, so this arm is never weaker than before — only stricter where there is positive evidence.

Tests

test/test_dashboard_peer_auth.py 50 → 58 passed. Three arms plus five contracts:

test pins
admits_a_co_tenant_its_tables_still_place_here token names the session and a table places it here → 200, binding=confirmed
denies_a_token_for_a_session_the_pid_no_longer_hosts valid token, claim released → 403 peer_session_unbound
silent_tables_keep_todays_semantics tables answer empty → 200, binding=no evidence
union_both_tables_and_walk_the_chain both tables read; ancestor decides, not the stub pid
no_evidence_when_a_table_raises a probe that could not ask is not a verdict
no_session_key_binds_nothing the mint child is defended but binds no session
dead_runtime_binds_no_session death releases ownership on both tables
binds_the_session_its_stubs_declare the turn records its own key, measured before / during / after

Neighbours unchanged: test_runtime_ownership.py, test_acp_session_provider.py, test_acp_session_provider_shutdown.py — 222 passed with the file above. Ratchets test_pid_reader_ratchet.py + test_kill_chokepoint_ratchet.py 24 passed, both numbers unchanged.

Mutations — 10 applied, 10 caught, every file restored byte-identical. The harness selftests itself first by breaking a pinned record on purpose and requiring the parser to name the expected test, so a silent run cannot read as a pass.

mutation defect reintroduced test that went red
W1 admit any key the token names denies_a_token_for_a_session_the_pid_no_longer_hosts
W2 read an empty answer as a verdict silent_tables_keep_todays_semantics
W3 bind from leases only union_both_tables_and_walk_the_chain
W4 bind from tenancies only union_both_tables_and_walk_the_chain
W5 ask only the peer pid, not its ancestor union_both_tables_and_walk_the_chain
W6 let a table's exception escape no_evidence_when_a_table_raises
W7 report a keyless claim as a bound session no_session_key_binds_nothing
W8 keep naming leases on an exited runtime dead_runtime_binds_no_session
W9 keep naming a tenant of an exited process dead_runtime_binds_no_session
W10 take the turn's tenancy without recording its session binds_the_session_its_stubs_declare

Manual verification

Driving a real AcpSessionProvider shared turn against the real tables, with the principal holding a lease on the same runtime, and reading the binding at the three points a tool call can arrive:

point declared key bound keys the tables name on the pid
before the turn no dashboard:chat-1-abc
during the turn yes dashboard:chat-1-abc, subagent:chat-1-abc-child
after the turn no dashboard:chat-1-abc

The window is exactly the turn, which is where every MCP tool call lands: mcp_core is the only client that sends X-Session-Key from a sub-agent's process, and it has no atexit hook, no background thread and no timer, so each of its requests is driven by a tool call inside a model turn. The sub-agent's own teardown (_teardown_run_session_impl → shutdown()) runs in the gateway process and never crosses the socket, and spawn_continue is a new turn with a new claim. Gates run locally: black, flake8, mypy (Success: no issues found in 2 source files), comment-history (passed), pr-description-check.sh (success).

Any other suggestions

  • _claim_shared_turn still swallows an unexpected exception at debug level, and with this change a claim that silently failed costs the turn its binding rather than only its defence. Unreachable in practice — claim() does a guarded getattr, a guarded liveness probe and dict work, and re-raises RuntimeTeardownCommitted — but the level is worth revisiting when the wider bearer fix lands.
  • PeerTenancy.admits / membership_complete and this binding now answer three overlapping questions about one pid. Worth folding once the roster stops being a disk snapshot.

Pattern harvest

A credential that proves who the caller is does not prove where the caller is, and a check that conflates the two is satisfied by anyone who can read the credential. Bind the name to a record of placement that the holder of the credential cannot write.

The record has to be the one the attacker cannot edit, which ruled out both obvious candidates: the published roster is a file in a sandbox-writable directory, and the session manager's snapshot omits sharing sub-agents entirely. The in-process ownership tables were the only account of a pid's tenancy an agent cannot reach.

And the direction of the unknown decides the whole design: "these tables place the session elsewhere" is evidence, while "these tables say nothing" is not, so only the first may deny. Writing it the other way would have turned a hardening into an outage for every caller outside this gateway's own placements.

Rule candidate: when a check gains a second source of truth, decide what its SILENCE means before deciding what its answer means — and if silence is the ordinary state for a legitimate caller, silence may not deny.

Refs #14357 #14646

@chenmingwei23
chenmingwei23 requested a review from a team as a code owner September 30, 2026 18:22
On a shared runtime the peer check admits a declared X-Session-Key when the
pid's roster records it and a per-session token verifies to it. The token is a
bearer credential in the runtime's environment, so a same-uid process that can
read /proc/<pid>/environ presents a sibling's token and satisfies that check,
and the roster it is compared against is a per-turn snapshot on disk.

Require the declared key to hold a LIVE entry in one of the two ownership
tables for the peer's ancestry as well: the lease table for a session that owns
its runtime, the tenancy table for a sharing sub-agent or task run that does
not. Tables that cannot speak about the pid answer empty, which stays today's
semantics; only a non-empty answer that names other sessions and not this one
denies, with 403 peer_session_unbound and an SEL record. A 1:1 pid never
reaches this arm and is unchanged.

A sub-agent's turn now records which session it is for, so the tenancy binds
the key its stubs declare rather than only defending the process.
@chenmingwei23
chenmingwei23 force-pushed the fix/token-bound-to-tenancy branch from 59458cf to 0afb441 Compare September 30, 2026 18:44
@github-actions github-actions Bot added the readiness: checking Automated validation is still running label Sep 30, 2026
@github-actions

Copy link
Copy Markdown
Contributor

Design Review (Fable 5) — 🟡 CONCERNS

Design-level review of 0afb441f337085fdd887686705cd588ae187a6ad — updated in place on each push. A BLOCK verdict blocks PR readiness; PASS/CONCERNS are advisory.

Design-Verdict: CONCERNS

A silently skipped turn claim now hard-fails the whole turn: auth admission rides on a kill-gate record that was designed to fail quiet.

Watch

_claim_shared_turn still ends with except Exception: logger.debug(...); return None (src/kiro_crew/acp/session_provider.py:237-239) — the turn proceeds unrecorded. Before this PR that degraded only kill-gate defense; now the tenancy entry is the only record admitting the sub-agent's declared key, and the principal's lease keeps the tables non-empty on that pid, so an unclaimed turn is read as positive evidence ("names OTHER sessions and not this one") and every stub call that turn gets 403 peer_session_unbound — with only a debug log explaining why. The PR's fail-open story covers silent tables and the cancelled-turn window, but not "the tables speak while this session's own claim silently failed to land." Either fail the turn loudly when the claim cannot be recorded (the same shape as the RuntimeTeardownCommitted → AcpProcessDied arm), or document why claim() cannot raise past teardown in practice.
Clears when: the swallowed-claim path either aborts the turn or is shown unreachable, pinned by a test where claim() raises and the turn's stub calls are not 403'd as unbound.

[DESIGN-REVIEWED] 0afb441

Description read

[DESCRIPTION-READ] 0916f3d9359d55b1ed16a68f55b956b5d4c7f99db3233e43eb22becf006011db

That sha256 names everything this verdict read: the PR description, plus the 1 evidence file(s) the workflow collected from it and handed this review. It covers that evidence because the media strip replaces every attachment URL with the same placeholder, so an edit swapping one attachment for another would leave the description's captured text identical while what this review judged changed. Recompute it with .github/scripts/pr-description-capture.sh over the same inputs; if it differs, the description or that evidence changed after this verdict was formed and any finding drawn from either is unproven.

@github-actions

Copy link
Copy Markdown
Contributor

First Principles Review (Fable 5) — ✅ PASS

Premise-level review of 0afb441f337085fdd887686705cd588ae187a6ad — why this exists and whether the shipped surface is the smallest honest version. Updated in place on each push. A BLOCK verdict blocks PR readiness; PASS/CONCERNS are advisory.

First-Principles-Verdict: PASS

Verify the turn-scoped tenancy spans every legitimate stub call — a tool call landing after release is refused on positive evidence, beyond the declared cancelled-turn case.

Not justified as shipped

  • Item 3 — rides along: the binding=confirmed/no evidence annotation on the admit path is observability, not the fix; declared ("the trail separates the hardened path from the one that fell open") and harm-free.

What this change ships

Inventory (5 items) — 4 justified

Intent: make a lifted shared-pid session token unusable unless the gateway's own in-memory tables place that session on the calling process — a FIX.

  1. A shared-pid call declaring a session the tables place elsewhere is now refused 403 peer_session_unbound — justified
  2. That denial writes a SEL event naming the pid and how many sessions were bound there — justified
  3. Admitted shared-pid calls' audit record now carries binding=confirmed or no evidence — rides along (declared observability on the admit path)
  4. A sharing sub-agent's turn now records its own session key in the tenancy table — justified
  5. runtime_ownership exports session_keys_bound_to_pid plus per-table key getters — justified

Counts run: claim_runtime_tenancy has 2 callers (mint passes no key by design); session_keys_bound_to_pid has 1 consumer (token_auth.py:1814). The existing _live_session_keys_on_chain (token_auth.py:1717) is not a duplicate: its own docstring says the manager's set "is NOT a closed account of the pid's tenancy" and omits shared sub-agents — the population the new tables cover. Defect provenance: the deny scenario returns 200 on base; siblings (recycled-pid half, degrade arm) are deferred with linked issue #14646. Fail-open leaves every default in place, so no lens-9 shape decision is required.

[FIRST-PRINCIPLES-REVIEWED] 0afb441

Description read

[DESCRIPTION-READ] 338680d059deaebf63e3ae18d37e3db9e486f6ea9719ba49d0020bae68186a8b

That sha256 names the PR description this verdict read. Recompute it with .github/scripts/pr-description-capture.sh; if it differs, the description changed after this verdict was formed and any finding drawn from the description is unproven.

@github-actions

Copy link
Copy Markdown
Contributor

GPT 5.6 Review — ✅ no blocking findings

GPT 5.6 completed its review of 0afb441f337085fdd887686705cd588ae187a6ad and found no blocking issues.

This comment is updated in place on each push.

Review details

No findings.
[GPT-REVIEWED] 0afb441

False positive or not applicable? A repository writer can comment:
/ai-review override gpt 0afb441f337085fdd887686705cd588ae187a6ad: <one-sentence reason>

@github-actions

Copy link
Copy Markdown
Contributor

Opus 5 Review — ✅ no blocking findings

Reviewed 0afb441f337085fdd887686705cd588ae187a6ad — this comment is updated in place on each push.

Review details

No findings.

[OPUS-REVIEWED] 0afb441

Verdict parsed from the review's SHA-scoped output markers for commit 0afb441f337085fdd887686705cd588ae187a6ad.

False positive or not applicable? A repository writer can comment:
/ai-review override fable 0afb441f337085fdd887686705cd588ae187a6ad: <one-sentence reason>

@chenmingwei23

Copy link
Copy Markdown
Contributor Author

Disposition for the Design Review finding on 0afb441f337085fdd887686705cd588ae187a6ad.

Accepted as real, deferred rather than folded in: #15557.

The finding is correct. _claim_shared_turn's except Exception: logger.debug(...)
was written to fail quiet when a missing tenancy cost only kill-gate defence, and
this PR makes that same entry the only record admitting a sharing sub-agent's
declared key — so a silently unclaimed turn is read as positive evidence and 403s
for its whole length on one debug line. #15557 carries the reviewer's two remedies
and its clears-when verbatim.

Deferred because the path is not reachable today and the remedy is not free.
RuntimeTenancy.claim does a guarded getattr, a guarded liveness probe and dict
work; the one exception it raises, RuntimeTeardownCommitted, is re-raised by the
arm directly above the swallow rather than caught by it. Meanwhile this board is
otherwise clean on this commit — First Principles PASS, GPT 5.6 no findings, Opus 5
no findings, Design CONCERNS and First Principles both advisory — and a push
re-rolls every one of those non-deterministic verdicts. Trading four clean reviews
for a change to an unreachable path is a net loss, so the fix goes to its own PR
where it can be reviewed on its own merits.

The cancelled-turn window the same theme touches is a separate, already-accepted
trade recorded under ## Not a goal in this PR's description.

@github-actions github-actions Bot added readiness: passed Eligible automated validation passed for the current revision and removed readiness: checking Automated validation is still running labels Sep 30, 2026
@iamwhatever
iamwhatever merged commit 0b475bf into main Sep 30, 2026
97 checks passed
@iamwhatever
iamwhatever deleted the fix/token-bound-to-tenancy branch September 30, 2026 23:54
@github-actions github-actions Bot removed the readiness: passed Eligible automated validation passed for the current revision label Oct 1, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants