API Reference
All routes are JSON over HTTP. Base URL is CP_BASE_URL (default http://localhost:4000).
For the machine-readable spec see ../openapi.yaml — it is
normative for request/response shapes and status codes; this page explains
behaviour and the reasons behind it. For the event payloads these endpoints
emit and ingest, see events.md; for the tables they read and
write, see data-model.md.
This reference covers the control-plane API. Protocol artifacts these endpoints carry (manifests, TCTs, the handshake) are defined by the AITP RFCs — these docs link to the spec rather than restate it.
Conventions
-
Content type:
application/jsonon POST/PATCH. -
Request gate scope: request IDs, CORS, authentication and rate limiting are applied by the request gate (
src/proxy.ts), which runs on/api/*paths only. The public/.well-known/aitp-manifestURL is a rewrite that reaches its handler without passing the gate, so responses on that path carry nox-request-idor CORS headers and are never rate-limited. Request the/api/well-known/*path directly if you need those headers. -
Request ID: Every
/api/*response carriesx-request-id. Clients may pre-set the header; the CP echoes it. -
CORS: On
/api/*,Access-Control-Allow-Originis set toCORS_ORIGIN(defaults tohttp://localhost:3000). Applied per-request by the proxy, so it reads from the runtime environment. A single origin is supported. Only a browser app that calls the CP directly needs it: the UI console does not, because its BFF proxy calls the CP server-to-server (where CORS does not apply), so leave it unset or set it to whichever browser origin calls/api/*itself.OPTIONSpreflights are answered204by the proxy. -
Filter key casing: List filters are accepted in both camelCase and snake_case where noted (e.g.
runIdorrun_id). The playground emits snake_case; UI clients tend to use camelCase. Both resolve to the same column. -
UUIDs: two different rules. A token id that "must be a UUID" (
jti,root_jti,parent_jti) must be RFC 4122 versions 1–5; a v6/v7/v8 UUID is rejected as malformed. The exception is a revocation entry'sjti(POST /api/revocation/entries), which must be a lowercase, hyphenated version 4 — exactly whatcrypto.randomUUID()returns: aitp ≥ 0.14 verifiers reject a whole revocation list that carries any other form, and aitp ≥ 0.18 signers refuse to sign one. An uppercase, braced,urn:uuid:or unhyphenated spelling is rejected, never normalized: a genuine TCT'sjtiis lowercase on the wire, so such a value cannot name a real token. A path:idon/api/trust-anchors/:id(and its/jwks) and/api/webhooks/:id(and its/circuit-breakerroutes) is checked for syntax only — the canonical hyphenated8-4-4-4-12hex form, any version, either case — and anything else is400 ID_INVALIDbefore the database is touched. Ids the CP hands out are always in that form. -
Error shape:
{ "error": "human message", "code": "MACHINE_CODE" }codeis the stable signal;erroris human-facing prose and may be reworded at any time. A few responses add one machine-readable detail field alongside these two:bucketon a429(which limiter tripped),verifyCodeonPOST /api/registry/enroll(which manifest check failed),eventTypeonPOST /api/events'413(which event was too big),issuerUrlonGET /api/trust-anchors/:id/jwks'503 JWKS_NOT_CACHED, andexisting: { id }onPOSTandPATCH /api/trust-anchors'409 ALREADY_EXISTS(the anchor that already holds that(namespace, issuerUrl)). Such a field is always optional and additive — absent means "not applicable here", never "unknown".The
codevalues are this service's own. Some share a name with the AITP error-code registry, but the CP is not bound by its definitions — in particular the CP'sMANIFEST_INVALIDcovers any enrollment-time manifest rejection (bad envelope, failed signature or proof-of-possession, bad AID), which is broader than the registry's schema-validation-only meaning.HTTP status codes are conventional:
400(bad body/filter),401(auth),403(READ_ONLY_KEY, or an issuer key on anotheriss),404(not found),405(wrong method),409(conflict),413(payload too large),429(rate limited),500(internal fault),503(misconfigured / unavailable / at capacity). DELETEs do not share one success shape: some answer204 No Content, others200with a small confirmation body — so check the status per route rather than assuming one shape for "a DELETE on this API". Each DELETE's status and body are stated on that operation inopenapi.yaml(and in the route tables below).A
500never carries the shape above. Its body is whatever the framework renders, so do not parse it and do not branch on it: the status is the whole signal — retry, and if it persists, the server's operator has the detail in their logs. Routes that cannot classify a failure rethrow it on purpose, which keeps internal detail (database messages especially) out of client-facing bodies;openapi.yamlsays on each declared500why that route can reach it. Where a route is known to still answer500for an input mistake rather than a400, it is listed per route below.POST /api/eventsno longer does: an item the database cannot store (including one with a NUL or a lone UTF-16 surrogate in itsjsonbfields) is dropped and reported instead (seePOST /api/eventsbody); its500now means a database fault — in the batch INSERT or, with anIdempotency-Key, the key lookup or response re-read.Body size. Every route that takes a body reads it with a hard byte ceiling and answers
413 PAYLOAD_TOO_LARGE({"error": "request body exceeds <n> bytes", "code": "PAYLOAD_TOO_LARGE"}) when the body is over it, whether or not aContent-Lengthwas sent (a declared length over the ceiling is refused without reading the body; a chunked or understated one is counted as it is read). Server memory per request is bounded by 1 MiB: the request gate runs on every/api/*request, and Next keeps at most that much of a body for the route (experimental.proxyClientMaxBodySize). The413is sent once the client has finished sending (or the server's request timeout ends the request), so a client streaming a huge body waits for its own upload, but the server does not hold it. The ceilings: 256 KiB forPOST /api/registry/enrollandPOST /api/registry/agents(the size aitp-rs's own client accepts for a Manifest), 256 KiB forPOST /api/events(with its own per-event caps, seePOST /api/eventsbody), and 64 KiB for every admin JSON route (/api/pinned-keys,/api/revocation/entries,/api/trust-anchors,/api/trust-anchors/{id},/api/webhooks,/api/webhooks/{id}). The size check comes before the route's body and token checks, so a413is never stored against anIdempotency-Key.POST /api/eventsnow decodes a body exactly as the other routes do: a leading UTF-8 byte-order mark is ignored (it used to make the body400 BODY_INVALID).This rule is about
500specifically, not about 5xx. A503is a deliberate, classified answer and carries{error, code}:SERVER_MISCONFIGURED(gate or enrollment),SSE_CAPACITY,REVOCATION_UNAVAILABLE,JWKS_NOT_CACHED. The probes are the exception:/api/healthand/api/readyzanswer with their own diagnostic shapes ({ok, service, aid, db},{ready, reason}), not with{error, code}— treat their bodies as probe output, not as the error contract.
Authentication
| Surface | Auth |
|---|---|
| Public discovery (health, readyz, well-known, registry GET) | none |
GET /api/metrics | API_KEYS (admin) key — the counts are operator data |
POST /api/registry/enroll | none — caller submits its own signed manifest; the CP verifies the signature and issues a one-time token |
POST /api/registry/agents | Authorization: Bearer <enrollment-token> (the token returned by /enroll, single-use) |
| All other gated routes | Authorization: Bearer <API_KEY> from the API_KEYS allowlist |
| Read-only GETs (list below) | API_KEYS key, or a READ_ONLY_API_KEYS key — see Read-only keys |
A gated request with a missing or unknown key is rejected by the gate with 401 { "error": "Unauthorized", "code": "INVALID_API_KEY" } before it reaches a handler. In production, an empty API_KEYS makes every gated route return 503 SERVER_MISCONFIGURED — fail-safe against accidental exposure. In non-production, an empty API_KEYS disables auth on gated routes (a boot-time warning is logged).
API keys (per-consumer labels)
API_KEYS is a comma-separated list. Each entry is either label:key or a bare key:
API_KEYS=console-20261024:<secret>,playground:<secret>,<legacy-bare-secret>- Label. 1-40 characters matching
[A-Za-z0-9][A-Za-z0-9._-]{0,39}, a short non-secret consumer name. Only the first:splits, and only when the prefix is a valid label; otherwise the whole entry is a bare key, so existing bare keys keep working unchanged. Clients always send just the key:Authorization: Bearer <secret>, neverlabel:secret. - Bare keys are labelled
unlabelled-<n>(1-based position in the list). That label moves if the list is reordered, so label every key. - Guards (they never print a secret): a label that equals a configured key, or is an 8+ character substring of one, is refused and falls back to
unlabelled-<n>, and a duplicate key keeps its first entry (both boot warnings). A label used twice, including an explicit label equal to a bare key'sunlabelled-<n>, is fatal: the process exits 1 at boot in everyNODE_ENV, because two keys under one label cannot be told apart in the audit log. The same rule applies toISSUER_KEYS. - Audit attribution. The gate resolves the label and forwards it to the handler (
x-aitp-key-label, together with the client IP asx-aitp-client-ip; any client-supplied copy of either header is dropped). Everyadmin_audit_logrow written by a key-authenticated mutation recordsactor_id = key:<label>and, when known,details.client_ip. Agent registration via an enrollment token recordsactor_id = enrollment-token. Agent telemetry (POST /api/events->audit_events) is not labelled; its event ids still derive from a key fingerprint. - Rate limits stay per key, not per label: two keys with the same label get separate
api-keybuckets. - Rotation without downtime. Add the new key next to the old one under a new label (
console-20261024:<old>,console-20261124:<new>), move the consumer to it, then remove the old entry; the removed key answers401 INVALID_API_KEYfrom then on.scripts/handoff/rotate-api-key.shdoes this for the console key (dry run by default;--apply,--rollback). - Issuer key rotation (
ISSUER_KEYS, Revocation) is the same overlap: one AID may be bound under several labels, so addresearcher-2@<aid>=<new>next toresearcher-1@<aid>=<old>, move the agent to the new key, then remove the old entry. Each label has exactly one AID, since a label used twice is fatal at boot; both keys pull the sameissmeanwhile, and the last-pull metric shows two series for thataiduntil the old entry is removed (a redeploy, which clears its series). - Review.
scripts/audit-review.tsis a read-only report overadmin_audit_log, telemetry and the state tables for a--since/--untilrange, grouped by key label, route, source IP and outcome, with unattributed mutations flagged (npx tsx scripts/audit-review.ts --since 2026-05-23 [--known-actors key:console-*,...] [--json]; readsAUDIT_REVIEW_DATABASE_URLorDATABASE_URL, and opens adefault_transaction_read_onlysession). Not every row comes from a key: awebhook.unsubscribedrow (a receiver answered410 Gone) has actorsystem:webhook-delivery, so includesystem:*in--known-actorsto keep those rows out of the flagged list.
Read-only keys
READ_ONLY_API_KEYS is a second key list, for a consumer that only reads (the console's dashboards). Entries are label:key, comma-separated; the label is required (an unlabelled entry is skipped with a boot warning). Clients send the key the same way: Authorization: Bearer <secret>.
A read-only key opens only GET, and only on these routes (exact paths; {x} is one path segment):
/api/dashboard/overview,/api/dashboard/agents/api/sessions,/api/sessions/{id},/api/sessions/{id}/replay,/api/sessions/{id}/export/api/events/history,/api/events/stream/api/tcts,/api/delegations,/api/pinned-keys,/api/revocation/issuers/api/trust-anchors,/api/trust-anchors/{id},/api/trust-anchors/{id}/jwks/api/registry/agents,/api/registry/agents/{aid},/api/registry/agents/{aid}/manifest(already public; listed so the allowlist stays complete if they are ever gated)
On a gated route, any other method (including HEAD) or route, such as every gated write, /api/audit, /api/metrics, /api/webhooks*, /api/revocations and /api/registry/agents/{aid}/export, is refused by the gate with 403 { "error": "Forbidden: read-only key", "code": "READ_ONLY_KEY" }. Paths match exactly, never by prefix: a different casing or a trailing slash never widens the allowlist. An unknown key is still 401 INVALID_API_KEY. Public routes ignore the key's kind: they answer a read key exactly as they answer an anonymous caller.
- Never admin. A key also listed in
API_KEYSorISSUER_KEYSis skipped with a boot warning (it keeps its stronger or narrower meaning there). A label that is part of a configured key is skipped too. A label used twice, or already used by anAPI_KEYSentry, is fatal at boot. - No admin detail. Responses that carry an operator identity hide it from read keys:
addedByon/api/pinned-keysand/api/trust-anchorscomes backnull. - Own rate bucket. Each read key gets a
read-keybucket (RATE_LIMIT_READ_KEY_PER_MIN, default 1200/min), separate from the adminapi-keybuckets, so dashboard traffic cannot starve admin or ingest callers. A read key on an already-publicGETalso counts against its own bucket instead of the caller's IP bucket. - SSE sub-cap. Read-key streams on
/api/events/streamshare at mostMAX_SSE_READ_KEY_CONNECTIONS(default 80% ofMAX_SSE_CONNECTIONS) of the stream slots, so admin streams always have room; over the cap answers503. - Kind header. The gate tells the handler which kind of key passed (
x-aitp-key-kind: admin | read | issuer); a client-supplied copy is dropped. - Rotation is the same overlap as admin keys: add the new
label:keyunder a new label, move the consumer, remove the old entry.scripts/handoff/create-read-key.shcreates one (dry run by default;--apply).
ENROLLMENT_SECRET is the server-side HMAC key the CP uses to mint and verify enrollment tokens. Callers never present it directly. A production server whose value is unset or shorter than 32 characters refuses to start, so the enrollment 503 SERVER_MISCONFIGURED below is something you should only see from a non-production deployment — see operations.md.
Rate limiting
Every /api/* route except /api/health, /api/readyz, and /api/metrics (exempt only after its admin-key check passes) is rate-limited per process (in-memory buckets). The /.well-known/* rewrites bypass the gate and are not rate-limited (see Conventions). Over-limit requests return:
HTTP 429
{ "error": "rate limit exceeded", "code": "RATE_LIMITED", "bucket": "<bucket>" }with headers Retry-After, X-RateLimit-Limit, X-RateLimit-Remaining: 0, and X-RateLimit-Reset (epoch seconds). Buckets: enroll-ip (strict, per-IP, default 5/min), public-ip (per-IP, default 60/min), api-key (per-key, default 600/min). See operations.md for tuning and the CLIENT_IP_HEADER / TRUSTED_PROXY_HOPS trust model.
Idempotency
These mutating endpoints honor an optional Idempotency-Key request header:
POST /api/registry/agents, POST /api/events, POST /api/webhooks, POST /api/trust-anchors, POST /api/pinned-keys, POST /api/revocation/entries.
- A key is scoped to its endpoint. Replaying the same
(endpoint, key)returns the stored status and body without re-running the handler, and adds the response headerIdempotency-Replayed: true. - The key is not bound to the request body: a replay with the same key and a different body still returns the first response.
- Only stable outcomes are stored:
200,201,202,204,400,409,422. A401,429or5xxis not stored, so a retry with the same key runs the handler again. - Some
400 BODY_INVALIDs (a body that is not JSON — and, on the JSON-object-body POSTs/api/trust-anchors,/api/webhooks,/api/pinned-keysand/api/revocation/entries, a JSON body that is not an object) are decided before the idempotency layer and are never stored; field-level400s decided inside it are. - Two concurrent requests with the same key may both run; the first one stored wins and the other caller receives the winner's response.
- A key that is empty, longer than 255 characters, or contains control characters is rejected
400 IDEMPOTENCY_KEY_INVALID.
Stored responses are retained for IDEMPOTENCY_KEY_TTL_DAYS (default 7).
Routes
Health & readiness
| Method | Path | Auth | Purpose |
|---|---|---|---|
| GET | /api/health | public | Process up + DB ping + the CP's AID: 200 {ok, service, aid, db: "ok"}, or 503 with db: "error" if the ping fails. Stays 200 during a SIGTERM drain. Railway's deploy-time healthcheck (gates deploys only; never restarts a running service); not a safe restart-triggering liveness probe — see operations.md. |
| GET | /api/readyz | public | Readiness: not draining, and the DB answers SELECT 1 — 503 if either fails. It checks nothing else, by decision (see operations.md); in particular it does not check identity (enforced at boot in production; /api/health reports the AID). |
| GET | /api/metrics | API key (admin) | Prometheus text format. Missing/unknown key → 401 INVALID_API_KEY; not rate-limited once authenticated |
Discovery
| Method | Path | Auth | Purpose |
|---|---|---|---|
| GET | /.well-known/aitp-manifest | public | CP's own AITP manifest. Rewritten to /api/well-known/aitp-manifest. Cache-Control: max-age=3600. Its handshake_endpoint is <CP_BASE_URL>/api/aitp/handshake/hello — required by the manifest schema, but the CP is not a handshake peer and that URL answers 404 (see operations.md § Identity). |
The CP's own manifest has an 86400s TTL and is kept fresh automatically — it rebuilds itself once it nears expiry, no restart required.
Registry
| Method | Path | Auth | Purpose |
|---|---|---|---|
| POST | /api/registry/enroll | public | Verify a signed manifest, issue a one-time enrollment token |
| GET | /api/registry/agents | public | Discover agents |
| POST | /api/registry/agents | enrollment token | Self-register an agent |
| GET | /api/registry/agents/:aid | public | Fetch one agent (summary fields; Cache-Control: public, max-age=30) |
| GET | /api/registry/agents/:aid/manifest | public | Fetch the cached signed manifest (raw JSON) |
| GET | /api/registry/agents/:aid/export | API key | Bundle agent + sessions + TCTs + recent events |
| DELETE | /api/registry/agents/:aid | API key | Deregister. 200 with {aid, status: "deregistered"} — a status flip, not a row deletion. |
POST /api/registry/enroll
Body is a ManifestEnvelope — the agent's own signed manifest. Abridged
example (the signed fields version, proof_of_possession, signature and
others are omitted; see
RFC-AITP-0003 §2
and the manifest JSON Schema
for the full shape, and
RFC-AITP-0001 §5.3
for AID forms; for a complete, really-signed envelope see the spec's
known-answer signed manifest,
— the envelope is {"manifest": …} with that file's manifest member; its
other top-level keys are fixture metadata):
{
"manifest": {
"aid": "aid:pubkey:ed25519:<43-char base64url public key>",
"display_name": "researcher-1",
"handshake_endpoint": "https://agent-host:8101/aitp",
"offered_capabilities": ["demo.echo"],
"expires_at": 1790000000,
"extensions": { "namespace": "default" }
}
}The CP verifies the manifest with the aitp SDK and returns 200 { token, expiresIn, aid } — a single-use enrollment token valid for 5 minutes. Errors:
400 MANIFEST_INVALID— the body has nomanifestobject, the SDK rejected the manifest,manifest.aidis missing or does not start withaid:, or the manifest verified but holds a value the registry cannot store:display_nameover 256 characters (Unicode code points) or not a string,aidover 512 characters — or, with nodisplay_name, over 256, since the AID is then stored as the display name — a NUL (U+0000) inaid,display_nameorhandshake_endpoint, ahandshake_endpointthat is not a string,offered_capabilitiesthat is not an array of NUL-free, well-formed strings, or anexpires_atthat is not a number of Unix seconds between years 0001 and 9999 (0,nullor absent means no expiry). Rejected here so no token is minted for a manifestPOST /api/registry/agentscould never store. Checked after the expiry guard, so a manifest that fails both reportsMANIFEST_EXPIRED. The SDK enforces the manifest schema first:handshake_endpointmust behttps://anddisplay_nameat most 128 characters, so a value outside the schema answersverifyCode: "malformed". Plainhttp://onlocalhostor127.0.0.1is accepted only for local testing (AITP_INSECURE_LOCALHOST_DANGEROUS, see operations), never in production.400 MANIFEST_EXPIRED— the manifest is already pastexpires_at, or expires inside the 5-minute registration window.POST /api/registry/agentsreturns the same code for the same condition; both mean "re-issue with a longer TTL".400 BODY_INVALID— the body is not JSON.413 PAYLOAD_TOO_LARGE— the body is over 256 KiB (see Conventions).503 SERVER_MISCONFIGURED— the server has no usableENROLLMENT_SECRETand cannot issue tokens to anyone. The body carries no configuration detail.500— anything the route cannot classify as the caller's bad manifest or a known misconfiguration is rethrown (see Conventions).
A 400 means your manifest is the problem and retrying it unchanged will not help; a 503 means the server is broken and the same request is worth retrying once the deployment is fixed.
A 400 may also carry verifyCode, the aitp SDK's own machine-readable reason for rejecting the manifest:
{ "error": "signature verification failed", "code": "MANIFEST_INVALID", "verifyCode": "signature_invalid" }Branch on verifyCode (or code), never on error. The value set is owned by the SDK's verifyManifestJson — see aitp-rs Node SDK: Manifest verification (verified against aitp ^0.24.0; unknown_field — a Manifest member the spec does not define — since 0.15, and an aitp/0.2 Manifest is version_unknown since 0.17). It is a different set from verifyRevocationList's, even where spellings overlap. How the CP maps it:
verifyCodeis present if and only if the SDK rejected the manifest. It is absent when one of the CP's own guards rejected it (theaid:prefix check, the 5-minute window, the storable-values check) or when the body never reached the SDK.- SDK code
expiredmaps tocode: MANIFEST_EXPIRED; every other SDK code maps toMANIFEST_INVALID. SoMANIFEST_EXPIREDarrives withverifyCode: "expired"(already pastexpires_at) or with noverifyCode(expires inside the registration window). - An SDK code the CP does not recognise is passed through verbatim — treat anything unknown as a generic "manifest verification failed". (The CP's
/api/metricscounter folds unknown codes into anotherlabel; seesrc/lib/registry/enroll-metrics.ts.)
The
ManifestEnvelopeshape and its signature/verification are defined by the protocol — RFC-AITP-0003 (Agent Manifest) and RFC-AITP-0007 (Key Resolution). The CP caches and serves the manifest; it does not define the format. Use theaitpSDK to build and sign one.
POST /api/registry/agents
Pass the enrollment token in Authorization: Bearer <token>. The body is the same ManifestEnvelope posted to /enroll, byte-for-byte (the CP stores the raw bytes as the cached manifest).
Checks run in this order:
- Body over 256 KiB →
413 PAYLOAD_TOO_LARGE, before the token is looked at or the database is touched. - Body not JSON, JSON but not an object (
null, an array, a string, a number), or nomanifest.aid→400 BODY_INVALID. These are answered even on a misconfigured server. - No usable
ENROLLMENT_SECRET→503 SERVER_MISCONFIGURED. Your token is not the problem and is not consumed. - Token invalid →
401 TOKEN_INVALID: wrong scope, expired,subnot equal tomanifest.aid, missingjti, malformed or badly signed, or not bound to this body. The token carries anmshclaim, the SHA-256 (hex) of the exact/enrollrequest-body bytes, and this route recomputes it over its body — re-serialising the JSON (key order, whitespace) or sending a different manifest for the same AID changes the digest. This check runs before thejtiis consumed, so a mismatch does not burn the token. Hashing raw bytes here is a deliberate exception to RFC-AITP-0001 §5.4.3 (never key on a signed object's raw bytes):mshbinds a one-time token to one request body and fails closed on any difference, and is not the Manifest's identity — the registry keys agents by AID. X-Aitp-Namespaceheader longer than 128 characters (Unicode code points) or containing a NUL (U+0000) →400 BAD_REQUEST. Runs before thejtiis consumed, so fixing the header and retrying with the same token works — but send the retry with a newIdempotency-Key(or none): a400is stored against the key, so a retry with the same key replays the stored400without re-running the handler (see Idempotency).- A manifest value the
agentsrow cannot store →400 BODY_INVALID: the same rules/enrollapplies before minting a token (display_name— or, when absent,aid— over 256 characters,aidover 512, a NUL inaid/display_name/handshake_endpoint, a non-stringhandshake_endpoint,offered_capabilitiesthat is not an array of NUL-free, well-formed strings, or anexpires_atoutside Unix seconds for years 0001–9999). Since the token is bound to the exact/enrollbody, only a token minted before/enrollapplied these rules can reach this; it runs before thejtiis consumed, so it does not burn the token — but the manifest is signed and token-bound, so the fix is a corrected manifest and a fresh enrollment. manifest.versionis notaitp/0.3→400 MANIFEST_INVALID(noverifyCode)./enrollalready rejects such a Manifest asversion_unknown, so only a token minted before the CP's aitp/0.3 cutover can reach this; it runs before thejtiis consumed. Re-enroll with a current SDK.manifest.expires_at(Unix seconds) less than 5 minutes in the future →400 MANIFEST_EXPIRED.manifest.extensions.namespacepresent but not a string, or (when noX-Aitp-Namespaceheader is sent) longer than 128 characters or containing a NUL →400 BODY_INVALID.- The token's
jtiis consumed and the agent is stored in one transaction. A second presentation of a token whose registration committed returns401 TOKEN_REPLAYED. If the store fails (a database fault, answered as a framework500), the consume is rolled back with it, so the same token and body can be retried within the token's 5-minute life. Of two simultaneous registrations with one token, exactly one succeeds; the other getsTOKEN_REPLAYED.
Every 400 above runs before the jti is consumed, so none of them spends the token. The token is bound to the exact body bytes (step 3), though, so a fix that changes the manifest (steps 5–8) needs a fresh /enroll; only the header fix in step 4 can reuse the token. /enroll applies the same 5-minute guard first to spare you the round trip, but the two routes read their own clocks, so a manifest near the boundary can pass enroll and fail here; and they disagree on expires_at: 0 (enroll rejects it, this route treats it as absent).
Namespace is taken from the X-Aitp-Namespace header (wins) or manifest.extensions.namespace, defaulting to default.
On a 503, reusing the same token later only works within its 5-minute lifetime and only if the operator restored the secret rather than rotating it; a new ENROLLMENT_SECRET invalidates every token minted under the old one (401 TOKEN_INVALID), so re-enroll. In production a replica with an unusable secret exits at boot, so this 503 is a non-production condition.
Response 201: { "aid": "...", "displayName": "...", "registeredAt": "..." }. Emits an agent.registered audit event.
GET /api/registry/agents
Filters: ?capability=, ?aid=, ?displayName= (or display_name), ?namespace=, ?include_manifest=true, ?limit= (default 200, max 1000; an empty ?limit= is clamped to 1), ?offset=. A NUL (U+0000) in any of the text filters returns 400 BAD_REQUEST.
Without
?namespace=, results span all namespaces by design. Namespaces are a control-plane scoping convention, not a protocol boundary — initial peer discovery is operational and non-normative in AITP. The CP enforces no implicit tenant isolation, so scope your queries with?namespace=if you need it.
Response { "agents": [...] }. Each record:
{
"aid": "aid:pubkey:ed25519:<43-char base64url public key>",
"displayName": "researcher-1",
"handshakeEndpoint": "https://agent-host:8101/aitp",
"offeredCaps": ["demo.echo"],
"status": "active",
"namespace": "default",
"registeredAt": "...",
"lastEnrolledAt": "...",
"lastSeenAt": "...",
"manifestUrl": "/api/registry/agents/<aid>/manifest",
"agentManifestHint": "https://agent-host:8101/.well-known/aitp-manifest",
"manifestJson": "{...}"
}manifestUrl is the CP's always-available cached copy. agentManifestHint is a best-effort guess at the agent's own .well-known URL (may 404 behind a gateway). manifestJson is present only when include_manifest=true.
GET /api/registry/agents/:aid returns a subset of these fields — aid, displayName, handshakeEndpoint, offeredCaps, status, registeredAt, lastSeenAt, manifestUrl — with Cache-Control: public, max-age=30. Use the list route with ?aid= if you need namespace, lastEnrolledAt, agentManifestHint or manifestJson.
Sessions
| Method | Path | Auth | Purpose |
|---|---|---|---|
| GET | /api/sessions | API key | List handshake sessions, newest first by creation time (ties by sessionId). ?limit= (default 200, max 1000; non-numeric → default, out-of-range clamped; an empty ?limit= is clamped to 1) and ?offset= (default 0; negative or non-numeric → 0). Filters: ?status= (exact match, not validated — an unknown value returns an empty list), ?runId= (or run_id), ?aid= (either side); a NUL character in any filter → 400 BAD_REQUEST |
| GET | /api/sessions/:sessionId | API key | Fetch one session + its events: { session, events } |
| GET | /api/sessions/:sessionId/export | API key | Bundle session + projected TCTs + events. ?format=json|jsonl |
| GET | /api/sessions/:sessionId/replay | API key | Ordered event stream for one session: { sessionId, count, events }. Filters: ?since=, ?until=, ?limit= (default 1000, max 10000). Malformed since/until → 400 BAD_REQUEST. An unknown sessionId is a 200 with no events, not a 404. |
Sessions are projected from events — the CP does not see handshake traffic. See events.md.
Events
| Method | Path | Auth | Purpose |
|---|---|---|---|
| POST | /api/events | API key (open in dev) | Ingest a batch of audit events |
| GET | /api/events/history | API key | Query persisted events. Filters: ?type=, ?aid=, ?sessionId= (or session_id), ?runId= (or run_id), ?since=, ?until=, ?limit= (default 100, max 1000), ?offset=. A NUL in a text filter → 400 FILTER_INVALID |
| GET | /api/events/stream | API key | Server-Sent Events (live + backlog). Filters: ?type=, ?runId= (or run_id), ?aid= |
POST /api/events body
Accepts either a bare array or { "events": [...] }. Each event:
{
"type": "handshake.complete",
"ts": "2026-05-25T12:00:00Z",
"aidA": "aid:pubkey:ed25519:<...>",
"aidB": "aid:pubkey:ed25519:<...>",
"sessionId": "uuid-or-base64url",
"runId": "run-123",
"grants": ["demo.echo"],
"payload": { "...": "..." },
"source": "playground"
}No field is required. Snake_case and playground aliases are accepted, defaults are applied (e.g. type → "unknown", source → "playground", a missing payload → the whole event object), and items that are not JSON objects are silently dropped — see events.md for the full normalization. Unknown event types are stored as-is (never 4xx); only a known set drives projections and webhooks.
The CP assigns every stored event's id (a client-supplied id is never used as the id). An event with a valid ts gets an id derived from its content and the caller's API key, so the same producer re-sending the same event — a retry, or a superset batch that repeats earlier events — is recognised as a duplicate (so give genuinely repeated, otherwise identical events a distinguishing field): stored once, streamed once, delivered to webhooks once. An event without a valid ts gets a random id and is stored again on every send. Recipe, caveats (at-most-once fan-out if the CP dies between the insert and the fan-out; a re-send after retention deleted the row is stored again) in events.md.
Response 200: { "ingested": <n>, "dropped": <m>, "errors": [...], "inserted": <i>, "duplicates": <d> }. All five fields are always present.
ingested— the items that passed per-item validation and were handed to the event store (non-object items and dropped items are not counted). Alwaysinserted + duplicates.inserted— of those, the events newly stored by this request. Only these are streamed over SSE and sent to webhooks.duplicates— of those, the events that were already stored (same content-derived id) or repeated earlier in the same batch. They are still run through the session/TCT projections (idempotently), but not stored, streamed or delivered again.dropped— object items refused by per-item validation (below). The rest of the batch is still ingested; a dropped item is not stored, streamed, projected or sent to webhooks. Non-object items are skipped silently and are not counted here.errors— one{ "index", "field", "reason" }per dropped item, at most 20 (droppedis the full count).indexis the item's position in the array you sent (counting non-object items);fieldnames the normalized field (type,aidA,aidB,sessionId,runId,source,grants,payload— e.g. an over-longsession_idreportssessionId);reasonis human prose and never echoes your data.
Per-item validation (after normalization) drops an item when:
typeorsourceis over 128 characters,aidA/aidBover 512, orsessionId/runIdover 255 (counted in Unicode code points, the unit the columns use);- any of those text fields, any
grantsentry, or any key or string value anywhere inpayloadcontains a NUL character (U+0000) — Postgres cannot store it; - any
grantsentry, or any key or string value anywhere inpayload, contains a lone (unpaired) UTF-16 surrogate, e.g. the JSON escape"\ud800"with no low surrogate after it —payloadandgrantsarejsonb, which rejects it (reason:"<field> contains a lone UTF-16 surrogate"). Well-formed surrogate pairs (emoji and other astral characters) are fine. Whenpayloadis absent the whole event is the payload, so this then covers every field of the event. (In the text columns of an item that has its ownpayload, a lone surrogate is not a drop: it is stored as U+FFFD.) payloadis nested more than 64 levels deep (reasonsays "too deep").
A ts that is out of range (a number beyond ±8.64×10¹⁵ ms, or one that renders outside years 0001–9999) is not a drop: like an unparseable ts, it is replaced with the ingest time. Dropped items are logged server-side as counts only and counted in the events_dropped_total metric (operations.md). With an Idempotency-Key, a replay returns the same dropped/errors report and does not count the drops in events_dropped_total again (the handler does not re-run).
Limits: a single batch must be ≤ 256 KiB on the wire and contain ≤ 500 events, and each event's payload must be ≤ 65,536 characters when serialized with JSON.stringify (UTF-16 code units, not bytes; when payload is absent the whole event is measured). Over-cap requests return 413 PAYLOAD_TOO_LARGE (the offending eventType is included when a single event is too big). Split large batches into multiple requests.
A body that is not JSON is 400 BODY_INVALID. A body whose events member is present and not null but is not an array (a string, number, boolean or object — including one with a numeric length) is 400 BODY_INVALID ("events must be an array"), checked before the 500-event cap; like any 400 it is stored against an Idempotency-Key, so resend the corrected body with a new key. A JSON body that is neither an array nor an object with an events member (or has "events": null) ingests nothing and answers 200 { "ingested": 0, "dropped": 0, "errors": [], "inserted": 0, "duplicates": 0 }. The 413 caps above stay whole-batch: a batch with one over-cap payload is refused entirely, even if that item would also have been dropped.
GET /api/events/history response
{ "events": [...], "count": <n> }. An unparseable since or until, or a NUL (U+0000) in type, aid, sessionId or runId, returns 400 FILTER_INVALID. A non-numeric limit or offset falls back to the default rather than erroring, and limit is clamped to 1–1000. An empty ?limit= is not "malformed": it reads as 0 and is clamped to 1.
GET /api/events/stream
text/event-stream, with Cache-Control: no-cache, no-transform and X-Accel-Buffering: no. Each event is delivered as a data: <json>\n\n frame.
- Backlog: on connect the stream replays the process's last 100 events, then applies your filters to them, so a filtered stream may replay fewer than 100. (
MAX_AUDIT_EVENTS_MEMORY, default 500, sizes the bus's total in-memory retention — not the per-subscriber replay.) It then streams live events. - No resume: frames carry no
id:line, soLast-Event-IDresume is not possible; a reconnect replays the backlog again. UseGET /api/events/historyto fill gaps. - Per replica: the bus and backlog are in-memory and per process. Behind several replicas, a stream only sees events ingested by the replica it is connected to.
- Auth from browsers: the route is gated, and a browser
EventSourcecannot send anAuthorizationheader — proxy the stream server-side, or use a client that can set headers. - Capacity: returns
503 SSE_CAPACITYwithRetry-After: 30onceMAX_SSE_CONNECTIONS(default 500) streams are already open on this process — back off and retry.
The first bytes are a prelude, not an event. Every accepted connection begins with a single chunk containing a retry: reconnect hint and a : connected comment frame:
retry: 15000
: connected
Clients must tolerate comment frames (any line beginning :) and must not assume the first frame carries data — EventSource and every conformant SSE parser already discard comments. The prelude is sent before the backlog replay and is what puts the HTTP status line and response headers on the wire; without it a quiet control plane would send no headers until the first heartbeat. The retry: value tracks SSE_HEARTBEAT_MS (default 15000); the same interval governs the periodic : heartbeat keepalive frames.
Audit
| Method | Path | Auth | Purpose |
|---|---|---|---|
| GET | /api/audit | API key | Admin audit log (who did what when), newest first. Filters: ?limit= (default 100, max 1000; an empty ?limit= is clamped to 1), ?offset=. Response { entries, count }. Entry details never carry a webhook secret: a webhook.update that sets it records secretRotated: true. |
This is the admin action log (registrations, revocations, webhook changes), distinct from the telemetry event store served by /api/events/history.
Revocation
The CP is a revocation registry and relay, not a revocation authority. Under RFC-AITP-0008 §1.5 a revocation list is valid only when it is signed by the issuer of the tokens it names, and a verifier discards a list signed by anyone else (spec fixture rev-011). So operators record entries here, each issuing agent pulls its own, signs them with its own key and serves the list at its Manifest's revocation endpoint. The CP signs nothing. (Until CP1.1 it served a CP-signed aggregate at /.well-known/aitp-revocation-list; that path now answers 404.)
sequenceDiagram
participant Op as Operator
participant CP as Control plane
participant B as Issuing agent B
participant V as Verifier
Op->>CP: POST /api/revocation/entries {jti}
Note over CP: iss resolved from the TCT projection
B->>CP: GET /api/revocations?iss=B (B's issuer key)
CP-->>B: {iss, entries}
Note over B: signRevocationList(entries) with B's own key
V->>B: fetch B's revocation list
Note over V: verifyRevocationList(list, B) then verifyTct(..., revokedJtis)| Method | Path | Auth | Purpose |
|---|---|---|---|
| POST | /api/revocation/entries | API key | Record a revoked JTI against its issuer |
| GET | /api/revocations?iss=<aid> | API key, or that issuer's issuer key | That issuer's entries, ready for it to sign |
| GET | /api/revocation/issuers | API key | Issuers that have entries, with counts |
POST /api/revocation/entries
{ "jti": "uuid", "reason": "operator action", "revokedAt": "2026-06-01T00:00:00Z", "iss": "aid:pubkey:..." }jti must be a lowercase hyphenated UUID v4 or 400 JTI_INVALID ("jti must be a lowercase UUID v4"); see the UUID rule. A delegation's synthetic id from /api/delegations is a v5 UUID and cannot be revoked this way. reason is optional, a string of ≤ 500 characters. revokedAt is an optional date string (ISO-8601 recommended) defaulting to now; a non-string revokedAt is ignored and treated as absent. Other invalid input — including a body that is not JSON or is JSON but not an object (null, an array, a string, a number) — → 400 BODY_INVALID. A body over 64 KiB → 413 PAYLOAD_TOO_LARGE. Response 201 { jti, revokedAt, reason, iss }.
iss — who the entry is relayed to. The CP takes it from what it already knows, in order: the issued_tcts row for this jti (from the agents' tct.issued reports), then an existing entry for this jti. An explicit iss is needed only when neither knows the token, and must be an AID (aid:...) or 400 ISS_INVALID. An explicit iss that contradicts what the CP knows is 409 ISS_MISMATCH, as is a stored entry whose iss disagrees with the TCT record (the stored value is what is relayed, and is never overwritten). A recorded issuer that is not an AID counts as unknown. No iss known and none given is 400 ISS_REQUIRED: an entry with no issuer would be stored and enforced nowhere, so it is refused.
Recording a revocation also flips the matching issued_tcts.revoked flag, cascades to descendant delegations, and emits a tct.revoked event (and webhook) whose payload carries iss.
Re-revoking a jti that already has an entry is not an error: the stored entry keeps its original revoked_at and reason, but the route still answers 201 echoing the values from this request, and emits another tct.revoked event and webhook delivery. Re-posting with iss is also how an operator attributes an entry that migration 0009 could not (see operations.md): an entry's iss is filled when it is empty, never changed.
Two further 400 BODY_INVALID rules exist because the values are storable by neither the revocation table nor the audit event the route emits: revokedAt must fall inside a bounded date range (as a UTC instant — the epoch is the lower bound, because a signed list carries revoked_at as seconds since it), and reason must not contain a NUL (U+0000) (other control characters are fine). The exact bounds and their reasons are in openapi.yaml, RevocationEntryRequest.
A genuine database fault is a framework 500 with no {error, code} body, per Conventions. If you use Idempotency-Key here, note that the BODY_INVALID for a non-JSON or non-object body is never stored, while the field-level 400s are.
GET /api/revocations?iss=<aid>
{
"iss": "aid:pubkey:...",
"entries": [{ "jti": "uuid", "revoked_at": 1782907200, "reason": "operator action" }]
}Every entry recorded for iss, oldest revoked_at first. This is the full set, not a delta, so each pull replaces the last. Entries are in the RFC-AITP-0008 shape: revoked_at in epoch seconds, reason only when set. The issuer passes them to its SDK's signRevocationList / sign_revocation_list (revoked_at maps to the Node binding's revokedAt). Always Cache-Control: no-store, and nothing is cached server-side, so a new entry is visible on the next pull from any replica.
400 ISS_INVALID—issmissing or not an AID.403 ISSUER_MISMATCH— an issuer key asked for anissother than its own.503 REVOCATION_UNAVAILABLE(Cache-Control: no-store,Retry-After: 30) — the database cannot be read. It never answers an empty200in that case: that would tell the issuer nothing is revoked, and it would sign and publish that. On a503the issuer should keep serving its last list.
Verifiers never talk to the CP for revocation. They fetch the issuer's list, verify it with verifyRevocationList pinning the TCT's issuer as the expected issuer, and branch on the thrown error's .code — see aitp-rs Node SDK: Revocation lists. Freshness and what to do when a list goes stale are the verifier's policy: RFC-AITP-0008 §3.1 (Modes) and §3.2 (Staleness).
GET /api/revocation/issuers
{ "issuers": [{ "iss": "aid:pubkey:...", "entries": 2 }], "limit": 100, "offset": 0 }Every issuer with at least one entry, and how many it has, ordered by iss, so an admin view can skip issuers with nothing to relay instead of pulling /api/revocations once per known issuer. Paged with ?limit= (default 100, clamped to 1-1000) and ?offset= (default 0). There is no total: a page shorter than limit is the last. An issuer that gets its first entry between two page requests shifts the later pages by one, so a full read is exact only from a single page. An entry with no iss is relayed to nobody and is not counted. Admin keys only: an issuer key is 401 here. Cache-Control: no-store.
Issuer keys
An issuing agent pulls with its own key from ISSUER_KEYS (label@aid=key, comma-separated), not an admin key. An issuer key opens only GET /api/revocations, and only for iss equal to the AID it is bound to. Anywhere else it is an unknown key (401 INVALID_API_KEY). A key listed in both ISSUER_KEYS and API_KEYS is refused at boot with a warning, so an issuer key never carries admin rights. Its label and bound AID name the agent's series (issuer and aid) in aitp_control_plane_revocation_last_pull_timestamp_seconds (operations.md). A bearer key rather than a signed request because the aitp SDK has no request-signing primitive yet; that is the trigger to replace it.
Webhooks
| Method | Path | Auth | Purpose |
|---|---|---|---|
| GET | /api/webhooks | API key | List subscriptions (the secret is never included) |
| POST | /api/webhooks | API key | Create |
| PATCH | /api/webhooks/:id | API key | Update any of url, events, secret, active |
| DELETE | /api/webhooks/:id | API key | Remove (200 with {id, deleted: true}, not 204) |
| GET | /api/webhooks/:id/circuit-breaker | API key | Current breaker state snapshot |
| POST | /api/webhooks/:id/circuit-breaker/reset | API key | Manually re-arm a breaker stuck open |
POST /api/webhooks body
{ "url": "https://hooks.example.com/aitp", "events": ["tct.revoked"], "secret": "shared-secret", "active": true }url must be http(s) — https only in production — and pass the SSRF guard (private/loopback/link-local ranges and hosts outside WEBHOOK_URL_ALLOWLIST are rejected 400 URL_NOT_ALLOWED); a non-string url is 400 BODY_INVALID. An empty/omitted events array means all deliverable event types. Only a fixed set of event types is deliverable — see events.md. If secret is omitted the server generates one. The 201 response is the only place the secret is returned ({ id, url, events, secret, active, createdAt }); store it then.
400 BODY_INVALID on POST and PATCH when: the body is not JSON or is JSON but not an object (null, an array, a string, a number); secret is longer than 255 characters (Unicode code points); or url, secret or any events entry contains a NUL (U+0000), or an events entry holds a lone UTF-16 surrogate (e.g. "\ud800", which jsonb cannot store). These are checked before the SSRF guard.
PATCH /api/webhooks/:id applies only the fields present (a new url passes the same guard) and answers 200 { id, url, events, active, updatedAt }. On PATCH and DELETE a :id that is not a UUID is 400 ID_INVALID (see Conventions); an unknown UUID is 404 NOT_FOUND. A PATCH that sets secret is recorded in the admin audit log as secretRotated: true — the secret itself is never written there. (Releases before this one did write it; the 0008 migration scrubs those rows, but rotate any webhook secret that was ever set via PATCH, since it may already have been read through GET /api/audit.)
Deliveries are POSTed with body { deliveryId, eventType, payload, enqueuedAt } (payload is the full event record) and headers X-Aitp-Signature: sha256=<hex> — an HMAC-SHA256 over the exact body bytes using the webhook's secret — plus X-Aitp-Event (the event type) and X-Aitp-Delivery (the delivery id). The body is fixed at enqueue time, so every retry of a delivery carries the same bytes and signature. Each attempt also carries X-Aitp-Timestamp (Unix seconds as a decimal integer string, set when that attempt is sent) and X-Aitp-Timestamp-Signature: sha256=<hex>, an HMAC-SHA256 over <X-Aitp-Timestamp>.<body bytes> under the same secret. A receiver bounding replay must require the timestamped signature (accept only ^[0-9]+$ timestamps) and check X-Aitp-Timestamp against its window, rather than enqueuedAt: a retry legitimately carries an enqueuedAt older than any short window, and a receiver that still accepts X-Aitp-Signature alone leaves replay unbounded. A 410 Gone response unsubscribes: the CP disables the webhook (active: false), fails its pending deliveries and audits webhook.unsubscribed (see events.md). Any other non-2xx, 404 included, is a failure. Retries follow WEBHOOK_RETRY_ATTEMPTS (default 3) with exponential backoff; a circuit breaker trips a repeatedly-failing endpoint open (thresholds configurable via WEBHOOK_BREAKER_FAILURE_THRESHOLD / WEBHOOK_BREAKER_RESET_MS — see operations.md).
Circuit-breaker state is held per process: each replica has its own breaker per webhook, and the snapshot and reset routes see only the replica that served them. Both routes answer 400 ID_INVALID for a :id that is not a UUID. Any UUID is accepted otherwise — an unknown id returns a fresh closed snapshot rather than 404, and a reset of an unknown id still writes an admin audit entry.
Dashboard JSON
| Method | Path | Auth | Purpose |
|---|---|---|---|
| GET | /api/dashboard/overview | API key | Aggregate counts + recent activity. ?range=1h|24h|7d|30d (default 24h; an unknown value falls back to 24h) |
| GET | /api/dashboard/agents | API key | Per-agent metrics: { agents } |
TCTs (observed)
The CP observes TCTs from agent-reported tct.issued and handshake.complete events. It never issues a TCT.
| Method | Path | Auth | Purpose |
|---|---|---|---|
| GET | /api/tcts | API key | Query observed TCTs. Filters: ?issuer=, ?subject=, ?audience=, ?capability=, ?sessionId=, ?active=true, ?limit= (default 100, max 1000), ?offset=. A NUL in a text filter → 400 BAD_REQUEST |
By default the projection records reported claims without checking any signature. With OBSERVED_ARTIFACT_VERIFICATION=strict, reports whose signed token does not verify (including claims-only reports) are not projected, so they never appear in /api/tcts or /api/delegations (a delegation verifies only when its delegator is enrolled here — see operations.md); warn projects every report and logs a warning only for one that carries a signed token which fails to verify — a claims-only report is projected without a log line. See operations.md.
Delegation chains
| Method | Path | Auth | Purpose |
|---|---|---|---|
| GET | /api/delegations | API key | Query delegations |
?root_jti=<uuid> (or rootJti) returns the whole descendant tree rooted at that JTI via a recursive CTE, oldest first; when it is present every other filter, limit and offset are ignored. Otherwise: ?parent_jti= (or parentJti), ?delegator=, ?delegatee=, ?active=true, ?limit= (default 100, max 1000), ?offset=, newest first. A malformed root_jti/parent_jti (not a UUID), or a NUL (U+0000) in delegator/delegatee, returns 400 BAD_REQUEST.
Trust anchors (OIDC)
| Method | Path | Auth | Purpose |
|---|---|---|---|
| GET | /api/trust-anchors | API key | List. ?namespace= filter (a NUL in it is 400 BAD_REQUEST) |
| POST | /api/trust-anchors | API key | Create. Body: { issuerUrl, namespace?, jwksUrl?, label? }. 400 BODY_INVALID if the body is not a JSON object, issuerUrl or a non-empty jwksUrl is not an http(s):// string, or a field is not storable (limits below). 409 ALREADY_EXISTS (with existing: { id }) if (namespace, issuerUrl) exists. |
| GET | /api/trust-anchors/:id | API key | Fetch one (without addedBy) |
| PATCH | /api/trust-anchors/:id | API key | Update issuerUrl / jwksUrl / label (without addedBy in the response; namespace is not patchable; a field of the wrong type is ignored). 400 BODY_INVALID if the body is not a JSON object, a string issuerUrl or a non-empty jwksUrl is not an http(s):// URL, or a field is not storable (limits below). 409 ALREADY_EXISTS (with existing: { id }) if the new issuerUrl is already used by another anchor in this anchor's namespace; nothing is changed. Clears the cached JWKS when issuerUrl or jwksUrl actually changes (see JWKS route below). |
| DELETE | /api/trust-anchors/:id | API key | Remove (204) |
| GET | /api/trust-anchors/:id/jwks | API key | The CP-cached JWKS for the anchor, for agents that cannot reach the issuer |
On every /api/trust-anchors/:id route (including /jwks), an :id that is not a UUID is 400 ID_INVALID (see Conventions); an unknown UUID is 404 NOT_FOUND.
Field limits (POST and PATCH, 400 BODY_INVALID when exceeded): namespace and label at most 128 characters (Unicode code points); issuerUrl at most 2048 characters and 2048 UTF-8 bytes (it sits in a unique index whose row limit is in bytes); jwksUrl at most 2048 characters; none may contain a NUL (U+0000). An empty-string jwksUrl means "no explicit JWKS URL" and is stored as null (on PATCH it clears the field, like null).
JWKS route. The cache is filled by a background refresher (see operations.md), never by this request.
200returns the cached JWKS withCache-Control: max-age=300andX-JWKS-Cached-At(the cache time).503 JWKS_NOT_CACHED(body includesissuerUrl; headersRetry-After: 60,Cache-Control: no-store) until the refresher has fetched the keyset once. If it never succeeds — the issuer is unreachable,JWKS_REFRESH_ENABLED=false, or the URL ishttp://in production — this persists.- After one successful fetch, later failures do not clear the cache: the route keeps serving the last good keyset with
200. CheckX-JWKS-Cached-Atto judge its age. - A
PATCHthat actually changesissuerUrlorjwksUrlclears the cache (jwks_cacheandjwks_cached_at) in the same statement, so the old issuer's keys are never served for the new URLs. The route then answers503 JWKS_NOT_CACHEDuntil the refresher's next pass fetches the new keyset — up toJWKS_REFRESH_INTERVAL_MS(default 15 min), longer if that fetch fails. The PATCH does not trigger a fetch itself. APATCHthat only changeslabel, or resends the current URLs unchanged (as the ui-console does on every edit;""andnullare the samejwksUrl), keeps the cache. A refresh that was already in flight when the URLs changed discards the keyset it fetched for the old URLs. 400 ID_INVALID(not a UUID — syntax only, any version),404 NOT_FOUND.
Pinned keys
| Method | Path | Auth | Purpose |
|---|---|---|---|
| GET | /api/pinned-keys | API key | List. ?namespace= filter, or ?aid=&namespace= for a single-row lookup (namespace defaults to default). A NUL in either → 400 BAD_REQUEST. |
| POST | /api/pinned-keys | API key | Upsert. Body: { aid, pubkey, namespace?, label?, expiresAt? }. 201 whether the row was created or replaced. |
| DELETE | /api/pinned-keys?namespace=&aid= | API key | Remove (204). Missing aid, or a NUL in aid/namespace → 400 BAD_REQUEST. |
POST returns 400 BODY_INVALID when the body is not JSON or is JSON but not an object (null, an array, a string, a number); aid is missing, empty, longer than 512 characters or contains a NUL; namespace is longer than 128 characters or contains a NUL; pubkey is not a 43-character base64url Ed25519 key; label is neither a string nor null, or is over 128 characters or contains a NUL; or expiresAt is neither a string nor null, or is unparseable or outside the writable timestamptz window (exact bounds in openapi.yaml; a past instant is allowed and retires the pin). Lengths count Unicode code points; other control characters (newline, tab) are allowed. Behaviour to be aware of:
- The upsert replaces
pubkey,labelandexpiresAton an existing(namespace, aid): sendingnullforlabelorexpiresAtclears it, and so does omitting it (full-replace semantics, intended). - A
namespacethat is not a string, or is empty, meansdefault.
Headers
| Header | Direction | Purpose |
|---|---|---|
Authorization | request | Bearer <api-key> (gated routes) or Bearer <enrollment-token> (POST /api/registry/agents) |
Idempotency-Key | request | Dedupe a retried mutation (see Idempotency) |
X-Aitp-Namespace | request | Namespace override on registration (POST /api/registry/agents) |
x-request-id | both | Propagated for log correlation (/api/* only) |
Idempotency-Replayed | response | true when the response is a stored idempotent replay |
Retry-After, X-RateLimit-* | response | Present on 429 responses (Retry-After also on some 503s) |
X-JWKS-Cached-At | response | Cache time of the JWKS served by GET /api/trust-anchors/:id/jwks |
X-Aitp-Signature | webhook delivery | sha256=<hex> HMAC-SHA256 of the body bytes |
X-Aitp-Timestamp | webhook delivery | Unix seconds at which this attempt was sent (changes per retry) |
X-Aitp-Timestamp-Signature | webhook delivery | sha256=<hex> HMAC-SHA256 of <X-Aitp-Timestamp>.<body bytes> |
X-Aitp-Event | webhook delivery | Event type of the delivery |
X-Aitp-Delivery | webhook delivery | Delivery id (stable across retries) |
Lifecycle
GET /api/readyzreturns503with{ "ready": false, "reason": "shutting_down" }once the process has received SIGTERM, so a load balancer can drain the pod before it exits.GET /api/healthcontinues to return200during the drain window. Seeoperations.md.