Skip to content

fix(mcp): stop answering MCP identity per process on a runtime hosting several sessions - #17524

Merged
chenmingwei23 merged 2 commits into
mainfrom
fix/claim-per-session
Oct 9, 2026
Merged

chenmingwei23 merged 2 commits into
mainfrom
fix/claim-per-session

Conversation

@chenmingwei23

@chenmingwei23 chenmingwei23 commented Oct 6, 2026 •

Copy link
Copy Markdown
Contributor

Problem / Motivation

Goal: a worker's MCP tool call stops being attributed to a different session that happens to share its runtime process, so one worker can no longer read or write another worker's ledger item.

When one kiro-cli runtime hosts several ACP sessions, two identity sources still answer per process, so a tool call made by one session can resolve to a co-tenant of that runtime.

Site 1, gatewayd retargets a tokenless stub connection PID-wide. _apply_claim narrows a claim to the session its stub_session_token names, but a connection carrying no token is retargeted by any claim on its pid:

if session_token and conn.stub_session_token and conn.stub_session_token != session_token:
    continue

That is correct when the pid hosts one session, because the process tree really does name it. When the pid hosts several, the tree names the runtime, the retarget is a guess, and the stub it lands on answers as whichever session claimed last.

Site 2, KIROCREW_SESSION_KEY is process-keyed and unguarded. mcp_core._resolve_session_key_strict returns the env var without consulting how many sessions the host pid serves. The var is stamped once per runtime and inherited by every MCP child of it, so on a shared runtime it names one tenant and cannot say which one is calling.

Source 3 of that same resolver, the signed session_pid_<pid>.txt lookup, already refuses this exact case. session_pid_sig states the reason verbatim: "without it the pid answers with whoever published last." Source 2 is equally process-keyed and has no such guard.

Why it matters

A misattributed caller does not fail visibly, it writes the wrong session's state. With the work ledger that means a worker's work_brief returns another worker's item and its work_report lands on that item, so one item collects a stranger's report while its own worker's never arrives. The same misattribution reaches anything else keyed by session: spawn_run parentage, session-scoped memory writes, monitors.

Several sessions per process is not hypothetical on main today. agent.session_sharing puts a spawn_run subagent on its parent's process, and the open chat-runtime-sharing work (#15325) puts N top-level chat sessions on one.

Not a goal

  • Does not fix the chat-runtime-sharing mount leak. An end-to-end reproduction found a separate mechanism where a co-tenant's tool call is served by the most recently mounted MCP server set, so identity follows the newest session on the process. It reproduces with the MCP gateway both on and off, and no resolver guard can repair it. That is tracked and being fixed separately against feat(acp): let eligible chat sessions share one runtime behind a cap #15325, not here.
  • Does not make chat runtime sharing safe to enable. These two changes reduce a silent cross-write to a refusal in the cases they cover, nothing more.
  • Does not change what a tokenless claim reaches. Its PID-wide behaviour is a deliberate compatibility contract with three passing assertions, and all three are untouched.
  • Does not add per-session identity to the claim path. That already shipped in feat: key gateway stub identity by session, not by process #10324.

What changed (motivation -> approach -> change)

Symptom: a worker's work_brief returns a co-tenant's item on a shared runtime.

Root cause: two identity sources answer by process. gatewayd retargets a connection that names no session whenever any claim arrives on its pid, and the strict resolver trusts an env var that is stamped once per runtime.

Change: both sites stop answering by process once the process is known to host several sessions, which turns a silent misattribution into a refusal that names its reason.

gatewayd (_apply_claim). A tokened claim no longer attributes a tokenless connection on a pid serving 2+ live sessions. It does not merely decline to re-target it: the connection's caller is cleared, which is the same fail-closed state the register path gives a token it cannot resolve. Leaving the earlier identity in place would let a stub belonging to the second tenant go on answering as the first, which stops the misattribution moving without stopping it. After clearing, the stub's calls carry no caller, strict tools refuse with a diagnosis, and a claim carrying that stub's own token repairs it. Audited as denied.

Clearing an identity is a verdict, not an absence, and two things follow from that, both of which the clearing would otherwise get wrong:

  • The connection is marked refused, and the stub-initiated recaller rejects it. The recaller may fill exactly one state, a key-less tokenless connection nothing has named yet, and a cleared connection looks identical to that. Without the mark, a refused stub could name any session it liked, using a key from its own process-tree walk, which on a shared runtime is the very per-runtime answer the refusal rejected.
  • Its subscriptions are evicted, alongside the retargeted ones in pass 2. A subscription granted while the connection answered as the old session must not outlive that identity: resource-update URIs can carry tokens or presigned params, and the cleared connection never reaches the retarget list that eviction normally walks.

"Serves 2+ live sessions" is read from the live connection index, not from the token bindings. A binding is append-only until its LRU evicts it, so the bindings answer "which sessions was this pid ever claimed for": a warm-pool handover from A to B would read as two tenants while B is the only one left. Connections carrying the claim's own token are excluded, so re-keying one slot is not mistaken for a second tenant.

