Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 38 additions & 1 deletion src/kiro_crew/mcp_caller.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -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.

Expand Down
43 changes: 40 additions & 3 deletions src/kiro_crew/mcp_core.py
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,7 @@
from kiro_crew.mcp_caller import (
CallerContext,
current_caller,
host_pid_is_shared,
resolve_own_identity,
set_current_caller,
)
Expand Down Expand Up @@ -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_<pid>.txt``
lookup, but ONLY when the HMAC sidecar written by the gateway
verifies (:func:`kiro_crew.session_pid_sig.verify_session_pid`).
Expand Down Expand Up @@ -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

Expand All @@ -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 "".

Expand Down
116 changes: 108 additions & 8 deletions src/kiro_crew/mcp_gateway/daemon/control.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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.
Expand All @@ -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
Expand Down Expand Up @@ -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
Expand All @@ -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 "<none>",
)
# 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 "<none>",
)
return {"type": "claimed", "updated": updated, "connections": len(conns), "skipped": skipped}


Expand Down
63 changes: 63 additions & 0 deletions src/kiro_crew/mcp_gateway/daemon/identity.py
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,7 @@ class _StubConn:
"pid_start_ids",
"tenant_nonce",
"stub_session_token",
"identity_refused",
)

def __init__(
Expand All @@ -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
Expand Down Expand Up @@ -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] = (),
Expand Down Expand Up @@ -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
Expand Down
1 change: 1 addition & 0 deletions src/kiro_crew/mcp_gateway/gatewayd.py
Original file line number Diff line number Diff line change
Expand Up @@ -193,6 +193,7 @@
_conn_index_add,
_conn_index_discard,
_peer_admitted,
_pid_live_tenants,
_register_pids,
_resolve_peer_identity,
_resolve_register_identity,
Expand Down
Loading
Loading