Skip to content

feat(node): signature-gated agent self-deregister (#29)#63

Merged
kevincodex1 merged 3 commits into
mainfrom
feat/agent-registry-retirement
Jun 23, 2026
Merged

feat(node): signature-gated agent self-deregister (#29)#63
kevincodex1 merged 3 commits into
mainfrom
feat/agent-registry-retirement

Conversation

@beardthelion

@beardthelion beardthelion commented Jun 20, 2026

Copy link
Copy Markdown
Collaborator

Summary

Adds a signature-gated agent self-deregister so the holder of a DID's key can retire their own agent, removing rotated or compromised orphan DIDs from discovery and capability routing.

Motivation & context

Agents whose keys are rotated or compromised could never be removed from a node's registry. The orphaned DID persisted indefinitely and, because discovery had no liveness concept, could be the first match for ?capability= routing — routing callers to a DID whose private key is in the wrong hands.

Closes #29

Kind of change

  • Bug fix
  • Feature
  • Security fix
  • Docs
  • Tests / CI
  • Refactor (no behavior change)
  • Breaking or protocol change (issue required first)

What changed

Crate: gitlawb-node.

  • A v5 migration adds an agent lifecycle status (default active) and a deactivated_at timestamp to the agents table.
  • list_agents now returns only active agents via a pure filter_discoverable helper, so a revoked DID no longer appears in discovery or capability routing. get_agent stays unfiltered so a revoked DID still resolves and surfaces its status.
  • status is surfaced on AgentResponse.
  • New DELETE /api/v1/agents/{did} lets an RFC 9421-authenticated caller mark its own agent revoked. The handler authorizes and acts on the verified AuthenticatedDid — never a value derived from the untrusted path — so the authorized identity and the mutated row are always the same.
  • Revocation is terminal: register_agent's ON CONFLICT leaves status untouched, so re-registering a leaked DID cannot resurrect it.

Authority is team-owned (the key holder); no external contract, chain, or operator power.

How a reviewer can verify

cargo test -p gitlawb-node            # 135 pass, incl. caller_matches_did auth-gate + filter_discoverable tests
cargo fmt --all -- --check
cargo clippy --workspace --all-targets -- -D warnings

Manual: with a signed request, DELETE /api/v1/agents/{your-own-did} returns 204 and the agent disappears from GET /api/v1/agents; a DELETE of a different DID is refused; an unauthenticated request is rejected by the signature middleware.

Before you request review

  • Scope is one logical change; no unrelated churn
  • cargo test --workspace passes locally
  • New behavior is covered by tests (required for fixes)
  • cargo fmt --all and cargo clippy --workspace --all-targets -- -D warnings are clean
  • Commit titles use Conventional Commits (feat(...), fix(...), docs(...))
  • Docs / .env.example updated if behavior or config changed (or N/A) — N/A, no new config
  • Checked existing PRs so this isn't a duplicate

Protocol & signing impact

  • Touches DID / did:key, Ed25519 / RFC 9421 signatures, UCAN, ref certs, or P2P wire formats
  • Discussed in an issue before implementation
  • Backward-compatible with existing nodes and previously signed history

The deregister endpoint authenticates via the existing RFC 9421 signature middleware and authorizes on the verified did:key identity. It is additive — a new migration, a new endpoint, and an additive status field — so existing nodes and previously signed history are unaffected.

Notes for reviewers

Deferred to follow-ups, out of scope here: lost-key retirement via an operator-authed prune; DB-integration tests (the crate has no live-Postgres harness today); an optional ?status= parameter on the list endpoint.

The on-chain rotation-contract approach raised in the issue thread was deliberately rejected: the retirement authority stays team-owned (the DID's key holder), with no dependency on an external contract or third-party service.

Summary by CodeRabbit

  • New Features
    • Added authenticated agent self-deregistration via DELETE /api/v1/agents/{did} (revokes the caller’s own agent and returns 204 on success).
    • Agent lifecycle status is now included in agent API responses (for example, active/revoked).
  • Bug Fixes
    • Discovery and capability routing now exclude revoked agents, while revoked agents can still be retrieved directly.
  • Tests
    • Added coverage for tolerant DID matching, correct authorization behavior, and status serialization.

Agents whose keys are rotated or compromised could never be removed from
the registry, so an orphaned DID persisted and could win ?capability=
routing. Give the DID's key holder a way to retire their own agent.

A v5 migration adds an agent lifecycle status (default 'active') plus a
deactivated_at timestamp. list_agents drops non-active agents via a pure
filter_discoverable helper, so a revoked DID no longer appears in
discovery or capability routing; get_agent stays unfiltered so a revoked
DID still resolves and surfaces its status.

DELETE /api/v1/agents/{did} lets an rfc9421-authenticated caller mark its
own agent revoked. Authorization is on the verified AuthenticatedDid via a
pure caller_matches_did gate (a DID can only retire itself), unit-tested
including the cross-DID rejection. Revocation is terminal: register_agent's
ON CONFLICT leaves status untouched, so re-registering a leaked DID cannot
resurrect it.

Authority is team-owned (the key holder); no external contract, chain, or
operator power. Lost-key retirement and any successor pointer are out of
scope.
@coderabbitai

coderabbitai Bot commented Jun 20, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

Adds a signature-gated DELETE /api/v1/agents/{did} self-deregistration endpoint. A new DB migration extends the agents table with status and deactivated_at columns. Discovery filtering is updated to exclude revoked agents from capability routing, AgentResponse gains a status field, and a DID normalization helper handles full vs. short did:key forms.

Changes

Agent Deregistration and Lifecycle Status

Layer / File(s) Summary
DB migration and AgentRow status semantics
crates/gitlawb-node/src/db/mod.rs
Migration v6 (agent_retirement) adds status (default active) and deactivated_at columns to the agents table. AgentRow.status documentation is updated to define active and revoked as terminal lifecycle values.
Discovery filtering, row mapping, and revoke logic
crates/gitlawb-node/src/db/mod.rs
row_to_agent constructs AgentRow from SQL results. filter_discoverable enforces active-only discovery with optional capability matching, explicitly excluding revoked agents from capability routing. list_agents applies this filter, get_agent still resolves revoked DIDs, and revoke_agent sets status='revoked' and deactivated_at. Unit tests validate filtering behavior including the revoked-orphan capability routing bug (issue #29).
AgentResponse status field and DID matching helper
crates/gitlawb-node/src/api/agents.rs
AgentResponse gains status: String. list_agents and show_agent populate it from AgentRow. caller_matches_did normalizes full and short did:key forms for tolerant DID comparison.
deregister_agent handler, route wiring, and tests
crates/gitlawb-node/src/api/agents.rs, crates/gitlawb-node/src/server.rs
deregister_agent verifies the caller DID matches the path DID, calls revoke_agent, and returns 204 or 404. The DELETE /api/v1/agents/{did} route is added to the authenticated write router. Tests cover full/short DID authorization, mismatch rejection, and AgentResponse.status serialization.

Sequence Diagram(s)

sequenceDiagram
  participant Client
  participant AuthMiddleware
  participant deregister_agent
  participant caller_matches_did
  participant revoke_agent as revoke_agent (DB)

  Client->>AuthMiddleware: DELETE /api/v1/agents/{did} + HTTP signature
  AuthMiddleware->>AuthMiddleware: verify signature + UCAN chain
  AuthMiddleware->>deregister_agent: AuthenticatedDid + Path(did)
  deregister_agent->>caller_matches_did: compare caller_did vs path_did
  alt DIDs do not match
    caller_matches_did-->>deregister_agent: false
    deregister_agent-->>Client: 403 Forbidden
  else DIDs match
    caller_matches_did-->>deregister_agent: true
    deregister_agent->>revoke_agent: UPDATE status='revoked', deactivated_at=now
    alt row affected
      revoke_agent-->>deregister_agent: true
      deregister_agent-->>Client: 204 No Content
    else not found
      revoke_agent-->>deregister_agent: false
      deregister_agent-->>Client: 404 Not Found
    end
  end
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Poem

🐇 Hop, hop — a key went astray,
The orphan DID had too long a stay.
Now DELETE clears the roster with grace,
status: revoked takes the orphan's place.
No ghost shall win capability's race! ✨

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title accurately summarizes the main change: adding a signature-gated agent self-deregister feature to address issue #29.
Description check ✅ Passed The PR description is comprehensive, covering all required template sections: summary, motivation/context with issue link, kind of change, detailed changes, verification steps, pre-review checklist, and protocol impact assessment.
Linked Issues check ✅ Passed The PR fully implements issue #29's primary requirement: signature-gated self-deregister via DELETE endpoint with RFC 9421 authentication, agent status filtering in discovery, and terminal revocation semantics.
Out of Scope Changes check ✅ Passed All changes are directly scoped to implementing #29: database migration for status tracking, filtering active agents in discovery, new DELETE endpoint, and supporting tests—with explicitly deferred follow-ups noted.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/agent-registry-retirement

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@coderabbitai coderabbitai Bot 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.

Actionable comments posted: 2

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@crates/gitlawb-node/src/db/mod.rs`:
- Around line 1095-1103: The revoke_agent method unconditionally updates the
deactivated_at timestamp every time it's called, which loses the original
deactivation timestamp if the method is retried. Modify the SQL UPDATE query in
revoke_agent to conditionally set deactivated_at only when it is currently NULL,
using COALESCE(deactivated_at, $2) so that the first deactivation timestamp is
preserved across multiple invocations of this idempotent operation.

In `@crates/gitlawb-node/src/server.rs`:
- Around line 151-153: The deregister_agent route for /api/v1/agents/{did}
currently inherits the add_auth_layers middleware which applies both
require_ucan_chain and require_signature authentication. This conflicts with the
self-deregistration model where a DID key holder should only need to provide an
RFC 9421 signature without requiring a UCAN chain. Remove this route from the
add_auth_layers middleware stack and instead apply only the require_signature
authentication layer directly to the route definition for deregister_agent to
allow self-retirement based on signature alone.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: bef7bba2-514a-4c01-9d87-8ebfb697f04a

📥 Commits

Reviewing files that changed from the base of the PR and between e37ea7f and 6b652a9.

📒 Files selected for processing (3)
  • crates/gitlawb-node/src/api/agents.rs
  • crates/gitlawb-node/src/db/mod.rs
  • crates/gitlawb-node/src/server.rs

Comment thread crates/gitlawb-node/src/db/mod.rs
Comment thread crates/gitlawb-node/src/server.rs
A retried DELETE /api/v1/agents/{did} re-ran the revoke UPDATE and
overwrote deactivated_at with a fresh timestamp, losing the true
first-retired time. Use COALESCE(deactivated_at, $2) so the original
timestamp is kept; the row still matches so the idempotent 204 is
unchanged.
@beardthelion beardthelion added kind:feature New capability or surface crate:node gitlawb-node — the serving node and REST API subsystem:peers Peer announce, discovery, and registry subsystem:identity DID/UCAN, http-sig auth, push authorization sev:medium Degraded but workaround exists labels Jun 22, 2026
Resolves a migration version collision in db/mod.rs: both this branch
and #40 (now on main) added a version-5 migration. Kept main's released
v5 (encrypted_blobs_blind_recipients) and renumbered this branch's
agent_retirement migration to v6, appended after it. The two are
independent (agents vs encrypted_blobs); only the version number
collided. schema_migrations keys on version, and the strictly-increasing
invariant test passes (1..6).

@coderabbitai coderabbitai Bot 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.

🧹 Nitpick comments (1)
crates/gitlawb-node/src/db/mod.rs (1)

1076-1087: 🧹 Nitpick | 🔵 Trivial | 💤 Low value

Consider filtering by status = 'active' in SQL for efficiency.

The query fetches all agents (including revoked) and filters in memory via filter_discoverable. For large registries, adding a WHERE clause reduces data transfer and memory usage:

         let rows = sqlx::query(
-            "SELECT did, trust_score, capabilities, registered_at, last_seen, status \
-             FROM agents ORDER BY trust_score DESC",
+            "SELECT did, trust_score, capabilities, registered_at, last_seen, status \
+             FROM agents WHERE status = 'active' ORDER BY trust_score DESC",
         )

This keeps filter_discoverable for capability matching while letting the DB handle status filtering. Low priority if agent counts stay modest.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@crates/gitlawb-node/src/db/mod.rs` around lines 1076 - 1087, The list_agents
method currently fetches all agents from the database and filters them in memory
via filter_discoverable, which is inefficient for large agent registries. Modify
the SQL query in list_agents to add a WHERE clause that filters for agents with
status = 'active' at the database level before results are transferred and
mapped, while keeping the existing filter_discoverable call to handle the
capability filtering logic.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Nitpick comments:
In `@crates/gitlawb-node/src/db/mod.rs`:
- Around line 1076-1087: The list_agents method currently fetches all agents
from the database and filters them in memory via filter_discoverable, which is
inefficient for large agent registries. Modify the SQL query in list_agents to
add a WHERE clause that filters for agents with status = 'active' at the
database level before results are transferred and mapped, while keeping the
existing filter_discoverable call to handle the capability filtering logic.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: b65dd486-61f6-44af-b2f7-af8991debe3d

📥 Commits

Reviewing files that changed from the base of the PR and between 6b652a9 and 7394ff0.

📒 Files selected for processing (1)
  • crates/gitlawb-node/src/db/mod.rs

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

LGTM

@kevincodex1 kevincodex1 merged commit ff492b4 into main Jun 23, 2026
14 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

crate:node gitlawb-node — the serving node and REST API kind:feature New capability or surface sev:medium Degraded but workaround exists subsystem:identity DID/UCAN, http-sig auth, push authorization subsystem:peers Peer announce, discovery, and registry

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Agents with rotated/compromised keys can't be deregistered — orphan DIDs persist under shared capabilities

2 participants