The env-var rung, in both copies. KIROCREW_SESSION_KEY is skipped when the host pid's mapping records several sessions, falling through to the signed-pid source rather than guessing. Two resolvers read that rung and both are guarded:

  • mcp_core._resolve_session_key_strict, source 2, used by tools that demand a strict identity.
  • mcp_caller.resolve_own_identity, rung 3. This is the shared client-side ladder, so the change also reaches its other consumers: the lenient resolver, the managed-tool-policy lookup, and read-only audit/telemetry callers. For those the effect is a key resolved one rung later, by the pid mapping, which already refuses co-tenants; mcp_shared's audit-attribution read is deliberately left per-process, since the module's contract already states misattribution is harmless for a read-only caller.

Both call one helper, mcp_caller.host_pid_is_shared, so the two resolvers cannot drift on how many sessions a pid serves nor on which read decides it.

Logging. Replacing a different, still-live identity on a shared runtime moves from INFO to WARNING. On a single-session runtime the same replacement is the warm-pool rekey the path exists for, and stays at INFO.

One deliberate asymmetry. The shared helper uses the unsigned mapping read, matching the co-tenancy refusal the pid rung already performs, because this answer only ever denies an identity. A forged tenant section costs its target a refusal that names the reason, while demanding the MAC would make the guard inert wherever the SEL trust root is missing, which is where identity is already weakest. Source 3 still demands the MAC, because source 3 grants a key.

Premise correction

This started from the theory that gateway stub identity was still keyed by pid and needed a per-session token. That is already shipped: #10324 mints a per-ACP-session token, narrows _apply_claim by it, and makes the register path fail closed on any unresolved token. What was actually left are the two process-keyed sources above.

Backwards compatibility

Compatible. Absence of a mapping is not evidence of sharing, so a single-session install keeps KIROCREW_SESSION_KEY exactly as authoritative as it was, on BOTH guarded rungs; only a pid recorded as serving several sessions loses it. That holds for the shared resolve_own_identity ladder too, so its lenient, policy and audit consumers are unchanged on every single-session topology, and on a shared pid they resolve one rung later instead of naming a co-tenant.

A tokenless claim keeps its PID-wide reach. A tokened claim still reaches its own session's stubs. A warm-pool rekey and a sequential handover both still re-target a tokenless stub, because neither is two live tenants.

Two behaviours narrow, both only on a pid recorded as serving several sessions: a tokened claim meeting a tokenless connection now clears that connection's identity instead of misattributing it, and the env-var rung stops answering. A caller that was being answered correctly by luck on such a pid is refused, which is the point: the value is identical for every child of the runtime, so a caller it happens to name cannot be told from one it does not.

Tests

Four new regression tests, each verified by mutation to fail with the fix reverted and pass with it applied.

test reverting the guard gives
test_a_tokenless_stub_is_not_handed_to_a_co_tenant assert 2 == 1, the tokenless stub was handed to the co-tenant; and with the clearing alone mutated out, the stub stays frozen on the first claimant's key
test_sequential_claims_on_one_runtime_are_not_sharing a handover reads as two tenants and strands the tokenless stub on the session that left
test_a_rekey_of_one_slot_is_not_sharing re-keying one slot reads as sharing
test_the_shared_ladder_refuses_the_env_var_on_a_shared_pid the ladder answers SOURCE_ENV with a co-tenant's key
test_a_parent_with_no_usable_token_is_refused_on_a_shared_runtime pins the chosen trade rather than leaving it implicit
test_a_refused_stub_cannot_name_itself_with_a_recaller the refused stub names any session it likes through the recaller
test_clearing_an_identity_evicts_its_subscriptions the old session's resource-update URIs keep reaching the cleared connection
test_replacing_a_live_identity_on_a_shared_runtime_warns assert 0 == 2, no warning published
test_strict_refuses_the_env_var_on_a_shared_pid the founder's key returned to a co-tenant's caller
test_strict_refuses_even_when_the_env_var_names_the_other_tenant the co-tenant's key returned by luck, not by resolution

Two controls pin the compatibility promise and survive both mutations, so each mutation is specific to the refusal rather than breaking the path wholesale: test_strict_keeps_the_env_var_on_a_sole_tenant_pid and test_strict_keeps_the_env_var_when_no_mapping_is_published.

Mutation procedure: the source file was copied outside the repo, mutated at exactly one asserted site, re-run, then restored by copy and re-verified by sha256sum against the pristine digest, so no mutation residue reached a commit.

Both owning test files in full: 196 passed, 1 skipped, 5 xfailed. mypy with the repo venv binary: Success: no issues found. flake8, isort and the comment-history gate clean.

Manual verification

A pod on the chat-runtime-sharing branch, three worker sessions proven by the runtime's own log to share one pid (tenants=3), each bound to its own ledger item.

  • MCP gateway off: worker B's work_brief returned worker A's item and B's report landed on it, while B's own item stayed empty.
  • MCP gateway on, mirroring the live config (kas backend, kirocrew-work stubbed): each session's first turn resolved correctly and each item carried only its own worker's report. Re-running the two older tenants after the third joined made both return the third's item.

That last result is the separate mount mechanism named under "Not a goal".

Pattern harvest

Rule candidate: semgrep.

