Skip to content

fix(dashboard): attest a session key before member scope trusts it - #12164

Merged
bolichen97 merged 1 commit into
mainfrom
fix/member-scope-requires-attestation
Sep 20, 2026
Merged

bolichen97 merged 1 commit into
mainfrom
fix/member-scope-requires-attestation

Conversation

@iamwhatever

@iamwhatever iamwhatever commented Sep 20, 2026 •

Copy link
Copy Markdown
Contributor

Problem / Motivation

Any program on the machine that knows the gateway's internal secret could act as another chat session. It read a victim's session key out of ~/.kiro/crew/sessions/*.jsonl, sent that key in the X-Session-Key header, and member_request_scope believed it. The caller then got that session's memory store, its chat controls, its spawn and directive routes.

Why it matters

This is the impersonation boundary between two agents on one host. A member's private memory is supposed to stay private from other members, and the chat-control refusals are supposed to hold per session. Both rest on member_request_scope answering "who is calling" correctly. The sibling path for the same question, memory_request_identity, already demanded proof; this one took the caller's word.

What changed (motivation → approach → change)

A header is a claim. Proof is what the two attestation channels carry, and member_request_scope now asks for one.

Request shape Before After
internal secret + bare X-Session-Key verified refused
peer_verified (unix-socket kernel attestation) verified verified
X-Session-Token that verifies to that key verified verified
token that verifies to a different key verified refused
no session key (the owner surface) verified verified

Root cause: the member-memory refactor moved scope resolution out of member_memory_auth.memory_request_identity and into a new _resolve in _shared.py that read the header directly. The gate did not come with it.

The check now lives in one place, session_key_is_attested in member_memory_auth.py, and both authorization sites call it, so the two cannot drift apart again. An unattested key returns an unverified scope, which existing callers already turn into 409 member_identity_unavailable or a 403. The execution record is not read at all on a name nobody vouched for.

Two legitimate callers had no attestation to offer, and both get a real one rather than an exemption.

Script crons had neither channel: nothing publishes a signed pid mapping for a sandbox launcher's pid, so the kernel peer walk cannot speak for them. Their launcher in cron_script.py now mints a stub session token for cron:<job id> and publishes its signed mapping before the spawn, using the primitives every ACP session already uses. One token per RUN: its mapping lives exactly as long as the run and is retracted in the run's finally, on every exit path including the early overlap return and the spawn exception, so completed runs leave no mapping behind and there is no cache to bound and nothing to orphan.

Internal callers attached the token on one verb only. The gateway's session-scoped reads authorize on the declared key exactly as the writes do, so _get / _patch / _put / _delete in mcp_core.py and the hand-built tool-policy request in mcp_shared.py now carry it too. That read is the one that bites: an unresolved managed tool policy fails closed, so a header missing there darkened a session's whole tool surface rather than one call. The header has one definition now, session_token_header in session_token_sig.py, beside the verifier that reads it.

Backwards compatibility

Breaking: a request carrying only the internal secret and an X-Session-Key no longer resolves to that session. Writer sweep re-run on fresh origin/main @ 954fb69:

Caller Proof it carries Outcome
MCP servers of a one-session ACP client X-Session-Token, now on every verb unchanged
MCP servers on the shared kiro runtime per-session token on each element unchanged
The managed tool-policy read token added here unchanged
Unix-socket callers with a signed pid sidecar (workflow workers, chat slots) peer_verified unchanged
Script crons' MCP children published token, added here unchanged
Command crons no session key at all unaffected
ScriptContext._post to /api/send-message n/a, never reaches member scope unaffected
Browser with a dashboard cookie no internal auth refused, as before

Tests

test_member_memory_auth.py pins the four outcomes of the new gate, including that the canonical record is never read for an unattested key. test_session_token_header_parity.py drives every transport helper and the tool-policy read for real and fails if one declares a key without the token, which is the defect class that took out the tool surface; it fails on a reverted _get and passes with it. test_directive_queue.py pins the 409 at a real route and that nothing is parked. test_cron_script_identity.py pins that the child's env carries a token verify_session_token() maps back to that job, that two jobs get different tokens, that a second run republishes one mapping instead of adding one, that an inherited token is overwritten, that two runs of one job get different tokens and leave no mapping, and that the mapping is retracted on the exception and early-return paths too; test_session_token_sig.py pins that retracting removes the file, drops the identity, and no-ops on an empty or unknown token. Eleven existing internal-caller doubles across seven files now carry an attestation, because a double without one is refused for a transport reason and stops measuring what it was written for.

Manual verification

The E2E (stub ACP backend, offline) lane is the end-to-end proof and runs in CI; this host has no usable sandbox backend (unshare(CLONE_NEWUSER) returns EPERM), so it cannot run locally and the parity test covers the same mechanism at the unit level instead.

Related Issues

no linked issue: this is a regression found by code audit rather than a filed report. The refactor that dropped the gate is #11780.

Pattern harvest

Rule candidate: review-prompt

Pattern: one half of a two-part contract wired at some call sites and not others — an authorization decision that reads a caller-supplied identity while a sibling path requires proof of it, and a proof header attached on one verb while the others send the same claim bare.

Checklist

  • At most two commits (one is the norm), with a Conventional Commits title (feat|fix|docs|refactor|perf|test|chore|ci|build|revert: ...)
  • Existing tests pass and new tests added for new functionality
  • Self-review completed; code follows project style guidelines
  • Documentation updated (if applicable)
  • No secrets, credentials, or internal references in the diff

@iamwhatever
iamwhatever requested review from a team and patrigao September 20, 2026 03:04
@github-actions github-actions Bot added the readiness: checking Automated validation is still running label Sep 20, 2026
@iamwhatever

Copy link
Copy Markdown
Contributor Author

Intent: Close a same-host impersonation hole: member_request_scope must not treat a caller-supplied X-Session-Key as an authenticated identity, so one agent on the machine cannot act inside another session's memory and chat controls.
Not a goal: Redesigning the attestation channels themselves, widening the check to routes that do not resolve a member scope, or changing what a verified caller is allowed to do.

@github-actions

github-actions Bot commented Sep 20, 2026 •

Copy link
Copy Markdown
Contributor

GPT 5.6 Review — ✅ no blocking findings

GPT 5.6 completed its review of 1a2a5a6e6e2f9bc0fa6637869fc007cfd7fb6b90 and found no blocking issues.

This comment is updated in place on each push.

Review details

No findings.
[GPT-REVIEWED] 1a2a5a6

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

@github-actions

github-actions Bot commented Sep 20, 2026 •

Copy link
Copy Markdown
Contributor

Design Review (Fable 5) — ✅ PASS

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

Design-Verdict: PASS

Verify the E2E (stub ACP backend, offline) lane ran green on this revision — it is the only end-to-end proof a script cron's MCP children still authenticate.

[DESIGN-REVIEWED] 1a2a5a6

@github-actions

github-actions Bot commented Sep 20, 2026 •

Copy link
Copy Markdown
Contributor

First Principles Review (Fable 5) — ✅ PASS

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

First-Principles-Verdict: PASS

The declared breaking change is the one residual: any out-of-tree internal caller sending only secret + bare X-Session-Key is now refused — confirm none exists in real deployments.

The defect has checkable provenance: the base diff shows memory_request_identity's own docstring pinning "a caller-controlled X-Session-Key is therefore not enough" while _shared.py's _resolve read the header bare, and the added test_bare_session_header_is_not_a_verified_scope fails on base. The fix sits at cause level — one shared session_key_is_attested (2 consumers, grepped) replaces the copy that drifted in #11780. Sibling sweep: I grepped every X-Session-Key sender under src/; all now carry the token (mcp_core verbs, mcp_shared), are kernel-attested (mcp_computer unix leg, and its /api/computer-use/invoke route never calls member_request_scope — 2 consuming files, both checked), or target non-member-scoped routes (ScriptContext._post → /api/send-message, verified: the only member_request_scope call in messaging.py is the spawn handler). New surface reuses existing primitives; no zero-consumer symbol shipped.

What this change ships

Inventory (8 items) — 8 justified

Intent: FIX — stop a same-host process holding the internal secret from impersonating another session by replaying its key.

  1. A bare secret + copied session key no longer buys another session's member scope; it gets the 409/403 refusal — justified
  2. Both authorization sites now share one attestation answer (session_key_is_attested), so they cannot drift apart again — justified
  3. Script cron runs mint a per-run signed token, published before spawn and retracted on every exit path — justified
  4. MCP read/delete verbs now send X-Session-Token like the writes, so session-scoped reads stay answered — justified
  5. The managed tool-policy read carries the token, keeping a session's tool surface from failing closed — justified
  6. The token header has one definition, beside its verifier (2 consumers, counted) — justified
  7. New retract_session_token, the publish counterpart (1 consumer, not generalized) — justified
  8. The internal chat middleware's bare-key refusal is now 409 member_identity_unavailable instead of 403 — declared consequence of item 1 — justified

[FIRST-PRINCIPLES-REVIEWED] 1a2a5a6

@github-actions

github-actions Bot commented Sep 20, 2026 •

Copy link
Copy Markdown
Contributor

Opus 4.8 Review — ✅ no blocking findings

Reviewed 1a2a5a6e6e2f9bc0fa6637869fc007cfd7fb6b90 — this comment is updated in place on each push.

Review details

No findings.

[OPUS-REVIEWED] 1a2a5a6

Verdict parsed from the review's SHA-scoped output markers for commit 1a2a5a6e6e2f9bc0fa6637869fc007cfd7fb6b90.

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

@github-actions github-actions Bot added readiness: action required A blocking check or review needs attention and removed readiness: checking Automated validation is still running labels Sep 20, 2026
@iamwhatever
iamwhatever force-pushed the fix/member-scope-requires-attestation branch from 1d5c076 to d660c36 Compare September 20, 2026 03:29
@iamwhatever

Copy link
Copy Markdown
Contributor Author

self-added: yes
mechanism: per-job stub token for script crons, published before the spawn

  • span=9005db27295a — cron_script.py comment overclaimed mapping lifetime: fixed in d660c36.

Upheld. The comment said a finished run "leaves nothing stale behind", and that is not what the code does: the token stays in _SCRIPT_SESSION_TOKENS and its signed mapping stays on disk after the run ends. Only the per-JOB bound was true.
The comment now states both facts: one mapping per script job however often it fires, and both the cached token and the mapping outlive a run, retired by the startup/shutdown prune that bounds every session-token file rather than at the end of a run.
Kept the per-job design rather than retracting per run. Retraction would need a new public API on the token protocol, and a per-run mint is what would make the directory grow per firing; one stable name per job is also the exact analogue of an AcpClient, which keeps its token and republishes the mapping across a rekey.

@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 Sep 20, 2026
@iamwhatever

Copy link
Copy Markdown
Contributor Author
  • span=462f7a150dcf — stolen process tokens still permit session impersonation: rebutted, not a defect of this change.

Not a defect. The residual is the token protocol's own stated boundary, and it predates this diff: session_token_sig's module docstring puts it OUT OF SCOPE in those words — "a same-uid process that can read the mapping directory ... can already read the pid mappings and present another session's key through KIROCREW_SESSION_KEY, and a shell-capable same-uid agent can bypass client-side resolution entirely by minting a local API token. Same-uid processes are inside the boundary."
The change is monotonic hardening, never a widening. On the base, member scope was granted for the internal secret plus ANY key read out of a world-readable ~/.kiro/crew/sessions/*.jsonl transcript. After it, the same caller additionally needs a live victim process to steal an environ value from, or a kernel peer attestation. Strictly harder in every case, weaker in none — so the finding names a residual the diff reduced.
The proposed fix removes the only attestation TCP has. Binding token verification to a kernel-attested runtime identity IS peer_verified, and it is already the FIRST branch (member_memory_auth.py:83). The token branch exists for the loopback-TCP case where the kernel peer walk resolves nothing; requiring attestation there collapses both branches into one and refuses every TCP MCP caller, which is the regression this round's E2E (stub ACP backend, offline) red already demonstrated.
The real remedy is named in the same docstring and is orthogonal to this PR: "Authenticating the calling process itself (SO_PEERCRED over a gateway-owned socket) is the stronger, orthogonal follow-up tracked with the pid sidecar's own note." That moves the whole protocol, not this gate.

@iamwhatever
iamwhatever force-pushed the fix/member-scope-requires-attestation branch from d660c36 to de434f1 Compare September 20, 2026 03:57
@iamwhatever

Copy link
Copy Markdown
Contributor Author

self-added: yes
mechanism: FIFO-bounded cache of per-job stub tokens in the script-cron launcher

  • span=31cfe0f000f2 — deleted script jobs remain permanently retained: fixed in de434f1.

Upheld. _SCRIPT_SESSION_TOKENS was a process-global dict with one entry per distinct script job id and no eviction anywhere in src/, so create/fire/delete of many unique jobs grew the gateway heap with no count bound. The anchored rule carries blocking: true and the reading is correct.
Fixed by bounding the cache itself: _SCRIPT_SESSION_TOKENS_CAP = 1024 with FIFO eviction under a threading.Lock, the publish left outside the lock so concurrent jobs do not serialise on blocking file I/O. Eviction is safe and the test says so — the evicted job's next run mints and publishes again, its identity is unchanged, and its earlier mapping stays valid.
Not fixed through the cron-removal path as suggested. Removal lives in another module, and importing it into the launcher would add a dependency from the spawn path to the scheduler's lifecycle; bounding the field the rule is about needs no such edge, and it also covers the case removal never sees, a job id that simply stops firing.
Not fixed by minting per run either: publish_session_token writes one file per distinct token and those files are pruned only at gateway startup/shutdown, so that trades a bounded dict for an unbounded directory.
Regression test test_fifo_cache_is_bounded_and_evicted_jobs_get_verifiable_tokens fails with assert 4 <= 3 when the eviction is removed.

@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 Sep 20, 2026
@iamwhatever
iamwhatever force-pushed the fix/member-scope-requires-attestation branch from de434f1 to 2fb3b7b Compare September 20, 2026 04:06
@iamwhatever

Copy link
Copy Markdown
Contributor Author

Rebased: main moved in nothing this PR touches (e8b94aa -> f31f25a); CI re-running. The rebase is what clears the First Principles blocker — see the two dispositions below.

@iamwhatever

Copy link
Copy Markdown
Contributor Author
  • span=1ccfb11b2451 — item 8, CI fleet migration rides along undeclared: fixed by rebase in 2fb3b7b.

The premise was a diff-form artefact, and the Clears-when condition is now met either way. f31f25a8a is not a commit this branch carries: it landed on main AFTER this branch's merge-base e8b94aaef7f3, so the branch was simply behind.
Measured on the pushed head de434f191e04: git diff --name-only origin/main...HEAD returned 20 files and zero matching .github/workflows|docs/ci|test_ci_|test_e2e_ci. The two-dot git diff --name-only origin/main HEAD returned those same 20 plus .github/workflows/ci.yml, docs/ci/ci-and-reviews.md, test_ci_fleet_routing_expression_parity.py, test_ci_nonroot_boundary.py and test_e2e_ci_scheduling.py — main's own commit rendered as changes on this side because the branch lacked it.
Rebased onto f31f25a8a regardless, which is the named subtraction. Both diff forms now match at zero CI hunks, and the rebase was clean because the overlap between that commit's six files and this PR's twenty is empty.

@iamwhatever
iamwhatever force-pushed the fix/member-scope-requires-attestation branch from f35947b to ab9cdeb Compare September 20, 2026 08:44
@iamwhatever

Copy link
Copy Markdown
Contributor Author

self-added: yes
mechanism: expected_result parameter on the launcher-env test helper

  • span=519c04c261c6 — launcher result ratchet was weakened: fixed in ab9cdeb.

Upheld, and the reading is exactly right. _capture_launcher_env asserted result == {"status": "ok"} on main; adding the overlap-return case relaxed it to result["status"] == expected_status, so any extra or wrong field in a launcher result would have passed. The helper is the only reader of that result, so nothing else would have caught it.
The relaxation was never forced by the new path, which is what makes it a ratchet breach rather than a cost. Restored to whole-dict equality: the helper takes expected_result and asserts result == wanted, with the overlap case naming its own two-key dict {"status": "skipped", "error": "Another run of this job is already starting or running"}.
The result is tighter than main rather than merely equal, because main had no overlap-return case to pin at all. Proved by injecting a stray field into that return: the helper fails with assert {'status': 's...ray': 'field'} == {...}, and the file is 16/16 green without it.

@iamwhatever

Copy link
Copy Markdown
Contributor Author
  • span=f4bb395025ca — one shared internal-auth header builder instead of five hand-assembled trios: accepted-and-deferred.

Agreed on the substance, and it is the right generalisation of this defect: the header trio is assembled by hand at five sites, and a sixth hand-built call site could repeat the same omission. A builder would make that structurally impossible instead of leaving the parity test to notice.
Deferred because it is a refactor of every internal call site, not part of closing the impersonation hole, and it would rewrite the headers of verbs this PR does not otherwise touch. Landing it here would also put the fix and a cross-cutting refactor behind one review.
Two things this PR already banks toward it: the token half now has a single definition in session_token_sig.session_token_header, and test_session_token_header_parity.py drives every verb for real, so it is the test a builder would be written against.
Tracked as the PR's own Pattern harvest entry (Rule candidate: review-prompt), which names this exact class: one half of a two-part contract wired at some call sites and not others.

@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 Sep 20, 2026
member_request_scope read the caller-supplied X-Session-Key as the
authenticated identity whenever the request carried the internal secret,
so any same-machine process holding that secret could name another
session's key and act inside that session's scope.

The declared key is now accepted only behind one of the two transport
attestations the sibling memory path already requires: the unix-socket
kernel peer attestation, or a signed per-session token that verifies back
to that same key. Both live in one shared helper,
member_memory_auth.session_key_is_attested, so the two authorization
sites answer the same question the same way. An unattested key yields an
unverified scope, which the callers turn into their established 409
member_identity_unavailable / 403 refusals, and the canonical execution
record is never read on a name the caller merely asserted.

Two legitimate callers lacked an attestation, and both get a real one
rather than an exemption.

Script crons had neither: no signed pid mapping names a sandbox
launcher's pid, so the peer walk cannot vouch for them. Their launcher
now mints a stub session token for cron:<job id> and publishes its signed
mapping before the spawn. One token per run: the mapping lives exactly as
long as the run and is retracted in the run's finally, on every exit path
including the early overlap return and the spawn exception, so completed
runs leave nothing behind. retract_session_token is a thin public wrapper
over the module's own removal primitive.

Internal requests attached the token on one verb only. The gateway's
session-scoped READS authorize on the declared key the same way the
writes do, so _get / _patch / _put / _delete and the hand-built
tool-policy request now carry it too. That read is why this matters: an
unresolved managed tool policy fails closed, so a missing header there
took out a session's whole tool surface rather than one call. The header
now has one definition, session_token_sig.session_token_header, beside
the verifier that reads it.
@iamwhatever
iamwhatever force-pushed the fix/member-scope-requires-attestation branch from ab9cdeb to 1a2a5a6 Compare September 20, 2026 11:35
@iamwhatever

Copy link
Copy Markdown
Contributor Author

Rebased onto 954fb69; CI re-running. Not a content change. Backend Tests (Windows) (1) was failing four test_acp_runtime.py reap-amendment tests that fail identically on other heads; main took the fix as #12269. Re-running the shard alone could not pick it up, because a workflow re-run replays the original merge commit rather than a recomputed one, so a new head was needed. Scoped tests pass on the rebased tree (1098).

@github-actions github-actions Bot added readiness: passed Eligible automated validation passed for the current revision and removed readiness: checking Automated validation is still running labels Sep 20, 2026
@bolichen97
bolichen97 enabled auto-merge (squash) September 20, 2026 17:08

@bolichen97 bolichen97 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.

Reviewed against the pr-triage-pipeline gates plus a full-diff security audit.

fix(dashboard), 21 files. Stops member_request_scope and memory_request_identity from treating a caller-declared X-Session-Key as the authenticated member identity whenever the request carries X-Internal-Secret. The declared key is now trusted only if session_key_is_attested() confirms it.

Security-flagged Tier 2: three checklist answers YES (modifies_auth_or_authz, modifies_trust_boundary, adds_or_changes_secret_handling). Worth recording that the security-path denylist does NOT match this diff even though it is an auth change: member_memory_auth.py is not a token_auth* prefix, dashboard/handlers/_shared.py is not the denylisted handlers/session*, and session is a domain noun. The checklist caught it, not the path gate.

[Security: the risk is not realized by this change, it is closed by it. Before, the internal secret only proved 'came through the local gateway', so any same-machine process holding it could read another session's key off a transcript, declare it, and act inside that session's V2 member scope, reading and writing private member memory and parking directives. That is horizontal session impersonation across the internal trust boundary. After, attestation requires one of two channels that both bind the request to the key's true owner: request['peer_verified'], the kernel AF_UNIX peer attestation set server-side by middleware and unsettable via any header; or a signed X-Session-Token that must HMAC-verify against the SEL trust root AND map to that specific declared key. A caller holding only the internal secret plus a stolen key name has neither. A caller holding its own valid token cannot use it against a victim, pinned by test_token_naming_another_session_attests_neither, so there is no confused deputy. The residual is classic bearer-token replay by a process that can already read another process's environment or capture its loopback traffic, which exceeds the threat this fix targets; cron tokens are retracted in the run's finally on every exit path, bounding their window to the run. Fail-closed: attestation runs before the canonical read_session_execution, so the record is never read on an unattested name, and unattested resolves to MemberScope(session, False, None) yielding the established 409 member_identity_unavailable or 403. Legitimate members are migrated rather than exempted: script crons mint and publish a per-run stub token, and the mcp_core read verbs plus the mcp_shared tool-policy request now attach the token, closing the availability hole where a token-less read would leave a managed tool policy unresolved and fail-closed the whole tool surface. The blocking file I/O in the token branch runs via asyncio.to_thread, so there is no event-loop-blocking regression.]

One non-blocking follow-up: confirm no other internal route grants member scope off a bare X-Session-Key outside member_request_scope, memory_request_identity and internal_memory_scope. Those three plus the updated test surface were verified; every route was not exhaustively enumerated.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants