Skip to content

feat(daemon): adoption CAS + daemon auth — ADR-026 D3 (Phase 1 S2) - #1315

Merged
lilyshen0722 merged 4 commits into
mainfrom
feat/daemon-adoption-cas
Aug 30, 2026
Merged

lilyshen0722 merged 4 commits into
mainfrom
feat/daemon-adoption-cas

Conversation

@lilyshen0722

Copy link
Copy Markdown
Contributor

Phase 1 S2, on the #1312 substrate:

  • daemonAuth middleware: cm_daemon_* bearers validated against the ledger (kind, status, expiry). Lifecycle-scoped by construction — a daemon token cannot pass agentRuntimeAuth and cannot act as any agent.
  • botMetadata.machineId declared on interface + schema (the Mongoose-stripping lesson applied preemptively)
  • POST /api/agent-binding/adopt (daemon-authed): atomic unbound → bound(machineId) conditional update. machineId is read from the daemon credential server-side — a caller-supplied value is ignored by construction. Ownership predicate: the daemon's owner must hold an active installation of the agent. Concurrent adopts: one winner, loser 409s with the holder. Idempotent re-adopt for the holder.
  • POST /api/agent-binding/release (owner JWT or admin): explicit unbind — rebinding is a deliberate two-step per D3, never a daemon-side race.

6 invariant tests incl. the concurrent-race case. Merge gate: @vera's S3 verdict. Pairs with Kai's S1 (Machine rows); adoption references machineId as an opaque string so the two merge independently.

🤖 Generated with Claude Code

https://claude.ai/code/session_013pc6nGXRS8mHvrwcXMSRDK

lilyshen0722 and others added 3 commits August 27, 2026 22:04
… D3 (Phase 1 S2)

cm_daemon_* auth against the ledger (lifecycle-scoped: cannot pass
agentRuntimeAuth or act as any agent); botMetadata.machineId declared on
interface AND schema; POST /api/agent-binding/adopt is an atomic
unbound→bound(machineId) conditional update — machineId comes from the
credential server-side, never the body; concurrent adopts yield one
winner and a clean 409; release is an explicit owner action, making
rebind a deliberate two-step.

6 CAS invariant tests on mongodb-memory-server incl. the concurrent race.

Co-Authored-By: Claude Fable 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_013pc6nGXRS8mHvrwcXMSRDK
…equiring factory

Vera on #1315: a scope nobody reads doesn't hold the claim. adopt now
requires 'agents:adopt'; heartbeat-only credentials 403. No legacy
daemon credentials exist, so enforcement is strict from birth. This is
THE daemon middleware — #1316 should consume it, not duplicate it.

Co-Authored-By: Claude Fable 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_013pc6nGXRS8mHvrwcXMSRDK
…act)

Minimal projection {machineId, ownerUserId, scopes} — the credential
document and its internals never reach route handlers.

Co-Authored-By: Claude Fable 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_013pc6nGXRS8mHvrwcXMSRDK
@lilyshen0722

Copy link
Copy Markdown
Contributor Author

Review at 2e02a707. Structurally this is right — the CAS is a single updateOne, machineId genuinely comes from the credential and is never read off the body, and the tests run against a real mongodb-memory-server with supertest rather than mocks, so the concurrency claim is actually tested rather than asserted. One defect.

normalize() lowercases instanceId, which is stored case-preserving

normalize() applies .trim().toLowerCase() to both identifiers, and that is correct for one of them and wrong for the other. Measured on origin/main:

AgentInstallation.schema.path('agentName').setters.length   → 1   (lowercase: true)
AgentInstallation.schema.path('instanceId').setters.length  → 0
User.schema.path('botMetadata.instanceId').setters.length   → 0

AgentInstallation.find({ agentName: 'Codex', instanceId: 'Cody', status: 'active' })
  → filter actually sent: {"agentName":"codex","instanceId":"Cody","status":"active"}

Mongoose applies the lowercase setter to the query filter, not just on write — so agentName is symmetric and normalize() on it is redundant but harmless. instanceId has no setter on either model, so it is written verbatim and matched verbatim. Nothing on the write path normalizes it either: getOrCreateAgentUser stores options.instanceId || 'default' as given, and buildAgentUsername lowercases only the derived username, not the stored field.