Pattern: an identity resolver answering from a PROCESS-keyed source (an env var stamped at spawn, a pid-to-session mapping, a /proc ancestor walk) without first establishing that the process serves exactly one session. Every instance of this class misattributes a caller to a co-tenant instead of failing closed, and the failure is silent because the answer is a well-formed session key.

This PR fixes two instances; mcp_caller and the signed-pid source had already fixed theirs independently, which is what makes it a class rather than a one-off. A rule that flags a return of os.environ.get("KIROCREW_SESSION_KEY") or of a pid-keyed lookup from any function named *resolve*session*, unless a multi-tenancy check is reached first, would have caught both sites here and would catch the next resolver added.

Fixes #17523

@chenmingwei23
chenmingwei23 requested a review from a team as a code owner October 6, 2026 20:45
@chenmingwei23 chenmingwei23 reopened this Oct 6, 2026
@github-actions github-actions Bot added the readiness: action required A blocking check or review needs attention label Oct 7, 2026
@github-actions

github-actions Bot commented Oct 7, 2026 •

Copy link
Copy Markdown
Contributor

UX Review (Opus 5.5) — ⏭️ skipped

Revision 07e39bdcc72313a02e24062944334e4376836678 touches no user-facing surface (no changes under website/ or committed screenshots), so the UX review was skipped. Advisory — does not block merge.

@github-actions

github-actions Bot commented Oct 7, 2026 •

Copy link
Copy Markdown
Contributor

Design Review (Opus 5.5) — 🟡 CONCERNS

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

Design-Verdict: CONCERNS

The stated repair path for a cleared tokenless stub doesn't exist: the stub carries no token, so no "claim carrying its own token" can ever name it.

Watch

  • Cleared stubs stay without an identity until the co-tenant leaves. In the new _apply_claim branch (session_token and not conn.stub_session_token and shared_pid), the claim sets conn.caller = None and identity_refused = True. The comment says "a claim carrying ITS token repairs it through the branch above", but the branch only runs when conn.stub_session_token is empty, so no such claim can exist. The only real ways back are a tokenless claim or a tokened claim that arrives after _pid_live_tenants drops below 2. So with agent.session_sharing on, a parent's tokenless stubs refuse strict tools for the whole time a subagent shares the runtime. Nothing in the PR says this is a chosen trade-off, unlike the env-var refusal, which test_a_parent_with_no_usable_token_is_refused_on_a_shared_runtime pins as one. identity_refused is also never reset anywhere, so after a later retarget the flag silently outlives the refusal that set it.
    Clears when: the description and code comments name the real recovery path (the co-tenant leaves, or a tokenless claim), a test shows the stub regaining an identity once the co-tenant's connections are gone, and the code either resets identity_refused when a claim re-attributes the stub or documents why it stays set.
  • Backwards compatibility couldn't be checked in full. The ## Backwards compatibility section is the last one before the [description TRUNCATED notice, so its reader list may sit past the cut. This PR takes something away: the env-var rung is skipped on a shared pid, in both mcp_core._resolve_session_key_strict and mcp_caller.resolve_own_identity. One reader of that rung that I found is mcp_shared.py:546, the managed-tool-policy lookup. On a shared pid it now resolves no key at all instead of the env var's key. That matches its own docstring, but it isn't visibly listed.
    Clears when: the section lists Reader: src/kiro_crew/mcp_shared.py:<lookup> and mcp_core._resolve_session_key, with why each still works, inside the visible part of the description.

[DESIGN-REVIEWED] 07e39bd

Description read

[DESCRIPTION-READ] d6023bfacb35164af4b0c079efa836dfa280394532ada4938f17c9ed4ede7e0a

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

github-actions Bot commented Oct 7, 2026 •

Copy link
Copy Markdown
Contributor

Opus 5.5 Review — ✅ no blocking findings

Reviewed 07e39bdcc72313a02e24062944334e4376836678 — this comment is updated in place on each push.

Review details

Advisory only. One finding survived and nothing blocks the merge.

FINDING — src/kiro_crew/mcp_core.py:742 — When the host pid's mapping lists several sessions and the SEL trust root is healthy, _resolve_session_key_strict now ignores KIROCREW_SESSION_KEY and verify_session_pid refuses the pid as co-tenant. That sends strict_identity_diagnosis into its host_pid.isdigit() branch, which says "the signed pid mapping for this session did not verify… Check kirocrew doctor (trust root)". Doctor then reports a healthy trust root, and the actual cause (the runtime is shared) is never mentioned. → Fix: in strict_identity_diagnosis, check host_pid_is_shared(host_pid) before the trust-root branch and return a reason that names co-tenancy. That function is in this file but outside the changed lines.

[OPUS-REVIEWED] 07e39bd

Verdict parsed from the review's SHA-scoped output markers for commit 07e39bdcc72313a02e24062944334e4376836678.

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

@github-actions

github-actions Bot commented Oct 7, 2026 •

Copy link
Copy Markdown
Contributor

First Principles Review (Opus 5.5) — 🟡 CONCERNS

Premise-level review of 07e39bdcc72313a02e24062944334e4376836678 — 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: CONCERNS

