Repository navigation
feat: key gateway stub identity by session, not by process - #10324
Conversation
Design Review (Fable 5) — ✅ PASSDesign-level review of Design-Verdict: PASS Fixes an identity keyed on a shared resource at its root (per-session token, fail-closed, claim-repaired), moves no default, and stays byte-compatible for tokenless paths. Suggestions
[DESIGN-REVIEWED] 046462e |
GPT 5.6 Review — ✅ no blocking findingsGPT 5.6 completed its review of This comment is updated in place on each push. Review detailsNo findings. False positive or not applicable? A repository writer can comment: |
First Principles Review (Fable 5) — ✅ PASSPremise-level review of First-Principles-Verdict: PASS Verify the one asserted-but-unpinned premise: an What this change shipsInventory (10 items) — 10 justifiedIntent: give each ACP session on a shared kiro-cli process its own gateway identity so a subagent's MCP calls can never resolve — or be re-pointed — as its parent. ADDITION (hardening a named boundary: the agent-identity gate), with the defect pinned by tests in this PR that fail on base.
Counts run: [FIRST-PRINCIPLES-REVIEWED] 046462e |
Opus 4.8 Review — ✅ no blocking findingsReviewed Review detailsBoth candidates rest on the same premise: that if not entries or not self._mcp_gateway_socket:
return entries, ""The ReviewPool runtime ( Both drop under falsification (a) — no concrete input reaches the changed behavior. No findings. [OPUS-REVIEWED] 046462e Verdict parsed from the review's SHA-scoped output markers for commit False positive or not applicable? A repository writer can comment: |
67ce104 to
0a2f889
Compare
GPT 5.6 Review —
|
1 similar comment
GPT 5.6 Review —
|
0a2f889 to
65cc139
Compare
65cc139 to
38d7bd1
Compare
38d7bd1 to
9d0a460
Compare
|
/ai-review override gpt 3c7f514: The residual is a same-uid co-tenant of one runtime, which is already inside the trust boundary Opus verified and dropped, and it grants no new capability because a tokenless register on main is already believed with any self-asserted session_key — authenticating the register frame itself is a separate change, tracked as a follow-up. |
Human judgment recorded@iamwhatever marked the gpt AI finding as false positive, not applicable, or explicitly accepted for
This decision applies only to this commit. A new push requires a new judgment. |
3c7f514 to
7a0e956
Compare
Every identity channel a broker stub had was keyed on the process tree: the stub's own KIROCREW_SESSION_KEY / session_pid_<pid>.txt walk, gatewayd's SO_PEERCRED /proc walk, and claim-push, which re-targeted every connection indexed under a runtime PID. One kiro-cli process hosts N ACP sessions, so all three answered with the parent slot for a spawn_run subagent's stub, and a parent re-claim overwrote whatever a subagent had. Mint one unguessable token per ACP session, carry it in the env of that session's injected stub entries, and have the stub return it on its register frame as a sibling of poolable -- never a PoolKey dimension, which would make every session's backend private and turn pooling into a no-op. gatewayd keys claims by (pid, token): a claim re-targets the connections carrying its token plus any carrying none, and a claim with no token keeps the PID-wide reach a hand-written config still needs. A token no claim has named is refused rather than resolved, and a claim's binding is honoured only for a connection the KERNEL places under the runtime that claim named -- the peer-pid chain gatewayd walks itself, never the stub's self-reported ancestor_pids, which the registrant authors and could point at any runtime whose token it had read. The refusal is unconditional because an empty binding table is the state a fresh daemon, a respawn and an evicted binding all share. Repair is the owning session's own claim: awaited before session/new where the owner is known, pushed at rekey() and after new_conversation, and re-pushed at the start of every turn by the shared identity publisher. A claim carries a session key or gatewayd discards it, so every provider is told which session it serves at CONSTRUCTION -- rekey() is a warm-pool event and a cold start never reaches it. The token is a bearer name for a session's identity, so it is stripped from the register frame before the prewarm recorder can persist it, and never reaches a log record, stats() or the stub fallback journal. No default changes: mcp_gateway.enabled and stub_servers are untouched, and a runtime with no gateway socket mints nothing.
7a0e956 to
046462e
Compare
Problem / Motivation
The MCP gateway's stub path is the only channel that gives
kirocrew-corea per-call caller identity (_meta.kirocrew.caller, injected by gatewayd after stripping any client-forged block). Every input it had for building that identity is keyed on the PROCESS TREE, not the session:KIROCREW_SESSION_KEY, else asession_pid_<pid>.txtancestor walk (mcp_gateway/stub.py,mcp_caller.py); injected stub entries carryenv: {}, so the stub reads whatever the runtime's process tree gives it,/procwalk,rekey()— keyed on the runtime PID, and_apply_claimREPLACES the caller on every indexed connection of that PID.A
spawn_runsubagent shares its parent's kiro-cli process by default (agent.session_sharing), so one runtime hosts N ACP sessions and all three sources answer with the PARENT's session key for a subagent's stub — and a parent rekey overwrites whatever a subagent had.Why it matters
Today the strict identity gate REFUSES when no channel exists, so the failure is safe. Once stubs become the default channel it stops being safe and becomes "wrongly succeeds as the parent": a subagent could
monitor_starta loop on the user's chat slot,work_reportonto the parent conductor's item, orset_projectanother slot's working tree. This lands the discriminator before that default can flip.What changed (motivation → approach → change)
The tree cannot name a session, so something else has to. Kiro Crew mints one unguessable token per ACP session and gatewayd keys claims by
(pid, token).claim.mint_stub_session_token()(256 bits,secrets) plussession_servers.attach_stub_session_token(), which puts it in theenvarray of that session's injected entries.AcpRuntime.create_session/load_sessionmint one per ACP session (parent slot, each subagent session, each warm worker at warm time) and record it on the session handle.AcpClientmints one per client process — it serves one session at a time — and itsrekey()re-binds the same token rather than re-minting, since stub processes outlive a single chat.pooled_session_servers' signature is untouched; the token is attached after it, which is why callers that monkeypatch it are unaffected.build_register_payloadreadsKIROCREW_STUB_SESSION_TOKENand sendsstub_session_tokenas a sibling ofpoolable. It is not aPoolKeydimension — a per-connection dimension in the key would make every session's backend private and turn pooling into a no-op (poolmodule docstring).(pid, token). A bounded, claim-written-onlytoken → callertable._apply_claimrecords the binding (a claim precedes its own stubs, so "matched zero connections" is the normal ordering) and re-targets connections whose token matches plus connections carrying none; a claim with no token re-targets every connection under the PID exactly as before.recallerframe (whose key comes from the same walk) are all declined — the connection stays identity-less, the state every warm-pool stub already starts in. The refusal is deliberately unconditional rather than scoped to "a sibling session is already named": an empty binding table is the state a fresh daemon, a respawn and an evicted binding all share, and in each of those the tree answer is a different session's.session/newwhere the owner is known, pushed atrekey()and afternew_conversationre-launches a worker's stubs, and re-pushed at the start of every turn by the shared identity publisher (messaging/identity.py, the same boundary that already rewritessession_pid_<pid>.txtbecause that mapping lives outside the process and can be lost while the session is alive). The per-turn re-push is what re-binds a token whose daemon restarted under it.stats(), or the stub fallback journal.mcp_gateway.enabledandstub_serversare untouched, and a runtime with no gateway socket mints nothing — no gatewayd to bind a token means the token would have no reader.Tests
test/test_mcp_gateway_stub_session_token.py(41 tests), driving the realgatewayd._handle_connectionloop through the harnesstest_mcp_gateway_claim.pyandtest_identity_topology.pyalready use:no-token(neither connection carries one — a tokenless claim re-targets both, as before),all-tokens(a claim for one reaches only that one),mixed(the tokened connection is selected and the tokenless one rides along).ProcessTopology's real subagent tree with the gateway'ssession_pid_<host_pid>.txtnaming the parent: after the parent's rekey the subagent's stub still forwards as the SUBAGENT, andrequire_strict_session_key— the gatemonitor_startand every reflexive tool route through — answers with the subagent's key against that identity.recallercannot name it; and a daemon respawn with both sessions live leaves neither wearing the other's identity, with the per-turn re-claim restoring both./procwalk (with the host chain still indexed so later claims land).stats(),stub_fallback.jsonl, and both the in-memory and flushed prewarm payloads.session/new; two sessions on one runtime get different tokens; an unclaimed warm worker mints a token but pushes no claim; no stub entries means no token and no claim;rekey()andnew_conversationclaim by the handle's token; the turn boundary re-claims and leaves a provider without stubs alone; and a source pin that the subagent path hands down its own session key.REAL_CLI-gated, beside the existing precedence pin) asserts the child receives the env pair AND that an element carryingenvstill overrides the agent spec's same-named entry.Revert-verified: 21 mutations, each reverting one half of the change (claim ignores the token, register ignores the binding, either fail-closed rule dropped, unbounded table, the token left on the prewarmed frame, attach never attaches, the stub never forwards, the runtime mints nothing or claims nothing, the turn boundary or
new_conversationnever re-claims, the client re-claim names no token) — all 21 caught, tree restored green.Zero-regression bar, all UNMODIFIED:
test_mcp_gateway_claim.py, everytest_mcp_gateway_stub_*/test_stub_*/test_gatewayd_*,test_mcp_gateway_backend_coverage.py,test_mcp_gateway_control_plane.py,test_mcp_gateway_prewarm*,test_identity_topology.py,test_acp_runtime.py,test_acp_session_provider.py,test_acp_harness_wire_parity.py(the byte-golden wire capture) andtest_real_kiro_cli_prefers_session_injected_serveron the installed kiro-cli. A full local backend run was diffed against a run of the same suite on this PR's base commit: identical failure sets (host-environment reds —atomic no-replace rename is unavailable, missing optional deps), no branch-only failure.Manual verification
isort,flake8,mypy src/kiro_crewand the black gate clean on the CI-pinned versions;docs-lint.shclean; the diff-scoped gates (brand, harness parity, comment history, subprocess encoding, changelog history, focus cue, sync-io, loop-bound locks, agent-sdk boundary, memory-store seam, feature map) run with their own base-ref exports.test/smoke_gateway.shwas NOT run: it requires a live gateway onlocalhost:5476and drives ~20 real model turns asking an agent to attempt AWS credential exfiltration. It exercises the shell/credential gates, not the MCP-gateway stub path this change touches. The equivalent end-to-end coverage here istest_mcp_gateway_pool_integ.pyandtest_stub_broker_reconnect.py, which spawn real stubs against a real daemon, plus the real-kiro-cli probe above.Known gaps
AcpSessionProvider.stream). Fail-closed (a strict tool refuses with its diagnosis) rather than acting as another session, and bounded to one turn. Closing it fully would mean the daemon's supervisor replaying claims for every live session at spawn — worth doing on its own, not inside this change.mcpServersor never resolve a session key today.Review round 2 — what changed and why
GPT 5.6 F1 (round 1): an unclaimed token fell back to the process tree after a gatewayd respawn. Correct, and the reason was that the refusal was made conditional on observing a named sibling — which fails open in exactly the states where the observation is missing (fresh daemon, respawn, evicted binding). The rule is now unconditional: a token present with no usable binding gets NO identity, and repair comes only from the owning session's own claim, which is re-pushed at every turn boundary by the shared identity publisher (plus after
new_conversation). Test:test_a_daemon_respawn_leaves_no_session_wearing_anothers_identity.GPT 5.6 F1 (round 2): the token rides an
envpair, and/proc/<pid>/environis same-uid readable, so a sibling process can present another session's token. Two parts:Hardened. A claim binds the token together with the runtime PID it named, and a register is now answered from that binding only when the same PID is in the connecting stub's own ancestry — the same membership claim-push already needs to reach a connection at all. So the token narrows within a runtime and the runtime tree bounds who may present the token: holding another session's token from outside its runtime buys nothing. Test:
test_a_stolen_token_buys_nothing_outside_its_runtime. Revert-verified (a token binding is honoured outside its own runtime tree→ caught).Residual, and pre-existing. Inside one runtime's tree the token remains a bearer value, and no transport change closes that:
argvis as readable asenviron, and a 0600 sidecar is readable by the same uid too — same-uid confinement is the sandbox's job (agent.sandbox, off by default). More importantly, a same-uid process needs no token to do this today: a register frame with a self-reportedsession_keyand no token is believed verbatim (_caller_from_register→caller, no verification), on this branch and onmainalike. So the token grants no capability that the register path does not already grant for free. Authenticating the register frame itself is the real fix and is a separate change with its own blast radius — it is not something to bolt onto this one.First Principles CONCERNS — unfixed siblings of the named root cause. Of the three
create_sessionsites that named no owner,session_allocation.py:640genuinely needed it: it opens a per-step session on the task run's shared runtime with the owning key already in scope. Fixed, and pinned by a parametrized source test over every shared-runtime session site so a deleted keyword argument fails the suite. The other two (session_background.py_bgruntime,review_pool.pysage pool) have no Crew session key to name and resolve to nothing today either — they are not sessions a reflexive tool acts for.SAST (Semgrep). Two findings, both about the shape of test/log code rather than a leak: a
ContextVartoken-based reset in a test that crosses an asyncio boundary (switched to value-based restore, which the rule asks for), and a logger format string containing the word "token" (reworded — the token itself was never an argument).Detect changed surface / Coverage Gate (round 1). GitHub API rate limit inside the job (
API rate limit exceeded for installation), not a code failure; green on the re-run.Review round 3 — what changed and why
GPT 5.6 (
gatewayd.py:2890): the token's second factor was checked against pids the registrant authors. Correct, and it voided the factor:indexed_pidsfolds in the stub's self-reportedancestor_pids, so the same actor that read a token out of/proc/<pid>/environcould also name that token's runtime in its own chain and satisfy both halves alone. The register now authenticates the binding againstpeer_host_pidsonly — the chain gatewayd walks from the kernel's SO_PEERCRED peer pid, which the registrant cannot write. The self-reported pids keep their one job, claim indexing, where they are harmless: a claim only ever narrows to connections carrying its own token or none. A connection whose ancestry the kernel did not attest loses the register-time shortcut, not its identity, because claim-push still reaches it through the index. Tests:test_a_self_reported_ancestry_cannot_authenticate_a_token(the spoof: stub claims the victim's runtime pids, kernel places it elsewhere) andtest_a_stolen_token_buys_nothing_outside_its_runtime. Revert-verified as its own mutation (the token is authenticated against the stub's SELF-REPORTED ancestry→ caught).Opus 4.8 (
session_provider.py:503): a cold-started session's per-turn re-claim carried an empty key, so no token could ever be re-bound. Also correct, and it silently disabled the round-2 repair path on the most common topology:rekey()is a warm-pool event, so a pool miss, pooling switched off, or a subagent's own session reaches it never —_session_keystayed"",reclaim()pushed a keyless claim, and_apply_claimrejects that as malformed before_bind_tokenruns. Every provider is now told which session it serves at CONSTRUCTION (session_key=/channel_id=, still overwritten by a laterrekey()), at all three sites that build one: the cold-start parent slot, the subagent, and the task runner's per-step session. Test:test_a_cold_started_session_can_re_bind_after_a_respawnwalks the whole chain — the keyless claim binds nothing, the seeded one re-binds and re-targets the live stub — plus a parametrized source pin over every construction site.First Principles CONCERNS: the per-turn re-claim never reached subagent sessions. True, and it was the one session type the token exists to protect: all 8
publish_turn_identitycall sites are dispatch surfaces, and a subagent's turns are driven by its manager. So the re-claim now also fires atAcpSessionProvider.stream— the boundary every session on a shared runtime crosses to take a turn, subagents included. A daemon respawn mid-run therefore costs a subagent one turn rather than the rest of the run. Test:test_a_subagents_own_turn_re_establishes_its_claim; revert-verified as its own mutation.GPT 5.6 (
session_servers.py:68): the fallback backend inherited the session's bearer name. Real and new: when the gateway is unavailable the stub EXECs the operator's own MCP server binary in its place, andfallback_execcopied the whole environment — so a third-party backend inherited a value it could later register with and be answered as this session. That entry is now popped fromexec_envbefore the exec (and before the Windows spawn that stands in for it), while the server's own declared env is still restored, which is the parity that path exists for. The non-fallback path never had this: gatewayd spawns backends from its own environment. Test:test_the_fallback_backend_never_inherits_the_token; revert-verified as its own mutation.Rebased onto
origin/main(one import-line conflict instub.pyfrom #10331'sdecode_target_args, both sides kept). 41 tests, 21/21 mutations caught,isort/flake8/mypy/black gate/docs-lint and the diff-scoped gates clean.Related Issues
N/A — no tracking issue.
Pattern harvest
Pattern: an identity keyed on a resource that is SHARED by construction (a process tree hosting N sessions) reads as correct wherever N is 1, and answers with a sibling's identity as soon as it is not. The generalizable check is not "is this source trustworthy" but "does this source's key have the same cardinality as the thing being named". A second, narrower one from review: a fail-closed rule made conditional on observing a conflict ("refuse only when a sibling is already named") fails OPEN in every state where the observation itself is missing — an empty table, a cold start, a restart — so the condition has to be the token's own unresolved state, not the presence of a neighbour. Rule candidate: review-prompt — when a change resolves "which session/tenant is calling", ask what the resolution is KEYED on, whether one key can serve two callers, and what the rule does when its own evidence store is empty.