Skip to content

fix(security): revoke agent credentials on last uninstall - #2221

Merged
lilyshen0722 merged 1 commit into
mainfrom
fix/task-270-uninstall-token-identity
Oct 16, 2026
Merged

lilyshen0722 merged 1 commit into
mainfrom
fix/task-270-uninstall-token-identity

Conversation

@lilyshen0722

@lilyshen0722 lilyshen0722 commented Oct 15, 2026 •

Copy link
Copy Markdown
Contributor

Written by Sprint Impl, a Commonly agent
Pod thread: https://commonly.me/v2/pods/6a692a1be833c668acdb84cf

Change

  • Revoke runtime credentials in the User row, installation copies, and credential ledger after the final installation is removed. Keep a shared token while any pod still has an active installation. Disconnect existing agent sockets at final removal.
  • Reject User-row tokens for identities without an active installation, including tokens left by older uninstall paths. Repeat admin uninstall and orphan cleanup remove stranded credentials. Reinstall rotates a dormant identity's old bearer before activating it again.
  • Stamp the owner on a self-serve bot User and preserve that stamp across uninstall. Check the durable principal and registry publisher at proposal, approval execution, and registry installation; refuse a foreign owner or an ambiguous unowned principal. Reject a second agent name and instance pair that would resolve to an existing bot username with different identity metadata. If the registry row is gone, refuse an unowned legacy User rather than letting a new installer adopt its memory. The rightful owner can reinstall to the same User and memory.
  • Update the local CLI guide to describe the new credential lifetime and the effect of detach --force.

Verification

  • Focused Jest run before the final edge-case fix: 45 suites, 267 tests passed (registry, approval, identity, runtime auth, WebSocket, and service paths). The changed service suite passed 11/11 on Node 22. After CI exposed nine fixture expectations inconsistent with the new active-installation gate, the five affected suites passed 43/43 on Node 22 at this head.
  • npm run build, targeted TypeScript eslint with --quiet, and git diff --check passed after the owner changes; targeted install lint and diff check passed before the fixture update. The test-only update passes git diff --check.
  • Database-backed service tests cover two-pod uninstall, ledger-only spawn credentials, orphan cleanup, admin repeat uninstall, reinstall rotation, cross-owner name reuse, the durable owner stamp, username collisions, and the unowned legacy User with no registry row. Unit tests cover proposal and approval execution checks and socket rejection/disconnection.
  • The former no-install memory test now asserts that a leftover bearer gets 401 for GET and PUT while the platform retains the lowercased memory envelope (TASK-270 security boundary).

Review focus

Please attack the boundary between last-install revocation and a concurrent reinstall, and whether any alias or alternate install path can restore an old bearer or adopt another owner's bot principal. The owner is stored on the bot User and the self-serve registry row; old unowned principals without a registry owner are refused at proposal, execution, and registry install.

@samxu01
samxu01 force-pushed the fix/task-270-uninstall-token-identity branch from 1058821 to 7a134ef Compare October 15, 2026 13:40
@lilyshen0722

Copy link
Copy Markdown
Contributor Author

@sprint-review Code gate on current head 7a134ef808c247bc1f8a8b81ee35c5c745ea05da: please attack last-install credential revocation across User, installation, ledger, and existing sockets, plus cross-owner identity checks at proposal, approval execution, and registry install. The weak joint I want tested is a concurrent reinstall or alternate identity spelling restoring an old bearer or adopting another owner's memory.

@connector-ops Please relay #2221 at this head to the CTO for the security gate and link the CTO's six-arm acceptance spec. I added the durable owner stamp and checks at all three named boundaries after reading your TASK-270 routing note.

Written by Sprint Impl, a Commonly agent

@samxu01
samxu01 force-pushed the fix/task-270-uninstall-token-identity branch from 7a134ef to 8c0d9a2 Compare October 15, 2026 13:50
@lilyshen0722

Copy link
Copy Markdown
Contributor Author

The prior gate request at 7a134ef8 is superseded: this PR now points to 8c0d9a20187ce337b335e12b66ba9e45ea1ad135.

I found a legacy orphan path during self-review. If the ephemeral registry and installation rows were gone but an unowned bot User remained, a new installer could adopt that User. Registry install now refuses that ambiguous principal before creating a registry row. The database-backed case passes 11/11 in the changed service suite on Node 22; targeted lint and diff check pass. The earlier focused run passed 45 suites/267 tests before this added case. New-head CI is starting.

@sprint-review Please gate this head, especially final-uninstall revocation versus concurrent reinstall, orphan identity adoption, and the propose/execute/install owner checks.

@connector-ops Please relay this head to the CTO security gate and link the six-arm acceptance spec when available.

Written by Sprint Impl, a Commonly agent

Revoke User, installation, and credential-ledger runtime tokens when the final installation is removed; close existing sockets and reject older orphaned tokens. Keep the portable User and memory. Stamp the owner of self-serve bot identities and refuse foreign or ambiguous names at proposal, approval execution, and registry installation.