_host_pid_hosts_several_sessions is a second spelling of host_pid_is_shared, and the _pid_live_tenants re-export from gatewayd has nothing reading it.

Not justified as shipped

  • Item 6 — duplicate of src/kiro_crew/mcp_caller.py:host_pid_is_shared: the wrapper's whole body is return host_pid_is_shared(host_pid). Grepping _host_pid_hosts_several_sessions finds one caller, mcp_core.py:742, plus one docstring reference.
    Subtraction: delete mcp_core._host_pid_hosts_several_sessions and call the already-imported host_pid_is_shared(host_pid) at line 742.
    Clears when: the wrapper is deleted.
  • Item 7 — zero consumers: gatewayd.py adds _pid_live_tenants to its noqa: F401 re-export list. Grepping _pid_live_tenants across test/ finds 0 hits, and the only src user, control.py, imports it from daemon.identity.
    Subtraction: drop _pid_live_tenants, from the gatewayd.py import block.
    Clears when: the re-export is removed, or a counted consumer reads it through gatewayd.
  • Item 5 — rides along: changing the log level does not affect who gets attributed.

What this change ships

Inventory (7 items) — 4 justified

Intent: stop a worker's MCP tool calls being credited to a co-tenant session on a shared runtime. FIX.

  1. A tokenless stub on a pid serving 2+ live sessions now has its identity cleared and its calls refused, instead of being retargeted — justified
  2. A cleared stub can no longer name itself through a recaller — justified
  3. A cleared stub's resource subscriptions are evicted — justified
  4. KIROCREW_SESSION_KEY is ignored on a pid recorded as shared, in both the strict resolver and the shared ladder — justified
  5. Replacing a live identity on a shared runtime now logs WARNING instead of INFO — rides along
  6. Private wrapper around the shared-pid helper — duplicate of mcp_caller.host_pid_is_shared
  7. _pid_live_tenants re-exported from gatewayd — zero consumers

[FIRST-PRINCIPLES-REVIEWED] 07e39bd

Description read

[DESCRIPTION-READ] b2be412c71025f5ec39655aef39b8fd928cb35d42fc14620f8d4b552510bcd4a

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

github-actions Bot commented Oct 7, 2026 •

Copy link
Copy Markdown
Contributor

⚠️ Stale verdict notice (2026-10-13 21:05 UTC): a later GPT 6.1 run did not produce a completed verdict for 07e39bdcc72313a02e24062944334e4376836678; the verdict below is from an earlier completed run. Inspect the GPT 6.1 Review job logs and re-run the workflow, or have a repository writer comment /ai-review override gpt 07e39bdcc72313a02e24062944334e4376836678: <one-sentence reason>.

GPT 6.1 Review — ✅ no blocking findings

GPT 6.1 completed its review of 07e39bdcc72313a02e24062944334e4376836678 and found no blocking issues.

This comment is updated in place on each push.

Review details

No findings.
[GPT-REVIEWED] 07e39bd

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

@chenmingwei23

Copy link
Copy Markdown
Contributor Author

Disposition for the two findings on dc38570fba, now addressed on ca6fed8d5c.

SAST (Semgrep) - fixed. python-logger-credential-disclosure fired on control.py:264:

logger.warning("claim refused an ambiguous tokenless stub: %s", reason)

The rule reads a logger literal mentioning a token as a possible secret. No token value reaches this call: the interpolated reason carries the pid, the stub uuid and the session key, and the token is deliberately excluded from logs, stats() and the fallback journal. Rather than suppress the rule, the message now says what the refusal is actually about, which is also the clearer wording:

logger.warning("claim refused a stub it cannot attribute: %s", reason)

Swept the rest of this change for the same shape: no other added logger literal mentions a token.

PR Hygiene - fixed. The description was written to the 5-section house format, but this gate requires the template's own headings verbatim. The body is rebuilt on .github/PULL_REQUEST_TEMPLATE.md with ## Problem / Motivation (carrying the **Goal:** line), ## Why it matters, ## Not a goal, ## What changed, ## Backwards compatibility, ## Tests, ## Manual verification and ## Pattern harvest, the last because this is a fix( PR. Verified before pushing by running .github/scripts/pr-description-check.sh against the new body: conclusion=success.

Security Scope Review - was not a finding. Its annotation said generate never resolved the lane's review scope (in_scope=""), so it failed closed on a change it never measured. That run's three upstream generate jobs were cancelled, because I had cancelled the round earlier to clear a wedged queue. A full re-run (not --failed, which would have left generate cancelled) cleared it.

Ordering note: the body edit landed before the push, so the round the push starts is the one that gets adjudicated rather than being cancelled mid-flight.

Local re-verification on the new head: both owning test files 196 passed, 1 skipped, 5 xfailed; mypy clean; flake8, isort and the comment-history gate clean; the take-away reader-list check reports no take-away shape.

@chenmingwei23
chenmingwei23 force-pushed the fix/claim-per-session branch from ca6fed8 to 29f6f24 Compare October 7, 2026 01:15
@chenmingwei23

Copy link
Copy Markdown
Contributor Author

Disposition for the two findings on ca6fed8d5c, now addressed on 29f6f24247.

