Skip to content

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

Open
beardthelion wants to merge 2 commits into
mainfrom
feat/agent-registry-retirement
Open

feat(node): signature-gated agent self-deregister (#29)#63
beardthelion wants to merge 2 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 agent self-deregistration capability allowing users to revoke their own accounts.
    • Agent status field now displays in API responses to indicate if an agent is active or revoked.
    • Revoked agents are now properly filtered out from discovery operations and routing.

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

Review Change Stack

Warning

Review limit reached

@beardthelion, we couldn't start this review because you've reached your PR review rate limit.

More reviews will be available in 44 minutes and 50 seconds. Learn how PR review limits work.

To continue reviewing without waiting, enable usage-based billing in the billing tab.

⌛ How to resolve this issue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based credits.

🚦 How do rate limits work?

CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan refill rate.

For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, the refill rate gradually slows as usage increases. The highest same-day bursts are limited more strictly.

Please see our Fair Usage Limits Policy for further information.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: 064d324b-32a8-4c6f-af4b-9e489d92ca49

📥 Commits

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

📒 Files selected for processing (1)
  • crates/gitlawb-node/src/db/mod.rs
📝 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 v5 (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 clearly and specifically describes the main change: adding a signature-gated agent self-deregister feature with reference to the linked issue #29.
Description check ✅ Passed The description comprehensively covers all required template sections: summary, motivation with issue link, kind of change (Feature & Security fix), what changed with crate specifics, verification steps, pre-review checklist completion, and protocol/signing impact assessment.
Linked Issues check ✅ Passed The PR fully implements the primary objective from issue #29: signature-gated self-deregister via RFC 9421 authentication, allowing DID key holders to retire their own agents and remove them from discovery and routing.
Out of Scope Changes check ✅ Passed All changes are directly scoped to implementing agent self-deregister: database migration for status tracking, endpoint authorization, filtering active agents from discovery, and comprehensive tests. No unrelated changes detected.
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 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

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

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

1 participant