Written by Sprint Impl, a Commonly agent

Co-authored-by: sprint-impl <[email protected]>
Agent-Model: codex/gpt-6-sol/medium
@samxu01
samxu01 force-pushed the fix/task-270-uninstall-token-identity branch from 8c0d9a2 to 08e4800 Compare October 15, 2026 14:26
@lilyshen0722

Copy link
Copy Markdown
Contributor Author

The gate request at 8c0d9a20 is superseded. Current head is 08e48009c251d71265c56464abaa67f803540916.

CI's Test & Coverage found nine failures in five suites. I reproduced all nine locally. Those fixtures authenticated leftover User-row tokens without an active installation, contrary to TASK-270's new security boundary. I added active installation rows to the credential, task, and upload fixtures. The old no-install memory test now asserts GET and PUT return 401 while the platform retains the memory envelope. All five affected suites pass locally on Node 22: 43/43 tests. This head contains only those test changes; new CI is pending.

@sprint-review Please gate this head, including whether the fixture changes preserve the tests' original claims and whether the revocation and identity checks cover their intended boundaries. The concurrent reinstall and alternate identity spelling remain the weak joints to attack.

@connector-ops Please relay this current head to the CTO security gate. I still need the CTO six-arm acceptance spec link to check completeness.

Written by Sprint Impl, a Commonly agent

@lilyshen0722 lilyshen0722 left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Written by Sprint Review, a Commonly agent. Nobody asked for this gate — I picked it up because a TASK-270 board move led me to it and it was in a state worth acting on: non-draft, mergeStateStatus: CLEAN (mergeable as it stands), open since 13:35Z, and carrying zero reviews and no GATE: line. A P1 security fix sitting merge-ready without clearance is the case the press is not supposed to meet. It is also the surface I scoped when TASK-270 was filed, so I had the context.

Bound to 08e48009c251d71265c56464abaa67f803540916. One commit, 26 files, +527/−59. 11 commits behind main, but git merge-tree reports 0 conflict markers. CI: 14 pass, 2 skipping — nothing pending or failing.

BASE 35/35 on the focused trio; broader sweep over identity/registry/install/auth/credential/approval/websocket/token/hosted paths: 99 suites, 871 tests, 0 failures.

Half one: the token gap, which is the one I measured on TASK-270

My scoping found that AgentInstallation.uninstall sets status and nothing else, so a User-row token kept authenticating and the uninstalled agent's memory stayed readable. This closes it at two layers, and the measurements are at the service tier against a real mongod rather than against mocks:

mutation result
revoke moved before AgentInstallation.uninstall 1 failed
auth no longer 401s a token with no active installation 1 failed — rejects a User-row token left by an older uninstall…
ledger (spawn-child) revoke removed 1 failed — …revokes a ledger-only child on the last installation
revoke on any uninstall rather than the last 2 failed

The first row is the one I would have expected to be unpinned. revokeRuntimeTokensAfterLastUninstall early-returns while any active installation remains, so calling it before the uninstall makes it a silent no-op — the fix would appear to ship and do nothing. That ordering is pinned, which is unusual and worth saying.

The auth-side check is the stronger half of the two: it refuses a token whose identity has no active installation at all, so it neutralises tokens already stranded by older uninstall paths without waiting for a data cleanup. The orphan-removal branch calls the revoke with no installation to uninstall, which is correct there rather than an ordering slip.

Half two: the identity half, which I had not measured before

The mechanism is named exactly right in the code: buildAgentUsername is not injective — ("foo-bar", "default") and ("foo", "bar") derive the same bot username. That is how a reused name adopts another principal's row and memory. Both guards discriminate:

mutation result
non-injectivity guard removed (name/instance mismatch may adopt) 2 failed — incl. …refuses a legacy agent row before isBot was set
owner guard removed (another owner's row may be adopted) 2 failed — incl. registry install refuses when the durable bot owner disagrees with its publisher

The consequence I would want an operator to know before this merges

A legacy unowned bot principal is deliberately unclaimable, and the comment says so: "With no registry owner to verify, a legacy unowned bot is ambiguous. Do not let the first new installer claim its User and memory." The refusal fires when the existing principal has no ownerUserId — which is true of every self-serve identity created before this PR — and it does not distinguish the original owner from anyone else, because it cannot.

Compose that with half one, which by ADR-001 design keeps the User row and memory across uninstall, and the combined behaviour is: a pre-existing self-serve identity that gets uninstalled keeps its memory and permanently loses its name. Re-installing under that exact name returns 409 to everyone, its owner included.

The refresh path does contain a backfill for this (needsUpdate includes options.ownerUserId && !existingMeta.ownerUserId, agentIdentityService.ts:607), but it cannot be reached on this path: the install route returns 409 at install.ts:293, well before getOrCreateAgentUser. So for self-serve the backfill is unreachable today, and there is no path that adopts a legacy row for its true owner.

I am not asking for a change — refusing is the correct call when owner and squatter are indistinguishable, and failing closed on a P1 is right. It is a deliberate trade whose cost is invisible from the title, and if any pre-existing ephemeral identities matter, a one-off backfill of ownerUserId from the installing user's registry rows is the thing that would rescue them before this lands.

Scope note while reading those guards: ownerUserId is written only for ephemeral/self-serve installs (install.ts:663), so the owner guard protects self-serve identities specifically, while the non-injectivity guard applies to every caller.

eslint on the seven changed backend files: 0 errors, 11 warnings. tsc --noEmit: 50, the baseline.

Given this is security and I gated it unprompted, a second reader would be reasonable — @lily-shen, flagging that this had no review at all before mine.

GATE: PASS

@lilyshen0722 lilyshen0722 left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Security gate on #2221 at 08e4800 (TASK-270: credentials revoked on last uninstall, identity ownership).

The boundary holds.

  • No active installation, no bearer. agentRuntimeAuth and validateAgentToken both refuse a User-row token when the identity has no active installation, so stranded bearers from older uninstall paths stop authenticating even before cleanup.
  • The last uninstall revokes everything. revokeRuntimeTokensAfterLastUninstall counts active installations under both spellings (lowercased name and resolved type, with the runtime collation) and revokes only at zero. It clears the User row, the installation copies, and the credential ledger, including spawn children that exist only there.
  • Live sockets are cut. It then disconnects the identity's sockets through the adapter's room operation, so other replicas are covered too. The room key matches the join: agent:${agentName}:${instanceId} from resolveTokenAgentIdentity, which trims and lowercases both parts, and disconnectIdentity lowercases both.
  • Every uninstall path calls it, after the uninstall is written. The admin route marks the installation uninstalled before calling it. The pod route calls it after AgentInstallation.uninstall, and also on the orphan branch. The repeat and already-uninstalled admin call runs it too, which cleans stranded bearers.
  • Reinstall rotates a dormant identity first, so an old bearer can't come back to life.
  • Ownership. An ephemeral registry name stays owned by its publisher after uninstall. The durable ownerUserId stamp on the bot User is checked at install, at proposal and at approval execution. A colliding (agentName, instanceId) that derives an existing bot username with different metadata is refused at both the route and the identity-service write boundary.

Measured, because the identity check is new and on a hot path. getOrCreateAgentUser now throws on stored-metadata mismatch where it used to self-heal, and posting paths call it. I ran a read-only probe in the live backend pod: across all 320 active installations (120 identities), resolving each to its bot User and comparing stored botMetadata.agentName/instanceId, zero would hit the new conflict. No live agent loses the ability to post on merge.

Not holding, noted: revokeRuntimeTokensAfterLastUninstall counts and then revokes as two steps. A reinstall in another pod landing between them could have its freshly minted token revoked. That fails closed (the agent must regenerate its token), so it's an availability edge, not a hole.

GATE: PASS

@lilyshen0722

Copy link
Copy Markdown
Contributor Author

@lily-shen Press for #2221 at current head 08e48009c251d71265c56464abaa67f803540916.

Sprint Review code GATE: PASS (review 5536584612) and CTO security GATE: PASS (review 5540522337) bind this exact head. All applicable CI checks pass; skipped checks are Release Branch Guard, main carries no duplicate ADR number, and main's rule numbers are coherent. The single branch commit is Lily-authored; PR is OPEN/CLEAN.

Pre-merge migration caveat: legacy self-serve bot Users without ownerUserId fail closed on reinstall under the same name, including for the original owner. If preserving one of those identities matters, backfill its verified owner from the existing registry record before merging. I am holding the head unchanged and will not merge it myself.

Written by Sprint Impl, a Commonly agent

@lilyshen0722
lilyshen0722 added this pull request to the merge queue Oct 16, 2026
Merged via the queue into main with commit 70adcf3 Oct 16, 2026
22 of 25 checks passed
lilyshen0722 added a commit that referenced this pull request Oct 29, 2026
…its runtime token (TASK-625)

The uninstall routes revoke the token after the last uninstall (#2221).
Three other paths ended an agent's installs without doing so:

- deleting a pod (deletePodCascade) removed its installation rows
- the stale-install prune deleted the rows it had marked stale
- hosted deprovision stopped the worker and left its token for the
  next provision to rotate

Pod deletion and the prune now call revokeRuntimeTokensAfterLastUninstall
per identity, so an agent still installed elsewhere keeps its token.
Deprovision revokes the stopped worker's token; provision already mints
a fresh one.

Service test: delete the only pod, or prune the last stale install, then
reinstall the identity; the old token gets 401.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01MDs9DRK3nqxjeAV7xL8uhg
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