Backend Lint & Type Check (3.12) - fixed. test/test_identity_topology.py was not black-formatted. Ran black --target-version py310 and re-checked every Python file this change touches: all 6 clean. My earlier local gate set ran flake8, isort, mypy and the comment-history gate but not black, which is why this reached CI.

PR Hygiene (Enforce commit count) - fixed. The branch carried 3 commits against a cap of 2. It is now 2, split along the two concerns rather than squashed flat:

  • fix(mcp-gateway): refuse a PID-keyed claim on a runtime hosting several sessions - control.py, identity.py, gatewayd.py and the stub-session-token tests. The Semgrep log reword folded in here, since it is the same file and the same refusal.
  • fix(mcp): stop the session-key env var naming a co-tenant on a shared runtime - mcp_core.py and the identity-topology tests.

main had moved to bb24a01b4d while this PR sat in the Actions backlog, so the branch was rebased onto it BEFORE squashing, and the base was verified afterwards (git merge-base HEAD origin/main equals origin/main). Without that order a soft reset to origin/main silently reverts everything main gained. Confirmed the diff against main contains only the 6 files this PR owns.

Re-verified on the rebased tree, not carried over from the pre-rebase run: both owning test files 196 passed, 1 skipped, 5 xfailed; black, flake8, isort clean on all 6 files; mypy Success on 4 source files; comment-history gate clean against the new base.

66 lanes were already green on ca6fed8d5c; the rebase re-rolls them on the new base.

@github-actions github-actions Bot added readiness: checking Automated validation is still running readiness: action required A blocking check or review needs attention and removed readiness: action required A blocking check or review needs attention readiness: checking Automated validation is still running labels Oct 7, 2026
@chenmingwei23
chenmingwei23 force-pushed the fix/claim-per-session branch from 29f6f24 to 9385af9 Compare October 7, 2026 02:50
@chenmingwei23

Copy link
Copy Markdown
Contributor Author

Disposition for the Design and First Principles CONCERNS on 29f6f24247, addressed on 9385af9cac.

Both verdicts were advisory, but Design's first item is a defect this PR itself introduced, and a defect in code this PR adds is always in scope. All four items are fixed rather than deferred.

Design 1, "shared really means ever shared" - fixed, and it was a real regression. _bind_token is append-only until the 512-entry LRU evicts it, so counting bindings answered "which sessions was this pid ever claimed for". A warm-pool runtime claimed by A and later by B counted 2, set shared_pid, and refused to retarget its tokenless stubs, stranding them on A while B was the only tenant. That is the misattribution this PR exists to prevent, re-created on a single-session runtime, and it also pushed the routine rekey to WARNING.

The predicate is now _pid_live_tenants(pid, exclude_token), read from the live _CONN_INDEX:

  • Only connections that CARRY a token count. A tokenless connection's current caller is not evidence of a separate session, it is whatever the last claim retargeted it to.
  • Connections carrying the claim's own token are excluded, so re-keying one slot is not read as two tenants.
  • The claiming session is unioned in, because a claim is pushed before its own stubs register.
  • The pid_start_id concern dissolves: a dead process's connections are already out of the index, so a recycled pid cannot contribute a stale tenant.

Pinned by test_sequential_claims_on_one_runtime_are_not_sharing (the test the verdict asked for) and test_a_rekey_of_one_slot_is_not_sharing. Mutation-checked: restoring the binding-derived count fails the sequential-claims test while the genuine-sharing refusal and the rekey test still pass, so the mutation is specific to this regression.

Design 2, a parent with no usable token loses strict tools - stated and pinned. This is the chosen trade, now explicit in test_a_parent_with_no_usable_token_is_refused_on_a_shared_runtime. On a runtime a subagent has joined, with the token channel failing closed, answering would hand the parent's key to whichever session is calling, and the subagent is the one that would write the parent's state. A refusal that names its reason is recoverable; a silent write to another session's state is not.

First Principles 1, the shared ladder's sibling rung - fixed. Correct and the more useful of the two findings: guarding only the strict helper left rung 3 of mcp_caller.resolve_own_identity returning SOURCE_ENV on a shared pid, and that ladder is the one every other client-side resolver shares. It now consults the same mapping its own pid rung (rung 4) already refuses co-tenants on, and falls through to it. Covered by test_the_shared_ladder_refuses_the_env_var_on_a_shared_pid with a sole-tenant control.

mcp_shared.py:423 is left answering per process deliberately: that read is audit attribution, and the module's existing contract already says the lenient resolver is for read-only callers where misattribution is harmless.

First Principles 4, duplicate predicate - fixed. mapping.refusal == REFUSAL_CO_TENANT or mapping.tenant_count >= 2 is now mapping.shared, which is that same expression's home.

Verification on 9385af9cac, rebased onto main 5b2aee24e4 (main moved twice during this PR; each time rebased before squashing and the base re-verified): 237 passed, 1 skipped, 5 xfailed across the three owning test files, now including test_mcp_caller.py for the ladder change. black, flake8 and isort clean on all 7 files; mypy Success on 5 source files; comment-history gate clean. Still 2 commits.