So for any agent whose instanceId contains an uppercase character, this route denies its legitimate owner, with an error that says something false:

  • /adopt → ownsAgent() queries instanceId: 'cody' against a stored 'Cody', misses, and returns 403 Agent is not owned by this daemon's owner. The owner does own it.
  • If ownership somehow passed, the CAS filter carries the same lowercased instanceId, matches nothing, and the read-back findOne misses too — 404 Agent identity not found for an agent that exists.
  • /release → identical miss, falls through to the admin check, 403 Access denied for the actual owner.

The failure mode is the expensive part: three different wrong answers, none of which points at casing. An operator debugging this reads "not owned by you" and goes looking at installations.

Fix is to stop normalizing the one field that isn't normalized anywhere else — .trim() on instanceId and lowercase only agentName (or drop the lowercase entirely and let the schema setter do it, which it already does):

const normalizeName = (v) => String(v ?? '').trim().toLowerCase();  // agentName
const normalizeInstance = (v) => String(v ?? '').trim();            // instanceId — stored case-preserving

Whichever way it goes, it wants a test with a mixed-case instanceId. Every fixture in agentBinding.adoption.test.js uses instanceId: 'default', so the suite cannot see this — the six invariants are real, they just all live in the all-lowercase corner.

Minor

The 409 at the end of /adopt reads back the holder after a failed CAS. If the winner releases in that window, identity.botMetadata.machineId is null and the caller gets 409 Agent is bound to another machine with boundTo: null — a message that contradicts its own payload. A retry fixes it, so this is cosmetic, but boundTo === null is arguably a 409-to-retry rather than a 409-to-release.

Verified, so you know what the above rests on

  • req.user?.id in /release is safe. I went looking for the req.user vs req.userId trap that CLAUDE.md warns about, because ownsAgent(undefined, …) would have Mongoose strip the installedBy key and match any owner's installation — an authenticated-user-releases-anything bypass. It does not happen: middleware/auth.ts sets req.user = { id } on both the cm_ API-token branch (:51) and the JWT branch (:81), and returns 401 before either if the id is absent. Not a bug.
  • AgentCredential already carries machineId, ownerUserId, scopes, kind, status, expiresAt on origin/main, so this does not depend on an unmerged feat(auth): AgentCredential substrate — ADR-026 Phase 0 #1312 and the String(credential.machineId || '') → '' path is correctly caught by the explicit 400 in /adopt rather than binding an agent to the empty machine.
  • The CAS $or on machineId: null / $exists: false is redundant — Mongo's {field: null} already matches missing — but harmless.

Not verified

I could not enumerate live botMetadata.instanceId values, so I cannot say whether any current row has uppercase in it — the finding is that the code creates the trap and nothing on the write path prevents it, not that a specific agent is broken today. I also did not exercise daemonAuth's scope-403 path or the expiry path beyond reading them, and I did not review #1316's machine-lifecycle endpoints, which this presumably pairs with.

Adoption requires an active installation installedBy the owner AND no
active installation of the identity installedBy anyone else. Test pins
the negative clause: a shared identity is not adoptable by either party.

Co-Authored-By: Claude Fable 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_013pc6nGXRS8mHvrwcXMSRDK
@lilyshen0722
lilyshen0722 merged commit 1c05e31 into main Aug 30, 2026
11 checks passed
@samxu01
samxu01 deleted the feat/daemon-adoption-cas branch August 30, 2026 01:19
@lilyshen0722

Copy link
Copy Markdown
Contributor Author

Held by Sam's ruling (2026-08-30): ADR-026's direction is approved and the doc merges as Proposed, but Phase 0 (token substrate) and everything after it are gated on ADR-023 W2 (hosted runtime) being live — casual signups are the activation goal and hosted is the bigger lever for them. This PR stays open until that gate opens; rebase when it does. Added acceptance criterion for Phase 1: revoke a machine → every agent bound to it stops within one heartbeat, as a tested requirement. The D6 ack race is now its own P1 row (TASK-090) — fix it independently of this stack.

@lilyshen0722

Copy link
Copy Markdown
Contributor Author

RETRACTED — the hold comment above was written from a stale queue listing. Sam ratified ADR-026 as Accepted via his other session on 2026-08-30 and this PR was merged and deployed under that decision before the comment landed. The ratification stands; ignore the hold.

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