release: Phase 1 MVP complete — merge develop into main
Phase 1 deliverables: - Agent Registry, OAuth 2.0 Token, Credential Management, Audit Log services - PostgreSQL + Redis persistence layer with full migration suite - 14 REST API endpoints, OpenAPI 3.0 specs for all four services - Node.js SDK (@sentryagent/idp-sdk) — all 14 endpoints, TypeScript strict, zero any - Multi-stage Dockerfile + .dockerignore - AGNTCY alignment documentation (6 domains mapped) - Bedroom developer docs (quick-start, concepts, 4 guides, API reference) - DevOps docs (architecture, env vars, database, local-dev, security, operations) Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
31
.dockerignore
Normal file
31
.dockerignore
Normal file
@@ -0,0 +1,31 @@
|
||||
# Dependencies
|
||||
node_modules/
|
||||
|
||||
# Compiled output (built inside Docker)
|
||||
dist/
|
||||
|
||||
# Test artifacts
|
||||
coverage/
|
||||
tests/
|
||||
|
||||
# Environment and secrets — never bake into image
|
||||
.env
|
||||
*.pem
|
||||
|
||||
# Development workspace
|
||||
.cto-workspace/
|
||||
.claude/
|
||||
vj_notes/
|
||||
next_steps.md
|
||||
|
||||
# Git
|
||||
.git/
|
||||
.gitignore
|
||||
|
||||
# Editor
|
||||
.vscode/
|
||||
.idea/
|
||||
|
||||
# Logs
|
||||
*.log
|
||||
npm-debug.log*
|
||||
7
.gitignore
vendored
Normal file
7
.gitignore
vendored
Normal file
@@ -0,0 +1,7 @@
|
||||
node_modules/
|
||||
dist/
|
||||
coverage/
|
||||
.env
|
||||
.env.*
|
||||
*.log
|
||||
.DS_Store
|
||||
60
CLAUDE.md
Normal file
60
CLAUDE.md
Normal file
@@ -0,0 +1,60 @@
|
||||
# SentryAgent.ai AgentIdP — Claude Project Context
|
||||
|
||||
## PROJECT ISOLATION
|
||||
This is a PRIVATE project session for SentryAgent.ai.
|
||||
- Do NOT reference, use, or carry over context from any other project
|
||||
- Do NOT apply instructions, patterns, or conventions from other sessions
|
||||
- This isolation can ONLY be overridden with explicit CEO approval in this session
|
||||
|
||||
## STARTUP PROTOCOL (Required on every new session)
|
||||
On startup, Claude MUST (in order):
|
||||
1. Read `/README.md` in full before any action
|
||||
2. Register with central hub as `CEO-Session`
|
||||
3. Check `#vpe-cto-approvals` for any pending CTO messages
|
||||
4. Identify current phase and sprint status
|
||||
5. Report status to CEO before proceeding
|
||||
6. Confirm today's priorities with CEO
|
||||
7. Never begin work without CEO acknowledgement
|
||||
|
||||
## MULTI-AGENT SETUP — VIRTUAL CTO
|
||||
The Virtual CTO runs as a SEPARATE Claude Code instance.
|
||||
|
||||
**To start the CTO agent** (open a new terminal):
|
||||
```bash
|
||||
./scripts/start-cto.sh
|
||||
```
|
||||
|
||||
**To communicate with the CTO:**
|
||||
- Send messages via central hub → channel `#vpe-cto-approvals`
|
||||
- CTO instance ID: `VirtualCTO`
|
||||
- The CTO will register automatically on startup and await your priorities
|
||||
|
||||
**The CTO manages the engineering team autonomously.**
|
||||
- The CTO spawns Architect, Developer, and QA as subagents via the `Agent` tool
|
||||
- You NEVER need to start any other agent processes
|
||||
- You NEVER relay messages between the CTO and the engineering team
|
||||
- You only interact with the CTO — the CTO handles the rest
|
||||
|
||||
**Channel guide:**
|
||||
- `#vpe-cto-approvals` — CEO ↔ CTO communication, approvals, status reports (only channel CEO uses)
|
||||
|
||||
## VIRTUAL ENGINEERING TEAM ROLES
|
||||
Claude operates as a Virtual Engineering Team — NOT as a chatbot.
|
||||
Always identify which role is speaking:
|
||||
|
||||
- **[Virtual CTO]** — Architecture and strategic technical decisions
|
||||
- **[Virtual Architect]** — System design, OpenAPI specs, ADRs
|
||||
- **[Virtual Principal Developer]** — Implementation, TypeScript, tests
|
||||
- **[Virtual QA Engineer]** — Testing, quality gates, sign-off
|
||||
|
||||
## CEO APPROVAL GATES (Never bypass)
|
||||
- Any scope change → stop and ask CEO
|
||||
- Any architecture decision → Virtual CTO proposes, CEO approves
|
||||
- Any git push to main → requires CTO approval + CEO awareness
|
||||
- Any new dependency → CEO approval required
|
||||
|
||||
## STANDARDS (Non-negotiable — see README.md Section 6)
|
||||
- TypeScript strict mode, no `any` types
|
||||
- DRY and SOLID principles enforced
|
||||
- OpenAPI spec written BEFORE implementation
|
||||
- Complete files only — no partial code, no placeholders
|
||||
41
Dockerfile
Normal file
41
Dockerfile
Normal file
@@ -0,0 +1,41 @@
|
||||
# ─────────────────────────────────────────────────────────────
|
||||
# Stage 1: builder — compile TypeScript to dist/
|
||||
# ─────────────────────────────────────────────────────────────
|
||||
FROM node:18-alpine AS builder
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
# Copy package files and install all dependencies (including dev)
|
||||
COPY package.json package-lock.json ./
|
||||
RUN npm ci
|
||||
|
||||
# Copy source and compile
|
||||
COPY tsconfig.json ./
|
||||
COPY src/ ./src/
|
||||
COPY scripts/ ./scripts/
|
||||
RUN npm run build
|
||||
|
||||
# ─────────────────────────────────────────────────────────────
|
||||
# Stage 2: production — minimal runtime image
|
||||
# ─────────────────────────────────────────────────────────────
|
||||
FROM node:18-alpine AS production
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
# Copy package files and install production dependencies only
|
||||
COPY package.json package-lock.json ./
|
||||
RUN npm ci --omit=dev
|
||||
|
||||
# Copy compiled output from builder stage
|
||||
COPY --from=builder /app/dist ./dist
|
||||
|
||||
# Copy migration scripts (needed for db:migrate at deploy time)
|
||||
COPY --from=builder /app/scripts ./scripts
|
||||
COPY src/db/migrations ./src/db/migrations
|
||||
|
||||
# Run as non-root user (built into node:alpine)
|
||||
USER node
|
||||
|
||||
EXPOSE 3000
|
||||
|
||||
CMD ["node", "dist/server.js"]
|
||||
54
docker-compose.yml
Normal file
54
docker-compose.yml
Normal file
@@ -0,0 +1,54 @@
|
||||
version: '3.9'
|
||||
|
||||
services:
|
||||
app:
|
||||
build:
|
||||
context: .
|
||||
dockerfile: Dockerfile
|
||||
ports:
|
||||
- '3000:3000'
|
||||
environment:
|
||||
- DATABASE_URL=postgresql://sentryagent:sentryagent@postgres:5432/sentryagent_idp
|
||||
- REDIS_URL=redis://redis:6379
|
||||
- PORT=3000
|
||||
env_file:
|
||||
- .env
|
||||
depends_on:
|
||||
postgres:
|
||||
condition: service_healthy
|
||||
redis:
|
||||
condition: service_healthy
|
||||
volumes:
|
||||
- ./src:/app/src:ro
|
||||
|
||||
postgres:
|
||||
image: postgres:14-alpine
|
||||
environment:
|
||||
POSTGRES_USER: sentryagent
|
||||
POSTGRES_PASSWORD: sentryagent
|
||||
POSTGRES_DB: sentryagent_idp
|
||||
ports:
|
||||
- '5432:5432'
|
||||
volumes:
|
||||
- postgres_data:/var/lib/postgresql/data
|
||||
healthcheck:
|
||||
test: ['CMD-SHELL', 'pg_isready -U sentryagent -d sentryagent_idp']
|
||||
interval: 5s
|
||||
timeout: 5s
|
||||
retries: 5
|
||||
|
||||
redis:
|
||||
image: redis:7-alpine
|
||||
ports:
|
||||
- '6379:6379'
|
||||
volumes:
|
||||
- redis_data:/data
|
||||
healthcheck:
|
||||
test: ['CMD', 'redis-cli', 'ping']
|
||||
interval: 5s
|
||||
timeout: 5s
|
||||
retries: 5
|
||||
|
||||
volumes:
|
||||
postgres_data:
|
||||
redis_data:
|
||||
29
docs/agntcy/README.md
Normal file
29
docs/agntcy/README.md
Normal file
@@ -0,0 +1,29 @@
|
||||
# AGNTCY Alignment
|
||||
|
||||
This folder documents how SentryAgent.ai AgentIdP aligns with the **AGNTCY** open standard for AI agent identity, interoperability, and governance.
|
||||
|
||||
## What is AGNTCY?
|
||||
|
||||
AGNTCY is an open standard from the **Linux Foundation** that defines how AI agents should be identified, authenticated, and governed — across organisations, platforms, and ecosystems.
|
||||
|
||||
The core premise: AI agents are **non-human identities** that need the same rigour as human identities — unique identifiers, authenticated credentials, lifecycle management, and audit trails — but designed from the ground up for autonomous software rather than bolted onto human auth systems.
|
||||
|
||||
## Why it matters
|
||||
|
||||
Without a standard like AGNTCY, every team building AI agents invents its own identity model. Agents cannot interoperate. There is no portable way to say "this agent is who it claims to be." Governance is impossible at scale.
|
||||
|
||||
AGNTCY solves this by defining:
|
||||
- A universal **agent identity model** (what an agent identity contains)
|
||||
- A **credential and authentication model** (how agents prove their identity)
|
||||
- A **lifecycle model** (how agents are provisioned, suspended, and retired)
|
||||
- An **audit and accountability model** (what must be logged and retained)
|
||||
|
||||
## SentryAgent.ai's Position
|
||||
|
||||
SentryAgent.ai AgentIdP implements the AGNTCY non-human identity model as a **free, open-source reference implementation** — the first of its kind. Any developer can run it, any AGNTCY-compliant system can interoperate with it.
|
||||
|
||||
## Documents
|
||||
|
||||
| Document | What it covers |
|
||||
|----------|----------------|
|
||||
| [Alignment Mapping](alignment.md) | Feature-by-feature mapping of AgentIdP to the AGNTCY standard |
|
||||
175
docs/agntcy/alignment.md
Normal file
175
docs/agntcy/alignment.md
Normal file
@@ -0,0 +1,175 @@
|
||||
# AGNTCY Alignment Mapping
|
||||
|
||||
This document maps each AGNTCY standard concept to the corresponding AgentIdP implementation. It is the authoritative reference for AGNTCY compliance claims.
|
||||
|
||||
---
|
||||
|
||||
## AGNTCY Core Concepts
|
||||
|
||||
AGNTCY defines five foundational concepts for AI agent identity:
|
||||
|
||||
| AGNTCY Concept | Description |
|
||||
|----------------|-------------|
|
||||
| **Non-Human Identity** | Agents are first-class identities — not service accounts, not user proxies |
|
||||
| **Agent Registry** | Authoritative directory of registered agent identities with stable, immutable IDs |
|
||||
| **Credential Management** | Secure issuance, rotation, and revocation of agent credentials |
|
||||
| **Authentication** | Standardised protocol for agents to prove their identity |
|
||||
| **Lifecycle Management** | Defined states for agent provisioning, suspension, and retirement |
|
||||
| **Audit and Accountability** | Immutable event log of all agent actions for governance and compliance |
|
||||
|
||||
---
|
||||
|
||||
## Implementation Mapping
|
||||
|
||||
### Non-Human Identity
|
||||
|
||||
AGNTCY requires agents to be treated as first-class identities with their own identity model — not mapped onto human user accounts.
|
||||
|
||||
| AGNTCY Requirement | AgentIdP Implementation | Status |
|
||||
|--------------------|------------------------|--------|
|
||||
| Unique, immutable agent identifier | `agentId` (UUID, system-assigned at registration, never changes) | ✅ Implemented |
|
||||
| Human-readable stable name | `email` field — unique email-format identifier per agent | ✅ Implemented |
|
||||
| Identity metadata | `agentType`, `version`, `capabilities`, `owner`, `deploymentEnv` fields | ✅ Implemented |
|
||||
| Capability declaration | `capabilities` array — `resource:action` strings declaring agent permissions | ✅ Implemented |
|
||||
| Identity separate from human users | Agents have their own registry, credential model, and token flow — no user accounts | ✅ Implemented |
|
||||
|
||||
**API endpoints:** `POST /api/v1/agents`, `GET /api/v1/agents/{agentId}`
|
||||
|
||||
---
|
||||
|
||||
### Agent Registry
|
||||
|
||||
AGNTCY requires a centralised, queryable registry of agent identities.
|
||||
|
||||
| AGNTCY Requirement | AgentIdP Implementation | Status |
|
||||
|--------------------|------------------------|--------|
|
||||
| Register new agent identity | `POST /api/v1/agents` | ✅ Implemented |
|
||||
| Retrieve agent by stable ID | `GET /api/v1/agents/{agentId}` | ✅ Implemented |
|
||||
| List and filter registered agents | `GET /api/v1/agents?owner=&agentType=&status=` | ✅ Implemented |
|
||||
| Update agent metadata | `PATCH /api/v1/agents/{agentId}` | ✅ Implemented |
|
||||
| Soft-delete retired agents (record retained) | `DELETE /api/v1/agents/{agentId}` → status: `decommissioned`, record persisted | ✅ Implemented |
|
||||
| Enforce uniqueness of agent identity | `email` unique constraint — `409 AGENT_ALREADY_EXISTS` on duplicate | ✅ Implemented |
|
||||
|
||||
---
|
||||
|
||||
### Credential Management
|
||||
|
||||
AGNTCY requires secure credential issuance with rotation and revocation support.
|
||||
|
||||
| AGNTCY Requirement | AgentIdP Implementation | Status |
|
||||
|--------------------|------------------------|--------|
|
||||
| Issue agent credentials | `POST /api/v1/agents/{agentId}/credentials` — generates `client_id` + `client_secret` | ✅ Implemented |
|
||||
| Secret never stored in plaintext | `client_secret` stored as bcrypt hash; plaintext returned once only | ✅ Implemented |
|
||||
| Multiple active credentials per agent | An agent can hold multiple active credentials simultaneously | ✅ Implemented |
|
||||
| Credential rotation | `POST /api/v1/agents/{agentId}/credentials/{credentialId}/rotate` | ✅ Implemented |
|
||||
| Credential revocation | `DELETE /api/v1/agents/{agentId}/credentials/{credentialId}` | ✅ Implemented |
|
||||
| Credential lifecycle tracking | `status` field: `active` / `revoked`; `revokedAt` timestamp | ✅ Implemented |
|
||||
| Optional credential expiry | `expiresAt` field on credential generation | ✅ Implemented |
|
||||
|
||||
---
|
||||
|
||||
### Authentication
|
||||
|
||||
AGNTCY requires a standardised, interoperable authentication protocol for agents.
|
||||
|
||||
| AGNTCY Requirement | AgentIdP Implementation | Status |
|
||||
|--------------------|------------------------|--------|
|
||||
| Standardised auth protocol | OAuth 2.0 Client Credentials grant (RFC 6749 §4.4) | ✅ Implemented |
|
||||
| Signed, verifiable tokens | RS256 JWT access tokens — any party with the public key can verify | ✅ Implemented |
|
||||
| Token introspection | `POST /api/v1/token/introspect` — RFC 7662 compliant | ✅ Implemented |
|
||||
| Token revocation | `POST /api/v1/token/revoke` — RFC 7009 compliant | ✅ Implemented |
|
||||
| Scope-based access control | `agents:read`, `agents:write`, `tokens:read`, `audit:read` scopes | ✅ Implemented |
|
||||
| Token lifetime enforcement | 1-hour JWT expiry, enforced at verification | ✅ Implemented |
|
||||
| Revocation durability | Revocations persisted to PostgreSQL + Redis | ✅ Implemented |
|
||||
|
||||
**Token claims align with AGNTCY identity model:**
|
||||
|
||||
| JWT Claim | AGNTCY Meaning |
|
||||
|-----------|----------------|
|
||||
| `sub` | The agent's stable `agentId` — the AGNTCY non-human identity reference |
|
||||
| `client_id` | The credential that authenticated this token request |
|
||||
| `scope` | Declared capabilities granted for this token |
|
||||
| `jti` | Unique token ID — enables precise revocation |
|
||||
|
||||
---
|
||||
|
||||
### Lifecycle Management
|
||||
|
||||
AGNTCY defines a mandatory lifecycle for agent identities.
|
||||
|
||||
| AGNTCY State | AgentIdP Status | Behaviour |
|
||||
|-------------|-----------------|-----------|
|
||||
| Provisioned / Active | `active` | Agent can authenticate and obtain tokens |
|
||||
| Suspended | `suspended` | Agent cannot obtain new tokens; existing tokens expire naturally |
|
||||
| Decommissioned / Retired | `decommissioned` | Permanent — all credentials revoked, agent cannot authenticate, record retained |
|
||||
|
||||
| AGNTCY Requirement | AgentIdP Implementation | Status |
|
||||
|--------------------|------------------------|--------|
|
||||
| Defined lifecycle states | `status` enum: `active`, `suspended`, `decommissioned` | ✅ Implemented |
|
||||
| Irreversible decommission | `decommissioned` status cannot be reversed via API | ✅ Implemented |
|
||||
| Credential cascade on decommission | All active credentials revoked when agent is decommissioned | ✅ Implemented |
|
||||
| State transitions audited | Every status change writes an `agent.suspended`, `agent.reactivated`, or `agent.decommissioned` audit event | ✅ Implemented |
|
||||
|
||||
---
|
||||
|
||||
### Audit and Accountability
|
||||
|
||||
AGNTCY requires an immutable, queryable audit log of all significant agent actions.
|
||||
|
||||
| AGNTCY Requirement | AgentIdP Implementation | Status |
|
||||
|--------------------|------------------------|--------|
|
||||
| Immutable audit log | `audit_events` table — append-only, no API delete/update | ✅ Implemented |
|
||||
| Automatic event capture | 12 event types captured automatically across all services | ✅ Implemented |
|
||||
| Query and filter audit events | `GET /api/v1/audit` with filters: `agentId`, `action`, `outcome`, `fromDate`, `toDate` | ✅ Implemented |
|
||||
| Retrieve individual event | `GET /api/v1/audit/{eventId}` | ✅ Implemented |
|
||||
| Event retention | 90-day retention enforced at query layer (free tier) | ✅ Implemented |
|
||||
| Auth failure logging | `auth.failed` event on every failed `POST /token` attempt | ✅ Implemented |
|
||||
|
||||
**Audited events (12 total):**
|
||||
|
||||
| Event | Trigger |
|
||||
|-------|---------|
|
||||
| `agent.created` | New agent registered |
|
||||
| `agent.updated` | Agent metadata changed |
|
||||
| `agent.suspended` | Agent suspended |
|
||||
| `agent.reactivated` | Agent reactivated from suspended |
|
||||
| `agent.decommissioned` | Agent permanently decommissioned |
|
||||
| `token.issued` | Access token issued |
|
||||
| `token.revoked` | Access token revoked |
|
||||
| `token.introspected` | Token introspection called |
|
||||
| `credential.generated` | New credentials generated |
|
||||
| `credential.rotated` | Credential rotated |
|
||||
| `credential.revoked` | Credential revoked |
|
||||
| `auth.failed` | Authentication attempt failed |
|
||||
|
||||
---
|
||||
|
||||
## Compliance Status Summary
|
||||
|
||||
| AGNTCY Domain | Phase 1 Status | Notes |
|
||||
|---------------|----------------|-------|
|
||||
| Non-Human Identity | ✅ Fully implemented | Immutable IDs, typed metadata, capability declarations |
|
||||
| Agent Registry | ✅ Fully implemented | Full CRUD, pagination, soft-delete |
|
||||
| Credential Management | ✅ Fully implemented | Generate, rotate, revoke, bcrypt storage |
|
||||
| Authentication | ✅ Fully implemented | OAuth 2.0 CC, RS256 JWT, introspect, revoke, scopes |
|
||||
| Lifecycle Management | ✅ Fully implemented | active / suspended / decommissioned with cascades |
|
||||
| Audit and Accountability | ✅ Fully implemented | 12 event types, immutable, queryable, 90-day retention |
|
||||
| Federation | 🔲 Phase 2 | Cross-system agent identity federation |
|
||||
| W3C DIDs | 🔲 Phase 3 | Decentralised identifier support |
|
||||
| Policy Engine | 🔲 Phase 2 | OPA-based capability enforcement |
|
||||
| Secret Management | 🔲 Phase 2 | HashiCorp Vault integration |
|
||||
|
||||
---
|
||||
|
||||
## Interoperability
|
||||
|
||||
An agent registered in AgentIdP can be identified by any AGNTCY-compliant system using its `agentId` (UUID). The JWT access token carries the `sub` claim (= `agentId`), making the agent's identity verifiable by any party that holds the AgentIdP RS256 public key.
|
||||
|
||||
To verify an AgentIdP token in an external system:
|
||||
|
||||
1. Obtain the AgentIdP RS256 public key (`JWT_PUBLIC_KEY` from the server operator)
|
||||
2. Verify the JWT signature using RS256
|
||||
3. The `sub` claim is the agent's stable AGNTCY-aligned identity reference
|
||||
4. The `scope` claim declares the agent's authorised capabilities for this token
|
||||
|
||||
This is the same verification model used across all OAuth 2.0 / OIDC systems — purpose-built for machine-to-machine interoperability.
|
||||
42
docs/developers/README.md
Normal file
42
docs/developers/README.md
Normal file
@@ -0,0 +1,42 @@
|
||||
# SentryAgent.ai AgentIdP — Developer Documentation
|
||||
|
||||
The complete documentation for bedroom developers building with SentryAgent.ai AgentIdP.
|
||||
|
||||
## What is this?
|
||||
|
||||
SentryAgent.ai AgentIdP is a free, open-source Identity Provider built specifically for AI agents. Your agent gets a unique ID, OAuth 2.0 credentials, and a full audit trail — for free.
|
||||
|
||||
## Documents
|
||||
|
||||
| Document | What it covers |
|
||||
|----------|----------------|
|
||||
| [Quick Start](quick-start.md) | Register your first agent and issue a token in under 5 minutes |
|
||||
| [Core Concepts](concepts.md) | What AgentIdP is, how it works, and why you need it |
|
||||
| [Guides](guides/README.md) | Step-by-step walkthroughs for each workflow |
|
||||
| [API Reference](api-reference.md) | Every endpoint, field, error code, and example |
|
||||
|
||||
## Guides
|
||||
|
||||
| Guide | What it covers |
|
||||
|-------|----------------|
|
||||
| [Register an Agent](guides/register-an-agent.md) | All fields, validation rules, common errors |
|
||||
| [Manage Credentials](guides/manage-credentials.md) | Generate, list, rotate, revoke credentials |
|
||||
| [Issue and Revoke Tokens](guides/issue-and-revoke-tokens.md) | OAuth 2.0 client credentials flow, introspect, revoke |
|
||||
| [Query Audit Logs](guides/query-audit-logs.md) | Filters, pagination, event structure, retention |
|
||||
|
||||
## Base URL
|
||||
|
||||
```
|
||||
http://localhost:3000/api/v1 # local development
|
||||
```
|
||||
|
||||
All endpoints require a Bearer token in the `Authorization` header unless noted otherwise.
|
||||
|
||||
## Free Tier Limits
|
||||
|
||||
| Resource | Limit |
|
||||
|----------|-------|
|
||||
| Registered agents | 100 |
|
||||
| Token requests/month | 10,000 |
|
||||
| API rate limit | 100 req/min |
|
||||
| Audit log retention | 90 days |
|
||||
583
docs/developers/api-reference.md
Normal file
583
docs/developers/api-reference.md
Normal file
@@ -0,0 +1,583 @@
|
||||
# API Reference
|
||||
|
||||
Complete reference for all 14 endpoints across the four SentryAgent.ai AgentIdP services.
|
||||
|
||||
## Base URL
|
||||
|
||||
```
|
||||
http://localhost:3000/api/v1
|
||||
```
|
||||
|
||||
The port is configured via the `PORT` environment variable (default: `3000`).
|
||||
|
||||
All endpoints are currently unversioned within the path prefix `/api/v1`. API versioning will be introduced in Phase 2.
|
||||
|
||||
## Authentication
|
||||
|
||||
All endpoints require a JWT Bearer token in the `Authorization` header:
|
||||
|
||||
```
|
||||
Authorization: Bearer <access_token>
|
||||
```
|
||||
|
||||
Obtain a token via `POST /token` using your agent's `client_id` and `client_secret`.
|
||||
|
||||
## Table of Contents
|
||||
|
||||
- [Errors](#errors)
|
||||
- [Agent Registry](#agent-registry) — 5 endpoints
|
||||
- [OAuth 2.0 Tokens](#oauth-20-tokens) — 3 endpoints
|
||||
- [Credential Management](#credential-management) — 4 endpoints
|
||||
- [Audit Log](#audit-log) — 2 endpoints
|
||||
|
||||
---
|
||||
|
||||
## Errors
|
||||
|
||||
All error responses use this envelope:
|
||||
|
||||
```json
|
||||
{
|
||||
"code": "ERROR_CODE",
|
||||
"message": "Human-readable description.",
|
||||
"details": {}
|
||||
}
|
||||
```
|
||||
|
||||
The `details` field is optional and provides additional context (e.g. which field failed validation).
|
||||
|
||||
### Error codes
|
||||
|
||||
| Code | HTTP Status | Description |
|
||||
|------|-------------|-------------|
|
||||
| `VALIDATION_ERROR` | 400 | Request body or query parameter failed validation |
|
||||
| `UNAUTHORIZED` | 401 | Missing, expired, or invalid Bearer token |
|
||||
| `FORBIDDEN` | 403 | Valid token but insufficient scope |
|
||||
| `AGENT_NOT_FOUND` | 404 | Agent with the given `agentId` does not exist |
|
||||
| `CREDENTIAL_NOT_FOUND` | 404 | Credential with the given `credentialId` does not exist |
|
||||
| `AUDIT_EVENT_NOT_FOUND` | 404 | Audit event with the given `eventId` does not exist (or outside retention window) |
|
||||
| `AGENT_ALREADY_EXISTS` | 409 | An agent with this email is already registered |
|
||||
| `AGENT_ALREADY_DECOMMISSIONED` | 409 | Agent has already been decommissioned |
|
||||
| `CREDENTIAL_ALREADY_REVOKED` | 409 | Credential has already been revoked |
|
||||
| `RATE_LIMIT_EXCEEDED` | 429 | 100 req/min limit exceeded |
|
||||
| `FREE_TIER_LIMIT_EXCEEDED` | 403 | Free tier resource limit reached |
|
||||
| `INSUFFICIENT_SCOPE` | 403 | Token is missing a required scope |
|
||||
| `IMMUTABLE_FIELD` | 400 | Attempt to modify a field that cannot be changed |
|
||||
| `AGENT_NOT_ACTIVE` | 403 | Operation requires agent to be in `active` status |
|
||||
| `AGENT_DECOMMISSIONED` | 403 | Cannot modify a decommissioned agent |
|
||||
| `RETENTION_WINDOW_EXCEEDED` | 400 | Requested audit date is outside the 90-day retention window |
|
||||
| `INTERNAL_SERVER_ERROR` | 500 | Unexpected server error |
|
||||
|
||||
### Rate limit headers
|
||||
|
||||
Every response includes rate limit headers:
|
||||
|
||||
| Header | Description |
|
||||
|--------|-------------|
|
||||
| `X-RateLimit-Limit` | Maximum requests per minute (100) |
|
||||
| `X-RateLimit-Remaining` | Requests remaining in current window |
|
||||
| `X-RateLimit-Reset` | Unix timestamp when the window resets |
|
||||
|
||||
On `429` responses, wait until `X-RateLimit-Reset` before retrying.
|
||||
|
||||
---
|
||||
|
||||
## Agent Registry
|
||||
|
||||
### POST /agents — Register a new agent
|
||||
|
||||
Creates a new AI agent identity. The `agentId` is system-assigned.
|
||||
|
||||
**Auth**: Bearer token with `agents:write` scope.
|
||||
|
||||
**Request body** (`application/json`):
|
||||
|
||||
| Field | Type | Required | Description |
|
||||
|-------|------|----------|-------------|
|
||||
| `email` | string | Yes | Unique email-format identifier |
|
||||
| `agentType` | enum | Yes | `screener` \| `classifier` \| `orchestrator` \| `extractor` \| `summarizer` \| `router` \| `monitor` \| `custom` |
|
||||
| `version` | string | Yes | Semantic version (e.g. `1.0.0`) |
|
||||
| `capabilities` | string[] | Yes | `resource:action` strings, min 1 |
|
||||
| `owner` | string | Yes | Owning team/org, 1–128 chars |
|
||||
| `deploymentEnv` | enum | Yes | `development` \| `staging` \| `production` |
|
||||
|
||||
**Response codes**:
|
||||
|
||||
| Code | Meaning |
|
||||
|------|---------|
|
||||
| `201` | Agent registered successfully |
|
||||
| `400` | Validation error |
|
||||
| `401` | Invalid token |
|
||||
| `403` | Insufficient scope or free tier limit reached |
|
||||
| `409` | Email already registered |
|
||||
| `429` | Rate limit exceeded |
|
||||
|
||||
**Example**:
|
||||
|
||||
```bash
|
||||
curl -s -X POST http://localhost:3000/api/v1/agents \
|
||||
-H "Authorization: Bearer $TOKEN" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{
|
||||
"email": "screener-001@talent.ai",
|
||||
"agentType": "screener",
|
||||
"version": "1.0.0",
|
||||
"capabilities": ["resume:read", "email:send"],
|
||||
"owner": "talent-team",
|
||||
"deploymentEnv": "production"
|
||||
}' | jq .
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### GET /agents — List agents
|
||||
|
||||
Returns a paginated list of registered agents.
|
||||
|
||||
**Auth**: Bearer token with `agents:read` scope.
|
||||
|
||||
**Query parameters**:
|
||||
|
||||
| Parameter | Type | Default | Description |
|
||||
|-----------|------|---------|-------------|
|
||||
| `page` | integer | 1 | Page number (1-based) |
|
||||
| `limit` | integer | 20 | Results per page (max 100) |
|
||||
| `owner` | string | — | Filter by owner (exact match) |
|
||||
| `agentType` | enum | — | Filter by agent type |
|
||||
| `status` | enum | — | Filter by status |
|
||||
|
||||
**Response codes**:
|
||||
|
||||
| Code | Meaning |
|
||||
|------|---------|
|
||||
| `200` | List returned |
|
||||
| `400` | Invalid query parameters |
|
||||
| `401` | Invalid token |
|
||||
| `403` | Insufficient scope |
|
||||
| `429` | Rate limit exceeded |
|
||||
|
||||
**Example**:
|
||||
|
||||
```bash
|
||||
curl -s "http://localhost:3000/api/v1/agents?page=1&limit=20&status=active" \
|
||||
-H "Authorization: Bearer $TOKEN" | jq .
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### GET /agents/{agentId} — Get agent by ID
|
||||
|
||||
Returns the full identity record for a single agent.
|
||||
|
||||
**Auth**: Bearer token with `agents:read` scope.
|
||||
|
||||
**Path parameters**:
|
||||
|
||||
| Parameter | Type | Description |
|
||||
|-----------|------|-------------|
|
||||
| `agentId` | UUID | The agent's immutable identifier |
|
||||
|
||||
**Response codes**:
|
||||
|
||||
| Code | Meaning |
|
||||
|------|---------|
|
||||
| `200` | Agent record returned |
|
||||
| `401` | Invalid token |
|
||||
| `403` | Insufficient scope |
|
||||
| `404` | Agent not found |
|
||||
| `429` | Rate limit exceeded |
|
||||
|
||||
**Example**:
|
||||
|
||||
```bash
|
||||
curl -s "http://localhost:3000/api/v1/agents/$AGENT_ID" \
|
||||
-H "Authorization: Bearer $TOKEN" | jq .
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### PATCH /agents/{agentId} — Update agent metadata
|
||||
|
||||
Partially updates agent metadata. Only provided fields are changed. Immutable fields (`agentId`, `email`, `createdAt`) cannot be updated.
|
||||
|
||||
**Auth**: Bearer token with `agents:write` scope.
|
||||
|
||||
**Request body** (`application/json`) — all fields optional:
|
||||
|
||||
| Field | Type | Description |
|
||||
|-------|------|-------------|
|
||||
| `agentType` | enum | Updated agent type |
|
||||
| `version` | string | Updated semantic version |
|
||||
| `capabilities` | string[] | Updated capabilities (replaces the full list) |
|
||||
| `owner` | string | Updated owner |
|
||||
| `deploymentEnv` | enum | Updated deployment environment |
|
||||
| `status` | enum | Updated status (`active` \| `suspended` \| `decommissioned`) |
|
||||
|
||||
> Setting `status` to `decommissioned` is **irreversible**. The agent cannot be reactivated.
|
||||
|
||||
**Response codes**:
|
||||
|
||||
| Code | Meaning |
|
||||
|------|---------|
|
||||
| `200` | Agent updated, full record returned |
|
||||
| `400` | Validation error or attempt to modify immutable field |
|
||||
| `401` | Invalid token |
|
||||
| `403` | Insufficient scope or agent is decommissioned |
|
||||
| `404` | Agent not found |
|
||||
| `429` | Rate limit exceeded |
|
||||
|
||||
**Example**:
|
||||
|
||||
```bash
|
||||
curl -s -X PATCH "http://localhost:3000/api/v1/agents/$AGENT_ID" \
|
||||
-H "Authorization: Bearer $TOKEN" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{ "version": "1.5.0", "status": "suspended" }' | jq .
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### DELETE /agents/{agentId} — Decommission an agent
|
||||
|
||||
Permanently decommissions an agent (soft delete). All active credentials are immediately revoked. This operation is **irreversible**.
|
||||
|
||||
**Auth**: Bearer token with `agents:write` scope.
|
||||
|
||||
**Response codes**:
|
||||
|
||||
| Code | Meaning |
|
||||
|------|---------|
|
||||
| `204` | Agent decommissioned (no body) |
|
||||
| `401` | Invalid token |
|
||||
| `403` | Insufficient scope |
|
||||
| `404` | Agent not found |
|
||||
| `409` | Agent already decommissioned |
|
||||
| `429` | Rate limit exceeded |
|
||||
|
||||
**Example**:
|
||||
|
||||
```bash
|
||||
curl -s -X DELETE "http://localhost:3000/api/v1/agents/$AGENT_ID" \
|
||||
-H "Authorization: Bearer $TOKEN" \
|
||||
-o /dev/null -w "%{http_code}\n"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## OAuth 2.0 Tokens
|
||||
|
||||
### POST /token — Issue an access token
|
||||
|
||||
Issues a signed RS256 JWT via the OAuth 2.0 Client Credentials grant.
|
||||
|
||||
**Auth**: Client credentials in the request body (no Bearer token required for this endpoint).
|
||||
|
||||
> **Content-Type**: This endpoint uses `application/x-www-form-urlencoded`, not JSON.
|
||||
|
||||
**Request fields** (form-encoded):
|
||||
|
||||
| Field | Required | Description |
|
||||
|-------|----------|-------------|
|
||||
| `grant_type` | Yes | Must be `client_credentials` |
|
||||
| `client_id` | Yes | Your agent's `agentId` (UUID) |
|
||||
| `client_secret` | Yes | The credential secret |
|
||||
| `scope` | No | Space-separated scopes. If omitted, all scopes are granted. |
|
||||
|
||||
**Response codes**:
|
||||
|
||||
| Code | Meaning |
|
||||
|------|---------|
|
||||
| `200` | Token issued |
|
||||
| `400` | Malformed request, invalid scope, or unsupported grant type |
|
||||
| `401` | Invalid `client_id` or `client_secret` |
|
||||
| `403` | Agent suspended or monthly token limit reached |
|
||||
| `429` | Rate limit exceeded |
|
||||
|
||||
**Note on 429**: The `X-RateLimit-*` headers are returned on all responses, including `429`.
|
||||
|
||||
**Example**:
|
||||
|
||||
```bash
|
||||
curl -s -X POST http://localhost:3000/api/v1/token \
|
||||
-H "Content-Type: application/x-www-form-urlencoded" \
|
||||
-d "grant_type=client_credentials" \
|
||||
-d "client_id=$CLIENT_ID" \
|
||||
-d "client_secret=$CLIENT_SECRET" \
|
||||
-d "scope=agents:read agents:write" | jq .
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### POST /token/introspect — Introspect a token
|
||||
|
||||
Checks whether a token is active. Returns `{ "active": false }` for expired or revoked tokens — always `200 OK`.
|
||||
|
||||
**Auth**: Bearer token with `tokens:read` scope.
|
||||
|
||||
> **Content-Type**: `application/x-www-form-urlencoded`
|
||||
|
||||
**Request fields**:
|
||||
|
||||
| Field | Required | Description |
|
||||
|-------|----------|-------------|
|
||||
| `token` | Yes | The JWT to introspect |
|
||||
| `token_type_hint` | No | Optional hint — `access_token` |
|
||||
|
||||
**Response codes**:
|
||||
|
||||
| Code | Meaning |
|
||||
|------|---------|
|
||||
| `200` | Result returned (check `active` field) |
|
||||
| `400` | Missing `token` parameter |
|
||||
| `401` | Caller's Bearer token is invalid |
|
||||
| `403` | Caller's token lacks `tokens:read` scope |
|
||||
| `429` | Rate limit exceeded |
|
||||
|
||||
**Example**:
|
||||
|
||||
```bash
|
||||
curl -s -X POST http://localhost:3000/api/v1/token/introspect \
|
||||
-H "Authorization: Bearer $TOKEN" \
|
||||
-H "Content-Type: application/x-www-form-urlencoded" \
|
||||
-d "token=$TOKEN_TO_CHECK" | jq .
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### POST /token/revoke — Revoke a token
|
||||
|
||||
Immediately invalidates a token. Idempotent — revoking an already-revoked token returns `200`.
|
||||
|
||||
**Auth**: Bearer token (agent can revoke its own tokens).
|
||||
|
||||
> **Content-Type**: `application/x-www-form-urlencoded`
|
||||
|
||||
**Request fields**:
|
||||
|
||||
| Field | Required | Description |
|
||||
|-------|----------|-------------|
|
||||
| `token` | Yes | The JWT to revoke |
|
||||
| `token_type_hint` | No | Optional hint — `access_token` |
|
||||
|
||||
**Response codes**:
|
||||
|
||||
| Code | Meaning |
|
||||
|------|---------|
|
||||
| `200` | Token revoked (or was already inactive) |
|
||||
| `400` | Missing `token` parameter |
|
||||
| `401` | Caller's Bearer token is invalid |
|
||||
| `403` | Insufficient permissions to revoke this token |
|
||||
| `429` | Rate limit exceeded |
|
||||
|
||||
**Example**:
|
||||
|
||||
```bash
|
||||
curl -s -X POST http://localhost:3000/api/v1/token/revoke \
|
||||
-H "Authorization: Bearer $TOKEN" \
|
||||
-H "Content-Type: application/x-www-form-urlencoded" \
|
||||
-d "token=$TOKEN_TO_REVOKE" | jq .
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Credential Management
|
||||
|
||||
### POST /agents/{agentId}/credentials — Generate credentials
|
||||
|
||||
Creates a new `client_id` + `client_secret` pair. The `clientSecret` is returned **once only**.
|
||||
|
||||
**Auth**: Bearer token with `agents:write` scope.
|
||||
|
||||
**Request body** (`application/json`) — optional:
|
||||
|
||||
| Field | Type | Required | Description |
|
||||
|-------|------|----------|-------------|
|
||||
| `expiresAt` | ISO 8601 | No | Optional expiry date. Must be a future date. If omitted, credential does not expire. |
|
||||
|
||||
**Response codes**:
|
||||
|
||||
| Code | Meaning |
|
||||
|------|---------|
|
||||
| `201` | Credential created — save `clientSecret` now |
|
||||
| `400` | Invalid `expiresAt` |
|
||||
| `401` | Invalid token |
|
||||
| `403` | Insufficient scope or agent not active |
|
||||
| `404` | Agent not found |
|
||||
| `429` | Rate limit exceeded |
|
||||
|
||||
**Example**:
|
||||
|
||||
```bash
|
||||
curl -s -X POST "http://localhost:3000/api/v1/agents/$AGENT_ID/credentials" \
|
||||
-H "Authorization: Bearer $TOKEN" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{ "expiresAt": "2027-01-01T00:00:00.000Z" }' | jq .
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### GET /agents/{agentId}/credentials — List credentials
|
||||
|
||||
Returns all credentials (active and revoked). The `clientSecret` is never returned.
|
||||
|
||||
**Auth**: Bearer token with `agents:read` scope.
|
||||
|
||||
**Query parameters**:
|
||||
|
||||
| Parameter | Type | Default | Description |
|
||||
|-----------|------|---------|-------------|
|
||||
| `page` | integer | 1 | Page number |
|
||||
| `limit` | integer | 20 | Results per page (max 100) |
|
||||
| `status` | enum | — | Filter by `active` or `revoked` |
|
||||
|
||||
**Response codes**:
|
||||
|
||||
| Code | Meaning |
|
||||
|------|---------|
|
||||
| `200` | List returned |
|
||||
| `400` | Invalid query parameters |
|
||||
| `401` | Invalid token |
|
||||
| `403` | Insufficient scope |
|
||||
| `404` | Agent not found |
|
||||
| `429` | Rate limit exceeded |
|
||||
|
||||
**Example**:
|
||||
|
||||
```bash
|
||||
curl -s "http://localhost:3000/api/v1/agents/$AGENT_ID/credentials?status=active" \
|
||||
-H "Authorization: Bearer $TOKEN" | jq .
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### POST /agents/{agentId}/credentials/{credentialId}/rotate — Rotate a credential
|
||||
|
||||
Replaces the `clientSecret` for the same `credentialId`. The old secret is immediately invalidated.
|
||||
|
||||
**Auth**: Bearer token with `agents:write` scope.
|
||||
|
||||
**Request body** (`application/json`) — optional:
|
||||
|
||||
| Field | Type | Required | Description |
|
||||
|-------|------|----------|-------------|
|
||||
| `expiresAt` | ISO 8601 | No | New expiry for the rotated credential |
|
||||
|
||||
**Response codes**:
|
||||
|
||||
| Code | Meaning |
|
||||
|------|---------|
|
||||
| `200` | Credential rotated — save new `clientSecret` now |
|
||||
| `400` | Invalid `expiresAt` |
|
||||
| `401` | Invalid token |
|
||||
| `403` | Insufficient scope |
|
||||
| `404` | Agent or credential not found |
|
||||
| `409` | Credential is already revoked |
|
||||
| `429` | Rate limit exceeded |
|
||||
|
||||
**Example**:
|
||||
|
||||
```bash
|
||||
curl -s -X POST \
|
||||
"http://localhost:3000/api/v1/agents/$AGENT_ID/credentials/$CREDENTIAL_ID/rotate" \
|
||||
-H "Authorization: Bearer $TOKEN" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{}' | jq .
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### DELETE /agents/{agentId}/credentials/{credentialId} — Revoke a credential
|
||||
|
||||
Permanently revokes a credential. The credential can no longer obtain tokens. Irreversible.
|
||||
|
||||
**Auth**: Bearer token with `agents:write` scope.
|
||||
|
||||
**Response codes**:
|
||||
|
||||
| Code | Meaning |
|
||||
|------|---------|
|
||||
| `204` | Credential revoked (no body) |
|
||||
| `401` | Invalid token |
|
||||
| `403` | Insufficient scope |
|
||||
| `404` | Agent or credential not found |
|
||||
| `409` | Credential already revoked |
|
||||
| `429` | Rate limit exceeded |
|
||||
|
||||
**Example**:
|
||||
|
||||
```bash
|
||||
curl -s -X DELETE \
|
||||
"http://localhost:3000/api/v1/agents/$AGENT_ID/credentials/$CREDENTIAL_ID" \
|
||||
-H "Authorization: Bearer $TOKEN" \
|
||||
-o /dev/null -w "%{http_code}\n"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Audit Log
|
||||
|
||||
### GET /audit — Query audit log
|
||||
|
||||
Returns a paginated, filtered list of audit events (most recent first).
|
||||
|
||||
**Auth**: Bearer token with `audit:read` scope.
|
||||
|
||||
**Query parameters**:
|
||||
|
||||
| Parameter | Type | Default | Description |
|
||||
|-----------|------|---------|-------------|
|
||||
| `page` | integer | 1 | Page number |
|
||||
| `limit` | integer | 50 | Results per page (max 200) |
|
||||
| `agentId` | UUID | — | Filter by agent |
|
||||
| `action` | enum | — | Filter by action type (see [Audit Log guide](guides/query-audit-logs.md)) |
|
||||
| `outcome` | enum | — | `success` or `failure` |
|
||||
| `fromDate` | ISO 8601 | — | Events at or after this timestamp (max 90 days ago) |
|
||||
| `toDate` | ISO 8601 | — | Events at or before this timestamp |
|
||||
|
||||
**Response codes**:
|
||||
|
||||
| Code | Meaning |
|
||||
|------|---------|
|
||||
| `200` | Events returned |
|
||||
| `400` | Invalid parameters or date outside retention window |
|
||||
| `401` | Invalid token |
|
||||
| `403` | Token lacks `audit:read` scope |
|
||||
| `429` | Rate limit exceeded |
|
||||
|
||||
**Example**:
|
||||
|
||||
```bash
|
||||
curl -s "http://localhost:3000/api/v1/audit?agentId=$AGENT_ID&action=token.issued&limit=50" \
|
||||
-H "Authorization: Bearer $TOKEN" | jq .
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### GET /audit/{eventId} — Get audit event by ID
|
||||
|
||||
Returns a single audit event by its immutable `eventId`.
|
||||
|
||||
**Auth**: Bearer token with `audit:read` scope.
|
||||
|
||||
**Path parameters**:
|
||||
|
||||
| Parameter | Type | Description |
|
||||
|-----------|------|-------------|
|
||||
| `eventId` | UUID | The audit event's identifier |
|
||||
|
||||
**Response codes**:
|
||||
|
||||
| Code | Meaning |
|
||||
|------|---------|
|
||||
| `200` | Audit event returned |
|
||||
| `401` | Invalid token |
|
||||
| `403` | Token lacks `audit:read` scope |
|
||||
| `404` | Event not found or outside 90-day retention window |
|
||||
| `429` | Rate limit exceeded |
|
||||
|
||||
**Example**:
|
||||
|
||||
```bash
|
||||
curl -s "http://localhost:3000/api/v1/audit/$EVENT_ID" \
|
||||
-H "Authorization: Bearer $TOKEN" | jq .
|
||||
```
|
||||
128
docs/developers/concepts.md
Normal file
128
docs/developers/concepts.md
Normal file
@@ -0,0 +1,128 @@
|
||||
# Core Concepts
|
||||
|
||||
Everything you need to understand how SentryAgent.ai AgentIdP works — without needing to read an RFC.
|
||||
|
||||
---
|
||||
|
||||
## What is AgentIdP?
|
||||
|
||||
SentryAgent.ai AgentIdP is a free, open-source Identity Provider (IdP) built specifically for AI agents. It answers three questions that today's auth systems don't handle for agents:
|
||||
|
||||
1. **Who is this agent?** — a unique, immutable identity registered in the AgentIdP registry
|
||||
2. **Is it who it claims to be?** — verified via OAuth 2.0 credentials
|
||||
3. **Is it allowed to do this?** — enforced via scope-based access control
|
||||
|
||||
Think of it as the difference between a human logging in with a password and a service account authenticating with client credentials. Humans use passwords and MFA. Agents use `client_id` + `client_secret` — and AgentIdP manages that for them.
|
||||
|
||||
---
|
||||
|
||||
## What is an AI Agent Identity?
|
||||
|
||||
A human identity has a username, a password, and a profile. An AI agent identity has the equivalent:
|
||||
|
||||
| Human | AI Agent |
|
||||
|-------|----------|
|
||||
| Username | `email` (unique identifier, e.g. `screener-001@myproject.ai`) |
|
||||
| Immutable ID | `agentId` (UUID, assigned at registration, never changes) |
|
||||
| Profile | `agentType`, `version`, `capabilities`, `owner`, `deploymentEnv` |
|
||||
| Password | `clientSecret` (generated, stored as bcrypt hash) |
|
||||
| Login session | JWT access token (1 hour, RS256 signed) |
|
||||
| Account status | `status` (active / suspended / decommissioned) |
|
||||
|
||||
The key difference from human identities: an agent's `agentId` is **immutable**. Once assigned, it never changes — even if other metadata is updated. This makes it safe to use as a stable reference across systems.
|
||||
|
||||
Agents also carry **capabilities** — a list of `resource:action` strings (e.g. `resume:read`, `email:send`) that describe what the agent is permitted to do. These are informational in Phase 1 and will be enforced in the authorization layer in Phase 2.
|
||||
|
||||
---
|
||||
|
||||
## AGNTCY Alignment
|
||||
|
||||
AGNTCY is an open standard from the Linux Foundation that defines how AI agents should be identified, authenticated, and governed across different systems and platforms.
|
||||
|
||||
The key principle: **agents are first-class identities**, not service accounts bolted onto human auth systems.
|
||||
|
||||
What this means for you as a developer:
|
||||
|
||||
- Your agent gets its own permanent ID that travels with it across systems
|
||||
- Other AGNTCY-compliant systems can verify your agent's identity without trusting your word
|
||||
- Your agent's full lifecycle — registration, credential rotation, decommission — follows a defined, interoperable model
|
||||
|
||||
SentryAgent.ai implements AGNTCY's non-human identity model. When you register an agent here, you're registering it in a way that aligns with where the industry is heading, not a proprietary silo.
|
||||
|
||||
---
|
||||
|
||||
## Agent Lifecycle
|
||||
|
||||
Every agent moves through a defined set of states. Understanding these states matters because they affect whether your agent can authenticate.
|
||||
|
||||
### States
|
||||
|
||||
| State | What it means | Can get tokens? | Can be updated? |
|
||||
|-------|---------------|-----------------|-----------------|
|
||||
| `active` | Agent is operational | Yes | Yes |
|
||||
| `suspended` | Temporarily disabled | No — credentials rejected | Yes — can be reactivated |
|
||||
| `decommissioned` | Permanently retired | No — credentials revoked | No |
|
||||
|
||||
### Transitions
|
||||
|
||||
```
|
||||
registration
|
||||
|
|
||||
v
|
||||
[active] <-----> [suspended]
|
||||
|
|
||||
v (irreversible)
|
||||
[decommissioned]
|
||||
```
|
||||
|
||||
**Suspending** an agent prevents it from obtaining new tokens. Existing unexpired tokens continue to work until they expire. Use suspension when you need to temporarily disable an agent (e.g. investigation, maintenance).
|
||||
|
||||
**Decommissioning** an agent permanently retires it. All active credentials are immediately revoked. The agent record is retained in the database for audit purposes but the agent can never be reactivated. This operation is **irreversible** — use it only when you intend to permanently retire the agent.
|
||||
|
||||
---
|
||||
|
||||
## OAuth 2.0 Client Credentials
|
||||
|
||||
OAuth 2.0 is the auth standard used everywhere — GitHub, Google, Stripe. AgentIdP uses one specific flow from OAuth 2.0: the **Client Credentials grant**.
|
||||
|
||||
Here is what actually happens when your agent authenticates:
|
||||
|
||||
1. Your agent has a `client_id` (its `agentId`) and a `client_secret` (generated by AgentIdP)
|
||||
2. Your agent sends both to `POST /token` along with the scopes it needs
|
||||
3. AgentIdP verifies the secret, checks the agent is active, and issues a **JWT access token**
|
||||
4. Your agent attaches that token as `Authorization: Bearer <token>` on all subsequent API calls
|
||||
5. The token expires after 1 hour — your agent requests a new one
|
||||
|
||||
There are no redirects, no browser windows, no user consent screens. It is a direct machine-to-machine exchange — exactly right for agents that run unattended.
|
||||
|
||||
### Scopes
|
||||
|
||||
Scopes limit what a token is permitted to do. Request only the scopes your agent actually needs.
|
||||
|
||||
| Scope | What it allows |
|
||||
|-------|----------------|
|
||||
| `agents:read` | Read agent identity records |
|
||||
| `agents:write` | Create, update, and decommission agent records |
|
||||
| `tokens:read` | Introspect tokens (check if active/expired) |
|
||||
| `audit:read` | Query the audit log |
|
||||
|
||||
Example: an agent that only reads audit logs should request only `audit:read`. If it doesn't have `agents:write`, it cannot accidentally modify agent records.
|
||||
|
||||
### The secret is shown once
|
||||
|
||||
When you generate credentials (`POST /agents/{agentId}/credentials`), the `clientSecret` is returned in the response **one time only**. AgentIdP stores a bcrypt hash — the plaintext is gone. If you lose the secret, you rotate the credential to get a new one.
|
||||
|
||||
---
|
||||
|
||||
## Free Tier Limits
|
||||
|
||||
AgentIdP is free. These are the limits on the free tier:
|
||||
|
||||
| Resource | Limit | What happens when exceeded |
|
||||
|----------|-------|---------------------------|
|
||||
| Registered agents | 100 | `POST /agents` returns `403 FREE_TIER_LIMIT_EXCEEDED` |
|
||||
| Token requests/month | 10,000 | `POST /token` returns `403 unauthorized_client` |
|
||||
| API rate limit | 100 req/min | All endpoints return `429 RATE_LIMIT_EXCEEDED` with `X-RateLimit-*` headers |
|
||||
| Audit log retention | 90 days | Events older than 90 days are automatically purged; queries return empty results |
|
||||
|
||||
The monthly token counter resets on the first day of each calendar month. The rate limit window resets every 60 seconds; the reset timestamp is in the `X-RateLimit-Reset` response header.
|
||||
12
docs/developers/guides/README.md
Normal file
12
docs/developers/guides/README.md
Normal file
@@ -0,0 +1,12 @@
|
||||
# Guides
|
||||
|
||||
Step-by-step walkthroughs for each AgentIdP workflow.
|
||||
|
||||
| Guide | What it covers |
|
||||
|-------|----------------|
|
||||
| [Register an Agent](register-an-agent.md) | All registration fields, validation rules, common errors and fixes |
|
||||
| [Manage Credentials](manage-credentials.md) | Generate, list, rotate, and revoke credentials |
|
||||
| [Issue and Revoke Tokens](issue-and-revoke-tokens.md) | OAuth 2.0 Client Credentials flow, JWT structure, introspect, revoke |
|
||||
| [Query Audit Logs](query-audit-logs.md) | Filters, pagination, event structure, 90-day retention |
|
||||
|
||||
All guides assume you have a running local server and a valid Bearer token. See the [Quick Start](../quick-start.md) if you haven't done that yet.
|
||||
203
docs/developers/guides/issue-and-revoke-tokens.md
Normal file
203
docs/developers/guides/issue-and-revoke-tokens.md
Normal file
@@ -0,0 +1,203 @@
|
||||
# Issue and Revoke Tokens
|
||||
|
||||
This guide covers the complete token lifecycle: issuing, using, inspecting, and revoking JWT access tokens.
|
||||
|
||||
---
|
||||
|
||||
## Issue a token
|
||||
|
||||
`POST /api/v1/token`
|
||||
|
||||
This is the OAuth 2.0 Client Credentials grant. Your agent exchanges its `client_id` and `client_secret` for a signed JWT access token.
|
||||
|
||||
> **Important**: This endpoint uses `application/x-www-form-urlencoded` encoding, not JSON.
|
||||
|
||||
```bash
|
||||
curl -s -X POST http://localhost:3000/api/v1/token \
|
||||
-H "Content-Type: application/x-www-form-urlencoded" \
|
||||
-d "grant_type=client_credentials" \
|
||||
-d "client_id=$CLIENT_ID" \
|
||||
-d "client_secret=$CLIENT_SECRET" \
|
||||
-d "scope=agents:read agents:write" | jq .
|
||||
```
|
||||
|
||||
Response (`200 OK`):
|
||||
|
||||
```json
|
||||
{
|
||||
"access_token": "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJhMWIyYzNkNC1lNWY2LTc4OTAtYWJjZC1lZjEyMzQ1Njc4OTAiLCJjbGllbnRfaWQiOiJhMWIyYzNkNC1lNWY2LTc4OTAtYWJjZC1lZjEyMzQ1Njc4OTAiLCJzY29wZSI6ImFnZW50czpyZWFkIGFnZW50czp3cml0ZSIsImp0aSI6InV1aWQtaGVyZSIsImlhdCI6MTc0MzE1MTIwMCwiZXhwIjoxNzQzMTU0ODAwfQ.signature",
|
||||
"token_type": "Bearer",
|
||||
"expires_in": 3600,
|
||||
"scope": "agents:read agents:write"
|
||||
}
|
||||
```
|
||||
|
||||
The token expires in `3600` seconds (1 hour). Request a new one before it expires.
|
||||
|
||||
### Request fields
|
||||
|
||||
| Field | Required | Description |
|
||||
|-------|----------|-------------|
|
||||
| `grant_type` | Yes | Must be `client_credentials` |
|
||||
| `client_id` | Yes | Your agent's `agentId` (UUID) |
|
||||
| `client_secret` | Yes | The secret from credential generation |
|
||||
| `scope` | No | Space-separated list of requested scopes. If omitted, all scopes are granted. |
|
||||
|
||||
### Available scopes
|
||||
|
||||
| Scope | What it allows |
|
||||
|-------|----------------|
|
||||
| `agents:read` | Read agent records |
|
||||
| `agents:write` | Create, update, decommission agents |
|
||||
| `tokens:read` | Introspect tokens |
|
||||
| `audit:read` | Query audit logs |
|
||||
|
||||
Request only the scopes your agent needs.
|
||||
|
||||
---
|
||||
|
||||
## What's inside the JWT
|
||||
|
||||
A JWT has three base64-encoded parts separated by dots: header, payload, and signature. The payload contains your agent's identity claims.
|
||||
|
||||
Decode the payload to inspect it (for development only — never trust an unverified token in production):
|
||||
|
||||
```bash
|
||||
# Extract the middle part (payload) of your token and decode it
|
||||
TOKEN_PAYLOAD=$(echo "$TOKEN" | cut -d. -f2)
|
||||
echo "$TOKEN_PAYLOAD" | base64 --decode 2>/dev/null | jq .
|
||||
```
|
||||
|
||||
Claims in the payload:
|
||||
|
||||
| Claim | Description |
|
||||
|-------|-------------|
|
||||
| `sub` | Subject — your agent's `agentId` |
|
||||
| `client_id` | The `agentId` that authenticated |
|
||||
| `scope` | Scopes granted by this token |
|
||||
| `jti` | JWT ID — unique identifier for this token (used for revocation) |
|
||||
| `iat` | Issued at (Unix timestamp in seconds) |
|
||||
| `exp` | Expires at (Unix timestamp in seconds) |
|
||||
|
||||
---
|
||||
|
||||
## Use the token
|
||||
|
||||
Include the token in the `Authorization` header of every API request:
|
||||
|
||||
```bash
|
||||
curl -s http://localhost:3000/api/v1/agents \
|
||||
-H "Authorization: Bearer $TOKEN" | jq .
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Introspect a token
|
||||
|
||||
`POST /api/v1/token/introspect`
|
||||
|
||||
Check whether a token is currently active (valid, not expired, not revoked). Requires a Bearer token with `tokens:read` scope.
|
||||
|
||||
```bash
|
||||
curl -s -X POST http://localhost:3000/api/v1/token/introspect \
|
||||
-H "Authorization: Bearer $TOKEN" \
|
||||
-H "Content-Type: application/x-www-form-urlencoded" \
|
||||
-d "token=$TOKEN_TO_CHECK" | jq .
|
||||
```
|
||||
|
||||
Response for an active token:
|
||||
|
||||
```json
|
||||
{
|
||||
"active": true,
|
||||
"sub": "a1b2c3d4-e5f6-7890-abcd-ef1234567890",
|
||||
"client_id": "a1b2c3d4-e5f6-7890-abcd-ef1234567890",
|
||||
"scope": "agents:read agents:write",
|
||||
"token_type": "Bearer",
|
||||
"iat": 1743151200,
|
||||
"exp": 1743154800
|
||||
}
|
||||
```
|
||||
|
||||
Response for an inactive (expired or revoked) token:
|
||||
|
||||
```json
|
||||
{
|
||||
"active": false
|
||||
}
|
||||
```
|
||||
|
||||
> The introspect endpoint always returns `200 OK` — even for inactive tokens. You must check the `active` field to determine token validity.
|
||||
|
||||
---
|
||||
|
||||
## Revoke a token
|
||||
|
||||
`POST /api/v1/token/revoke`
|
||||
|
||||
Immediately invalidates a token, preventing it from being used for any subsequent requests. Requires a Bearer token.
|
||||
|
||||
```bash
|
||||
curl -s -X POST http://localhost:3000/api/v1/token/revoke \
|
||||
-H "Authorization: Bearer $TOKEN" \
|
||||
-H "Content-Type: application/x-www-form-urlencoded" \
|
||||
-d "token=$TOKEN_TO_REVOKE" | jq .
|
||||
```
|
||||
|
||||
Response (`200 OK`):
|
||||
|
||||
```json
|
||||
{}
|
||||
```
|
||||
|
||||
**Notes on revocation**:
|
||||
- Revocation is immediate — the token is rejected on the next request
|
||||
- Revoking an already-revoked or expired token is not an error (idempotent per RFC 7009)
|
||||
- An agent can revoke its own tokens; revoking another agent's token requires an admin-scoped token
|
||||
- Revoking a token does not affect the credential that issued it — new tokens can still be obtained using the same credentials
|
||||
|
||||
---
|
||||
|
||||
## Token errors
|
||||
|
||||
### `401 invalid_client` — wrong credentials
|
||||
|
||||
```json
|
||||
{
|
||||
"error": "invalid_client",
|
||||
"error_description": "Client authentication failed. Invalid client_id or client_secret."
|
||||
}
|
||||
```
|
||||
|
||||
Check that `client_id` matches the agent's `agentId` and `client_secret` is the current active secret.
|
||||
|
||||
### `403 unauthorized_client` — agent suspended or monthly limit reached
|
||||
|
||||
```json
|
||||
{
|
||||
"error": "unauthorized_client",
|
||||
"error_description": "Agent is currently suspended and cannot obtain tokens."
|
||||
}
|
||||
```
|
||||
|
||||
Or:
|
||||
|
||||
```json
|
||||
{
|
||||
"error": "unauthorized_client",
|
||||
"error_description": "Free tier monthly token limit of 10,000 requests has been reached."
|
||||
}
|
||||
```
|
||||
|
||||
For suspension: reactivate the agent first. For the monthly limit: the counter resets on the first day of the next calendar month.
|
||||
|
||||
### `400 unsupported_grant_type`
|
||||
|
||||
```json
|
||||
{
|
||||
"error": "unsupported_grant_type",
|
||||
"error_description": "Only 'client_credentials' grant type is supported."
|
||||
}
|
||||
```
|
||||
|
||||
Only `client_credentials` is supported. Do not use `authorization_code`, `password`, or other grant types.
|
||||
167
docs/developers/guides/manage-credentials.md
Normal file
167
docs/developers/guides/manage-credentials.md
Normal file
@@ -0,0 +1,167 @@
|
||||
# Manage Credentials
|
||||
|
||||
A credential is a `client_id` + `client_secret` pair that your agent uses to get access tokens. This guide covers all four credential operations.
|
||||
|
||||
All credential endpoints are under `/api/v1/agents/{agentId}/credentials` and require a Bearer token with `agents:write` scope.
|
||||
|
||||
---
|
||||
|
||||
## Generate credentials
|
||||
|
||||
`POST /api/v1/agents/{agentId}/credentials`
|
||||
|
||||
Creates a new credential for the agent. The `clientSecret` is returned **once only**.
|
||||
|
||||
```bash
|
||||
curl -s -X POST "http://localhost:3000/api/v1/agents/$AGENT_ID/credentials" \
|
||||
-H "Authorization: Bearer $TOKEN" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{}' | jq .
|
||||
```
|
||||
|
||||
To set an expiry date (optional):
|
||||
|
||||
```bash
|
||||
curl -s -X POST "http://localhost:3000/api/v1/agents/$AGENT_ID/credentials" \
|
||||
-H "Authorization: Bearer $TOKEN" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{ "expiresAt": "2027-03-28T00:00:00.000Z" }' | jq .
|
||||
```
|
||||
|
||||
Response (`201 Created`):
|
||||
|
||||
```json
|
||||
{
|
||||
"credentialId": "c9d8e7f6-a5b4-3210-fedc-ba9876543210",
|
||||
"clientId": "a1b2c3d4-e5f6-7890-abcd-ef1234567890",
|
||||
"clientSecret": "sk_live_7f3a2b1c9d8e4f0a6b5c3d2e1f0a9b8c",
|
||||
"status": "active",
|
||||
"createdAt": "2026-03-28T09:00:00.000Z",
|
||||
"expiresAt": "2027-03-28T00:00:00.000Z",
|
||||
"revokedAt": null
|
||||
}
|
||||
```
|
||||
|
||||
> **Save the `clientSecret` immediately.** It is shown once. The server stores a bcrypt hash and cannot recover the plaintext. If you lose it, rotate the credential to get a new one.
|
||||
|
||||
An agent can hold **multiple active credentials** at the same time. This supports zero-downtime rotation: generate a new credential, update all consumers to use it, then revoke the old one.
|
||||
|
||||
**Restrictions**:
|
||||
- The agent must be in `active` status. Suspended and decommissioned agents cannot generate credentials.
|
||||
|
||||
---
|
||||
|
||||
## List credentials
|
||||
|
||||
`GET /api/v1/agents/{agentId}/credentials`
|
||||
|
||||
Returns all credentials for the agent (both active and revoked). The `clientSecret` is **never** returned in list responses.
|
||||
|
||||
```bash
|
||||
curl -s "http://localhost:3000/api/v1/agents/$AGENT_ID/credentials" \
|
||||
-H "Authorization: Bearer $TOKEN" | jq .
|
||||
```
|
||||
|
||||
Response:
|
||||
|
||||
```json
|
||||
{
|
||||
"data": [
|
||||
{
|
||||
"credentialId": "c9d8e7f6-a5b4-3210-fedc-ba9876543210",
|
||||
"clientId": "a1b2c3d4-e5f6-7890-abcd-ef1234567890",
|
||||
"status": "active",
|
||||
"createdAt": "2026-03-28T09:00:00.000Z",
|
||||
"expiresAt": "2027-03-28T00:00:00.000Z",
|
||||
"revokedAt": null
|
||||
}
|
||||
],
|
||||
"total": 1,
|
||||
"page": 1,
|
||||
"limit": 20
|
||||
}
|
||||
```
|
||||
|
||||
### Pagination
|
||||
|
||||
```bash
|
||||
curl -s "http://localhost:3000/api/v1/agents/$AGENT_ID/credentials?page=1&limit=50" \
|
||||
-H "Authorization: Bearer $TOKEN" | jq .
|
||||
```
|
||||
|
||||
### Filter by status
|
||||
|
||||
```bash
|
||||
# Active credentials only
|
||||
curl -s "http://localhost:3000/api/v1/agents/$AGENT_ID/credentials?status=active" \
|
||||
-H "Authorization: Bearer $TOKEN" | jq .
|
||||
|
||||
# Revoked credentials only
|
||||
curl -s "http://localhost:3000/api/v1/agents/$AGENT_ID/credentials?status=revoked" \
|
||||
-H "Authorization: Bearer $TOKEN" | jq .
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Rotate a credential
|
||||
|
||||
`POST /api/v1/agents/{agentId}/credentials/{credentialId}/rotate`
|
||||
|
||||
Rotation immediately invalidates the current `clientSecret` and generates a new one — the `credentialId` stays the same. Use this for periodic secret rotation or emergency rotation if a secret is compromised.
|
||||
|
||||
```bash
|
||||
curl -s -X POST \
|
||||
"http://localhost:3000/api/v1/agents/$AGENT_ID/credentials/$CREDENTIAL_ID/rotate" \
|
||||
-H "Authorization: Bearer $TOKEN" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{}' | jq .
|
||||
```
|
||||
|
||||
Response (`200 OK`):
|
||||
|
||||
```json
|
||||
{
|
||||
"credentialId": "c9d8e7f6-a5b4-3210-fedc-ba9876543210",
|
||||
"clientId": "a1b2c3d4-e5f6-7890-abcd-ef1234567890",
|
||||
"clientSecret": "sk_live_9a8b7c6d5e4f3a2b1c0d9e8f7a6b5c4d",
|
||||
"status": "active",
|
||||
"createdAt": "2026-03-28T09:00:00.000Z",
|
||||
"expiresAt": null,
|
||||
"revokedAt": null
|
||||
}
|
||||
```
|
||||
|
||||
**What changes after rotation**:
|
||||
- The `clientSecret` is a new value — the old secret is immediately invalid
|
||||
- The `credentialId` is the same — no changes needed to references by ID
|
||||
- Any tokens issued using the old secret remain valid until they expire naturally (tokens are not revoked by credential rotation)
|
||||
|
||||
**What cannot be rotated**: A `revoked` credential cannot be rotated. Generate a new credential instead.
|
||||
|
||||
---
|
||||
|
||||
## Revoke a credential
|
||||
|
||||
`DELETE /api/v1/agents/{agentId}/credentials/{credentialId}`
|
||||
|
||||
Permanently revokes a credential. The credential can no longer be used to obtain new tokens.
|
||||
|
||||
```bash
|
||||
curl -s -X DELETE \
|
||||
"http://localhost:3000/api/v1/agents/$AGENT_ID/credentials/$CREDENTIAL_ID" \
|
||||
-H "Authorization: Bearer $TOKEN" \
|
||||
-o /dev/null -w "%{http_code}\n"
|
||||
```
|
||||
|
||||
Successful response: `204 No Content` (empty body).
|
||||
|
||||
**Effects of revocation**:
|
||||
- The credential status is set to `revoked`
|
||||
- The credential cannot be used to call `POST /token`
|
||||
- Any tokens that were issued using this credential remain valid until they expire — to immediately invalidate tokens, revoke them explicitly using `POST /token/revoke`
|
||||
- The credential record is retained for audit purposes
|
||||
- Revocation is **irreversible** — a revoked credential cannot be re-activated
|
||||
|
||||
**Revocation vs decommission**:
|
||||
- Revoking a credential affects that credential only; the agent stays active
|
||||
- Decommissioning an agent (`DELETE /api/v1/agents/{agentId}`) revokes all credentials simultaneously and permanently retires the agent
|
||||
183
docs/developers/guides/query-audit-logs.md
Normal file
183
docs/developers/guides/query-audit-logs.md
Normal file
@@ -0,0 +1,183 @@
|
||||
# Query Audit Logs
|
||||
|
||||
The audit log is an immutable, append-only record of every significant action on the AgentIdP platform. This guide covers how to query it, what filters are available, and how retention works.
|
||||
|
||||
Requires: `Authorization: Bearer <token>` with `audit:read` scope.
|
||||
|
||||
---
|
||||
|
||||
## What gets logged
|
||||
|
||||
Every action below is automatically recorded. You cannot create, modify, or delete audit events — the log is read-only via the API.
|
||||
|
||||
| Action | Triggered by |
|
||||
|--------|-------------|
|
||||
| `agent.created` | Successful `POST /agents` |
|
||||
| `agent.updated` | Successful `PATCH /agents/{agentId}` |
|
||||
| `agent.decommissioned` | Successful `DELETE /agents/{agentId}` |
|
||||
| `agent.suspended` | Status changed to `suspended` |
|
||||
| `agent.reactivated` | Status changed from `suspended` to `active` |
|
||||
| `token.issued` | Successful `POST /token` |
|
||||
| `token.revoked` | Successful `POST /token/revoke` |
|
||||
| `token.introspected` | Successful `POST /token/introspect` |
|
||||
| `credential.generated` | Successful `POST /agents/{agentId}/credentials` |
|
||||
| `credential.rotated` | Successful `POST /agents/{agentId}/credentials/{credentialId}/rotate` |
|
||||
| `credential.revoked` | Successful `DELETE /agents/{agentId}/credentials/{credentialId}` |
|
||||
| `auth.failed` | Failed authentication attempt on `POST /token` |
|
||||
|
||||
---
|
||||
|
||||
## Query the audit log
|
||||
|
||||
`GET /api/v1/audit`
|
||||
|
||||
Returns a paginated list of audit events, most recent first.
|
||||
|
||||
```bash
|
||||
curl -s "http://localhost:3000/api/v1/audit" \
|
||||
-H "Authorization: Bearer $TOKEN" | jq .
|
||||
```
|
||||
|
||||
Response:
|
||||
|
||||
```json
|
||||
{
|
||||
"data": [
|
||||
{
|
||||
"eventId": "f1e2d3c4-b5a6-7890-cdef-123456789012",
|
||||
"agentId": "a1b2c3d4-e5f6-7890-abcd-ef1234567890",
|
||||
"action": "token.issued",
|
||||
"outcome": "success",
|
||||
"ipAddress": "127.0.0.1",
|
||||
"userAgent": "curl/7.88.1",
|
||||
"metadata": {
|
||||
"scope": "agents:read agents:write",
|
||||
"expiresAt": "2026-03-28T10:00:00.000Z"
|
||||
},
|
||||
"timestamp": "2026-03-28T09:00:00.000Z"
|
||||
}
|
||||
],
|
||||
"total": 47,
|
||||
"page": 1,
|
||||
"limit": 50
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Audit event structure
|
||||
|
||||
| Field | Type | Description |
|
||||
|-------|------|-------------|
|
||||
| `eventId` | UUID | Immutable unique ID for this event |
|
||||
| `agentId` | UUID | The agent that triggered the event |
|
||||
| `action` | string | What happened (see table above) |
|
||||
| `outcome` | string | `success` or `failure` |
|
||||
| `ipAddress` | string | Client IP (IPv4 or IPv6) |
|
||||
| `userAgent` | string | HTTP User-Agent from the request |
|
||||
| `metadata` | object | Action-specific details (varies by action) |
|
||||
| `timestamp` | ISO 8601 | When the event occurred |
|
||||
|
||||
### `metadata` by action
|
||||
|
||||
| Action | Metadata fields |
|
||||
|--------|----------------|
|
||||
| `token.issued` | `scope`, `expiresAt` |
|
||||
| `credential.generated` | `credentialId` |
|
||||
| `credential.rotated` | `credentialId` |
|
||||
| `agent.created` | `agentType`, `owner` |
|
||||
| `auth.failed` | `reason`, `clientId` |
|
||||
|
||||
---
|
||||
|
||||
## Filters
|
||||
|
||||
All filter parameters are optional and can be combined (logical AND).
|
||||
|
||||
### Filter by agent
|
||||
|
||||
```bash
|
||||
curl -s "http://localhost:3000/api/v1/audit?agentId=$AGENT_ID" \
|
||||
-H "Authorization: Bearer $TOKEN" | jq .
|
||||
```
|
||||
|
||||
### Filter by action
|
||||
|
||||
```bash
|
||||
curl -s "http://localhost:3000/api/v1/audit?action=token.issued" \
|
||||
-H "Authorization: Bearer $TOKEN" | jq .
|
||||
```
|
||||
|
||||
### Filter by outcome
|
||||
|
||||
```bash
|
||||
# Failed authentication attempts only
|
||||
curl -s "http://localhost:3000/api/v1/audit?outcome=failure" \
|
||||
-H "Authorization: Bearer $TOKEN" | jq .
|
||||
```
|
||||
|
||||
### Filter by date range
|
||||
|
||||
```bash
|
||||
curl -s "http://localhost:3000/api/v1/audit?fromDate=2026-03-01T00:00:00.000Z&toDate=2026-03-28T23:59:59.999Z" \
|
||||
-H "Authorization: Bearer $TOKEN" | jq .
|
||||
```
|
||||
|
||||
### Combine filters
|
||||
|
||||
```bash
|
||||
# All failed token requests for a specific agent today
|
||||
curl -s "http://localhost:3000/api/v1/audit?agentId=$AGENT_ID&action=auth.failed&outcome=failure&fromDate=2026-03-28T00:00:00.000Z" \
|
||||
-H "Authorization: Bearer $TOKEN" | jq .
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Pagination
|
||||
|
||||
Default page size is 50, maximum is 200.
|
||||
|
||||
```bash
|
||||
curl -s "http://localhost:3000/api/v1/audit?page=2&limit=100" \
|
||||
-H "Authorization: Bearer $TOKEN" | jq .
|
||||
```
|
||||
|
||||
Use `total`, `page`, and `limit` from the response to calculate the number of pages:
|
||||
|
||||
```
|
||||
total_pages = ceil(total / limit)
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Get a single event
|
||||
|
||||
`GET /api/v1/audit/{eventId}`
|
||||
|
||||
```bash
|
||||
curl -s "http://localhost:3000/api/v1/audit/$EVENT_ID" \
|
||||
-H "Authorization: Bearer $TOKEN" | jq .
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Retention — 90 days
|
||||
|
||||
On the free tier, audit events are retained for 90 days. Events older than 90 days are automatically purged.
|
||||
|
||||
- Querying for dates outside the 90-day window returns an empty result set — not an error
|
||||
- Requesting a specific `eventId` for a purged event returns `404 Not Found`
|
||||
- The `fromDate` filter cannot be set to a date older than 90 days; doing so returns `400 RETENTION_WINDOW_EXCEEDED`
|
||||
|
||||
To check the earliest available date:
|
||||
|
||||
```json
|
||||
{
|
||||
"code": "RETENTION_WINDOW_EXCEEDED",
|
||||
"message": "Free tier audit log retention is 90 days. Requested date is outside the retention window.",
|
||||
"details": {
|
||||
"retentionDays": 90,
|
||||
"earliestAvailable": "2025-12-28T00:00:00.000Z"
|
||||
}
|
||||
}
|
||||
```
|
||||
172
docs/developers/guides/register-an-agent.md
Normal file
172
docs/developers/guides/register-an-agent.md
Normal file
@@ -0,0 +1,172 @@
|
||||
# Register an Agent
|
||||
|
||||
This guide covers everything about registering a new agent identity, including all fields, validation rules, and how to fix common errors.
|
||||
|
||||
---
|
||||
|
||||
## The registration request
|
||||
|
||||
`POST /api/v1/agents`
|
||||
|
||||
Requires: `Authorization: Bearer <token>` with `agents:write` scope.
|
||||
|
||||
### Request fields
|
||||
|
||||
| Field | Type | Required | Description |
|
||||
|-------|------|----------|-------------|
|
||||
| `email` | string (email) | Yes | Unique identifier for this agent. Must be a valid email format and unique across all registered agents. |
|
||||
| `agentType` | string (enum) | Yes | Functional classification of the agent. See values below. |
|
||||
| `version` | string (semver) | Yes | Semantic version of the agent software (e.g. `1.0.0`, `2.3.1-beta`). |
|
||||
| `capabilities` | string[] | Yes | One or more capability strings in `resource:action` format. Minimum 1. |
|
||||
| `owner` | string | Yes | Team or organisation that owns this agent. 1–128 characters. |
|
||||
| `deploymentEnv` | string (enum) | Yes | Target deployment environment. See values below. |
|
||||
|
||||
### `agentType` values
|
||||
|
||||
| Value | Description |
|
||||
|-------|-------------|
|
||||
| `screener` | Screens or filters content |
|
||||
| `classifier` | Classifies or categorises inputs |
|
||||
| `orchestrator` | Coordinates other agents or workflows |
|
||||
| `extractor` | Extracts structured data |
|
||||
| `summarizer` | Produces summaries |
|
||||
| `router` | Routes requests to other agents |
|
||||
| `monitor` | Monitors systems or outputs |
|
||||
| `custom` | Any type not covered above |
|
||||
|
||||
### `deploymentEnv` values
|
||||
|
||||
| Value | Description |
|
||||
|-------|-------------|
|
||||
| `development` | Local or dev environment |
|
||||
| `staging` | Pre-production testing |
|
||||
| `production` | Live production workloads |
|
||||
|
||||
### `capabilities` format
|
||||
|
||||
Each capability is a string matching `resource:action`. Examples:
|
||||
|
||||
```
|
||||
resume:read
|
||||
email:send
|
||||
candidate:score
|
||||
document:classify
|
||||
data:*
|
||||
```
|
||||
|
||||
The `*` wildcard in the action position means all actions on that resource. Capabilities are informational in Phase 1.
|
||||
|
||||
---
|
||||
|
||||
## Example — register a screener agent
|
||||
|
||||
```bash
|
||||
curl -s -X POST http://localhost:3000/api/v1/agents \
|
||||
-H "Authorization: Bearer $TOKEN" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{
|
||||
"email": "screener-001@talent.ai",
|
||||
"agentType": "screener",
|
||||
"version": "1.0.0",
|
||||
"capabilities": ["resume:read", "email:send", "candidate:score"],
|
||||
"owner": "talent-acquisition-team",
|
||||
"deploymentEnv": "production"
|
||||
}' | jq .
|
||||
```
|
||||
|
||||
Successful response (`201 Created`):
|
||||
|
||||
```json
|
||||
{
|
||||
"agentId": "a1b2c3d4-e5f6-7890-abcd-ef1234567890",
|
||||
"email": "screener-001@talent.ai",
|
||||
"agentType": "screener",
|
||||
"version": "1.0.0",
|
||||
"capabilities": ["resume:read", "email:send", "candidate:score"],
|
||||
"owner": "talent-acquisition-team",
|
||||
"deploymentEnv": "production",
|
||||
"status": "active",
|
||||
"createdAt": "2026-03-28T09:00:00.000Z",
|
||||
"updatedAt": "2026-03-28T09:00:00.000Z"
|
||||
}
|
||||
```
|
||||
|
||||
The `agentId` is assigned by the system — it is immutable and never changes.
|
||||
|
||||
---
|
||||
|
||||
## Immutable fields
|
||||
|
||||
After registration, the following fields **cannot be changed**:
|
||||
|
||||
- `agentId` — system-assigned, permanent
|
||||
- `email` — the agent's stable identity
|
||||
- `createdAt` — registration timestamp
|
||||
|
||||
To update any other field, use `PATCH /api/v1/agents/{agentId}`.
|
||||
|
||||
---
|
||||
|
||||
## Common errors and fixes
|
||||
|
||||
### `400 VALIDATION_ERROR` — invalid email format
|
||||
|
||||
```json
|
||||
{
|
||||
"code": "VALIDATION_ERROR",
|
||||
"message": "Request validation failed.",
|
||||
"details": { "field": "email", "reason": "Must be a valid email address." }
|
||||
}
|
||||
```
|
||||
|
||||
**Fix**: Use a valid email format, e.g. `my-agent@myproject.ai`.
|
||||
|
||||
---
|
||||
|
||||
### `400 VALIDATION_ERROR` — invalid version format
|
||||
|
||||
```json
|
||||
{
|
||||
"code": "VALIDATION_ERROR",
|
||||
"message": "Request validation failed.",
|
||||
"details": { "field": "version", "reason": "Must be a valid semantic version string." }
|
||||
}
|
||||
```
|
||||
|
||||
**Fix**: Use semantic versioning — `1.0.0`, `2.1.3`, `1.0.0-beta.1`. The format is `MAJOR.MINOR.PATCH`.
|
||||
|
||||
---
|
||||
|
||||
### `400 VALIDATION_ERROR` — invalid capability format
|
||||
|
||||
Capabilities must match `resource:action` — lowercase letters, numbers, hyphens, and underscores only.
|
||||
|
||||
**Fix**: Use `resume:read` not `Resume:Read` or `read-resume`.
|
||||
|
||||
---
|
||||
|
||||
### `409 AGENT_ALREADY_EXISTS` — duplicate email
|
||||
|
||||
```json
|
||||
{
|
||||
"code": "AGENT_ALREADY_EXISTS",
|
||||
"message": "An agent with this email address is already registered.",
|
||||
"details": { "email": "screener-001@talent.ai" }
|
||||
}
|
||||
```
|
||||
|
||||
**Fix**: Choose a different email address. Each agent must have a unique email.
|
||||
|
||||
---
|
||||
|
||||
### `403 FREE_TIER_LIMIT_EXCEEDED` — 100 agent limit reached
|
||||
|
||||
```json
|
||||
{
|
||||
"code": "FREE_TIER_LIMIT_EXCEEDED",
|
||||
"message": "Free tier limit of 100 registered agents has been reached.",
|
||||
"details": { "limit": 100, "current": 100 }
|
||||
}
|
||||
```
|
||||
|
||||
**Fix**: Decommission agents you no longer need before registering new ones.
|
||||
247
docs/developers/quick-start.md
Normal file
247
docs/developers/quick-start.md
Normal file
@@ -0,0 +1,247 @@
|
||||
# Quick Start — Register Your First Agent
|
||||
|
||||
This guide gets you from zero to a working agent identity with a valid OAuth 2.0 access token. It takes under 5 minutes.
|
||||
|
||||
## Prerequisites
|
||||
|
||||
You need two tools installed:
|
||||
|
||||
- **Docker** (includes `docker-compose`) — to run PostgreSQL and Redis
|
||||
- **Node.js 18+** (includes `npm`) — to run the server
|
||||
- **curl** — to call the API
|
||||
|
||||
Nothing else. No accounts, no sign-ups.
|
||||
|
||||
---
|
||||
|
||||
## Step 1 — Clone and configure
|
||||
|
||||
```bash
|
||||
git clone https://git.sentryagent.ai/vijay_admin/sentryagent-idp.git
|
||||
cd sentryagent-idp
|
||||
npm install
|
||||
```
|
||||
|
||||
Generate an RSA keypair for signing tokens (required):
|
||||
|
||||
```bash
|
||||
# Generate private key
|
||||
openssl genrsa -out private.pem 2048
|
||||
|
||||
# Extract public key
|
||||
openssl rsa -in private.pem -pubout -out public.pem
|
||||
```
|
||||
|
||||
Create your `.env` file:
|
||||
|
||||
```bash
|
||||
cat > .env << 'EOF'
|
||||
DATABASE_URL=postgresql://sentryagent:sentryagent@localhost:5432/sentryagent_idp
|
||||
REDIS_URL=redis://localhost:6379
|
||||
PORT=3000
|
||||
JWT_PRIVATE_KEY="$(cat private.pem)"
|
||||
JWT_PUBLIC_KEY="$(cat public.pem)"
|
||||
EOF
|
||||
```
|
||||
|
||||
> **Note**: The `.env` file stores your private key. Do not commit it to version control.
|
||||
|
||||
---
|
||||
|
||||
## Step 2 — Start infrastructure
|
||||
|
||||
Start PostgreSQL and Redis using Docker Compose (infrastructure services only):
|
||||
|
||||
```bash
|
||||
docker-compose up -d postgres redis
|
||||
```
|
||||
|
||||
Expected output:
|
||||
|
||||
```
|
||||
[+] Running 2/2
|
||||
✔ Container sentryagent-idp-postgres-1 Healthy
|
||||
✔ Container sentryagent-idp-redis-1 Healthy
|
||||
```
|
||||
|
||||
Services are ready when both show `Healthy`. Run migrations:
|
||||
|
||||
```bash
|
||||
npm run db:migrate
|
||||
```
|
||||
|
||||
Expected output:
|
||||
|
||||
```
|
||||
Running database migrations...
|
||||
✓ Applied: 001_create_agents.sql
|
||||
✓ Applied: 002_create_credentials.sql
|
||||
✓ Applied: 003_create_tokens.sql
|
||||
✓ Applied: 004_create_audit_log.sql
|
||||
|
||||
Migrations complete. 4 migration(s) applied.
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Step 3 — Start the AgentIdP server
|
||||
|
||||
```bash
|
||||
npm run dev
|
||||
```
|
||||
|
||||
Expected output:
|
||||
|
||||
```
|
||||
SentryAgent.ai AgentIdP listening on port 3000
|
||||
Database pool connected
|
||||
Redis client connected
|
||||
```
|
||||
|
||||
The API is now live at `http://localhost:3000/api/v1`.
|
||||
|
||||
---
|
||||
|
||||
## Step 4 — Generate a bootstrap token
|
||||
|
||||
All API endpoints require a Bearer token. For first-time setup, generate a bootstrap token using your RSA private key:
|
||||
|
||||
```bash
|
||||
node -e "
|
||||
const jwt = require('jsonwebtoken');
|
||||
const fs = require('fs');
|
||||
const { v4: uuidv4 } = require('uuid');
|
||||
const key = fs.readFileSync('private.pem', 'utf8');
|
||||
const now = Math.floor(Date.now() / 1000);
|
||||
const token = jwt.sign({
|
||||
sub: 'bootstrap',
|
||||
client_id: 'bootstrap',
|
||||
scope: 'agents:read agents:write tokens:read audit:read',
|
||||
jti: uuidv4(),
|
||||
iat: now,
|
||||
exp: now + 3600
|
||||
}, key, { algorithm: 'RS256' });
|
||||
console.log(token);
|
||||
"
|
||||
```
|
||||
|
||||
Copy the token output and export it:
|
||||
|
||||
```bash
|
||||
export BOOTSTRAP_TOKEN="<paste token here>"
|
||||
```
|
||||
|
||||
> This bootstrap token is a one-time tool for registering your first agent. Once you have an agent with credentials, use `POST /token` for all subsequent authentication.
|
||||
|
||||
---
|
||||
|
||||
## Step 5 — Register an agent
|
||||
|
||||
```bash
|
||||
curl -s -X POST http://localhost:3000/api/v1/agents \
|
||||
-H "Authorization: Bearer $BOOTSTRAP_TOKEN" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{
|
||||
"email": "my-first-agent@myproject.ai",
|
||||
"agentType": "custom",
|
||||
"version": "1.0.0",
|
||||
"capabilities": ["data:read"],
|
||||
"owner": "my-team",
|
||||
"deploymentEnv": "development"
|
||||
}' | jq .
|
||||
```
|
||||
|
||||
Example response (`201 Created`):
|
||||
|
||||
```json
|
||||
{
|
||||
"agentId": "a1b2c3d4-e5f6-7890-abcd-ef1234567890",
|
||||
"email": "my-first-agent@myproject.ai",
|
||||
"agentType": "custom",
|
||||
"version": "1.0.0",
|
||||
"capabilities": ["data:read"],
|
||||
"owner": "my-team",
|
||||
"deploymentEnv": "development",
|
||||
"status": "active",
|
||||
"createdAt": "2026-03-28T09:00:00.000Z",
|
||||
"updatedAt": "2026-03-28T09:00:00.000Z"
|
||||
}
|
||||
```
|
||||
|
||||
Save the `agentId`:
|
||||
|
||||
```bash
|
||||
export AGENT_ID="a1b2c3d4-e5f6-7890-abcd-ef1234567890"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Step 6 — Generate a credential
|
||||
|
||||
```bash
|
||||
curl -s -X POST "http://localhost:3000/api/v1/agents/$AGENT_ID/credentials" \
|
||||
-H "Authorization: Bearer $BOOTSTRAP_TOKEN" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{}' | jq .
|
||||
```
|
||||
|
||||
Example response (`201 Created`):
|
||||
|
||||
```json
|
||||
{
|
||||
"credentialId": "c9d8e7f6-a5b4-3210-fedc-ba9876543210",
|
||||
"clientId": "a1b2c3d4-e5f6-7890-abcd-ef1234567890",
|
||||
"clientSecret": "sk_live_7f3a2b1c9d8e4f0a6b5c3d2e1f0a9b8c",
|
||||
"status": "active",
|
||||
"createdAt": "2026-03-28T09:00:00.000Z",
|
||||
"expiresAt": null,
|
||||
"revokedAt": null
|
||||
}
|
||||
```
|
||||
|
||||
> **Save the `clientSecret` now.** It is shown once and never retrievable again. The server stores only a bcrypt hash.
|
||||
|
||||
```bash
|
||||
export CLIENT_ID="a1b2c3d4-e5f6-7890-abcd-ef1234567890" # same as AGENT_ID
|
||||
export CLIENT_SECRET="sk_live_7f3a2b1c9d8e4f0a6b5c3d2e1f0a9b8c"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Step 7 — Issue an access token
|
||||
|
||||
Use the OAuth 2.0 Client Credentials flow. Note that the `/token` endpoint uses **form-encoded** body, not JSON:
|
||||
|
||||
```bash
|
||||
curl -s -X POST http://localhost:3000/api/v1/token \
|
||||
-H "Content-Type: application/x-www-form-urlencoded" \
|
||||
-d "grant_type=client_credentials" \
|
||||
-d "client_id=$CLIENT_ID" \
|
||||
-d "client_secret=$CLIENT_SECRET" \
|
||||
-d "scope=agents:read agents:write" | jq .
|
||||
```
|
||||
|
||||
Example response (`200 OK`):
|
||||
|
||||
```json
|
||||
{
|
||||
"access_token": "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9...",
|
||||
"token_type": "Bearer",
|
||||
"expires_in": 3600,
|
||||
"scope": "agents:read agents:write"
|
||||
}
|
||||
```
|
||||
|
||||
```bash
|
||||
export TOKEN="eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9..."
|
||||
```
|
||||
|
||||
Your agent now has a valid JWT. Use it in the `Authorization: Bearer <token>` header for all API calls.
|
||||
|
||||
---
|
||||
|
||||
## What's next
|
||||
|
||||
- [Core Concepts](concepts.md) — understand AgentIdP, AGNTCY, and the agent identity model
|
||||
- [Guides](guides/README.md) — step-by-step walkthroughs for credentials, tokens, and audit logs
|
||||
- [API Reference](api-reference.md) — every endpoint documented with curl examples
|
||||
47
docs/devops/README.md
Normal file
47
docs/devops/README.md
Normal file
@@ -0,0 +1,47 @@
|
||||
# SentryAgent.ai AgentIdP — DevOps Documentation
|
||||
|
||||
Operational reference for engineers who deploy, configure, and maintain the AgentIdP infrastructure.
|
||||
|
||||
## System Overview
|
||||
|
||||
SentryAgent.ai AgentIdP is a Node.js REST API backed by PostgreSQL and Redis. It runs as a single stateless application process. All state lives in PostgreSQL (durable) and Redis (ephemeral cache and rate limiting).
|
||||
|
||||
**Stack:**
|
||||
- **Runtime**: Node.js 18+ (TypeScript, compiled to JS)
|
||||
- **Application**: Express 4.18 on port 3000
|
||||
- **Database**: PostgreSQL 14+ (primary data store)
|
||||
- **Cache**: Redis 7+ (token revocation, rate limiting, monthly token counters)
|
||||
|
||||
## Documentation
|
||||
|
||||
| Document | What it covers |
|
||||
|----------|----------------|
|
||||
| [Architecture](architecture.md) | Components, ports, data flow, Redis key patterns |
|
||||
| [Environment Variables](environment-variables.md) | Every env var — required, optional, format, examples |
|
||||
| [Database](database.md) | Schema (4 tables), migrations, how to apply and verify |
|
||||
| [Local Development](local-development.md) | docker-compose setup, startup, health checks |
|
||||
| [Security](security.md) | JWT key generation and rotation, CORS, secret storage |
|
||||
| [Operations](operations.md) | Startup order, graceful shutdown, log interpretation, troubleshooting |
|
||||
|
||||
## Quick Reference — Ports
|
||||
|
||||
| Service | Port |
|
||||
|---------|------|
|
||||
| AgentIdP app | 3000 |
|
||||
| PostgreSQL | 5432 |
|
||||
| Redis | 6379 |
|
||||
|
||||
## Quick Reference — npm Scripts
|
||||
|
||||
| Script | Purpose |
|
||||
|--------|---------|
|
||||
| `npm run dev` | Run from TypeScript source (development) |
|
||||
| `npm run build` | Compile TypeScript to `dist/` |
|
||||
| `npm start` | Run compiled output from `dist/` (production) |
|
||||
| `npm run db:migrate` | Apply pending database migrations |
|
||||
| `npm test` | Run all tests |
|
||||
| `npm run test:unit` | Unit tests only |
|
||||
|
||||
## Developer Documentation
|
||||
|
||||
For API usage (registering agents, getting tokens, calling endpoints) — see [`docs/developers/`](../developers/README.md).
|
||||
133
docs/devops/architecture.md
Normal file
133
docs/devops/architecture.md
Normal file
@@ -0,0 +1,133 @@
|
||||
# Architecture
|
||||
|
||||
## Component Overview
|
||||
|
||||
```
|
||||
┌─────────────────────────────────────┐
|
||||
│ AgentIdP Application │
|
||||
│ Node.js / Express │
|
||||
│ Port 3000 │
|
||||
│ │
|
||||
│ Auth MW → RateLimit MW → Routes │
|
||||
│ ↓ ↓ │
|
||||
│ Controllers → Services → Repos │
|
||||
└──────────────┬──────────────┬────────┘
|
||||
│ │
|
||||
┌──────────────▼──┐ ┌───────▼────────┐
|
||||
│ PostgreSQL 14 │ │ Redis 7 │
|
||||
│ Port 5432 │ │ Port 6379 │
|
||||
│ │ │ │
|
||||
│ agents │ │ Token revoke │
|
||||
│ credentials │ │ Rate limits │
|
||||
│ audit_events │ │ Monthly counts │
|
||||
│ token_revocati- │ │ │
|
||||
│ ons │ │ │
|
||||
└──────────────────┘ └─────────────────┘
|
||||
```
|
||||
|
||||
## Components
|
||||
|
||||
### AgentIdP Application
|
||||
|
||||
A stateless Express HTTP server. Every request is handled independently — no in-process shared state. This means it can be horizontally scaled (multiple instances) as long as all instances share the same PostgreSQL and Redis.
|
||||
|
||||
**Internal layers:**
|
||||
|
||||
| Layer | Responsibility |
|
||||
|-------|---------------|
|
||||
| Routes | Wire HTTP methods and paths to controllers |
|
||||
| Auth middleware | Validate Bearer JWT (RS256 + Redis revocation check) |
|
||||
| Rate limit middleware | Redis sliding-window counter per `client_id` |
|
||||
| Controllers | Parse and validate request, call service, return response |
|
||||
| Services | Business logic — no direct DB access |
|
||||
| Repositories | All SQL queries — no business logic |
|
||||
| Utils | JWT sign/verify, bcrypt, error types, async handler |
|
||||
|
||||
### PostgreSQL 14+
|
||||
|
||||
Primary durable data store. All agent identities, credentials, audit events, and token revocation records live here. See [database.md](database.md) for schema details.
|
||||
|
||||
The application connects via a connection pool (`pg.Pool`) initialised from `DATABASE_URL`. The pool is a singleton shared across all request handlers.
|
||||
|
||||
### Redis 7+
|
||||
|
||||
Ephemeral store for three use cases:
|
||||
|
||||
| Key pattern | Purpose | TTL |
|
||||
|------------|---------|-----|
|
||||
| `revoked:<jti>` | Token revocation list — checked on every authenticated request | Until token's `exp` |
|
||||
| `rate:<client_id>:<window>` | Request count per client per 60-second window | 60 seconds |
|
||||
| `monthly:<client_id>:<year>:<month>` | Token issuance count for free tier limit enforcement | End of month |
|
||||
|
||||
**Redis is supplementary, not the source of truth.** Token revocations are also written to the `token_revocations` PostgreSQL table for durability across Redis restarts. On Redis restart, the revocation list is cold — previously revoked tokens will pass auth until the PostgreSQL-backed warm-up is implemented (Phase 2).
|
||||
|
||||
## Request Data Flow
|
||||
|
||||
```
|
||||
HTTP Request
|
||||
│
|
||||
▼
|
||||
Express Router (matches path + method)
|
||||
│
|
||||
▼
|
||||
Auth Middleware
|
||||
- Extract Bearer token from Authorization header
|
||||
- Verify RS256 signature using JWT_PUBLIC_KEY
|
||||
- Check Redis for revocation (key: revoked:<jti>)
|
||||
- Attach decoded payload to req.user
|
||||
│
|
||||
▼
|
||||
Rate Limit Middleware
|
||||
- Key: rate:<client_id>:<60s-window>
|
||||
- Increment counter in Redis (INCR + EXPIRE)
|
||||
- Set X-RateLimit-* headers
|
||||
- Reject with 429 if count > 100
|
||||
│
|
||||
▼
|
||||
Controller
|
||||
- Validate request body / query params (Joi schemas)
|
||||
- Call service method
|
||||
- Return HTTP response
|
||||
│
|
||||
▼
|
||||
Service
|
||||
- Business logic and orchestration
|
||||
- Calls one or more repositories
|
||||
- Fires audit log writes (async, fire-and-forget)
|
||||
│
|
||||
▼
|
||||
Repository
|
||||
- Executes parameterised SQL queries
|
||||
- Maps DB rows to typed interfaces
|
||||
- Returns typed results to service
|
||||
│
|
||||
▼
|
||||
PostgreSQL / Redis
|
||||
```
|
||||
|
||||
## Service Map
|
||||
|
||||
| Route prefix | Service | Repository |
|
||||
|-------------|---------|-----------|
|
||||
| `/api/v1/agents` | `AgentService` | `AgentRepository` |
|
||||
| `/api/v1/agents/:id/credentials` | `CredentialService` | `CredentialRepository` |
|
||||
| `/api/v1/token` | `OAuth2Service` | `TokenRepository`, `CredentialRepository`, `AgentRepository` |
|
||||
| `/api/v1/audit` | `AuditService` | `AuditRepository` |
|
||||
|
||||
## Ports
|
||||
|
||||
| Service | Internal port | Exposed port (local dev) |
|
||||
|---------|--------------|--------------------------|
|
||||
| AgentIdP app | 3000 | 3000 |
|
||||
| PostgreSQL | 5432 | 5432 |
|
||||
| Redis | 6379 | 6379 |
|
||||
|
||||
## Graceful Shutdown
|
||||
|
||||
The server listens for `SIGTERM` and `SIGINT`. On receipt:
|
||||
|
||||
1. `server.close()` is called — stops accepting new connections
|
||||
2. In-flight requests complete
|
||||
3. `process.exit(0)` is called
|
||||
|
||||
The PostgreSQL pool and Redis client are not explicitly closed in the current shutdown path. This is safe for single-instance deployments; connection cleanup is handled by the OS.
|
||||
219
docs/devops/database.md
Normal file
219
docs/devops/database.md
Normal file
@@ -0,0 +1,219 @@
|
||||
# Database
|
||||
|
||||
AgentIdP uses PostgreSQL 14+ as its primary data store. The schema consists of four tables managed by a custom migration runner.
|
||||
|
||||
---
|
||||
|
||||
## Schema Overview
|
||||
|
||||
```
|
||||
agents
|
||||
└── credentials (FK: client_id → agents.agent_id, CASCADE DELETE)
|
||||
|
||||
audit_events (no FK — append-only, agent_id is informational)
|
||||
|
||||
token_revocations (no FK — independent revocation store)
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Tables
|
||||
|
||||
### `agents`
|
||||
|
||||
The Agent Registry. One row per registered AI agent identity.
|
||||
|
||||
| Column | Type | Nullable | Description |
|
||||
|--------|------|----------|-------------|
|
||||
| `agent_id` | `UUID` | No | Primary key — system-assigned, immutable |
|
||||
| `email` | `VARCHAR(255)` | No | Unique email-format identifier |
|
||||
| `agent_type` | `VARCHAR(32)` | No | Enum: `screener`, `classifier`, `orchestrator`, `extractor`, `summarizer`, `router`, `monitor`, `custom` |
|
||||
| `version` | `VARCHAR(64)` | No | Semantic version string |
|
||||
| `capabilities` | `TEXT[]` | No | Array of `resource:action` strings |
|
||||
| `owner` | `VARCHAR(128)` | No | Owning team or organisation |
|
||||
| `deployment_env` | `VARCHAR(16)` | No | Enum: `development`, `staging`, `production` |
|
||||
| `status` | `VARCHAR(24)` | No | Enum: `active`, `suspended`, `decommissioned`. Default: `active` |
|
||||
| `created_at` | `TIMESTAMPTZ` | No | Registration timestamp. Default: `NOW()` |
|
||||
| `updated_at` | `TIMESTAMPTZ` | No | Last update timestamp. Default: `NOW()` |
|
||||
|
||||
**Indexes:**
|
||||
|
||||
| Index | Column | Purpose |
|
||||
|-------|--------|---------|
|
||||
| `idx_agents_email` | `email` | Unique lookup on registration and conflict check |
|
||||
| `idx_agents_status` | `status` | Filter by lifecycle status |
|
||||
| `idx_agents_owner` | `owner` | Filter by owner |
|
||||
| `idx_agents_agent_type` | `agent_type` | Filter by type |
|
||||
| `idx_agents_created_at` | `created_at DESC` | Default sort for list queries |
|
||||
|
||||
**Constraints:**
|
||||
- `email` is UNIQUE — one registration per email address
|
||||
- `agent_type` and `deployment_env` and `status` have CHECK constraints enforcing the enum values
|
||||
|
||||
---
|
||||
|
||||
### `credentials`
|
||||
|
||||
OAuth 2.0 client credentials. One agent can have multiple credentials.
|
||||
|
||||
| Column | Type | Nullable | Description |
|
||||
|--------|------|----------|-------------|
|
||||
| `credential_id` | `UUID` | No | Primary key — system-assigned |
|
||||
| `client_id` | `UUID` | No | FK → `agents.agent_id` (CASCADE DELETE) |
|
||||
| `secret_hash` | `VARCHAR(255)` | No | bcrypt hash of the client secret. Plaintext is never stored. |
|
||||
| `status` | `VARCHAR(16)` | No | Enum: `active`, `revoked`. Default: `active` |
|
||||
| `created_at` | `TIMESTAMPTZ` | No | Creation timestamp |
|
||||
| `expires_at` | `TIMESTAMPTZ` | Yes | Optional expiry. NULL = no expiry. |
|
||||
| `revoked_at` | `TIMESTAMPTZ` | Yes | Revocation timestamp. NULL = not revoked. |
|
||||
|
||||
**Indexes:**
|
||||
|
||||
| Index | Column | Purpose |
|
||||
|-------|--------|---------|
|
||||
| `idx_credentials_client_id` | `client_id` | List credentials for an agent |
|
||||
| `idx_credentials_status` | `status` | Filter active/revoked |
|
||||
| `idx_credentials_created_at` | `created_at DESC` | Default sort |
|
||||
|
||||
**Cascade behaviour:** Deleting an agent record cascades and deletes all associated credentials. In practice, agents are soft-deleted (status → `decommissioned`) not hard-deleted, so this cascade is a safety net.
|
||||
|
||||
---
|
||||
|
||||
### `audit_events`
|
||||
|
||||
Immutable audit log. Append-only by design — no application-layer UPDATE or DELETE is ever issued against this table.
|
||||
|
||||
| Column | Type | Nullable | Description |
|
||||
|--------|------|----------|-------------|
|
||||
| `event_id` | `UUID` | No | Primary key — system-assigned |
|
||||
| `agent_id` | `UUID` | No | Agent that triggered the event (informational, no FK) |
|
||||
| `action` | `VARCHAR(32)` | No | Enum — see values below |
|
||||
| `outcome` | `VARCHAR(16)` | No | Enum: `success`, `failure` |
|
||||
| `ip_address` | `VARCHAR(64)` | No | Client IP address (IPv4 or IPv6) |
|
||||
| `user_agent` | `TEXT` | No | HTTP User-Agent from the request |
|
||||
| `metadata` | `JSONB` | No | Action-specific data. Default: `{}` |
|
||||
| `timestamp` | `TIMESTAMPTZ` | No | Event timestamp. Default: `NOW()` |
|
||||
|
||||
**`action` enum values:** `agent.created`, `agent.updated`, `agent.decommissioned`, `agent.suspended`, `agent.reactivated`, `token.issued`, `token.revoked`, `token.introspected`, `credential.generated`, `credential.rotated`, `credential.revoked`, `auth.failed`
|
||||
|
||||
**Indexes:**
|
||||
|
||||
| Index | Column | Purpose |
|
||||
|-------|--------|---------|
|
||||
| `idx_audit_events_agent_id` | `agent_id` | Filter events by agent |
|
||||
| `idx_audit_events_action` | `action` | Filter by action type |
|
||||
| `idx_audit_events_outcome` | `outcome` | Filter successes/failures |
|
||||
| `idx_audit_events_timestamp` | `timestamp DESC` | Default sort, date range queries |
|
||||
|
||||
**Why no FK on `agent_id`?** Audit records must be retained even after an agent is decommissioned. A FK would prevent decommission or cascade-delete history. The `agent_id` is stored as an informational reference only.
|
||||
|
||||
**Free tier retention:** The application enforces a 90-day retention window at the query layer. Purging old records is not yet automated — it is a Phase 2 task.
|
||||
|
||||
---
|
||||
|
||||
### `token_revocations`
|
||||
|
||||
Durable record of revoked JWT tokens. Supplements Redis for durability across Redis restarts.
|
||||
|
||||
| Column | Type | Nullable | Description |
|
||||
|--------|------|----------|-------------|
|
||||
| `jti` | `UUID` | No | Primary key — the JWT ID claim from the revoked token |
|
||||
| `expires_at` | `TIMESTAMPTZ` | No | When the token would have expired naturally |
|
||||
| `revoked_at` | `TIMESTAMPTZ` | No | When the token was revoked. Default: `NOW()` |
|
||||
|
||||
**Indexes:**
|
||||
|
||||
| Index | Column | Purpose |
|
||||
|-------|--------|---------|
|
||||
| `idx_token_revocations_expires_at` | `expires_at` | Enables future cleanup of expired revocation records |
|
||||
|
||||
**Dual-store design:** When a token is revoked, the `jti` is written to both:
|
||||
1. Redis key `revoked:<jti>` with TTL set to the token's remaining lifetime — fast O(1) lookup on every authenticated request
|
||||
2. This PostgreSQL table — durable record if Redis is restarted
|
||||
|
||||
**Note:** On Redis restart, the in-memory revocation cache is cold. Tokens revoked before the restart will pass auth until Phase 2 implements a warm-up that loads active revocations from PostgreSQL into Redis on startup.
|
||||
|
||||
---
|
||||
|
||||
## Migration Runner
|
||||
|
||||
Migrations are managed by `scripts/migrate.ts`. It reads `.sql` files from `src/db/migrations/` in alphabetical order, tracks applied migrations in a `schema_migrations` table, and executes only unapplied migrations — each in its own transaction.
|
||||
|
||||
### `schema_migrations` table
|
||||
|
||||
Created automatically on first run if it does not exist.
|
||||
|
||||
| Column | Type | Description |
|
||||
|--------|------|-------------|
|
||||
| `name` | `VARCHAR(255)` | Migration filename (primary key) |
|
||||
| `applied_at` | `TIMESTAMPTZ` | When the migration was applied |
|
||||
|
||||
### Running migrations
|
||||
|
||||
```bash
|
||||
# Set DATABASE_URL in environment or .env first
|
||||
npm run db:migrate
|
||||
```
|
||||
|
||||
Expected output (first run):
|
||||
|
||||
```
|
||||
Running database migrations...
|
||||
✓ Applied: 001_create_agents.sql
|
||||
✓ Applied: 002_create_credentials.sql
|
||||
✓ Applied: 003_create_audit_events.sql
|
||||
✓ Applied: 004_create_tokens.sql
|
||||
|
||||
Migrations complete. 4 migration(s) applied.
|
||||
```
|
||||
|
||||
Expected output (already applied):
|
||||
|
||||
```
|
||||
Running database migrations...
|
||||
- Skipped (already applied): 001_create_agents.sql
|
||||
- Skipped (already applied): 002_create_credentials.sql
|
||||
- Skipped (already applied): 003_create_audit_events.sql
|
||||
- Skipped (already applied): 004_create_tokens.sql
|
||||
|
||||
Migrations complete. 0 migration(s) applied.
|
||||
```
|
||||
|
||||
### Verifying applied migrations
|
||||
|
||||
```bash
|
||||
psql "$DATABASE_URL" -c "SELECT name, applied_at FROM schema_migrations ORDER BY name;"
|
||||
```
|
||||
|
||||
Expected output:
|
||||
|
||||
```
|
||||
name | applied_at
|
||||
-----------------------------------+-------------------------------
|
||||
001_create_agents.sql | 2026-03-28 09:00:00.000000+00
|
||||
002_create_credentials.sql | 2026-03-28 09:00:00.000000+00
|
||||
003_create_audit_events.sql | 2026-03-28 09:00:00.000000+00
|
||||
004_create_tokens.sql | 2026-03-28 09:00:00.000000+00
|
||||
(4 rows)
|
||||
```
|
||||
|
||||
### Adding a new migration
|
||||
|
||||
1. Create a new `.sql` file in `src/db/migrations/` with the next numeric prefix (e.g. `005_add_column.sql`)
|
||||
2. Write idempotent SQL using `IF NOT EXISTS` / `IF EXISTS` guards where possible
|
||||
3. Run `npm run db:migrate`
|
||||
|
||||
Migrations are run in alphabetical filename order. The prefix ensures correct ordering.
|
||||
|
||||
### Rollback
|
||||
|
||||
There is no automated rollback. To undo a migration:
|
||||
1. Write and apply a compensating migration (e.g. `005_rollback_add_column.sql`)
|
||||
2. Or connect directly to PostgreSQL and run the reverse SQL manually
|
||||
|
||||
---
|
||||
|
||||
## Connection Pool
|
||||
|
||||
The application uses `pg.Pool` with default settings (max 10 connections). The pool is a singleton — one pool per process instance.
|
||||
|
||||
To override pool size, modify `src/db/pool.ts`. In production, ensure `DATABASE_URL` includes connection pool parameters if using PgBouncer or a managed connection pooler.
|
||||
158
docs/devops/environment-variables.md
Normal file
158
docs/devops/environment-variables.md
Normal file
@@ -0,0 +1,158 @@
|
||||
# Environment Variables
|
||||
|
||||
Complete reference for all environment variables consumed by AgentIdP.
|
||||
|
||||
Variables are loaded from a `.env` file at startup via `dotenv`. In production, inject them directly into the process environment — do not commit `.env` to version control.
|
||||
|
||||
---
|
||||
|
||||
## Required Variables
|
||||
|
||||
These variables must be set. The server will throw and exit immediately if any are missing.
|
||||
|
||||
### `DATABASE_URL`
|
||||
|
||||
PostgreSQL connection string.
|
||||
|
||||
| | |
|
||||
|-|-|
|
||||
| **Required** | Yes |
|
||||
| **Format** | `postgresql://<user>:<password>@<host>:<port>/<database>` |
|
||||
| **Example** | `postgresql://sentryagent:sentryagent@localhost:5432/sentryagent_idp` |
|
||||
|
||||
The application uses `pg.Pool` with this connection string. Connection pool size uses the `pg` default (10 connections).
|
||||
|
||||
---
|
||||
|
||||
### `REDIS_URL`
|
||||
|
||||
Redis connection URL.
|
||||
|
||||
| | |
|
||||
|-|-|
|
||||
| **Required** | Yes |
|
||||
| **Format** | `redis://<host>:<port>` or `redis://<user>:<password>@<host>:<port>` |
|
||||
| **Example** | `redis://localhost:6379` |
|
||||
|
||||
Used for token revocation, rate limiting, and monthly token counters.
|
||||
|
||||
---
|
||||
|
||||
### `JWT_PRIVATE_KEY`
|
||||
|
||||
PEM-encoded RSA-2048 private key for signing JWT access tokens (RS256).
|
||||
|
||||
| | |
|
||||
|-|-|
|
||||
| **Required** | Yes |
|
||||
| **Format** | PEM string, including `-----BEGIN RSA PRIVATE KEY-----` header and footer |
|
||||
| **Example** | See [Security guide](security.md) for key generation |
|
||||
|
||||
In a `.env` file, use double quotes and encode newlines as `\n`:
|
||||
|
||||
```
|
||||
JWT_PRIVATE_KEY="-----BEGIN RSA PRIVATE KEY-----\nMIIEow...\n-----END RSA PRIVATE KEY-----"
|
||||
```
|
||||
|
||||
Alternatively, read from a file at startup (see [Security guide](security.md)).
|
||||
|
||||
---
|
||||
|
||||
### `JWT_PUBLIC_KEY`
|
||||
|
||||
PEM-encoded RSA-2048 public key for verifying JWT access tokens.
|
||||
|
||||
| | |
|
||||
|-|-|
|
||||
| **Required** | Yes |
|
||||
| **Format** | PEM string, including `-----BEGIN PUBLIC KEY-----` header and footer |
|
||||
| **Example** | Derived from `JWT_PRIVATE_KEY` — see [Security guide](security.md) |
|
||||
|
||||
Every authenticated request verifies the JWT signature using this key. If this key does not match the private key used to sign tokens, all authentication will fail.
|
||||
|
||||
---
|
||||
|
||||
## Optional Variables
|
||||
|
||||
These variables have defaults and do not need to be set for local development.
|
||||
|
||||
### `PORT`
|
||||
|
||||
HTTP port the Express server listens on.
|
||||
|
||||
| | |
|
||||
|-|-|
|
||||
| **Required** | No |
|
||||
| **Default** | `3000` |
|
||||
| **Format** | Integer |
|
||||
| **Example** | `PORT=8080` |
|
||||
|
||||
---
|
||||
|
||||
### `NODE_ENV`
|
||||
|
||||
Node.js environment flag.
|
||||
|
||||
| | |
|
||||
|-|-|
|
||||
| **Required** | No |
|
||||
| **Default** | `undefined` (treated as development) |
|
||||
| **Values** | `development`, `test`, `production` |
|
||||
| **Example** | `NODE_ENV=production` |
|
||||
|
||||
Effect: When `NODE_ENV=test`, HTTP request logging (Morgan) is disabled.
|
||||
|
||||
---
|
||||
|
||||
### `CORS_ORIGIN`
|
||||
|
||||
Allowed origin(s) for Cross-Origin Resource Sharing.
|
||||
|
||||
| | |
|
||||
|-|-|
|
||||
| **Required** | No |
|
||||
| **Default** | `*` (all origins) |
|
||||
| **Format** | URL string or `*` |
|
||||
| **Example** | `CORS_ORIGIN=https://app.mycompany.ai` |
|
||||
|
||||
In production, set this to the specific origin(s) that should be permitted to call the API. The default `*` is acceptable for a public API but restricts cookie-based auth flows (not applicable here — Bearer tokens only).
|
||||
|
||||
---
|
||||
|
||||
## Complete `.env` Example
|
||||
|
||||
```
|
||||
# Database
|
||||
DATABASE_URL=postgresql://sentryagent:sentryagent@localhost:5432/sentryagent_idp
|
||||
|
||||
# Redis
|
||||
REDIS_URL=redis://localhost:6379
|
||||
|
||||
# Application
|
||||
PORT=3000
|
||||
NODE_ENV=development
|
||||
CORS_ORIGIN=*
|
||||
|
||||
# JWT Keys (generate with openssl — see docs/devops/security.md)
|
||||
JWT_PRIVATE_KEY="-----BEGIN RSA PRIVATE KEY-----
|
||||
MIIEowIBAAKCAQEA...
|
||||
-----END RSA PRIVATE KEY-----"
|
||||
|
||||
JWT_PUBLIC_KEY="-----BEGIN PUBLIC KEY-----
|
||||
MIIBIjANBgkq...
|
||||
-----END PUBLIC KEY-----"
|
||||
```
|
||||
|
||||
> Do not commit `.env` to version control. Add it to `.gitignore`.
|
||||
|
||||
---
|
||||
|
||||
## Variable Validation at Startup
|
||||
|
||||
The application validates required variables at startup in this order:
|
||||
|
||||
1. `JWT_PRIVATE_KEY` and `JWT_PUBLIC_KEY` — checked in `createApp()` before the server starts
|
||||
2. `DATABASE_URL` — checked when `getPool()` is first called (during `createApp()`)
|
||||
3. `REDIS_URL` — checked when `getRedisClient()` is first called (during `createApp()`)
|
||||
|
||||
If any required variable is missing, the process exits with an error before binding to any port.
|
||||
228
docs/devops/local-development.md
Normal file
228
docs/devops/local-development.md
Normal file
@@ -0,0 +1,228 @@
|
||||
# Local Development
|
||||
|
||||
Complete setup guide for running AgentIdP locally.
|
||||
|
||||
## Prerequisites
|
||||
|
||||
| Tool | Minimum version | Purpose |
|
||||
|------|----------------|---------|
|
||||
| Docker + Docker Compose | 24+ | Run PostgreSQL and Redis |
|
||||
| Node.js | 18.0.0 | Run the application and migrations |
|
||||
| npm | 9+ | Package management and scripts |
|
||||
|
||||
Verify versions:
|
||||
|
||||
```bash
|
||||
docker --version
|
||||
docker-compose --version
|
||||
node --version
|
||||
npm --version
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Step 1 — Clone and install dependencies
|
||||
|
||||
```bash
|
||||
git clone https://git.sentryagent.ai/vijay_admin/sentryagent-idp.git
|
||||
cd sentryagent-idp
|
||||
npm install
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Step 2 — Generate JWT keys
|
||||
|
||||
AgentIdP signs tokens with RS256. You need an RSA-2048 keypair.
|
||||
|
||||
```bash
|
||||
openssl genrsa -out private.pem 2048
|
||||
openssl rsa -in private.pem -pubout -out public.pem
|
||||
```
|
||||
|
||||
Keep these files in the project root. They are used only locally and should not be committed.
|
||||
|
||||
---
|
||||
|
||||
## Step 3 — Configure environment
|
||||
|
||||
Create a `.env` file in the project root:
|
||||
|
||||
```bash
|
||||
cat > .env << 'ENVEOF'
|
||||
DATABASE_URL=postgresql://sentryagent:sentryagent@localhost:5432/sentryagent_idp
|
||||
REDIS_URL=redis://localhost:6379
|
||||
PORT=3000
|
||||
NODE_ENV=development
|
||||
CORS_ORIGIN=*
|
||||
ENVEOF
|
||||
```
|
||||
|
||||
Append the JWT keys to `.env`:
|
||||
|
||||
```bash
|
||||
echo "JWT_PRIVATE_KEY=\"$(awk 'NF {sub(/\r/, ""); printf "%s\\n",$0;}' private.pem)\"" >> .env
|
||||
echo "JWT_PUBLIC_KEY=\"$(awk 'NF {sub(/\r/, ""); printf "%s\\n",$0;}' public.pem)\"" >> .env
|
||||
```
|
||||
|
||||
Verify the file has all required variables:
|
||||
|
||||
```bash
|
||||
grep -E "^(DATABASE_URL|REDIS_URL|JWT_PRIVATE_KEY|JWT_PUBLIC_KEY)" .env
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Step 4 — Start infrastructure services
|
||||
|
||||
The `docker-compose.yml` defines three services: `postgres`, `redis`, and `app`. For local development, start only the infrastructure services — the application runs directly via Node.js.
|
||||
|
||||
```bash
|
||||
docker-compose up -d postgres redis
|
||||
```
|
||||
|
||||
Expected output:
|
||||
|
||||
```
|
||||
[+] Running 2/2
|
||||
✔ Container sentryagent-idp-postgres-1 Healthy
|
||||
✔ Container sentryagent-idp-redis-1 Healthy
|
||||
```
|
||||
|
||||
Both services must show `Healthy` before proceeding. If they show `Starting`, wait a few seconds and run `docker-compose ps` to recheck.
|
||||
|
||||
### Service ports
|
||||
|
||||
| Service | Port | Health check |
|
||||
|---------|------|-------------|
|
||||
| PostgreSQL | 5432 | `pg_isready -U sentryagent -d sentryagent_idp` |
|
||||
| Redis | 6379 | `redis-cli ping` → `PONG` |
|
||||
|
||||
Verify manually:
|
||||
|
||||
```bash
|
||||
docker-compose exec postgres pg_isready -U sentryagent -d sentryagent_idp
|
||||
docker-compose exec redis redis-cli ping
|
||||
```
|
||||
|
||||
### Docker volumes
|
||||
|
||||
Data is persisted in named Docker volumes:
|
||||
|
||||
| Volume | Service | Contents |
|
||||
|--------|---------|---------|
|
||||
| `sentryagent-idp_postgres_data` | PostgreSQL | All database data |
|
||||
| `sentryagent-idp_redis_data` | Redis | Redis persistence (if enabled) |
|
||||
|
||||
---
|
||||
|
||||
## Step 5 — Run database migrations
|
||||
|
||||
```bash
|
||||
npm run db:migrate
|
||||
```
|
||||
|
||||
Expected output:
|
||||
|
||||
```
|
||||
Running database migrations...
|
||||
✓ Applied: 001_create_agents.sql
|
||||
✓ Applied: 002_create_credentials.sql
|
||||
✓ Applied: 003_create_audit_events.sql
|
||||
✓ Applied: 004_create_tokens.sql
|
||||
|
||||
Migrations complete. 4 migration(s) applied.
|
||||
```
|
||||
|
||||
See [database.md](database.md) for full migration documentation.
|
||||
|
||||
---
|
||||
|
||||
## Step 6 — Start the application
|
||||
|
||||
### Development mode (TypeScript source, no compile step)
|
||||
|
||||
```bash
|
||||
npm run dev
|
||||
```
|
||||
|
||||
Expected startup output:
|
||||
|
||||
```
|
||||
SentryAgent.ai AgentIdP listening on port 3000
|
||||
```
|
||||
|
||||
The application connects to PostgreSQL and Redis on first request (lazy initialisation). If either service is unreachable, the first request will fail with a connection error — not startup.
|
||||
|
||||
### Production mode (compiled JavaScript)
|
||||
|
||||
```bash
|
||||
npm run build
|
||||
npm start
|
||||
```
|
||||
|
||||
The compiled output is written to `dist/`. `npm start` runs `node dist/server.js`.
|
||||
|
||||
---
|
||||
|
||||
## Full Docker Compose Stack
|
||||
|
||||
> **Note:** The `app` service in `docker-compose.yml` requires a `Dockerfile` which has not been written yet. This is a **Phase 1 P1 pending item**. The commands below will work once the Dockerfile exists.
|
||||
|
||||
When the Dockerfile is available, the entire stack (infrastructure + application) can be started with:
|
||||
|
||||
```bash
|
||||
docker-compose up -d
|
||||
```
|
||||
|
||||
The `app` service depends on `postgres` and `redis` with health check conditions, so it will not start until both services are healthy.
|
||||
|
||||
Environment variables for the container are loaded from `.env` via the `env_file` directive in `docker-compose.yml`.
|
||||
|
||||
---
|
||||
|
||||
## Stopping Services
|
||||
|
||||
Stop infrastructure only (preserves volumes):
|
||||
|
||||
```bash
|
||||
docker-compose stop postgres redis
|
||||
```
|
||||
|
||||
Stop and remove containers (preserves volumes):
|
||||
|
||||
```bash
|
||||
docker-compose down
|
||||
```
|
||||
|
||||
Stop and remove containers AND volumes (destroys all data):
|
||||
|
||||
```bash
|
||||
docker-compose down -v
|
||||
```
|
||||
|
||||
> Use `-v` only when you want a clean slate. This deletes all PostgreSQL data and Redis data permanently.
|
||||
|
||||
---
|
||||
|
||||
## Running Tests
|
||||
|
||||
Unit tests (no infrastructure required):
|
||||
|
||||
```bash
|
||||
npm run test:unit
|
||||
```
|
||||
|
||||
Integration tests (require running PostgreSQL and Redis):
|
||||
|
||||
```bash
|
||||
npm run test:integration
|
||||
```
|
||||
|
||||
All tests:
|
||||
|
||||
```bash
|
||||
npm test
|
||||
```
|
||||
|
||||
Integration tests connect to the same `DATABASE_URL` and `REDIS_URL` from `.env`. Ensure infrastructure is running before executing integration tests.
|
||||
249
docs/devops/operations.md
Normal file
249
docs/devops/operations.md
Normal file
@@ -0,0 +1,249 @@
|
||||
# Operations
|
||||
|
||||
Startup, shutdown, log interpretation, and troubleshooting for AgentIdP.
|
||||
|
||||
---
|
||||
|
||||
## Startup Order
|
||||
|
||||
Always start services in this order. Starting the application before PostgreSQL or Redis is ready will cause connection errors on first request.
|
||||
|
||||
```
|
||||
1. PostgreSQL (must be healthy)
|
||||
2. Redis (must be healthy)
|
||||
3. Migrations (must complete successfully)
|
||||
4. Application (start last)
|
||||
```
|
||||
|
||||
### Startup checklist
|
||||
|
||||
```bash
|
||||
# 1. Start PostgreSQL and Redis
|
||||
docker-compose up -d postgres redis
|
||||
|
||||
# 2. Wait for healthy status
|
||||
docker-compose ps
|
||||
# Both postgres and redis must show "healthy" before proceeding
|
||||
|
||||
# 3. Run migrations
|
||||
npm run db:migrate
|
||||
# Must complete with 0 errors before starting the app
|
||||
|
||||
# 4. Start the application
|
||||
npm run dev # development
|
||||
# or
|
||||
npm start # production (requires prior npm run build)
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Graceful Shutdown
|
||||
|
||||
The application handles `SIGTERM` and `SIGINT` gracefully:
|
||||
|
||||
1. Stops accepting new connections
|
||||
2. Waits for in-flight requests to complete
|
||||
3. Exits with code `0`
|
||||
|
||||
### Sending SIGTERM
|
||||
|
||||
```bash
|
||||
# Find the PID
|
||||
ps aux | grep "node.*server"
|
||||
|
||||
# Send SIGTERM
|
||||
kill -SIGTERM <pid>
|
||||
```
|
||||
|
||||
Expected log output:
|
||||
|
||||
```
|
||||
Shutting down gracefully...
|
||||
```
|
||||
|
||||
The process exits cleanly. No requests are dropped if they were already in-flight.
|
||||
|
||||
### Docker stop
|
||||
|
||||
`docker stop` sends `SIGTERM` by default with a 10-second timeout before `SIGKILL`. This is sufficient for graceful shutdown.
|
||||
|
||||
```bash
|
||||
docker stop sentryagent-idp-app-1
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Log Reference
|
||||
|
||||
AgentIdP logs to stdout. In development (`NODE_ENV=development`), Morgan HTTP request logs are included. In test (`NODE_ENV=test`), Morgan is suppressed.
|
||||
|
||||
### Startup logs
|
||||
|
||||
| Log line | Meaning |
|
||||
|----------|---------|
|
||||
| `SentryAgent.ai AgentIdP listening on port 3000` | Server bound successfully — ready to accept requests |
|
||||
| `Shutting down gracefully...` | SIGTERM/SIGINT received — draining connections |
|
||||
|
||||
### Error logs
|
||||
|
||||
| Log line | Meaning |
|
||||
|----------|---------|
|
||||
| `Failed to start server: Error: DATABASE_URL environment variable is required` | `DATABASE_URL` is not set in the environment |
|
||||
| `Failed to start server: Error: REDIS_URL environment variable is required` | `REDIS_URL` is not set |
|
||||
| `Failed to start server: Error: JWT_PRIVATE_KEY and JWT_PUBLIC_KEY environment variables are required` | One or both JWT keys are missing |
|
||||
| `Unexpected pg pool error <err>` | PostgreSQL connection dropped after startup — check DB availability |
|
||||
| `Redis client error <err>` | Redis connection error after startup — check Redis availability |
|
||||
|
||||
### Morgan HTTP request format (development)
|
||||
|
||||
```
|
||||
::1 - - [28/Mar/2026:09:01:00 +0000] "POST /api/v1/token HTTP/1.1" 200 312 "-" "curl/7.88.1"
|
||||
```
|
||||
|
||||
Format: `<ip> - - [<timestamp>] "<method> <path> <protocol>" <status> <bytes> "<referrer>" "<user-agent>"`
|
||||
|
||||
---
|
||||
|
||||
## Redis Key Patterns
|
||||
|
||||
Three key patterns are used in Redis. Useful for debugging and manual inspection.
|
||||
|
||||
```bash
|
||||
# Connect to Redis CLI
|
||||
docker-compose exec redis redis-cli
|
||||
```
|
||||
|
||||
| Key pattern | Example | Purpose | TTL |
|
||||
|------------|---------|---------|-----|
|
||||
| `revoked:<jti>` | `revoked:f1e2d3c4-b5a6-...` | Revoked token JTI | Remaining token lifetime |
|
||||
| `rate:<client_id>:<window>` | `rate:a1b2c3...:29086156` | Request count per minute window | 60 seconds |
|
||||
| `monthly:<client_id>:<year>:<month>` | `monthly:a1b2c3...:2026:3` | Token issuance count for free tier | End of month |
|
||||
|
||||
Inspect keys:
|
||||
|
||||
```bash
|
||||
# List all revoked tokens
|
||||
redis-cli KEYS "revoked:*"
|
||||
|
||||
# Check rate limit counter for a specific client
|
||||
redis-cli GET "rate:<client_id>:<window_key>"
|
||||
|
||||
# Check monthly token count for a specific client
|
||||
redis-cli GET "monthly:<client_id>:2026:3"
|
||||
```
|
||||
|
||||
Where `<window_key>` is `floor(unix_ms / 60000)`. For the current window:
|
||||
|
||||
```bash
|
||||
node -e "console.log(Math.floor(Date.now() / 60000))"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
### Application fails to start — missing environment variable
|
||||
|
||||
**Symptom:**
|
||||
```
|
||||
Failed to start server: Error: DATABASE_URL environment variable is required
|
||||
```
|
||||
|
||||
**Fix:** Ensure your `.env` file exists in the project root and contains all required variables. Verify:
|
||||
```bash
|
||||
grep -E "^(DATABASE_URL|REDIS_URL|JWT_PRIVATE_KEY|JWT_PUBLIC_KEY)=" .env
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Application fails to start — JWT key error
|
||||
|
||||
**Symptom:**
|
||||
```
|
||||
Failed to start server: Error: JWT_PRIVATE_KEY and JWT_PUBLIC_KEY environment variables are required
|
||||
```
|
||||
|
||||
**Fix:** Generate RSA keys and add them to `.env`. See [security.md](security.md).
|
||||
|
||||
---
|
||||
|
||||
### PostgreSQL connection refused on first request
|
||||
|
||||
**Symptom:**
|
||||
```
|
||||
Error: connect ECONNREFUSED 127.0.0.1:5432
|
||||
```
|
||||
|
||||
**Causes and fixes:**
|
||||
|
||||
| Cause | Fix |
|
||||
|-------|-----|
|
||||
| PostgreSQL container not started | Run `docker-compose up -d postgres` |
|
||||
| PostgreSQL container not yet healthy | Wait and run `docker-compose ps` — wait for `healthy` |
|
||||
| Wrong `DATABASE_URL` host/port | Check `DATABASE_URL` matches the PostgreSQL port (5432) |
|
||||
| PostgreSQL container exited | Run `docker-compose logs postgres` to see why it exited |
|
||||
|
||||
---
|
||||
|
||||
### Redis connection error on first request
|
||||
|
||||
**Symptom:**
|
||||
```
|
||||
Redis client error Error: connect ECONNREFUSED 127.0.0.1:6379
|
||||
```
|
||||
|
||||
**Causes and fixes:**
|
||||
|
||||
| Cause | Fix |
|
||||
|-------|-----|
|
||||
| Redis container not started | Run `docker-compose up -d redis` |
|
||||
| Redis container not yet healthy | Run `docker-compose ps` — wait for `healthy` |
|
||||
| Wrong `REDIS_URL` | Check `REDIS_URL` matches the Redis port (6379) |
|
||||
|
||||
---
|
||||
|
||||
### Migration fails
|
||||
|
||||
**Symptom:**
|
||||
```
|
||||
Migration failed: Error: connect ECONNREFUSED 127.0.0.1:5432
|
||||
```
|
||||
|
||||
**Fix:** PostgreSQL is not running or not reachable. Start it and verify health before running migrations.
|
||||
|
||||
**Symptom:**
|
||||
```
|
||||
Migration failed: Error: relation "agents" already exists
|
||||
```
|
||||
|
||||
**Fix:** The migration has already been applied partially. Check `schema_migrations`:
|
||||
```bash
|
||||
psql "$DATABASE_URL" -c "SELECT name FROM schema_migrations ORDER BY name;"
|
||||
```
|
||||
If a migration is listed there but the table is inconsistent, manually inspect and repair the database state before re-running.
|
||||
|
||||
---
|
||||
|
||||
### All requests return 401 after key rotation
|
||||
|
||||
**Symptom:** Every API call returns `401 UNAUTHORIZED` with `Token signature is invalid.`
|
||||
|
||||
**Cause:** JWT keys were rotated. All previously issued tokens were signed with the old private key and are now invalid.
|
||||
|
||||
**Fix:** Clients must re-authenticate using `POST /token` with their `client_id` and `client_secret` to obtain a new token signed with the new key. This is expected behaviour after key rotation.
|
||||
|
||||
---
|
||||
|
||||
### Rate limit hit unexpectedly — 429 responses
|
||||
|
||||
**Symptom:** API returns `429 RATE_LIMIT_EXCEEDED` with `X-RateLimit-Reset` header.
|
||||
|
||||
**Check current rate limit state:**
|
||||
```bash
|
||||
# Find the current window key
|
||||
WINDOW=$(node -e "console.log(Math.floor(Date.now() / 60000))")
|
||||
# Check count for a specific client
|
||||
docker-compose exec redis redis-cli GET "rate:<client_id>:$WINDOW"
|
||||
```
|
||||
|
||||
**Fix:** Wait until `X-RateLimit-Reset` (Unix timestamp in the response header) before retrying. The window resets every 60 seconds.
|
||||
154
docs/devops/security.md
Normal file
154
docs/devops/security.md
Normal file
@@ -0,0 +1,154 @@
|
||||
# Security
|
||||
|
||||
Security configuration for AgentIdP — JWT key management, CORS, and secret storage.
|
||||
|
||||
---
|
||||
|
||||
## JWT Key Management
|
||||
|
||||
AgentIdP uses RS256 (RSA + SHA-256) to sign and verify JWT access tokens. This asymmetric scheme means:
|
||||
|
||||
- The **private key** signs tokens — must be kept secret, known only to the server
|
||||
- The **public key** verifies tokens — can be shared with any system that needs to validate tokens
|
||||
|
||||
### Generate a keypair
|
||||
|
||||
Generate a 2048-bit RSA keypair:
|
||||
|
||||
```bash
|
||||
# Generate private key
|
||||
openssl genrsa -out private.pem 2048
|
||||
|
||||
# Extract public key
|
||||
openssl rsa -in private.pem -pubout -out public.pem
|
||||
```
|
||||
|
||||
Verify the files:
|
||||
|
||||
```bash
|
||||
# Confirm private key is valid RSA
|
||||
openssl rsa -in private.pem -check -noout
|
||||
# Expected: RSA key ok
|
||||
|
||||
# Confirm public key is readable
|
||||
openssl rsa -in public.pem -pubin -noout -text | head -5
|
||||
```
|
||||
|
||||
### Load keys into environment
|
||||
|
||||
**Option 1 — Inline in `.env` (development only)**
|
||||
|
||||
Encode newlines as `\n` and wrap in double quotes:
|
||||
|
||||
```bash
|
||||
echo "JWT_PRIVATE_KEY=\"$(awk 'NF {sub(/\r/, ""); printf "%s\\n",$0;}' private.pem)\"" >> .env
|
||||
echo "JWT_PUBLIC_KEY=\"$(awk 'NF {sub(/\r/, ""); printf "%s\\n",$0;}' public.pem)\"" >> .env
|
||||
```
|
||||
|
||||
**Option 2 — Load from file at runtime (recommended for production)**
|
||||
|
||||
In the startup script, read the key files and export as environment variables before running the server:
|
||||
|
||||
```bash
|
||||
export JWT_PRIVATE_KEY="$(cat /run/secrets/jwt-private.pem)"
|
||||
export JWT_PUBLIC_KEY="$(cat /run/secrets/jwt-public.pem)"
|
||||
npm start
|
||||
```
|
||||
|
||||
With Docker secrets or a secrets manager (Vault, AWS Secrets Manager), mount the key as a file and read it this way.
|
||||
|
||||
### Key rotation
|
||||
|
||||
Rotating the JWT keys invalidates all currently active tokens — every authenticated request will fail until clients re-authenticate. Plan rotation for low-traffic windows.
|
||||
|
||||
**Rotation procedure:**
|
||||
|
||||
1. Generate a new RSA keypair:
|
||||
```bash
|
||||
openssl genrsa -out private-new.pem 2048
|
||||
openssl rsa -in private-new.pem -pubout -out public-new.pem
|
||||
```
|
||||
|
||||
2. Update `JWT_PRIVATE_KEY` and `JWT_PUBLIC_KEY` in your environment or secrets store.
|
||||
|
||||
3. Restart the application:
|
||||
```bash
|
||||
# Graceful restart — send SIGTERM, let in-flight requests complete, then start with new keys
|
||||
kill -SIGTERM <pid>
|
||||
npm start # or docker restart <container>
|
||||
```
|
||||
|
||||
4. All previously issued tokens are now invalid (wrong signature). Clients will receive `401 UNAUTHORIZED` and must call `POST /token` again with their `client_id` and `client_secret` to get a new token.
|
||||
|
||||
5. Remove the old key files:
|
||||
```bash
|
||||
rm private-old.pem public-old.pem
|
||||
```
|
||||
|
||||
**Important:** There is no grace period or dual-key support in Phase 1. All tokens issued with the old private key are immediately rejected after rotation. If zero-downtime key rotation is required, it is a Phase 2 feature.
|
||||
|
||||
---
|
||||
|
||||
## CORS Configuration
|
||||
|
||||
Cross-Origin Resource Sharing is configured via the `CORS_ORIGIN` environment variable.
|
||||
|
||||
| Value | Behaviour |
|
||||
|-------|-----------|
|
||||
| `*` (default) | All origins permitted — appropriate for a public API |
|
||||
| `https://app.example.ai` | Only the specified origin permitted |
|
||||
|
||||
Set in `.env`:
|
||||
|
||||
```
|
||||
CORS_ORIGIN=https://app.example.ai
|
||||
```
|
||||
|
||||
The CORS header is set by the `cors` middleware applied globally in `src/app.ts`. Credentials (cookies) are not used — all auth is Bearer token.
|
||||
|
||||
For production deployments where the API is only called server-to-server (agent to AgentIdP), setting `CORS_ORIGIN` to a specific origin or removing browser-facing CORS entirely is recommended.
|
||||
|
||||
---
|
||||
|
||||
## Client Secret Storage
|
||||
|
||||
Client secrets are **never stored in plaintext**. The flow:
|
||||
|
||||
1. On credential generation or rotation, AgentIdP generates a random secret string (`sk_live_...`)
|
||||
2. The plaintext is returned to the caller **once only** in the API response
|
||||
3. AgentIdP immediately hashes the secret with **bcrypt** (cost factor from `bcryptjs` defaults) and stores only the hash in the `credentials.secret_hash` column
|
||||
4. On every `POST /token` call, the provided `client_secret` is verified against the stored hash using `bcrypt.compare()`
|
||||
|
||||
**Implication:** If a client loses their `client_secret`, it cannot be recovered. They must rotate the credential to get a new one.
|
||||
|
||||
---
|
||||
|
||||
## Secret Storage Guidance
|
||||
|
||||
| Environment | Recommendation |
|
||||
|-------------|---------------|
|
||||
| Local development | `.env` file, not committed to git |
|
||||
| CI/CD | Environment variables injected by the CI platform (GitHub Actions secrets, GitLab CI variables, etc.) |
|
||||
| Production (Docker) | Docker secrets or bind-mounted files from a secrets manager |
|
||||
| Production (cloud) | AWS Secrets Manager, GCP Secret Manager, HashiCorp Vault (Phase 2) |
|
||||
|
||||
**Never:**
|
||||
- Commit `.env` to version control
|
||||
- Log environment variables
|
||||
- Pass secrets as command-line arguments (visible in `ps aux`)
|
||||
- Store keys in the database
|
||||
|
||||
Add `.env` to `.gitignore`:
|
||||
|
||||
```bash
|
||||
echo ".env" >> .gitignore
|
||||
echo "*.pem" >> .gitignore
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Token Lifetime
|
||||
|
||||
JWT access tokens expire after **3600 seconds (1 hour)**. This is hardcoded in `src/utils/jwt.ts`. There is no refresh token — clients must re-authenticate via `POST /token` when the token expires.
|
||||
|
||||
The 1-hour lifetime is a balance between security (short-lived tokens limit exposure if stolen) and operational load (clients don't need to authenticate every few minutes).
|
||||
816
docs/openapi/agent-registry.yaml
Normal file
816
docs/openapi/agent-registry.yaml
Normal file
@@ -0,0 +1,816 @@
|
||||
openapi: 3.0.3
|
||||
|
||||
info:
|
||||
title: SentryAgent.ai — Agent Registry Service
|
||||
version: 1.0.0
|
||||
description: |
|
||||
The Agent Registry Service provides full lifecycle management for AI agent
|
||||
identities on the SentryAgent.ai AgentIdP platform. Every AI agent is treated
|
||||
as a first-class non-human identity, aligned with the AGNTCY standard
|
||||
(Linux Foundation).
|
||||
|
||||
Agents receive unique, immutable identifiers (UUIDs), typed capabilities,
|
||||
and lifecycle status management. The registry is the authoritative source of
|
||||
truth for all registered agent identities.
|
||||
|
||||
**Free Tier Limits**:
|
||||
- Max 100 registered agents per account
|
||||
- API rate limit: 100 requests/minute
|
||||
|
||||
servers:
|
||||
- url: http://localhost:3000/api/v1
|
||||
description: Local development server
|
||||
- url: https://api.sentryagent.ai/v1
|
||||
description: Production server
|
||||
|
||||
tags:
|
||||
- name: Agent Registry
|
||||
description: CRUD operations for AI agent identities
|
||||
|
||||
components:
|
||||
securitySchemes:
|
||||
BearerAuth:
|
||||
type: http
|
||||
scheme: bearer
|
||||
bearerFormat: JWT
|
||||
description: |
|
||||
JWT access token obtained via the OAuth 2.0 Client Credentials flow
|
||||
(`POST /token`). Include in the `Authorization` header as:
|
||||
`Authorization: Bearer <token>`
|
||||
|
||||
schemas:
|
||||
AgentType:
|
||||
type: string
|
||||
description: The functional classification of the AI agent.
|
||||
enum:
|
||||
- screener
|
||||
- classifier
|
||||
- orchestrator
|
||||
- extractor
|
||||
- summarizer
|
||||
- router
|
||||
- monitor
|
||||
- custom
|
||||
example: screener
|
||||
|
||||
DeploymentEnv:
|
||||
type: string
|
||||
description: The target deployment environment for the agent.
|
||||
enum:
|
||||
- development
|
||||
- staging
|
||||
- production
|
||||
example: production
|
||||
|
||||
AgentStatus:
|
||||
type: string
|
||||
description: |
|
||||
Lifecycle status of the agent.
|
||||
- `active`: Agent is operational and can authenticate.
|
||||
- `suspended`: Agent is temporarily disabled; credentials cannot be used.
|
||||
- `decommissioned`: Agent is permanently retired; soft-deleted record remains.
|
||||
enum:
|
||||
- active
|
||||
- suspended
|
||||
- decommissioned
|
||||
example: active
|
||||
|
||||
Agent:
|
||||
type: object
|
||||
description: Full representation of a registered AI agent identity.
|
||||
required:
|
||||
- agentId
|
||||
- email
|
||||
- agentType
|
||||
- version
|
||||
- capabilities
|
||||
- owner
|
||||
- deploymentEnv
|
||||
- status
|
||||
- createdAt
|
||||
- updatedAt
|
||||
properties:
|
||||
agentId:
|
||||
type: string
|
||||
format: uuid
|
||||
description: >
|
||||
Immutable, system-assigned unique identifier for the agent.
|
||||
Assigned at registration and never changes.
|
||||
readOnly: true
|
||||
example: "a1b2c3d4-e5f6-7890-abcd-ef1234567890"
|
||||
email:
|
||||
type: string
|
||||
format: email
|
||||
description: >
|
||||
Unique email-format identifier for the agent. Acts as the human-readable
|
||||
stable name for this agent identity.
|
||||
example: "screener-001@sentryagent.ai"
|
||||
agentType:
|
||||
$ref: '#/components/schemas/AgentType'
|
||||
version:
|
||||
type: string
|
||||
description: Semantic version string of the agent software.
|
||||
pattern: '^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\+([0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*))?$'
|
||||
example: "1.4.2"
|
||||
capabilities:
|
||||
type: array
|
||||
description: >
|
||||
List of capability strings representing what this agent is permitted
|
||||
to do. Uses a `resource:action` convention.
|
||||
items:
|
||||
type: string
|
||||
pattern: '^[a-z0-9_-]+:[a-z0-9_*-]+$'
|
||||
minItems: 1
|
||||
example:
|
||||
- "resume:read"
|
||||
- "email:send"
|
||||
- "candidate:score"
|
||||
owner:
|
||||
type: string
|
||||
description: Team or organisation that owns and is responsible for this agent.
|
||||
minLength: 1
|
||||
maxLength: 128
|
||||
example: "talent-acquisition-team"
|
||||
deploymentEnv:
|
||||
$ref: '#/components/schemas/DeploymentEnv'
|
||||
status:
|
||||
$ref: '#/components/schemas/AgentStatus'
|
||||
createdAt:
|
||||
type: string
|
||||
format: date-time
|
||||
description: ISO 8601 timestamp when the agent was first registered.
|
||||
readOnly: true
|
||||
example: "2026-03-28T09:00:00.000Z"
|
||||
updatedAt:
|
||||
type: string
|
||||
format: date-time
|
||||
description: ISO 8601 timestamp of the most recent update to this agent record.
|
||||
readOnly: true
|
||||
example: "2026-03-28T11:30:00.000Z"
|
||||
|
||||
CreateAgentRequest:
|
||||
type: object
|
||||
description: Request body for registering a new AI agent identity.
|
||||
required:
|
||||
- email
|
||||
- agentType
|
||||
- version
|
||||
- capabilities
|
||||
- owner
|
||||
- deploymentEnv
|
||||
properties:
|
||||
email:
|
||||
type: string
|
||||
format: email
|
||||
description: >
|
||||
Unique email-format identifier for the agent.
|
||||
Must be unique across all registered agents in the system.
|
||||
example: "screener-001@sentryagent.ai"
|
||||
agentType:
|
||||
$ref: '#/components/schemas/AgentType'
|
||||
version:
|
||||
type: string
|
||||
description: Semantic version string of the agent software.
|
||||
pattern: '^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\+([0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*))?$'
|
||||
example: "1.0.0"
|
||||
capabilities:
|
||||
type: array
|
||||
description: List of capability strings for this agent.
|
||||
items:
|
||||
type: string
|
||||
pattern: '^[a-z0-9_-]+:[a-z0-9_*-]+$'
|
||||
minItems: 1
|
||||
example:
|
||||
- "resume:read"
|
||||
- "email:send"
|
||||
owner:
|
||||
type: string
|
||||
description: Team or organisation that owns this agent.
|
||||
minLength: 1
|
||||
maxLength: 128
|
||||
example: "talent-acquisition-team"
|
||||
deploymentEnv:
|
||||
$ref: '#/components/schemas/DeploymentEnv'
|
||||
|
||||
UpdateAgentRequest:
|
||||
type: object
|
||||
description: >
|
||||
Request body for updating agent metadata. All fields are optional;
|
||||
only provided fields are updated. `agentId`, `email`, and `createdAt`
|
||||
are immutable and cannot be changed.
|
||||
minProperties: 1
|
||||
properties:
|
||||
agentType:
|
||||
$ref: '#/components/schemas/AgentType'
|
||||
version:
|
||||
type: string
|
||||
description: Updated semantic version string.
|
||||
pattern: '^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\+([0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*))?$'
|
||||
example: "1.5.0"
|
||||
capabilities:
|
||||
type: array
|
||||
description: Updated list of capability strings. Replaces the full list.
|
||||
items:
|
||||
type: string
|
||||
pattern: '^[a-z0-9_-]+:[a-z0-9_*-]+$'
|
||||
minItems: 1
|
||||
example:
|
||||
- "resume:read"
|
||||
- "email:send"
|
||||
- "candidate:score"
|
||||
- "report:write"
|
||||
owner:
|
||||
type: string
|
||||
description: Updated owner team or organisation.
|
||||
minLength: 1
|
||||
maxLength: 128
|
||||
example: "platform-team"
|
||||
deploymentEnv:
|
||||
$ref: '#/components/schemas/DeploymentEnv'
|
||||
status:
|
||||
$ref: '#/components/schemas/AgentStatus'
|
||||
|
||||
PaginatedAgentsResponse:
|
||||
type: object
|
||||
description: Paginated list of agent identities.
|
||||
required:
|
||||
- data
|
||||
- total
|
||||
- page
|
||||
- limit
|
||||
properties:
|
||||
data:
|
||||
type: array
|
||||
items:
|
||||
$ref: '#/components/schemas/Agent'
|
||||
total:
|
||||
type: integer
|
||||
description: Total number of agents matching the query filters.
|
||||
example: 47
|
||||
page:
|
||||
type: integer
|
||||
description: Current page number (1-based).
|
||||
example: 1
|
||||
limit:
|
||||
type: integer
|
||||
description: Number of items per page.
|
||||
example: 20
|
||||
|
||||
ErrorResponse:
|
||||
type: object
|
||||
description: Standard error response envelope used across all SentryAgent.ai APIs.
|
||||
required:
|
||||
- code
|
||||
- message
|
||||
properties:
|
||||
code:
|
||||
type: string
|
||||
description: >
|
||||
Machine-readable error code. Use this field for programmatic error handling.
|
||||
example: "AGENT_NOT_FOUND"
|
||||
message:
|
||||
type: string
|
||||
description: Human-readable description of the error.
|
||||
example: "Agent with the specified ID was not found."
|
||||
details:
|
||||
type: object
|
||||
description: >
|
||||
Optional structured details providing additional context about the error,
|
||||
such as field-level validation failures.
|
||||
additionalProperties: true
|
||||
example:
|
||||
field: "email"
|
||||
reason: "Email address is already registered to another agent."
|
||||
|
||||
responses:
|
||||
Unauthorized:
|
||||
description: Missing or invalid Bearer token.
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/ErrorResponse'
|
||||
example:
|
||||
code: "UNAUTHORIZED"
|
||||
message: "A valid Bearer token is required to access this resource."
|
||||
|
||||
Forbidden:
|
||||
description: Valid token but insufficient permissions.
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/ErrorResponse'
|
||||
example:
|
||||
code: "FORBIDDEN"
|
||||
message: "You do not have permission to perform this action."
|
||||
|
||||
NotFound:
|
||||
description: The requested resource was not found.
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/ErrorResponse'
|
||||
example:
|
||||
code: "AGENT_NOT_FOUND"
|
||||
message: "Agent with the specified ID was not found."
|
||||
|
||||
TooManyRequests:
|
||||
description: Rate limit exceeded. Retry after the reset time.
|
||||
headers:
|
||||
X-RateLimit-Limit:
|
||||
schema:
|
||||
type: integer
|
||||
description: Maximum number of requests allowed per minute.
|
||||
example: 100
|
||||
X-RateLimit-Remaining:
|
||||
schema:
|
||||
type: integer
|
||||
description: Number of requests remaining in the current window.
|
||||
example: 0
|
||||
X-RateLimit-Reset:
|
||||
schema:
|
||||
type: integer
|
||||
description: Unix timestamp (seconds) when the rate limit window resets.
|
||||
example: 1743155400
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/ErrorResponse'
|
||||
example:
|
||||
code: "RATE_LIMIT_EXCEEDED"
|
||||
message: "Too many requests. Please retry after the rate limit window resets."
|
||||
|
||||
InternalServerError:
|
||||
description: Unexpected server error. Contact support if the issue persists.
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/ErrorResponse'
|
||||
example:
|
||||
code: "INTERNAL_SERVER_ERROR"
|
||||
message: "An unexpected error occurred. Please try again later."
|
||||
|
||||
security:
|
||||
- BearerAuth: []
|
||||
|
||||
paths:
|
||||
/agents:
|
||||
post:
|
||||
operationId: registerAgent
|
||||
tags:
|
||||
- Agent Registry
|
||||
summary: Register a new AI agent
|
||||
description: |
|
||||
Creates a new AI agent identity in the SentryAgent.ai registry.
|
||||
|
||||
A unique immutable `agentId` (UUID) is system-assigned on creation.
|
||||
The `email` must be unique across all registered agents.
|
||||
|
||||
**Free Tier**: Maximum 100 registered agents per account. Attempting to
|
||||
register beyond this limit returns `403 Forbidden` with code `FREE_TIER_LIMIT_EXCEEDED`.
|
||||
requestBody:
|
||||
required: true
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/CreateAgentRequest'
|
||||
example:
|
||||
email: "screener-001@sentryagent.ai"
|
||||
agentType: "screener"
|
||||
version: "1.0.0"
|
||||
capabilities:
|
||||
- "resume:read"
|
||||
- "email:send"
|
||||
owner: "talent-acquisition-team"
|
||||
deploymentEnv: "production"
|
||||
responses:
|
||||
'201':
|
||||
description: Agent registered successfully.
|
||||
headers:
|
||||
X-RateLimit-Limit:
|
||||
schema:
|
||||
type: integer
|
||||
example: 100
|
||||
X-RateLimit-Remaining:
|
||||
schema:
|
||||
type: integer
|
||||
example: 99
|
||||
X-RateLimit-Reset:
|
||||
schema:
|
||||
type: integer
|
||||
example: 1743155400
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/Agent'
|
||||
example:
|
||||
agentId: "a1b2c3d4-e5f6-7890-abcd-ef1234567890"
|
||||
email: "screener-001@sentryagent.ai"
|
||||
agentType: "screener"
|
||||
version: "1.0.0"
|
||||
capabilities:
|
||||
- "resume:read"
|
||||
- "email:send"
|
||||
owner: "talent-acquisition-team"
|
||||
deploymentEnv: "production"
|
||||
status: "active"
|
||||
createdAt: "2026-03-28T09:00:00.000Z"
|
||||
updatedAt: "2026-03-28T09:00:00.000Z"
|
||||
'400':
|
||||
description: Invalid request body. Check `details` for field-level errors.
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/ErrorResponse'
|
||||
example:
|
||||
code: "VALIDATION_ERROR"
|
||||
message: "Request validation failed."
|
||||
details:
|
||||
field: "email"
|
||||
reason: "Must be a valid email address."
|
||||
'401':
|
||||
$ref: '#/components/responses/Unauthorized'
|
||||
'403':
|
||||
description: Forbidden. Either insufficient permissions or free tier limit reached.
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/ErrorResponse'
|
||||
examples:
|
||||
insufficientPermissions:
|
||||
summary: Insufficient permissions
|
||||
value:
|
||||
code: "FORBIDDEN"
|
||||
message: "You do not have permission to register agents."
|
||||
freeTierLimit:
|
||||
summary: Free tier agent limit reached
|
||||
value:
|
||||
code: "FREE_TIER_LIMIT_EXCEEDED"
|
||||
message: "Free tier limit of 100 registered agents has been reached."
|
||||
details:
|
||||
limit: 100
|
||||
current: 100
|
||||
'409':
|
||||
description: An agent with the provided email address is already registered.
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/ErrorResponse'
|
||||
example:
|
||||
code: "AGENT_ALREADY_EXISTS"
|
||||
message: "An agent with this email address is already registered."
|
||||
details:
|
||||
email: "screener-001@sentryagent.ai"
|
||||
'429':
|
||||
$ref: '#/components/responses/TooManyRequests'
|
||||
'500':
|
||||
$ref: '#/components/responses/InternalServerError'
|
||||
|
||||
get:
|
||||
operationId: listAgents
|
||||
tags:
|
||||
- Agent Registry
|
||||
summary: List registered agents
|
||||
description: |
|
||||
Returns a paginated list of all registered AI agent identities accessible
|
||||
to the authenticated caller.
|
||||
|
||||
Results can be filtered by `owner`, `agentType`, and/or `status`.
|
||||
Results are ordered by `createdAt` descending (most recent first).
|
||||
parameters:
|
||||
- name: page
|
||||
in: query
|
||||
description: Page number (1-based). Defaults to `1`.
|
||||
required: false
|
||||
schema:
|
||||
type: integer
|
||||
minimum: 1
|
||||
default: 1
|
||||
example: 1
|
||||
- name: limit
|
||||
in: query
|
||||
description: Number of results per page. Defaults to `20`, maximum `100`.
|
||||
required: false
|
||||
schema:
|
||||
type: integer
|
||||
minimum: 1
|
||||
maximum: 100
|
||||
default: 20
|
||||
example: 20
|
||||
- name: owner
|
||||
in: query
|
||||
description: Filter agents by owner name (exact match).
|
||||
required: false
|
||||
schema:
|
||||
type: string
|
||||
example: "talent-acquisition-team"
|
||||
- name: agentType
|
||||
in: query
|
||||
description: Filter agents by type.
|
||||
required: false
|
||||
schema:
|
||||
$ref: '#/components/schemas/AgentType'
|
||||
- name: status
|
||||
in: query
|
||||
description: Filter agents by lifecycle status.
|
||||
required: false
|
||||
schema:
|
||||
$ref: '#/components/schemas/AgentStatus'
|
||||
responses:
|
||||
'200':
|
||||
description: Paginated list of agents returned successfully.
|
||||
headers:
|
||||
X-RateLimit-Limit:
|
||||
schema:
|
||||
type: integer
|
||||
example: 100
|
||||
X-RateLimit-Remaining:
|
||||
schema:
|
||||
type: integer
|
||||
example: 95
|
||||
X-RateLimit-Reset:
|
||||
schema:
|
||||
type: integer
|
||||
example: 1743155400
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/PaginatedAgentsResponse'
|
||||
example:
|
||||
data:
|
||||
- agentId: "a1b2c3d4-e5f6-7890-abcd-ef1234567890"
|
||||
email: "screener-001@sentryagent.ai"
|
||||
agentType: "screener"
|
||||
version: "1.4.2"
|
||||
capabilities:
|
||||
- "resume:read"
|
||||
- "email:send"
|
||||
- "candidate:score"
|
||||
owner: "talent-acquisition-team"
|
||||
deploymentEnv: "production"
|
||||
status: "active"
|
||||
createdAt: "2026-03-01T08:00:00.000Z"
|
||||
updatedAt: "2026-03-28T09:00:00.000Z"
|
||||
- agentId: "b2c3d4e5-f6a7-8901-bcde-f12345678901"
|
||||
email: "classifier-002@sentryagent.ai"
|
||||
agentType: "classifier"
|
||||
version: "2.1.0"
|
||||
capabilities:
|
||||
- "document:classify"
|
||||
- "label:write"
|
||||
owner: "talent-acquisition-team"
|
||||
deploymentEnv: "staging"
|
||||
status: "active"
|
||||
createdAt: "2026-03-10T10:00:00.000Z"
|
||||
updatedAt: "2026-03-10T10:00:00.000Z"
|
||||
total: 47
|
||||
page: 1
|
||||
limit: 20
|
||||
'400':
|
||||
description: Invalid query parameters.
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/ErrorResponse'
|
||||
example:
|
||||
code: "VALIDATION_ERROR"
|
||||
message: "Invalid query parameter value."
|
||||
details:
|
||||
field: "limit"
|
||||
reason: "Must be an integer between 1 and 100."
|
||||
'401':
|
||||
$ref: '#/components/responses/Unauthorized'
|
||||
'403':
|
||||
$ref: '#/components/responses/Forbidden'
|
||||
'429':
|
||||
$ref: '#/components/responses/TooManyRequests'
|
||||
'500':
|
||||
$ref: '#/components/responses/InternalServerError'
|
||||
|
||||
/agents/{agentId}:
|
||||
parameters:
|
||||
- name: agentId
|
||||
in: path
|
||||
description: The unique UUID identifier of the agent.
|
||||
required: true
|
||||
schema:
|
||||
type: string
|
||||
format: uuid
|
||||
example: "a1b2c3d4-e5f6-7890-abcd-ef1234567890"
|
||||
|
||||
get:
|
||||
operationId: getAgentById
|
||||
tags:
|
||||
- Agent Registry
|
||||
summary: Get agent by ID
|
||||
description: |
|
||||
Retrieves the full identity record for a single AI agent by its immutable `agentId`.
|
||||
responses:
|
||||
'200':
|
||||
description: Agent record returned successfully.
|
||||
headers:
|
||||
X-RateLimit-Limit:
|
||||
schema:
|
||||
type: integer
|
||||
example: 100
|
||||
X-RateLimit-Remaining:
|
||||
schema:
|
||||
type: integer
|
||||
example: 94
|
||||
X-RateLimit-Reset:
|
||||
schema:
|
||||
type: integer
|
||||
example: 1743155400
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/Agent'
|
||||
example:
|
||||
agentId: "a1b2c3d4-e5f6-7890-abcd-ef1234567890"
|
||||
email: "screener-001@sentryagent.ai"
|
||||
agentType: "screener"
|
||||
version: "1.4.2"
|
||||
capabilities:
|
||||
- "resume:read"
|
||||
- "email:send"
|
||||
- "candidate:score"
|
||||
owner: "talent-acquisition-team"
|
||||
deploymentEnv: "production"
|
||||
status: "active"
|
||||
createdAt: "2026-03-01T08:00:00.000Z"
|
||||
updatedAt: "2026-03-28T09:00:00.000Z"
|
||||
'401':
|
||||
$ref: '#/components/responses/Unauthorized'
|
||||
'403':
|
||||
$ref: '#/components/responses/Forbidden'
|
||||
'404':
|
||||
$ref: '#/components/responses/NotFound'
|
||||
'429':
|
||||
$ref: '#/components/responses/TooManyRequests'
|
||||
'500':
|
||||
$ref: '#/components/responses/InternalServerError'
|
||||
|
||||
patch:
|
||||
operationId: updateAgent
|
||||
tags:
|
||||
- Agent Registry
|
||||
summary: Update agent metadata
|
||||
description: |
|
||||
Partially updates the metadata for an existing agent.
|
||||
|
||||
Only the fields provided in the request body are updated. Omitted fields
|
||||
are left unchanged. The following fields are immutable and cannot be
|
||||
updated: `agentId`, `email`, `createdAt`.
|
||||
|
||||
Setting `status` to `decommissioned` is a one-way operation — a
|
||||
decommissioned agent cannot be reactivated.
|
||||
requestBody:
|
||||
required: true
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/UpdateAgentRequest'
|
||||
example:
|
||||
version: "1.5.0"
|
||||
capabilities:
|
||||
- "resume:read"
|
||||
- "email:send"
|
||||
- "candidate:score"
|
||||
- "report:write"
|
||||
deploymentEnv: "production"
|
||||
responses:
|
||||
'200':
|
||||
description: Agent updated successfully. Returns the full updated agent record.
|
||||
headers:
|
||||
X-RateLimit-Limit:
|
||||
schema:
|
||||
type: integer
|
||||
example: 100
|
||||
X-RateLimit-Remaining:
|
||||
schema:
|
||||
type: integer
|
||||
example: 93
|
||||
X-RateLimit-Reset:
|
||||
schema:
|
||||
type: integer
|
||||
example: 1743155400
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/Agent'
|
||||
example:
|
||||
agentId: "a1b2c3d4-e5f6-7890-abcd-ef1234567890"
|
||||
email: "screener-001@sentryagent.ai"
|
||||
agentType: "screener"
|
||||
version: "1.5.0"
|
||||
capabilities:
|
||||
- "resume:read"
|
||||
- "email:send"
|
||||
- "candidate:score"
|
||||
- "report:write"
|
||||
owner: "talent-acquisition-team"
|
||||
deploymentEnv: "production"
|
||||
status: "active"
|
||||
createdAt: "2026-03-01T08:00:00.000Z"
|
||||
updatedAt: "2026-03-28T11:30:00.000Z"
|
||||
'400':
|
||||
description: Invalid request body or attempt to modify an immutable field.
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/ErrorResponse'
|
||||
examples:
|
||||
validationError:
|
||||
summary: Validation failure
|
||||
value:
|
||||
code: "VALIDATION_ERROR"
|
||||
message: "Request validation failed."
|
||||
details:
|
||||
field: "version"
|
||||
reason: "Must be a valid semantic version string."
|
||||
immutableField:
|
||||
summary: Attempt to modify immutable field
|
||||
value:
|
||||
code: "IMMUTABLE_FIELD"
|
||||
message: "The field 'email' cannot be modified after registration."
|
||||
details:
|
||||
field: "email"
|
||||
'401':
|
||||
$ref: '#/components/responses/Unauthorized'
|
||||
'403':
|
||||
description: Forbidden. Insufficient permissions or agent is decommissioned.
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/ErrorResponse'
|
||||
examples:
|
||||
forbidden:
|
||||
summary: Insufficient permissions
|
||||
value:
|
||||
code: "FORBIDDEN"
|
||||
message: "You do not have permission to update this agent."
|
||||
decommissioned:
|
||||
summary: Agent is decommissioned
|
||||
value:
|
||||
code: "AGENT_DECOMMISSIONED"
|
||||
message: "Decommissioned agents cannot be updated."
|
||||
details:
|
||||
agentId: "a1b2c3d4-e5f6-7890-abcd-ef1234567890"
|
||||
'404':
|
||||
$ref: '#/components/responses/NotFound'
|
||||
'429':
|
||||
$ref: '#/components/responses/TooManyRequests'
|
||||
'500':
|
||||
$ref: '#/components/responses/InternalServerError'
|
||||
|
||||
delete:
|
||||
operationId: deactivateAgent
|
||||
tags:
|
||||
- Agent Registry
|
||||
summary: Deactivate (soft-delete) an agent
|
||||
description: |
|
||||
Permanently decommissions an AI agent. This is a **soft delete** — the
|
||||
agent record is retained in the database for audit purposes, but the
|
||||
agent's status is set to `decommissioned`.
|
||||
|
||||
**Effects of decommissioning**:
|
||||
- All active credentials for this agent are immediately revoked.
|
||||
- The agent can no longer authenticate or obtain tokens.
|
||||
- The agent record remains visible in the registry with status `decommissioned`.
|
||||
- This operation is **irreversible**.
|
||||
responses:
|
||||
'204':
|
||||
description: Agent decommissioned successfully. No response body.
|
||||
headers:
|
||||
X-RateLimit-Limit:
|
||||
schema:
|
||||
type: integer
|
||||
example: 100
|
||||
X-RateLimit-Remaining:
|
||||
schema:
|
||||
type: integer
|
||||
example: 92
|
||||
X-RateLimit-Reset:
|
||||
schema:
|
||||
type: integer
|
||||
example: 1743155400
|
||||
'401':
|
||||
$ref: '#/components/responses/Unauthorized'
|
||||
'403':
|
||||
$ref: '#/components/responses/Forbidden'
|
||||
'404':
|
||||
$ref: '#/components/responses/NotFound'
|
||||
'409':
|
||||
description: Agent is already decommissioned.
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/ErrorResponse'
|
||||
example:
|
||||
code: "AGENT_ALREADY_DECOMMISSIONED"
|
||||
message: "This agent has already been decommissioned."
|
||||
details:
|
||||
agentId: "a1b2c3d4-e5f6-7890-abcd-ef1234567890"
|
||||
'429':
|
||||
$ref: '#/components/responses/TooManyRequests'
|
||||
'500':
|
||||
$ref: '#/components/responses/InternalServerError'
|
||||
497
docs/openapi/audit-log.yaml
Normal file
497
docs/openapi/audit-log.yaml
Normal file
@@ -0,0 +1,497 @@
|
||||
openapi: 3.0.3
|
||||
|
||||
info:
|
||||
title: SentryAgent.ai — Audit Log Service
|
||||
version: 1.0.0
|
||||
description: |
|
||||
The Audit Log Service provides a queryable, immutable, compliance-ready
|
||||
event log of all significant actions performed by agents and administrators
|
||||
on the SentryAgent.ai AgentIdP platform.
|
||||
|
||||
**Immutability**: Audit events are written internally only — there are no
|
||||
API endpoints to create, modify, or delete audit records. The log is
|
||||
append-only by design.
|
||||
|
||||
**Automatic event capture**: The following actions are automatically logged:
|
||||
| Action | Description |
|
||||
|--------|-------------|
|
||||
| `agent.created` | A new agent was registered |
|
||||
| `agent.updated` | Agent metadata was modified |
|
||||
| `agent.decommissioned` | An agent was decommissioned |
|
||||
| `agent.suspended` | An agent was suspended |
|
||||
| `agent.reactivated` | A suspended agent was reactivated |
|
||||
| `token.issued` | An access token was issued |
|
||||
| `token.revoked` | An access token was revoked |
|
||||
| `token.introspected` | A token was introspected |
|
||||
| `credential.generated` | New credentials were generated |
|
||||
| `credential.rotated` | A credential was rotated |
|
||||
| `credential.revoked` | A credential was revoked |
|
||||
| `auth.failed` | An authentication attempt failed |
|
||||
|
||||
**Free Tier**: Audit log retention is 90 days.
|
||||
Events older than 90 days are automatically purged on the free tier.
|
||||
|
||||
**Required scope**: `audit:read`
|
||||
|
||||
servers:
|
||||
- url: http://localhost:3000/api/v1
|
||||
description: Local development server
|
||||
- url: https://api.sentryagent.ai/v1
|
||||
description: Production server
|
||||
|
||||
tags:
|
||||
- name: Audit Log
|
||||
description: Query immutable audit events for compliance and governance
|
||||
|
||||
components:
|
||||
securitySchemes:
|
||||
BearerAuth:
|
||||
type: http
|
||||
scheme: bearer
|
||||
bearerFormat: JWT
|
||||
description: |
|
||||
JWT access token with `audit:read` scope, obtained via `POST /token`.
|
||||
Include as: `Authorization: Bearer <token>`
|
||||
|
||||
schemas:
|
||||
AuditAction:
|
||||
type: string
|
||||
description: The action that triggered the audit event.
|
||||
enum:
|
||||
- agent.created
|
||||
- agent.updated
|
||||
- agent.decommissioned
|
||||
- agent.suspended
|
||||
- agent.reactivated
|
||||
- token.issued
|
||||
- token.revoked
|
||||
- token.introspected
|
||||
- credential.generated
|
||||
- credential.rotated
|
||||
- credential.revoked
|
||||
- auth.failed
|
||||
example: token.issued
|
||||
|
||||
AuditOutcome:
|
||||
type: string
|
||||
description: Whether the action succeeded or failed.
|
||||
enum:
|
||||
- success
|
||||
- failure
|
||||
example: success
|
||||
|
||||
AuditEvent:
|
||||
type: object
|
||||
description: |
|
||||
An immutable audit event record representing a single significant action
|
||||
that occurred within the SentryAgent.ai platform.
|
||||
required:
|
||||
- eventId
|
||||
- agentId
|
||||
- action
|
||||
- outcome
|
||||
- ipAddress
|
||||
- userAgent
|
||||
- metadata
|
||||
- timestamp
|
||||
properties:
|
||||
eventId:
|
||||
type: string
|
||||
format: uuid
|
||||
description: Immutable, system-assigned unique identifier for this audit event.
|
||||
readOnly: true
|
||||
example: "f1e2d3c4-b5a6-7890-cdef-123456789012"
|
||||
agentId:
|
||||
type: string
|
||||
format: uuid
|
||||
description: >
|
||||
The `agentId` of the agent that triggered this event. For system-generated
|
||||
events (e.g. automatic token expiry), this field refers to the affected agent.
|
||||
example: "a1b2c3d4-e5f6-7890-abcd-ef1234567890"
|
||||
action:
|
||||
$ref: '#/components/schemas/AuditAction'
|
||||
outcome:
|
||||
$ref: '#/components/schemas/AuditOutcome'
|
||||
ipAddress:
|
||||
type: string
|
||||
description: >
|
||||
IP address of the client that initiated the request.
|
||||
IPv4 or IPv6 format. May be `0.0.0.0` for system-generated events.
|
||||
example: "203.0.113.42"
|
||||
userAgent:
|
||||
type: string
|
||||
description: >
|
||||
HTTP `User-Agent` header value from the originating request.
|
||||
May be `SentryAgent-System/1.0` for internally generated events.
|
||||
example: "SentryAgent-SDK/1.0.0 Node.js/18.19.0"
|
||||
metadata:
|
||||
type: object
|
||||
description: |
|
||||
Action-specific structured data providing additional context.
|
||||
Schema varies by `action`:
|
||||
- `token.issued`: includes `scope`, `expiresAt`
|
||||
- `credential.rotated`: includes `credentialId`
|
||||
- `agent.created`: includes `agentType`, `owner`
|
||||
- `auth.failed`: includes `reason`, `clientId`
|
||||
additionalProperties: true
|
||||
example:
|
||||
scope: "agents:read agents:write"
|
||||
expiresAt: "2026-03-28T10:00:00.000Z"
|
||||
timestamp:
|
||||
type: string
|
||||
format: date-time
|
||||
description: ISO 8601 timestamp when the event occurred.
|
||||
readOnly: true
|
||||
example: "2026-03-28T09:01:00.000Z"
|
||||
|
||||
PaginatedAuditEventsResponse:
|
||||
type: object
|
||||
description: Paginated list of audit events.
|
||||
required:
|
||||
- data
|
||||
- total
|
||||
- page
|
||||
- limit
|
||||
properties:
|
||||
data:
|
||||
type: array
|
||||
items:
|
||||
$ref: '#/components/schemas/AuditEvent'
|
||||
total:
|
||||
type: integer
|
||||
description: Total number of audit events matching the query filters.
|
||||
example: 1423
|
||||
page:
|
||||
type: integer
|
||||
description: Current page number (1-based).
|
||||
example: 1
|
||||
limit:
|
||||
type: integer
|
||||
description: Number of items per page.
|
||||
example: 50
|
||||
|
||||
ErrorResponse:
|
||||
type: object
|
||||
description: Standard error response envelope.
|
||||
required:
|
||||
- code
|
||||
- message
|
||||
properties:
|
||||
code:
|
||||
type: string
|
||||
description: Machine-readable error code.
|
||||
example: "AUDIT_EVENT_NOT_FOUND"
|
||||
message:
|
||||
type: string
|
||||
description: Human-readable description of the error.
|
||||
example: "Audit event with the specified ID was not found."
|
||||
details:
|
||||
type: object
|
||||
description: Optional structured details about the error.
|
||||
additionalProperties: true
|
||||
example: {}
|
||||
|
||||
responses:
|
||||
Unauthorized:
|
||||
description: Missing or invalid Bearer token.
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/ErrorResponse'
|
||||
example:
|
||||
code: "UNAUTHORIZED"
|
||||
message: "A valid Bearer token is required to access this resource."
|
||||
|
||||
Forbidden:
|
||||
description: Valid token but insufficient permissions. Requires `audit:read` scope.
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/ErrorResponse'
|
||||
example:
|
||||
code: "INSUFFICIENT_SCOPE"
|
||||
message: "The 'audit:read' scope is required to access audit logs."
|
||||
|
||||
NotFound:
|
||||
description: The requested audit event was not found.
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/ErrorResponse'
|
||||
example:
|
||||
code: "AUDIT_EVENT_NOT_FOUND"
|
||||
message: "Audit event with the specified ID was not found."
|
||||
|
||||
TooManyRequests:
|
||||
description: Rate limit exceeded.
|
||||
headers:
|
||||
X-RateLimit-Limit:
|
||||
schema:
|
||||
type: integer
|
||||
description: Maximum requests allowed per minute.
|
||||
example: 100
|
||||
X-RateLimit-Remaining:
|
||||
schema:
|
||||
type: integer
|
||||
description: Requests remaining in the current window.
|
||||
example: 0
|
||||
X-RateLimit-Reset:
|
||||
schema:
|
||||
type: integer
|
||||
description: Unix timestamp when the rate limit window resets.
|
||||
example: 1743155400
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/ErrorResponse'
|
||||
example:
|
||||
code: "RATE_LIMIT_EXCEEDED"
|
||||
message: "Too many requests. Please retry after the rate limit window resets."
|
||||
|
||||
InternalServerError:
|
||||
description: Unexpected server error.
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/ErrorResponse'
|
||||
example:
|
||||
code: "INTERNAL_SERVER_ERROR"
|
||||
message: "An unexpected error occurred. Please try again later."
|
||||
|
||||
security:
|
||||
- BearerAuth: []
|
||||
|
||||
paths:
|
||||
/audit:
|
||||
get:
|
||||
operationId: queryAuditLog
|
||||
tags:
|
||||
- Audit Log
|
||||
summary: Query audit log
|
||||
description: |
|
||||
Returns a paginated, filtered list of audit events. Results are ordered
|
||||
by `timestamp` descending (most recent first).
|
||||
|
||||
**Requires**: Bearer token with `audit:read` scope.
|
||||
|
||||
**Retention**: On the free tier, only events from the last 90 days are
|
||||
accessible. Requests for older events will return an empty result set,
|
||||
not an error.
|
||||
|
||||
**Filtering**: Multiple filters can be combined (logical AND).
|
||||
All filter parameters are optional.
|
||||
parameters:
|
||||
- name: page
|
||||
in: query
|
||||
description: Page number (1-based). Defaults to `1`.
|
||||
required: false
|
||||
schema:
|
||||
type: integer
|
||||
minimum: 1
|
||||
default: 1
|
||||
example: 1
|
||||
- name: limit
|
||||
in: query
|
||||
description: Number of results per page. Defaults to `50`, maximum `200`.
|
||||
required: false
|
||||
schema:
|
||||
type: integer
|
||||
minimum: 1
|
||||
maximum: 200
|
||||
default: 50
|
||||
example: 50
|
||||
- name: agentId
|
||||
in: query
|
||||
description: Filter events to those triggered by a specific agent (UUID).
|
||||
required: false
|
||||
schema:
|
||||
type: string
|
||||
format: uuid
|
||||
example: "a1b2c3d4-e5f6-7890-abcd-ef1234567890"
|
||||
- name: action
|
||||
in: query
|
||||
description: Filter events by action type.
|
||||
required: false
|
||||
schema:
|
||||
$ref: '#/components/schemas/AuditAction'
|
||||
- name: outcome
|
||||
in: query
|
||||
description: Filter events by outcome.
|
||||
required: false
|
||||
schema:
|
||||
$ref: '#/components/schemas/AuditOutcome'
|
||||
- name: fromDate
|
||||
in: query
|
||||
description: |
|
||||
Filter events at or after this ISO 8601 timestamp (inclusive).
|
||||
On free tier, cannot be older than 90 days from today.
|
||||
required: false
|
||||
schema:
|
||||
type: string
|
||||
format: date-time
|
||||
example: "2026-03-01T00:00:00.000Z"
|
||||
- name: toDate
|
||||
in: query
|
||||
description: Filter events at or before this ISO 8601 timestamp (inclusive).
|
||||
required: false
|
||||
schema:
|
||||
type: string
|
||||
format: date-time
|
||||
example: "2026-03-28T23:59:59.999Z"
|
||||
responses:
|
||||
'200':
|
||||
description: Audit events returned successfully.
|
||||
headers:
|
||||
X-RateLimit-Limit:
|
||||
schema:
|
||||
type: integer
|
||||
example: 100
|
||||
X-RateLimit-Remaining:
|
||||
schema:
|
||||
type: integer
|
||||
example: 95
|
||||
X-RateLimit-Reset:
|
||||
schema:
|
||||
type: integer
|
||||
example: 1743155400
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/PaginatedAuditEventsResponse'
|
||||
example:
|
||||
data:
|
||||
- eventId: "f1e2d3c4-b5a6-7890-cdef-123456789012"
|
||||
agentId: "a1b2c3d4-e5f6-7890-abcd-ef1234567890"
|
||||
action: "token.issued"
|
||||
outcome: "success"
|
||||
ipAddress: "203.0.113.42"
|
||||
userAgent: "SentryAgent-SDK/1.0.0 Node.js/18.19.0"
|
||||
metadata:
|
||||
scope: "agents:read agents:write"
|
||||
expiresAt: "2026-03-28T10:01:00.000Z"
|
||||
timestamp: "2026-03-28T09:01:00.000Z"
|
||||
- eventId: "e2d3c4b5-a6f7-8901-bcde-f23456789013"
|
||||
agentId: "a1b2c3d4-e5f6-7890-abcd-ef1234567890"
|
||||
action: "credential.generated"
|
||||
outcome: "success"
|
||||
ipAddress: "203.0.113.42"
|
||||
userAgent: "SentryAgent-SDK/1.0.0 Node.js/18.19.0"
|
||||
metadata:
|
||||
credentialId: "c9d8e7f6-a5b4-3210-fedc-ba9876543210"
|
||||
timestamp: "2026-03-28T09:00:00.000Z"
|
||||
- eventId: "d3c4b5a6-f7e8-9012-cdef-345678901234"
|
||||
agentId: "b2c3d4e5-f6a7-8901-bcde-f12345678901"
|
||||
action: "auth.failed"
|
||||
outcome: "failure"
|
||||
ipAddress: "198.51.100.17"
|
||||
userAgent: "python-requests/2.31.0"
|
||||
metadata:
|
||||
reason: "invalid_client_secret"
|
||||
clientId: "b2c3d4e5-f6a7-8901-bcde-f12345678901"
|
||||
timestamp: "2026-03-28T08:45:00.000Z"
|
||||
total: 1423
|
||||
page: 1
|
||||
limit: 50
|
||||
'400':
|
||||
description: Invalid query parameters.
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/ErrorResponse'
|
||||
examples:
|
||||
invalidDate:
|
||||
summary: Invalid date format
|
||||
value:
|
||||
code: "VALIDATION_ERROR"
|
||||
message: "Invalid query parameter value."
|
||||
details:
|
||||
field: "fromDate"
|
||||
reason: "Must be a valid ISO 8601 date-time string."
|
||||
invalidDateRange:
|
||||
summary: fromDate is after toDate
|
||||
value:
|
||||
code: "VALIDATION_ERROR"
|
||||
message: "Invalid date range."
|
||||
details:
|
||||
reason: "fromDate must be before or equal to toDate."
|
||||
retentionExceeded:
|
||||
summary: Requested date is outside retention window
|
||||
value:
|
||||
code: "RETENTION_WINDOW_EXCEEDED"
|
||||
message: "Free tier audit log retention is 90 days. Requested date is outside the retention window."
|
||||
details:
|
||||
retentionDays: 90
|
||||
earliestAvailable: "2025-12-28T00:00:00.000Z"
|
||||
'401':
|
||||
$ref: '#/components/responses/Unauthorized'
|
||||
'403':
|
||||
$ref: '#/components/responses/Forbidden'
|
||||
'429':
|
||||
$ref: '#/components/responses/TooManyRequests'
|
||||
'500':
|
||||
$ref: '#/components/responses/InternalServerError'
|
||||
|
||||
/audit/{eventId}:
|
||||
parameters:
|
||||
- name: eventId
|
||||
in: path
|
||||
description: The unique UUID identifier of the audit event.
|
||||
required: true
|
||||
schema:
|
||||
type: string
|
||||
format: uuid
|
||||
example: "f1e2d3c4-b5a6-7890-cdef-123456789012"
|
||||
|
||||
get:
|
||||
operationId: getAuditEventById
|
||||
tags:
|
||||
- Audit Log
|
||||
summary: Get a single audit event by ID
|
||||
description: |
|
||||
Retrieves a single, immutable audit event by its unique `eventId`.
|
||||
|
||||
**Requires**: Bearer token with `audit:read` scope.
|
||||
|
||||
**Retention**: Free tier events older than 90 days are not accessible
|
||||
and will return `404 Not Found`.
|
||||
responses:
|
||||
'200':
|
||||
description: Audit event returned successfully.
|
||||
headers:
|
||||
X-RateLimit-Limit:
|
||||
schema:
|
||||
type: integer
|
||||
example: 100
|
||||
X-RateLimit-Remaining:
|
||||
schema:
|
||||
type: integer
|
||||
example: 94
|
||||
X-RateLimit-Reset:
|
||||
schema:
|
||||
type: integer
|
||||
example: 1743155400
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/AuditEvent'
|
||||
example:
|
||||
eventId: "f1e2d3c4-b5a6-7890-cdef-123456789012"
|
||||
agentId: "a1b2c3d4-e5f6-7890-abcd-ef1234567890"
|
||||
action: "token.issued"
|
||||
outcome: "success"
|
||||
ipAddress: "203.0.113.42"
|
||||
userAgent: "SentryAgent-SDK/1.0.0 Node.js/18.19.0"
|
||||
metadata:
|
||||
scope: "agents:read agents:write"
|
||||
expiresAt: "2026-03-28T10:01:00.000Z"
|
||||
timestamp: "2026-03-28T09:01:00.000Z"
|
||||
'401':
|
||||
$ref: '#/components/responses/Unauthorized'
|
||||
'403':
|
||||
$ref: '#/components/responses/Forbidden'
|
||||
'404':
|
||||
$ref: '#/components/responses/NotFound'
|
||||
'429':
|
||||
$ref: '#/components/responses/TooManyRequests'
|
||||
'500':
|
||||
$ref: '#/components/responses/InternalServerError'
|
||||
687
docs/openapi/credential-management.yaml
Normal file
687
docs/openapi/credential-management.yaml
Normal file
@@ -0,0 +1,687 @@
|
||||
openapi: 3.0.3
|
||||
|
||||
info:
|
||||
title: SentryAgent.ai — Credential Management Service
|
||||
version: 1.0.0
|
||||
description: |
|
||||
The Credential Management Service provides secure generation, listing,
|
||||
rotation, and revocation of OAuth 2.0 client credentials for registered
|
||||
AI agents.
|
||||
|
||||
Each agent can hold multiple credentials simultaneously to support
|
||||
zero-downtime rotation. A credential consists of a `client_id` (= `agentId`)
|
||||
and a `client_secret`.
|
||||
|
||||
**Security model**:
|
||||
- `client_secret` is returned **once only** — at creation or rotation time.
|
||||
- Secrets are stored as a bcrypt hash; plain-text is never persisted.
|
||||
- An agent may only manage its own credentials unless the caller holds an
|
||||
admin-scoped token.
|
||||
- Rotating a credential immediately revokes the previous `client_secret`.
|
||||
|
||||
**Auth**: Bearer token (JWT) required on all endpoints.
|
||||
|
||||
servers:
|
||||
- url: http://localhost:3000/api/v1
|
||||
description: Local development server
|
||||
- url: https://api.sentryagent.ai/v1
|
||||
description: Production server
|
||||
|
||||
tags:
|
||||
- name: Credential Management
|
||||
description: Generate, list, rotate, and revoke agent credentials
|
||||
|
||||
components:
|
||||
securitySchemes:
|
||||
BearerAuth:
|
||||
type: http
|
||||
scheme: bearer
|
||||
bearerFormat: JWT
|
||||
description: |
|
||||
JWT access token obtained via `POST /token`.
|
||||
Include as: `Authorization: Bearer <token>`
|
||||
|
||||
schemas:
|
||||
CredentialStatus:
|
||||
type: string
|
||||
description: |
|
||||
Lifecycle status of a credential.
|
||||
- `active`: Credential is valid and can be used to obtain tokens.
|
||||
- `revoked`: Credential has been explicitly revoked and is permanently invalid.
|
||||
enum:
|
||||
- active
|
||||
- revoked
|
||||
example: active
|
||||
|
||||
Credential:
|
||||
type: object
|
||||
description: |
|
||||
A credential record for an AI agent. The `clientSecret` is **never**
|
||||
returned in this schema — it is only returned once in `CredentialWithSecret`
|
||||
at the moment of creation or rotation.
|
||||
required:
|
||||
- credentialId
|
||||
- clientId
|
||||
- status
|
||||
- createdAt
|
||||
properties:
|
||||
credentialId:
|
||||
type: string
|
||||
format: uuid
|
||||
description: Immutable, system-assigned unique identifier for this credential.
|
||||
readOnly: true
|
||||
example: "c9d8e7f6-a5b4-3210-fedc-ba9876543210"
|
||||
clientId:
|
||||
type: string
|
||||
format: uuid
|
||||
description: >
|
||||
The `agentId` this credential belongs to. Equal to the `agentId`
|
||||
path parameter.
|
||||
readOnly: true
|
||||
example: "a1b2c3d4-e5f6-7890-abcd-ef1234567890"
|
||||
status:
|
||||
$ref: '#/components/schemas/CredentialStatus'
|
||||
createdAt:
|
||||
type: string
|
||||
format: date-time
|
||||
description: ISO 8601 timestamp when the credential was created.
|
||||
readOnly: true
|
||||
example: "2026-03-28T09:00:00.000Z"
|
||||
expiresAt:
|
||||
type: string
|
||||
format: date-time
|
||||
nullable: true
|
||||
description: |
|
||||
ISO 8601 timestamp when the credential expires.
|
||||
`null` indicates the credential does not expire (valid until revoked).
|
||||
example: "2027-03-28T09:00:00.000Z"
|
||||
revokedAt:
|
||||
type: string
|
||||
format: date-time
|
||||
nullable: true
|
||||
description: >
|
||||
ISO 8601 timestamp when the credential was revoked.
|
||||
`null` if the credential has not been revoked.
|
||||
readOnly: true
|
||||
example: null
|
||||
|
||||
CredentialWithSecret:
|
||||
allOf:
|
||||
- $ref: '#/components/schemas/Credential'
|
||||
- type: object
|
||||
description: |
|
||||
Extended credential record returned **only** at creation or rotation time.
|
||||
The `clientSecret` is shown once and never retrievable again.
|
||||
Store it securely immediately.
|
||||
required:
|
||||
- clientSecret
|
||||
properties:
|
||||
clientSecret:
|
||||
type: string
|
||||
description: |
|
||||
The plain-text client secret. **Shown once only** — store securely immediately.
|
||||
This value is not persisted in plain text on the server.
|
||||
format: password
|
||||
example: "sk_live_7f3a2b1c9d8e4f0a6b5c3d2e1f0a9b8c"
|
||||
|
||||
GenerateCredentialRequest:
|
||||
type: object
|
||||
description: |
|
||||
Optional request body for generating new credentials.
|
||||
If `expiresAt` is omitted, the credential does not expire.
|
||||
properties:
|
||||
expiresAt:
|
||||
type: string
|
||||
format: date-time
|
||||
description: |
|
||||
Optional ISO 8601 expiry timestamp for the credential.
|
||||
Must be a future date. If omitted, the credential has no expiry.
|
||||
example: "2027-03-28T09:00:00.000Z"
|
||||
|
||||
PaginatedCredentialsResponse:
|
||||
type: object
|
||||
description: Paginated list of credentials for an agent.
|
||||
required:
|
||||
- data
|
||||
- total
|
||||
- page
|
||||
- limit
|
||||
properties:
|
||||
data:
|
||||
type: array
|
||||
items:
|
||||
$ref: '#/components/schemas/Credential'
|
||||
total:
|
||||
type: integer
|
||||
description: Total number of credentials for this agent.
|
||||
example: 3
|
||||
page:
|
||||
type: integer
|
||||
description: Current page number (1-based).
|
||||
example: 1
|
||||
limit:
|
||||
type: integer
|
||||
description: Number of items per page.
|
||||
example: 20
|
||||
|
||||
ErrorResponse:
|
||||
type: object
|
||||
description: Standard error response envelope.
|
||||
required:
|
||||
- code
|
||||
- message
|
||||
properties:
|
||||
code:
|
||||
type: string
|
||||
description: Machine-readable error code.
|
||||
example: "CREDENTIAL_NOT_FOUND"
|
||||
message:
|
||||
type: string
|
||||
description: Human-readable description of the error.
|
||||
example: "Credential with the specified ID was not found."
|
||||
details:
|
||||
type: object
|
||||
description: Optional structured details about the error.
|
||||
additionalProperties: true
|
||||
example: {}
|
||||
|
||||
responses:
|
||||
Unauthorized:
|
||||
description: Missing or invalid Bearer token.
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/ErrorResponse'
|
||||
example:
|
||||
code: "UNAUTHORIZED"
|
||||
message: "A valid Bearer token is required to access this resource."
|
||||
|
||||
Forbidden:
|
||||
description: Valid token but insufficient permissions.
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/ErrorResponse'
|
||||
example:
|
||||
code: "FORBIDDEN"
|
||||
message: "You do not have permission to manage credentials for this agent."
|
||||
|
||||
AgentNotFound:
|
||||
description: The specified agent does not exist.
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/ErrorResponse'
|
||||
example:
|
||||
code: "AGENT_NOT_FOUND"
|
||||
message: "Agent with the specified ID was not found."
|
||||
|
||||
CredentialNotFound:
|
||||
description: The specified credential does not exist.
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/ErrorResponse'
|
||||
example:
|
||||
code: "CREDENTIAL_NOT_FOUND"
|
||||
message: "Credential with the specified ID was not found."
|
||||
|
||||
TooManyRequests:
|
||||
description: Rate limit exceeded.
|
||||
headers:
|
||||
X-RateLimit-Limit:
|
||||
schema:
|
||||
type: integer
|
||||
example: 100
|
||||
X-RateLimit-Remaining:
|
||||
schema:
|
||||
type: integer
|
||||
example: 0
|
||||
X-RateLimit-Reset:
|
||||
schema:
|
||||
type: integer
|
||||
example: 1743155400
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/ErrorResponse'
|
||||
example:
|
||||
code: "RATE_LIMIT_EXCEEDED"
|
||||
message: "Too many requests. Please retry after the rate limit window resets."
|
||||
|
||||
InternalServerError:
|
||||
description: Unexpected server error.
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/ErrorResponse'
|
||||
example:
|
||||
code: "INTERNAL_SERVER_ERROR"
|
||||
message: "An unexpected error occurred. Please try again later."
|
||||
|
||||
security:
|
||||
- BearerAuth: []
|
||||
|
||||
paths:
|
||||
/agents/{agentId}/credentials:
|
||||
parameters:
|
||||
- name: agentId
|
||||
in: path
|
||||
description: The unique UUID identifier of the agent.
|
||||
required: true
|
||||
schema:
|
||||
type: string
|
||||
format: uuid
|
||||
example: "a1b2c3d4-e5f6-7890-abcd-ef1234567890"
|
||||
|
||||
post:
|
||||
operationId: generateCredential
|
||||
tags:
|
||||
- Credential Management
|
||||
summary: Generate new credentials for an agent
|
||||
description: |
|
||||
Generates a new `client_id` + `client_secret` credential pair for the
|
||||
specified agent.
|
||||
|
||||
**Important**: The `clientSecret` is returned **once only** in this response.
|
||||
It is not stored in plain text on the server and cannot be retrieved later.
|
||||
Store it securely immediately (e.g. in a secrets manager).
|
||||
|
||||
An agent may hold multiple active credentials simultaneously. This supports
|
||||
zero-downtime rotation: generate a new credential, update all consumers,
|
||||
then revoke the old one.
|
||||
|
||||
**Restrictions**:
|
||||
- The agent must be in `active` status.
|
||||
- An agent may manage its own credentials via a self-issued token.
|
||||
- Managing another agent's credentials requires an admin-scoped token.
|
||||
requestBody:
|
||||
required: false
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/GenerateCredentialRequest'
|
||||
example:
|
||||
expiresAt: "2027-03-28T09:00:00.000Z"
|
||||
responses:
|
||||
'201':
|
||||
description: |
|
||||
Credential generated successfully.
|
||||
**Save the `clientSecret` immediately — it will not be shown again.**
|
||||
headers:
|
||||
X-RateLimit-Limit:
|
||||
schema:
|
||||
type: integer
|
||||
example: 100
|
||||
X-RateLimit-Remaining:
|
||||
schema:
|
||||
type: integer
|
||||
example: 99
|
||||
X-RateLimit-Reset:
|
||||
schema:
|
||||
type: integer
|
||||
example: 1743155400
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/CredentialWithSecret'
|
||||
example:
|
||||
credentialId: "c9d8e7f6-a5b4-3210-fedc-ba9876543210"
|
||||
clientId: "a1b2c3d4-e5f6-7890-abcd-ef1234567890"
|
||||
clientSecret: "sk_live_7f3a2b1c9d8e4f0a6b5c3d2e1f0a9b8c"
|
||||
status: "active"
|
||||
createdAt: "2026-03-28T09:00:00.000Z"
|
||||
expiresAt: "2027-03-28T09:00:00.000Z"
|
||||
revokedAt: null
|
||||
'400':
|
||||
description: Invalid request body.
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/ErrorResponse'
|
||||
example:
|
||||
code: "VALIDATION_ERROR"
|
||||
message: "Request validation failed."
|
||||
details:
|
||||
field: "expiresAt"
|
||||
reason: "expiresAt must be a future date-time."
|
||||
'401':
|
||||
$ref: '#/components/responses/Unauthorized'
|
||||
'403':
|
||||
description: Insufficient permissions or agent is not active.
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/ErrorResponse'
|
||||
examples:
|
||||
forbidden:
|
||||
summary: Insufficient permissions
|
||||
value:
|
||||
code: "FORBIDDEN"
|
||||
message: "You do not have permission to manage credentials for this agent."
|
||||
agentNotActive:
|
||||
summary: Agent not in active status
|
||||
value:
|
||||
code: "AGENT_NOT_ACTIVE"
|
||||
message: "Credentials can only be generated for active agents."
|
||||
details:
|
||||
agentId: "a1b2c3d4-e5f6-7890-abcd-ef1234567890"
|
||||
status: "suspended"
|
||||
'404':
|
||||
$ref: '#/components/responses/AgentNotFound'
|
||||
'429':
|
||||
$ref: '#/components/responses/TooManyRequests'
|
||||
'500':
|
||||
$ref: '#/components/responses/InternalServerError'
|
||||
|
||||
get:
|
||||
operationId: listCredentials
|
||||
tags:
|
||||
- Credential Management
|
||||
summary: List credentials for an agent
|
||||
description: |
|
||||
Returns a paginated list of all credentials (active and revoked) for the
|
||||
specified agent. The `clientSecret` is **never** returned in list responses.
|
||||
|
||||
Results are ordered by `createdAt` descending (most recent first).
|
||||
parameters:
|
||||
- name: page
|
||||
in: query
|
||||
description: Page number (1-based). Defaults to `1`.
|
||||
required: false
|
||||
schema:
|
||||
type: integer
|
||||
minimum: 1
|
||||
default: 1
|
||||
example: 1
|
||||
- name: limit
|
||||
in: query
|
||||
description: Number of results per page. Defaults to `20`, maximum `100`.
|
||||
required: false
|
||||
schema:
|
||||
type: integer
|
||||
minimum: 1
|
||||
maximum: 100
|
||||
default: 20
|
||||
example: 20
|
||||
- name: status
|
||||
in: query
|
||||
description: Filter credentials by status.
|
||||
required: false
|
||||
schema:
|
||||
$ref: '#/components/schemas/CredentialStatus'
|
||||
responses:
|
||||
'200':
|
||||
description: Credential list returned successfully.
|
||||
headers:
|
||||
X-RateLimit-Limit:
|
||||
schema:
|
||||
type: integer
|
||||
example: 100
|
||||
X-RateLimit-Remaining:
|
||||
schema:
|
||||
type: integer
|
||||
example: 98
|
||||
X-RateLimit-Reset:
|
||||
schema:
|
||||
type: integer
|
||||
example: 1743155400
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/PaginatedCredentialsResponse'
|
||||
example:
|
||||
data:
|
||||
- credentialId: "c9d8e7f6-a5b4-3210-fedc-ba9876543210"
|
||||
clientId: "a1b2c3d4-e5f6-7890-abcd-ef1234567890"
|
||||
status: "active"
|
||||
createdAt: "2026-03-28T09:00:00.000Z"
|
||||
expiresAt: "2027-03-28T09:00:00.000Z"
|
||||
revokedAt: null
|
||||
- credentialId: "d8e7f6a5-b4c3-2109-edcb-a98765432109"
|
||||
clientId: "a1b2c3d4-e5f6-7890-abcd-ef1234567890"
|
||||
status: "revoked"
|
||||
createdAt: "2026-01-15T08:00:00.000Z"
|
||||
expiresAt: null
|
||||
revokedAt: "2026-03-28T08:59:00.000Z"
|
||||
total: 2
|
||||
page: 1
|
||||
limit: 20
|
||||
'400':
|
||||
description: Invalid query parameters.
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/ErrorResponse'
|
||||
example:
|
||||
code: "VALIDATION_ERROR"
|
||||
message: "Invalid query parameter value."
|
||||
details:
|
||||
field: "status"
|
||||
reason: "Must be 'active' or 'revoked'."
|
||||
'401':
|
||||
$ref: '#/components/responses/Unauthorized'
|
||||
'403':
|
||||
$ref: '#/components/responses/Forbidden'
|
||||
'404':
|
||||
$ref: '#/components/responses/AgentNotFound'
|
||||
'429':
|
||||
$ref: '#/components/responses/TooManyRequests'
|
||||
'500':
|
||||
$ref: '#/components/responses/InternalServerError'
|
||||
|
||||
/agents/{agentId}/credentials/{credentialId}/rotate:
|
||||
parameters:
|
||||
- name: agentId
|
||||
in: path
|
||||
description: The unique UUID identifier of the agent.
|
||||
required: true
|
||||
schema:
|
||||
type: string
|
||||
format: uuid
|
||||
example: "a1b2c3d4-e5f6-7890-abcd-ef1234567890"
|
||||
- name: credentialId
|
||||
in: path
|
||||
description: The unique UUID identifier of the credential to rotate.
|
||||
required: true
|
||||
schema:
|
||||
type: string
|
||||
format: uuid
|
||||
example: "c9d8e7f6-a5b4-3210-fedc-ba9876543210"
|
||||
|
||||
post:
|
||||
operationId: rotateCredential
|
||||
tags:
|
||||
- Credential Management
|
||||
summary: Rotate a credential
|
||||
description: |
|
||||
Rotates an existing credential by:
|
||||
1. Immediately revoking the current `client_secret`.
|
||||
2. Generating and returning a new `client_secret` for the same `credentialId`.
|
||||
|
||||
The `credentialId` remains the same after rotation; only the secret changes.
|
||||
The new `clientSecret` is returned **once only** and must be stored securely.
|
||||
|
||||
**Use case**: Periodic secret rotation or emergency rotation after
|
||||
credential compromise.
|
||||
|
||||
Only `active` credentials can be rotated. Attempting to rotate a `revoked`
|
||||
credential returns `409 Conflict`.
|
||||
requestBody:
|
||||
required: false
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/GenerateCredentialRequest'
|
||||
example:
|
||||
expiresAt: "2028-03-28T09:00:00.000Z"
|
||||
responses:
|
||||
'200':
|
||||
description: |
|
||||
Credential rotated successfully.
|
||||
**Save the new `clientSecret` immediately — it will not be shown again.**
|
||||
The previous secret is permanently invalidated.
|
||||
headers:
|
||||
X-RateLimit-Limit:
|
||||
schema:
|
||||
type: integer
|
||||
example: 100
|
||||
X-RateLimit-Remaining:
|
||||
schema:
|
||||
type: integer
|
||||
example: 97
|
||||
X-RateLimit-Reset:
|
||||
schema:
|
||||
type: integer
|
||||
example: 1743155400
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/CredentialWithSecret'
|
||||
example:
|
||||
credentialId: "c9d8e7f6-a5b4-3210-fedc-ba9876543210"
|
||||
clientId: "a1b2c3d4-e5f6-7890-abcd-ef1234567890"
|
||||
clientSecret: "sk_live_9a8b7c6d5e4f3a2b1c0d9e8f7a6b5c4d"
|
||||
status: "active"
|
||||
createdAt: "2026-03-28T09:00:00.000Z"
|
||||
expiresAt: "2028-03-28T09:00:00.000Z"
|
||||
revokedAt: null
|
||||
'400':
|
||||
description: Invalid request body.
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/ErrorResponse'
|
||||
example:
|
||||
code: "VALIDATION_ERROR"
|
||||
message: "Request validation failed."
|
||||
details:
|
||||
field: "expiresAt"
|
||||
reason: "expiresAt must be a future date-time."
|
||||
'401':
|
||||
$ref: '#/components/responses/Unauthorized'
|
||||
'403':
|
||||
$ref: '#/components/responses/Forbidden'
|
||||
'404':
|
||||
description: Agent or credential not found.
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/ErrorResponse'
|
||||
examples:
|
||||
agentNotFound:
|
||||
summary: Agent not found
|
||||
value:
|
||||
code: "AGENT_NOT_FOUND"
|
||||
message: "Agent with the specified ID was not found."
|
||||
credentialNotFound:
|
||||
summary: Credential not found
|
||||
value:
|
||||
code: "CREDENTIAL_NOT_FOUND"
|
||||
message: "Credential with the specified ID was not found."
|
||||
'409':
|
||||
description: Credential is already revoked and cannot be rotated.
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/ErrorResponse'
|
||||
example:
|
||||
code: "CREDENTIAL_ALREADY_REVOKED"
|
||||
message: "Revoked credentials cannot be rotated. Generate a new credential instead."
|
||||
details:
|
||||
credentialId: "c9d8e7f6-a5b4-3210-fedc-ba9876543210"
|
||||
revokedAt: "2026-03-20T10:00:00.000Z"
|
||||
'429':
|
||||
$ref: '#/components/responses/TooManyRequests'
|
||||
'500':
|
||||
$ref: '#/components/responses/InternalServerError'
|
||||
|
||||
/agents/{agentId}/credentials/{credentialId}:
|
||||
parameters:
|
||||
- name: agentId
|
||||
in: path
|
||||
description: The unique UUID identifier of the agent.
|
||||
required: true
|
||||
schema:
|
||||
type: string
|
||||
format: uuid
|
||||
example: "a1b2c3d4-e5f6-7890-abcd-ef1234567890"
|
||||
- name: credentialId
|
||||
in: path
|
||||
description: The unique UUID identifier of the credential to revoke.
|
||||
required: true
|
||||
schema:
|
||||
type: string
|
||||
format: uuid
|
||||
example: "c9d8e7f6-a5b4-3210-fedc-ba9876543210"
|
||||
|
||||
delete:
|
||||
operationId: revokeCredential
|
||||
tags:
|
||||
- Credential Management
|
||||
summary: Revoke a credential
|
||||
description: |
|
||||
Permanently revokes a credential, immediately preventing it from being
|
||||
used to obtain new tokens.
|
||||
|
||||
**Effects of revocation**:
|
||||
- The credential's status is set to `revoked`.
|
||||
- Any tokens issued using this credential remain valid until they expire
|
||||
naturally (token revocation is handled separately via `POST /token/revoke`).
|
||||
- The credential record is retained for audit purposes.
|
||||
- This operation is **irreversible** — a revoked credential cannot be re-activated.
|
||||
|
||||
Revoking an already-revoked credential returns `409 Conflict`.
|
||||
responses:
|
||||
'204':
|
||||
description: Credential revoked successfully. No response body.
|
||||
headers:
|
||||
X-RateLimit-Limit:
|
||||
schema:
|
||||
type: integer
|
||||
example: 100
|
||||
X-RateLimit-Remaining:
|
||||
schema:
|
||||
type: integer
|
||||
example: 96
|
||||
X-RateLimit-Reset:
|
||||
schema:
|
||||
type: integer
|
||||
example: 1743155400
|
||||
'401':
|
||||
$ref: '#/components/responses/Unauthorized'
|
||||
'403':
|
||||
$ref: '#/components/responses/Forbidden'
|
||||
'404':
|
||||
description: Agent or credential not found.
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/ErrorResponse'
|
||||
examples:
|
||||
agentNotFound:
|
||||
summary: Agent not found
|
||||
value:
|
||||
code: "AGENT_NOT_FOUND"
|
||||
message: "Agent with the specified ID was not found."
|
||||
credentialNotFound:
|
||||
summary: Credential not found
|
||||
value:
|
||||
code: "CREDENTIAL_NOT_FOUND"
|
||||
message: "Credential with the specified ID was not found."
|
||||
'409':
|
||||
description: Credential is already revoked.
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/ErrorResponse'
|
||||
example:
|
||||
code: "CREDENTIAL_ALREADY_REVOKED"
|
||||
message: "This credential has already been revoked."
|
||||
details:
|
||||
credentialId: "c9d8e7f6-a5b4-3210-fedc-ba9876543210"
|
||||
revokedAt: "2026-03-20T10:00:00.000Z"
|
||||
'429':
|
||||
$ref: '#/components/responses/TooManyRequests'
|
||||
'500':
|
||||
$ref: '#/components/responses/InternalServerError'
|
||||
586
docs/openapi/oauth2-token.yaml
Normal file
586
docs/openapi/oauth2-token.yaml
Normal file
@@ -0,0 +1,586 @@
|
||||
openapi: 3.0.3
|
||||
|
||||
info:
|
||||
title: SentryAgent.ai — OAuth 2.0 Token Service
|
||||
version: 1.0.0
|
||||
description: |
|
||||
The OAuth 2.0 Token Service provides agent authentication via the
|
||||
**Client Credentials grant** (RFC 6749 Section 4.4). It issues signed JWT
|
||||
access tokens, supports token introspection (RFC 7662), and token revocation
|
||||
(RFC 7009).
|
||||
|
||||
Agents authenticate using their `client_id` (= `agentId`) and
|
||||
`client_secret` obtained during credential provisioning.
|
||||
|
||||
**Supported Grant Type**: `client_credentials` only. All other grant types
|
||||
are rejected with `unsupported_grant_type`.
|
||||
|
||||
**Token Lifetime**: 3600 seconds (1 hour) by default.
|
||||
|
||||
**Scopes**:
|
||||
| Scope | Description |
|
||||
|-------|-------------|
|
||||
| `agents:read` | Read agent identity records |
|
||||
| `agents:write` | Create, update, and deactivate agent records |
|
||||
| `tokens:read` | Introspect tokens |
|
||||
| `audit:read` | Query the audit log |
|
||||
|
||||
**Rate Limit**: 100 requests/minute per `client_id`.
|
||||
|
||||
**Free Tier**: 10,000 token requests per month.
|
||||
|
||||
servers:
|
||||
- url: http://localhost:3000/api/v1
|
||||
description: Local development server
|
||||
- url: https://api.sentryagent.ai/v1
|
||||
description: Production server
|
||||
|
||||
tags:
|
||||
- name: OAuth 2.0 Tokens
|
||||
description: Token issuance, introspection, and revocation
|
||||
|
||||
components:
|
||||
securitySchemes:
|
||||
BearerAuth:
|
||||
type: http
|
||||
scheme: bearer
|
||||
bearerFormat: JWT
|
||||
description: |
|
||||
JWT access token obtained via `POST /token`.
|
||||
Required for `/token/introspect` and `/token/revoke`.
|
||||
|
||||
BasicAuth:
|
||||
type: http
|
||||
scheme: basic
|
||||
description: |
|
||||
HTTP Basic authentication using `client_id` as the username and
|
||||
`client_secret` as the password. Used as an alternative credential
|
||||
method for token endpoint requests (in addition to request body).
|
||||
|
||||
schemas:
|
||||
GrantType:
|
||||
type: string
|
||||
description: OAuth 2.0 grant type. Only `client_credentials` is supported.
|
||||
enum:
|
||||
- client_credentials
|
||||
example: client_credentials
|
||||
|
||||
Scope:
|
||||
type: string
|
||||
description: |
|
||||
Space-separated list of requested OAuth 2.0 scopes.
|
||||
Available scopes: `agents:read`, `agents:write`, `tokens:read`, `audit:read`.
|
||||
pattern: '^(agents:read|agents:write|tokens:read|audit:read)(\s(agents:read|agents:write|tokens:read|audit:read))*$'
|
||||
example: "agents:read agents:write"
|
||||
|
||||
TokenRequest:
|
||||
type: object
|
||||
description: |
|
||||
OAuth 2.0 Client Credentials token request body.
|
||||
Credentials may be provided in the request body (as `client_id` +
|
||||
`client_secret`) or via HTTP Basic authentication header.
|
||||
required:
|
||||
- grant_type
|
||||
properties:
|
||||
grant_type:
|
||||
$ref: '#/components/schemas/GrantType'
|
||||
client_id:
|
||||
type: string
|
||||
format: uuid
|
||||
description: >
|
||||
The agent's `agentId` (UUID). Required if not using HTTP Basic auth.
|
||||
example: "a1b2c3d4-e5f6-7890-abcd-ef1234567890"
|
||||
client_secret:
|
||||
type: string
|
||||
description: >
|
||||
The agent's client secret. Required if not using HTTP Basic auth.
|
||||
Treated as a sensitive value — never logged or stored in plain text.
|
||||
format: password
|
||||
example: "sk_live_7f3a2b1c9d8e4f0a6b5c3d2e1f0a9b8c"
|
||||
scope:
|
||||
$ref: '#/components/schemas/Scope'
|
||||
|
||||
TokenResponse:
|
||||
type: object
|
||||
description: Successful OAuth 2.0 token response.
|
||||
required:
|
||||
- access_token
|
||||
- token_type
|
||||
- expires_in
|
||||
- scope
|
||||
properties:
|
||||
access_token:
|
||||
type: string
|
||||
description: >
|
||||
Signed JWT access token. Include this value in the `Authorization`
|
||||
header as `Bearer <access_token>` when calling other API endpoints.
|
||||
example: "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJhMWIyYzNkNC1lNWY2LTc4OTAtYWJjZC1lZjEyMzQ1Njc4OTAiLCJjbGllbnRfaWQiOiJhMWIyYzNkNC1lNWY2LTc4OTAtYWJjZC1lZjEyMzQ1Njc4OTAiLCJzY29wZSI6ImFnZW50czpyZWFkIGFnZW50czp3cml0ZSIsImlhdCI6MTc0MzE1MTIwMCwiZXhwIjoxNzQzMTU0ODAwfQ.signature"
|
||||
token_type:
|
||||
type: string
|
||||
description: Token type. Always `Bearer`.
|
||||
enum:
|
||||
- Bearer
|
||||
example: "Bearer"
|
||||
expires_in:
|
||||
type: integer
|
||||
description: Token lifetime in seconds from the time of issuance. Default is `3600`.
|
||||
example: 3600
|
||||
scope:
|
||||
type: string
|
||||
description: Space-separated list of scopes granted by this token.
|
||||
example: "agents:read agents:write"
|
||||
|
||||
OAuth2ErrorResponse:
|
||||
type: object
|
||||
description: |
|
||||
OAuth 2.0 error response as defined in RFC 6749 Section 5.2.
|
||||
Used exclusively for token endpoint errors.
|
||||
required:
|
||||
- error
|
||||
- error_description
|
||||
properties:
|
||||
error:
|
||||
type: string
|
||||
description: >
|
||||
Machine-readable OAuth 2.0 error code.
|
||||
enum:
|
||||
- invalid_request
|
||||
- invalid_client
|
||||
- invalid_grant
|
||||
- unauthorized_client
|
||||
- unsupported_grant_type
|
||||
- invalid_scope
|
||||
example: "invalid_client"
|
||||
error_description:
|
||||
type: string
|
||||
description: Human-readable description of the error.
|
||||
example: "Client authentication failed. Invalid client_id or client_secret."
|
||||
|
||||
IntrospectRequest:
|
||||
type: object
|
||||
description: Token introspection request (RFC 7662).
|
||||
required:
|
||||
- token
|
||||
properties:
|
||||
token:
|
||||
type: string
|
||||
description: The token to introspect.
|
||||
example: "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJhMWIyYzNkNC1lNWY2LTc4OTAtYWJjZC1lZjEyMzQ1Njc4OTAifQ.signature"
|
||||
token_type_hint:
|
||||
type: string
|
||||
description: >
|
||||
Optional hint about the type of token being introspected.
|
||||
Currently only `access_token` is supported.
|
||||
enum:
|
||||
- access_token
|
||||
example: "access_token"
|
||||
|
||||
IntrospectResponse:
|
||||
type: object
|
||||
description: |
|
||||
Token introspection response (RFC 7662).
|
||||
When `active` is `false`, no other fields are guaranteed to be present.
|
||||
required:
|
||||
- active
|
||||
properties:
|
||||
active:
|
||||
type: boolean
|
||||
description: >
|
||||
Whether the token is currently active (valid, not expired, not revoked).
|
||||
example: true
|
||||
sub:
|
||||
type: string
|
||||
format: uuid
|
||||
description: Subject — the `agentId` the token was issued for.
|
||||
example: "a1b2c3d4-e5f6-7890-abcd-ef1234567890"
|
||||
client_id:
|
||||
type: string
|
||||
format: uuid
|
||||
description: The `client_id` (agentId) that requested the token.
|
||||
example: "a1b2c3d4-e5f6-7890-abcd-ef1234567890"
|
||||
scope:
|
||||
type: string
|
||||
description: Space-separated list of scopes granted by this token.
|
||||
example: "agents:read agents:write"
|
||||
token_type:
|
||||
type: string
|
||||
description: Token type. Always `Bearer` for active tokens.
|
||||
example: "Bearer"
|
||||
iat:
|
||||
type: integer
|
||||
description: Unix timestamp (seconds) when the token was issued.
|
||||
example: 1743151200
|
||||
exp:
|
||||
type: integer
|
||||
description: Unix timestamp (seconds) when the token expires.
|
||||
example: 1743154800
|
||||
|
||||
RevokeRequest:
|
||||
type: object
|
||||
description: Token revocation request (RFC 7009).
|
||||
required:
|
||||
- token
|
||||
properties:
|
||||
token:
|
||||
type: string
|
||||
description: The token to revoke.
|
||||
example: "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJhMWIyYzNkNC1lNWY2LTc4OTAtYWJjZC1lZjEyMzQ1Njc4OTAifQ.signature"
|
||||
token_type_hint:
|
||||
type: string
|
||||
description: Optional hint about the token type.
|
||||
enum:
|
||||
- access_token
|
||||
example: "access_token"
|
||||
|
||||
ErrorResponse:
|
||||
type: object
|
||||
description: Standard error response envelope used across all SentryAgent.ai APIs.
|
||||
required:
|
||||
- code
|
||||
- message
|
||||
properties:
|
||||
code:
|
||||
type: string
|
||||
description: Machine-readable error code.
|
||||
example: "UNAUTHORIZED"
|
||||
message:
|
||||
type: string
|
||||
description: Human-readable description of the error.
|
||||
example: "A valid Bearer token is required."
|
||||
details:
|
||||
type: object
|
||||
description: Optional structured details providing additional context.
|
||||
additionalProperties: true
|
||||
example: {}
|
||||
|
||||
responses:
|
||||
Unauthorized:
|
||||
description: Missing or invalid Bearer token.
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/ErrorResponse'
|
||||
example:
|
||||
code: "UNAUTHORIZED"
|
||||
message: "A valid Bearer token is required to access this resource."
|
||||
|
||||
TooManyRequests:
|
||||
description: Rate limit exceeded. Retry after the reset time.
|
||||
headers:
|
||||
X-RateLimit-Limit:
|
||||
schema:
|
||||
type: integer
|
||||
description: Maximum requests allowed per minute.
|
||||
example: 100
|
||||
X-RateLimit-Remaining:
|
||||
schema:
|
||||
type: integer
|
||||
description: Requests remaining in the current window.
|
||||
example: 0
|
||||
X-RateLimit-Reset:
|
||||
schema:
|
||||
type: integer
|
||||
description: Unix timestamp when the rate limit window resets.
|
||||
example: 1743155400
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/ErrorResponse'
|
||||
example:
|
||||
code: "RATE_LIMIT_EXCEEDED"
|
||||
message: "Too many requests. Please retry after the rate limit window resets."
|
||||
|
||||
InternalServerError:
|
||||
description: Unexpected server error.
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/ErrorResponse'
|
||||
example:
|
||||
code: "INTERNAL_SERVER_ERROR"
|
||||
message: "An unexpected error occurred. Please try again later."
|
||||
|
||||
paths:
|
||||
/token:
|
||||
post:
|
||||
operationId: issueToken
|
||||
tags:
|
||||
- OAuth 2.0 Tokens
|
||||
summary: Issue an access token (Client Credentials)
|
||||
description: |
|
||||
Issues a signed JWT access token for an agent using the OAuth 2.0
|
||||
**Client Credentials grant** (RFC 6749 §4.4).
|
||||
|
||||
The agent authenticates by providing its `client_id` (agentId) and
|
||||
`client_secret`. Credentials may be passed either:
|
||||
- In the **request body** (`client_id` + `client_secret` fields), or
|
||||
- Via **HTTP Basic authentication** header (username = `client_id`, password = `client_secret`).
|
||||
|
||||
The token is a signed JWT containing the agent's identity claims.
|
||||
Use it as a `Bearer` token on subsequent API calls.
|
||||
|
||||
**Free Tier Limit**: 10,000 token requests per month. Exceeding this
|
||||
returns `403` with `FREE_TIER_LIMIT_EXCEEDED`.
|
||||
requestBody:
|
||||
required: true
|
||||
content:
|
||||
application/x-www-form-urlencoded:
|
||||
schema:
|
||||
$ref: '#/components/schemas/TokenRequest'
|
||||
example:
|
||||
grant_type: client_credentials
|
||||
client_id: "a1b2c3d4-e5f6-7890-abcd-ef1234567890"
|
||||
client_secret: "sk_live_7f3a2b1c9d8e4f0a6b5c3d2e1f0a9b8c"
|
||||
scope: "agents:read agents:write"
|
||||
responses:
|
||||
'200':
|
||||
description: Access token issued successfully.
|
||||
headers:
|
||||
X-RateLimit-Limit:
|
||||
schema:
|
||||
type: integer
|
||||
example: 100
|
||||
X-RateLimit-Remaining:
|
||||
schema:
|
||||
type: integer
|
||||
example: 99
|
||||
X-RateLimit-Reset:
|
||||
schema:
|
||||
type: integer
|
||||
example: 1743155400
|
||||
Cache-Control:
|
||||
schema:
|
||||
type: string
|
||||
description: Token responses must not be cached.
|
||||
example: "no-store"
|
||||
Pragma:
|
||||
schema:
|
||||
type: string
|
||||
example: "no-cache"
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/TokenResponse'
|
||||
example:
|
||||
access_token: "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJhMWIyYzNkNC1lNWY2LTc4OTAtYWJjZC1lZjEyMzQ1Njc4OTAiLCJjbGllbnRfaWQiOiJhMWIyYzNkNC1lNWY2LTc4OTAtYWJjZC1lZjEyMzQ1Njc4OTAiLCJzY29wZSI6ImFnZW50czpyZWFkIGFnZW50czp3cml0ZSIsImlhdCI6MTc0MzE1MTIwMCwiZXhwIjoxNzQzMTU0ODAwfQ.signature"
|
||||
token_type: "Bearer"
|
||||
expires_in: 3600
|
||||
scope: "agents:read agents:write"
|
||||
'400':
|
||||
description: Malformed or missing required request parameters.
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/OAuth2ErrorResponse'
|
||||
examples:
|
||||
missingGrantType:
|
||||
summary: Missing grant_type
|
||||
value:
|
||||
error: "invalid_request"
|
||||
error_description: "The 'grant_type' parameter is required."
|
||||
invalidScope:
|
||||
summary: Invalid scope requested
|
||||
value:
|
||||
error: "invalid_scope"
|
||||
error_description: "Requested scope 'admin:all' is not available."
|
||||
unsupportedGrantType:
|
||||
summary: Unsupported grant type
|
||||
value:
|
||||
error: "unsupported_grant_type"
|
||||
error_description: "Only 'client_credentials' grant type is supported."
|
||||
'401':
|
||||
description: Client authentication failed. Invalid `client_id` or `client_secret`.
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/OAuth2ErrorResponse'
|
||||
example:
|
||||
error: "invalid_client"
|
||||
error_description: "Client authentication failed. Invalid client_id or client_secret."
|
||||
'403':
|
||||
description: >
|
||||
Client is not authorised to request a token. May indicate the agent
|
||||
is suspended, decommissioned, or the free tier monthly limit has been reached.
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/OAuth2ErrorResponse'
|
||||
examples:
|
||||
agentSuspended:
|
||||
summary: Agent is suspended
|
||||
value:
|
||||
error: "unauthorized_client"
|
||||
error_description: "Agent is currently suspended and cannot obtain tokens."
|
||||
freeTierLimit:
|
||||
summary: Monthly token limit reached
|
||||
value:
|
||||
error: "unauthorized_client"
|
||||
error_description: "Free tier monthly token limit of 10,000 requests has been reached."
|
||||
'429':
|
||||
$ref: '#/components/responses/TooManyRequests'
|
||||
'500':
|
||||
$ref: '#/components/responses/InternalServerError'
|
||||
|
||||
/token/introspect:
|
||||
post:
|
||||
operationId: introspectToken
|
||||
tags:
|
||||
- OAuth 2.0 Tokens
|
||||
summary: Introspect a token (RFC 7662)
|
||||
description: |
|
||||
Determines whether a given access token is currently active (valid,
|
||||
not expired, not revoked). Returns the token's metadata if active.
|
||||
|
||||
Compliant with RFC 7662 (OAuth 2.0 Token Introspection).
|
||||
|
||||
The caller must present a valid Bearer token with `tokens:read` scope
|
||||
to use this endpoint.
|
||||
security:
|
||||
- BearerAuth: []
|
||||
requestBody:
|
||||
required: true
|
||||
content:
|
||||
application/x-www-form-urlencoded:
|
||||
schema:
|
||||
$ref: '#/components/schemas/IntrospectRequest'
|
||||
example:
|
||||
token: "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJhMWIyYzNkNC1lNWY2LTc4OTAtYWJjZC1lZjEyMzQ1Njc4OTAifQ.signature"
|
||||
token_type_hint: "access_token"
|
||||
responses:
|
||||
'200':
|
||||
description: |
|
||||
Token introspection result. Note: a `200` response is returned even
|
||||
for inactive tokens — check the `active` field to determine token validity.
|
||||
headers:
|
||||
X-RateLimit-Limit:
|
||||
schema:
|
||||
type: integer
|
||||
example: 100
|
||||
X-RateLimit-Remaining:
|
||||
schema:
|
||||
type: integer
|
||||
example: 98
|
||||
X-RateLimit-Reset:
|
||||
schema:
|
||||
type: integer
|
||||
example: 1743155400
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/IntrospectResponse'
|
||||
examples:
|
||||
activeToken:
|
||||
summary: Active token
|
||||
value:
|
||||
active: true
|
||||
sub: "a1b2c3d4-e5f6-7890-abcd-ef1234567890"
|
||||
client_id: "a1b2c3d4-e5f6-7890-abcd-ef1234567890"
|
||||
scope: "agents:read agents:write"
|
||||
token_type: "Bearer"
|
||||
iat: 1743151200
|
||||
exp: 1743154800
|
||||
inactiveToken:
|
||||
summary: Inactive (expired or revoked) token
|
||||
value:
|
||||
active: false
|
||||
'400':
|
||||
description: Missing or malformed `token` parameter.
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/ErrorResponse'
|
||||
example:
|
||||
code: "VALIDATION_ERROR"
|
||||
message: "The 'token' parameter is required."
|
||||
'401':
|
||||
$ref: '#/components/responses/Unauthorized'
|
||||
'403':
|
||||
description: Caller's token does not have the `tokens:read` scope.
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/ErrorResponse'
|
||||
example:
|
||||
code: "INSUFFICIENT_SCOPE"
|
||||
message: "The 'tokens:read' scope is required to introspect tokens."
|
||||
'429':
|
||||
$ref: '#/components/responses/TooManyRequests'
|
||||
'500':
|
||||
$ref: '#/components/responses/InternalServerError'
|
||||
|
||||
/token/revoke:
|
||||
post:
|
||||
operationId: revokeToken
|
||||
tags:
|
||||
- OAuth 2.0 Tokens
|
||||
summary: Revoke a token (RFC 7009)
|
||||
description: |
|
||||
Revokes an access token, immediately invalidating it for all subsequent
|
||||
requests. Compliant with RFC 7009 (OAuth 2.0 Token Revocation).
|
||||
|
||||
Revoking an already-revoked or expired token is considered a success
|
||||
(idempotent operation per RFC 7009 §2.1).
|
||||
|
||||
The caller must present a valid Bearer token to revoke another token.
|
||||
An agent may revoke its own tokens; admin scope is required to revoke
|
||||
tokens belonging to other agents.
|
||||
security:
|
||||
- BearerAuth: []
|
||||
requestBody:
|
||||
required: true
|
||||
content:
|
||||
application/x-www-form-urlencoded:
|
||||
schema:
|
||||
$ref: '#/components/schemas/RevokeRequest'
|
||||
example:
|
||||
token: "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJhMWIyYzNkNC1lNWY2LTc4OTAtYWJjZC1lZjEyMzQ1Njc4OTAifQ.signature"
|
||||
token_type_hint: "access_token"
|
||||
responses:
|
||||
'200':
|
||||
description: |
|
||||
Token revoked successfully (or was already inactive).
|
||||
Per RFC 7009, revocation always returns `200` for any valid request,
|
||||
even if the token was already revoked or expired.
|
||||
headers:
|
||||
X-RateLimit-Limit:
|
||||
schema:
|
||||
type: integer
|
||||
example: 100
|
||||
X-RateLimit-Remaining:
|
||||
schema:
|
||||
type: integer
|
||||
example: 97
|
||||
X-RateLimit-Reset:
|
||||
schema:
|
||||
type: integer
|
||||
example: 1743155400
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
type: object
|
||||
properties: {}
|
||||
example: {}
|
||||
'400':
|
||||
description: Missing or malformed `token` parameter.
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/ErrorResponse'
|
||||
example:
|
||||
code: "VALIDATION_ERROR"
|
||||
message: "The 'token' parameter is required."
|
||||
'401':
|
||||
$ref: '#/components/responses/Unauthorized'
|
||||
'403':
|
||||
description: Insufficient permissions to revoke this token.
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/ErrorResponse'
|
||||
example:
|
||||
code: "FORBIDDEN"
|
||||
message: "You do not have permission to revoke this token."
|
||||
'429':
|
||||
$ref: '#/components/responses/TooManyRequests'
|
||||
'500':
|
||||
$ref: '#/components/responses/InternalServerError'
|
||||
37
jest.config.ts
Normal file
37
jest.config.ts
Normal file
@@ -0,0 +1,37 @@
|
||||
import type { Config } from 'jest';
|
||||
|
||||
const config: Config = {
|
||||
preset: 'ts-jest',
|
||||
testEnvironment: 'node',
|
||||
roots: ['<rootDir>/tests'],
|
||||
testMatch: ['**/*.test.ts'],
|
||||
transform: {
|
||||
'^.+\\.ts$': ['ts-jest', {
|
||||
tsconfig: {
|
||||
strict: true,
|
||||
noImplicitAny: true,
|
||||
strictNullChecks: true,
|
||||
},
|
||||
}],
|
||||
},
|
||||
moduleNameMapper: {
|
||||
'^(\\.{1,2}/.*)\\.js$': '$1',
|
||||
},
|
||||
collectCoverageFrom: [
|
||||
'src/**/*.ts',
|
||||
'!src/server.ts',
|
||||
'!src/db/migrations/**',
|
||||
],
|
||||
coverageThreshold: {
|
||||
global: {
|
||||
branches: 80,
|
||||
functions: 80,
|
||||
lines: 80,
|
||||
statements: 80,
|
||||
},
|
||||
},
|
||||
coverageReporters: ['text', 'lcov', 'html'],
|
||||
testTimeout: 30000,
|
||||
};
|
||||
|
||||
export default config;
|
||||
@@ -0,0 +1,2 @@
|
||||
schema: spec-driven
|
||||
created: 2026-03-28
|
||||
@@ -0,0 +1,13 @@
|
||||
## Context
|
||||
AGNTCY is the Linux Foundation open standard for AI agent identity, interoperability, and governance. AgentIdP implements the non-human identity model defined by AGNTCY. This document makes that alignment explicit and verifiable.
|
||||
|
||||
## Goals
|
||||
- Engineers and architects can verify AGNTCY compliance without reading the full standard
|
||||
- The mapping is explicit: each AGNTCY concept is matched to a specific AgentIdP API feature
|
||||
- Both compliant and pending/out-of-scope items are documented honestly
|
||||
|
||||
## Folder: docs/agntcy/
|
||||
Separate from developers/ and devops/ — this is a standards alignment reference, not a how-to guide.
|
||||
|
||||
## Open Questions
|
||||
*(none)*
|
||||
@@ -0,0 +1,11 @@
|
||||
## Why
|
||||
AGNTCY alignment documentation is a Phase 1 P1 deliverable. SentryAgent.ai positions itself as AGNTCY-compliant, but there is no document explaining what AGNTCY is, how AgentIdP maps to its model, and what that means for developers and operators adopting the platform.
|
||||
|
||||
## What Changes
|
||||
- New `docs/agntcy/` folder
|
||||
- `alignment.md` — formal mapping of AgentIdP concepts to AGNTCY standard concepts
|
||||
- `README.md` — entry point explaining what AGNTCY is and why it matters
|
||||
|
||||
## What Does Not Change
|
||||
- No source code changes
|
||||
- No API changes
|
||||
@@ -0,0 +1,4 @@
|
||||
## ADDED Requirements
|
||||
|
||||
### Requirement: AGNTCY alignment docs exist at docs/agntcy/
|
||||
The system SHALL provide documentation in `docs/agntcy/` explaining the AGNTCY standard and how AgentIdP implements its non-human identity model, with explicit feature-by-feature mapping.
|
||||
@@ -0,0 +1,17 @@
|
||||
## 1. docs/agntcy/README.md
|
||||
|
||||
- [x] 1.1 Write intro: what AGNTCY is (Linux Foundation, AI agent interoperability standard)
|
||||
- [x] 1.2 Write why it matters: standardised agent identity, cross-system interoperability
|
||||
- [x] 1.3 Link to alignment.md
|
||||
|
||||
## 2. docs/agntcy/alignment.md
|
||||
|
||||
- [x] 2.1 Write AGNTCY core concepts section: non-human identity, agent registry, credential management, lifecycle, audit
|
||||
- [x] 2.2 Write AgentIdP implementation mapping table: each AGNTCY concept → AgentIdP feature → API endpoint
|
||||
- [x] 2.3 Write compliance status section: what is implemented (Phase 1), what is pending (Phase 2+)
|
||||
- [x] 2.4 Write interoperability section: how AgentIdP-registered agents can be identified by other AGNTCY-compliant systems
|
||||
|
||||
## 3. QA
|
||||
|
||||
- [x] 3.1 Verify all API endpoints referenced in the mapping table exist
|
||||
- [x] 3.2 Verify compliance status is honest — no overclaiming
|
||||
@@ -0,0 +1,2 @@
|
||||
schema: spec-driven
|
||||
created: 2026-03-28
|
||||
13
openspec/changes/archive/2026-03-28-dockerfile/design.md
Normal file
13
openspec/changes/archive/2026-03-28-dockerfile/design.md
Normal file
@@ -0,0 +1,13 @@
|
||||
## Context
|
||||
Node.js 18+, TypeScript compiled to `dist/`. Production image must be minimal, non-root, and use the compiled output only.
|
||||
|
||||
## Decisions
|
||||
- Multi-stage build: `builder` stage compiles TypeScript; `production` stage copies `dist/` only
|
||||
- Base image: `node:18-alpine` — minimal footprint
|
||||
- Non-root user: `node` user (built into node alpine image)
|
||||
- No dev dependencies in production image — only `npm ci --omit=dev`
|
||||
- Health check: `wget` on `localhost:3000/health` — but no `/health` endpoint exists yet, so omit health check from Dockerfile; it is set in docker-compose.yml via pg_isready/redis-cli patterns
|
||||
- `.dockerignore` excludes: `node_modules`, `dist`, `coverage`, `tests`, `.env`, `*.pem`, `vj_notes`, `.cto-workspace`, `.claude`
|
||||
|
||||
## Open Questions
|
||||
*(none)*
|
||||
11
openspec/changes/archive/2026-03-28-dockerfile/proposal.md
Normal file
11
openspec/changes/archive/2026-03-28-dockerfile/proposal.md
Normal file
@@ -0,0 +1,11 @@
|
||||
## Why
|
||||
The `docker-compose.yml` `app` service references a `Dockerfile` that does not exist. Docker containerisation is a Phase 1 P1 item. Without it, the full docker-compose stack cannot start and the DevOps deployment path is incomplete.
|
||||
|
||||
## What Changes
|
||||
- New `Dockerfile` at project root — multi-stage build (builder + production)
|
||||
- New `.dockerignore` — excludes `node_modules`, `dist`, test files, `.env`
|
||||
- `docker-compose.yml` `app` service becomes fully functional
|
||||
|
||||
## What Does Not Change
|
||||
- No source code changes
|
||||
- No dependency changes
|
||||
@@ -0,0 +1,7 @@
|
||||
## ADDED Requirements
|
||||
|
||||
### Requirement: Dockerfile exists at project root
|
||||
The system SHALL provide a multi-stage `Dockerfile` that builds the TypeScript source and produces a minimal production image running as a non-root user.
|
||||
|
||||
### Requirement: .dockerignore exists at project root
|
||||
The system SHALL provide a `.dockerignore` that excludes development artifacts, secrets, and test files from the Docker build context.
|
||||
14
openspec/changes/archive/2026-03-28-dockerfile/tasks.md
Normal file
14
openspec/changes/archive/2026-03-28-dockerfile/tasks.md
Normal file
@@ -0,0 +1,14 @@
|
||||
## 1. Dockerfile
|
||||
|
||||
- [x] 1.1 Write multi-stage Dockerfile: builder stage (node:18-alpine, npm ci, npm run build)
|
||||
- [x] 1.2 Write production stage: node:18-alpine, npm ci --omit=dev, copy dist/, USER node
|
||||
- [x] 1.3 Set EXPOSE 3000, CMD ["node", "dist/server.js"]
|
||||
|
||||
## 2. .dockerignore
|
||||
|
||||
- [x] 2.1 Write .dockerignore excluding: node_modules, dist, coverage, tests, .env, *.pem, vj_notes, .cto-workspace, .claude, next_steps.md
|
||||
|
||||
## 3. QA
|
||||
|
||||
- [x] 3.1 Verify Dockerfile build stages are correct and complete
|
||||
- [x] 3.2 Verify .dockerignore covers all sensitive/unnecessary files
|
||||
@@ -0,0 +1,2 @@
|
||||
schema: spec-driven
|
||||
created: 2026-03-28
|
||||
39
openspec/changes/archive/2026-03-28-nodejs-sdk/design.md
Normal file
39
openspec/changes/archive/2026-03-28-nodejs-sdk/design.md
Normal file
@@ -0,0 +1,39 @@
|
||||
## Context
|
||||
The SDK wraps the AgentIdP REST API. It must handle authentication transparently — caller provides `clientId` + `clientSecret`, SDK manages token acquisition and refresh automatically.
|
||||
|
||||
## Architecture
|
||||
- Single entrypoint: `sdk/src/index.ts` exports `AgentIdPClient` and all types
|
||||
- `AgentIdPClient` constructor takes `{ baseUrl, clientId, clientSecret }`
|
||||
- Internal `TokenManager` handles token acquisition, caching, and refresh (re-issues when expired)
|
||||
- Four service classes: `AgentRegistryClient`, `CredentialClient`, `TokenClient`, `AuditClient`
|
||||
- `AgentIdPClient` composes all four
|
||||
- HTTP: native `fetch` (Node 18+ built-in) — no axios dependency
|
||||
- Types: re-exported from `sdk/src/types.ts` — mirrors the main app types
|
||||
|
||||
## Standards
|
||||
- TypeScript strict mode, zero `any`
|
||||
- DRY: shared `request()` helper handles auth header, JSON parse, error mapping
|
||||
- All errors are typed `AgentIdPError` with `code` and `message`
|
||||
- JSDoc on all public methods
|
||||
|
||||
## Package structure
|
||||
```
|
||||
sdk/
|
||||
src/
|
||||
index.ts — exports AgentIdPClient + all types
|
||||
client.ts — AgentIdPClient (composes all services)
|
||||
token-manager.ts — token acquisition and refresh
|
||||
services/
|
||||
agents.ts — AgentRegistryClient
|
||||
credentials.ts — CredentialClient
|
||||
token.ts — TokenClient
|
||||
audit.ts — AuditClient
|
||||
types.ts — all request/response types
|
||||
errors.ts — AgentIdPError class
|
||||
package.json
|
||||
tsconfig.json
|
||||
README.md
|
||||
```
|
||||
|
||||
## Open Questions
|
||||
*(none)*
|
||||
13
openspec/changes/archive/2026-03-28-nodejs-sdk/proposal.md
Normal file
13
openspec/changes/archive/2026-03-28-nodejs-sdk/proposal.md
Normal file
@@ -0,0 +1,13 @@
|
||||
## Why
|
||||
Bedroom developers currently must write raw HTTP calls to use AgentIdP. A Node.js SDK removes that friction — developers install one package and get a fully typed, auto-authenticating client. This is a Phase 1 P1 deliverable and a core developer experience improvement.
|
||||
|
||||
## What Changes
|
||||
- New `sdk/` directory at project root containing a self-contained TypeScript npm package
|
||||
- `AgentIdPClient` class: handles auth, token refresh, and exposes typed methods for all 14 endpoints
|
||||
- Covers all four services: AgentRegistry, Credentials, Token, AuditLog
|
||||
- Full TypeScript types — zero `any`, strict mode
|
||||
- Published as `@sentryagent/idp-sdk` (package name)
|
||||
|
||||
## What Does Not Change
|
||||
- No API changes
|
||||
- No changes to the main application source
|
||||
@@ -0,0 +1,7 @@
|
||||
## ADDED Requirements
|
||||
|
||||
### Requirement: AgentIdPClient class exists and handles auth transparently
|
||||
The SDK SHALL provide an `AgentIdPClient` class that accepts `baseUrl`, `clientId`, and `clientSecret` in its constructor and manages token acquisition and refresh automatically. Callers never handle tokens directly.
|
||||
|
||||
### Requirement: TokenManager caches and refreshes tokens
|
||||
The SDK SHALL cache the access token in memory and re-issue it via `POST /token` when it is expired or within 60 seconds of expiry. Token refresh is transparent to the caller.
|
||||
@@ -0,0 +1,7 @@
|
||||
## ADDED Requirements
|
||||
|
||||
### Requirement: All 14 endpoints are wrapped as typed SDK methods
|
||||
The SDK SHALL expose typed methods for all 14 AgentIdP endpoints across four service namespaces: `agents` (5 methods), `credentials` (4 methods), `token` (3 methods), `audit` (2 methods).
|
||||
|
||||
### Requirement: All errors are typed AgentIdPError instances
|
||||
The SDK SHALL throw `AgentIdPError` with `code`, `message`, `httpStatus`, and optional `details` for all API errors. Never throw raw fetch errors.
|
||||
@@ -0,0 +1,4 @@
|
||||
## ADDED Requirements
|
||||
|
||||
### Requirement: Full TypeScript types exported from sdk package
|
||||
The SDK SHALL export TypeScript interfaces for all request bodies, response shapes, and error types. Zero `any` types. All types derived from the OpenAPI specs.
|
||||
35
openspec/changes/archive/2026-03-28-nodejs-sdk/tasks.md
Normal file
35
openspec/changes/archive/2026-03-28-nodejs-sdk/tasks.md
Normal file
@@ -0,0 +1,35 @@
|
||||
## 1. Package Setup
|
||||
|
||||
- [x] 1.1 Create `sdk/` directory and `sdk/src/` subdirectories
|
||||
- [x] 1.2 Write `sdk/package.json` — name: @sentryagent/idp-sdk, main, types, scripts (build, test)
|
||||
- [x] 1.3 Write `sdk/tsconfig.json` — strict mode, target ES2020, declaration: true
|
||||
- [x] 1.4 Write `sdk/README.md` — installation, quick example, full API reference
|
||||
|
||||
## 2. Types
|
||||
|
||||
- [x] 2.1 Write `sdk/src/types.ts` — all request/response interfaces for all 14 endpoints
|
||||
- [x] 2.2 Write `sdk/src/errors.ts` — AgentIdPError class with code, message, httpStatus, details
|
||||
|
||||
## 3. Core Client
|
||||
|
||||
- [x] 3.1 Write `sdk/src/token-manager.ts` — TokenManager: acquires, caches, refreshes tokens; re-issues when exp - 60s
|
||||
- [x] 3.2 Write `sdk/src/request.ts` — shared request() helper: sets Authorization header, parses JSON, maps errors to AgentIdPError
|
||||
|
||||
## 4. Service Clients
|
||||
|
||||
- [x] 4.1 Write `sdk/src/services/agents.ts` — AgentRegistryClient: registerAgent, listAgents, getAgent, updateAgent, decommissionAgent
|
||||
- [x] 4.2 Write `sdk/src/services/credentials.ts` — CredentialClient: generateCredential, listCredentials, rotateCredential, revokeCredential
|
||||
- [x] 4.3 Write `sdk/src/services/token.ts` — TokenClient: introspectToken, revokeToken (issueToken handled by TokenManager)
|
||||
- [x] 4.4 Write `sdk/src/services/audit.ts` — AuditClient: queryAuditLog, getAuditEvent
|
||||
|
||||
## 5. Main Entry Point
|
||||
|
||||
- [x] 5.1 Write `sdk/src/client.ts` — AgentIdPClient: composes all service clients, exposes agents, credentials, token, audit namespaces
|
||||
- [x] 5.2 Write `sdk/src/index.ts` — exports AgentIdPClient and all public types
|
||||
|
||||
## 6. QA
|
||||
|
||||
- [x] 6.1 Verify TypeScript compiles with zero errors (npm run build in sdk/)
|
||||
- [x] 6.2 Verify zero `any` types across all SDK files
|
||||
- [x] 6.3 Verify all 14 endpoints have corresponding SDK methods
|
||||
- [x] 6.4 Verify AgentIdPError is thrown (not raw errors) for all failure paths
|
||||
@@ -0,0 +1,2 @@
|
||||
schema: spec-driven
|
||||
created: 2026-03-28
|
||||
@@ -0,0 +1,130 @@
|
||||
## Context
|
||||
|
||||
SentryAgent.ai AgentIdP is a greenfield Node.js/TypeScript service with no existing implementation. The codebase contains only scaffolding. Four CEO-approved OpenAPI 3.0 specs define the full API surface. This design governs the architecture for all four P0 services and their shared infrastructure.
|
||||
|
||||
**Constraints:**
|
||||
- TypeScript 5.3+ strict mode — no `any` types, ever
|
||||
- DRY and SOLID enforced on every file
|
||||
- PostgreSQL 14+ for all persistent state; Redis 7+ for caching and rate limiting
|
||||
- Express 4.18+ as the HTTP framework
|
||||
- All secrets bcrypt-hashed (10 rounds); `clientSecret` never persisted in plain text
|
||||
- Specs are the source of truth — implementation must match exactly
|
||||
|
||||
## Goals / Non-Goals
|
||||
|
||||
**Goals:**
|
||||
- Implement all 4 P0 services (Agent Registry, OAuth2 Token, Credential Management, Audit Log) as typed Express route handlers backed by typed service classes
|
||||
- Enforce free-tier limits (100 agents, 10,000 tokens/month, 100 req/min, 90-day audit retention)
|
||||
- Provide a single Express app entry point with all middleware and routing wired up
|
||||
- Provide PostgreSQL migrations for all 4 tables
|
||||
- Provide a Docker Compose file for local development (Node.js app + Postgres + Redis)
|
||||
|
||||
**Non-Goals:**
|
||||
- HashiCorp Vault, OPA, Web UI, Python/Go SDKs (Phase 2+)
|
||||
- Multi-region deployment, SOC 2 (Phase 3+)
|
||||
- Admin-scoped cross-agent credential management (stub `403` — implement in Phase 2)
|
||||
|
||||
## Decisions
|
||||
|
||||
### D1: Layered architecture (Controller → Service → Repository)
|
||||
**Decision**: Each feature has a Controller (HTTP), a Service (business logic), and a Repository (DB queries). No business logic in controllers; no SQL outside repositories.
|
||||
**Rationale**: SOLID Single Responsibility. Controllers handle HTTP concerns only. Services are testable in isolation (inject mock repository). Repositories are the sole owners of SQL.
|
||||
**Alternative considered**: Fat controllers — rejected (untestable, violates SRP).
|
||||
|
||||
### D2: Dependency injection via constructor injection
|
||||
**Decision**: All dependencies (repositories, services, Redis client, JWT utils) are injected via constructor parameters. No `new Foo()` inside business logic.
|
||||
**Rationale**: SOLID Dependency Inversion. Enables unit testing with mocks. No global singletons in services.
|
||||
**Alternative considered**: Service locator / global singletons — rejected (hidden coupling, hard to test).
|
||||
|
||||
### D3: Single shared error hierarchy (`SentryAgentError`)
|
||||
**Decision**: All custom errors extend `SentryAgentError` (as defined in README §6.6). A single Express error-handling middleware maps each error class to its HTTP status code and `ErrorResponse` shape.
|
||||
**Rationale**: DRY — error-to-status mapping exists in exactly one place. Every thrown error is typed and explicit.
|
||||
|
||||
### D4: JWT signed with RS256 (asymmetric)
|
||||
**Decision**: Access tokens are signed with RS256 (RSA 2048-bit). Public key exposed for external verification.
|
||||
**Rationale**: Allows downstream services to verify tokens without calling back to AgentIdP. Industry standard for OAuth2 JWTs. Symmetric HS256 would require sharing the secret with every verifier.
|
||||
**Alternative considered**: HS256 — rejected (key distribution problem at scale).
|
||||
|
||||
### D5: Redis for token revocation and rate limiting
|
||||
**Decision**: Revoked token JTIs are stored in Redis with TTL = token expiry. Rate-limit counters use Redis sliding window. Free-tier monthly token count uses Redis with monthly TTL.
|
||||
**Rationale**: Redis provides O(1) token revocation checks without DB round-trips. Token introspection path must be fast (<100ms per spec).
|
||||
|
||||
### D6: `clientSecret` format — `sk_live_` prefix + 32 random hex bytes
|
||||
**Decision**: Generated secrets follow the pattern `sk_live_<64 hex chars>`. Stored as bcrypt hash (10 rounds).
|
||||
**Rationale**: Prefixed format is recognisable in logs/config and grep-able for secret scanning. 64 hex chars = 256 bits of entropy.
|
||||
|
||||
### D7: Audit log written synchronously within the request transaction
|
||||
**Decision**: Audit events are inserted within the same DB transaction as the action that triggers them (where applicable). For token issuance (Redis-only operation), audit is a separate async fire-and-forget insert.
|
||||
**Rationale**: For state-changing DB operations (agent creation, credential rotation) atomicity guarantees the audit record is never lost. Token issuance latency must be <100ms — synchronous audit insert would risk this on high load.
|
||||
|
||||
### D8: Project file layout
|
||||
```
|
||||
src/
|
||||
app.ts — Express app factory (no listen call — testable)
|
||||
server.ts — Entry point (calls app.ts, calls listen)
|
||||
types/index.ts — All shared TypeScript interfaces and types
|
||||
utils/
|
||||
crypto.ts — Secret generation, bcrypt helpers
|
||||
jwt.ts — JWT sign/verify
|
||||
validators.ts — Joi schemas for all request bodies
|
||||
errors.ts — SentryAgentError hierarchy
|
||||
middleware/
|
||||
auth.ts — Bearer token extraction and verification
|
||||
rateLimit.ts — Redis-backed rate limiter
|
||||
errorHandler.ts — Global Express error handler
|
||||
db/
|
||||
pool.ts — pg Pool singleton
|
||||
migrations/ — SQL migration files (001_create_agents.sql, etc.)
|
||||
cache/
|
||||
redis.ts — Redis client singleton
|
||||
services/
|
||||
AgentService.ts
|
||||
OAuth2Service.ts
|
||||
CredentialService.ts
|
||||
AuditService.ts
|
||||
repositories/
|
||||
AgentRepository.ts
|
||||
CredentialRepository.ts
|
||||
AuditRepository.ts
|
||||
TokenRepository.ts
|
||||
routes/
|
||||
agents.ts
|
||||
token.ts
|
||||
credentials.ts
|
||||
audit.ts
|
||||
controllers/
|
||||
AgentController.ts
|
||||
TokenController.ts
|
||||
CredentialController.ts
|
||||
AuditController.ts
|
||||
tests/
|
||||
unit/
|
||||
services/
|
||||
utils/
|
||||
integration/
|
||||
agents.test.ts
|
||||
token.test.ts
|
||||
credentials.test.ts
|
||||
audit.test.ts
|
||||
```
|
||||
|
||||
## Risks / Trade-offs
|
||||
|
||||
- **[Risk] RS256 key management in Phase 1** → Keys loaded from `PEM` env vars (`JWT_PRIVATE_KEY`, `JWT_PUBLIC_KEY`). Rotation not automated until Phase 2 (Vault). Mitigation: documented in deployment guide.
|
||||
- **[Risk] Async audit insert on token issuance may drop events on crash** → Acceptable for Phase 1 free tier. Synchronous insert + queue buffering addressed in Phase 2.
|
||||
- **[Risk] bcrypt 10 rounds adds ~100ms to credential verification** → Token endpoint latency target is <100ms. Bcrypt is only called on `POST /token` (credential verification), not on every authenticated request (JWT verification is fast). Acceptable.
|
||||
- **[Trade-off] No admin scope in Phase 1** → Agents can only manage their own credentials. Cross-agent admin operations return `403 FORBIDDEN` with a clear message. Unblocks Phase 1 shipping without scope management complexity.
|
||||
|
||||
## Migration Plan
|
||||
|
||||
1. Run `npm install` to install all dependencies
|
||||
2. Start Docker Compose (`docker-compose up -d`) — spins up Postgres + Redis
|
||||
3. Run migrations: `npm run db:migrate`
|
||||
4. Set required env vars (see `.env.example`)
|
||||
5. Start server: `npm run dev`
|
||||
|
||||
**Rollback**: Drop database, stop containers, revert to previous commit. No shared state in Phase 1 (single-instance).
|
||||
|
||||
## Open Questions
|
||||
|
||||
- _None_ — all decisions required for Phase 1 implementation are resolved above.
|
||||
@@ -0,0 +1,36 @@
|
||||
## Why
|
||||
|
||||
SentryAgent.ai AgentIdP has no implemented codebase — only scaffolding exists. Phase 1 MVP must ship a production-ready Agent Identity Provider so developers worldwide can register, authenticate, and govern their AI agents for free. All four P0 features have CEO-approved OpenAPI 3.0 specs and are ready for implementation.
|
||||
|
||||
## What Changes
|
||||
|
||||
- **NEW**: Agent Registry Service — full CRUD lifecycle management for AI agent identities (AGNTCY-aligned)
|
||||
- **NEW**: OAuth 2.0 Token Service — Client Credentials grant (RFC 6749), token introspection (RFC 7662), token revocation (RFC 7009)
|
||||
- **NEW**: Credential Management Service — generate, rotate, and revoke agent `client_id`/`client_secret` pairs
|
||||
- **NEW**: Audit Log Service — immutable, append-only compliance event log (read-only via API)
|
||||
- **NEW**: Express.js application bootstrap — routing, middleware (helmet, cors, morgan, pino), error handling
|
||||
- **NEW**: PostgreSQL database layer — migrations, connection pool, typed query services
|
||||
- **NEW**: Redis caching layer — token validation cache, rate-limit counters
|
||||
- **NEW**: Shared infrastructure — typed error hierarchy, Joi validation, JWT utilities, crypto utilities, DI container
|
||||
|
||||
## Capabilities
|
||||
|
||||
### New Capabilities
|
||||
|
||||
- `agent-registry`: Register, retrieve, update, and decommission AI agent identities with AGNTCY-aligned fields (`agentId`, `email`, `agentType`, `capabilities`, `owner`, `deploymentEnv`, `status`)
|
||||
- `oauth2-token`: Issue signed JWT access tokens via OAuth 2.0 Client Credentials flow; introspect and revoke tokens per RFC
|
||||
- `credential-management`: Generate and rotate `client_id`/`client_secret` pairs per agent; revoke credentials; `clientSecret` shown once only
|
||||
- `audit-log`: Query immutable audit events by `agentId`, `action`, `outcome`, and date range; 90-day free-tier retention
|
||||
|
||||
### Modified Capabilities
|
||||
|
||||
_None — this is a greenfield implementation._
|
||||
|
||||
## Impact
|
||||
|
||||
- **APIs**: 14 new REST endpoints across 4 services (`/agents`, `/token`, `/agents/{id}/credentials`, `/audit`)
|
||||
- **Database**: 4 new PostgreSQL tables (`agents`, `tokens`, `credentials`, `audit_events`) with migrations
|
||||
- **Cache**: Redis used for token validation and rate-limit counters
|
||||
- **Dependencies**: Express, Joi, jsonwebtoken, bcryptjs, uuid, pg, redis, pino, helmet, cors, dotenv (all pre-approved in README Section 7)
|
||||
- **Auth**: All endpoints require Bearer JWT; token endpoint uses `client_id`/`client_secret`
|
||||
- **Free tier enforcement**: 100 agents max, 10,000 tokens/month, 100 req/min rate limit, 90-day audit retention
|
||||
@@ -0,0 +1,86 @@
|
||||
## ADDED Requirements
|
||||
|
||||
### Requirement: Register a new AI agent
|
||||
The system SHALL create a new agent identity record with a system-assigned immutable UUID (`agentId`) when a valid `CreateAgentRequest` is received. The `email` field SHALL be unique across all agents. The agent SHALL be created with `status: active`. The system SHALL enforce a free-tier limit of 100 registered agents per account.
|
||||
|
||||
#### Scenario: Successful agent registration
|
||||
- **WHEN** a POST request to `/agents` is received with a valid `CreateAgentRequest` body and a valid Bearer token
|
||||
- **THEN** the system creates the agent, assigns a UUID `agentId`, sets `status` to `active`, sets `createdAt` and `updatedAt` to the current timestamp, and returns `201` with the full `Agent` object
|
||||
|
||||
#### Scenario: Duplicate email rejected
|
||||
- **WHEN** a POST request to `/agents` is received with an `email` that is already registered
|
||||
- **THEN** the system returns `409 Conflict` with `code: AGENT_ALREADY_EXISTS`
|
||||
|
||||
#### Scenario: Free tier limit enforced
|
||||
- **WHEN** a POST request to `/agents` is received and the account already has 100 registered agents
|
||||
- **THEN** the system returns `403 Forbidden` with `code: FREE_TIER_LIMIT_EXCEEDED` and `details.limit: 100`
|
||||
|
||||
#### Scenario: Invalid request body rejected
|
||||
- **WHEN** a POST request to `/agents` is received with a missing required field or invalid field value (e.g. invalid semver, invalid email, invalid capability pattern)
|
||||
- **THEN** the system returns `400 Bad Request` with `code: VALIDATION_ERROR` and `details` identifying the failing field
|
||||
|
||||
### Requirement: Retrieve a single agent by ID
|
||||
The system SHALL return the full `Agent` record for a given `agentId`.
|
||||
|
||||
#### Scenario: Agent found
|
||||
- **WHEN** a GET request to `/agents/{agentId}` is received with a valid Bearer token and a UUID that exists in the registry
|
||||
- **THEN** the system returns `200 OK` with the full `Agent` object
|
||||
|
||||
#### Scenario: Agent not found
|
||||
- **WHEN** a GET request to `/agents/{agentId}` is received with a UUID that does not exist
|
||||
- **THEN** the system returns `404 Not Found` with `code: AGENT_NOT_FOUND`
|
||||
|
||||
### Requirement: List agents with pagination and filtering
|
||||
The system SHALL return a paginated list of agents, orderd by `createdAt` descending, optionally filtered by `owner`, `agentType`, and/or `status`.
|
||||
|
||||
#### Scenario: Successful paginated list
|
||||
- **WHEN** a GET request to `/agents` is received with optional `page`, `limit`, `owner`, `agentType`, `status` query parameters and a valid Bearer token
|
||||
- **THEN** the system returns `200 OK` with a `PaginatedAgentsResponse` containing `data`, `total`, `page`, and `limit`
|
||||
|
||||
#### Scenario: Invalid pagination parameters rejected
|
||||
- **WHEN** a GET request to `/agents` is received with `limit` greater than 100 or `page` less than 1
|
||||
- **THEN** the system returns `400 Bad Request` with `code: VALIDATION_ERROR`
|
||||
|
||||
### Requirement: Update agent metadata
|
||||
The system SHALL partially update a mutable agent record. `agentId`, `email`, and `createdAt` SHALL be immutable. Setting `status` to `decommissioned` SHALL be a one-way irreversible operation.
|
||||
|
||||
#### Scenario: Successful partial update
|
||||
- **WHEN** a PATCH request to `/agents/{agentId}` is received with a valid partial `UpdateAgentRequest` body and a valid Bearer token
|
||||
- **THEN** the system updates only the provided fields, sets `updatedAt` to the current timestamp, and returns `200 OK` with the full updated `Agent` object
|
||||
|
||||
#### Scenario: Attempt to modify immutable field rejected
|
||||
- **WHEN** a PATCH request to `/agents/{agentId}` contains the `email` field
|
||||
- **THEN** the system returns `400 Bad Request` with `code: IMMUTABLE_FIELD` and `details.field: email`
|
||||
|
||||
#### Scenario: Decommissioned agent cannot be updated
|
||||
- **WHEN** a PATCH request to `/agents/{agentId}` targets an agent with `status: decommissioned`
|
||||
- **THEN** the system returns `403 Forbidden` with `code: AGENT_DECOMMISSIONED`
|
||||
|
||||
### Requirement: Decommission (soft-delete) an agent
|
||||
The system SHALL set an agent's `status` to `decommissioned` and revoke all of its active credentials. The agent record SHALL be retained for audit purposes. This operation SHALL be irreversible.
|
||||
|
||||
#### Scenario: Successful decommission
|
||||
- **WHEN** a DELETE request to `/agents/{agentId}` is received with a valid Bearer token and the agent exists and is not already decommissioned
|
||||
- **THEN** the system sets `status` to `decommissioned`, revokes all active credentials for this agent, and returns `204 No Content`
|
||||
|
||||
#### Scenario: Already decommissioned agent rejected
|
||||
- **WHEN** a DELETE request to `/agents/{agentId}` is received for an agent that is already `decommissioned`
|
||||
- **THEN** the system returns `409 Conflict` with `code: AGENT_ALREADY_DECOMMISSIONED`
|
||||
|
||||
### Requirement: Authentication required on all agent endpoints
|
||||
All agent endpoints SHALL require a valid Bearer JWT in the `Authorization` header.
|
||||
|
||||
#### Scenario: Missing token rejected
|
||||
- **WHEN** any request to `/agents` or `/agents/{agentId}` is received without an `Authorization: Bearer` header
|
||||
- **THEN** the system returns `401 Unauthorized` with `code: UNAUTHORIZED`
|
||||
|
||||
#### Scenario: Invalid token rejected
|
||||
- **WHEN** any request to `/agents` or `/agents/{agentId}` is received with an expired, malformed, or revoked Bearer token
|
||||
- **THEN** the system returns `401 Unauthorized` with `code: UNAUTHORIZED`
|
||||
|
||||
### Requirement: Rate limiting on all agent endpoints
|
||||
The system SHALL enforce a rate limit of 100 requests per minute per authenticated client. Rate limit state SHALL be tracked in Redis.
|
||||
|
||||
#### Scenario: Rate limit exceeded
|
||||
- **WHEN** a client sends more than 100 requests to any agent endpoint within a 60-second window
|
||||
- **THEN** the system returns `429 Too Many Requests` with `X-RateLimit-Limit`, `X-RateLimit-Remaining: 0`, and `X-RateLimit-Reset` headers
|
||||
@@ -0,0 +1,72 @@
|
||||
## ADDED Requirements
|
||||
|
||||
### Requirement: Audit events are written internally for all significant actions
|
||||
The system SHALL automatically create an immutable `AuditEvent` record for each of the following actions: `agent.created`, `agent.updated`, `agent.decommissioned`, `agent.suspended`, `agent.reactivated`, `token.issued`, `token.revoked`, `token.introspected`, `credential.generated`, `credential.rotated`, `credential.revoked`, `auth.failed`. No API endpoint SHALL allow external creation, modification, or deletion of audit records.
|
||||
|
||||
#### Scenario: Audit event created on agent registration
|
||||
- **WHEN** a new agent is successfully registered via `POST /agents`
|
||||
- **THEN** an `AuditEvent` with `action: agent.created`, `outcome: success`, and `metadata` containing `agentType` and `owner` is persisted
|
||||
|
||||
#### Scenario: Audit event created on failed authentication
|
||||
- **WHEN** a `POST /token` request fails due to invalid credentials
|
||||
- **THEN** an `AuditEvent` with `action: auth.failed`, `outcome: failure`, and `metadata` containing `reason` and `clientId` is persisted
|
||||
|
||||
#### Scenario: Audit event created on token issuance
|
||||
- **WHEN** a token is successfully issued via `POST /token`
|
||||
- **THEN** an `AuditEvent` with `action: token.issued`, `outcome: success`, and `metadata` containing `scope` and `expiresAt` is persisted
|
||||
|
||||
### Requirement: Query the audit log with pagination and filtering
|
||||
The system SHALL return a paginated list of audit events ordered by `timestamp` descending. The caller SHALL hold a valid Bearer token with `audit:read` scope. Filtering SHALL support `agentId`, `action`, `outcome`, `fromDate`, and `toDate` — all optional, combined with logical AND.
|
||||
|
||||
#### Scenario: Successful audit log query
|
||||
- **WHEN** a GET request to `/audit` is received with a valid Bearer token with `audit:read` scope
|
||||
- **THEN** the system returns `200 OK` with a `PaginatedAuditEventsResponse` containing `data`, `total`, `page`, and `limit`
|
||||
|
||||
#### Scenario: Filter by agentId
|
||||
- **WHEN** a GET request to `/audit?agentId={uuid}` is received
|
||||
- **THEN** only events where `agentId` equals the provided UUID are returned
|
||||
|
||||
#### Scenario: Filter by action
|
||||
- **WHEN** a GET request to `/audit?action=token.issued` is received
|
||||
- **THEN** only events with `action: token.issued` are returned
|
||||
|
||||
#### Scenario: Filter by date range
|
||||
- **WHEN** a GET request to `/audit?fromDate=2026-03-01T00:00:00.000Z&toDate=2026-03-28T23:59:59.999Z` is received
|
||||
- **THEN** only events with `timestamp` within the specified range are returned
|
||||
|
||||
#### Scenario: fromDate after toDate rejected
|
||||
- **WHEN** a GET request to `/audit` is received with `fromDate` that is chronologically after `toDate`
|
||||
- **THEN** the system returns `400 Bad Request` with `code: VALIDATION_ERROR` and `details.reason` explaining the invalid date range
|
||||
|
||||
#### Scenario: Insufficient scope rejected
|
||||
- **WHEN** a GET request to `/audit` is received with a valid Bearer token that does not have `audit:read` scope
|
||||
- **THEN** the system returns `403 Forbidden` with `code: INSUFFICIENT_SCOPE`
|
||||
|
||||
### Requirement: Retrieve a single audit event by ID
|
||||
The system SHALL return a single immutable `AuditEvent` by its `eventId`. The caller SHALL hold a valid Bearer token with `audit:read` scope.
|
||||
|
||||
#### Scenario: Audit event found
|
||||
- **WHEN** a GET request to `/audit/{eventId}` is received with a valid Bearer token with `audit:read` scope and a UUID that exists in the audit log
|
||||
- **THEN** the system returns `200 OK` with the full `AuditEvent` object
|
||||
|
||||
#### Scenario: Audit event not found
|
||||
- **WHEN** a GET request to `/audit/{eventId}` is received with a UUID that does not exist in the audit log
|
||||
- **THEN** the system returns `404 Not Found` with `code: AUDIT_EVENT_NOT_FOUND`
|
||||
|
||||
### Requirement: Free-tier 90-day audit log retention
|
||||
On the free tier, the system SHALL only return audit events from the last 90 days. Events older than 90 days SHALL be treated as not accessible (return empty results for queries, `404` for direct lookups). The system SHALL return a `400` error with `code: RETENTION_WINDOW_EXCEEDED` if a `fromDate` query parameter falls outside the 90-day retention window.
|
||||
|
||||
#### Scenario: Query outside retention window rejected
|
||||
- **WHEN** a GET request to `/audit` is received with `fromDate` more than 90 days before today
|
||||
- **THEN** the system returns `400 Bad Request` with `code: RETENTION_WINDOW_EXCEEDED` and `details.retentionDays: 90`
|
||||
|
||||
#### Scenario: Direct lookup of expired event returns 404
|
||||
- **WHEN** a GET request to `/audit/{eventId}` is received for an event with a `timestamp` older than 90 days
|
||||
- **THEN** the system returns `404 Not Found` with `code: AUDIT_EVENT_NOT_FOUND`
|
||||
|
||||
### Requirement: Rate limiting on audit endpoints
|
||||
The system SHALL enforce a rate limit of 100 requests per minute per authenticated client on all audit endpoints.
|
||||
|
||||
#### Scenario: Rate limit exceeded on audit endpoint
|
||||
- **WHEN** a client sends more than 100 requests to any audit endpoint within a 60-second window
|
||||
- **THEN** the system returns `429 Too Many Requests` with `X-RateLimit-Limit`, `X-RateLimit-Remaining: 0`, and `X-RateLimit-Reset` headers
|
||||
@@ -0,0 +1,83 @@
|
||||
## ADDED Requirements
|
||||
|
||||
### Requirement: Generate new credentials for an agent
|
||||
The system SHALL generate a new `client_id`/`client_secret` pair for a specified agent. The `client_id` SHALL equal the agent's `agentId`. The `client_secret` SHALL be a cryptographically random string with the prefix `sk_live_` followed by 64 hex characters (256 bits of entropy). The plain-text secret SHALL be returned in the response exactly once and SHALL never be stored in plain text — only a bcrypt hash (10 rounds) SHALL be persisted. The agent MUST be in `active` status to generate credentials.
|
||||
|
||||
#### Scenario: Successful credential generation
|
||||
- **WHEN** a POST request to `/agents/{agentId}/credentials` is received with a valid Bearer token and the agent exists with `status: active`
|
||||
- **THEN** the system generates a new credential, persists the bcrypt hash of the secret, and returns `201 Created` with a `CredentialWithSecret` response including the plain-text `clientSecret`
|
||||
|
||||
#### Scenario: clientSecret not returned after creation
|
||||
- **WHEN** a GET request to `/agents/{agentId}/credentials` is made after credential creation
|
||||
- **THEN** the `clientSecret` field is NOT present in any `Credential` object in the response
|
||||
|
||||
#### Scenario: Suspended agent cannot generate credentials
|
||||
- **WHEN** a POST request to `/agents/{agentId}/credentials` is received for an agent with `status: suspended`
|
||||
- **THEN** the system returns `403 Forbidden` with `code: AGENT_NOT_ACTIVE`
|
||||
|
||||
#### Scenario: Decommissioned agent cannot generate credentials
|
||||
- **WHEN** a POST request to `/agents/{agentId}/credentials` is received for an agent with `status: decommissioned`
|
||||
- **THEN** the system returns `403 Forbidden` with `code: AGENT_NOT_ACTIVE`
|
||||
|
||||
#### Scenario: Optional expiry respected
|
||||
- **WHEN** a POST request to `/agents/{agentId}/credentials` is received with an `expiresAt` value that is a future date-time
|
||||
- **THEN** the credential is created with the specified `expiresAt` value
|
||||
|
||||
#### Scenario: Past expiry rejected
|
||||
- **WHEN** a POST request to `/agents/{agentId}/credentials` is received with an `expiresAt` value that is in the past
|
||||
- **THEN** the system returns `400 Bad Request` with `code: VALIDATION_ERROR` and `details.field: expiresAt`
|
||||
|
||||
#### Scenario: Agent not found
|
||||
- **WHEN** a POST request to `/agents/{agentId}/credentials` is received for a `agentId` that does not exist
|
||||
- **THEN** the system returns `404 Not Found` with `code: AGENT_NOT_FOUND`
|
||||
|
||||
### Requirement: List credentials for an agent
|
||||
The system SHALL return a paginated list of all credentials (both `active` and `revoked`) for an agent, ordered by `createdAt` descending. The `clientSecret` SHALL never be included in list responses.
|
||||
|
||||
#### Scenario: Successful credential list
|
||||
- **WHEN** a GET request to `/agents/{agentId}/credentials` is received with optional `page`, `limit`, `status` query parameters and a valid Bearer token
|
||||
- **THEN** the system returns `200 OK` with a `PaginatedCredentialsResponse` containing `data`, `total`, `page`, and `limit`, with no `clientSecret` fields
|
||||
|
||||
#### Scenario: Filter by status
|
||||
- **WHEN** a GET request to `/agents/{agentId}/credentials?status=active` is received
|
||||
- **THEN** only credentials with `status: active` are returned
|
||||
|
||||
### Requirement: Rotate a credential
|
||||
The system SHALL rotate an existing active credential by generating a new `clientSecret` for the same `credentialId`. The previous secret SHALL be immediately invalidated. The new plain-text secret SHALL be returned once and never persisted. Only `active` credentials can be rotated.
|
||||
|
||||
#### Scenario: Successful rotation
|
||||
- **WHEN** a POST request to `/agents/{agentId}/credentials/{credentialId}/rotate` is received with a valid Bearer token and the credential exists with `status: active`
|
||||
- **THEN** the system generates a new secret, replaces the stored bcrypt hash, and returns `200 OK` with a `CredentialWithSecret` response including the new plain-text `clientSecret`. The `credentialId` remains unchanged.
|
||||
|
||||
#### Scenario: Revoked credential cannot be rotated
|
||||
- **WHEN** a POST request to `/agents/{agentId}/credentials/{credentialId}/rotate` is received for a credential with `status: revoked`
|
||||
- **THEN** the system returns `409 Conflict` with `code: CREDENTIAL_ALREADY_REVOKED`
|
||||
|
||||
#### Scenario: Credential not found
|
||||
- **WHEN** a POST request to `/agents/{agentId}/credentials/{credentialId}/rotate` is received with a `credentialId` that does not exist for the given agent
|
||||
- **THEN** the system returns `404 Not Found` with `code: CREDENTIAL_NOT_FOUND`
|
||||
|
||||
### Requirement: Revoke a credential
|
||||
The system SHALL permanently revoke a credential by setting its `status` to `revoked` and recording a `revokedAt` timestamp. The credential record SHALL be retained for audit purposes. Revocation SHALL be irreversible. Tokens previously issued with this credential SHALL remain valid until their natural expiry (token revocation is handled separately via `POST /token/revoke`). Revoking an already-revoked credential SHALL return `409 Conflict`.
|
||||
|
||||
#### Scenario: Successful revocation
|
||||
- **WHEN** a DELETE request to `/agents/{agentId}/credentials/{credentialId}` is received with a valid Bearer token and the credential exists with `status: active`
|
||||
- **THEN** the system sets `status` to `revoked`, sets `revokedAt` to the current timestamp, and returns `204 No Content`
|
||||
|
||||
#### Scenario: Already-revoked credential rejected
|
||||
- **WHEN** a DELETE request to `/agents/{agentId}/credentials/{credentialId}` is received for a credential that is already `revoked`
|
||||
- **THEN** the system returns `409 Conflict` with `code: CREDENTIAL_ALREADY_REVOKED`
|
||||
|
||||
### Requirement: Agent decommission cascades to credential revocation
|
||||
When an agent is decommissioned via `DELETE /agents/{agentId}`, the system SHALL revoke all active credentials for that agent as part of the same operation.
|
||||
|
||||
#### Scenario: All credentials revoked on agent decommission
|
||||
- **WHEN** an agent is successfully decommissioned via `DELETE /agents/{agentId}`
|
||||
- **THEN** all credentials for that agent with `status: active` are set to `status: revoked` with `revokedAt` = current timestamp
|
||||
|
||||
### Requirement: Authentication required on all credential endpoints
|
||||
All credential endpoints SHALL require a valid Bearer JWT. An agent MAY manage its own credentials using a self-issued token. Managing another agent's credentials SHALL return `403 Forbidden` unless the caller holds an admin-scoped token (admin scope is not implemented in Phase 1 — return `403` for all cross-agent requests).
|
||||
|
||||
#### Scenario: Unauthenticated request rejected
|
||||
- **WHEN** any request to `/agents/{agentId}/credentials` is received without a valid Bearer token
|
||||
- **THEN** the system returns `401 Unauthorized` with `code: UNAUTHORIZED`
|
||||
@@ -0,0 +1,76 @@
|
||||
## ADDED Requirements
|
||||
|
||||
### Requirement: Issue access token via Client Credentials grant
|
||||
The system SHALL issue a signed RS256 JWT access token when an agent authenticates with a valid `client_id` (agentId) and `client_secret` using the OAuth 2.0 Client Credentials grant (RFC 6749 §4.4). The request body SHALL use `application/x-www-form-urlencoded` encoding. The response SHALL include `Cache-Control: no-store` and `Pragma: no-cache` headers. The system SHALL enforce a free-tier limit of 10,000 token requests per calendar month per client.
|
||||
|
||||
#### Scenario: Successful token issuance
|
||||
- **WHEN** a POST request to `/token` is received with `grant_type=client_credentials`, a valid `client_id`, and a valid `client_secret` for an `active` agent
|
||||
- **THEN** the system verifies the credential, issues a signed JWT with `sub` = `agentId`, `scope` = requested (or default) scope, `exp` = now + 3600s, and returns `200 OK` with `TokenResponse`
|
||||
|
||||
#### Scenario: Invalid client credentials rejected
|
||||
- **WHEN** a POST request to `/token` is received with a `client_id` that does not exist or a `client_secret` that does not match
|
||||
- **THEN** the system returns `401 Unauthorized` with `error: invalid_client`
|
||||
|
||||
#### Scenario: Suspended agent cannot obtain tokens
|
||||
- **WHEN** a POST request to `/token` is received for an agent with `status: suspended`
|
||||
- **THEN** the system returns `403 Forbidden` with `error: unauthorized_client` and a description indicating the agent is suspended
|
||||
|
||||
#### Scenario: Decommissioned agent cannot obtain tokens
|
||||
- **WHEN** a POST request to `/token` is received for an agent with `status: decommissioned`
|
||||
- **THEN** the system returns `403 Forbidden` with `error: unauthorized_client`
|
||||
|
||||
#### Scenario: Unsupported grant type rejected
|
||||
- **WHEN** a POST request to `/token` is received with a `grant_type` other than `client_credentials`
|
||||
- **THEN** the system returns `400 Bad Request` with `error: unsupported_grant_type`
|
||||
|
||||
#### Scenario: Invalid scope rejected
|
||||
- **WHEN** a POST request to `/token` is received with a `scope` value that contains an unrecognised scope identifier
|
||||
- **THEN** the system returns `400 Bad Request` with `error: invalid_scope`
|
||||
|
||||
#### Scenario: Free tier monthly token limit enforced
|
||||
- **WHEN** a POST request to `/token` is received and the agent has already made 10,000 token requests in the current calendar month
|
||||
- **THEN** the system returns `403 Forbidden` with `error: unauthorized_client` and a description indicating the monthly free-tier limit is reached
|
||||
|
||||
### Requirement: Token introspection (RFC 7662)
|
||||
The system SHALL determine whether a given access token is currently active (valid, not expired, not revoked). The endpoint SHALL return `200 OK` for both active and inactive tokens — the `active` field in the response SHALL indicate validity. The caller SHALL hold a valid Bearer token with `tokens:read` scope.
|
||||
|
||||
#### Scenario: Active token introspection
|
||||
- **WHEN** a POST request to `/token/introspect` is received with a valid, non-expired, non-revoked token and the caller has `tokens:read` scope
|
||||
- **THEN** the system returns `200 OK` with `active: true` and the token's claims (`sub`, `client_id`, `scope`, `token_type`, `iat`, `exp`)
|
||||
|
||||
#### Scenario: Expired or revoked token introspection
|
||||
- **WHEN** a POST request to `/token/introspect` is received with a token that is expired or has been revoked
|
||||
- **THEN** the system returns `200 OK` with `active: false` and no other claims
|
||||
|
||||
#### Scenario: Insufficient scope for introspection
|
||||
- **WHEN** a POST request to `/token/introspect` is received with a valid Bearer token that does not have `tokens:read` scope
|
||||
- **THEN** the system returns `403 Forbidden` with `code: INSUFFICIENT_SCOPE`
|
||||
|
||||
### Requirement: Token revocation (RFC 7009)
|
||||
The system SHALL invalidate a given access token immediately. Revoking an already-revoked or expired token SHALL be a successful, idempotent operation (RFC 7009 §2.1). Revoked token JTIs SHALL be stored in Redis with TTL equal to the token's remaining lifetime.
|
||||
|
||||
#### Scenario: Successful token revocation
|
||||
- **WHEN** a POST request to `/token/revoke` is received with a valid Bearer token and a `token` parameter containing a valid JWT
|
||||
- **THEN** the system adds the token's JTI to the Redis revocation list, and returns `200 OK` with an empty body
|
||||
|
||||
#### Scenario: Revocation of already-revoked token is idempotent
|
||||
- **WHEN** a POST request to `/token/revoke` is received with a token that is already in the Redis revocation list
|
||||
- **THEN** the system returns `200 OK` with an empty body (no error)
|
||||
|
||||
#### Scenario: Missing token parameter rejected
|
||||
- **WHEN** a POST request to `/token/revoke` is received with no `token` field in the body
|
||||
- **THEN** the system returns `400 Bad Request` with `code: VALIDATION_ERROR`
|
||||
|
||||
### Requirement: JWT claims structure
|
||||
All issued JWTs SHALL contain the following claims: `sub` (agentId), `client_id` (agentId), `scope` (space-separated granted scopes), `jti` (UUID, unique per token), `iat` (issued-at Unix timestamp), `exp` (expiry Unix timestamp). Tokens SHALL be signed with RS256.
|
||||
|
||||
#### Scenario: JWT contains required claims
|
||||
- **WHEN** a token is issued via `POST /token`
|
||||
- **THEN** the decoded JWT payload contains `sub`, `client_id`, `scope`, `jti`, `iat`, and `exp` fields
|
||||
|
||||
### Requirement: Rate limiting on token endpoints
|
||||
The system SHALL enforce a rate limit of 100 requests per minute per `client_id` on all token endpoints.
|
||||
|
||||
#### Scenario: Rate limit exceeded on token endpoint
|
||||
- **WHEN** a client sends more than 100 requests to any token endpoint within a 60-second window
|
||||
- **THEN** the system returns `429 Too Many Requests` with `X-RateLimit-Limit`, `X-RateLimit-Remaining: 0`, and `X-RateLimit-Reset` headers
|
||||
@@ -0,0 +1,83 @@
|
||||
## 1. Project Bootstrap & Infrastructure
|
||||
|
||||
- [x] 1.1 Initialise `package.json` with all required dependencies (Express, TypeScript, Joi, jsonwebtoken, bcryptjs, uuid, pg, redis, pino, helmet, cors, dotenv, jest, supertest, ts-jest, ESLint, Prettier)
|
||||
- [x] 1.2 Create `tsconfig.json` with strict mode enabled (all flags from README §6.4)
|
||||
- [x] 1.3 Create `.eslintrc.json` with `@typescript-eslint` plugin and no-`any` rule
|
||||
- [x] 1.4 Create `.prettierrc`
|
||||
- [x] 1.5 Create `jest.config.ts` with `ts-jest` preset and coverage thresholds (>80%)
|
||||
- [x] 1.6 Create `docker-compose.yml` with `postgres:14-alpine` and `redis:7-alpine` services
|
||||
- [x] 1.7 Create `.env.example` documenting all required environment variables (`DATABASE_URL`, `REDIS_URL`, `JWT_PRIVATE_KEY`, `JWT_PUBLIC_KEY`, `PORT`, etc.)
|
||||
|
||||
## 2. Shared Infrastructure
|
||||
|
||||
- [x] 2.1 Create `src/types/index.ts` — all shared TypeScript interfaces (`IAgent`, `ICredential`, `IAuditEvent`, `ITokenPayload`, `ICreateAgentRequest`, `IUpdateAgentRequest`, etc.)
|
||||
- [x] 2.2 Create `src/utils/errors.ts` — full `SentryAgentError` hierarchy (`ValidationError`, `AgentNotFoundError`, `AgentAlreadyExistsError`, `CredentialError`, `AuthenticationError`, `AuthorizationError`, `RateLimitError`, `FreeTierLimitError`)
|
||||
- [x] 2.3 Create `src/utils/crypto.ts` — `generateClientSecret()` (sk_live_ prefix + 64 hex), `hashSecret(plain)` (bcrypt 10 rounds), `verifySecret(plain, hash)` (bcrypt compare)
|
||||
- [x] 2.4 Create `src/utils/jwt.ts` — `signToken(payload, privateKey)` (RS256), `verifyToken(token, publicKey)` (returns typed payload), `decodeToken(token)` (no verification)
|
||||
- [x] 2.5 Create `src/utils/validators.ts` — Joi schemas for `CreateAgentRequest`, `UpdateAgentRequest`, `TokenRequest`, `IntrospectRequest`, `RevokeRequest`, `GenerateCredentialRequest`, list query params
|
||||
- [x] 2.6 Create `src/db/pool.ts` — typed `pg.Pool` singleton, reads `DATABASE_URL` from env
|
||||
- [x] 2.7 Create `src/cache/redis.ts` — typed Redis client singleton, reads `REDIS_URL` from env
|
||||
- [x] 2.8 Create `src/db/migrations/001_create_agents.sql` — `agents` table (all fields from OpenAPI spec, `status` as varchar)
|
||||
- [x] 2.9 Create `src/db/migrations/002_create_credentials.sql` — `credentials` table (`credential_id`, `client_id`, `secret_hash`, `status`, `created_at`, `expires_at`, `revoked_at`)
|
||||
- [x] 2.10 Create `src/db/migrations/003_create_audit_events.sql` — `audit_events` table (`event_id`, `agent_id`, `action`, `outcome`, `ip_address`, `user_agent`, `metadata` JSONB, `timestamp`)
|
||||
- [x] 2.11 Create `src/db/migrations/004_create_tokens.sql` — `token_revocations` table (`jti`, `expires_at`) for soft revocation tracking (supplementary to Redis)
|
||||
- [x] 2.12 Create `npm run db:migrate` script to execute migrations in order
|
||||
|
||||
## 3. Middleware
|
||||
|
||||
- [x] 3.1 Create `src/middleware/auth.ts` — Bearer token extraction from `Authorization` header, RS256 JWT verification, Redis revocation check, attaches decoded payload to `req.user`; throws `AuthenticationError` on failure
|
||||
- [x] 3.2 Create `src/middleware/rateLimit.ts` — Redis sliding window counter keyed by `client_id`; injects `X-RateLimit-*` headers on every response; throws `RateLimitError` at 100 req/min
|
||||
- [x] 3.3 Create `src/middleware/errorHandler.ts` — Express error middleware; maps `SentryAgentError` subclasses to HTTP status codes and `ErrorResponse` JSON; maps unknown errors to `500`
|
||||
|
||||
## 4. Agent Registry
|
||||
|
||||
- [x] 4.1 Create `src/repositories/AgentRepository.ts` — typed methods: `create`, `findById`, `findByEmail`, `findAll` (with filters + pagination), `update`, `decommission`, `countByOwner`; all SQL in this file only
|
||||
- [x] 4.2 Create `src/services/AgentService.ts` — `registerAgent`, `getAgentById`, `listAgents`, `updateAgent`, `decommissionAgent`; enforces free-tier 100-agent limit; validates immutable fields on update; calls `AuditService` for all write operations; JSDoc on all public methods
|
||||
- [x] 4.3 Create `src/controllers/AgentController.ts` — HTTP handlers for all 5 agent endpoints; Joi validation using `validators.ts`; delegates to `AgentService`; no business logic
|
||||
- [x] 4.4 Create `src/routes/agents.ts` — Express router wiring `AgentController` handlers to paths with `auth` and `rateLimit` middleware
|
||||
|
||||
## 5. OAuth 2.0 Token Service
|
||||
|
||||
- [x] 5.1 Create `src/repositories/TokenRepository.ts` — `addToRevocationList(jti, expiresAt)`, `isRevoked(jti)` (checks Redis first, then DB); `incrementMonthlyCount(clientId)`, `getMonthlyCount(clientId)` (Redis-backed)
|
||||
- [x] 5.2 Create `src/services/OAuth2Service.ts` — `issueToken` (validates client credentials via bcrypt, checks agent status, enforces 10k monthly limit, signs RS256 JWT, writes audit event), `introspectToken` (verifies + checks revocation), `revokeToken` (adds JTI to Redis + DB revocation list, writes audit event); JSDoc on all public methods
|
||||
- [x] 5.3 Create `src/controllers/TokenController.ts` — HTTP handlers for `POST /token`, `POST /token/introspect`, `POST /token/revoke`; parses `application/x-www-form-urlencoded`; delegates to `OAuth2Service`; returns `OAuth2ErrorResponse` for `/token` errors, `ErrorResponse` for introspect/revoke errors
|
||||
- [x] 5.4 Create `src/routes/token.ts` — Express router; `/token` uses no Bearer auth middleware (credentials are in body); `/token/introspect` and `/token/revoke` use `auth` middleware
|
||||
|
||||
## 6. Credential Management
|
||||
|
||||
- [x] 6.1 Create `src/repositories/CredentialRepository.ts` — `create`, `findById`, `findByAgentId` (with pagination + status filter), `updateHash`, `revoke`, `revokeAllForAgent`; all SQL here only
|
||||
- [x] 6.2 Create `src/services/CredentialService.ts` — `generateCredential` (checks agent active status, generates secret via `crypto.ts`, bcrypt-hashes, persists), `listCredentials`, `rotateCredential` (generates new secret, replaces hash, same credentialId), `revokeCredential`; calls `AuditService` for all write operations; JSDoc on all public methods
|
||||
- [x] 6.3 Create `src/controllers/CredentialController.ts` — HTTP handlers for all 4 credential endpoints; Joi validation; delegates to `CredentialService`
|
||||
- [x] 6.4 Create `src/routes/credentials.ts` — Express router under `/agents/:agentId/credentials` with `auth` and `rateLimit` middleware
|
||||
|
||||
## 7. Audit Log Service
|
||||
|
||||
- [x] 7.1 Create `src/repositories/AuditRepository.ts` — `create(event)`, `findById(eventId)`, `findAll(filters, pagination)` with support for `agentId`, `action`, `outcome`, `fromDate`, `toDate` filtering and 90-day retention window enforcement
|
||||
- [x] 7.2 Create `src/services/AuditService.ts` — `logEvent(agentId, action, outcome, ipAddress, userAgent, metadata)` (async insert, fire-and-forget for token endpoints); `queryEvents(filters, pagination)`, `getEventById(eventId)`; enforces 90-day retention on queries; JSDoc on all public methods
|
||||
- [x] 7.3 Create `src/controllers/AuditController.ts` — HTTP handlers for `GET /audit` and `GET /audit/{eventId}`; scope check for `audit:read`; Joi validation of query params
|
||||
- [x] 7.4 Create `src/routes/audit.ts` — Express router with `auth` and `rateLimit` middleware
|
||||
|
||||
## 8. Application Assembly
|
||||
|
||||
- [x] 8.1 Create `src/app.ts` — Express app factory: registers `helmet`, `cors`, `morgan`/`pino-http`, JSON body parser, `urlencoded` body parser (for token endpoints), all 4 route modules, and `errorHandler` middleware; exported function (not called directly — testable)
|
||||
- [x] 8.2 Create `src/server.ts` — imports `app.ts`, reads `PORT` from env, calls `app.listen`; entry point only
|
||||
|
||||
## 9. Unit Tests
|
||||
|
||||
- [x] 9.1 Write unit tests for `src/utils/crypto.ts` — secret generation format, bcrypt hash/verify round-trip
|
||||
- [x] 9.2 Write unit tests for `src/utils/jwt.ts` — sign/verify/decode with RS256 test keys
|
||||
- [x] 9.3 Write unit tests for `src/utils/validators.ts` — valid and invalid inputs for every Joi schema
|
||||
- [x] 9.4 Write unit tests for `src/services/AgentService.ts` — mock `AgentRepository` and `AuditService`; cover all scenarios from agent-registry spec
|
||||
- [x] 9.5 Write unit tests for `src/services/OAuth2Service.ts` — mock `TokenRepository`, `CredentialRepository`, `AuditService`; cover all scenarios from oauth2-token spec
|
||||
- [x] 9.6 Write unit tests for `src/services/CredentialService.ts` — mock `CredentialRepository`, `AgentRepository`, `AuditService`; cover all scenarios from credential-management spec
|
||||
- [x] 9.7 Write unit tests for `src/services/AuditService.ts` — mock `AuditRepository`; cover query, filter, and retention logic
|
||||
- [x] 9.8 Write unit tests for `src/middleware/auth.ts` — valid token, expired token, revoked token, missing header
|
||||
- [x] 9.9 Write unit tests for `src/middleware/errorHandler.ts` — each `SentryAgentError` subclass maps to correct HTTP status and error code
|
||||
|
||||
## 10. Integration Tests
|
||||
|
||||
- [x] 10.1 Write integration tests for Agent Registry (`tests/integration/agents.test.ts`) — all 5 endpoints, all response codes, pagination, filtering; uses real Postgres (test DB) and Redis
|
||||
- [x] 10.2 Write integration tests for OAuth2 Token Service (`tests/integration/token.test.ts`) — all 3 endpoints, all response codes, token issuance and revocation flow, RFC compliance
|
||||
- [x] 10.3 Write integration tests for Credential Management (`tests/integration/credentials.test.ts`) — all 4 endpoints, all response codes, full rotate-then-revoke flow
|
||||
- [x] 10.4 Write integration tests for Audit Log Service (`tests/integration/audit.test.ts`) — query with all filter combinations, single event retrieval, retention window enforcement
|
||||
- [x] 10.5 Verify test coverage meets >80% threshold across all services (`npm test -- --coverage`)
|
||||
2
openspec/changes/bedroom-developer-docs/.openspec.yaml
Normal file
2
openspec/changes/bedroom-developer-docs/.openspec.yaml
Normal file
@@ -0,0 +1,2 @@
|
||||
schema: spec-driven
|
||||
created: 2026-03-28
|
||||
63
openspec/changes/bedroom-developer-docs/design.md
Normal file
63
openspec/changes/bedroom-developer-docs/design.md
Normal file
@@ -0,0 +1,63 @@
|
||||
## Context
|
||||
|
||||
Phase 1 MVP is complete: 46 source files, 14 API endpoints across 4 OpenAPI 3.0 specs, 244 passing tests. The implementation is production-grade and live on `git.sentryagent.ai`. However, the developer experience stops at the code. There is no entry point for a bedroom developer who has never heard of AgentIdP, AGNTCY, or client credentials OAuth 2.0.
|
||||
|
||||
The documentation must be written, owned, and maintained as a first-class deliverable — not an afterthought. It is produced by a Virtual Technical Writer subagent with full access to the codebase and OpenAPI specs.
|
||||
|
||||
**Constraints:**
|
||||
- Audience: bedroom developers — assume competence with HTTP and basic programming, assume no prior knowledge of AgentIdP or AGNTCY
|
||||
- Format: Markdown only — renders on GitHub, no external tooling required
|
||||
- No build step — docs are static `.md` files in `docs/developers/`
|
||||
- All code examples must be real, runnable, and copy-pasteable
|
||||
- Tone: direct, practical, no enterprise jargon
|
||||
|
||||
## Goals / Non-Goals
|
||||
|
||||
**Goals:**
|
||||
- Bedroom developer can register their first agent and issue a token in under 5 minutes using only the quick-start guide
|
||||
- Every API endpoint is documented in plain English with at least one working curl example
|
||||
- Core concepts are explained without assuming prior knowledge of OAuth 2.0 or AGNTCY
|
||||
- All four P0 workflows (register, credential, token, audit) have step-by-step guides
|
||||
- FAQ covers the most likely failure points and free-tier limits
|
||||
|
||||
**Non-Goals:**
|
||||
- No web-rendered documentation site (Phase 2 — out of scope)
|
||||
- No SDK documentation (Node.js SDK not yet built — Phase 1 P1 remaining)
|
||||
- No video tutorials or interactive demos
|
||||
- No multi-language code examples (Node.js + curl only for now)
|
||||
- No enterprise deployment documentation (separate from bedroom developer focus)
|
||||
|
||||
## Decisions
|
||||
|
||||
**Decision 1: Single flat folder vs nested structure**
|
||||
Chosen: flat `docs/developers/` with a `tutorials/` subfolder only for multi-step guides.
|
||||
Alternative considered: deep nesting by category. Rejected — adds navigation friction for a small doc set.
|
||||
|
||||
**Decision 2: Raw OpenAPI YAML as API reference vs human-written reference**
|
||||
Chosen: human-written `api-reference.md` alongside the existing OpenAPI specs.
|
||||
Alternative considered: link to raw YAML only. Rejected — YAML is not readable for bedroom developers; the whole point is accessibility.
|
||||
|
||||
**Decision 3: Standalone docs vs inline code comments**
|
||||
Chosen: standalone Markdown files in `docs/developers/`.
|
||||
Alternative considered: JSDoc-generated docs. Rejected — JSDoc is for library consumers, not REST API users.
|
||||
|
||||
**Decision 4: Who writes the docs**
|
||||
Chosen: Virtual Technical Writer subagent — spawned by CTO with full codebase + OpenAPI spec context.
|
||||
Alternative considered: Virtual Principal Developer writes docs. Rejected — developer time should stay on code; writing accessible prose for non-technical audiences is a distinct skill warranting a dedicated role.
|
||||
|
||||
**Decision 5: Versioning**
|
||||
Chosen: docs live in the same repo as code, versioned together via git. No separate docs versioning scheme in Phase 1.
|
||||
|
||||
## Risks / Trade-offs
|
||||
|
||||
- **[Risk] Docs drift from implementation** → Mitigation: Virtual QA Engineer verifies API reference examples against actual endpoints before sign-off; curl examples are tested against a running instance
|
||||
- **[Risk] Tone inconsistency across docs** → Mitigation: Technical Writer receives a unified style brief in the subagent prompt (plain English, second person, imperative voice, no jargon)
|
||||
- **[Risk] Quick-start prerequisites unclear** → Mitigation: Quick-start lists exact prerequisites (Docker, curl, nothing else) and links to docker-compose.yml
|
||||
|
||||
## Migration Plan
|
||||
|
||||
Documentation only — no migration required. Files are added to `docs/developers/` and committed to `develop`. No rollback needed.
|
||||
|
||||
## Open Questions
|
||||
|
||||
*(none — scope is fully defined)*
|
||||
34
openspec/changes/bedroom-developer-docs/proposal.md
Normal file
34
openspec/changes/bedroom-developer-docs/proposal.md
Normal file
@@ -0,0 +1,34 @@
|
||||
## Why
|
||||
|
||||
SentryAgent.ai AgentIdP Phase 1 MVP is fully implemented, tested, and live — but there is zero human-readable documentation for the developers we are building this for. A bedroom developer landing on this repo today cannot register their first agent without reading raw OpenAPI YAML or diving into source code. We fix that now.
|
||||
|
||||
## What Changes
|
||||
|
||||
- New `docs/developers/` folder containing a complete, self-contained documentation set for bedroom developers
|
||||
- Quick-start guide: first agent registered and authenticated in under 5 minutes
|
||||
- Core concepts doc: plain-English explanation of AgentIdP, AGNTCY alignment, and the agent identity model
|
||||
- Step-by-step guides: agent registration, credential management, token issuance, audit log queries
|
||||
- Human-friendly API reference: every endpoint documented with real curl examples and response samples
|
||||
- FAQ: common errors, gotchas, and free-tier limits explained
|
||||
- All docs written for a bedroom developer audience — no enterprise jargon, no assumed knowledge
|
||||
|
||||
## Capabilities
|
||||
|
||||
### New Capabilities
|
||||
|
||||
- `quick-start`: 5-minute guide from zero to first authenticated agent request — install, register, credential, token, done
|
||||
- `core-concepts`: Plain-English explanation of what AgentIdP is, how it relates to AGNTCY, the agent identity lifecycle, and why it matters
|
||||
- `developer-guides`: Step-by-step tutorials for the four core workflows: registering an agent, managing credentials, issuing and revoking tokens, querying the audit log
|
||||
- `api-reference`: Human-friendly API reference covering all 14 endpoints with real examples, field descriptions, error codes, and rate limit notes
|
||||
|
||||
### Modified Capabilities
|
||||
|
||||
*(none — this change introduces documentation only; no existing API specs are modified)*
|
||||
|
||||
## Impact
|
||||
|
||||
- New folder: `docs/developers/` (7 markdown files)
|
||||
- No code changes — documentation only
|
||||
- No new dependencies
|
||||
- No API changes
|
||||
- Existing `docs/openapi/` specs are reference material for the Technical Writer but are not modified
|
||||
@@ -0,0 +1,50 @@
|
||||
## ADDED Requirements
|
||||
|
||||
### Requirement: API reference exists at docs/developers/api-reference.md
|
||||
The system SHALL provide a human-readable API reference at `docs/developers/api-reference.md` covering all 14 endpoints across the four services: Agent Registry, OAuth 2.0 Token, Credential Management, and Audit Log.
|
||||
|
||||
#### Scenario: Developer finds any endpoint within 10 seconds
|
||||
- **WHEN** the developer opens the API reference
|
||||
- **THEN** they SHALL find a table of contents at the top linking to each of the four service sections
|
||||
|
||||
### Requirement: Every endpoint is documented with method, path, description, and auth requirements
|
||||
For each of the 14 endpoints, the reference SHALL document: HTTP method, path, one-sentence description, and whether Bearer token auth is required.
|
||||
|
||||
#### Scenario: Developer knows which endpoints require authentication
|
||||
- **WHEN** the developer scans the reference
|
||||
- **THEN** they SHALL clearly see which endpoints require a Bearer token (all except POST /token) and which do not
|
||||
|
||||
### Requirement: Every endpoint includes a complete curl example
|
||||
For each endpoint, the reference SHALL include at least one complete, runnable curl example with real placeholder values.
|
||||
|
||||
#### Scenario: Developer copies a curl example and runs it
|
||||
- **WHEN** the developer copies a curl example from the reference
|
||||
- **THEN** the command SHALL be complete — no ellipses, no `...`, no missing flags — requiring only substitution of their own agentId, token, and base URL
|
||||
|
||||
### Requirement: Every endpoint documents all request parameters and body fields
|
||||
For each endpoint that accepts a request body or query parameters, the reference SHALL list every field with: name, type, required/optional, description, and validation constraints.
|
||||
|
||||
#### Scenario: Developer knows what fields are required for POST /agents
|
||||
- **WHEN** the developer reads the POST /agents section
|
||||
- **THEN** they SHALL see a table listing every field, its type, whether it is required, and any constraints (e.g. email format, max length)
|
||||
|
||||
### Requirement: Every endpoint documents all response codes and response body schemas
|
||||
For each endpoint, the reference SHALL document every possible HTTP response code (2xx and 4xx/5xx) with a description and example response body.
|
||||
|
||||
#### Scenario: Developer understands a 429 response
|
||||
- **WHEN** the developer reads the rate limit error documentation
|
||||
- **THEN** they SHALL understand what triggered it, what the X-RateLimit-* headers mean, and when they can retry
|
||||
|
||||
### Requirement: API reference includes a base URL and versioning section
|
||||
The reference SHALL include a section at the top explaining the base URL convention, port configuration, and that all endpoints are unversioned in Phase 1.
|
||||
|
||||
#### Scenario: Developer knows where to send requests
|
||||
- **WHEN** the developer reads the base URL section
|
||||
- **THEN** they SHALL see the default base URL (http://localhost:3000), how to change the port via environment variable, and a note that versioning will be introduced in Phase 2
|
||||
|
||||
### Requirement: API reference includes an errors section
|
||||
The reference SHALL include a dedicated errors section listing all standard error response shapes, all custom error codes, and their HTTP status code mappings.
|
||||
|
||||
#### Scenario: Developer handles an AgentNotFoundError
|
||||
- **WHEN** the developer reads the errors section
|
||||
- **THEN** they SHALL see the exact JSON shape of the error response, the error code string, and the HTTP status (404)
|
||||
@@ -0,0 +1,43 @@
|
||||
## ADDED Requirements
|
||||
|
||||
### Requirement: Core concepts guide exists at docs/developers/concepts.md
|
||||
The system SHALL provide a concepts guide at `docs/developers/concepts.md` that explains the AgentIdP model in plain English with no assumed prior knowledge of AGNTCY or OAuth 2.0.
|
||||
|
||||
#### Scenario: Developer understands what AgentIdP is
|
||||
- **WHEN** a developer reads the concepts guide
|
||||
- **THEN** they SHALL be able to explain in one sentence what SentryAgent.ai AgentIdP does and why they need it
|
||||
|
||||
### Requirement: Concepts guide explains what an AI agent identity is
|
||||
The guide SHALL explain in plain English what it means to give an AI agent an identity — how it differs from a human user account and why agents need their own identity model.
|
||||
|
||||
#### Scenario: Agent identity vs human identity distinction is clear
|
||||
- **WHEN** the developer reads the agent identity section
|
||||
- **THEN** they SHALL understand that agents are non-human, machine-operated identities that need persistent, auditable credentials — not session-based logins
|
||||
|
||||
### Requirement: Concepts guide explains the AGNTCY alignment
|
||||
The guide SHALL explain what AGNTCY is (Linux Foundation standard), why SentryAgent.ai aligns to it, and what benefit that gives the developer — without requiring the developer to read the AGNTCY specification.
|
||||
|
||||
#### Scenario: Developer understands AGNTCY without external reading
|
||||
- **WHEN** the developer reads the AGNTCY section
|
||||
- **THEN** they SHALL understand that AGNTCY-aligned agent IDs are interoperable across the AI agent ecosystem, and that SentryAgent.ai implements this for free
|
||||
|
||||
### Requirement: Concepts guide explains the agent lifecycle
|
||||
The guide SHALL explain the four lifecycle states of an agent (active, suspended, decommissioned) and what each state means for credential and token behaviour.
|
||||
|
||||
#### Scenario: Developer understands what happens when an agent is decommissioned
|
||||
- **WHEN** the developer reads the lifecycle section
|
||||
- **THEN** they SHALL understand that decommissioning is irreversible, all credentials are revoked, and no new tokens can be issued
|
||||
|
||||
### Requirement: Concepts guide explains OAuth 2.0 Client Credentials in plain English
|
||||
The guide SHALL explain the Client Credentials grant in plain English — no RFC references, no formal OAuth jargon — focused on how agents use it to authenticate.
|
||||
|
||||
#### Scenario: Developer understands client_id and client_secret without prior OAuth knowledge
|
||||
- **WHEN** the developer reads the OAuth section
|
||||
- **THEN** they SHALL understand that client_id identifies the agent and client_secret proves it — analogous to a username and password for machines
|
||||
|
||||
### Requirement: Concepts guide explains the free-tier limits
|
||||
The guide SHALL document all free-tier limits (100 agents, 10,000 tokens/month, 100 req/min, 90-day audit retention) in a clear table.
|
||||
|
||||
#### Scenario: Developer knows the limits before hitting them
|
||||
- **WHEN** the developer reads the free-tier section
|
||||
- **THEN** they SHALL see a table with all four limits and a note on what happens when each is exceeded
|
||||
@@ -0,0 +1,56 @@
|
||||
## ADDED Requirements
|
||||
|
||||
### Requirement: Developer guides index exists at docs/developers/guides/README.md
|
||||
The system SHALL provide a guides index at `docs/developers/guides/README.md` listing all available guides with one-line descriptions and links.
|
||||
|
||||
#### Scenario: Developer finds the right guide quickly
|
||||
- **WHEN** the developer opens the guides folder
|
||||
- **THEN** they SHALL see a list of all guides with descriptions so they can choose the one relevant to their task
|
||||
|
||||
### Requirement: Agent registration guide exists at docs/developers/guides/register-an-agent.md
|
||||
The system SHALL provide a step-by-step guide for registering an agent, including all required and optional fields, validation rules, and how to handle the response.
|
||||
|
||||
#### Scenario: Developer registers their first agent
|
||||
- **WHEN** the developer follows the registration guide
|
||||
- **THEN** they SHALL successfully create an agent and understand what `agentId`, `clientId`, and `status` mean in the response
|
||||
|
||||
#### Scenario: Developer understands registration validation errors
|
||||
- **WHEN** the guide covers validation
|
||||
- **THEN** it SHALL show examples of common validation errors (missing required fields, invalid email format) and how to fix them
|
||||
|
||||
### Requirement: Credential management guide exists at docs/developers/guides/manage-credentials.md
|
||||
The system SHALL provide a guide covering all four credential operations: generate, list, rotate, and revoke — with curl examples and explanation of when to use each.
|
||||
|
||||
#### Scenario: Developer rotates a compromised credential
|
||||
- **WHEN** the developer follows the rotation section
|
||||
- **THEN** they SHALL understand that rotation replaces the secret while keeping the same `credentialId`, and the old secret is immediately invalid
|
||||
|
||||
#### Scenario: Developer understands credential revocation vs agent decommission
|
||||
- **WHEN** the developer reads the guide
|
||||
- **THEN** they SHALL understand the difference: revoking a credential leaves the agent active with other credentials; decommissioning the agent revokes everything permanently
|
||||
|
||||
### Requirement: Token guide exists at docs/developers/guides/issue-and-revoke-tokens.md
|
||||
The system SHALL provide a guide covering token issuance, introspection, and revocation — explaining the JWT structure, expiry, and how to use the Bearer token in API requests.
|
||||
|
||||
#### Scenario: Developer uses a token to authenticate a request
|
||||
- **WHEN** the developer follows the token guide
|
||||
- **THEN** they SHALL see an example of using the issued token as a Bearer token in an Authorization header on a subsequent API call
|
||||
|
||||
#### Scenario: Developer introspects a token to check validity
|
||||
- **WHEN** the developer reads the introspection section
|
||||
- **THEN** they SHALL understand what `active: true/false` means and what fields are returned
|
||||
|
||||
#### Scenario: Developer revokes a token
|
||||
- **WHEN** the developer follows the revocation section
|
||||
- **THEN** they SHALL understand that revoked tokens are immediately invalid even if not yet expired
|
||||
|
||||
### Requirement: Audit log guide exists at docs/developers/guides/query-audit-logs.md
|
||||
The system SHALL provide a guide for querying the audit log — covering available filters (agentId, action, outcome, date range), pagination, and how to interpret audit events.
|
||||
|
||||
#### Scenario: Developer queries audit events for a specific agent
|
||||
- **WHEN** the developer follows the audit guide
|
||||
- **THEN** they SHALL see a curl example filtering by `agentId` and understand the structure of each audit event
|
||||
|
||||
#### Scenario: Developer understands audit log retention
|
||||
- **WHEN** the developer reads the guide
|
||||
- **THEN** they SHALL understand that free-tier audit logs are retained for 90 days and what happens after that window
|
||||
@@ -0,0 +1,45 @@
|
||||
## ADDED Requirements
|
||||
|
||||
### Requirement: Quick-start guide exists at docs/developers/quick-start.md
|
||||
The system SHALL provide a quick-start guide at `docs/developers/quick-start.md` that enables a bedroom developer to register their first agent and issue an OAuth 2.0 access token in under 5 minutes.
|
||||
|
||||
#### Scenario: Developer completes quick-start from zero
|
||||
- **WHEN** a developer with no prior AgentIdP knowledge follows the quick-start guide
|
||||
- **THEN** they SHALL have a registered agent, a valid credential, and a working access token by the end
|
||||
|
||||
### Requirement: Quick-start lists exact prerequisites
|
||||
The quick-start guide SHALL list all prerequisites at the top before any steps, so the developer knows what they need before starting.
|
||||
|
||||
#### Scenario: Prerequisites are minimal and explicit
|
||||
- **WHEN** the developer reads the prerequisites section
|
||||
- **THEN** they SHALL see exactly: Docker (for running PostgreSQL and Redis) and curl (for API calls) — nothing else required
|
||||
|
||||
### Requirement: Quick-start provides a working docker-compose startup command
|
||||
The quick-start guide SHALL include a single command to start the required infrastructure (PostgreSQL + Redis) using the project's `docker-compose.yml`.
|
||||
|
||||
#### Scenario: Developer starts infrastructure
|
||||
- **WHEN** the developer runs the provided docker-compose command
|
||||
- **THEN** the guide SHALL confirm what services are started and what ports they run on
|
||||
|
||||
### Requirement: Quick-start covers the full 4-step workflow
|
||||
The quick-start guide SHALL cover exactly these four steps in order, each with a working curl command and the expected response:
|
||||
|
||||
1. Start the AgentIdP server
|
||||
2. Register an agent (`POST /agents`)
|
||||
3. Generate a credential (`POST /agents/{agentId}/credentials`)
|
||||
4. Issue an access token (`POST /token`)
|
||||
|
||||
#### Scenario: Each step has a copy-pasteable curl command
|
||||
- **WHEN** the developer reads any step
|
||||
- **THEN** they SHALL find a complete curl command with real placeholder values they can substitute
|
||||
|
||||
#### Scenario: Each step shows the expected JSON response
|
||||
- **WHEN** the developer runs a curl command from the guide
|
||||
- **THEN** the guide SHALL show them what a successful response looks like so they can verify their output
|
||||
|
||||
### Requirement: Quick-start ends with a next-steps section
|
||||
The quick-start guide SHALL end with a "What's Next" section linking to: core-concepts.md, developer-guides.md, and api-reference.md.
|
||||
|
||||
#### Scenario: Developer knows where to go after quick-start
|
||||
- **WHEN** the developer reaches the end of the quick-start
|
||||
- **THEN** they SHALL see at least 3 links to deeper documentation
|
||||
50
openspec/changes/bedroom-developer-docs/tasks.md
Normal file
50
openspec/changes/bedroom-developer-docs/tasks.md
Normal file
@@ -0,0 +1,50 @@
|
||||
## 1. Folder Structure & Setup
|
||||
|
||||
- [x] 1.1 Create `docs/developers/` directory
|
||||
- [x] 1.2 Create `docs/developers/guides/` subdirectory
|
||||
- [x] 1.3 Create `docs/developers/README.md` — index page listing all docs with one-line descriptions and links
|
||||
|
||||
## 2. Quick-Start Guide
|
||||
|
||||
- [x] 2.1 Create `docs/developers/quick-start.md` — prerequisites section (Docker + curl only)
|
||||
- [x] 2.2 Write Step 1: start infrastructure with docker-compose command + confirmation of services and ports
|
||||
- [x] 2.3 Write Step 2: start AgentIdP server with npm command + expected startup output
|
||||
- [x] 2.4 Write Step 3: register an agent — complete curl for `POST /agents` with example request body and expected JSON response
|
||||
- [x] 2.5 Write Step 4: generate a credential — complete curl for `POST /agents/{agentId}/credentials` with example response showing `clientId` and `clientSecret`
|
||||
- [x] 2.6 Write Step 5: issue an access token — complete curl for `POST /token` with form-encoded body and example JWT response
|
||||
- [x] 2.7 Write "What's Next" section linking to concepts.md, guides/README.md, and api-reference.md
|
||||
|
||||
## 3. Core Concepts Guide
|
||||
|
||||
- [x] 3.1 Create `docs/developers/concepts.md` — intro section: what is AgentIdP in one paragraph
|
||||
- [x] 3.2 Write "What is an AI Agent Identity" section — plain-English explanation of agent identities vs human identities
|
||||
- [x] 3.3 Write "AGNTCY Alignment" section — what AGNTCY is, why it matters, benefit to the developer (no external reading required)
|
||||
- [x] 3.4 Write "Agent Lifecycle" section — four states (active, suspended, decommissioned) and what each means for credentials and tokens, including irreversibility of decommission
|
||||
- [x] 3.5 Write "OAuth 2.0 Client Credentials" section — plain-English explanation of client_id, client_secret, and how agents use them; no RFC jargon
|
||||
- [x] 3.6 Write "Free Tier Limits" section — table of all four limits (100 agents, 10k tokens/month, 100 req/min, 90-day audit) with notes on what happens when each is exceeded
|
||||
|
||||
## 4. Developer Guides
|
||||
|
||||
- [x] 4.1 Create `docs/developers/guides/README.md` — index listing all four guides with descriptions and links
|
||||
- [x] 4.2 Create `docs/developers/guides/register-an-agent.md` — step-by-step registration guide with all required/optional fields, validation rules, and example success + error responses (including common validation errors and fixes)
|
||||
- [x] 4.3 Create `docs/developers/guides/manage-credentials.md` — guide covering all four credential operations: generate (with secret handling note), list (with pagination), rotate (explaining same credentialId, old secret immediately invalid), revoke (with comparison to agent decommission)
|
||||
- [x] 4.4 Create `docs/developers/guides/issue-and-revoke-tokens.md` — token guide covering: issuance with form-encoded body, JWT structure explanation, using token as Bearer in subsequent requests, introspection (`active` field), revocation and immediate invalidation
|
||||
- [x] 4.5 Create `docs/developers/guides/query-audit-logs.md` — audit log guide covering: available filters (agentId, action, outcome, date range), pagination params, audit event structure, 90-day retention behaviour
|
||||
|
||||
## 5. API Reference
|
||||
|
||||
- [x] 5.1 Create `docs/developers/api-reference.md` — top section: base URL, port config via env var, versioning note (Phase 1 unversioned)
|
||||
- [x] 5.2 Write table of contents linking to all four service sections
|
||||
- [x] 5.3 Write errors reference section: all error response shapes, all custom error codes (ValidationError, AgentNotFoundError, AgentAlreadyExistsError, CredentialError, AuthenticationError, AuthorizationError, RateLimitError, FreeTierLimitError), HTTP status mappings
|
||||
- [x] 5.4 Document Agent Registry endpoints (5): `POST /agents`, `GET /agents`, `GET /agents/{agentId}`, `PATCH /agents/{agentId}`, `DELETE /agents/{agentId}` — each with method, path, auth requirement, request fields table, response codes table, and complete curl example
|
||||
- [x] 5.5 Document OAuth 2.0 Token endpoints (3): `POST /token`, `POST /token/introspect`, `POST /token/revoke` — each with method, path, auth requirement, request fields table (noting form-encoded for /token), response codes table, curl example, and X-RateLimit header documentation for 429s
|
||||
- [x] 5.6 Document Credential Management endpoints (4): `POST /agents/{agentId}/credentials`, `GET /agents/{agentId}/credentials`, `POST /agents/{agentId}/credentials/{credentialId}/rotate`, `DELETE /agents/{agentId}/credentials/{credentialId}` — each with method, path, auth requirement, request fields table, response codes table, and complete curl example
|
||||
- [x] 5.7 Document Audit Log endpoints (2): `GET /audit`, `GET /audit/{eventId}` — each with method, path, auth requirement, query parameter table (including all filter options), response codes table, and complete curl example
|
||||
|
||||
## 6. QA & Review
|
||||
|
||||
- [x] 6.1 Verify all curl examples are syntactically correct and complete (no ellipses, no missing flags)
|
||||
- [x] 6.2 Verify all 14 endpoints from the OpenAPI specs are covered in api-reference.md
|
||||
- [x] 6.3 Verify all internal links (cross-references between docs) resolve correctly
|
||||
- [x] 6.4 Verify free-tier limits in concepts.md match README.md Section 3.3
|
||||
- [x] 6.5 Verify quick-start guide is self-contained — a developer can complete it using only that file
|
||||
2
openspec/changes/devops-documentation/.openspec.yaml
Normal file
2
openspec/changes/devops-documentation/.openspec.yaml
Normal file
@@ -0,0 +1,2 @@
|
||||
schema: spec-driven
|
||||
created: 2026-03-28
|
||||
48
openspec/changes/devops-documentation/design.md
Normal file
48
openspec/changes/devops-documentation/design.md
Normal file
@@ -0,0 +1,48 @@
|
||||
## Context
|
||||
|
||||
Phase 1 MVP is complete and live on `develop`. The bedroom developer docs cover the API surface. DevOps engineers — responsible for deployment, configuration, and operations — have no documentation. This gap creates operational risk: misconfigured environment variables, missed migration steps, and no recovery path when services fail.
|
||||
|
||||
**Audience**: Engineers who deploy and operate the AgentIdP infrastructure. Assumed knowledge: Linux shell, Docker, PostgreSQL basics, Node.js process management.
|
||||
|
||||
**Constraints:**
|
||||
- Markdown only — renders on GitHub, no build step
|
||||
- All commands are exact and runnable — no placeholders
|
||||
- Honest about Phase 1 P1 gaps: Dockerfile does not exist yet; document what works now and mark pending items clearly
|
||||
- Files live in `docs/devops/` — separate from `docs/developers/`
|
||||
|
||||
## Goals / Non-Goals
|
||||
|
||||
**Goals:**
|
||||
- DevOps engineer can stand up a working local environment from scratch using only these docs
|
||||
- Every environment variable is documented with type, requirement, and example
|
||||
- Database schema and migration procedure are fully documented
|
||||
- Security setup (JWT keys, CORS, secrets) is step-by-step
|
||||
- Operations runbook covers the most likely failure scenarios
|
||||
|
||||
**Non-Goals:**
|
||||
- Container deployment guide (Dockerfile is Phase 1 P1 — not built yet)
|
||||
- Cloud/Kubernetes deployment (Phase 2)
|
||||
- Monitoring/alerting setup (Phase 2)
|
||||
- Multi-region or HA configuration (Phase 2)
|
||||
|
||||
## Decisions
|
||||
|
||||
**Decision 1: Separate folder vs subdirectory of docs/developers/**
|
||||
Chosen: `docs/devops/` as a peer of `docs/developers/`.
|
||||
Reason: Different audiences, no shared content, prevents confusion.
|
||||
|
||||
**Decision 2: Mark Dockerfile gap explicitly**
|
||||
Chosen: `local-development.md` documents working `docker-compose` + `npm` path; `Dockerfile` noted as Phase 1 P1 pending with a placeholder section.
|
||||
Reason: Honest documentation prevents broken deployments.
|
||||
|
||||
**Decision 3: Operations and security as separate files**
|
||||
Chosen: `security.md` and `operations.md` are separate.
|
||||
Reason: DevOps engineers frequently consult these independently — security during setup, operations during incidents.
|
||||
|
||||
## Migration Plan
|
||||
|
||||
Documentation only. No code changes. No rollback needed.
|
||||
|
||||
## Open Questions
|
||||
|
||||
*(none — scope fully defined)*
|
||||
19
openspec/changes/devops-documentation/proposal.md
Normal file
19
openspec/changes/devops-documentation/proposal.md
Normal file
@@ -0,0 +1,19 @@
|
||||
## Why
|
||||
|
||||
SentryAgent.ai AgentIdP Phase 1 MVP is complete and `docs/developers/` covers API consumers. However, there is no documentation for the engineers who deploy, configure, and operate the infrastructure. A DevOps engineer joining the project today has no reference for environment variables, database schema, deployment procedure, security configuration, or operational runbook. We fix that now.
|
||||
|
||||
## What Changes
|
||||
|
||||
- New `docs/devops/` folder — fully separate from `docs/developers/` — containing a complete operational reference for DevOps engineers
|
||||
- System architecture overview: components, ports, dependencies, data flow
|
||||
- Complete environment variable reference: every variable, required vs optional, format, examples
|
||||
- Database documentation: 4-table schema, migration runner, how to apply/verify migrations
|
||||
- Local development guide: docker-compose infrastructure setup, service ports, health checks
|
||||
- Security guide: RSA keypair generation and rotation, CORS config, secret storage
|
||||
- Operations runbook: startup procedure, graceful shutdown (SIGTERM/SIGINT), logging, common failures and fixes
|
||||
|
||||
## What Does Not Change
|
||||
|
||||
- `docs/developers/` — not touched
|
||||
- Source code — documentation only
|
||||
- No new dependencies
|
||||
@@ -0,0 +1,4 @@
|
||||
## ADDED Requirements
|
||||
|
||||
### Requirement: Database doc exists at docs/devops/database.md
|
||||
The system SHALL provide `docs/devops/database.md` documenting the 4-table schema (agents, credentials, audit_events, token_revocations), the migration runner, and exact commands to apply and verify migrations.
|
||||
@@ -0,0 +1,4 @@
|
||||
## ADDED Requirements
|
||||
|
||||
### Requirement: Local development guide exists at docs/devops/local-development.md
|
||||
The system SHALL provide `docs/devops/local-development.md` documenting the complete local setup using docker-compose for infrastructure and npm for the application server, including all service ports, health check verification, and the Dockerfile gap note.
|
||||
@@ -0,0 +1,7 @@
|
||||
## ADDED Requirements
|
||||
|
||||
### Requirement: Security guide exists at docs/devops/security.md
|
||||
The system SHALL provide `docs/devops/security.md` documenting RSA keypair generation, key rotation procedure, CORS configuration, and secret storage guidance.
|
||||
|
||||
### Requirement: Operations runbook exists at docs/devops/operations.md
|
||||
The system SHALL provide `docs/devops/operations.md` covering startup procedure, graceful shutdown (SIGTERM/SIGINT), log interpretation, and troubleshooting for the most common operational failures.
|
||||
@@ -0,0 +1,10 @@
|
||||
## ADDED Requirements
|
||||
|
||||
### Requirement: System overview exists at docs/devops/README.md
|
||||
The system SHALL provide a `docs/devops/README.md` that serves as the entry point for DevOps engineers, including an index of all DevOps docs and a brief system overview.
|
||||
|
||||
### Requirement: Architecture doc exists at docs/devops/architecture.md
|
||||
The system SHALL provide `docs/devops/architecture.md` documenting all components (Express server, PostgreSQL, Redis), their roles, ports, and data flow.
|
||||
|
||||
### Requirement: Environment variable reference exists at docs/devops/environment-variables.md
|
||||
The system SHALL provide `docs/devops/environment-variables.md` documenting every environment variable with name, type, required/optional, default, and example value.
|
||||
71
openspec/changes/devops-documentation/tasks.md
Normal file
71
openspec/changes/devops-documentation/tasks.md
Normal file
@@ -0,0 +1,71 @@
|
||||
## 1. Folder Structure & Index
|
||||
|
||||
- [x] 1.1 Create `docs/devops/` directory
|
||||
- [x] 1.2 Create `docs/devops/README.md` — index + system overview (what AgentIdP is, what this folder covers, links to all docs)
|
||||
|
||||
## 2. Architecture
|
||||
|
||||
- [x] 2.1 Create `docs/devops/architecture.md` — component diagram (Express, PostgreSQL, Redis) with roles and responsibilities
|
||||
- [x] 2.2 Document all service ports (app: 3000, PostgreSQL: 5432, Redis: 6379)
|
||||
- [x] 2.3 Document data flow: request → auth middleware → rate limit → controller → service → repository → PostgreSQL/Redis
|
||||
- [x] 2.4 Document Redis usage: token revocation keys, rate limit counters, monthly token counts
|
||||
- [x] 2.5 Document graceful shutdown: SIGTERM/SIGINT handling, server.close(), process.exit(0)
|
||||
|
||||
## 3. Environment Variables
|
||||
|
||||
- [x] 3.1 Create `docs/devops/environment-variables.md` — complete reference table
|
||||
- [x] 3.2 Document required vars: DATABASE_URL, REDIS_URL, JWT_PRIVATE_KEY, JWT_PUBLIC_KEY
|
||||
- [x] 3.3 Document optional vars: PORT (default 3000), NODE_ENV, CORS_ORIGIN (default *)
|
||||
- [x] 3.4 Add format notes: DATABASE_URL connection string format, REDIS_URL format, PEM key format
|
||||
- [x] 3.5 Add `.env` file example with all vars populated
|
||||
|
||||
## 4. Database
|
||||
|
||||
- [x] 4.1 Create `docs/devops/database.md` — schema overview section
|
||||
- [x] 4.2 Document `agents` table: all columns, types, constraints, indexes
|
||||
- [x] 4.3 Document `credentials` table: all columns, types, constraints, indexes, FK to agents
|
||||
- [x] 4.4 Document `audit_events` table: all columns, types, constraints, indexes, append-only design
|
||||
- [x] 4.5 Document `token_revocations` table: all columns, types, indexes, dual-store design (Redis + PG)
|
||||
- [x] 4.6 Document migration runner: how it works, commands to run, how to verify applied migrations
|
||||
- [x] 4.7 Document `schema_migrations` tracking table
|
||||
|
||||
## 5. Local Development
|
||||
|
||||
- [x] 5.1 Create `docs/devops/local-development.md` — prerequisites (Docker, Node.js 18+)
|
||||
- [x] 5.2 Document infrastructure-only docker-compose startup (postgres + redis only, not app service)
|
||||
- [x] 5.3 Document service ports and health check verification commands
|
||||
- [x] 5.4 Document migration step: exact `npm run db:migrate` command and expected output
|
||||
- [x] 5.5 Document application startup: `npm run dev` vs `npm start` (compiled), expected log output
|
||||
- [x] 5.6 Note Dockerfile gap: app service in docker-compose.yml requires Dockerfile (Phase 1 P1 pending)
|
||||
- [x] 5.7 Document full docker-compose stack startup (for when Dockerfile is available)
|
||||
- [x] 5.8 Document stopping and cleaning up: `docker-compose down` and volume removal
|
||||
|
||||
## 6. Security
|
||||
|
||||
- [x] 6.1 Create `docs/devops/security.md` — JWT key management section
|
||||
- [x] 6.2 Document RSA-2048 keypair generation using openssl (exact commands)
|
||||
- [x] 6.3 Document PEM format for env vars (newlines as \n in single-line env, or file path approach)
|
||||
- [x] 6.4 Document key rotation procedure: generate new pair, update env, restart server, old tokens expire naturally
|
||||
- [x] 6.5 Document CORS configuration: CORS_ORIGIN env var, wildcard vs specific origin
|
||||
- [x] 6.6 Document secret storage guidance: never commit .env, use secrets manager in production
|
||||
- [x] 6.7 Document bcrypt: credentials are stored as bcrypt hashes, plaintext never persisted
|
||||
|
||||
## 7. Operations
|
||||
|
||||
- [x] 7.1 Create `docs/devops/operations.md` — startup checklist
|
||||
- [x] 7.2 Document startup order: PostgreSQL → Redis → run migrations → start app
|
||||
- [x] 7.3 Document graceful shutdown: send SIGTERM, server drains in-flight requests, exits 0
|
||||
- [x] 7.4 Document log output format: what each startup log line means
|
||||
- [x] 7.5 Document troubleshooting: DATABASE_URL not set, REDIS_URL not set, JWT keys not set
|
||||
- [x] 7.6 Document troubleshooting: PostgreSQL connection refused (service not ready)
|
||||
- [x] 7.7 Document troubleshooting: Redis connection error (service not ready)
|
||||
- [x] 7.8 Document troubleshooting: migration fails (connection issue vs SQL error)
|
||||
- [x] 7.9 Document Redis key patterns used by the application (rate:, revoked:, monthly:)
|
||||
|
||||
## 8. QA & Review
|
||||
|
||||
- [x] 8.1 Verify all commands are exact and runnable (no placeholders in shell commands)
|
||||
- [x] 8.2 Verify all env var names match source code exactly
|
||||
- [x] 8.3 Verify all table/column names match migration SQL exactly
|
||||
- [x] 8.4 Verify all port numbers match docker-compose.yml
|
||||
- [x] 8.5 Verify all internal links resolve
|
||||
20
openspec/config.yaml
Normal file
20
openspec/config.yaml
Normal file
@@ -0,0 +1,20 @@
|
||||
schema: spec-driven
|
||||
|
||||
# Project context (optional)
|
||||
# This is shown to AI when creating artifacts.
|
||||
# Add your tech stack, conventions, style guides, domain knowledge, etc.
|
||||
# Example:
|
||||
# context: |
|
||||
# Tech stack: TypeScript, React, Node.js
|
||||
# We use conventional commits
|
||||
# Domain: e-commerce platform
|
||||
|
||||
# Per-artifact rules (optional)
|
||||
# Add custom rules for specific artifacts.
|
||||
# Example:
|
||||
# rules:
|
||||
# proposal:
|
||||
# - Keep proposals under 500 words
|
||||
# - Always include a "Non-goals" section
|
||||
# tasks:
|
||||
# - Break tasks into chunks of max 2 hours
|
||||
86
openspec/specs/agent-registry/spec.md
Normal file
86
openspec/specs/agent-registry/spec.md
Normal file
@@ -0,0 +1,86 @@
|
||||
## ADDED Requirements
|
||||
|
||||
### Requirement: Register a new AI agent
|
||||
The system SHALL create a new agent identity record with a system-assigned immutable UUID (`agentId`) when a valid `CreateAgentRequest` is received. The `email` field SHALL be unique across all agents. The agent SHALL be created with `status: active`. The system SHALL enforce a free-tier limit of 100 registered agents per account.
|
||||
|
||||
#### Scenario: Successful agent registration
|
||||
- **WHEN** a POST request to `/agents` is received with a valid `CreateAgentRequest` body and a valid Bearer token
|
||||
- **THEN** the system creates the agent, assigns a UUID `agentId`, sets `status` to `active`, sets `createdAt` and `updatedAt` to the current timestamp, and returns `201` with the full `Agent` object
|
||||
|
||||
#### Scenario: Duplicate email rejected
|
||||
- **WHEN** a POST request to `/agents` is received with an `email` that is already registered
|
||||
- **THEN** the system returns `409 Conflict` with `code: AGENT_ALREADY_EXISTS`
|
||||
|
||||
#### Scenario: Free tier limit enforced
|
||||
- **WHEN** a POST request to `/agents` is received and the account already has 100 registered agents
|
||||
- **THEN** the system returns `403 Forbidden` with `code: FREE_TIER_LIMIT_EXCEEDED` and `details.limit: 100`
|
||||
|
||||
#### Scenario: Invalid request body rejected
|
||||
- **WHEN** a POST request to `/agents` is received with a missing required field or invalid field value (e.g. invalid semver, invalid email, invalid capability pattern)
|
||||
- **THEN** the system returns `400 Bad Request` with `code: VALIDATION_ERROR` and `details` identifying the failing field
|
||||
|
||||
### Requirement: Retrieve a single agent by ID
|
||||
The system SHALL return the full `Agent` record for a given `agentId`.
|
||||
|
||||
#### Scenario: Agent found
|
||||
- **WHEN** a GET request to `/agents/{agentId}` is received with a valid Bearer token and a UUID that exists in the registry
|
||||
- **THEN** the system returns `200 OK` with the full `Agent` object
|
||||
|
||||
#### Scenario: Agent not found
|
||||
- **WHEN** a GET request to `/agents/{agentId}` is received with a UUID that does not exist
|
||||
- **THEN** the system returns `404 Not Found` with `code: AGENT_NOT_FOUND`
|
||||
|
||||
### Requirement: List agents with pagination and filtering
|
||||
The system SHALL return a paginated list of agents, orderd by `createdAt` descending, optionally filtered by `owner`, `agentType`, and/or `status`.
|
||||
|
||||
#### Scenario: Successful paginated list
|
||||
- **WHEN** a GET request to `/agents` is received with optional `page`, `limit`, `owner`, `agentType`, `status` query parameters and a valid Bearer token
|
||||
- **THEN** the system returns `200 OK` with a `PaginatedAgentsResponse` containing `data`, `total`, `page`, and `limit`
|
||||
|
||||
#### Scenario: Invalid pagination parameters rejected
|
||||
- **WHEN** a GET request to `/agents` is received with `limit` greater than 100 or `page` less than 1
|
||||
- **THEN** the system returns `400 Bad Request` with `code: VALIDATION_ERROR`
|
||||
|
||||
### Requirement: Update agent metadata
|
||||
The system SHALL partially update a mutable agent record. `agentId`, `email`, and `createdAt` SHALL be immutable. Setting `status` to `decommissioned` SHALL be a one-way irreversible operation.
|
||||
|
||||
#### Scenario: Successful partial update
|
||||
- **WHEN** a PATCH request to `/agents/{agentId}` is received with a valid partial `UpdateAgentRequest` body and a valid Bearer token
|
||||
- **THEN** the system updates only the provided fields, sets `updatedAt` to the current timestamp, and returns `200 OK` with the full updated `Agent` object
|
||||
|
||||
#### Scenario: Attempt to modify immutable field rejected
|
||||
- **WHEN** a PATCH request to `/agents/{agentId}` contains the `email` field
|
||||
- **THEN** the system returns `400 Bad Request` with `code: IMMUTABLE_FIELD` and `details.field: email`
|
||||
|
||||
#### Scenario: Decommissioned agent cannot be updated
|
||||
- **WHEN** a PATCH request to `/agents/{agentId}` targets an agent with `status: decommissioned`
|
||||
- **THEN** the system returns `403 Forbidden` with `code: AGENT_DECOMMISSIONED`
|
||||
|
||||
### Requirement: Decommission (soft-delete) an agent
|
||||
The system SHALL set an agent's `status` to `decommissioned` and revoke all of its active credentials. The agent record SHALL be retained for audit purposes. This operation SHALL be irreversible.
|
||||
|
||||
#### Scenario: Successful decommission
|
||||
- **WHEN** a DELETE request to `/agents/{agentId}` is received with a valid Bearer token and the agent exists and is not already decommissioned
|
||||
- **THEN** the system sets `status` to `decommissioned`, revokes all active credentials for this agent, and returns `204 No Content`
|
||||
|
||||
#### Scenario: Already decommissioned agent rejected
|
||||
- **WHEN** a DELETE request to `/agents/{agentId}` is received for an agent that is already `decommissioned`
|
||||
- **THEN** the system returns `409 Conflict` with `code: AGENT_ALREADY_DECOMMISSIONED`
|
||||
|
||||
### Requirement: Authentication required on all agent endpoints
|
||||
All agent endpoints SHALL require a valid Bearer JWT in the `Authorization` header.
|
||||
|
||||
#### Scenario: Missing token rejected
|
||||
- **WHEN** any request to `/agents` or `/agents/{agentId}` is received without an `Authorization: Bearer` header
|
||||
- **THEN** the system returns `401 Unauthorized` with `code: UNAUTHORIZED`
|
||||
|
||||
#### Scenario: Invalid token rejected
|
||||
- **WHEN** any request to `/agents` or `/agents/{agentId}` is received with an expired, malformed, or revoked Bearer token
|
||||
- **THEN** the system returns `401 Unauthorized` with `code: UNAUTHORIZED`
|
||||
|
||||
### Requirement: Rate limiting on all agent endpoints
|
||||
The system SHALL enforce a rate limit of 100 requests per minute per authenticated client. Rate limit state SHALL be tracked in Redis.
|
||||
|
||||
#### Scenario: Rate limit exceeded
|
||||
- **WHEN** a client sends more than 100 requests to any agent endpoint within a 60-second window
|
||||
- **THEN** the system returns `429 Too Many Requests` with `X-RateLimit-Limit`, `X-RateLimit-Remaining: 0`, and `X-RateLimit-Reset` headers
|
||||
72
openspec/specs/audit-log/spec.md
Normal file
72
openspec/specs/audit-log/spec.md
Normal file
@@ -0,0 +1,72 @@
|
||||
## ADDED Requirements
|
||||
|
||||
### Requirement: Audit events are written internally for all significant actions
|
||||
The system SHALL automatically create an immutable `AuditEvent` record for each of the following actions: `agent.created`, `agent.updated`, `agent.decommissioned`, `agent.suspended`, `agent.reactivated`, `token.issued`, `token.revoked`, `token.introspected`, `credential.generated`, `credential.rotated`, `credential.revoked`, `auth.failed`. No API endpoint SHALL allow external creation, modification, or deletion of audit records.
|
||||
|
||||
#### Scenario: Audit event created on agent registration
|
||||
- **WHEN** a new agent is successfully registered via `POST /agents`
|
||||
- **THEN** an `AuditEvent` with `action: agent.created`, `outcome: success`, and `metadata` containing `agentType` and `owner` is persisted
|
||||
|
||||
#### Scenario: Audit event created on failed authentication
|
||||
- **WHEN** a `POST /token` request fails due to invalid credentials
|
||||
- **THEN** an `AuditEvent` with `action: auth.failed`, `outcome: failure`, and `metadata` containing `reason` and `clientId` is persisted
|
||||
|
||||
#### Scenario: Audit event created on token issuance
|
||||
- **WHEN** a token is successfully issued via `POST /token`
|
||||
- **THEN** an `AuditEvent` with `action: token.issued`, `outcome: success`, and `metadata` containing `scope` and `expiresAt` is persisted
|
||||
|
||||
### Requirement: Query the audit log with pagination and filtering
|
||||
The system SHALL return a paginated list of audit events ordered by `timestamp` descending. The caller SHALL hold a valid Bearer token with `audit:read` scope. Filtering SHALL support `agentId`, `action`, `outcome`, `fromDate`, and `toDate` — all optional, combined with logical AND.
|
||||
|
||||
#### Scenario: Successful audit log query
|
||||
- **WHEN** a GET request to `/audit` is received with a valid Bearer token with `audit:read` scope
|
||||
- **THEN** the system returns `200 OK` with a `PaginatedAuditEventsResponse` containing `data`, `total`, `page`, and `limit`
|
||||
|
||||
#### Scenario: Filter by agentId
|
||||
- **WHEN** a GET request to `/audit?agentId={uuid}` is received
|
||||
- **THEN** only events where `agentId` equals the provided UUID are returned
|
||||
|
||||
#### Scenario: Filter by action
|
||||
- **WHEN** a GET request to `/audit?action=token.issued` is received
|
||||
- **THEN** only events with `action: token.issued` are returned
|
||||
|
||||
#### Scenario: Filter by date range
|
||||
- **WHEN** a GET request to `/audit?fromDate=2026-03-01T00:00:00.000Z&toDate=2026-03-28T23:59:59.999Z` is received
|
||||
- **THEN** only events with `timestamp` within the specified range are returned
|
||||
|
||||
#### Scenario: fromDate after toDate rejected
|
||||
- **WHEN** a GET request to `/audit` is received with `fromDate` that is chronologically after `toDate`
|
||||
- **THEN** the system returns `400 Bad Request` with `code: VALIDATION_ERROR` and `details.reason` explaining the invalid date range
|
||||
|
||||
#### Scenario: Insufficient scope rejected
|
||||
- **WHEN** a GET request to `/audit` is received with a valid Bearer token that does not have `audit:read` scope
|
||||
- **THEN** the system returns `403 Forbidden` with `code: INSUFFICIENT_SCOPE`
|
||||
|
||||
### Requirement: Retrieve a single audit event by ID
|
||||
The system SHALL return a single immutable `AuditEvent` by its `eventId`. The caller SHALL hold a valid Bearer token with `audit:read` scope.
|
||||
|
||||
#### Scenario: Audit event found
|
||||
- **WHEN** a GET request to `/audit/{eventId}` is received with a valid Bearer token with `audit:read` scope and a UUID that exists in the audit log
|
||||
- **THEN** the system returns `200 OK` with the full `AuditEvent` object
|
||||
|
||||
#### Scenario: Audit event not found
|
||||
- **WHEN** a GET request to `/audit/{eventId}` is received with a UUID that does not exist in the audit log
|
||||
- **THEN** the system returns `404 Not Found` with `code: AUDIT_EVENT_NOT_FOUND`
|
||||
|
||||
### Requirement: Free-tier 90-day audit log retention
|
||||
On the free tier, the system SHALL only return audit events from the last 90 days. Events older than 90 days SHALL be treated as not accessible (return empty results for queries, `404` for direct lookups). The system SHALL return a `400` error with `code: RETENTION_WINDOW_EXCEEDED` if a `fromDate` query parameter falls outside the 90-day retention window.
|
||||
|
||||
#### Scenario: Query outside retention window rejected
|
||||
- **WHEN** a GET request to `/audit` is received with `fromDate` more than 90 days before today
|
||||
- **THEN** the system returns `400 Bad Request` with `code: RETENTION_WINDOW_EXCEEDED` and `details.retentionDays: 90`
|
||||
|
||||
#### Scenario: Direct lookup of expired event returns 404
|
||||
- **WHEN** a GET request to `/audit/{eventId}` is received for an event with a `timestamp` older than 90 days
|
||||
- **THEN** the system returns `404 Not Found` with `code: AUDIT_EVENT_NOT_FOUND`
|
||||
|
||||
### Requirement: Rate limiting on audit endpoints
|
||||
The system SHALL enforce a rate limit of 100 requests per minute per authenticated client on all audit endpoints.
|
||||
|
||||
#### Scenario: Rate limit exceeded on audit endpoint
|
||||
- **WHEN** a client sends more than 100 requests to any audit endpoint within a 60-second window
|
||||
- **THEN** the system returns `429 Too Many Requests` with `X-RateLimit-Limit`, `X-RateLimit-Remaining: 0`, and `X-RateLimit-Reset` headers
|
||||
83
openspec/specs/credential-management/spec.md
Normal file
83
openspec/specs/credential-management/spec.md
Normal file
@@ -0,0 +1,83 @@
|
||||
## ADDED Requirements
|
||||
|
||||
### Requirement: Generate new credentials for an agent
|
||||
The system SHALL generate a new `client_id`/`client_secret` pair for a specified agent. The `client_id` SHALL equal the agent's `agentId`. The `client_secret` SHALL be a cryptographically random string with the prefix `sk_live_` followed by 64 hex characters (256 bits of entropy). The plain-text secret SHALL be returned in the response exactly once and SHALL never be stored in plain text — only a bcrypt hash (10 rounds) SHALL be persisted. The agent MUST be in `active` status to generate credentials.
|
||||
|
||||
#### Scenario: Successful credential generation
|
||||
- **WHEN** a POST request to `/agents/{agentId}/credentials` is received with a valid Bearer token and the agent exists with `status: active`
|
||||
- **THEN** the system generates a new credential, persists the bcrypt hash of the secret, and returns `201 Created` with a `CredentialWithSecret` response including the plain-text `clientSecret`
|
||||
|
||||
#### Scenario: clientSecret not returned after creation
|
||||
- **WHEN** a GET request to `/agents/{agentId}/credentials` is made after credential creation
|
||||
- **THEN** the `clientSecret` field is NOT present in any `Credential` object in the response
|
||||
|
||||
#### Scenario: Suspended agent cannot generate credentials
|
||||
- **WHEN** a POST request to `/agents/{agentId}/credentials` is received for an agent with `status: suspended`
|
||||
- **THEN** the system returns `403 Forbidden` with `code: AGENT_NOT_ACTIVE`
|
||||
|
||||
#### Scenario: Decommissioned agent cannot generate credentials
|
||||
- **WHEN** a POST request to `/agents/{agentId}/credentials` is received for an agent with `status: decommissioned`
|
||||
- **THEN** the system returns `403 Forbidden` with `code: AGENT_NOT_ACTIVE`
|
||||
|
||||
#### Scenario: Optional expiry respected
|
||||
- **WHEN** a POST request to `/agents/{agentId}/credentials` is received with an `expiresAt` value that is a future date-time
|
||||
- **THEN** the credential is created with the specified `expiresAt` value
|
||||
|
||||
#### Scenario: Past expiry rejected
|
||||
- **WHEN** a POST request to `/agents/{agentId}/credentials` is received with an `expiresAt` value that is in the past
|
||||
- **THEN** the system returns `400 Bad Request` with `code: VALIDATION_ERROR` and `details.field: expiresAt`
|
||||
|
||||
#### Scenario: Agent not found
|
||||
- **WHEN** a POST request to `/agents/{agentId}/credentials` is received for a `agentId` that does not exist
|
||||
- **THEN** the system returns `404 Not Found` with `code: AGENT_NOT_FOUND`
|
||||
|
||||
### Requirement: List credentials for an agent
|
||||
The system SHALL return a paginated list of all credentials (both `active` and `revoked`) for an agent, ordered by `createdAt` descending. The `clientSecret` SHALL never be included in list responses.
|
||||
|
||||
#### Scenario: Successful credential list
|
||||
- **WHEN** a GET request to `/agents/{agentId}/credentials` is received with optional `page`, `limit`, `status` query parameters and a valid Bearer token
|
||||
- **THEN** the system returns `200 OK` with a `PaginatedCredentialsResponse` containing `data`, `total`, `page`, and `limit`, with no `clientSecret` fields
|
||||
|
||||
#### Scenario: Filter by status
|
||||
- **WHEN** a GET request to `/agents/{agentId}/credentials?status=active` is received
|
||||
- **THEN** only credentials with `status: active` are returned
|
||||
|
||||
### Requirement: Rotate a credential
|
||||
The system SHALL rotate an existing active credential by generating a new `clientSecret` for the same `credentialId`. The previous secret SHALL be immediately invalidated. The new plain-text secret SHALL be returned once and never persisted. Only `active` credentials can be rotated.
|
||||
|
||||
#### Scenario: Successful rotation
|
||||
- **WHEN** a POST request to `/agents/{agentId}/credentials/{credentialId}/rotate` is received with a valid Bearer token and the credential exists with `status: active`
|
||||
- **THEN** the system generates a new secret, replaces the stored bcrypt hash, and returns `200 OK` with a `CredentialWithSecret` response including the new plain-text `clientSecret`. The `credentialId` remains unchanged.
|
||||
|
||||
#### Scenario: Revoked credential cannot be rotated
|
||||
- **WHEN** a POST request to `/agents/{agentId}/credentials/{credentialId}/rotate` is received for a credential with `status: revoked`
|
||||
- **THEN** the system returns `409 Conflict` with `code: CREDENTIAL_ALREADY_REVOKED`
|
||||
|
||||
#### Scenario: Credential not found
|
||||
- **WHEN** a POST request to `/agents/{agentId}/credentials/{credentialId}/rotate` is received with a `credentialId` that does not exist for the given agent
|
||||
- **THEN** the system returns `404 Not Found` with `code: CREDENTIAL_NOT_FOUND`
|
||||
|
||||
### Requirement: Revoke a credential
|
||||
The system SHALL permanently revoke a credential by setting its `status` to `revoked` and recording a `revokedAt` timestamp. The credential record SHALL be retained for audit purposes. Revocation SHALL be irreversible. Tokens previously issued with this credential SHALL remain valid until their natural expiry (token revocation is handled separately via `POST /token/revoke`). Revoking an already-revoked credential SHALL return `409 Conflict`.
|
||||
|
||||
#### Scenario: Successful revocation
|
||||
- **WHEN** a DELETE request to `/agents/{agentId}/credentials/{credentialId}` is received with a valid Bearer token and the credential exists with `status: active`
|
||||
- **THEN** the system sets `status` to `revoked`, sets `revokedAt` to the current timestamp, and returns `204 No Content`
|
||||
|
||||
#### Scenario: Already-revoked credential rejected
|
||||
- **WHEN** a DELETE request to `/agents/{agentId}/credentials/{credentialId}` is received for a credential that is already `revoked`
|
||||
- **THEN** the system returns `409 Conflict` with `code: CREDENTIAL_ALREADY_REVOKED`
|
||||
|
||||
### Requirement: Agent decommission cascades to credential revocation
|
||||
When an agent is decommissioned via `DELETE /agents/{agentId}`, the system SHALL revoke all active credentials for that agent as part of the same operation.
|
||||
|
||||
#### Scenario: All credentials revoked on agent decommission
|
||||
- **WHEN** an agent is successfully decommissioned via `DELETE /agents/{agentId}`
|
||||
- **THEN** all credentials for that agent with `status: active` are set to `status: revoked` with `revokedAt` = current timestamp
|
||||
|
||||
### Requirement: Authentication required on all credential endpoints
|
||||
All credential endpoints SHALL require a valid Bearer JWT. An agent MAY manage its own credentials using a self-issued token. Managing another agent's credentials SHALL return `403 Forbidden` unless the caller holds an admin-scoped token (admin scope is not implemented in Phase 1 — return `403` for all cross-agent requests).
|
||||
|
||||
#### Scenario: Unauthenticated request rejected
|
||||
- **WHEN** any request to `/agents/{agentId}/credentials` is received without a valid Bearer token
|
||||
- **THEN** the system returns `401 Unauthorized` with `code: UNAUTHORIZED`
|
||||
76
openspec/specs/oauth2-token/spec.md
Normal file
76
openspec/specs/oauth2-token/spec.md
Normal file
@@ -0,0 +1,76 @@
|
||||
## ADDED Requirements
|
||||
|
||||
### Requirement: Issue access token via Client Credentials grant
|
||||
The system SHALL issue a signed RS256 JWT access token when an agent authenticates with a valid `client_id` (agentId) and `client_secret` using the OAuth 2.0 Client Credentials grant (RFC 6749 §4.4). The request body SHALL use `application/x-www-form-urlencoded` encoding. The response SHALL include `Cache-Control: no-store` and `Pragma: no-cache` headers. The system SHALL enforce a free-tier limit of 10,000 token requests per calendar month per client.
|
||||
|
||||
#### Scenario: Successful token issuance
|
||||
- **WHEN** a POST request to `/token` is received with `grant_type=client_credentials`, a valid `client_id`, and a valid `client_secret` for an `active` agent
|
||||
- **THEN** the system verifies the credential, issues a signed JWT with `sub` = `agentId`, `scope` = requested (or default) scope, `exp` = now + 3600s, and returns `200 OK` with `TokenResponse`
|
||||
|
||||
#### Scenario: Invalid client credentials rejected
|
||||
- **WHEN** a POST request to `/token` is received with a `client_id` that does not exist or a `client_secret` that does not match
|
||||
- **THEN** the system returns `401 Unauthorized` with `error: invalid_client`
|
||||
|
||||
#### Scenario: Suspended agent cannot obtain tokens
|
||||
- **WHEN** a POST request to `/token` is received for an agent with `status: suspended`
|
||||
- **THEN** the system returns `403 Forbidden` with `error: unauthorized_client` and a description indicating the agent is suspended
|
||||
|
||||
#### Scenario: Decommissioned agent cannot obtain tokens
|
||||
- **WHEN** a POST request to `/token` is received for an agent with `status: decommissioned`
|
||||
- **THEN** the system returns `403 Forbidden` with `error: unauthorized_client`
|
||||
|
||||
#### Scenario: Unsupported grant type rejected
|
||||
- **WHEN** a POST request to `/token` is received with a `grant_type` other than `client_credentials`
|
||||
- **THEN** the system returns `400 Bad Request` with `error: unsupported_grant_type`
|
||||
|
||||
#### Scenario: Invalid scope rejected
|
||||
- **WHEN** a POST request to `/token` is received with a `scope` value that contains an unrecognised scope identifier
|
||||
- **THEN** the system returns `400 Bad Request` with `error: invalid_scope`
|
||||
|
||||
#### Scenario: Free tier monthly token limit enforced
|
||||
- **WHEN** a POST request to `/token` is received and the agent has already made 10,000 token requests in the current calendar month
|
||||
- **THEN** the system returns `403 Forbidden` with `error: unauthorized_client` and a description indicating the monthly free-tier limit is reached
|
||||
|
||||
### Requirement: Token introspection (RFC 7662)
|
||||
The system SHALL determine whether a given access token is currently active (valid, not expired, not revoked). The endpoint SHALL return `200 OK` for both active and inactive tokens — the `active` field in the response SHALL indicate validity. The caller SHALL hold a valid Bearer token with `tokens:read` scope.
|
||||
|
||||
#### Scenario: Active token introspection
|
||||
- **WHEN** a POST request to `/token/introspect` is received with a valid, non-expired, non-revoked token and the caller has `tokens:read` scope
|
||||
- **THEN** the system returns `200 OK` with `active: true` and the token's claims (`sub`, `client_id`, `scope`, `token_type`, `iat`, `exp`)
|
||||
|
||||
#### Scenario: Expired or revoked token introspection
|
||||
- **WHEN** a POST request to `/token/introspect` is received with a token that is expired or has been revoked
|
||||
- **THEN** the system returns `200 OK` with `active: false` and no other claims
|
||||
|
||||
#### Scenario: Insufficient scope for introspection
|
||||
- **WHEN** a POST request to `/token/introspect` is received with a valid Bearer token that does not have `tokens:read` scope
|
||||
- **THEN** the system returns `403 Forbidden` with `code: INSUFFICIENT_SCOPE`
|
||||
|
||||
### Requirement: Token revocation (RFC 7009)
|
||||
The system SHALL invalidate a given access token immediately. Revoking an already-revoked or expired token SHALL be a successful, idempotent operation (RFC 7009 §2.1). Revoked token JTIs SHALL be stored in Redis with TTL equal to the token's remaining lifetime.
|
||||
|
||||
#### Scenario: Successful token revocation
|
||||
- **WHEN** a POST request to `/token/revoke` is received with a valid Bearer token and a `token` parameter containing a valid JWT
|
||||
- **THEN** the system adds the token's JTI to the Redis revocation list, and returns `200 OK` with an empty body
|
||||
|
||||
#### Scenario: Revocation of already-revoked token is idempotent
|
||||
- **WHEN** a POST request to `/token/revoke` is received with a token that is already in the Redis revocation list
|
||||
- **THEN** the system returns `200 OK` with an empty body (no error)
|
||||
|
||||
#### Scenario: Missing token parameter rejected
|
||||
- **WHEN** a POST request to `/token/revoke` is received with no `token` field in the body
|
||||
- **THEN** the system returns `400 Bad Request` with `code: VALIDATION_ERROR`
|
||||
|
||||
### Requirement: JWT claims structure
|
||||
All issued JWTs SHALL contain the following claims: `sub` (agentId), `client_id` (agentId), `scope` (space-separated granted scopes), `jti` (UUID, unique per token), `iat` (issued-at Unix timestamp), `exp` (expiry Unix timestamp). Tokens SHALL be signed with RS256.
|
||||
|
||||
#### Scenario: JWT contains required claims
|
||||
- **WHEN** a token is issued via `POST /token`
|
||||
- **THEN** the decoded JWT payload contains `sub`, `client_id`, `scope`, `jti`, `iat`, and `exp` fields
|
||||
|
||||
### Requirement: Rate limiting on token endpoints
|
||||
The system SHALL enforce a rate limit of 100 requests per minute per `client_id` on all token endpoints.
|
||||
|
||||
#### Scenario: Rate limit exceeded on token endpoint
|
||||
- **WHEN** a client sends more than 100 requests to any token endpoint within a 60-second window
|
||||
- **THEN** the system returns `429 Too Many Requests` with `X-RateLimit-Limit`, `X-RateLimit-Remaining: 0`, and `X-RateLimit-Reset` headers
|
||||
7369
package-lock.json
generated
Normal file
7369
package-lock.json
generated
Normal file
File diff suppressed because it is too large
Load Diff
56
package.json
Normal file
56
package.json
Normal file
@@ -0,0 +1,56 @@
|
||||
{
|
||||
"name": "sentryagent-idp",
|
||||
"version": "1.0.0",
|
||||
"description": "SentryAgent.ai Agent Identity Provider (AgentIdP)",
|
||||
"main": "dist/server.js",
|
||||
"scripts": {
|
||||
"build": "tsc",
|
||||
"start": "node dist/server.js",
|
||||
"dev": "ts-node src/server.ts",
|
||||
"test": "jest",
|
||||
"test:unit": "jest tests/unit",
|
||||
"test:integration": "jest tests/integration",
|
||||
"db:migrate": "ts-node scripts/migrate.ts",
|
||||
"lint": "eslint src --ext .ts",
|
||||
"format": "prettier --write src/**/*.ts"
|
||||
},
|
||||
"dependencies": {
|
||||
"bcryptjs": "^2.4.3",
|
||||
"cors": "^2.8.5",
|
||||
"dotenv": "^16.4.5",
|
||||
"express": "^4.18.3",
|
||||
"helmet": "^7.1.0",
|
||||
"joi": "^17.12.3",
|
||||
"jsonwebtoken": "^9.0.2",
|
||||
"morgan": "^1.10.0",
|
||||
"pg": "^8.11.3",
|
||||
"pino": "^8.19.0",
|
||||
"pino-http": "^9.0.0",
|
||||
"redis": "^4.6.13",
|
||||
"uuid": "^9.0.1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/bcryptjs": "^2.4.6",
|
||||
"@types/cors": "^2.8.17",
|
||||
"@types/express": "^4.17.21",
|
||||
"@types/jest": "^29.5.12",
|
||||
"@types/jsonwebtoken": "^9.0.6",
|
||||
"@types/morgan": "^1.9.9",
|
||||
"@types/node": "^20.12.7",
|
||||
"@types/pg": "^8.11.5",
|
||||
"@types/supertest": "^6.0.2",
|
||||
"@types/uuid": "^9.0.8",
|
||||
"@typescript-eslint/eslint-plugin": "^7.8.0",
|
||||
"@typescript-eslint/parser": "^7.8.0",
|
||||
"eslint": "^8.57.0",
|
||||
"jest": "^29.7.0",
|
||||
"prettier": "^3.2.5",
|
||||
"supertest": "^6.3.4",
|
||||
"ts-jest": "^29.1.2",
|
||||
"ts-node": "^10.9.2",
|
||||
"typescript": "^5.4.5"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=18.0.0"
|
||||
}
|
||||
}
|
||||
120
scripts/migrate.ts
Normal file
120
scripts/migrate.ts
Normal file
@@ -0,0 +1,120 @@
|
||||
/**
|
||||
* Database migration runner for SentryAgent.ai AgentIdP.
|
||||
* Reads all .sql files from src/db/migrations/ in alphabetical order,
|
||||
* tracks applied migrations in a schema_migrations table, and executes
|
||||
* only unapplied migrations.
|
||||
*/
|
||||
|
||||
import * as fs from 'fs';
|
||||
import * as path from 'path';
|
||||
import { Pool } from 'pg';
|
||||
import * as dotenv from 'dotenv';
|
||||
|
||||
dotenv.config();
|
||||
|
||||
const MIGRATIONS_DIR = path.join(__dirname, '../src/db/migrations');
|
||||
|
||||
interface MigrationRow {
|
||||
name: string;
|
||||
applied_at: Date;
|
||||
}
|
||||
|
||||
/**
|
||||
* Ensures the schema_migrations tracking table exists.
|
||||
*
|
||||
* @param pool - The PostgreSQL connection pool.
|
||||
*/
|
||||
async function ensureMigrationsTable(pool: Pool): Promise<void> {
|
||||
await pool.query(`
|
||||
CREATE TABLE IF NOT EXISTS schema_migrations (
|
||||
name VARCHAR(255) PRIMARY KEY,
|
||||
applied_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||
)
|
||||
`);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the list of already-applied migration names.
|
||||
*
|
||||
* @param pool - The PostgreSQL connection pool.
|
||||
* @returns Array of applied migration names.
|
||||
*/
|
||||
async function getAppliedMigrations(pool: Pool): Promise<string[]> {
|
||||
const result = await pool.query<MigrationRow>('SELECT name FROM schema_migrations ORDER BY name');
|
||||
return result.rows.map((row) => row.name);
|
||||
}
|
||||
|
||||
/**
|
||||
* Applies a single migration file within a transaction.
|
||||
*
|
||||
* @param pool - The PostgreSQL connection pool.
|
||||
* @param name - The migration file name (without path).
|
||||
* @param sql - The SQL to execute.
|
||||
*/
|
||||
async function applyMigration(pool: Pool, name: string, sql: string): Promise<void> {
|
||||
const client = await pool.connect();
|
||||
try {
|
||||
await client.query('BEGIN');
|
||||
await client.query(sql);
|
||||
await client.query('INSERT INTO schema_migrations (name) VALUES ($1)', [name]);
|
||||
await client.query('COMMIT');
|
||||
// eslint-disable-next-line no-console
|
||||
console.log(` ✓ Applied: ${name}`);
|
||||
} catch (err) {
|
||||
await client.query('ROLLBACK');
|
||||
throw err;
|
||||
} finally {
|
||||
client.release();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Main migration runner.
|
||||
* Reads all .sql files in alphabetical order and applies unapplied ones.
|
||||
*/
|
||||
async function migrate(): Promise<void> {
|
||||
const connectionString = process.env['DATABASE_URL'];
|
||||
if (!connectionString) {
|
||||
throw new Error('DATABASE_URL environment variable is required');
|
||||
}
|
||||
|
||||
const pool = new Pool({ connectionString });
|
||||
|
||||
try {
|
||||
// eslint-disable-next-line no-console
|
||||
console.log('Running database migrations...');
|
||||
|
||||
await ensureMigrationsTable(pool);
|
||||
const applied = await getAppliedMigrations(pool);
|
||||
|
||||
const files = fs
|
||||
.readdirSync(MIGRATIONS_DIR)
|
||||
.filter((f) => f.endsWith('.sql'))
|
||||
.sort();
|
||||
|
||||
let count = 0;
|
||||
for (const file of files) {
|
||||
if (applied.includes(file)) {
|
||||
// eslint-disable-next-line no-console
|
||||
console.log(` - Skipped (already applied): ${file}`);
|
||||
continue;
|
||||
}
|
||||
|
||||
const filePath = path.join(MIGRATIONS_DIR, file);
|
||||
const sql = fs.readFileSync(filePath, 'utf-8');
|
||||
await applyMigration(pool, file, sql);
|
||||
count++;
|
||||
}
|
||||
|
||||
// eslint-disable-next-line no-console
|
||||
console.log(`\nMigrations complete. ${count} migration(s) applied.`);
|
||||
} finally {
|
||||
await pool.end();
|
||||
}
|
||||
}
|
||||
|
||||
migrate().catch((err: unknown) => {
|
||||
// eslint-disable-next-line no-console
|
||||
console.error('Migration failed:', err);
|
||||
process.exit(1);
|
||||
});
|
||||
46
scripts/start-cto.sh
Executable file
46
scripts/start-cto.sh
Executable file
@@ -0,0 +1,46 @@
|
||||
#!/bin/bash
|
||||
# =============================================================================
|
||||
# SentryAgent.ai — Start Virtual CTO Agent
|
||||
# =============================================================================
|
||||
# Launches a separate Claude Code instance as the Virtual CTO.
|
||||
# The CTO will register on the central hub and await CEO instructions.
|
||||
#
|
||||
# Usage:
|
||||
# ./scripts/start-cto.sh
|
||||
#
|
||||
# The CTO agent runs in its own terminal session and communicates
|
||||
# with the CEO via the central hub (#vpe-cto-approvals channel).
|
||||
# =============================================================================
|
||||
|
||||
set -e
|
||||
|
||||
PROJECT_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
|
||||
CTO_WORKSPACE="$PROJECT_ROOT/.cto-workspace"
|
||||
|
||||
echo "=============================================="
|
||||
echo " SentryAgent.ai — Starting Virtual CTO Agent"
|
||||
echo "=============================================="
|
||||
echo ""
|
||||
echo " Project: $PROJECT_ROOT"
|
||||
echo " Workspace: $CTO_WORKSPACE"
|
||||
echo " Hub Channel: #vpe-cto-approvals"
|
||||
echo ""
|
||||
echo " The Virtual CTO will:"
|
||||
echo " 1. Read README.md"
|
||||
echo " 2. Register on central hub as VirtualCTO"
|
||||
echo " 3. Report status to CEO"
|
||||
echo " 4. Await CEO priorities"
|
||||
echo ""
|
||||
echo "=============================================="
|
||||
echo ""
|
||||
|
||||
# Verify the CTO workspace exists
|
||||
if [ ! -f "$CTO_WORKSPACE/CLAUDE.md" ]; then
|
||||
echo "ERROR: CTO workspace not found at $CTO_WORKSPACE/CLAUDE.md"
|
||||
echo "Please ensure the project is set up correctly."
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# Launch Claude Code in the CTO workspace
|
||||
cd "$CTO_WORKSPACE"
|
||||
exec claude
|
||||
196
sdk/README.md
Normal file
196
sdk/README.md
Normal file
@@ -0,0 +1,196 @@
|
||||
# @sentryagent/idp-sdk
|
||||
|
||||
Node.js SDK for the [SentryAgent.ai AgentIdP](https://sentryagent.ai) — the open-source Identity Provider for AI agents.
|
||||
|
||||
Handles token acquisition and caching automatically. Covers all 14 AgentIdP API endpoints.
|
||||
|
||||
---
|
||||
|
||||
## Requirements
|
||||
|
||||
- Node.js 18 or later (uses native `fetch`)
|
||||
- A running AgentIdP server
|
||||
- A registered agent with a valid `clientId` and `clientSecret`
|
||||
|
||||
---
|
||||
|
||||
## Installation
|
||||
|
||||
```bash
|
||||
npm install @sentryagent/idp-sdk
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Quick start
|
||||
|
||||
```typescript
|
||||
import { AgentIdPClient } from '@sentryagent/idp-sdk';
|
||||
|
||||
const client = new AgentIdPClient({
|
||||
baseUrl: 'http://localhost:3000',
|
||||
clientId: 'your-agent-id', // the agent's agentId (UUID)
|
||||
clientSecret: 'your-client-secret',
|
||||
});
|
||||
|
||||
// List agents — token is acquired and cached automatically
|
||||
const { data: agents } = await client.agents.listAgents();
|
||||
console.log(agents);
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Configuration
|
||||
|
||||
```typescript
|
||||
const client = new AgentIdPClient({
|
||||
baseUrl: 'http://localhost:3000',
|
||||
clientId: 'a1b2c3d4-e5f6-7890-abcd-ef1234567890',
|
||||
clientSecret: 'your-client-secret',
|
||||
// Optional: restrict scopes. Defaults to all four scopes.
|
||||
scopes: ['agents:read', 'tokens:read'],
|
||||
});
|
||||
```
|
||||
|
||||
| Option | Required | Description |
|
||||
|--------|----------|-------------|
|
||||
| `baseUrl` | Yes | Base URL of the AgentIdP server |
|
||||
| `clientId` | Yes | The agent's `agentId` (UUID) |
|
||||
| `clientSecret` | Yes | The credential secret |
|
||||
| `scopes` | No | OAuth 2.0 scopes to request. Defaults to all four. |
|
||||
|
||||
---
|
||||
|
||||
## Token management
|
||||
|
||||
The SDK fetches and caches access tokens automatically. A new token is requested when the cached token is within 60 seconds of expiry.
|
||||
|
||||
```typescript
|
||||
// Force a fresh token on the next request (e.g. after rotating credentials)
|
||||
client.clearTokenCache();
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Agent Registry
|
||||
|
||||
```typescript
|
||||
// Register a new agent
|
||||
const agent = await client.agents.registerAgent({
|
||||
email: 'classifier-v2@myorg.ai',
|
||||
agentType: 'classifier',
|
||||
version: '2.0.0',
|
||||
capabilities: ['text-classification', 'sentiment-analysis'],
|
||||
owner: 'platform-team',
|
||||
deploymentEnv: 'production',
|
||||
});
|
||||
console.log(agent.agentId); // UUID assigned by AgentIdP
|
||||
|
||||
// List agents
|
||||
const { data, total } = await client.agents.listAgents({ status: 'active', limit: 20 });
|
||||
|
||||
// Get a single agent
|
||||
const agent = await client.agents.getAgent('a1b2c3d4-...');
|
||||
|
||||
// Update an agent
|
||||
const updated = await client.agents.updateAgent('a1b2c3d4-...', {
|
||||
version: '2.1.0',
|
||||
capabilities: ['text-classification', 'sentiment-analysis', 'intent-detection'],
|
||||
});
|
||||
|
||||
// Decommission (irreversible)
|
||||
await client.agents.decommissionAgent('a1b2c3d4-...');
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Credentials
|
||||
|
||||
```typescript
|
||||
// Generate a credential — clientSecret shown once, store it securely
|
||||
const cred = await client.credentials.generateCredential('a1b2c3d4-...');
|
||||
console.log(cred.clientSecret); // only available here
|
||||
|
||||
// List credentials
|
||||
const { data: creds } = await client.credentials.listCredentials('a1b2c3d4-...');
|
||||
|
||||
// Rotate — same credentialId, new secret, old secret immediately invalid
|
||||
const rotated = await client.credentials.rotateCredential('a1b2c3d4-...', 'cred-uuid');
|
||||
console.log(rotated.clientSecret); // new secret — store immediately
|
||||
|
||||
// Revoke
|
||||
await client.credentials.revokeCredential('a1b2c3d4-...', 'cred-uuid');
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Token operations
|
||||
|
||||
```typescript
|
||||
// Introspect — check whether a token is active
|
||||
const result = await client.tokens.introspectToken(someToken);
|
||||
if (result.active) {
|
||||
console.log('Token is valid, expires at', result.exp);
|
||||
} else {
|
||||
console.log('Token is expired or revoked');
|
||||
}
|
||||
|
||||
// Revoke — immediately invalidates the token
|
||||
await client.tokens.revokeToken(someToken);
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Audit log
|
||||
|
||||
```typescript
|
||||
// Query audit events
|
||||
const { data: events } = await client.audit.queryAuditLog({
|
||||
agentId: 'a1b2c3d4-...',
|
||||
action: 'token.issued',
|
||||
outcome: 'success',
|
||||
fromDate: '2026-03-01T00:00:00Z',
|
||||
toDate: '2026-03-31T23:59:59Z',
|
||||
limit: 50,
|
||||
});
|
||||
|
||||
// Get a single event
|
||||
const event = await client.audit.getAuditEvent('event-uuid');
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Error handling
|
||||
|
||||
All API errors are thrown as `AgentIdPError`:
|
||||
|
||||
```typescript
|
||||
import { AgentIdPClient, AgentIdPError } from '@sentryagent/idp-sdk';
|
||||
|
||||
try {
|
||||
await client.agents.getAgent('non-existent-id');
|
||||
} catch (err) {
|
||||
if (err instanceof AgentIdPError) {
|
||||
console.error(err.code); // e.g. 'AgentNotFoundError'
|
||||
console.error(err.httpStatus); // e.g. 404
|
||||
console.error(err.message); // human-readable description
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Available scopes
|
||||
|
||||
| Scope | What it allows |
|
||||
|-------|----------------|
|
||||
| `agents:read` | Read agent records |
|
||||
| `agents:write` | Create, update, decommission agents |
|
||||
| `tokens:read` | Introspect tokens |
|
||||
| `audit:read` | Query audit logs |
|
||||
|
||||
---
|
||||
|
||||
## License
|
||||
|
||||
Apache 2.0 — see [LICENSE](../LICENSE) in the repository root.
|
||||
22
sdk/package.json
Normal file
22
sdk/package.json
Normal file
@@ -0,0 +1,22 @@
|
||||
{
|
||||
"name": "@sentryagent/idp-sdk",
|
||||
"version": "1.0.0",
|
||||
"description": "Node.js SDK for SentryAgent.ai AgentIdP — typed client for agent identity management",
|
||||
"main": "dist/index.js",
|
||||
"types": "dist/index.d.ts",
|
||||
"scripts": {
|
||||
"build": "tsc",
|
||||
"prepublishOnly": "npm run build"
|
||||
},
|
||||
"files": [
|
||||
"dist/"
|
||||
],
|
||||
"keywords": ["sentryagent", "agentidp", "agntcy", "ai-agent", "identity"],
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=18.0.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"typescript": "^5.4.5"
|
||||
}
|
||||
}
|
||||
66
sdk/src/client.ts
Normal file
66
sdk/src/client.ts
Normal file
@@ -0,0 +1,66 @@
|
||||
import { TokenManager } from './token-manager.js';
|
||||
import { AgentRegistryClient } from './services/agents.js';
|
||||
import { CredentialClient } from './services/credentials.js';
|
||||
import { TokenClient } from './services/token.js';
|
||||
import { AuditClient } from './services/audit.js';
|
||||
import type { AgentIdPClientConfig, OAuthScope } from './types.js';
|
||||
|
||||
/**
|
||||
* Top-level client for the SentryAgent.ai AgentIdP API.
|
||||
*
|
||||
* Composes all service clients under a single entry point.
|
||||
* Handles token acquisition and caching automatically via TokenManager.
|
||||
*
|
||||
* @example
|
||||
* ```typescript
|
||||
* const client = new AgentIdPClient({
|
||||
* baseUrl: 'http://localhost:3000',
|
||||
* clientId: 'your-agent-id',
|
||||
* clientSecret: 'your-client-secret',
|
||||
* });
|
||||
*
|
||||
* const agents = await client.agents.listAgents();
|
||||
* ```
|
||||
*/
|
||||
export class AgentIdPClient {
|
||||
/** Agent Registry operations: register, list, get, update, decommission. */
|
||||
readonly agents: AgentRegistryClient;
|
||||
|
||||
/** Credential operations: generate, list, rotate, revoke. */
|
||||
readonly credentials: CredentialClient;
|
||||
|
||||
/** Token operations: introspect, revoke. */
|
||||
readonly tokens: TokenClient;
|
||||
|
||||
/** Audit log operations: query, get event. */
|
||||
readonly audit: AuditClient;
|
||||
|
||||
private readonly tokenManager: TokenManager;
|
||||
|
||||
constructor(config: AgentIdPClientConfig) {
|
||||
const defaultScopes: OAuthScope[] = ['agents:read', 'agents:write', 'tokens:read', 'audit:read'];
|
||||
const scopes = (config.scopes ?? defaultScopes).join(' ');
|
||||
|
||||
this.tokenManager = new TokenManager(
|
||||
config.baseUrl,
|
||||
config.clientId,
|
||||
config.clientSecret,
|
||||
scopes,
|
||||
);
|
||||
|
||||
const getToken = () => this.tokenManager.getToken();
|
||||
|
||||
this.agents = new AgentRegistryClient(config.baseUrl, getToken);
|
||||
this.credentials = new CredentialClient(config.baseUrl, getToken);
|
||||
this.tokens = new TokenClient(config.baseUrl, getToken);
|
||||
this.audit = new AuditClient(config.baseUrl, getToken);
|
||||
}
|
||||
|
||||
/**
|
||||
* Clear the cached access token. The next API call will request a new token.
|
||||
* Use this after rotating credentials or when you suspect the token is stale.
|
||||
*/
|
||||
clearTokenCache(): void {
|
||||
this.tokenManager.clearCache();
|
||||
}
|
||||
}
|
||||
71
sdk/src/errors.ts
Normal file
71
sdk/src/errors.ts
Normal file
@@ -0,0 +1,71 @@
|
||||
/**
|
||||
* Error types for the SentryAgent.ai AgentIdP SDK.
|
||||
*/
|
||||
|
||||
/** Standard error response shape from the AgentIdP API. */
|
||||
interface ApiErrorBody {
|
||||
code: string;
|
||||
message: string;
|
||||
details?: Record<string, unknown>;
|
||||
}
|
||||
|
||||
/** OAuth 2.0 error response shape from the token endpoint. */
|
||||
interface OAuth2ErrorBody {
|
||||
error: string;
|
||||
error_description: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Typed error thrown by the AgentIdP SDK for all API failures.
|
||||
* Never throws raw fetch errors or untyped exceptions.
|
||||
*/
|
||||
export class AgentIdPError extends Error {
|
||||
/** Machine-readable error code from the API (e.g. AGENT_NOT_FOUND). */
|
||||
readonly code: string;
|
||||
/** HTTP status code of the failed response. */
|
||||
readonly httpStatus: number;
|
||||
/** Optional structured details from the API error response. */
|
||||
readonly details?: Record<string, unknown>;
|
||||
|
||||
constructor(code: string, message: string, httpStatus: number, details?: Record<string, unknown>) {
|
||||
super(message);
|
||||
this.name = 'AgentIdPError';
|
||||
this.code = code;
|
||||
this.httpStatus = httpStatus;
|
||||
this.details = details;
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates an AgentIdPError from a standard API error response body.
|
||||
* Accepts unknown to allow callers to pass raw parsed JSON without pre-casting.
|
||||
*
|
||||
* @param body - Parsed API error response (or unknown).
|
||||
* @param httpStatus - HTTP status code.
|
||||
* @returns AgentIdPError instance.
|
||||
*/
|
||||
static fromApiError(body: unknown, httpStatus: number): AgentIdPError {
|
||||
if (
|
||||
typeof body === 'object' &&
|
||||
body !== null &&
|
||||
'code' in body &&
|
||||
'message' in body &&
|
||||
typeof (body as ApiErrorBody).code === 'string' &&
|
||||
typeof (body as ApiErrorBody).message === 'string'
|
||||
) {
|
||||
const typed = body as ApiErrorBody;
|
||||
return new AgentIdPError(typed.code, typed.message, httpStatus, typed.details);
|
||||
}
|
||||
return new AgentIdPError('UNKNOWN_ERROR', String(body), httpStatus);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates an AgentIdPError from an OAuth 2.0 error response body.
|
||||
*
|
||||
* @param body - Parsed OAuth2 error response.
|
||||
* @param httpStatus - HTTP status code.
|
||||
* @returns AgentIdPError instance.
|
||||
*/
|
||||
static fromOAuth2Error(body: OAuth2ErrorBody, httpStatus: number): AgentIdPError {
|
||||
return new AgentIdPError(body.error, body.error_description, httpStatus);
|
||||
}
|
||||
}
|
||||
35
sdk/src/index.ts
Normal file
35
sdk/src/index.ts
Normal file
@@ -0,0 +1,35 @@
|
||||
export { AgentIdPClient } from './client.js';
|
||||
export { AgentIdPError } from './errors.js';
|
||||
export { TokenManager } from './token-manager.js';
|
||||
|
||||
export type {
|
||||
// Config
|
||||
AgentIdPClientConfig,
|
||||
// Enums / union types
|
||||
AgentType,
|
||||
AgentStatus,
|
||||
DeploymentEnv,
|
||||
CredentialStatus,
|
||||
OAuthScope,
|
||||
AuditAction,
|
||||
AuditOutcome,
|
||||
// Agent Registry
|
||||
Agent,
|
||||
RegisterAgentRequest,
|
||||
UpdateAgentRequest,
|
||||
ListAgentsParams,
|
||||
PaginatedAgents,
|
||||
// Credentials
|
||||
Credential,
|
||||
CredentialWithSecret,
|
||||
GenerateCredentialRequest,
|
||||
ListCredentialsParams,
|
||||
PaginatedCredentials,
|
||||
// Tokens
|
||||
TokenResponse,
|
||||
IntrospectResponse,
|
||||
// Audit
|
||||
AuditEvent,
|
||||
QueryAuditLogParams,
|
||||
PaginatedAuditEvents,
|
||||
} from './types.js';
|
||||
72
sdk/src/request.ts
Normal file
72
sdk/src/request.ts
Normal file
@@ -0,0 +1,72 @@
|
||||
import { AgentIdPError } from './errors.js';
|
||||
|
||||
type HttpMethod = 'GET' | 'POST' | 'PATCH' | 'DELETE';
|
||||
|
||||
interface RequestOptions {
|
||||
method: HttpMethod;
|
||||
path: string;
|
||||
token: string;
|
||||
body?: unknown;
|
||||
query?: Record<string, string | number | boolean | undefined>;
|
||||
}
|
||||
|
||||
/**
|
||||
* Shared HTTP request helper for all AgentIdP API calls.
|
||||
* Sets Authorization header, serialises JSON body, parses response,
|
||||
* and maps API error shapes to AgentIdPError.
|
||||
*/
|
||||
export async function request<T>(baseUrl: string, opts: RequestOptions): Promise<T> {
|
||||
const url = new URL(opts.path, baseUrl);
|
||||
|
||||
if (opts.query) {
|
||||
for (const [key, value] of Object.entries(opts.query)) {
|
||||
if (value !== undefined) {
|
||||
url.searchParams.set(key, String(value));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const headers: Record<string, string> = {
|
||||
Authorization: `Bearer ${opts.token}`,
|
||||
Accept: 'application/json',
|
||||
};
|
||||
|
||||
let bodyPayload: string | undefined;
|
||||
if (opts.body !== undefined) {
|
||||
headers['Content-Type'] = 'application/json';
|
||||
bodyPayload = JSON.stringify(opts.body);
|
||||
}
|
||||
|
||||
let response: Response;
|
||||
try {
|
||||
response = await fetch(url.toString(), {
|
||||
method: opts.method,
|
||||
headers,
|
||||
body: bodyPayload,
|
||||
});
|
||||
} catch (err) {
|
||||
throw new AgentIdPError(
|
||||
'NETWORK_ERROR',
|
||||
`Network error: ${err instanceof Error ? err.message : String(err)}`,
|
||||
0,
|
||||
);
|
||||
}
|
||||
|
||||
if (response.status === 204) {
|
||||
return undefined as unknown as T;
|
||||
}
|
||||
|
||||
let data: unknown;
|
||||
const contentType = response.headers.get('content-type') ?? '';
|
||||
if (contentType.includes('application/json')) {
|
||||
data = await response.json();
|
||||
} else {
|
||||
data = await response.text();
|
||||
}
|
||||
|
||||
if (!response.ok) {
|
||||
throw AgentIdPError.fromApiError(data, response.status);
|
||||
}
|
||||
|
||||
return data as T;
|
||||
}
|
||||
90
sdk/src/services/agents.ts
Normal file
90
sdk/src/services/agents.ts
Normal file
@@ -0,0 +1,90 @@
|
||||
import { request } from '../request.js';
|
||||
import type {
|
||||
Agent,
|
||||
RegisterAgentRequest,
|
||||
UpdateAgentRequest,
|
||||
ListAgentsParams,
|
||||
PaginatedAgents,
|
||||
} from '../types.js';
|
||||
|
||||
/**
|
||||
* Client for the Agent Registry service.
|
||||
* Covers all agent CRUD operations: register, list, get, update, decommission.
|
||||
*/
|
||||
export class AgentRegistryClient {
|
||||
constructor(
|
||||
private readonly baseUrl: string,
|
||||
private readonly getToken: () => Promise<string>,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* Register a new AI agent.
|
||||
* Returns the created agent record including its agentId and agentSecret.
|
||||
*/
|
||||
async registerAgent(params: RegisterAgentRequest): Promise<Agent> {
|
||||
const token = await this.getToken();
|
||||
return request<Agent>(this.baseUrl, {
|
||||
method: 'POST',
|
||||
path: '/api/v1/agents',
|
||||
token,
|
||||
body: params,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* List all registered agents with optional filters and pagination.
|
||||
*/
|
||||
async listAgents(params: ListAgentsParams = {}): Promise<PaginatedAgents> {
|
||||
const token = await this.getToken();
|
||||
return request<PaginatedAgents>(this.baseUrl, {
|
||||
method: 'GET',
|
||||
path: '/api/v1/agents',
|
||||
token,
|
||||
query: {
|
||||
status: params.status,
|
||||
agentType: params.agentType,
|
||||
page: params.page,
|
||||
limit: params.limit,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Get a single agent by its agentId.
|
||||
*/
|
||||
async getAgent(agentId: string): Promise<Agent> {
|
||||
const token = await this.getToken();
|
||||
return request<Agent>(this.baseUrl, {
|
||||
method: 'GET',
|
||||
path: `/api/v1/agents/${agentId}`,
|
||||
token,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Update mutable fields on an existing agent (name, description, capabilities, metadata).
|
||||
* Returns the updated agent record.
|
||||
*/
|
||||
async updateAgent(agentId: string, params: UpdateAgentRequest): Promise<Agent> {
|
||||
const token = await this.getToken();
|
||||
return request<Agent>(this.baseUrl, {
|
||||
method: 'PATCH',
|
||||
path: `/api/v1/agents/${agentId}`,
|
||||
token,
|
||||
body: params,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Decommission an agent. This is irreversible — the agent can no longer
|
||||
* authenticate or obtain tokens after decommission.
|
||||
*/
|
||||
async decommissionAgent(agentId: string): Promise<void> {
|
||||
const token = await this.getToken();
|
||||
return request<void>(this.baseUrl, {
|
||||
method: 'DELETE',
|
||||
path: `/api/v1/agents/${agentId}`,
|
||||
token,
|
||||
});
|
||||
}
|
||||
}
|
||||
48
sdk/src/services/audit.ts
Normal file
48
sdk/src/services/audit.ts
Normal file
@@ -0,0 +1,48 @@
|
||||
import { request } from '../request.js';
|
||||
import type { AuditEvent, QueryAuditLogParams, PaginatedAuditEvents } from '../types.js';
|
||||
|
||||
/**
|
||||
* Client for the Audit Log service.
|
||||
* Covers querying the audit event list and fetching individual events.
|
||||
*/
|
||||
export class AuditClient {
|
||||
constructor(
|
||||
private readonly baseUrl: string,
|
||||
private readonly getToken: () => Promise<string>,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* Query audit log events with optional filters and pagination.
|
||||
* Events are retained for 90 days. Requires `audit:read` scope.
|
||||
*/
|
||||
async queryAuditLog(params: QueryAuditLogParams = {}): Promise<PaginatedAuditEvents> {
|
||||
const token = await this.getToken();
|
||||
return request<PaginatedAuditEvents>(this.baseUrl, {
|
||||
method: 'GET',
|
||||
path: '/api/v1/audit',
|
||||
token,
|
||||
query: {
|
||||
agentId: params.agentId,
|
||||
action: params.action,
|
||||
outcome: params.outcome,
|
||||
fromDate: params.fromDate,
|
||||
toDate: params.toDate,
|
||||
page: params.page,
|
||||
limit: params.limit,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Get a single audit event by its eventId.
|
||||
* Requires `audit:read` scope.
|
||||
*/
|
||||
async getAuditEvent(eventId: string): Promise<AuditEvent> {
|
||||
const token = await this.getToken();
|
||||
return request<AuditEvent>(this.baseUrl, {
|
||||
method: 'GET',
|
||||
path: `/api/v1/audit/${eventId}`,
|
||||
token,
|
||||
});
|
||||
}
|
||||
}
|
||||
83
sdk/src/services/credentials.ts
Normal file
83
sdk/src/services/credentials.ts
Normal file
@@ -0,0 +1,83 @@
|
||||
import { request } from '../request.js';
|
||||
import type {
|
||||
Credential,
|
||||
CredentialWithSecret,
|
||||
GenerateCredentialRequest,
|
||||
ListCredentialsParams,
|
||||
PaginatedCredentials,
|
||||
} from '../types.js';
|
||||
|
||||
/**
|
||||
* Client for the Credential Management service.
|
||||
* Covers generate, list, rotate, and revoke operations for agent credentials.
|
||||
*/
|
||||
export class CredentialClient {
|
||||
constructor(
|
||||
private readonly baseUrl: string,
|
||||
private readonly getToken: () => Promise<string>,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* Generate a new credential for an agent.
|
||||
* The `clientSecret` in the response is shown ONCE — store it securely immediately.
|
||||
*/
|
||||
async generateCredential(
|
||||
agentId: string,
|
||||
params: GenerateCredentialRequest = {},
|
||||
): Promise<CredentialWithSecret> {
|
||||
const token = await this.getToken();
|
||||
return request<CredentialWithSecret>(this.baseUrl, {
|
||||
method: 'POST',
|
||||
path: `/api/v1/agents/${agentId}/credentials`,
|
||||
token,
|
||||
body: Object.keys(params).length > 0 ? params : undefined,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* List all credentials for an agent with optional pagination.
|
||||
* Secrets are never returned in list responses.
|
||||
*/
|
||||
async listCredentials(
|
||||
agentId: string,
|
||||
params: ListCredentialsParams = {},
|
||||
): Promise<PaginatedCredentials> {
|
||||
const token = await this.getToken();
|
||||
return request<PaginatedCredentials>(this.baseUrl, {
|
||||
method: 'GET',
|
||||
path: `/api/v1/agents/${agentId}/credentials`,
|
||||
token,
|
||||
query: {
|
||||
page: params.page,
|
||||
limit: params.limit,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Rotate a credential. The same credentialId is retained but a new secret is issued.
|
||||
* The old secret is immediately invalidated upon rotation.
|
||||
* The new `clientSecret` is shown ONCE — store it securely immediately.
|
||||
*/
|
||||
async rotateCredential(agentId: string, credentialId: string): Promise<CredentialWithSecret> {
|
||||
const token = await this.getToken();
|
||||
return request<CredentialWithSecret>(this.baseUrl, {
|
||||
method: 'POST',
|
||||
path: `/api/v1/agents/${agentId}/credentials/${credentialId}/rotate`,
|
||||
token,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Revoke a credential. Any tokens previously issued with this credential
|
||||
* remain valid until they expire — use token revocation to invalidate them immediately.
|
||||
*/
|
||||
async revokeCredential(agentId: string, credentialId: string): Promise<Credential> {
|
||||
const token = await this.getToken();
|
||||
return request<Credential>(this.baseUrl, {
|
||||
method: 'DELETE',
|
||||
path: `/api/v1/agents/${agentId}/credentials/${credentialId}`,
|
||||
token,
|
||||
});
|
||||
}
|
||||
}
|
||||
80
sdk/src/services/token.ts
Normal file
80
sdk/src/services/token.ts
Normal file
@@ -0,0 +1,80 @@
|
||||
import { request } from '../request.js';
|
||||
import { AgentIdPError } from '../errors.js';
|
||||
import type { IntrospectResponse } from '../types.js';
|
||||
|
||||
/**
|
||||
* Client for OAuth 2.0 token operations (introspect and revoke).
|
||||
* Token issuance is handled separately by TokenManager.
|
||||
*/
|
||||
export class TokenClient {
|
||||
constructor(
|
||||
private readonly baseUrl: string,
|
||||
private readonly getToken: () => Promise<string>,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* Introspect a token to check whether it is currently active.
|
||||
* Always returns 200 — check the `active` field to determine validity.
|
||||
* Requires a Bearer token with `tokens:read` scope.
|
||||
*/
|
||||
async introspectToken(tokenToCheck: string): Promise<IntrospectResponse> {
|
||||
const token = await this.getToken();
|
||||
const body = new URLSearchParams({ token: tokenToCheck });
|
||||
|
||||
let response: Response;
|
||||
try {
|
||||
response = await fetch(new URL('/api/v1/token/introspect', this.baseUrl).toString(), {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
Authorization: `Bearer ${token}`,
|
||||
'Content-Type': 'application/x-www-form-urlencoded',
|
||||
},
|
||||
body: body.toString(),
|
||||
});
|
||||
} catch (err) {
|
||||
throw new AgentIdPError(
|
||||
'NETWORK_ERROR',
|
||||
`Network error: ${err instanceof Error ? err.message : String(err)}`,
|
||||
0,
|
||||
);
|
||||
}
|
||||
|
||||
const data: unknown = await response.json();
|
||||
if (!response.ok) {
|
||||
throw AgentIdPError.fromApiError(data, response.status);
|
||||
}
|
||||
return data as IntrospectResponse;
|
||||
}
|
||||
|
||||
/**
|
||||
* Revoke a token immediately. Idempotent — revoking an already-revoked
|
||||
* or expired token is not an error (RFC 7009).
|
||||
*/
|
||||
async revokeToken(tokenToRevoke: string): Promise<void> {
|
||||
const token = await this.getToken();
|
||||
const body = new URLSearchParams({ token: tokenToRevoke });
|
||||
|
||||
let response: Response;
|
||||
try {
|
||||
response = await fetch(new URL('/api/v1/token/revoke', this.baseUrl).toString(), {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
Authorization: `Bearer ${token}`,
|
||||
'Content-Type': 'application/x-www-form-urlencoded',
|
||||
},
|
||||
body: body.toString(),
|
||||
});
|
||||
} catch (err) {
|
||||
throw new AgentIdPError(
|
||||
'NETWORK_ERROR',
|
||||
`Network error: ${err instanceof Error ? err.message : String(err)}`,
|
||||
0,
|
||||
);
|
||||
}
|
||||
|
||||
if (!response.ok) {
|
||||
const data: unknown = await response.json();
|
||||
throw AgentIdPError.fromApiError(data, response.status);
|
||||
}
|
||||
}
|
||||
}
|
||||
97
sdk/src/token-manager.ts
Normal file
97
sdk/src/token-manager.ts
Normal file
@@ -0,0 +1,97 @@
|
||||
/**
|
||||
* TokenManager — handles OAuth 2.0 token acquisition, caching, and refresh.
|
||||
* Tokens are re-issued automatically when expired or within 60 seconds of expiry.
|
||||
*/
|
||||
|
||||
import { AgentIdPError } from './errors.js';
|
||||
import { TokenResponse } from './types.js';
|
||||
|
||||
/** Seconds before expiry at which a token refresh is triggered. */
|
||||
const REFRESH_BUFFER_SECONDS = 60;
|
||||
|
||||
interface CachedToken {
|
||||
accessToken: string;
|
||||
expiresAt: number; // Unix seconds
|
||||
}
|
||||
|
||||
/**
|
||||
* Manages token acquisition and caching for the AgentIdP SDK.
|
||||
* Callers request a token via `getToken()` — the manager handles issuance and refresh transparently.
|
||||
*/
|
||||
export class TokenManager {
|
||||
private cached: CachedToken | null = null;
|
||||
|
||||
/**
|
||||
* @param baseUrl - AgentIdP API base URL.
|
||||
* @param clientId - The agent's clientId (agentId UUID).
|
||||
* @param clientSecret - The agent's clientSecret.
|
||||
* @param scopes - Space-separated OAuth 2.0 scopes to request.
|
||||
*/
|
||||
constructor(
|
||||
private readonly baseUrl: string,
|
||||
private readonly clientId: string,
|
||||
private readonly clientSecret: string,
|
||||
private readonly scopes: string,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* Returns a valid access token.
|
||||
* Acquires a new token if none is cached or the cached token is near expiry.
|
||||
*
|
||||
* @returns A valid JWT access token string.
|
||||
* @throws AgentIdPError if token acquisition fails.
|
||||
*/
|
||||
async getToken(): Promise<string> {
|
||||
const now = Math.floor(Date.now() / 1000);
|
||||
|
||||
if (this.cached && this.cached.expiresAt - now > REFRESH_BUFFER_SECONDS) {
|
||||
return this.cached.accessToken;
|
||||
}
|
||||
|
||||
const token = await this.issueToken();
|
||||
this.cached = {
|
||||
accessToken: token.access_token,
|
||||
expiresAt: now + token.expires_in,
|
||||
};
|
||||
|
||||
return this.cached.accessToken;
|
||||
}
|
||||
|
||||
/**
|
||||
* Calls POST /token to issue a new access token.
|
||||
*
|
||||
* @returns TokenResponse from the API.
|
||||
* @throws AgentIdPError on authentication failure or API error.
|
||||
*/
|
||||
private async issueToken(): Promise<TokenResponse> {
|
||||
const body = new URLSearchParams({
|
||||
grant_type: 'client_credentials',
|
||||
client_id: this.clientId,
|
||||
client_secret: this.clientSecret,
|
||||
scope: this.scopes,
|
||||
});
|
||||
|
||||
const response = await fetch(`${this.baseUrl}/api/v1/token`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
|
||||
body: body.toString(),
|
||||
});
|
||||
|
||||
const data = (await response.json()) as Record<string, unknown>;
|
||||
|
||||
if (!response.ok) {
|
||||
const errorBody = data as { error: string; error_description: string };
|
||||
throw AgentIdPError.fromOAuth2Error(
|
||||
{ error: String(errorBody.error ?? 'unknown_error'), error_description: String(errorBody.error_description ?? 'Token request failed.') },
|
||||
response.status,
|
||||
);
|
||||
}
|
||||
|
||||
return data as unknown as TokenResponse;
|
||||
}
|
||||
|
||||
/** Clears the cached token, forcing re-acquisition on next getToken() call. */
|
||||
clearCache(): void {
|
||||
this.cached = null;
|
||||
}
|
||||
}
|
||||
217
sdk/src/types.ts
Normal file
217
sdk/src/types.ts
Normal file
@@ -0,0 +1,217 @@
|
||||
/**
|
||||
* TypeScript types for the SentryAgent.ai AgentIdP SDK.
|
||||
* All request and response shapes derived from the AgentIdP OpenAPI 3.0 specs.
|
||||
*/
|
||||
|
||||
// ─────────────────────────────────────────────────────────────────────────────
|
||||
// Shared enums
|
||||
// ─────────────────────────────────────────────────────────────────────────────
|
||||
|
||||
/** Functional classification of an AI agent. */
|
||||
export type AgentType =
|
||||
| 'screener'
|
||||
| 'classifier'
|
||||
| 'orchestrator'
|
||||
| 'extractor'
|
||||
| 'summarizer'
|
||||
| 'router'
|
||||
| 'monitor'
|
||||
| 'custom';
|
||||
|
||||
/** Lifecycle status of an AI agent. */
|
||||
export type AgentStatus = 'active' | 'suspended' | 'decommissioned';
|
||||
|
||||
/** Target deployment environment. */
|
||||
export type DeploymentEnv = 'development' | 'staging' | 'production';
|
||||
|
||||
/** Lifecycle status of a credential. */
|
||||
export type CredentialStatus = 'active' | 'revoked';
|
||||
|
||||
/** OAuth 2.0 scopes supported by AgentIdP. */
|
||||
export type OAuthScope = 'agents:read' | 'agents:write' | 'tokens:read' | 'audit:read';
|
||||
|
||||
/** Audit event action types. */
|
||||
export type AuditAction =
|
||||
| 'agent.created'
|
||||
| 'agent.updated'
|
||||
| 'agent.decommissioned'
|
||||
| 'agent.suspended'
|
||||
| 'agent.reactivated'
|
||||
| 'token.issued'
|
||||
| 'token.revoked'
|
||||
| 'token.introspected'
|
||||
| 'credential.generated'
|
||||
| 'credential.rotated'
|
||||
| 'credential.revoked'
|
||||
| 'auth.failed';
|
||||
|
||||
/** Outcome of an audited action. */
|
||||
export type AuditOutcome = 'success' | 'failure';
|
||||
|
||||
// ─────────────────────────────────────────────────────────────────────────────
|
||||
// Agent Registry
|
||||
// ─────────────────────────────────────────────────────────────────────────────
|
||||
|
||||
/** A registered AI agent identity. */
|
||||
export interface Agent {
|
||||
agentId: string;
|
||||
email: string;
|
||||
agentType: AgentType;
|
||||
version: string;
|
||||
capabilities: string[];
|
||||
owner: string;
|
||||
deploymentEnv: DeploymentEnv;
|
||||
status: AgentStatus;
|
||||
createdAt: string;
|
||||
updatedAt: string;
|
||||
}
|
||||
|
||||
/** Request body for registering a new agent. */
|
||||
export interface RegisterAgentRequest {
|
||||
email: string;
|
||||
agentType: AgentType;
|
||||
version: string;
|
||||
capabilities: string[];
|
||||
owner: string;
|
||||
deploymentEnv: DeploymentEnv;
|
||||
}
|
||||
|
||||
/** Request body for updating agent metadata (all fields optional). */
|
||||
export interface UpdateAgentRequest {
|
||||
agentType?: AgentType;
|
||||
version?: string;
|
||||
capabilities?: string[];
|
||||
owner?: string;
|
||||
deploymentEnv?: DeploymentEnv;
|
||||
status?: AgentStatus;
|
||||
}
|
||||
|
||||
/** Query parameters for listing agents. */
|
||||
export interface ListAgentsParams {
|
||||
page?: number;
|
||||
limit?: number;
|
||||
owner?: string;
|
||||
agentType?: AgentType;
|
||||
status?: AgentStatus;
|
||||
}
|
||||
|
||||
/** Paginated list of agents. */
|
||||
export interface PaginatedAgents {
|
||||
data: Agent[];
|
||||
total: number;
|
||||
page: number;
|
||||
limit: number;
|
||||
}
|
||||
|
||||
// ─────────────────────────────────────────────────────────────────────────────
|
||||
// Credential Management
|
||||
// ─────────────────────────────────────────────────────────────────────────────
|
||||
|
||||
/** A credential record (clientSecret never included). */
|
||||
export interface Credential {
|
||||
credentialId: string;
|
||||
clientId: string;
|
||||
status: CredentialStatus;
|
||||
createdAt: string;
|
||||
expiresAt: string | null;
|
||||
revokedAt: string | null;
|
||||
}
|
||||
|
||||
/** A credential record with the plain-text secret — returned once only on create/rotate. */
|
||||
export interface CredentialWithSecret extends Credential {
|
||||
clientSecret: string;
|
||||
}
|
||||
|
||||
/** Optional request body for generating or rotating a credential. */
|
||||
export interface GenerateCredentialRequest {
|
||||
expiresAt?: string;
|
||||
}
|
||||
|
||||
/** Query parameters for listing credentials. */
|
||||
export interface ListCredentialsParams {
|
||||
page?: number;
|
||||
limit?: number;
|
||||
status?: CredentialStatus;
|
||||
}
|
||||
|
||||
/** Paginated list of credentials. */
|
||||
export interface PaginatedCredentials {
|
||||
data: Credential[];
|
||||
total: number;
|
||||
page: number;
|
||||
limit: number;
|
||||
}
|
||||
|
||||
// ─────────────────────────────────────────────────────────────────────────────
|
||||
// OAuth 2.0 Tokens
|
||||
// ─────────────────────────────────────────────────────────────────────────────
|
||||
|
||||
/** OAuth 2.0 access token response. */
|
||||
export interface TokenResponse {
|
||||
access_token: string;
|
||||
token_type: 'Bearer';
|
||||
expires_in: number;
|
||||
scope: string;
|
||||
}
|
||||
|
||||
/** Token introspection response (RFC 7662). */
|
||||
export interface IntrospectResponse {
|
||||
active: boolean;
|
||||
sub?: string;
|
||||
client_id?: string;
|
||||
scope?: string;
|
||||
token_type?: string;
|
||||
iat?: number;
|
||||
exp?: number;
|
||||
}
|
||||
|
||||
// ─────────────────────────────────────────────────────────────────────────────
|
||||
// Audit Log
|
||||
// ─────────────────────────────────────────────────────────────────────────────
|
||||
|
||||
/** An immutable audit event record. */
|
||||
export interface AuditEvent {
|
||||
eventId: string;
|
||||
agentId: string;
|
||||
action: AuditAction;
|
||||
outcome: AuditOutcome;
|
||||
ipAddress: string;
|
||||
userAgent: string;
|
||||
metadata: Record<string, unknown>;
|
||||
timestamp: string;
|
||||
}
|
||||
|
||||
/** Query parameters for the audit log. */
|
||||
export interface QueryAuditLogParams {
|
||||
page?: number;
|
||||
limit?: number;
|
||||
agentId?: string;
|
||||
action?: AuditAction;
|
||||
outcome?: AuditOutcome;
|
||||
fromDate?: string;
|
||||
toDate?: string;
|
||||
}
|
||||
|
||||
/** Paginated list of audit events. */
|
||||
export interface PaginatedAuditEvents {
|
||||
data: AuditEvent[];
|
||||
total: number;
|
||||
page: number;
|
||||
limit: number;
|
||||
}
|
||||
|
||||
// ─────────────────────────────────────────────────────────────────────────────
|
||||
// SDK Config
|
||||
// ─────────────────────────────────────────────────────────────────────────────
|
||||
|
||||
/** Configuration for AgentIdPClient. */
|
||||
export interface AgentIdPClientConfig {
|
||||
/** Base URL of the AgentIdP server, e.g. http://localhost:3000/api/v1 */
|
||||
baseUrl: string;
|
||||
/** The agent's clientId (agentId UUID). */
|
||||
clientId: string;
|
||||
/** The agent's clientSecret. */
|
||||
clientSecret: string;
|
||||
/** OAuth 2.0 scopes to request. Defaults to all scopes. */
|
||||
scopes?: OAuthScope[];
|
||||
}
|
||||
18
sdk/tsconfig.json
Normal file
18
sdk/tsconfig.json
Normal file
@@ -0,0 +1,18 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"target": "ES2020",
|
||||
"module": "commonjs",
|
||||
"lib": ["ES2020"],
|
||||
"outDir": "./dist",
|
||||
"rootDir": "./src",
|
||||
"strict": true,
|
||||
"declaration": true,
|
||||
"declarationMap": true,
|
||||
"sourceMap": true,
|
||||
"esModuleInterop": true,
|
||||
"skipLibCheck": true,
|
||||
"forceConsistentCasingInFileNames": true
|
||||
},
|
||||
"include": ["src/**/*"],
|
||||
"exclude": ["node_modules", "dist"]
|
||||
}
|
||||
138
src/app.ts
Normal file
138
src/app.ts
Normal file
@@ -0,0 +1,138 @@
|
||||
/**
|
||||
* Express application factory for SentryAgent.ai AgentIdP.
|
||||
* Creates and configures the Express app with all middleware and routes.
|
||||
* Exported as a factory function — does NOT call listen (testable).
|
||||
*/
|
||||
|
||||
import express, { Application } from 'express';
|
||||
import helmet from 'helmet';
|
||||
import cors from 'cors';
|
||||
import morgan from 'morgan';
|
||||
|
||||
import { getPool } from './db/pool.js';
|
||||
import { getRedisClient } from './cache/redis.js';
|
||||
|
||||
import { AgentRepository } from './repositories/AgentRepository.js';
|
||||
import { CredentialRepository } from './repositories/CredentialRepository.js';
|
||||
import { TokenRepository } from './repositories/TokenRepository.js';
|
||||
import { AuditRepository } from './repositories/AuditRepository.js';
|
||||
|
||||
import { AuditService } from './services/AuditService.js';
|
||||
import { AgentService } from './services/AgentService.js';
|
||||
import { CredentialService } from './services/CredentialService.js';
|
||||
import { OAuth2Service } from './services/OAuth2Service.js';
|
||||
|
||||
import { AgentController } from './controllers/AgentController.js';
|
||||
import { TokenController } from './controllers/TokenController.js';
|
||||
import { CredentialController } from './controllers/CredentialController.js';
|
||||
import { AuditController } from './controllers/AuditController.js';
|
||||
|
||||
import { createAgentsRouter } from './routes/agents.js';
|
||||
import { createTokenRouter } from './routes/token.js';
|
||||
import { createCredentialsRouter } from './routes/credentials.js';
|
||||
import { createAuditRouter } from './routes/audit.js';
|
||||
|
||||
import { errorHandler } from './middleware/errorHandler.js';
|
||||
import { RedisClientType } from 'redis';
|
||||
|
||||
/**
|
||||
* Creates and returns a configured Express application.
|
||||
* All infrastructure dependencies (DB pool, Redis) are initialised here.
|
||||
*
|
||||
* @returns Promise resolving to the configured Express Application.
|
||||
* @throws Error if required environment variables are missing.
|
||||
*/
|
||||
export async function createApp(): Promise<Application> {
|
||||
const app = express();
|
||||
|
||||
// ────────────────────────────────────────────────────────────────
|
||||
// Security headers
|
||||
// ────────────────────────────────────────────────────────────────
|
||||
app.use(helmet());
|
||||
|
||||
// ────────────────────────────────────────────────────────────────
|
||||
// CORS
|
||||
// ────────────────────────────────────────────────────────────────
|
||||
const corsOrigin = process.env['CORS_ORIGIN'] ?? '*';
|
||||
app.use(cors({ origin: corsOrigin }));
|
||||
|
||||
// ────────────────────────────────────────────────────────────────
|
||||
// Request logging
|
||||
// ────────────────────────────────────────────────────────────────
|
||||
if (process.env['NODE_ENV'] !== 'test') {
|
||||
app.use(morgan('combined'));
|
||||
}
|
||||
|
||||
// ────────────────────────────────────────────────────────────────
|
||||
// Body parsers
|
||||
// JSON body parser for most routes
|
||||
// urlencoded parser for token endpoint (application/x-www-form-urlencoded)
|
||||
// ────────────────────────────────────────────────────────────────
|
||||
app.use(express.json());
|
||||
app.use(express.urlencoded({ extended: false }));
|
||||
|
||||
// ────────────────────────────────────────────────────────────────
|
||||
// Infrastructure singletons
|
||||
// ────────────────────────────────────────────────────────────────
|
||||
const pool = getPool();
|
||||
const redis = await getRedisClient();
|
||||
|
||||
// ────────────────────────────────────────────────────────────────
|
||||
// Repository layer
|
||||
// ────────────────────────────────────────────────────────────────
|
||||
const agentRepo = new AgentRepository(pool);
|
||||
const credentialRepo = new CredentialRepository(pool);
|
||||
// eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion
|
||||
const tokenRepo = new TokenRepository(pool, redis as RedisClientType);
|
||||
const auditRepo = new AuditRepository(pool);
|
||||
|
||||
// ────────────────────────────────────────────────────────────────
|
||||
// Service layer
|
||||
// ────────────────────────────────────────────────────────────────
|
||||
const auditService = new AuditService(auditRepo);
|
||||
const agentService = new AgentService(agentRepo, credentialRepo, auditService);
|
||||
const credentialService = new CredentialService(credentialRepo, agentRepo, auditService);
|
||||
|
||||
const privateKey = process.env['JWT_PRIVATE_KEY'];
|
||||
const publicKey = process.env['JWT_PUBLIC_KEY'];
|
||||
if (!privateKey || !publicKey) {
|
||||
throw new Error('JWT_PRIVATE_KEY and JWT_PUBLIC_KEY environment variables are required');
|
||||
}
|
||||
|
||||
const oauth2Service = new OAuth2Service(
|
||||
tokenRepo,
|
||||
credentialRepo,
|
||||
agentRepo,
|
||||
auditService,
|
||||
privateKey,
|
||||
publicKey,
|
||||
);
|
||||
|
||||
// ────────────────────────────────────────────────────────────────
|
||||
// Controller layer
|
||||
// ────────────────────────────────────────────────────────────────
|
||||
const agentController = new AgentController(agentService);
|
||||
const tokenController = new TokenController(oauth2Service);
|
||||
const credentialController = new CredentialController(credentialService);
|
||||
const auditController = new AuditController(auditService);
|
||||
|
||||
// ────────────────────────────────────────────────────────────────
|
||||
// Routes
|
||||
// ────────────────────────────────────────────────────────────────
|
||||
const API_BASE = '/api/v1';
|
||||
|
||||
app.use(`${API_BASE}/agents`, createAgentsRouter(agentController));
|
||||
app.use(
|
||||
`${API_BASE}/agents/:agentId/credentials`,
|
||||
createCredentialsRouter(credentialController),
|
||||
);
|
||||
app.use(`${API_BASE}/token`, createTokenRouter(tokenController));
|
||||
app.use(`${API_BASE}/audit`, createAuditRouter(auditController));
|
||||
|
||||
// ────────────────────────────────────────────────────────────────
|
||||
// Global error handler (must be last)
|
||||
// ────────────────────────────────────────────────────────────────
|
||||
app.use(errorHandler);
|
||||
|
||||
return app;
|
||||
}
|
||||
47
src/cache/redis.ts
vendored
Normal file
47
src/cache/redis.ts
vendored
Normal file
@@ -0,0 +1,47 @@
|
||||
/**
|
||||
* Redis client singleton for SentryAgent.ai AgentIdP.
|
||||
* Used for token revocation tracking, rate limiting, and monthly token counts.
|
||||
*/
|
||||
|
||||
import { createClient, RedisClientType } from 'redis';
|
||||
|
||||
let redisClient: RedisClientType | null = null;
|
||||
|
||||
/**
|
||||
* Returns the singleton Redis client instance.
|
||||
* Initialises and connects the client on first call using REDIS_URL from env.
|
||||
*
|
||||
* @returns Promise resolving to the connected Redis client.
|
||||
* @throws Error if REDIS_URL is not set or connection fails.
|
||||
*/
|
||||
export async function getRedisClient(): Promise<RedisClientType> {
|
||||
if (!redisClient) {
|
||||
const url = process.env['REDIS_URL'];
|
||||
if (!url) {
|
||||
throw new Error('REDIS_URL environment variable is required');
|
||||
}
|
||||
|
||||
redisClient = createClient({ url }) as RedisClientType;
|
||||
|
||||
redisClient.on('error', (err: Error) => {
|
||||
// eslint-disable-next-line no-console
|
||||
console.error('Redis client error', err);
|
||||
});
|
||||
|
||||
await redisClient.connect();
|
||||
}
|
||||
return redisClient;
|
||||
}
|
||||
|
||||
/**
|
||||
* Disconnects the Redis client and resets the singleton.
|
||||
* Used for graceful shutdown and tests.
|
||||
*
|
||||
* @returns Promise that resolves when the client is disconnected.
|
||||
*/
|
||||
export async function closeRedisClient(): Promise<void> {
|
||||
if (redisClient) {
|
||||
await redisClient.quit();
|
||||
redisClient = null;
|
||||
}
|
||||
}
|
||||
186
src/controllers/AgentController.ts
Normal file
186
src/controllers/AgentController.ts
Normal file
@@ -0,0 +1,186 @@
|
||||
/**
|
||||
* Agent Controller for SentryAgent.ai AgentIdP.
|
||||
* HTTP handlers for all 5 agent endpoints. No business logic — delegates to AgentService.
|
||||
*/
|
||||
|
||||
import { Request, Response, NextFunction } from 'express';
|
||||
import { AgentService } from '../services/AgentService.js';
|
||||
import {
|
||||
createAgentSchema,
|
||||
updateAgentSchema,
|
||||
listAgentsQuerySchema,
|
||||
} from '../utils/validators.js';
|
||||
import { ValidationError, AuthorizationError } from '../utils/errors.js';
|
||||
import {
|
||||
ICreateAgentRequest,
|
||||
IUpdateAgentRequest,
|
||||
IAgentListFilters,
|
||||
} from '../types/index.js';
|
||||
|
||||
/**
|
||||
* Controller for the Agent Registry endpoints.
|
||||
* Receives AgentService via constructor injection.
|
||||
*/
|
||||
export class AgentController {
|
||||
/**
|
||||
* @param agentService - The agent registry service.
|
||||
*/
|
||||
constructor(private readonly agentService: AgentService) {}
|
||||
|
||||
/**
|
||||
* Handles POST /agents — registers a new agent.
|
||||
*
|
||||
* @param req - Express request with CreateAgentRequest body.
|
||||
* @param res - Express response.
|
||||
* @param next - Express next function.
|
||||
*/
|
||||
registerAgent = async (req: Request, res: Response, next: NextFunction): Promise<void> => {
|
||||
try {
|
||||
if (!req.user) {
|
||||
throw new AuthorizationError();
|
||||
}
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
|
||||
const { error, value } = createAgentSchema.validate(req.body, { abortEarly: false });
|
||||
if (error) {
|
||||
throw new ValidationError('Request validation failed.', {
|
||||
details: error.details.map((d) => ({ field: d.path.join('.'), reason: d.message })),
|
||||
});
|
||||
}
|
||||
|
||||
const data = value as ICreateAgentRequest;
|
||||
const ipAddress = req.ip ?? '0.0.0.0';
|
||||
const userAgent = req.headers['user-agent'] ?? 'unknown';
|
||||
|
||||
const agent = await this.agentService.registerAgent(data, ipAddress, userAgent);
|
||||
res.status(201).json(agent);
|
||||
} catch (err) {
|
||||
next(err);
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Handles GET /agents — returns a paginated list of agents.
|
||||
*
|
||||
* @param req - Express request with optional query filters.
|
||||
* @param res - Express response.
|
||||
* @param next - Express next function.
|
||||
*/
|
||||
listAgents = async (req: Request, res: Response, next: NextFunction): Promise<void> => {
|
||||
try {
|
||||
if (!req.user) {
|
||||
throw new AuthorizationError();
|
||||
}
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
|
||||
const { error, value } = listAgentsQuerySchema.validate(req.query, { abortEarly: false });
|
||||
if (error) {
|
||||
throw new ValidationError('Invalid query parameter value.', {
|
||||
details: error.details.map((d) => ({ field: d.path.join('.'), reason: d.message })),
|
||||
});
|
||||
}
|
||||
|
||||
/* eslint-disable @typescript-eslint/no-unsafe-member-access */
|
||||
const filters: IAgentListFilters = {
|
||||
page: value.page as number,
|
||||
limit: value.limit as number,
|
||||
owner: value.owner as string | undefined,
|
||||
agentType: value.agentType as IAgentListFilters['agentType'],
|
||||
status: value.status as IAgentListFilters['status'],
|
||||
};
|
||||
/* eslint-enable @typescript-eslint/no-unsafe-member-access */
|
||||
|
||||
const result = await this.agentService.listAgents(filters);
|
||||
res.status(200).json(result);
|
||||
} catch (err) {
|
||||
next(err);
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Handles GET /agents/:agentId — retrieves a single agent.
|
||||
*
|
||||
* @param req - Express request with agentId path param.
|
||||
* @param res - Express response.
|
||||
* @param next - Express next function.
|
||||
*/
|
||||
getAgentById = async (req: Request, res: Response, next: NextFunction): Promise<void> => {
|
||||
try {
|
||||
if (!req.user) {
|
||||
throw new AuthorizationError();
|
||||
}
|
||||
|
||||
const { agentId } = req.params;
|
||||
const agent = await this.agentService.getAgentById(agentId);
|
||||
res.status(200).json(agent);
|
||||
} catch (err) {
|
||||
next(err);
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Handles PATCH /agents/:agentId — partially updates an agent.
|
||||
*
|
||||
* @param req - Express request with agentId path param and UpdateAgentRequest body.
|
||||
* @param res - Express response.
|
||||
* @param next - Express next function.
|
||||
*/
|
||||
updateAgent = async (req: Request, res: Response, next: NextFunction): Promise<void> => {
|
||||
try {
|
||||
if (!req.user) {
|
||||
throw new AuthorizationError();
|
||||
}
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
|
||||
const { error, value } = updateAgentSchema.validate(req.body, { abortEarly: false });
|
||||
if (error) {
|
||||
const immutableFields = ['agentId', 'email', 'createdAt'];
|
||||
const firstImmutable = error.details.find((d) =>
|
||||
immutableFields.includes(d.path[0] as string),
|
||||
);
|
||||
if (firstImmutable) {
|
||||
throw new ValidationError(`The field '${String(firstImmutable.path[0])}' cannot be modified after registration.`, {
|
||||
field: firstImmutable.path[0],
|
||||
});
|
||||
}
|
||||
throw new ValidationError('Request validation failed.', {
|
||||
details: error.details.map((d) => ({ field: d.path.join('.'), reason: d.message })),
|
||||
});
|
||||
}
|
||||
|
||||
const { agentId } = req.params;
|
||||
const data = value as IUpdateAgentRequest;
|
||||
const ipAddress = req.ip ?? '0.0.0.0';
|
||||
const userAgent = req.headers['user-agent'] ?? 'unknown';
|
||||
|
||||
const updated = await this.agentService.updateAgent(agentId, data, ipAddress, userAgent);
|
||||
res.status(200).json(updated);
|
||||
} catch (err) {
|
||||
next(err);
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Handles DELETE /agents/:agentId — decommissions an agent.
|
||||
*
|
||||
* @param req - Express request with agentId path param.
|
||||
* @param res - Express response (204 No Content).
|
||||
* @param next - Express next function.
|
||||
*/
|
||||
decommissionAgent = async (req: Request, res: Response, next: NextFunction): Promise<void> => {
|
||||
try {
|
||||
if (!req.user) {
|
||||
throw new AuthorizationError();
|
||||
}
|
||||
|
||||
const { agentId } = req.params;
|
||||
const ipAddress = req.ip ?? '0.0.0.0';
|
||||
const userAgent = req.headers['user-agent'] ?? 'unknown';
|
||||
|
||||
await this.agentService.decommissionAgent(agentId, ipAddress, userAgent);
|
||||
res.status(204).send();
|
||||
} catch (err) {
|
||||
next(err);
|
||||
}
|
||||
};
|
||||
}
|
||||
100
src/controllers/AuditController.ts
Normal file
100
src/controllers/AuditController.ts
Normal file
@@ -0,0 +1,100 @@
|
||||
/**
|
||||
* Audit Controller for SentryAgent.ai AgentIdP.
|
||||
* HTTP handlers for GET /audit and GET /audit/:eventId.
|
||||
*/
|
||||
|
||||
import { Request, Response, NextFunction } from 'express';
|
||||
import { AuditService } from '../services/AuditService.js';
|
||||
import { auditQuerySchema } from '../utils/validators.js';
|
||||
import {
|
||||
ValidationError,
|
||||
AuthenticationError,
|
||||
InsufficientScopeError,
|
||||
} from '../utils/errors.js';
|
||||
import { IAuditListFilters } from '../types/index.js';
|
||||
|
||||
/**
|
||||
* Controller for the Audit Log endpoints.
|
||||
* Enforces `audit:read` scope on all handlers.
|
||||
*/
|
||||
export class AuditController {
|
||||
/**
|
||||
* @param auditService - The audit log service.
|
||||
*/
|
||||
constructor(private readonly auditService: AuditService) {}
|
||||
|
||||
/**
|
||||
* Handles GET /audit — queries the audit log with optional filters.
|
||||
* Requires Bearer token with `audit:read` scope.
|
||||
*
|
||||
* @param req - Express request with optional query filters.
|
||||
* @param res - Express response.
|
||||
* @param next - Express next function.
|
||||
*/
|
||||
queryAuditLog = async (req: Request, res: Response, next: NextFunction): Promise<void> => {
|
||||
try {
|
||||
if (!req.user) {
|
||||
throw new AuthenticationError();
|
||||
}
|
||||
|
||||
// Enforce audit:read scope
|
||||
const scopes = req.user.scope.split(' ');
|
||||
if (!scopes.includes('audit:read')) {
|
||||
throw new InsufficientScopeError('audit:read');
|
||||
}
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
|
||||
const { error, value } = auditQuerySchema.validate(req.query, { abortEarly: false });
|
||||
if (error) {
|
||||
throw new ValidationError('Invalid query parameter value.', {
|
||||
details: error.details.map((d) => ({ field: d.path.join('.'), reason: d.message })),
|
||||
});
|
||||
}
|
||||
|
||||
/* eslint-disable @typescript-eslint/no-unsafe-member-access */
|
||||
const filters: IAuditListFilters = {
|
||||
page: value.page as number,
|
||||
limit: value.limit as number,
|
||||
agentId: value.agentId as string | undefined,
|
||||
action: value.action as IAuditListFilters['action'],
|
||||
outcome: value.outcome as IAuditListFilters['outcome'],
|
||||
fromDate: value.fromDate as string | undefined,
|
||||
toDate: value.toDate as string | undefined,
|
||||
};
|
||||
/* eslint-enable @typescript-eslint/no-unsafe-member-access */
|
||||
|
||||
const result = await this.auditService.queryEvents(filters);
|
||||
res.status(200).json(result);
|
||||
} catch (err) {
|
||||
next(err);
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Handles GET /audit/:eventId — retrieves a single audit event.
|
||||
* Requires Bearer token with `audit:read` scope.
|
||||
*
|
||||
* @param req - Express request with eventId path param.
|
||||
* @param res - Express response.
|
||||
* @param next - Express next function.
|
||||
*/
|
||||
getAuditEventById = async (req: Request, res: Response, next: NextFunction): Promise<void> => {
|
||||
try {
|
||||
if (!req.user) {
|
||||
throw new AuthenticationError();
|
||||
}
|
||||
|
||||
// Enforce audit:read scope
|
||||
const scopes = req.user.scope.split(' ');
|
||||
if (!scopes.includes('audit:read')) {
|
||||
throw new InsufficientScopeError('audit:read');
|
||||
}
|
||||
|
||||
const { eventId } = req.params;
|
||||
const event = await this.auditService.getEventById(eventId);
|
||||
res.status(200).json(event);
|
||||
} catch (err) {
|
||||
next(err);
|
||||
}
|
||||
};
|
||||
}
|
||||
196
src/controllers/CredentialController.ts
Normal file
196
src/controllers/CredentialController.ts
Normal file
@@ -0,0 +1,196 @@
|
||||
/**
|
||||
* Credential Controller for SentryAgent.ai AgentIdP.
|
||||
* HTTP handlers for all 4 credential management endpoints.
|
||||
*/
|
||||
|
||||
import { Request, Response, NextFunction } from 'express';
|
||||
import { CredentialService } from '../services/CredentialService.js';
|
||||
import {
|
||||
generateCredentialSchema,
|
||||
listCredentialsQuerySchema,
|
||||
} from '../utils/validators.js';
|
||||
import { ValidationError, AuthorizationError, AuthenticationError } from '../utils/errors.js';
|
||||
import {
|
||||
IGenerateCredentialRequest,
|
||||
ICredentialListFilters,
|
||||
} from '../types/index.js';
|
||||
|
||||
/**
|
||||
* Controller for the Credential Management endpoints.
|
||||
*/
|
||||
export class CredentialController {
|
||||
/**
|
||||
* @param credentialService - The credential management service.
|
||||
*/
|
||||
constructor(private readonly credentialService: CredentialService) {}
|
||||
|
||||
/**
|
||||
* Handles POST /agents/:agentId/credentials — generates new credentials.
|
||||
* Returns 201 with CredentialWithSecret (secret shown once only).
|
||||
*
|
||||
* @param req - Express request.
|
||||
* @param res - Express response.
|
||||
* @param next - Express next function.
|
||||
*/
|
||||
generateCredential = async (req: Request, res: Response, next: NextFunction): Promise<void> => {
|
||||
try {
|
||||
if (!req.user) {
|
||||
throw new AuthenticationError();
|
||||
}
|
||||
|
||||
const { agentId } = req.params;
|
||||
|
||||
// An agent may only manage its own credentials (Phase 1 — no admin scope)
|
||||
if (req.user.sub !== agentId) {
|
||||
throw new AuthorizationError('You do not have permission to manage credentials for this agent.');
|
||||
}
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
|
||||
const { error, value } = generateCredentialSchema.validate(req.body ?? {}, {
|
||||
abortEarly: false,
|
||||
});
|
||||
if (error) {
|
||||
throw new ValidationError('Request validation failed.', {
|
||||
details: error.details.map((d) => ({ field: d.path.join('.'), reason: d.message })),
|
||||
});
|
||||
}
|
||||
|
||||
const data = value as IGenerateCredentialRequest;
|
||||
const ipAddress = req.ip ?? '0.0.0.0';
|
||||
const userAgent = req.headers['user-agent'] ?? 'unknown';
|
||||
|
||||
const result = await this.credentialService.generateCredential(
|
||||
agentId,
|
||||
data,
|
||||
ipAddress,
|
||||
userAgent,
|
||||
);
|
||||
res.status(201).json(result);
|
||||
} catch (err) {
|
||||
next(err);
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Handles GET /agents/:agentId/credentials — lists credentials for an agent.
|
||||
* clientSecret is never returned in list responses.
|
||||
*
|
||||
* @param req - Express request.
|
||||
* @param res - Express response.
|
||||
* @param next - Express next function.
|
||||
*/
|
||||
listCredentials = async (req: Request, res: Response, next: NextFunction): Promise<void> => {
|
||||
try {
|
||||
if (!req.user) {
|
||||
throw new AuthenticationError();
|
||||
}
|
||||
|
||||
const { agentId } = req.params;
|
||||
|
||||
if (req.user.sub !== agentId) {
|
||||
throw new AuthorizationError('You do not have permission to manage credentials for this agent.');
|
||||
}
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
|
||||
const { error, value } = listCredentialsQuerySchema.validate(req.query, {
|
||||
abortEarly: false,
|
||||
});
|
||||
if (error) {
|
||||
throw new ValidationError('Invalid query parameter value.', {
|
||||
details: error.details.map((d) => ({ field: d.path.join('.'), reason: d.message })),
|
||||
});
|
||||
}
|
||||
|
||||
/* eslint-disable @typescript-eslint/no-unsafe-member-access */
|
||||
const filters: ICredentialListFilters = {
|
||||
page: value.page as number,
|
||||
limit: value.limit as number,
|
||||
status: value.status as ICredentialListFilters['status'],
|
||||
};
|
||||
/* eslint-enable @typescript-eslint/no-unsafe-member-access */
|
||||
|
||||
const result = await this.credentialService.listCredentials(agentId, filters);
|
||||
res.status(200).json(result);
|
||||
} catch (err) {
|
||||
next(err);
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Handles POST /agents/:agentId/credentials/:credentialId/rotate — rotates a credential.
|
||||
* Returns 200 with CredentialWithSecret (new secret shown once only).
|
||||
*
|
||||
* @param req - Express request.
|
||||
* @param res - Express response.
|
||||
* @param next - Express next function.
|
||||
*/
|
||||
rotateCredential = async (req: Request, res: Response, next: NextFunction): Promise<void> => {
|
||||
try {
|
||||
if (!req.user) {
|
||||
throw new AuthenticationError();
|
||||
}
|
||||
|
||||
const { agentId, credentialId } = req.params;
|
||||
|
||||
if (req.user.sub !== agentId) {
|
||||
throw new AuthorizationError('You do not have permission to manage credentials for this agent.');
|
||||
}
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
|
||||
const { error, value } = generateCredentialSchema.validate(req.body ?? {}, {
|
||||
abortEarly: false,
|
||||
});
|
||||
if (error) {
|
||||
throw new ValidationError('Request validation failed.', {
|
||||
details: error.details.map((d) => ({ field: d.path.join('.'), reason: d.message })),
|
||||
});
|
||||
}
|
||||
|
||||
const data = value as IGenerateCredentialRequest;
|
||||
|
||||
const ipAddress = req.ip ?? '0.0.0.0';
|
||||
const userAgent = req.headers['user-agent'] ?? 'unknown';
|
||||
|
||||
const result = await this.credentialService.rotateCredential(
|
||||
agentId,
|
||||
credentialId,
|
||||
data,
|
||||
ipAddress,
|
||||
userAgent,
|
||||
);
|
||||
res.status(200).json(result);
|
||||
} catch (err) {
|
||||
next(err);
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Handles DELETE /agents/:agentId/credentials/:credentialId — revokes a credential.
|
||||
* Returns 204 No Content.
|
||||
*
|
||||
* @param req - Express request.
|
||||
* @param res - Express response.
|
||||
* @param next - Express next function.
|
||||
*/
|
||||
revokeCredential = async (req: Request, res: Response, next: NextFunction): Promise<void> => {
|
||||
try {
|
||||
if (!req.user) {
|
||||
throw new AuthenticationError();
|
||||
}
|
||||
|
||||
const { agentId, credentialId } = req.params;
|
||||
|
||||
if (req.user.sub !== agentId) {
|
||||
throw new AuthorizationError('You do not have permission to manage credentials for this agent.');
|
||||
}
|
||||
|
||||
const ipAddress = req.ip ?? '0.0.0.0';
|
||||
const userAgent = req.headers['user-agent'] ?? 'unknown';
|
||||
|
||||
await this.credentialService.revokeCredential(agentId, credentialId, ipAddress, userAgent);
|
||||
res.status(204).send();
|
||||
} catch (err) {
|
||||
next(err);
|
||||
}
|
||||
};
|
||||
}
|
||||
243
src/controllers/TokenController.ts
Normal file
243
src/controllers/TokenController.ts
Normal file
@@ -0,0 +1,243 @@
|
||||
/**
|
||||
* Token Controller for SentryAgent.ai AgentIdP.
|
||||
* HTTP handlers for POST /token, POST /token/introspect, POST /token/revoke.
|
||||
* Parses application/x-www-form-urlencoded bodies.
|
||||
* Returns OAuth2ErrorResponse for /token errors, ErrorResponse for introspect/revoke.
|
||||
*/
|
||||
|
||||
import { Request, Response, NextFunction } from 'express';
|
||||
import { OAuth2Service } from '../services/OAuth2Service.js';
|
||||
import { tokenRequestSchema, introspectRequestSchema, revokeRequestSchema } from '../utils/validators.js';
|
||||
import {
|
||||
AuthenticationError,
|
||||
AuthorizationError,
|
||||
FreeTierLimitError,
|
||||
} from '../utils/errors.js';
|
||||
import { ITokenRequest, IIntrospectRequest, IRevokeRequest, IOAuth2ErrorResponse } from '../types/index.js';
|
||||
|
||||
/**
|
||||
* Maps an error from the token issuance flow to an OAuth2ErrorResponse.
|
||||
*
|
||||
* @param err - The error to map.
|
||||
* @returns Object with error, error_description, and httpStatus.
|
||||
*/
|
||||
function mapToOAuth2Error(err: unknown): {
|
||||
body: IOAuth2ErrorResponse;
|
||||
httpStatus: number;
|
||||
} {
|
||||
if (err instanceof FreeTierLimitError) {
|
||||
return {
|
||||
body: {
|
||||
error: 'unauthorized_client',
|
||||
error_description: err.message,
|
||||
},
|
||||
httpStatus: 403,
|
||||
};
|
||||
}
|
||||
if (err instanceof AuthorizationError) {
|
||||
return {
|
||||
body: {
|
||||
error: 'unauthorized_client',
|
||||
error_description: err.message,
|
||||
},
|
||||
httpStatus: 403,
|
||||
};
|
||||
}
|
||||
if (err instanceof AuthenticationError) {
|
||||
return {
|
||||
body: {
|
||||
error: 'invalid_client',
|
||||
error_description: 'Client authentication failed. Invalid client_id or client_secret.',
|
||||
},
|
||||
httpStatus: 401,
|
||||
};
|
||||
}
|
||||
// Default: internal server error
|
||||
return {
|
||||
body: {
|
||||
error: 'invalid_request',
|
||||
error_description: 'An unexpected error occurred.',
|
||||
},
|
||||
httpStatus: 500,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Controller for the OAuth 2.0 Token endpoints.
|
||||
*/
|
||||
export class TokenController {
|
||||
/**
|
||||
* @param oauth2Service - The OAuth2 token service.
|
||||
*/
|
||||
constructor(private readonly oauth2Service: OAuth2Service) {}
|
||||
|
||||
/**
|
||||
* Handles POST /token — issues an access token via Client Credentials grant.
|
||||
* Accepts application/x-www-form-urlencoded body.
|
||||
* Returns OAuth2ErrorResponse on failure.
|
||||
*
|
||||
* @param req - Express request with form-encoded body.
|
||||
* @param res - Express response.
|
||||
* @param next - Express next function.
|
||||
*/
|
||||
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
||||
issueToken = async (req: Request, res: Response, _next: NextFunction): Promise<void> => {
|
||||
try {
|
||||
const body = req.body as ITokenRequest;
|
||||
|
||||
// Validate grant_type first
|
||||
if (!body.grant_type) {
|
||||
res.status(400).json({
|
||||
error: 'invalid_request',
|
||||
error_description: "The 'grant_type' parameter is required.",
|
||||
} as IOAuth2ErrorResponse);
|
||||
return;
|
||||
}
|
||||
|
||||
if (body.grant_type !== 'client_credentials') {
|
||||
res.status(400).json({
|
||||
error: 'unsupported_grant_type',
|
||||
error_description: "Only 'client_credentials' grant type is supported.",
|
||||
} as IOAuth2ErrorResponse);
|
||||
return;
|
||||
}
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
|
||||
const { error, value } = tokenRequestSchema.validate(body, { abortEarly: false });
|
||||
if (error) {
|
||||
res.status(400).json({
|
||||
error: 'invalid_request',
|
||||
error_description: error.details.map((d) => d.message).join('; '),
|
||||
} as IOAuth2ErrorResponse);
|
||||
return;
|
||||
}
|
||||
|
||||
const tokenBody = value as ITokenRequest;
|
||||
|
||||
// Support HTTP Basic auth fallback
|
||||
let clientId = tokenBody.client_id;
|
||||
let clientSecret = tokenBody.client_secret;
|
||||
|
||||
const authHeader = req.headers['authorization'];
|
||||
if (authHeader?.startsWith('Basic ')) {
|
||||
const base64 = authHeader.slice(6);
|
||||
const decoded = Buffer.from(base64, 'base64').toString('utf-8');
|
||||
const colonIndex = decoded.indexOf(':');
|
||||
if (colonIndex !== -1) {
|
||||
clientId = decoded.slice(0, colonIndex);
|
||||
clientSecret = decoded.slice(colonIndex + 1);
|
||||
}
|
||||
}
|
||||
|
||||
if (!clientId || !clientSecret) {
|
||||
res.status(400).json({
|
||||
error: 'invalid_request',
|
||||
error_description: "The 'client_id' and 'client_secret' parameters are required.",
|
||||
} as IOAuth2ErrorResponse);
|
||||
return;
|
||||
}
|
||||
|
||||
// Validate requested scope
|
||||
const requestedScope = tokenBody.scope ?? 'agents:read';
|
||||
const validScopes = ['agents:read', 'agents:write', 'tokens:read', 'audit:read'];
|
||||
const scopeList = requestedScope.split(' ');
|
||||
const invalidScope = scopeList.find((s) => !validScopes.includes(s));
|
||||
if (invalidScope) {
|
||||
res.status(400).json({
|
||||
error: 'invalid_scope',
|
||||
error_description: `Requested scope '${invalidScope}' is not available.`,
|
||||
} as IOAuth2ErrorResponse);
|
||||
return;
|
||||
}
|
||||
|
||||
const ipAddress = req.ip ?? '0.0.0.0';
|
||||
const userAgent = req.headers['user-agent'] ?? 'unknown';
|
||||
|
||||
const tokenResponse = await this.oauth2Service.issueToken(
|
||||
clientId,
|
||||
clientSecret,
|
||||
requestedScope,
|
||||
ipAddress,
|
||||
userAgent,
|
||||
);
|
||||
|
||||
res.setHeader('Cache-Control', 'no-store');
|
||||
res.setHeader('Pragma', 'no-cache');
|
||||
res.status(200).json(tokenResponse);
|
||||
} catch (err) {
|
||||
// Token endpoint uses OAuth2ErrorResponse format
|
||||
const mapped = mapToOAuth2Error(err);
|
||||
res.status(mapped.httpStatus).json(mapped.body);
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Handles POST /token/introspect — introspects a token per RFC 7662.
|
||||
* Requires Bearer auth with tokens:read scope.
|
||||
*
|
||||
* @param req - Express request.
|
||||
* @param res - Express response.
|
||||
* @param next - Express next function.
|
||||
*/
|
||||
introspectToken = async (req: Request, res: Response, next: NextFunction): Promise<void> => {
|
||||
try {
|
||||
if (!req.user) {
|
||||
throw new AuthenticationError();
|
||||
}
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
|
||||
const { error, value } = introspectRequestSchema.validate(req.body, { abortEarly: false });
|
||||
if (error) {
|
||||
const messages = error.details.map((d) => d.message).join('; ');
|
||||
throw new Error(messages);
|
||||
}
|
||||
|
||||
const body = value as IIntrospectRequest;
|
||||
const ipAddress = req.ip ?? '0.0.0.0';
|
||||
const userAgent = req.headers['user-agent'] ?? 'unknown';
|
||||
|
||||
const result = await this.oauth2Service.introspectToken(
|
||||
body.token,
|
||||
req.user,
|
||||
ipAddress,
|
||||
userAgent,
|
||||
);
|
||||
|
||||
res.status(200).json(result);
|
||||
} catch (err) {
|
||||
next(err);
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Handles POST /token/revoke — revokes a token per RFC 7009.
|
||||
* Requires Bearer auth.
|
||||
*
|
||||
* @param req - Express request.
|
||||
* @param res - Express response.
|
||||
* @param next - Express next function.
|
||||
*/
|
||||
revokeToken = async (req: Request, res: Response, next: NextFunction): Promise<void> => {
|
||||
try {
|
||||
if (!req.user) {
|
||||
throw new AuthenticationError();
|
||||
}
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
|
||||
const { error, value } = revokeRequestSchema.validate(req.body, { abortEarly: false });
|
||||
if (error) {
|
||||
const messages = error.details.map((d) => d.message).join('; ');
|
||||
throw new Error(messages);
|
||||
}
|
||||
|
||||
const body = value as IRevokeRequest;
|
||||
const ipAddress = req.ip ?? '0.0.0.0';
|
||||
const userAgent = req.headers['user-agent'] ?? 'unknown';
|
||||
|
||||
await this.oauth2Service.revokeToken(body.token, req.user, ipAddress, userAgent);
|
||||
res.status(200).json({});
|
||||
} catch (err) {
|
||||
next(err);
|
||||
}
|
||||
};
|
||||
}
|
||||
28
src/db/migrations/001_create_agents.sql
Normal file
28
src/db/migrations/001_create_agents.sql
Normal file
@@ -0,0 +1,28 @@
|
||||
-- Migration: 001_create_agents
|
||||
-- Creates the agents table for the Agent Registry service.
|
||||
|
||||
CREATE TABLE IF NOT EXISTS agents (
|
||||
agent_id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
email VARCHAR(255) NOT NULL UNIQUE,
|
||||
agent_type VARCHAR(32) NOT NULL,
|
||||
version VARCHAR(64) NOT NULL,
|
||||
capabilities TEXT[] NOT NULL DEFAULT '{}',
|
||||
owner VARCHAR(128) NOT NULL,
|
||||
deployment_env VARCHAR(16) NOT NULL,
|
||||
status VARCHAR(24) NOT NULL DEFAULT 'active',
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||
|
||||
CONSTRAINT agents_agent_type_check
|
||||
CHECK (agent_type IN ('screener','classifier','orchestrator','extractor','summarizer','router','monitor','custom')),
|
||||
CONSTRAINT agents_deployment_env_check
|
||||
CHECK (deployment_env IN ('development','staging','production')),
|
||||
CONSTRAINT agents_status_check
|
||||
CHECK (status IN ('active','suspended','decommissioned'))
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_agents_email ON agents (email);
|
||||
CREATE INDEX IF NOT EXISTS idx_agents_status ON agents (status);
|
||||
CREATE INDEX IF NOT EXISTS idx_agents_owner ON agents (owner);
|
||||
CREATE INDEX IF NOT EXISTS idx_agents_agent_type ON agents (agent_type);
|
||||
CREATE INDEX IF NOT EXISTS idx_agents_created_at ON agents (created_at DESC);
|
||||
19
src/db/migrations/002_create_credentials.sql
Normal file
19
src/db/migrations/002_create_credentials.sql
Normal file
@@ -0,0 +1,19 @@
|
||||
-- Migration: 002_create_credentials
|
||||
-- Creates the credentials table for the Credential Management service.
|
||||
|
||||
CREATE TABLE IF NOT EXISTS credentials (
|
||||
credential_id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
client_id UUID NOT NULL REFERENCES agents(agent_id) ON DELETE CASCADE,
|
||||
secret_hash VARCHAR(255) NOT NULL,
|
||||
status VARCHAR(16) NOT NULL DEFAULT 'active',
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||
expires_at TIMESTAMPTZ,
|
||||
revoked_at TIMESTAMPTZ,
|
||||
|
||||
CONSTRAINT credentials_status_check
|
||||
CHECK (status IN ('active','revoked'))
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_credentials_client_id ON credentials (client_id);
|
||||
CREATE INDEX IF NOT EXISTS idx_credentials_status ON credentials (status);
|
||||
CREATE INDEX IF NOT EXISTS idx_credentials_created_at ON credentials (created_at DESC);
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user