@github-actions github-actions Bot added readiness: checking Automated validation is still running readiness: passed Eligible automated validation passed for the current revision and removed readiness: action required A blocking check or review needs attention readiness: checking Automated validation is still running labels Oct 7, 2026
@chenmingwei23
chenmingwei23 force-pushed the fix/claim-per-session branch from 9385af9 to 5d01d78 Compare October 7, 2026 03:25
@chenmingwei23

Copy link
Copy Markdown
Contributor Author

Disposition for the Design and First Principles CONCERNS on 9385af9cac, addressed on 5d01d78644.

Design 1, "the gateway site does not refuse anything" - fixed, and the verdict was right. skipped += 1 ... continue left the tokenless connection on its last guessed identity. That identity is an earlier guess by the same PID, so a stub belonging to the second or third tenant went on answering as the first claimant: the misattribution stopped moving without stopping. The description's word "refusal" did not describe the code.

The connection's caller is now cleared, which is the same fail-closed state the register path gives a token it cannot resolve. No caller on the wire, strict tools refuse with a diagnosis, and a claim carrying that stub's own token repairs it. test_a_tokenless_stub_is_not_handed_to_a_co_tenant now asserts the identity is gone rather than frozen, and mutating out just the conn.caller = None line fails that test while the sequential-handover and rekey tests still pass, so the clearing is independently pinned.

Design 2, the third identity site and two wrong statements in the description - fixed. All three were accurate:

  • ## What changed now has its own paragraph for mcp_caller.resolve_own_identity rung 3, naming the consumers it reaches (the lenient resolver, the managed-tool-policy lookup, read-only audit/telemetry callers) and what changes for them: a key resolved one rung later by the pid mapping, which already refuses co-tenants. It also records that mcp_shared's audit-attribution read is left per-process on purpose.
  • ## Backwards compatibility is re-argued for both rungs rather than the strict path alone.
  • The claim that the tenant count is "derived from the existing claim bindings" was stale after the previous round and is corrected to the live connection index, which is what _pid_live_tenants actually reads.

Design suggestion, the fixture docstring - fixed. _wire_strict_env no longer says the guard reads the MAC-verified mapping. It now states that both guards read the mapping unsigned on purpose and that the tenant section, not the sidecar, is what makes the fixture work.

First Principles 4, two copies of the same check - fixed. Correct, and they had already diverged on whether they passed config_dir(). There is now one helper, mcp_caller.host_pid_is_shared(host_pid=""), defaulting to this process's own KIROCREW_HOST_PID for the ladder and taking an explicit pid for the strict resolver. mcp_core._host_pid_hosts_several_sessions delegates to it, so the two resolvers cannot drift on how many sessions a pid serves nor on which read decides it.

Verification on 5d01d78644, base main 5b2aee24e4 unchanged this round: 237 passed, 1 skipped, 5 xfailed across the three owning test files; black, flake8, isort clean on all 7; mypy Success on 5 source files; comment-history gate clean; the description gate's own script returns conclusion=success. Still 2 commits.

One ordering note against myself: the body edit in this round was attempted before the push, as it should be, but it silently did not apply and I only caught that afterwards, so the body landed after the push rather than before it. The round this push started will therefore be re-rolled once by that edit.

@github-actions github-actions Bot added readiness: checking Automated validation is still running readiness: action required A blocking check or review needs attention and removed readiness: passed Eligible automated validation passed for the current revision readiness: checking Automated validation is still running labels Oct 7, 2026
A claim carrying a session token re-targets a connection that carries no token,
on the grounds that such a connection has no finer identity than the process
tree the claim named. When the runtime serves exactly one ACP session that tree
does name it. When it serves several, the PID names the runtime and not a
session, so the attribution is a guess, and the stub it lands on answers as a
co-tenant: its work_brief and work_report read and write the claiming session's
ledger.

The connection's caller is CLEARED in that case, not left alone. Whatever it
holds is an earlier guess by the same PID, so a stub belonging to the second
tenant would go on answering as the first -- the misattribution would stop
moving without stopping.

Clearing is a VERDICT, not an absence, and two things follow:

* The connection is marked refused and the stub-initiated recaller rejects it.
  The recaller may fill exactly one state -- a key-less, tokenless connection
  nothing has named yet -- and a cleared connection is indistinguishable from
  that. Unmarked, a refused stub could name any session it liked, with a key
  from its own process-tree walk: the very per-runtime answer the refusal
  rejected. Only claim-push, naming this connection's own token, may name it.
* Its subscriptions are evicted alongside the retargeted ones. A subscription
  granted while it answered as the old session must not outlive that identity,
  because resource-update URIs can carry tokens or presigned params, and the
  cleared connection never reaches the retarget list eviction walks.

"Serves several sessions" is read from the LIVE connection index, not from the
token bindings. A binding is append-only until the LRU cap evicts it, so the
bindings say which sessions a pid was EVER claimed for: a warm-pool runtime
claimed by A and later by B would read as two tenants while B is the only one
left, and the stub would be stranded on A. Live connections also need no process
start token, since a dead process's connections are already gone from the index.
Connections carrying the claim's own token are excluded, because a slot's own
stubs still show the previous session at the moment it is re-keyed.

