diff --git a/src/kiro_crew/mcp_caller.py b/src/kiro_crew/mcp_caller.py index 021ae7be8cd1..4c20cdd6372f 100644 --- a/src/kiro_crew/mcp_caller.py +++ b/src/kiro_crew/mcp_caller.py @@ -329,7 +329,13 @@ def resolve_own_identity( if from_token: return OwnIdentity(session_key=from_token, source=SOURCE_TOKEN) env_key = os.environ.get("KIROCREW_SESSION_KEY", "") - if env_key: + # Rung 3 is PROCESS-keyed: the var is stamped once with the session the + # runtime was spawned for, and every MCP child of that runtime inherits + # it. On a pid the mapping records as serving several sessions it names + # one tenant and cannot say which is calling, which is the same ground + # rung 4 refuses such a pid on. Fall through to it rather than answer + # with a co-tenant's key. + if env_key and not host_pid_is_shared(): return OwnIdentity(session_key=env_key, source=SOURCE_ENV) if skip_pid_mapping: return OwnIdentity(source=SOURCE_UNRESOLVED) @@ -338,6 +344,37 @@ def resolve_own_identity( return OwnIdentity(failed=True) +def host_pid_is_shared(host_pid: str = "") -> bool: + """True only on POSITIVE evidence that a runtime serves several sessions. + + The ONE answer both identity resolvers use -- this module's ladder and + ``mcp_core``'s strict resolver -- so they cannot drift on how many sessions a + pid serves, nor on which mapping read decides it. *host_pid* defaults to this + process's own ``KIROCREW_HOST_PID``, which is what the ladder wants; the + strict resolver passes the pid it already read. + + Reads the same mapping rung 4 reads, through the same hardened reader, so the + two rungs cannot disagree about how many sessions a pid serves. Absence is + not evidence: a missing or malformed mapping answers False and leaves the env + var as authoritative as it was, so the single-session topology that var was + written for is untouched. + + Never raises. It is consulted from inside the ladder's own guard, but the + promise belongs here too: a rung that can raise would turn a resolvable + session into a failed identity. + """ + pid = host_pid or os.environ.get("KIROCREW_HOST_PID", "") + if not pid.isdigit(): + return False + try: + from kiro_crew.config.paths import config_dir + from kiro_crew.session_pid_sig import read_session_pid_mapping + + return read_session_pid_mapping(pid, config_dir()).shared + except Exception: + return False + + def _identity_from_pid_mapping() -> OwnIdentity: """Rung 4: the gateway-published pid mapping, by host pid then by ancestry. diff --git a/src/kiro_crew/mcp_core.py b/src/kiro_crew/mcp_core.py index ca048667707a..3ceb0476a5d5 100644 --- a/src/kiro_crew/mcp_core.py +++ b/src/kiro_crew/mcp_core.py @@ -54,6 +54,7 @@ from kiro_crew.mcp_caller import ( CallerContext, current_caller, + host_pid_is_shared, resolve_own_identity, set_current_caller, ) @@ -675,7 +676,12 @@ def _resolve_session_key_strict() -> str: broker stub, no config key) — which is why it is accepted ABOVE the env var: where the two disagree, a warm-pool rekey has made the env stale and the file is current. - 2. The gateway-injected ``KIROCREW_SESSION_KEY`` env var. + 2. The gateway-injected ``KIROCREW_SESSION_KEY`` env var, EXCEPT on a host + pid the mapping records as hosting several sessions. 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 — the same + ground on which source 3 refuses such a pid + (:func:`_host_pid_hosts_several_sessions`). 3. The direct ``KIROCREW_HOST_PID`` -> ``session_pid_.txt`` lookup, but ONLY when the HMAC sidecar written by the gateway verifies (:func:`kiro_crew.session_pid_sig.verify_session_pid`). @@ -725,10 +731,17 @@ def _resolve_session_key_strict() -> str: if from_token: return from_token sk = os.environ.get("KIROCREW_SESSION_KEY", "") - if sk: + host_pid = os.environ.get("KIROCREW_HOST_PID", "") + # The env var is PROCESS-keyed: it is stamped once, with the session the + # runtime was spawned for, and every MCP child of that runtime inherits the + # same value. One runtime hosts many ACP sessions, so on a runtime a signed + # mapping records as multi-tenant the var names ONE tenant and cannot say + # which one is calling — the same reason source 3 below refuses such a pid. + # Answering would attribute this caller to a co-tenant and a state-mutating + # tool would write another session's state. + if sk and not _host_pid_hosts_several_sessions(host_pid): return sk try: - host_pid = os.environ.get("KIROCREW_HOST_PID", "") if host_pid.isdigit(): from kiro_crew.session_pid_sig import verify_session_pid @@ -738,6 +751,30 @@ def _resolve_session_key_strict() -> str: return "" +def _host_pid_hosts_several_sessions(host_pid: str) -> bool: + """True only when the mapping POSITIVELY records several sessions on *host_pid*. + + Delegates to :func:`kiro_crew.mcp_caller.host_pid_is_shared`, the one answer + both resolvers share, so the strict path and the client-side ladder cannot + disagree about how many sessions a pid serves, nor about which mapping read + decides it. + + That shared answer takes the UNSIGNED read on purpose, because it only ever + DENIES an identity. A same-uid agent that forges a tenant section costs its + target a refusal that names the reason, while the MAC-verified read would + make the guard silently inert wherever the SEL trust root is missing, which + is exactly where identity is already weakest. Source 3 below still demands + the MAC, because source 3 GRANTS a key. + + Absence is NOT evidence: a missing or malformed mapping answers False and + leaves the env var exactly as authoritative as it was, so the single-session + topology the var was written for is unaffected and only a pid recorded as + shared loses it. Never raises -- an identity source that can raise would turn + a resolvable session into a crashed tool call. + """ + return host_pid_is_shared(host_pid) + + def strict_identity_diagnosis(server: str = "kirocrew-core") -> str: """Return the machine-specific reason strict identity is unavailable, or "". diff --git a/src/kiro_crew/mcp_gateway/daemon/control.py b/src/kiro_crew/mcp_gateway/daemon/control.py index c179e0abc5c7..b97a8dc31210 100644 --- a/src/kiro_crew/mcp_gateway/daemon/control.py +++ b/src/kiro_crew/mcp_gateway/daemon/control.py @@ -16,7 +16,12 @@ from kiro_crew.mcp_gateway.admission import Admission from kiro_crew.mcp_gateway.daemon import logger from kiro_crew.mcp_gateway.daemon.audit import _audit_caller_claimed, _audit_stand_down -from kiro_crew.mcp_gateway.daemon.identity import _CONN_INDEX, _bind_token, _caller_from_register +from kiro_crew.mcp_gateway.daemon.identity import ( + _CONN_INDEX, + _bind_token, + _caller_from_register, + _pid_live_tenants, +) from kiro_crew.mcp_gateway.daemon.launch import resolvable_target_stems from kiro_crew.mcp_gateway.daemon.wire import _write_json_line from kiro_crew.mcp_gateway.pool import BackendPool @@ -190,6 +195,13 @@ async def _apply_claim( raw_token = frame.get("pid_start_id") claim_token = raw_token if isinstance(raw_token, str) else None _bind_token(session_token, updated_caller, pid, claim_token) + # Does this runtime host more than one ACP session RIGHT NOW? The claiming + # session is unioned in because its own stubs may not have registered yet -- + # a claim is pushed before they launch -- so the live index alone would miss + # it. Two or more means the process tree names a RUNTIME and not a session, + # which is what the two branches below consult it for. + live_tenants = _pid_live_tenants(pid, session_token) | {updated_caller.session_key} + shared_pid = len(live_tenants) >= 2 conns = _CONN_INDEX.get(pid, set()) if not conns: # Usually the normal ordering: a session's claim is pushed before its @@ -226,6 +238,10 @@ async def _apply_claim( # Pass 1: retarget every eligible connection SYNCHRONOUSLY (no awaits) # before any eviction runs — see the wrong-principal note below. retargeted: list[tuple[Any, str]] = [] + # Connections whose identity this claim CLEARED. They are not retargeted, so + # they take no ``updated`` count and no allowed audit, but they owe the same + # subscription eviction a retarget owes. + cleared: list[Any] = [] # Snapshot: the eviction below AWAITS, and a connection disconnecting # during that await mutates the live ``conns`` set mid-iteration — # aborting the claim with no ack and leaving the remaining stubs stale. @@ -235,6 +251,54 @@ async def _apply_claim( # runtime — the ``spawn_run`` subagent case. Not a skip worth # auditing as denied: nothing was attempted against it. continue + if session_token and not conn.stub_session_token and shared_pid: + # A tokened claim meeting a TOKENLESS connection on a runtime serving + # several sessions. The connection names no session, so the only thing + # linking it to this claim is the PID — and the PID is shared, so that + # link cannot tell whether the connection is this claim's session or a + # co-tenant's. Retargeting it would hand one session's tools to + # another: its work_brief / work_report would read and write the + # claiming session's ledger. + # + # Leaving the identity in place is not the answer either: whatever it + # holds is an EARLIER guess by this same PID, so a stub belonging to + # the second tenant would go on answering as the first. That stops the + # misattribution moving without stopping it. So the identity is + # CLEARED, which is the same fail-closed state the register path gives + # a token it cannot resolve: the stub's calls carry no caller, strict + # tools refuse with a diagnosis, and a claim carrying ITS token repairs + # it through the branch above. + skipped += 1 + old_unattributable = conn.caller.session_key if conn.caller is not None else "" + conn.caller = None + # A verdict, not an absence: it is what stops the stub-initiated + # recaller from filling the key-less state this clearing creates. + conn.identity_refused = True + if old_unattributable: + # The identity is gone but its SUBSCRIPTIONS are not. They were + # granted while this connection answered as the old session, and + # resource-update URIs can carry tokens or presigned params, so + # leaving them would keep delivering that session's updates to a + # connection the gateway just declared unattributable. Evicted in + # pass 2 with the retargeted ones, because eviction awaits and + # every caller reassignment must land before the first await. + cleared.append(conn) + reason = ( + f"pid {pid} serves {len(live_tenants)} live sessions " + f"and stub {conn.stub_uuid} carries no session token — refusing to " + f"attribute it on PID alone (claim named " + f"{updated_caller.session_key}); its identity is cleared until a " + f"claim carrying its own token names it" + ) + logger.warning("claim cleared a stub it cannot attribute: %s", reason) + _audit_caller_claimed( + old_unattributable, + updated_caller.session_key, + conn.pool_label, + "denied", + reason, + ) + continue recorded_token = conn.pid_start_ids.get(pid) if claim_token is not None and recorded_token is not None and claim_token != recorded_token: skipped += 1 @@ -265,6 +329,23 @@ async def _apply_claim( conn.caller = updated_caller retargeted.append((conn, old_key)) # Pass 2: all connections now carry the new owner; run the evictions. + # + # The cleared ones first, and for the same reason the retargeted ones are + # evicted at all: a subscription granted under an identity must not outlive + # it. Here the identity went away rather than moving to a new owner, so + # there is no new session to misdeliver to -- but the OLD session's update + # URIs would still reach a connection that answers as nobody. + for conn in cleared: + if pool is None: + break + for backend in pool.backends_hosting_stub(conn.stub_uuid): + try: + await backend.evict_stub_subscriptions(conn.stub_uuid) + except Exception: + logger.exception( + "claim: subscription eviction failed for cleared stub %s", + conn.stub_uuid, + ) for conn, old_key in retargeted: if pool is not None: # The stub changed OWNER: its resource subscriptions belong to @@ -284,13 +365,32 @@ async def _apply_claim( ) updated += 1 _audit_caller_claimed(old_key, updated_caller.session_key, conn.pool_label, "allowed") - logger.info( - "stub %s claim → session_key=%s type=%s (was %s)", - conn.stub_uuid, - updated_caller.session_key, - updated_caller.session_type, - old_key or "", - ) + # Every connection reaching pass 2 carries an identity DIFFERENT from the + # claim's (an equal one is skipped above as an idempotent re-claim). On a + # single-session runtime that is the warm-pool rekey this path exists for, + # and it is routine. On a runtime hosting several sessions it means one + # session's live identity was replaced by another's, which is worth an + # operator's attention: the displaced session's tools now answer as the + # claiming session until a claim naming its own token repairs it. + if old_key and shared_pid: + logger.warning( + "stub %s claim replaced a live identity on a shared runtime: " + "session_key=%s type=%s (was %s); pid=%d hosts %d claimed sessions", + conn.stub_uuid, + updated_caller.session_key, + updated_caller.session_type, + old_key, + pid, + len(live_tenants), + ) + else: + logger.info( + "stub %s claim → session_key=%s type=%s (was %s)", + conn.stub_uuid, + updated_caller.session_key, + updated_caller.session_type, + old_key or "", + ) return {"type": "claimed", "updated": updated, "connections": len(conns), "skipped": skipped} diff --git a/src/kiro_crew/mcp_gateway/daemon/identity.py b/src/kiro_crew/mcp_gateway/daemon/identity.py index 5bb1b2e64caa..0c6d531f2629 100644 --- a/src/kiro_crew/mcp_gateway/daemon/identity.py +++ b/src/kiro_crew/mcp_gateway/daemon/identity.py @@ -74,6 +74,7 @@ class _StubConn: "pid_start_ids", "tenant_nonce", "stub_session_token", + "identity_refused", ) def __init__( @@ -90,6 +91,14 @@ def __init__( self.ancestor_pids = ancestor_pids self.pool_label = pool_label self.caller = caller + #: Set when a claim REFUSED to attribute this connection on a shared + #: runtime and cleared its identity. A key-less connection is otherwise + #: indistinguishable from one nothing has named yet, and that is the one + #: state the stub-initiated recaller is allowed to fill, so without this + #: flag a refusal would hand the stub a way to name any session it likes. + #: Refused is a VERDICT, not an absence: only claim-push may clear it, by + #: naming this connection's own token. + self.identity_refused = False self.pid_start_ids = pid_start_ids if pid_start_ids is not None else {} self.stub_session_token = stub_session_token # Namespace separator for a connection whose session the gateway cannot @@ -160,6 +169,42 @@ def _bind_token( _TOKEN_BINDINGS.popitem(last=False) +def _pid_live_tenants(pid: int, exclude_token: str = "") -> set[str]: + """Session keys that hold their OWN token-carrying connection under *pid* now. + + *exclude_token* drops the connections carrying that token, which is how a + warm-pool rekey is told from a second tenant: the claim's own stubs still + carry the PREVIOUS session's caller at the moment the claim is applied, so + counting them would make every rekey of a single-session runtime read as + sharing and log at WARNING. + + Read from the live connection index, not from :data:`_TOKEN_BINDINGS`: a + binding is append-only until the LRU cap evicts it, so a binding table says + which sessions a pid was EVER claimed for, and a warm-pool runtime claimed + first by A and later by B would read as two tenants while B is the only one + left. Counting live connections answers the question the caller actually + asks, "how many sessions does this runtime serve right now", and it needs no + process start token: a connection belonging to a dead process is gone from + the index, so a recycled pid cannot contribute a stale tenant either. + + Only a TOKEN-CARRYING connection counts. A tokenless connection's current + caller is not evidence of a separate live session -- it is whatever the last + claim retargeted it to, which on a warm-pool rekey is the session that just + handed the runtime over. Counting it would make every rekey look like + sharing. A token, by contrast, is minted per ACP session and names one, so a + connection that carries one is that session being present. + """ + tenants: set[str] = set() + for conn in _CONN_INDEX.get(pid, ()): + if not conn.stub_session_token: + continue + if exclude_token and conn.stub_session_token == exclude_token: + continue + if conn.caller is not None and conn.caller.session_key: + tenants.add(conn.caller.session_key) + return tenants + + def _token_caller( token: str, attested_pids: Collection[int] = (), @@ -540,6 +585,24 @@ def _apply_recaller(msg: dict[str, Any], conn: _StubConn, pool_label: str) -> No # ever send a recaller when their Register was key-less, so this # never blocks the intended path. existing_key = caller.session_key if caller is not None else "" + if getattr(conn, "identity_refused", False): + # A claim already refused to attribute this connection on a shared + # runtime and cleared it. That clearing is a verdict, so the key-less + # state it leaves must not read as "nothing has named me yet" and let the + # recaller fill it: the recaller key comes from the stub's own + # process-tree walk, which on a shared runtime is the very per-runtime + # answer the refusal rejected. Only a claim carrying this connection's + # own token may name it now. + logger.warning( + "stub %s sent recaller after a co-tenancy refusal; only claim-push may name it", + stub_uuid, + ) + _audit_recaller_rejected( + existing_key, + pool_label, + "recaller on a connection refused for co-tenancy", + ) + return if conn.stub_session_token: # The recaller key comes from the stub's own process-tree # walk, so it is the same per-runtime answer the register diff --git a/src/kiro_crew/mcp_gateway/gatewayd.py b/src/kiro_crew/mcp_gateway/gatewayd.py index 47918957cb2f..81e5a99888e7 100644 --- a/src/kiro_crew/mcp_gateway/gatewayd.py +++ b/src/kiro_crew/mcp_gateway/gatewayd.py @@ -193,6 +193,7 @@ _conn_index_add, _conn_index_discard, _peer_admitted, + _pid_live_tenants, _register_pids, _resolve_peer_identity, _resolve_register_identity, diff --git a/test/test_identity_topology.py b/test/test_identity_topology.py index 3b3ed84a6d2b..61e7af4ed076 100644 --- a/test/test_identity_topology.py +++ b/test/test_identity_topology.py @@ -555,6 +555,127 @@ def test_mcp_core_names_the_co_tenant_from_its_own_token(shared_topo, monkeypatc assert mcp_core._resolve_session_key() == CO_TENANT_KEY +# -- the strict resolver's env-var source on a shared pid ------------------- + + +def _wire_strict_env(monkeypatch, cfg_dir: Path, env_key: str, *, tenants) -> None: + """Run as an MCP child of a runtime whose SIGNED mapping names *tenants*. + + Published through ``publish_session_pid`` itself rather than the model's own + writer, so the bytes and the tenant section are the publisher's. Both guards + read the mapping UNSIGNED on purpose -- they only ever DENY an identity -- so + the sidecar is not what makes this fixture work; the tenant section is. + ``_wire_shared`` deliberately clears both env vars to + exercise the walk, so the env-var source needs them put back -- *env_key* is + the value the runtime was stamped with, and ``KIROCREW_HOST_PID`` names the + runtime whose mapping says how many sessions it serves. ``tenants=None`` + publishes nothing at all. + """ + from kiro_crew import session_pid_sig + + topo = ProcessTopology(cfg_dir) + topo.add(GATEWAY, 1) + topo.add(SESSION_HOST, GATEWAY) + topo.add(KIRO_CLI, SESSION_HOST) + topo.add(MCP_SERVER, KIRO_CLI) + _wire_shared(monkeypatch, topo) + monkeypatch.setattr(session_pid_sig, "config_dir", lambda: topo.cfg_dir) + monkeypatch.setattr("kiro_crew.config.paths.config_dir", lambda: topo.cfg_dir) + monkeypatch.setattr(session_pid_sig.platform_compat, "get_process_start_id", lambda pid: None) + if tenants is not None: + session_pid_sig.publish_session_pid(KIRO_CLI, SESSION_KEY, co_tenants=tenants) + monkeypatch.setenv("KIROCREW_SESSION_KEY", env_key) + monkeypatch.setenv("KIROCREW_HOST_PID", str(KIRO_CLI)) + + +def test_strict_refuses_the_env_var_on_a_shared_pid(tmp_path, monkeypatch) -> None: + """THE property. The env var is stamped once per runtime and inherited by + every MCP child of it, so on a runtime serving two sessions it names one of + them and cannot say which is calling. Answering hands this caller the + co-tenant's identity, and a state-mutating tool then writes that session's + state -- which is a work_report landing on another worker's item.""" + from kiro_crew import mcp_core + + _wire_strict_env(monkeypatch, tmp_path, SESSION_KEY, tenants=[SESSION_KEY, CO_TENANT_KEY]) + assert mcp_core._resolve_session_key_strict() == "" + + +def test_strict_refuses_even_when_the_env_var_names_the_other_tenant(tmp_path, monkeypatch) -> None: + """The value is the same for every child of the runtime, so which tenant it + happens to name changes nothing about who is calling.""" + from kiro_crew import mcp_core + + _wire_strict_env(monkeypatch, tmp_path, CO_TENANT_KEY, tenants=[SESSION_KEY, CO_TENANT_KEY]) + assert mcp_core._resolve_session_key_strict() == "" + + +def test_strict_keeps_the_env_var_on_a_sole_tenant_pid(tmp_path, monkeypatch) -> None: + """The control, and the compatibility guarantee: one session on the pid means + the env var names it, and that is the topology the var was written for.""" + from kiro_crew import mcp_core + + _wire_strict_env(monkeypatch, tmp_path, SESSION_KEY, tenants=[SESSION_KEY]) + assert mcp_core._resolve_session_key_strict() == SESSION_KEY + + +def test_strict_keeps_the_env_var_when_no_mapping_is_published(tmp_path, monkeypatch) -> None: + """Absence is not evidence of sharing. A deployment that publishes no mapping + keeps the env var exactly as authoritative as it was, so the guard costs an + unshared install nothing.""" + from kiro_crew import mcp_core + + _wire_strict_env(monkeypatch, tmp_path, SESSION_KEY, tenants=None) + assert mcp_core._resolve_session_key_strict() == SESSION_KEY + + +def test_the_shared_ladder_refuses_the_env_var_on_a_shared_pid(tmp_path, monkeypatch) -> None: + """The env rung of ``resolve_own_identity`` holds the same line. + + That ladder is the one client-side resolver every consumer shares, so + guarding only the strict helper would leave the identical process-keyed rung + answering with a co-tenant's key for every caller that goes through it. + """ + from kiro_crew import mcp_caller + + _wire_strict_env(monkeypatch, tmp_path, SESSION_KEY, tenants=[SESSION_KEY, CO_TENANT_KEY]) + ident = mcp_caller.resolve_own_identity() + assert ident.source != mcp_caller.SOURCE_ENV + assert ident.session_key != SESSION_KEY + + +def test_the_shared_ladder_keeps_the_env_var_on_a_sole_tenant_pid(tmp_path, monkeypatch) -> None: + """The control: one session on the pid and the env rung answers as it always did.""" + from kiro_crew import mcp_caller + + _wire_strict_env(monkeypatch, tmp_path, SESSION_KEY, tenants=[SESSION_KEY]) + ident = mcp_caller.resolve_own_identity() + assert (ident.session_key, ident.source) == (SESSION_KEY, mcp_caller.SOURCE_ENV) + + +def test_a_parent_with_no_usable_token_is_refused_on_a_shared_runtime( + tmp_path, monkeypatch +) -> None: + """The deliberate trade, pinned so it is a decision and not an oversight. + + A ``session_sharing`` parent whose own token cannot be verified -- the SEL + trust root is missing, so the token channel fails closed -- is refused on a + runtime a subagent has joined, EVEN THOUGH the runtime's env var names that + parent. The parent loses the tools that demand a strict identity until a + usable token names it. + + This is chosen over the alternative. Answering would hand the parent's key to + whichever of the two sessions is calling, and the subagent is the one that + would then write the parent's state. A refusal that names its reason is + recoverable; a silent write to another session's state is not. + """ + from kiro_crew import mcp_core + + _wire_strict_env(monkeypatch, tmp_path, SESSION_KEY, tenants=[SESSION_KEY, CO_TENANT_KEY]) + assert mcp_core._resolve_session_key_strict() == "" + # And the diagnosis is reachable, so an operator is not left guessing. + assert isinstance(mcp_core.strict_identity_diagnosis(), str) + + # -- walk copy 3: the policy walk in mcp_shared ----------------------------- diff --git a/test/test_mcp_gateway_stub_session_token.py b/test/test_mcp_gateway_stub_session_token.py index 597413d01187..97943b833a8f 100644 --- a/test/test_mcp_gateway_stub_session_token.py +++ b/test/test_mcp_gateway_stub_session_token.py @@ -525,6 +525,220 @@ async def test_a_claim_for_one_session_leaves_its_sibling_alone( await _close(b_reader, b_task) +@pytest.mark.asyncio +async def test_a_tokenless_stub_is_not_handed_to_a_co_tenant( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """A tokenless stub on a runtime hosting SEVERAL sessions stays where it is. + + One runtime, three connections: two that name their session with a token, and + one launched outside the token path that names none. While only one session has + claimed, the tokenless stub rides along on the process tree exactly as it always + did — the runtime still has one plausible owner. Once a SECOND session claims the + same runtime, the tree stops naming a session, and the next claim must not take + the tokenless stub with it: that stub's ``work_brief`` and ``work_report`` would + then read and write the claiming session's ledger instead of its own. + """ + token_c = "c" * 64 + a_backend, a_reader, a_task = await _live_conn(monkeypatch, "", TOKEN_A, "stub-a") + b_backend, b_reader, b_task = await _live_conn(monkeypatch, "", TOKEN_B, "stub-b") + plain_backend, plain_reader, plain_task = await _live_conn(monkeypatch, "", "", "stub-plain") + + # One session so far: the runtime has a single plausible owner, so the + # tokenless stub is still re-targeted on the tree. Unchanged behavior. + first = await gw._apply_claim(_claim_with_token(_PID, PARENT_KEY, TOKEN_A)) + assert first["updated"] == 2 and first["skipped"] == 0 + assert (await _next_caller(a_backend, a_reader)).session_key == PARENT_KEY + assert (await _next_caller(plain_backend, plain_reader)).session_key == PARENT_KEY + + # A second session claims the same runtime. Now the PID names two sessions, + # so it names neither: the tokenless stub is not reassigned. + second = await gw._apply_claim(_claim_with_token(_PID, SUB_KEY, TOKEN_B)) + assert second["updated"] == 1, "only the stub whose token the claim names" + assert second["skipped"] == 1, "the tokenless stub is not retargeted" + assert (await _next_caller(b_backend, b_reader)).session_key == SUB_KEY + # THE property, and it is CLEARED rather than frozen: leaving the earlier + # PARENT_KEY in place would let a stub that belongs to the second tenant go + # on answering as the first, which stops the misattribution moving without + # stopping it. No caller means strict tools refuse with a diagnosis. + assert await _next_caller(plain_backend, plain_reader) is None + + # A claim naming the tokenless stub's runtime for a THIRD session cannot + # attribute it either, and does not re-grant the identity just cleared. + third = await gw._apply_claim(_claim_with_token(_PID, "dashboard:chat-9", token_c)) + assert third["skipped"] == 1 + assert await _next_caller(plain_backend, plain_reader) is None + + await _close(a_reader, a_task) + await _close(b_reader, b_task) + await _close(plain_reader, plain_task) + + +@pytest.mark.asyncio +async def test_replacing_a_live_identity_on_a_shared_runtime_warns( + monkeypatch: pytest.MonkeyPatch, + caplog: pytest.LogCaptureFixture, +) -> None: + """Overwriting a DIFFERENT live identity on a shared runtime is a warning. + + A tokenless claim keeps its PID-wide reach, so on a runtime hosting several + sessions it still replaces each one's live identity. That is the case an + operator has to be able to find in a log: on a single-session runtime the same + replacement is just the warm-pool rekey this path exists for, and stays at INFO. + """ + a_backend, a_reader, a_task = await _live_conn(monkeypatch, "", TOKEN_A, "stub-a") + b_backend, b_reader, b_task = await _live_conn(monkeypatch, "", TOKEN_B, "stub-b") + await gw._apply_claim(_claim_with_token(_PID, PARENT_KEY, TOKEN_A)) + + # One claimed session: a re-claim of that same slot is the routine rekey. + caplog.clear() + with caplog.at_level(logging.INFO): + await gw._apply_claim(_claim_with_token(_PID, "dashboard:chat-2", TOKEN_A)) + assert not [r for r in caplog.records if r.levelno >= logging.WARNING] + + # Two claimed sessions, then a tokenless claim that reaches both: each stub + # loses a live identity to a session that is not its own. + await gw._apply_claim(_claim_with_token(_PID, SUB_KEY, TOKEN_B)) + caplog.clear() + with caplog.at_level(logging.INFO): + ack = await gw._apply_claim(_claim(_PID, "dashboard:chat-3")) + assert ack["updated"] == 2, "a tokenless claim keeps the PID-wide reach it had" + warnings = [ + r.getMessage() + for r in caplog.records + if r.levelno >= logging.WARNING and "replaced a live identity" in r.getMessage() + ] + assert len(warnings) == 2, warnings + assert any("stub-a" in m for m in warnings) and any("stub-b" in m for m in warnings) + # The token itself must never reach a log record. + assert not any(TOKEN_A in m or TOKEN_B in m for m in warnings) + + await _close(a_reader, a_task) + await _close(b_reader, b_task) + + +@pytest.mark.asyncio +async def test_a_refused_stub_cannot_name_itself_with_a_recaller( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """Clearing an identity must not hand the stub a way to choose a new one. + + The recaller is deny-by-default and may fill exactly one state: a key-less, + tokenless connection that nothing has named yet. A co-tenancy refusal + produces a connection that LOOKS like that, so without a verdict flag the + refused stub could name any session it liked -- and the key it would send + comes from its own process-tree walk, which on a shared runtime is the very + per-runtime answer the refusal rejected. + """ + a_backend, a_reader, a_task = await _live_conn(monkeypatch, "", TOKEN_A, "stub-a") + b_backend, b_reader, b_task = await _live_conn(monkeypatch, "", TOKEN_B, "stub-b") + plain_backend, plain_reader, plain_task = await _live_conn(monkeypatch, "", "", "stub-plain") + + await gw._apply_claim(_claim_with_token(_PID, PARENT_KEY, TOKEN_A)) + refusing = await gw._apply_claim(_claim_with_token(_PID, SUB_KEY, TOKEN_B)) + assert refusing["skipped"] == 1 + assert await _next_caller(plain_backend, plain_reader) is None + + # The refused stub now asks for an identity of its own choosing. + plain_reader.feed(_register(PARENT_KEY)) + plain_reader.feed({"type": "recaller", "session_key": PARENT_KEY}) + assert ( + await _next_caller(plain_backend, plain_reader) is None + ), "a refusal is a verdict; only claim-push may name this connection" + + await _close(a_reader, a_task) + await _close(b_reader, b_task) + await _close(plain_reader, plain_task) + + +@pytest.mark.asyncio +async def test_clearing_an_identity_evicts_its_subscriptions( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """A subscription granted under an identity must not outlive it. + + The cleared connection is not retargeted, so it never reaches the retarget + list that pass 2 evicts from. Skipping it would leave the OLD session's + resource-update URIs -- which can carry tokens or presigned params -- still + being delivered to a connection that answers as nobody. + """ + a_backend, a_reader, a_task = await _live_conn(monkeypatch, "", TOKEN_A, "stub-a") + b_backend, b_reader, b_task = await _live_conn(monkeypatch, "", TOKEN_B, "stub-b") + plain_backend, plain_reader, plain_task = await _live_conn(monkeypatch, "", "", "stub-plain") + + # Give the tokenless stub an identity, so the clearing has something to take. + await gw._apply_claim(_claim_with_token(_PID, PARENT_KEY, TOKEN_A)) + assert (await _next_caller(plain_backend, plain_reader)).session_key == PARENT_KEY + + evicted: list[str] = [] + + class _EvictingPool(_FakePool): + def backends_hosting_stub(self, stub_uuid: str) -> Any: + return [self] + + async def evict_stub_subscriptions(self, stub_uuid: str) -> None: + evicted.append(stub_uuid) + + ack = await gw._apply_claim(_claim_with_token(_PID, SUB_KEY, TOKEN_B), _EvictingPool()) + assert ack["skipped"] == 1 + assert "stub-plain" in evicted, "the cleared connection owes the same eviction" + + await _close(a_reader, a_task) + await _close(b_reader, b_task) + await _close(plain_reader, plain_task) + + +@pytest.mark.asyncio +async def test_sequential_claims_on_one_runtime_are_not_sharing( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """A runtime claimed by one session and later by another is NOT shared. + + "How many sessions has this pid ever been claimed for" and "how many does it + serve now" are different questions, and only the second one makes a PID-keyed + answer a guess. A warm-pool runtime hands over: session A finishes, session B + takes the process. Reading that as two tenants would refuse to retarget the + runtime's tokenless stubs, so they would keep A's identity while B is the + only session there -- which is the very misattribution this guard exists to + prevent, re-created on a single-session runtime. + """ + plain_backend, plain_reader, plain_task = await _live_conn(monkeypatch, "", "", "stub-plain") + + first = await gw._apply_claim(_claim_with_token(_PID, PARENT_KEY, TOKEN_A)) + assert first["updated"] == 1 and first["skipped"] == 0 + assert (await _next_caller(plain_backend, plain_reader)).session_key == PARENT_KEY + + # The handover. Two tokens have now named this pid, but only one session is + # on it, so the tokenless stub must follow. + second = await gw._apply_claim(_claim_with_token(_PID, SUB_KEY, TOKEN_B)) + assert second["skipped"] == 0, "a handover is not a co-tenant" + assert second["updated"] == 1 + assert (await _next_caller(plain_backend, plain_reader)).session_key == SUB_KEY + + await _close(plain_reader, plain_task) + + +@pytest.mark.asyncio +async def test_a_rekey_of_one_slot_is_not_sharing(monkeypatch: pytest.MonkeyPatch) -> None: + """Re-claiming the SAME token slot is a rekey, not a second tenant. + + The claim's own stubs still carry the previous session's caller at the moment + it is applied, so counting them would make every warm-pool rekey of a + single-session runtime read as shared. + """ + a_backend, a_reader, a_task = await _live_conn(monkeypatch, "", TOKEN_A, "stub-a") + plain_backend, plain_reader, plain_task = await _live_conn(monkeypatch, "", "", "stub-plain") + + assert (await gw._apply_claim(_claim_with_token(_PID, PARENT_KEY, TOKEN_A)))["skipped"] == 0 + rekey = await gw._apply_claim(_claim_with_token(_PID, "dashboard:chat-2", TOKEN_A)) + assert rekey["skipped"] == 0, "the slot's own stubs are not co-tenants of it" + assert (await _next_caller(a_backend, a_reader)).session_key == "dashboard:chat-2" + assert (await _next_caller(plain_backend, plain_reader)).session_key == "dashboard:chat-2" + + await _close(a_reader, a_task) + await _close(plain_reader, plain_task) + + @pytest.mark.asyncio async def test_a_claim_binds_its_token_even_when_it_matches_nothing() -> None: """A session's claim is pushed BEFORE its stubs launch, so "matched zero" is