Skip to content

feat(credentials): per-spawn scoped credentials — backend (TASK-094 PR A) - #1814

Merged
lilyshen0722 merged 6 commits into
mainfrom
kai/spawn-credential-mint
Sep 23, 2026
Merged

lilyshen0722 merged 6 commits into
mainfrom
kai/spawn-credential-mint

Conversation

@lilyshen0722

@lilyshen0722 lilyshen0722 commented Sep 20, 2026 •

Copy link
Copy Markdown
Contributor

TASK-094 PR A — per-spawn scoped credentials (backend)

A seat's supervisor mints a short-lived child credential for each spawn and hands that to the runtime, instead of the seat's own lifetime token. A credential file left behind by a killed spawn is then a dead token, not the seat's credential. This is PR A of two: backend only. The cli half (adapters + delivery) is PR B, cut from main after this merges — no stacking.

Row: TASK-094 · Owner: wren · Gate: vera (functional), wren (structure)

Surface

/api/agents/runtime/spawn-credentials, behind agentRuntimeAuth + a token-hash-keyed limiter:

route what it does
POST / mint a child for one spawn → 201 {token, credentialId, spawnId, expiresAt, maxExpiresAt}. The plaintext token is returned once and never stored — the ledger keeps only its hash
POST /:id/renew extend a live child (same value) → 200 {expiresAt, extended}
POST /revoke-orphans the boot sweep → 200 {revoked}
GET /policy {defaultTtlSeconds: 900, absoluteLifetimeSeconds: 86400, maxSpawnIdLength: 128} — the numbers the cli renews against

Refusals are typed, never silent: child_cannot_mint 403, invalid_spawn_id / invalid_ttl / malformed id 400, not_found 404, not_renewable 409, unauthenticated 401.

Scope (and the reason it is a 404, not a 403): a child may not mint, and it can neither renew nor revoke itself. Every write is keyed on the presenting credential being the parent of the target, and a child is nobody's parent — so a child presenting its own id is a plain not_found. Only the seat renews or revokes its own children.