Every other topology is byte-for-byte: a tokened claim still reaches its own
session's stubs, and a tokenless claim keeps its PID-wide reach, which a
deployment whose sessions predate the token depends on.

Replacing a DIFFERENT live identity on a shared runtime moves from INFO to
WARNING. On a single-session runtime that replacement is the warm-pool rekey the
path exists for and stays at INFO.

The log line names what it is about rather than the stub's missing token: a
logger literal mentioning a token reads to the credential-disclosure scanner as
a possible secret, and no token value reaches that call.
… runtime

``KIROCREW_SESSION_KEY`` is stamped once per runtime and inherited by every MCP
child of it. One runtime hosts many ACP sessions, so on a runtime the mapping
records as multi-tenant the var names ONE tenant and cannot say which one is
calling. Returning it attributes the caller to a co-tenant and lets a
state-mutating tool write another session's state -- a work_report landing on
another worker's ledger item.

Both copies of that rung refuse it now, on the same ground the signed-pid source
already refuses such a pid: source 2 of ``mcp_core``'s strict resolver, and rung
3 of ``mcp_caller.resolve_own_identity``, which is the one client-side ladder
every other resolver shares. Guarding only the strict helper would leave the
identical process-keyed rung answering for every caller that goes through the
ladder -- the lenient resolver and the managed-tool-policy lookup among them.
``mcp_shared``'s audit-attribution read stays per-process, as its own contract
already says misattribution is harmless for a read-only caller.

One helper, ``mcp_caller.host_pid_is_shared``, serves both resolvers, so they
cannot drift on how many sessions a pid serves nor on which read decides it. It
takes the UNSIGNED mapping, matching the co-tenancy refusal the pid rung already
performs, because this answer only ever DENIES an identity: a forged tenant
section costs its target a refusal that names the reason, while demanding the MAC
would make the guard inert wherever the SEL trust root is missing. Absence of a
mapping is not evidence of sharing, so a single-session install keeps the var
untouched on both rungs.

A session_sharing parent whose own token cannot be verified is refused on a
runtime a subagent has joined, even though the env var names that parent. That
is the chosen trade and a test pins it: answering would hand the parent's key to
whichever session is calling, and a silent write to another session's state is
not recoverable where a named refusal is.
@github-actions github-actions Bot added readiness: checking Automated validation is still running and removed readiness: action required A blocking check or review needs attention labels Oct 7, 2026
@chenmingwei23
chenmingwei23 force-pushed the fix/claim-per-session branch from 5d01d78 to 07e39bd Compare October 7, 2026 04:08
@chenmingwei23

Copy link
Copy Markdown
Contributor Author

Disposition for the GPT 6.1 BLOCK on 5d01d78644, addressed on 07e39bdcc7.

Both findings are security-class, both were upheld by adjudication, and both are direct consequences of the identity clearing added in the previous round. Confirmed in the code before fixing, and both are now fixed with their own mutation-verified test.

F1, control.py:269, clearing re-enables untrusted recaller grants - real, fixed. _apply_recaller rejects a connection that carries a session token, and one that already holds a key. A cleared connection has neither, so it fell through to the one allowed transition and could adopt any session key it named. The key it would send comes from the stub's own process-tree walk, which on a shared runtime is the same per-runtime answer the refusal had just rejected, so the refusal handed back exactly what it refused.

A clearing is now recorded as a verdict rather than an absence: _StubConn.identity_refused is set, and _apply_recaller rejects such a connection with its own audited reason. Only claim-push, naming that connection's own token, can name it again.

F2, control.py:285, clearing skips subscription revocation - real, fixed. The cleared branch hit continue before retargeted.append, so pass 2's evict_stub_subscriptions never ran for it, and _resource_update_targets still returned that stub for the old session's URIs. Those URIs can carry tokens or presigned params.

Cleared connections are now collected and evicted in pass 2 alongside the retargeted ones. They are evicted but not counted in updated and not audited as allowed, because nothing was granted to them. The eviction stays in pass 2 so every synchronous caller assignment still lands before the first await, which is the ordering the surrounding comments require.

Both are pinned, and each mutation is caught by its own test while the sibling still passes:

test mutating out
test_a_refused_stub_cannot_name_itself_with_a_recaller conn.identity_refused = True
test_clearing_an_identity_evicts_its_subscriptions cleared.append(conn)

The description now declares both, under "What changed": that clearing is a verdict not an absence, and the two consequences that follow from it.

Verification on 07e39bdcc7, base main 5b2aee24e4 unchanged: 277 passed, 1 skipped, 5 xfailed across four owning test files, now including test_mcp_gateway_claim.py since _apply_claim and _apply_recaller both changed. black, flake8, isort clean on all 7 files; mypy Success on 5 source files; comment-history gate clean; the description gate's own script returns conclusion=success. Still 2 commits. The body edit was applied and read back before pushing this time.

@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 Oct 7, 2026
@chenmingwei23

Copy link
Copy Markdown
Contributor Author

Disposition for the two advisory CONCERNS on 07e39bdcc7. The board is green, the readiness signal passes, and both lanes define CONCERNS as advisory, so these are captured rather than acted on here: a push would re-roll four clean verdicts including a GPT lane that has just cleared a block, and none of the five items is a behavioural defect.

All five are accurate and are filed with the reviewers' own coordinates and clears-when in #17612:

  1. The code comment names a recovery path that cannot happen. A cleared stub is tokenless, so no tokened claim can match it; the real paths are a tokenless claim or a tokened one after the co-tenant leaves. The consequence (a parent's tokenless stubs refuse strict tools while a subagent shares the runtime) deserves the same explicit framing the env-var trade already has.
  2. identity_refused is never reset. No wrong behaviour follows today, because the pre-existing existing_key guard rejects a recaller once a caller is present, so the flag is redundant while a key is held and correct while it is absent. It is still state outliving its condition.
  3. The description is longer than the review tooling reads: about 12.5k characters, cut shortly after ## Backwards compatibility, so the lanes judged this change without the ## Tests evidence. The PR Hygiene gate reads the raw body and passes, so this is a reviewer-view problem only.
  4. mcp_shared.py:546, the managed-tool-policy lookup, is a reader of the guarded env rung and is not named in the backwards-compatibility list.
  5. Two subtractions: mcp_core._host_pid_hosts_several_sessions is now a pure pass-through to the already-imported host_pid_is_shared, and gatewayd's _pid_live_tenants re-export has no consumer.

Item 3 is the one I would act on first, since it is why the lanes are reviewing without the evidence section.

@iamwhatever

Copy link
Copy Markdown
Contributor

Reviewed, not approving (crew-pr-reviewer). This changes how MCP identity is answered on a shared runtime. That is an identity boundary, so it needs a security owner.

@buluoray buluoray left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Approve. On a runtime the pid mapping records as hosting several sessions, both process-keyed identity sources now refuse rather than name a co-tenant. A single-session runtime behaves exactly as before.

What was verified

  • The fix does what it says. mcp_core._resolve_session_key_strict (source 2) and mcp_caller.resolve_own_identity (rung 3) both skip KIROCREW_SESSION_KEY only when host_pid_is_shared() reports positive evidence (PidMapping.shared = tenant_count > 1). Execution then falls through to the signed-pid source, which already refuses co-tenants, so the outcome is fail-closed "". The per-session token rung and the gateway caller block still sit above it, so a tokened caller keeps resolving correctly.
  • In _apply_claim, a tokened claim that meets a tokenless connection on a pid with two or more live token-carrying tenants clears conn.caller, sets identity_refused, audits the change as denied and evicts that connection's subscriptions. This is fail-closed. The recaller rejects a refused connection, which closes the self-naming route. Tokenless claims keep their PID-wide reach, and that compatibility contract is untouched.
  • _pid_live_tenants reads the live connection index and excludes the claimant's own token. The token is minted once per AcpClient and survives rekey(), so a warm-pool rekey of one slot is not counted as sharing.
  • Statelessness holds. mcp_core/mcp_caller gain no module global, and host_pid_is_shared reads the mapping on every call and never raises. The new per-connection flag lives on gatewayd's existing _StubConn, not in an MCP tool process.
  • Every new guard was disabled one at a time, and each mutation reddens a named test: the four env-var tests, the tokenless-co-tenant test, the recaller-after-refusal test, the subscription-eviction test, and the rekey-is-not-sharing and shared-runtime-warning tests.
  • Targeted suites pass at this head, with one exception: test_a_proven_recycle_is_not_unverifiable fails identically on main in the reviewer's environment, so this PR did not cause it. CI is 85 success, 13 skipped, 0 failure on this head.

Blocking findings: none.

Non-blocking follow-ups

  1. The comments in control.py and identity.py, and the PR body, say a cleared stub is repaired by "a claim carrying ITS token". A cleared connection is tokenless by construction, so no such claim can exist. What actually restores it is a later tokened claim after the pid stops being shared, or a tokenless PID-wide claim. Both reach conn.caller = updated_caller in pass 1. The comments should say that instead. Note also that identity_refused is never reset after a repair. That is harmless while the caller is set, but it should be documented or cleared at line 329.
  2. host_pid_is_shared() adds one mapping-file read to every resolution that reaches the env-var rung. This is cheap, but it now sits on a per-call path for strict tools.
  3. docs/system-specs/modules/security.md (the "Strict Caller-Identity Classification" section) still lists the strict sources without the new shared-pid exception for the env var. It should get a one-line update.

Upgrade impact: none on a single-session install. A mapping with no tenant section, or with one tenant, leaves the env var authoritative on both rungs, and publish_turn_identity writes a tenant section only when it sees more than one session on the pid. The behaviour narrows only on a pid recorded as shared, where the old answer was a guess.
Audience fit: the default path is unchanged. The new refusals apply only to multi-tenant runtimes, which is the case being fixed.

@chenmingwei23
chenmingwei23 merged commit bad0419 into main Oct 9, 2026
102 checks passed
@chenmingwei23
chenmingwei23 deleted the fix/claim-per-session branch October 9, 2026 23:25
@github-actions github-actions Bot removed the readiness: passed Eligible automated validation passed for the current revision label Oct 9, 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.

MCP identity is answered per process on a runtime hosting several sessions, so a tool call is attributed to a co-tenant

3 participants