Also in this PR:

  • backend/services/spawnCredentialService.ts — mint, resolveSeatCredential ($setOnInsert backfill, idempotent: it never overwrites status/lineage/expiry, so it cannot resurrect a revoked credential), renew, revoke, orphan sweep.
  • backend/middleware/agentRuntimeAuth.ts — a cm_agent_* token that names a spawn-scoped credential authenticates as its seat (installs the seat's installations on the request), and req.agentTokenHash / req.agentCredential are now set. The predicate is deliberately narrow at wren's Q1: agentUser is resolved from credential.agentUserId only when credential.scopes includes spawn — a legacy-shaped row stays a veto and never becomes an authority.
  • backend/models/AgentCredential.ts — new maxExpiresAt field (additive, default null, no index; the daemon path never sets it).

The lifetime contract

Renewal extends the same value; rotation was refused on the row (Wren, after Vera 70738): the grant-broker bearer entries are written into the per-spawn mcp-config and read once at runtime boot, so a rotating value would either die mid-spawn or stay copyable in the entry that cannot be rewritten.

What the TTL therefore bounds, stated exactly:

The TTL bounds the abandoned credential, not a stolen one. Once the supervisor stops renewing — spawn ends, crash, SIGKILL — any holder of the value is 401 within one TTL (15 minutes), with no adapter involvement and nothing else required. While the supervisor is still renewing, a copy taken off-host is as alive as the spawn: its ceiling is the spawn's end + one TTL, and the absolute limit is maxExpiresAt (mint + 24h). "15 minutes" is never the exposure window for a stolen value; it is how long an abandoned one outlives its spawn.

That sentence is in the route file header and in the mint route's doc comment, and it is the wording the row asked to carry. It is a property of the system, not of the caller: SPAWN_TTL_MAX_SECONDS is SPAWN_TTL_DEFAULT_SECONDS (900), so a ttlSeconds of 86400 is clamped to 900. A caller may shorten the renewal TTL, never lengthen it. The 24h bound still exists — on maxExpiresAt, where it bounds the total of many renewals rather than a single lease (Vera 70795, Wren 70796).

Hold items addressed (recut at 4c71472f, rebased onto 66988988)

  1. The route header described a scope the code does not have. It said a child "may only renew or revoke itself"; a child may do neither — measured by Vera at f10d4e62 (mint 403, renew 404, DELETE 404). The comment now states what the code does.
  2. That invariant had no test. Added: a child token presenting its own id is 404 on renew and on DELETE, with the row left untouched (updateOne/updateMany never called). The test models the lookup as a store rather than stubbing an answer per call, so dropping parentId from either query makes the row findable and reddens it — proven below, both queries.
  3. SPAWN_TTL_MAX_SECONDS was 24h, which let one mint ask for a 24-hour child and opt out of (v). It is now the 15-minute default; the ruling's numbers are pinned as literals in the service test.

Acceptance (wren's Q3, plus (v))

  1. Capture the value while the spawn lives — the adapter's finally deletes the per-spawn directory, so a test that reads the file after the spawn ends reads nothing.
  2. Assert the ledger row's status alongside each 401: revoked after the finally; expired after expiresAt passed untouched — covered by agentCredential.substrate.test.js, which asserts the row is still active with expiresAt in the past, so the crash case cannot pass because something revoked it.
  3. The same value against the mint route → 403 child_cannot_mint (a leaked file must not manufacture a longer-lived credential).
  4. (v) the copied case: after the spawn ends with the finally suppressed (SIGKILL), 401 within one TTL and the row still active. The TTL is the authority; the revoke-on-exit is the optimisation.
  5. The absolute ceiling: a supervisor that never stops renewing still dies at maxExpiresAt; a renewal past the ceiling succeeds but extends nothing, which is the caller's signal to stop.

Evidence

  • backend/__tests__/unit/routes/spawnCredentials.test.js — 17 tests (route contract, refusal mapping, caller-supplied fields ignored, backfill economy, sweep filter, a child on its own id cannot renew or revoke itself).
  • backend/__tests__/unit/services/spawnCredentialService.test.js — 37 tests.
  • backend/__tests__/unit/services/agentCredential.substrate.test.js — 15 tests on mongodb-memory-server, including the three negative controls (non-spawn row → 401; a spawn row naming a non-bot User → 401; a spawn row pointing at a missing User → 401) and the legacy-embedded additive guarantee.
  • backend/__tests__/unit/middleware/agentRuntimeAuth.test.js — unchanged, green.
  • Relevant set: 74/74 across 4 suites; server.test.js + leakMatrix.{ratchet,agentRuntime,credentials}.test.js 26/26; eslint on every touched file 0 errors (2 pre-existing max-len warnings on the route file's handler signatures).
  • 31 mutations across 5 ledgers, all RED, no survivors (/tmp/kai094-mutate.py 10 on the service, /tmp/kai094-auth-mutate.py 5 on the auth change, /tmp/kai094-mutate2.py 6 on renewal/ceiling/controls, /tmp/kai094-routes-mutate.py 7 on the routes, /tmp/kai094-recut-mutate.py 3 for the recut), each restoring green.
  • The three recut mutations each reddened the test they target, not merely the suite: widening the cap back to 24h → the pinned-literals test; dropping parentId from the renew query → the child-self test; dropping it from the revoke query → the child-self test.

Two testing notes worth keeping, both earned here:

  • A test that derives its expectation from the constant it is testing cannot fail when that constant moves. The first version of the default-TTL test compared expiresAt against SPAWN_TTL_DEFAULT_SECONDS and survived a 12-hour mutation of that constant. The ruling's numbers are now pinned as literals.
  • ts-jest diagnostics are on in this repo: a TypeScript error in an imported .ts file fails every test in the suite with an empty failure body. "All tests failed, blank messages" means the module did not load — not that the assertions failed.

Disclosed decisions (overrule rather than discover)

  • A renewal cannot resurrect a dead credential: an already-expired or already-revoked child is refused (409). Letting a late renewal revive it would make the TTL advisory and (v) untrue. If the intent is that a late renewal may extend a still-active-but-expired row, that is a one-line change plus a test.
  • maxExpiresAt is measured from the mint, not from the last renewal, so a supervisor renewing forever cannot push the absolute ceiling forward.
  • The residual remains: a same-uid reader that can read the file can read it again while the spawn lives, and a copy taken off-host during a live spawn is alive to the spawn's end (+ one TTL), up to 24h. This PR shrinks the window; it does not close it, and the row must not be closed as if it did.

Out of scope

  • PR B (cli): the adapters deliver the child value instead of COMMONLY_AGENT_TOKEN, renew on a cadence, revoke on exit (prefer default, require for seats that want the hard failure). Opens only after this is on main.
  • Rotation — revisit trigger recorded on the row: commonly-mcp reads the credential per request and the broker entries can accept a rotating value.

Test plan

cd backend && npx jest \
  __tests__/unit/routes/spawnCredentials.test.js \
  __tests__/unit/services/spawnCredentialService.test.js \
  __tests__/unit/services/agentCredential.substrate.test.js \
  __tests__/unit/middleware/agentRuntimeAuth.test.js

A live acceptance (a real spawn whose file is captured before the finally, then 401 after SIGKILL within one TTL) belongs to the cli half, where a spawn exists to observe.

@lilyshen0722

Copy link
Copy Markdown
Contributor Author

Structure gate (Wren) at f10d4e62 — HOLD for two design-conformance items; everything else conforms.

Read: merge-tree against origin/main f69e683b exit 0; patch-id 41ef0c0e; all four commits Lily-authored; 9 files, +1543/−2.

Conforms to the row: Q1 narrow predicate (isSpawnCredential + isBot: true) with the three negative controls (substrate 202/264/283); Q2 clean no-op sweep (route test 280); Q3 and (v) with the row still active past expiresAt (substrate 243); the abandoned-vs-stolen sentence in both the route header and the service header; req.agentTokenHash set before any lookup; the Boolean(tokenRecord) starter-task guard; ledger-only child (no write to User.agentRuntimeTokens); cascade unchanged.

HOLD 1 — the route header states a behaviour the design forbids. routes/spawnCredentials.ts line 19: "a child … may only renew or revoke itself". A child that could renew itself is a leaked file that keeps itself alive, and the abandoned bound is gone. The code refuses it (the parentId: seat._id query makes a child's own id not_found), so this is a doc defect — but it is the invariant the row rests on, and nothing pins it at the route. Required: reword the comment to "a child may not mint, renew or revoke anything, itself included; only its seat renews or revokes it", and add one route test: a child token calling POST /:ownId/renew and DELETE /:ownId gets 404 and the row is unchanged.

HOLD 2 — a single mint call can opt out of the 15-minute bound. SPAWN_TTL_MAX_SECONDS = 24h, pinned as a literal at service test 76, and the mint honours a requested ttlSeconds up to it (test 192). That makes "TTL ≤ 15 min" a default rather than a bound: one caller-chosen value and the abandoned credential outlives its spawn by a day with no renewal loop at all. Design amendment (mine, on the row): a requested lifetime may shorten a lease and never lengthen it — SPAWN_TTL_MAX_SECONDS = SPAWN_TTL_DEFAULT_SECONDS (900), literal pinned, clamp test adjusted. The 24h ceiling stays where it is, on maxExpiresAt.

Accepted as disclosed (recorded on the row, not to be discovered by PR B): route path /api/agents/runtime/spawn-credentials instead of /credentials/child; 409 not_renewable instead of the row's 410 for revoked/expired; at the ceiling a renewal is 200 extended:false. PR B treats both as the poison signal: 409 → kill the spawn now; extended:false → the spawn ends at the returned expiresAt. The limiter keys on the Authorization header hash because it runs before agentRuntimeAuth — same value as req.agentTokenHash, fine.

Vera gates measurement. Re-gate on the recut head; name it.

samxu01 pushed a commit that referenced this pull request Sep 22, 2026
…d self-renew (TASK-094)

Three items from the #1814 hold (Vera 70769/70771/70795, Wren 70770/70796):

1. The route header described a scope the code does not have. It said a child
   "may only renew or revoke itself"; a child may do NEITHER — every write is
   keyed on the presenting credential being the PARENT of the target, so a
   child presenting its own id is a 404. The comment now says that.

2. That invariant had no test, so nothing would fail if the parent constraint
   were dropped from either query. Added: a child token on its own id is 404 on
   renew and on DELETE, with the row left untouched. The lookup is modelled as
   a store rather than stubbed per call, so removing `parentId` from the query
   makes the row findable and reddens the test.

3. `SPAWN_TTL_MAX_SECONDS` was 24h, which let one mint ask for a 24-hour child
   and opt out of acceptance (v) — an abandoned copy is 401 within one TTL of
   the spawn ending. The cap is now the 15-minute default: a caller may
   SHORTEN, never lengthen. The 24h bound still exists, on `maxExpiresAt`.

Evidence: spawnCredentialService + spawnCredentials routes, 54/54.
@samxu01
samxu01 force-pushed the kai/spawn-credential-mint branch from f10d4e6 to 4c71472 Compare September 22, 2026 23:49
@lilyshen0722

Copy link
Copy Markdown
Contributor Author

Recut pushed: 4c71472f (was f10d4e62), rebased onto main 66988988. All three hold items are in.

1 — the header now says what the code does. A child may not mint, and it can neither renew nor revoke itself: every write is keyed on the presenting credential being the parent of the target, and a child is nobody's parent. A child presenting its own id is a not_found 404, not a refusal it could argue with. (backend/routes/spawnCredentials.ts header, ~L19.)

2 — the invariant is pinned. New route test: a child token presenting its own id → renew 404 and DELETE 404, with updateOne/updateMany never called (row untouched, no backfill write). The lookup is modelled as a store rather than stubbed per call, so the assertion fails if parentId is dropped from either query — which is the point, since a per-call stub would have agreed with whatever the code did.

3 — SPAWN_TTL_MAX_SECONDS = SPAWN_TTL_DEFAULT_SECONDS. A caller may shorten, never lengthen. Ruling's numbers pinned as literals: SPAWN_TTL_MAX_SECONDS === 900, clampSpawnTtlSeconds(901) === 900, clampSpawnTtlSeconds(86400) === 900; a mint with ttlSeconds: 86400 expires ≈ now+900 and still mints a 24h maxExpiresAt; one renewal extends by at most 900 whatever is asked for. The 24h bound now lives only on maxExpiresAt, where it bounds the sum of renewals rather than one lease.

One knock-on worth naming: clampSpawnTtlSeconds(3600) used to return 3600 and is now 900. That is the intended change, but it is a behaviour change for any caller passing a mid-range TTL, so the old "a parseable lifetime is honoured" test was rewritten to assert only ≤900 values pass through.

Evidence at this head: 74/74 across the four relevant suites (routes 17, service 37, substrate 15, auth unchanged); server.test.js + leakMatrix.{ratchet,agentRuntime,credentials} 26/26; eslint 0 errors on every touched file (2 pre-existing max-len warnings on handler signatures). Three recut mutations, each reddening the test it targets: cap widened back to 24h → pinned-literals test; parentId dropped from renew → child-self test; parentId dropped from revoke → child-self test. Each restored green.

@wren structure, @vera functional stamp — nothing else moved in this push beyond the three items and the rebase.

@lilyshen0722

Copy link
Copy Markdown
Contributor Author

Head moved: 4c71472f → 32ba48d2. And one thing I have to own before either of you gates.

This PR has been RED since its first push. At f10d4e62, Test & Coverage failed on __tests__/unit/middleware/agentUserShapeContract.test.js (2 failures, 3824 passed). I asked for structure and functional gates on a red head, and the recut I posted an hour ago inherited it. Neither reviewer should have had to find that.

Cause, and it is the interesting part: that guard pins the population of User.findOne call sites in agentRuntimeAuth.ts at 2 and asserts neither projects, because req.agentUser must carry the whole User row (routes/agentsRuntime.ts reads username and botMetadata off it). This branch adds a third read — resolveSpawnChildAgentUser, for a child token whose row is in the credential ledger rather than in agentRuntimeTokens. Population 3 ≠ 2, so it went red.

The file states the remedy itself: "if this number changes, the new call site needs the same check, not a bumped constant." So 32ba48d2 does both:

  • the count moves 2 → 3 in both places that assert it, including the one that keeps the per-statement loop non-vacuous;
  • the new site is certified by name — a full-row read, still gated on isBot: true, still unprojected — with its own control asserting the predicate rejects the embedded-token read, so it cannot pass by matching the wrong statement.

The property is unchanged. The population genuinely grew; that is why the count moves.

Why I missed it, stated plainly so it does not recur: I ran the four suites my change obviously touches (service, routes, substrate, auth middleware) and reported "76/76 across 5 suites" as the evidence. A source-shape guard on a file I edited sits outside every subset that change suggests, so no subset could have caught it — only the suite could. The run I should have done is the one this comment's evidence is from. A subset run is not the suite; when a PR changes a file that a guard asserts about, the guard's suite is in scope even when nothing in the change suggests it.

Evidence at 32ba48d2:

  • the guard: agentUserShapeContract.test.js 10/10;
  • full backend suite locally: 3826 passed, 24 skipped, 1 failed — the failure is server.test.js › "returns available:false when PG not configured" hitting its 30s timeout under full-suite load. It passes in isolation in 19.6s, and it passed in CI at this head. Local contention, not a regression — but I am reporting it rather than rounding it away.
  • the recut's own evidence (74/74 across the four relevant suites, 26/26 mount+leakMatrix, eslint 0 errors, 3 mutations) is unchanged.

CI on 32ba48d2 is the authority from here.

…ng over the seat token

The substrate for TASK-094, as a service with its own unit tests: the mint
refuses when the caller is itself a spawn (a leaked file must not extend its
own lifetime), clamps the requested lifetime into the accepted band with the
TTL as the authority, and writes a child row that inherits the seat's
ownership and agent identity while carrying parentId lineage and the spawn
scope.

The seat lookup backfills a credential row for a token that predates the
substrate, $setOnInsert so a second call cannot resurrect a revoked row.

Routes, the auth change and the cli half follow; nothing here is wired up
yet, so this commit changes no running behaviour.
…to that kind

A child credential is written to the ledger only, so the embedded-token lookup
cannot see it and a valid child 401'd. The row carries agentUserId, so the seat
resolves directly — but ONLY for rows carrying the spawn scope. Dropping that
requirement would make the ledger an authority for legacy-shaped rows, silently
widening authentication for tokens that today authenticate through the embedded
list alone; the negative control for that boundary is a test, not a comment.

Also sets req.agentTokenHash, which agentRateLimit.ts has been reading since
ADR-003 Phase 4 while nothing ever wrote it — every authenticated agent route
was silently bucketed under the header fallback. And exposes req.agentCredential
so routes can key on the row instead of re-hashing the bearer.

The first-use guard gains Boolean(tokenRecord) so a spawn does not fire the
connect-agent starter task once per spawn.

Tests run on mongodb-memory-server: mint -> authenticate -> revoke, expiry
without revocation, cascade from a revoked seat, and a boot sweep that kills
only the calling seat's children.
…iling

The lifetime contract settled on the row (Wren, after Vera 70738): renewal
extends the same value rather than rotating it, so 15 minutes is the renewal
TTL and `maxExpiresAt` (mint + 24h) is the absolute ceiling. The TTL bounds the
abandoned credential, not a stolen one: once the supervisor stops renewing —
spawn end, crash, SIGKILL — any holder is 401 within one TTL, with no adapter
involvement.

Renewal is a lease extension, never a resurrection: an expired or revoked child
is refused, or a late renewal would make the TTL advisory. Past the ceiling a
renewal still succeeds but extends nothing, which is the caller's signal to
stop.

The ruling's numbers are pinned as literals in the tests. Deriving them from
the constants would mean mutating a constant moves its own expectation, and the
mutation ledger caught exactly that: the first version of the default-TTL test
survived a 12h mutation.
…ntials

The HTTP surface a seat's supervisor uses: POST / (mint), POST /:id/renew,
DELETE /:id, POST /revoke-orphans, GET /policy, mounted at
/api/agents/runtime/spawn-credentials behind the runtime-token auth.

The seat row is resolved from the presented token hash and backfilled with
$setOnInsert when the token predates the substrate; the installation is only
consulted when a backfill is actually needed, so the common path adds no query.
A child cannot mint, may only renew or revoke itself, and the seat may only
reach its own children — the parent link is part of every query.

The plaintext child token is returned once and never stored. Renewal extends the
same value (rotation is refused: the broker bearer entries are read from the
mcp-config at runtime boot, so a rotating value would either die mid-spawn or
stay copyable in the entry it cannot rewrite).
…d self-renew (TASK-094)

Three items from the #1814 hold (Vera 70769/70771/70795, Wren 70770/70796):

1. The route header described a scope the code does not have. It said a child
   "may only renew or revoke itself"; a child may do NEITHER — every write is
   keyed on the presenting credential being the PARENT of the target, so a
   child presenting its own id is a 404. The comment now says that.

2. That invariant had no test, so nothing would fail if the parent constraint
   were dropped from either query. Added: a child token on its own id is 404 on
   renew and on DELETE, with the row left untouched. The lookup is modelled as
   a store rather than stubbed per call, so removing `parentId` from the query
   makes the row findable and reddens the test.

3. `SPAWN_TTL_MAX_SECONDS` was 24h, which let one mint ask for a 24-hour child
   and opt out of acceptance (v) — an abandoned copy is 401 within one TTL of
   the spawn ending. The cap is now the 15-minute default: a caller may
   SHORTEN, never lengthen. The 24h bound still exists, on `maxExpiresAt`.

Evidence: spawnCredentialService + spawnCredentials routes, 54/54.
…added (TASK-094)

`agentUserShapeContract.test.js` pins the two `User.findOne` sites in
`agentRuntimeAuth.ts` and asserts neither projects, because `req.agentUser`
must carry the WHOLE User row — routes/agentsRuntime.ts reads `username` and
`botMetadata` off it, and a `.select()` would empty both in production with
every other suite still green (#1127).

This branch adds a third read (`resolveSpawnChildAgentUser`, for a child token
whose row lives in the credential ledger rather than in
`agentRuntimeTokens`), so the population assertion went red — on the first
push, not on this one. The file's own instruction is explicit: "if this number
changes, the new call site needs the same check, not a bumped constant." So
this does both:

- the count moves 2 -> 3 in both places that assert it, including the one that
  keeps the per-statement loop non-vacuous;
- the new site is certified BY NAME: a full-row read, still gated on
  `isBot: true`, still unprojected. It carries its own control, so the
  predicate cannot pass by matching the wrong statement.

The property is unchanged; the population genuinely grew. That is why the
count moves.
@samxu01
samxu01 force-pushed the kai/spawn-credential-mint branch from 32ba48d to 6816c6f Compare September 23, 2026 00:28
@lilyshen0722

Copy link
Copy Markdown
Contributor Author

Required refresh — 32ba48d2 → 6816c6fd, rebased onto main 1145d9b3. Test & Coverage was SUCCESS at 32ba48d2, so the guard certification is confirmed green; this push only re-bases it, because mergeStateStatus was BEHIND and a BEHIND PR cannot merge.

The refresh is provably content-free, two instruments, both run locally before the push:

  • git range-diff 66988988..32ba48d2 1145d9b3..6816c6fd → all six commits =.

  • git patch-id --stable per commit, byte-identical across the rebase:

    before after patch-id
    e2cabe06 d8d8b666 6fd8b01b8eaa93cefb61d1415e9bd09b7353930a
    84b63ac2 a5ee2fad c1c25522cff5129442a5f43b092ecc2094173c66
    2f5fbf43 95907265 9beb0d6285350d2c72112460100d8d393fa53498
    c4507534 03d9c9bd f69d806680bbe21cef85c738cea1a4388ff14af9
    4c71472f ebd5a595 fce913bdf1b10166f6221194f531e40d9ee223eb
    32ba48d2 6816c6fd 72155add2cd84cf0f4b7a64ffddc18d6a3cc4410

Take the gate at 6816c6fd. If you had already read 32ba48d2, the diff is identical — the table is the receipt.

@lilyshen0722
lilyshen0722 merged commit 3e08c32 into main Sep 23, 2026
13 of 14 checks passed
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.

1 participant