@agent-custody/receipts 0.14.0 → 0.16.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (60) hide show
  1. package/README.md +48 -21
  2. package/dist/acs.d.ts +47 -0
  3. package/dist/acs.js +235 -0
  4. package/dist/addresses.d.ts +6 -0
  5. package/dist/addresses.js +90 -0
  6. package/dist/check.d.ts +10 -0
  7. package/dist/check.js +179 -3
  8. package/dist/cli.js +147 -12
  9. package/dist/config.d.ts +198 -1
  10. package/dist/config.js +154 -3
  11. package/dist/console.js +16 -7
  12. package/dist/deny-report.js +1 -1
  13. package/dist/door.d.ts +203 -0
  14. package/dist/door.js +712 -0
  15. package/dist/egress-draft.d.ts +43 -0
  16. package/dist/egress-draft.js +153 -0
  17. package/dist/egress.d.ts +116 -0
  18. package/dist/egress.js +585 -0
  19. package/dist/export.d.ts +39 -0
  20. package/dist/export.js +95 -0
  21. package/dist/gateway.js +53 -21
  22. package/dist/index.d.ts +15 -0
  23. package/dist/index.js +10 -0
  24. package/dist/issue.js +5 -65
  25. package/dist/lock.d.ts +12 -0
  26. package/dist/lock.js +124 -0
  27. package/dist/log.d.ts +11 -5
  28. package/dist/log.js +63 -43
  29. package/dist/opa-server.d.ts +34 -0
  30. package/dist/opa-server.js +93 -0
  31. package/dist/policy-rego.d.ts +30 -0
  32. package/dist/policy-rego.js +116 -0
  33. package/dist/portal.js +147 -41
  34. package/dist/pr-summary.d.ts +25 -0
  35. package/dist/pr-summary.js +87 -0
  36. package/dist/receipt.d.ts +8 -2
  37. package/dist/retention.d.ts +1 -1
  38. package/dist/retention.js +14 -4
  39. package/dist/sdk/index.js +10 -3
  40. package/dist/simulate.d.ts +3 -1
  41. package/dist/simulate.js +15 -7
  42. package/dist/verify.js +35 -4
  43. package/docs/acs.md +107 -0
  44. package/docs/configuration.md +3 -3
  45. package/docs/door-signals.md +66 -0
  46. package/docs/door.md +168 -0
  47. package/docs/egress.md +177 -0
  48. package/docs/github-action.md +164 -0
  49. package/docs/policies.md +112 -1
  50. package/docs/sdk.md +25 -9
  51. package/docs/threat-model.md +1 -1
  52. package/docs/tutorials.md +7 -0
  53. package/docs/usage.md +2 -2
  54. package/docs/verification.md +16 -2
  55. package/package.json +14 -13
  56. package/templates/claude-code.cedar +287 -10
  57. package/vectors/audit.json +27 -27
  58. package/vectors/canonical.json +5 -5
  59. package/vectors/merkle.json +123 -0
  60. package/vectors/receipts.json +1951 -1005
package/dist/simulate.js CHANGED
@@ -6,6 +6,7 @@ import { canonicalize, dsseVerify } from "./crypto.js";
6
6
  import { decodeDelegation, DELEGATION_TYPE, delegationValidAt } from "./delegation.js";
7
7
  import { leafHash, verifyInclusion } from "./log.js";
8
8
  import { evaluate, policyDigest } from "./policy.js";
9
+ import { compileRego, evaluateRego } from "./policy-rego.js";
9
10
  import { AUTHORIZATION_PREDICATE_TYPE, RECEIPT_TYPE, TREEHEAD_TYPE } from "./receipt.js";
10
11
  import { structuralProblem } from "./verify.js";
11
12
  const strings = (v) => Array.isArray(v) && v.every((x) => typeof x === "string");
@@ -55,7 +56,7 @@ export function verifyOrphanAuthorization(bundle, issuerKeys, logKeys) {
55
56
  return statement.predicate;
56
57
  }
57
58
  /**
58
- * Compare a proposed Cedar policy with recorded policy decisions, using each receipt's original arguments, fact
59
+ * Compare a proposed Cedar or Rego policy with recorded policy decisions, using each receipt's original arguments, fact
59
60
  * values, agent, and (for gateways) grant context. Observe-mode decisions are the baseline even when the call ran.
60
61
  * Receipts are not signature-verified here; verify their bundles separately when their authenticity matters. A
61
62
  * reconciliation receipt is trusted as a provider read only after `verifyBundle` accepts it: the library checks no more
@@ -66,9 +67,14 @@ export function verifyOrphanAuthorization(bundle, issuerKeys, logKeys) {
66
67
  * The receipts are read once, one at a time, so a caller can verify and parse a large history lazily.
67
68
  */
68
69
  export function simulatePolicy(policyText, receipts, options = {}) {
69
- const parsed = cedar.checkParsePolicySet({ staticPolicies: policyText });
70
- if (parsed.type === "failure")
71
- throw new Error(`invalid Cedar policy: ${parsed.errors.map((e) => e.message).join("; ")}`);
70
+ const rego = options.language === "rego" ? compileRego(policyText) : undefined;
71
+ if (rego && !rego.policy)
72
+ throw new Error(`invalid Rego policy: ${rego.errors.join("; ")}`);
73
+ if (!rego) {
74
+ const parsed = cedar.checkParsePolicySet({ staticPolicies: policyText });
75
+ if (parsed.type === "failure")
76
+ throw new Error(`invalid Cedar policy: ${parsed.errors.map((e) => e.message).join("; ")}`);
77
+ }
72
78
  const unreplayable = options.unreplayable ?? [];
73
79
  const report = {
74
80
  runId: randomUUID(),
@@ -122,7 +128,7 @@ export function simulatePolicy(policyText, receipts, options = {}) {
122
128
  }
123
129
  digests.add(previous.policyDigest);
124
130
  if (!receiptId || !tool || typeof original.agent.id !== "string" || !original.agent.id
125
- || !Number.isFinite(Date.parse(original.timestamp)) || !["sdk", "gateway"].includes(original.issuer.kind)) {
131
+ || !Number.isFinite(Date.parse(original.timestamp)) || !["sdk", "gateway", "door", "egress", "guardian"].includes(original.issuer.kind)) {
126
132
  skip("malformed receipt: receipt id, tool, agent, timestamp, or issuer is invalid");
127
133
  continue;
128
134
  }
@@ -154,7 +160,8 @@ export function simulatePolicy(policyText, receipts, options = {}) {
154
160
  args: p.request.args,
155
161
  facts: Object.fromEntries(Object.entries(p.facts).map(([name, fact]) => [name, fact.value])),
156
162
  };
157
- if (p.issuer.kind === "gateway") {
163
+ // a door receipt carries a grant only when the arrival presented one; the policy then saw context.grant, else not
164
+ if (p.issuer.kind === "gateway" || (p.issuer.kind === "door" && p.delegation)) {
158
165
  const envelope = p.delegation?.envelope;
159
166
  const grant = envelope?.payloadType === DELEGATION_TYPE ? decodeDelegation(envelope) : null;
160
167
  if (!grant || grant.agent !== p.agent.id || grant.principal !== p.principal.id) {
@@ -173,7 +180,8 @@ export function simulatePolicy(policyText, receipts, options = {}) {
173
180
  }
174
181
  let proposed;
175
182
  try {
176
- proposed = evaluate(policyText, { agentId: p.agent.id, tool, context });
183
+ const request = { agentId: p.agent.id, tool, context };
184
+ proposed = rego?.policy ? evaluateRego(rego.policy, report.policyDigest, request) : evaluate(policyText, request);
177
185
  }
178
186
  catch (e) {
179
187
  // An evaluator exception is a deny, just as at the gateway; it must never become an allow in a replay.
package/dist/verify.js CHANGED
@@ -1,4 +1,5 @@
1
1
  // Independent verification of a receipt bundle. Needs only public keys, and optionally a copy of the log.
2
+ import { internalAddress, isAddressLiteral, sameAddress } from "./addresses.js";
2
3
  import { canonicalize, digestOf, dsseVerifiers, dsseVerify } from "./crypto.js";
3
4
  import { isApprovalTime, verifyApproval, verifyApprovalStatement } from "./approval.js";
4
5
  import { digestSaltFor, getAt, isCommitment, pathKey, pathText, restorePaths, under } from "./capture.js";
@@ -53,8 +54,8 @@ function verifyOriginalAuthorization(bundle, opts) {
53
54
  add("structural parts in clear", !problem, problem ?? undefined);
54
55
  if (problem)
55
56
  return { ok: false, predicate: null, checks };
56
- add("authorization issued by the gateway", p.issuer.kind === "gateway" && p.issuer.keyid === sig.keyid);
57
- add("authorization operation is submitted", p.operation?.status === "submitted");
57
+ add("authorization issued by the gateway", (p.issuer.kind === "gateway" || p.issuer.kind === "door") && p.issuer.keyid === sig.keyid, p.issuer.kind === "door" ? "a door commits a request before relaying it, as a gateway commits a call" : undefined);
58
+ add("authorization operation is submitted", p.issuer.kind === "door" || p.operation?.status === "submitted", p.issuer.kind === "door" ? "a door has no operations" : undefined);
58
59
  add("authorization permits the original call", p.policy?.decision === "allow" ? Array.isArray(p.policy.errors) && p.policy.errors.length === 0 : p.policy?.decision === "deny" && p.policy.enforced === false);
59
60
  const del = p.delegation && verifyDelegation(p.delegation.envelope, opts.principalKeys);
60
61
  add("delegation signature (principal key)", !!del?.ok);
@@ -184,7 +185,7 @@ export function verifyBundle(bundle, opts) {
184
185
  if (!add("structural parts in clear", !broken, broken ?? undefined))
185
186
  return done(null);
186
187
  const p = st.predicate;
187
- add("issuer kind is known", p.issuer.kind === "gateway" || p.issuer.kind === "sdk", `${p.issuer.kind}${p.issuer.framework ? ` / ${p.issuer.framework}` : ""}`);
188
+ add("issuer kind is known", p.issuer.kind === "gateway" || p.issuer.kind === "sdk" || p.issuer.kind === "door" || p.issuer.kind === "egress" || p.issuer.kind === "guardian", `${p.issuer.kind}${p.issuer.framework ? ` / ${p.issuer.framework}` : ""}`);
188
189
  add("issuer keyid matches signer", p.issuer.keyid === sig.keyid);
189
190
  if (opts.requireStrict) {
190
191
  add("strict mode in force", p.issuer.kind === "gateway" && p.issuer.strict === true, p.issuer.strict === true ? undefined : "the issuer does not say it ran in strict mode");
@@ -207,6 +208,34 @@ export function verifyBundle(bundle, opts) {
207
208
  add("gateway receipt carries a delegation", p.delegation !== undefined);
208
209
  add("gateway receipt carries a policy decision", p.policy !== null);
209
210
  }
211
+ // A door decides every arrival by policy; an arrival carries a grant only when it chose to present one.
212
+ if (p.issuer.kind === "door")
213
+ add("door receipt carries a policy decision", p.policy !== null);
214
+ // An egress witness saw a connection that went around the gateway: where it went and how much, never what was sent.
215
+ // Its destination is its own observation; its agent is only as good as the proxy credential it checked.
216
+ if (p.issuer.kind === "egress") {
217
+ add("egress receipt carries a policy decision", p.policy !== null);
218
+ const dest = Object.hasOwn(p.facts, "destination") ? p.facts.destination : undefined;
219
+ const seen = dest?.value;
220
+ const name = typeof seen?.host === "string" && typeof seen.port === "number" ? `${seen.host.includes(":") ? `[${seen.host}]` : seen.host}:${seen.port}` : undefined;
221
+ add("egress destination observed", p.tool.provenance === "observed" && dest?.provenance === "observed" && name === p.tool.name, name === p.tool.name ? `${p.tool.name}; an observed bypass of the gateway, not a record of what was sent` : `the destination fact names ${name ?? "nothing"}, the receipt ${p.tool.name}`);
222
+ const relayed = p.execution.status === "executed" || p.execution.status === "failed" || p.execution.status === "error";
223
+ add("egress relayed only for a checked agent", !relayed || p.agent.provenance === "observed", p.agent.provenance === "observed" ? `${p.agent.id}, by the proxy credential the witness checked` : relayed ? `the connection was ${p.execution.status} for an agent the witness did not check` : "no agent was checked and nothing was relayed");
224
+ add("egress open committed before relaying", !relayed || !!p.authorization, relayed ? (p.authorization ? "the connection was in the log before any byte moved" : `the connection was ${p.execution.status} with nothing committed first`) : "nothing was relayed");
225
+ // An IP literal is the action itself: the peer must be that very address. A host name must have led to a public address.
226
+ const host = typeof seen?.host === "string" ? seen.host : "";
227
+ const literal = isAddressLiteral(host);
228
+ const reached = p.execution.status === "executed" || p.execution.status === "failed";
229
+ const peer = p.execution.status === "executed" || p.execution.status === "failed" ? p.execution.result?.peer : undefined;
230
+ const peerOk = typeof peer === "string" && (literal ? sameAddress(peer, host) : !internalAddress(peer));
231
+ add("egress peer matches the destination", !reached || peerOk, !reached ? "no connection was made" : literal ? `${host}, an address the policy named, reached ${typeof peer === "string" ? peer : "no recorded peer"}` : `${host} reached ${typeof peer === "string" ? peer : "no recorded peer"}${peerOk ? ", a public address" : ""}`);
232
+ }
233
+ // A Guardian decides and carries out nothing: an allow is withheld (nothing forwarded), a deny is denied.
234
+ if (p.issuer.kind === "guardian") {
235
+ add("guardian receipt carries a policy decision", !!p.policy && typeof p.policy === "object" && !Array.isArray(p.policy));
236
+ const decided = p.execution.status === "denied" ? p.policy?.decision === "deny" : p.execution.status === "withheld" && p.policy?.decision === "allow";
237
+ add("guardian decided, executed nothing", decided, decided ? `${p.policy?.decision}; the agent asked, reports the call itself, and is trusted to honor the answer` : `the receipt says ${p.execution.status} with a policy ${p.policy?.decision ?? "absent"}`);
238
+ }
210
239
  if (p.delegation) {
211
240
  const del = verifyDelegation(p.delegation.envelope, opts.principalKeys);
212
241
  add("delegation signature (principal key)", del.ok, del.ok ? `signed by ${short(del.keyid)}` : del.error);
@@ -541,6 +570,8 @@ export function auditExtends(older, newer, proof, keys, logId, opts = {}) {
541
570
  const ISSUER_NOTE = {
542
571
  gateway: "enforced outside the agent's process; the agent could neither skip nor forge this receipt",
543
572
  sdk: "self-reported by the agent's own process; tamper-evident after issue, but nothing here was enforced outside the agent",
573
+ guardian: "decided by an ACS Guardian outside the agent's process and signed with its own key, so the decision is attributable to it; the call is the agent's own report, and the agent could skip the Guardian or ignore its answer",
574
+ egress: "observed by a forward proxy in the agent's network path, for a connection that went around the gateway: where it went and how much, never what was sent; the agent is known only by the proxy credential the witness checked, and a connection that skipped the proxy (no lockdown) leaves no receipt at all",
544
575
  };
545
576
  /** Human-readable report: checks, then every field with its provenance so the reader knows what was proven vs. claimed. */
546
577
  export function formatReport(r) {
@@ -579,7 +610,7 @@ export function formatReport(r) {
579
610
  const committed = r.checks.filter((c) => c.name.startsWith("authorization ")).every((c) => c.ok);
580
611
  row("authorization", "observed", committed ? `committed to the log as leaf ${p.authorization.inclusion.leafIndex}, before the call was forwarded` : "carried, but its checks FAILED");
581
612
  }
582
- else if (p.execution.status === "withheld")
613
+ else if (p.execution.status === "withheld" && p.issuer.kind !== "guardian")
583
614
  row("authorization", "observed", "the log would not commit it; the call was not forwarded");
584
615
  if (p.approval)
585
616
  row("approval", p.approval.provenance, `${p.approval.status}; ${p.approval.requiredApprovers} approver(s) required${p.approval.consumedAt ? `; consumed ${p.approval.consumedAt}` : ""}${typeof p.approval.reason === "string" ? `; ${p.approval.reason}` : ""}`);
package/docs/acs.md ADDED
@@ -0,0 +1,107 @@
1
+ # The ACS Guardian
2
+
3
+ The [OWASP Agent Control Standard](https://github.com/GenAI-Security-Project/agent-control-standard) (ACS) is a wire contract between an agent and a separate policy point. Before the agent acts, its instrumentation sends a JSON-RPC 2.0 hook, such as `steps/toolCallRequest`, to a **Guardian**. The Guardian answers `allow`, `deny`, `modify`, `ask`, or `defer`, and the agent is expected to honor the answer. `agent-custody acs` is a Guardian for two of those hooks. It decides each one with a Cedar policy and returns the decision with a signed, logged receipt (`issuer.kind: "guardian"`). A third party can check that receipt with the Guardian's public key alone.
4
+
5
+ This is a spike: enough to show the two fit together. It is not an ACS-Core conformant Guardian. The list of what it leaves out is [below](#what-it-does-not-implement). It was written against the ACS repository at commit `db457a8` (`version.txt` 0.1.4, schemas under `specification/v0.1.0/`).
6
+
7
+ ## Why a receipt and not just the ACS answer
8
+
9
+ ACS already asks the Guardian to keep an audit chain and publish its head. Two passages in the specification set the limits of that record. A receipt from this Guardian is meant to supply what they say is missing:
10
+
11
+ - **ACS §8.6, chain head publication.** The baseline signature is HMAC-SHA256, with a per-session key that both the Guardian and the agent derive (§10). The section says a valid HMAC shows that *a* holder of the session key produced a message, not *which* one. So under the baseline a Guardian decision is not attributable to the Guardian against the agent. The agent can produce a validly signed `allow` that the Guardian never sent, and the Guardian can re-sign a rewritten chain. ACS leaves non-repudiation to its optional asymmetric ACS-Crypto profile.
12
+ - **ACS Trace README, "Observability Goals".** Trace events are self-reported observations, produced inside the environment being observed. The README says they become evidence only when a party outside the emitting runtime attests to them.
13
+
14
+ A receipt from this Guardian is signed by a key that only the Guardian holds (Ed25519, DSSE). It goes into an append-only Merkle log, which a witness can countersign, and the same `agent-custody verify` checks it that checks every other receipt. Neither party can mint or edit one without the Guardian's key, and the Guardian cannot quietly drop one from a log that others have already seen.
15
+
16
+ ## ACS issue #18: an audit chain that does not rest on one Guardian
17
+
18
+ [ACS issue #18](https://github.com/GenAI-Security-Project/agent-control-standard/issues/18) points out that the §8 chain is only as trustworthy as the one Guardian that keeps it. It notes there is no way for an auditor who trusts no Guardian to check or compare chains, and it proposes three directions for later versions. Here is each one against what this Guardian does:
19
+
20
+ 1. **Sign `chain_hash` under a long-lived audit key, and export it as a signed checkpoint.** Done. Every decision's receipt carries the session's `chain_hash`, `previous_hash`, and `request_hash` in its `acsStep` fact. The receipt is signed with the Guardian's long-lived Ed25519 key, which is not an ACS session key. The bundle (receipt, signed tree head, and inclusion proof) is the exported checkpoint, and it verifies offline with the Guardian's public key. The receipt carries a head for every decision, not only a periodic one.
21
+ 2. **Guardians exchange and commit to each other's chain heads when they mediate an A2A interaction.** Not done. Nothing here sends a chain head to another Guardian or records one received. Two Guardians that append to the same log, or to logs that one witness watches, can be compared by an auditor after the fact. That is not the exchange protocol #18 describes.
22
+ 3. **Publish signed chain heads to an external append-only log, Sigstore/Rekor style.** Done, with agent-custody's own log rather than Rekor. Each receipt is a leaf in an RFC 6962 Merkle log. When the log is run by someone else (`log: { url, keys }`), the tree head is signed by that operator's key, and the verifier checks it with `--log-key`. So a verifier learns the decision was in a log the Guardian could not rewrite. `agent-custody audit` (or `auditExtends`) checks a consistency proof (RFC 9162) between two tree heads, which shows a later head extends an earlier one. The [witness](verification.md) countersigns the log's checkpoints, so the log operator cannot show different histories to different parties. The witness is not part of example 43.
23
+
24
+ [Example 43](../examples/43-acs-guardian.ts) shows directions 1 and 3 end to end. It starts a log under a separate key. It pipes the ACS README's sample `toolCallRequest` through `agent-custody acs`. It verifies the receipt with only the Guardian's and the log's public keys. Then it checks that the log after a later deny extends the log that held the first decision.
25
+
26
+ ## What it does, and what it does not prove
27
+
28
+ The Guardian decides, signs, and logs. It carries out nothing. The agent chose to ask. It reports the call in its own words, and nothing makes it honor the answer or ask at all. So a guardian receipt proves **what the Guardian decided, on what request, under which policy, and when**. It does not prove that the call happened or did not happen. The [gateway](usage.md) is the enforcement point an agent cannot skip: it holds the tool credentials and forwards the call itself. ACS supplies the hooks. agent-custody supplies the proof, and the gateway where it matters.
29
+
30
+ | ACS | receipt |
31
+ | --- | --- |
32
+ | `params.metadata.agent_id` | `agent.id`, `claimed`: nothing on the wire binds it to the agent |
33
+ | `params.metadata.session_id`, `params.request_id` | `session.id`, `session.toolUseId`, `claimed` |
34
+ | `payload.tool.name` | `tool.name`, `claimed`; also the Cedar action and resource |
35
+ | toolCallRequest `payload.arguments` | `request.args`, `claimed`: each `{value, provenance}` unwrapped to its value |
36
+ | toolCallResult `exit_status`, `outputs`, `duration_ms`, `request_id_ref` | `request.args`, `claimed`: the result is what the agent submitted for a decision |
37
+ | the method | `issuer.framework`, e.g. `acs steps/toolCallRequest` |
38
+ | the decision | `policy`, `observed`; `execution.status` is `withheld` for an allow (the Guardian forwards nothing) and `denied` for a deny |
39
+ | `request_hash` and `chain_hash` (§8.1, §8.2) | the `acsStep` fact, `observed`: `{method, request_id, request_hash, entry_id, previous_hash, chain_hash, request_ref?}` |
40
+
41
+ The answer is an ordinary ACS result: `type: "final"`, `decision`, `reasoning`, `reason_codes` on a deny (`policy_denied` or `policy_error`), `policy_references` (the Cedar rule ids, each with its `@reason` and the policy's sha256), `chain_hash`, and `metadata.evaluator: "deterministic"`. The receipt rides in `policy_data["agent-custody"]` as `{receiptId, keyid, receipt}`. The README sample and the Guardian's answer to it both validate against the ACS `request-envelope.json`, `hooks/tool-call-request.json`, and `response-envelope.json`.
42
+
43
+ ### The policy
44
+
45
+ Cedar, as everywhere else in agent-custody. The principal is `Agent::"<agent_id>"`, and the action and resource are the tool name. The context is:
46
+
47
+ ```
48
+ context.args the argument values (toolCallRequest), or {exit_status, outputs, duration_ms?, request_id_ref?} (toolCallResult)
49
+ context.acs.method "steps/toolCallRequest" | "steps/toolCallResult"
50
+ context.acs.capability, context.acs.operation when the payload carries them
51
+ context.acs.requestRef on a result with request_id_ref: {resolved, decision?, tool?, agent?, consumed?}: the decision this
52
+ Guardian gave that request in this session, its tool and agent, and whether a result for it was already allowed
53
+ ```
54
+
55
+ `examples/acs/policy.cedar` allows `file_read` under `/reports/`, and refuses any path containing `..`, because `like` matches characters, not paths: `/reports/../etc/passwd` matches `/reports/*`. The tool should resolve the path as well. The policy lets one result through, and only for a `file_read` request this Guardian allowed. A policy that permits results for several tools should compare `context.acs.requestRef.tool` with the action, or a result for one tool could ride on a request allowed for another. When a result names a `request_id_ref` the Guardian cannot resolve, the receipt records it as `resolved: false`, as ACS `hooks.md` (toolCallResult) requires, and the policy decides what that means. Everything else is denied: Cedar is default deny, and an evaluation error is a deny.
56
+
57
+ The policy file is re-read when it changes, and the next call is decided under the new one. A changed file that does not parse is refused with a message on stderr, and the policy in force stays. Each receipt names the digest of the policy it was decided under.
58
+
59
+ ## Run it
60
+
61
+ ```bash
62
+ agent-custody keygen --dir keys --name guardian
63
+ cp examples/acs/policy.cedar .
64
+ cat > acs.json <<'EOF'
65
+ { "identity": { "keyFile": "keys/guardian.key" }, "policyFile": "policy.cedar", "receiptsDir": "receipts", "logFile": "log.jsonl" }
66
+ EOF
67
+ agent-custody acs --config acs.json < examples/acs/tool-call-request.json > answer.json
68
+ jq '.result.policy_data["agent-custody"].receipt' answer.json > receipt.json
69
+ agent-custody verify receipt.json --issuer-key keys/guardian.pub --log log.jsonl
70
+ ```
71
+
72
+ `examples/acs/tool-call-request.json` is the sample from the ACS README ("A hook, on the wire"), byte for byte. The answer is `allow`. The verifier reports `issuer kind is known (guardian / acs steps/toolCallRequest)`, `guardian receipt carries a policy decision`, `guardian decided, executed nothing`, the signature, and the log inclusion, then `RESULT: VERIFIED`. With the Guardian's own local log, as here, the tree head is signed by the Guardian's key too. For a verifier who should not have to trust the Guardian, point `log` at a log someone else runs and verify with `--log-key` as well. [Example 43](../examples/43-acs-guardian.ts) does that, then runs a denied read, a result let through, a result for an unknown request, and a consistency check of the log.
73
+
74
+ `acs` reads one JSON document from stdin, either one request or a JSON-RPC batch evaluated in order, and prints the answer. It exits 0 when every answer is a decision, deny included, and 1 when any answer is an error, such as `-32603` for a receipt that could not be written. In code, `createAcsGuardian(cfg).handle(message)` does the same with no transport, so it can sit behind any HTTP or stdio server. Calls in one session are decided one at a time, in arrival order, so concurrent calls cannot both pass the replay check or fork the chain. Calls in different sessions do not wait for each other.
75
+
76
+ A session belongs to the agent that opened it. A call that names the same `session_id` with another `agent_id` is refused with `-32000` (`SESSION_REFUSED`, `data.reason: "agent_mismatch"`), so a second caller who knows a session id cannot extend its chain or ride on its allowed requests. That binds the claimed id, not the agent. Without ACS signatures, a caller who knows both ids can still speak for the agent.
77
+
78
+ Only a decision gets a receipt. An invalid request, an unknown method, a version mismatch, a replay, an agent mismatch, and a receipt that could not be written are answered with a JSON-RPC error and leave no receipt. A `system/ping` leaves none either.
79
+
80
+ ## What a verifier checks
81
+
82
+ Besides the checks every receipt gets (signature, structure, argument digest, log inclusion):
83
+
84
+ - `guardian receipt carries a policy decision`: every step is decided by policy.
85
+ - `guardian decided, executed nothing`: an allow is `withheld` and a deny is `denied`. A guardian receipt that says `executed` is one someone re-signed.
86
+
87
+ The TypeScript, browser, and Python verifiers all run these. `vectors/receipts.json` carries `guardian-acs-allow`, `guardian-acs-deny`, and two re-signed cases that must fail.
88
+
89
+ The verifiers do not read the `acsStep` fact. They do not recompute `chain_hash` from `previous_hash` and `request_hash`, and they do not check that one receipt's `previous_hash` is the previous receipt's `chain_hash`. The fields are signed, so nobody but the key holder can change them. But a verifier that holds a session's receipts could recompute the links itself (`acsEntryHash` does it, and the tests do it with an independent implementation). That check is not built.
90
+
91
+ Trust is by key, not by kind. A verifier accepts a `guardian` receipt signed by any key it is given as an issuer key, so the holder of a gateway's or an SDK's trusted key could sign one. Give `--issuer-key` only the Guardian's key when checking Guardian decisions.
92
+
93
+ ## What it does not implement
94
+
95
+ - **The handshake (§4).** There is no `handshake/hello` and no ServerHello. Nothing negotiates versions, methods, timeouts, `on_decision_failure`, or profiles. `handshake/hello` gets `-32601`. ACS-Core requires the handshake.
96
+ - **ACS signatures (§10).** A request's `signature` is not checked, with HMAC or anything else, and the answer carries none. The answer therefore does not meet ACS-Core's signature requirement, and its `chain_hash` is not covered by a response signature as §8.6 requires. The receipt's own signature covers it instead. Ed25519 is not in the ACS algorithm registry (§10.1), so the receipt sits beside an ACS-Crypto signature and does not replace one.
97
+ - **Most of the hooks.** Only `steps/toolCallRequest` and `steps/toolCallResult` are decided, and `system/ping` is answered. The other 17 `steps/*` hooks, `protocols/MCP/*`, and `agbom/*` get `-32601`.
98
+ - **Dispositions other than allow and deny.** There is no `modify`, `ask`, or `defer`, and so none of the substitution rules in §6.5 and §9.2.
99
+ - **Replay protection (§10.3), in part.** A repeated `request_id` in a session is refused with `REPLAY_DETECTED` (`-32005`), and no second receipt is written. The timestamp skew window is not enforced, so the README sample, stamped September 2026, is accepted. Nonces are not tracked.
100
+ - **Provenance (§7).** Argument and output `provenance` objects are dropped before the policy sees the values. There is no trust derivation from `origin`, and no `provenance_producer`. A policy cannot express FIDES or CaMeL-style rules here.
101
+ - **SessionContext and Intent (§8).** The chain is kept in memory, per process, with no bound or expiry. The CLI runs one process per document, so each run starts a new chain at `previous_hash: null`. Use `handle()` in one long-lived process, or a batch, to keep a session together. There is no `provenance_summary`, no Intent, and no `CHAIN_MISMATCH` check against the agent's `session_state.chain_hash`.
102
+ - **Canonical JSON.** `request_hash` and `entry_hash` use agent-custody's canonical JSON (sorted keys, no whitespace). That matches RFC 8785 for ordinary JSON, but it is not a full JCS implementation: edge cases in number formatting and lone surrogates may differ. ACS publishes no chain-hash vector to check against. The tests recompute the chain with an independent implementation.
103
+ - **Engines.** The Guardian uses Cedar only. ACS §12.1 names OPA/Rego as its v0.1 reference engine and Cedar as v0.2. The gateway already evaluates Rego, but it is not wired in here. There is no agent (LLM) layer, which §12.2 makes optional.
104
+ - **Transports.** There is no HTTP server and no stdio `Content-Length` framing. The CLI reads one document from stdin.
105
+ - **Decision failure (§6.4).** When the receipt cannot be written, the Guardian gives no decision: it answers `-32603` with `data.reason: "receipt_not_written"`. ACS's default failure posture is `proceed`, so an agent left at that default carries on unguarded. A deployment that wants every decision on record sets `on_decision_failure: deny`.
106
+ - **Trace and Inspect.** No OTel or OCSF events, and no AgBOM.
107
+ - **Identity.** `agent_id` is whatever the wire says. ACS leaves authentication to the deployment (§11), and nothing here binds the id to the agent. For agent identity, the gateway's signed grant is the mechanism.
@@ -1,6 +1,6 @@
1
1
  # Configuring the gateway
2
2
 
3
- Who may use which tools, and where those tools live, is set in three files and a few environment variables. This page is the map: what each one decides, how they fit together, a worked example with two agents on one shared gateway, how it all works in the Docker image, and how to check a config before you start. The full list of config keys is in [the gateway reference](/reference/gateway); the Cedar language is in [policies.md](policies.md).
3
+ Who may use which tools, and where those tools live, is set in three files and a few environment variables. This page is the map: what each one decides, how they fit together, a worked example with two agents on one shared gateway, how it all works in the Docker image, and how to check a config before you start. The full list of config keys is in [the gateway reference](/reference/gateway); the Cedar and Rego languages are in [policies.md](policies.md).
4
4
 
5
5
  ## What you configure, and where
6
6
 
@@ -22,7 +22,7 @@ For each call, in this order, and a refusal at any step is a signed receipt:
22
22
  1. **The grant** is valid, signed by a trusted principal, inside its window, and not revoked.
23
23
  2. **The tool** is one of the grant's scopes.
24
24
  3. **Facts** the policy needs are fetched by the gateway from an upstream (`facts` in the config).
25
- 4. **The Cedar policy** permits the call. No matching `permit` means deny.
25
+ 4. **The policy** permits the call: Cedar, a Rego file, or an OPA server ([policies.md](policies.md#rego)). Nothing permitting it means deny.
26
26
  5. **For `precommit` tools**, the authorization is committed to the log before anything is forwarded.
27
27
  6. **The call** is forwarded to the upstream that owns the tool.
28
28
 
@@ -197,7 +197,7 @@ docker run --rm -v "$PWD/config:/config:ro" -v gateway-data:/data --env-file .en
197
197
  | a key that is not in the schema (a typo such as `precomit` is otherwise silently ignored, and the setting stays at its default) | **error**, with the key it nearly is |
198
198
  | the gateway key loads, and is not readable by other users | error, and a warning |
199
199
  | every trusted principal key loads | error |
200
- | the Cedar policy parses, and has at least one `permit` rule (a `permit(` in a comment does not count) | error, and a warning |
200
+ | the Cedar policy parses, and has at least one `permit` rule (a `permit(` in a comment does not count); a `.rego` file compiles; an OPA server answers for the package, and reports a bundle revision | error, and a warning |
201
201
  | every credential variable the config names is set: upstream tokens and headers, the log's token, the capture key, the Splunk token, and the OpenTelemetry headers | **error**: the gateway does not start without it |
202
202
  | a stdio `command` exists, and a script argument exists | error, and a warning |
203
203
  | the receipts, log, revocation, operations database, and approvals paths can be written, and the revocation file is a JSON array | error |
@@ -0,0 +1,66 @@
1
+ # Door signals: what each one does and does not mean
2
+
3
+ The door records one fact for every arrival, `arrival`, and gives it to the policy as `context.facts.arrival`. Every field in it is a signal: something the door observed, labelled by how far it was checked. None of them is a verdict. This page says, for each signal, what it establishes, what it does not, and how a policy should read it. The door's guide is [the door](door.md); the contract is the [reference](https://agent-custody.dev/reference/door).
4
+
5
+ Three labels run through the table:
6
+
7
+ - **Checked.** The door verified it against a key it trusts or computed it itself. A policy may rely on it.
8
+ - **Observed.** The door saw it on the wire. It is true that it was sent; nothing about the sender follows.
9
+ - **A claim.** The caller asserted it and the door could not check it. A policy that relies on it relies on the caller.
10
+
11
+ ## The signals
12
+
13
+ | signal | label | what it means | what it does not mean |
14
+ | --- | --- | --- | --- |
15
+ | `class: "verified"` | checked | A grant signed by a principal in `trustedPrincipalKeys`, inside its validity window, names this agent and lists this arrival's route among its scopes. The Cedar `principal` is that agent | That the agent is well-behaved, that the principal is who they say they are beyond holding the key, or that the request body is what the principal intended. The grant has no revocation list: it stands until it expires |
16
+ | `class: "claimed"` | a claim | Something was asserted that the door could not accept: a grant from a key it does not trust, an expired one, one for other routes, a declared agent name, or an HTTP signature header. `grant` and `grantError` say which | That the arrival is an agent, or that it is hostile. A misconfigured client, a grant for the wrong route, and an impostor all look the same here |
17
+ | `class: "unknown"` | observed | Nothing was presented | That the arrival is a person. A browser, a crawler, and a script that sends no headers are all `unknown`. There is no `human` class, and a policy that admits `unknown` on a route admits everything on that route |
18
+ | `grant: "verified"` | checked | As `class: "verified"` | |
19
+ | `grant: "out-of-scope"` | checked | The grant verified and is valid, but this route is not among its scopes. `subject` is the agent it names | That the agent may do anything here. The principal did not grant this route |
20
+ | `grant: "invalid"` | checked | The grant did not verify against a trusted key, did not decode, or is outside its window. `grantError` says which | Who signed it. A grant from an untrusted principal is `invalid` even when it is genuine |
21
+ | `grant: "absent"` | observed | No grant header | |
22
+ | `subject` | checked only when `class` is `verified` | The agent a verified grant names; else the declared name or the agent a rejected grant named; else `unknown` | For a `claimed` arrival, anything. It is recorded so the receipt shows what was asserted; the Cedar `principal` is `Agent::"unknown"` for it |
23
+ | `declared` | a claim | The `x-agent-custody-agent` header, as sent, cut at 200 characters | That the agent is that agent. Anyone can send the header. A permit on a declared name admits whoever types it |
24
+ | `signature: true` | a claim | An RFC 9421 `Signature-Input` header was present, so the arrival asserts a signature | That the signature is valid, or who signed. **The door does not check it yet.** It is recorded so that a later verifier, or a reader of the receipt, knows a signature travelled with the request |
25
+ | `remote` | observed | The socket's address, or with `trustProxy` the last address in `X-Forwarded-For`, the one your proxy appended | Who the person or program is. One address serves a whole office, a mobile carrier, or a cloud region; one program can use many |
26
+ | `challenge.outcome` | checked, against the provider | Only when `challenge` is configured. `passed`: Turnstile or hCaptcha confirmed the token this arrival sent, so the provider judged a person present when the token was made. `failed`: the provider refused the token itself (bad, expired, or already used; `error` carries the codes), the token was issued on a hostname not in `hostnames` or for another action, or it was too long to be a token. `unavailable`: the provider did not answer in time, answered a non-200, a redirect, or something that is not JSON, reported a fault of its own or of the operator's (a wrong or rotated secret, a site key that does not match it), or too many checks were already waiting, which is the provider's or the door's state, not the arrival's. `absent`: no token | That the arrival is a person now, or that the person is who they say: a token is made once and sent by whatever holds it, and the provider's own error rate applies. It does not change `class`. `unavailable` is not `failed`: a policy that treats it as one locks everyone out when the provider is down, and one that treats it as a pass admits everyone; say which, on purpose |
27
+ | `rate.burst`, `rate.minute` | checked | Arrivals from the same source in the last 10 and 60 seconds, this one included, whatever the policy decided about them, counted by this door process on a monotonic clock, so a step of the wall clock does not move the windows. `rate.by` says what the source is: `agent`, the verified agent's name, or `remote`, the address | That the source is a program, or that it is abusive. Twenty arrivals a minute is one page load for a site that fans out to its API, and one agent on a job. The count is one process's memory: it starts at one when the door starts, two doors do not share it, and an address shared by many people counts them together. It keeps at most 10,000 sources and forgets the least recently seen first, so a client that sends from many new addresses can make another source's count start again |
28
+ | `method`, `path`, `route` | observed | What arrived, the path percent-decoded once, and the route it fell under | |
29
+
30
+ ## Reading them in a policy
31
+
32
+ The signals are attributes of `context.facts.arrival`. A permit for an agent requires the arrival to be verified, or the permit admits nothing but a header:
33
+
34
+ ```cedar
35
+ permit(principal == Agent::"shopping-agent", action == Action::"api", resource)
36
+ when { context.facts.arrival.class == "verified" };
37
+ ```
38
+
39
+ `agent-custody check` warns about a permit that names an agent without that condition.
40
+
41
+ Rate is a reason to slow a route down or to ask for more, not a reason to decide what the arrival is. A forbid on it refuses the arrivals past the limit and receipts each refusal, so the receipts show how often the limit was hit and by what:
42
+
43
+ ```cedar
44
+ forbid(principal, action == Action::"refund", resource)
45
+ when { context.facts.arrival.rate.minute > 30 };
46
+ ```
47
+
48
+ A limit by `remote` reaches everyone behind one address. Put it high enough that a shared address is not refused for one user's pace, or scope it to routes where a person's pace is slow in any case, as a refund form is. For a verified agent the count is by agent name across every address it uses, so a limit on a verified agent is a limit on the agent.
49
+
50
+ An `unknown` arrival that comes fast is still unknown. The honest policy for a route that should not take bursts from strangers is to refuse them and say why, and to route the agents you want through a grant, which makes them `verified` and counted by name.
51
+
52
+ A challenge is the way a person gets through a route that refuses `unknown`. The permit names the outcome, not the class, and a second permit lets the agents you trust through without the widget:
53
+
54
+ ```cedar
55
+ permit(principal, action == Action::"refund", resource)
56
+ when { context.facts.arrival.challenge.outcome == "passed" };
57
+
58
+ permit(principal == Agent::"shopping-agent", action == Action::"refund", resource)
59
+ when { context.facts.arrival.class == "verified" };
60
+ ```
61
+
62
+ Decide what `unavailable` means for each route before the provider has its first outage: a forbid on `outcome != "passed"` closes the route then, and the receipts show that the provider, not the arrivals, was the reason.
63
+
64
+ ## What is not a signal yet
65
+
66
+ Nothing in the arrival fact says whether the arrival is a program. Behavioural and fingerprint signals, HTTP message signature verification, and Web Bot Auth directory lookups are not built; when they are, each will arrive with a measured error rate beside it, and this page will say what it means. Until then a policy has the grant, the claims, the address, and the pace, and the receipt records which of them it used.
package/docs/door.md ADDED
@@ -0,0 +1,168 @@
1
+ # The door: a receipted reverse proxy in front of your own site or API
2
+
3
+ The gateway stands between an agent and the tools it uses. The door stands between the world and your own HTTP surface: a website, an API, a form. Every arrival, a browser, an API client, a crawler, or an agent acting for someone, is classified by what it presented, decided by a Cedar policy for the route it hit, relayed to your origin or refused, and receipted either way. The receipt is the same signed, logged, independently verifiable receipt the gateway issues, with `issuer.kind: "door"`.
4
+
5
+ This is the first piece of the agent front door. It answers "what may this arrival do here" and "what did it do, provably". It does not yet answer "is this an agent" for web traffic: that is detection, and the door records only what it can check. Read [what the door knows](#what-the-door-knows-about-an-arrival) before writing a policy.
6
+
7
+ ```bash
8
+ agent-custody keygen --dir keys --name door
9
+ agent-custody check --config door.json
10
+ agent-custody door --config door.json --port 8780
11
+ ```
12
+
13
+ ## The config file
14
+
15
+ `door.json`, paths relative to the file. Loaded with `loadDoorConfig(path)`.
16
+
17
+ ```json
18
+ {
19
+ "identity": { "keyFile": "keys/door.key" },
20
+ "origin": { "url": "http://127.0.0.1:3000", "timeoutMs": 30000 },
21
+ "routes": [
22
+ { "name": "catalogue", "methods": ["GET"], "path": "/catalogue/*" },
23
+ { "name": "refund", "methods": ["POST"], "path": "/refunds" },
24
+ { "name": "api", "path": "/api/*" }
25
+ ],
26
+ "unmatchedRoute": "other",
27
+ "trustedPrincipalKeys": ["keys/principal.pub"],
28
+ "policyFile": "policy.cedar",
29
+ "receiptsDir": "receipts",
30
+ "logFile": "log.jsonl"
31
+ }
32
+ ```
33
+
34
+ | field | meaning |
35
+ | --- | --- |
36
+ | `identity.keyFile` | the door's Ed25519 key; signs every receipt. From `agent-custody keygen` |
37
+ | `origin.url` | where allowed arrivals are relayed: the site or API behind the door. `headers` and `headerEnv` add headers to every relayed request, the latter from the environment, so the origin can require a secret only the door holds. `timeoutMs` bounds one relayed request, default 30 s. A path in the URL (`https://host/api/v1`) is kept: the arrival's path goes under it, and a redirect from the origin to a place under it comes back as a door path |
38
+ | `routes` | what the policy sees as the action. `path` is exact (`/refunds`), a prefix (`/api/*`), or `*`; `methods` narrows it, default every method. The first route that matches wins; an arrival no route matches is the action `unmatchedRoute`, default `other`. The match reads the path as the origin will: percent-decoded once, so `/%61dmin` falls under `/admin/*`, and with empty segments merged, so `//admin/users` and `/admin//users` fall under it too (nginx, Apache, and many frameworks merge them). A trailing slash matches as none: `/refunds/` falls under `/refunds`. The origin is sent that merged, decoded form, trailing slash kept, so the door and the origin read one path. A path with a segment that does not decode, or decodes to a slash or a backslash, falls under `unmatchedRoute` and is never relayed |
39
+ | `trustedPrincipalKeys` | public keys of principals whose signed grants the door accepts as a passport. Without any, no arrival can be `verified` |
40
+ | `policyFile` | the Cedar policy, re-read when the file changes; one that does not parse is refused and the policy in force stays |
41
+ | `mode` | `enforce` (default) refuses what the policy denies. `observe` relays everything and records the decision with `enforced: false` |
42
+ | `trustProxy` | behind one reverse proxy you run: the arrival's address is the last in `X-Forwarded-For`, the one your proxy appended; everything before it is what the client sent. The proxy's `X-Forwarded-For`, `-Proto`, and `-Host` are kept on the relay, with the door's own socket address appended, and the other client-address headers (`Forwarded`, `X-Real-IP`, `True-Client-IP`, `CF-Connecting-IP`, every `X-Forwarded-*`) are relayed as the proxy sent them. Without `trustProxy` the client wrote all of these: the door drops them and sets `X-Forwarded-For`, `-Host`, `-Proto`, and `X-Real-IP` itself |
43
+ | `maxBodyBytes` | the largest request body the door relays; a larger one gets 413 and a `withheld` receipt once the policy has allowed it. Default 1 MiB |
44
+ | `maxResponseBytes` | the largest origin response the door relays; see [what the arrival gets back](#what-the-arrival-gets-back). Default 32 MiB |
45
+ | `maxInFlight` | arrivals handled at once. Each holds its body and the origin's answer in memory until it is answered, so this bounds the door's memory at about `maxInFlight × (maxBodyBytes + maxResponseBytes)`. Past it the next arrival gets 503 with `Retry-After: 1` before its body is read: it is not decided, relayed, or receipted. Default 256 |
46
+ | `precommit` | route names whose arrivals are committed to the log before they are relayed whatever their method, or `["*"]`. Every arrival whose method is not GET, HEAD, or OPTIONS is committed regardless; see [before the origin hears of it](#before-the-origin-hears-of-it). Default `[]` |
47
+ | `challenge` | the human branch: `{ provider: "turnstile" or "hcaptcha", siteKey, secretEnv, hostnames, action?, header?, timeoutMs?, maxInFlight? }`. `hostnames` lists the hosts of the pages that render the widget, `action` (Turnstile only) the widget's action, and `maxInFlight` (default 64) how many checks may wait on the provider at once. A token an arrival sends in `header` (default `x-agent-custody-challenge`) is verified with the provider, and the outcome is the arrival's `challenge` signal; see [challenging a human](#challenging-a-human). The secret comes from the environment variable, read at startup; missing is a startup error |
48
+ | `receiptsDir`, `logFile` or `log`, `otel`, `splunk`, `capture`, `captureKeyEnv` | as for the [gateway](configuration.md): where receipts and the log go, exporters, and private evidence per route. A remote `log` needs `log.keys`, because its answer is checked before a request is relayed. Unlike the gateway, the door withholds by default: see [what a receipt records](#what-a-receipt-records-of-the-query-and-the-body) |
49
+
50
+ `agent-custody check --config door.json` reads a door config the way the door would: unknown keys, the key, the principal keys, the policy (including a permit that names an agent without requiring a verified arrival, see below), the routes, what is precommitted, the challenge provider or its absence, the origin's scheme, every credential variable the door reads at startup (origin headers, the log, Splunk, OTel, the capture key, the challenge secret), and the paths. It exits 1 on an error.
51
+
52
+ ## What the door knows about an arrival
53
+
54
+ The door records one fact for every arrival, `arrival`, observed by the door itself, and the policy reads it as `context.facts.arrival`:
55
+
56
+ | field | values | meaning |
57
+ | --- | --- | --- |
58
+ | `class` | `verified`, `claimed`, `unknown` | `verified`: a grant signed by a trusted principal, inside its window, naming this route among its scopes. `claimed`: something was asserted that the door could not accept: a grant from a stranger, an expired one, one for other routes, a declared agent name, or an HTTP signature header. `unknown`: nothing was presented |
59
+ | `subject` | string | the agent named in a verified grant; else the declared name or the agent a rejected grant named; else `unknown`. Only a verified subject reaches the Cedar `principal` |
60
+ | `grant` | `verified`, `out-of-scope`, `invalid`, `absent` | what became of the grant header, with `grantError` when it was not accepted |
61
+ | `signature` | boolean | an RFC 9421 `Signature-Input` header was present. **Not checked yet.** It is a claim |
62
+ | `declared` | string | the `x-agent-custody-agent` header, when sent. A claim |
63
+ | `remote` | string | the arrival's address |
64
+ | `challenge` | `{ provider, outcome, error? }` | only when `challenge` is configured. `passed`: the provider confirmed the token the arrival sent. `failed`: the provider refused the token (`invalid-input-response`, `timeout-or-duplicate`, `expired-input-response`, `already-seen-response`, `missing-input-response`, with the codes in `error`), it confirmed a token issued on another hostname or for another action, or the token was longer than 4096 characters, which is refused without calling the provider. `unavailable`: the provider did not answer in time, answered a non-200, a redirect, or something that is not JSON, answered a code that is its own or the operator's fault (`internal-error`, `bad-request`, `missing-input-secret`, `invalid-input-secret`, `sitekey-secret-mismatch`, `invalid-sitekey`, `missing-sitekey`, `invalid-remoteip`: a rotated secret gives every person one of these), or `maxInFlight` checks were already waiting. `absent`: no token. A passed challenge leaves `class` as it was: it says a provider's test was passed in front of this arrival, not who the arrival is |
65
+ | `rate` | `{ by, burst, minute }` | arrivals from the same source in the last 10 and 60 seconds, this one included, whatever was decided about them, counted by this door process alone. `by` is `agent` for a verified arrival (counted by the agent's name across addresses) or `remote` (by address). A pace, not a verdict |
66
+ | `method`, `path`, `route` | strings | what arrived, and the route it fell under |
67
+
68
+ [Door signals](door-signals.md) says, for each field, what it establishes and what it does not, and how a policy should read it.
69
+
70
+ There is no `human` class. The door cannot tell a person from a program that presents nothing, and it does not pretend to. With `challenge` configured, a policy can require a passed challenge on a route instead; without it, a policy that lets `unknown` through on a route is letting everything through on that route, and should say so.
71
+
72
+ **Presenting a passport.** An agent presents its grant exactly as it does to the HTTP gateway: the DSSE envelope as base64url in `Authorization: Bearer <value>` or in `X-Agent-Custody-Grant`. The scopes of the grant are route names. A grant that travelled in `Authorization` is stripped before the request is relayed, so the origin never sees it; one in the custom header is stripped too. The door's own headers are added to the relayed request: `X-Agent-Custody-Receipt` (the receipt id), `X-Agent-Custody-Class`, and `X-Forwarded-For`, `-Host`, `-Proto`, with `X-Real-IP` when `trustProxy` is off.
73
+
74
+ **A verified arrival is bearer-grade.** The door checks the grant's signature, window, and scope. It does not check that the sender holds the agent's key: there is no request signature yet (RFC 9421 is [future work](#what-it-does-not-do-yet)). Anyone who holds the grant's bytes is that agent until the grant expires, and every verified receipt carries the grant in `delegation`, so a person who can read one receipt can replay its grant. Issue door grants with short lifetimes (minutes, not days), scope them to the routes they need, bound what a route allows per call in the policy, and treat receipt files and logs as holding live credentials until those grants expire.
75
+
76
+ **Challenging a human.** The door builds no CAPTCHA. With `challenge` configured, a page in front of a protected route renders the provider's widget (Cloudflare Turnstile or hCaptcha) with `siteKey`, and sends the token the widget produced in the `challenge.header` header of its request. The door posts the token and the secret from `secretEnv` to the provider's `siteverify` endpoint, with a timeout, and records the answer as `challenge.outcome`. It adds the arrival's address as `remoteip` only with `trustProxy`, where that address is the client's; without it the socket's address may be a proxy's, and the provider would refuse a token the client solved. It never follows a redirect, which would resend the secret and the token elsewhere. To hCaptcha it also sends `siteKey` as `sitekey`: an hCaptcha secret belongs to the account, and without it a token solved on the account's easiest widget would pass on the hardest. A Turnstile secret belongs to one widget already. `success` alone does not pass: the token must have been issued on one of `hostnames`, and for `action` when one is set, or a token solved on another site that uses this site key, or for another widget, would count. At most `maxInFlight` checks wait on the provider at once; an arrival past that is `unavailable`. The token is stripped before the request is relayed, and neither the token nor the secret is recorded. A policy admits a person on a form route with
77
+
78
+ ```cedar
79
+ permit(principal, action == Action::"refund", resource)
80
+ when { context.facts.arrival.challenge.outcome == "passed" };
81
+ ```
82
+
83
+ and a refused arrival that has not passed is told how in the 403 body: `challenge: { provider, siteKey, header }`, so a page can render the widget and try again.
84
+
85
+ **A token serves one request.** Turnstile and hCaptcha refuse a token they have seen (`timeout-or-duplicate`, `already-seen-response`), and the door keeps no pass between requests: it does not set a cookie or remember an address. So the page must take a new token for every request it sends to a challenged route, and for every retry: call `turnstile.reset()` or `hcaptcha.reset()` after each request, and wait for the new token before the next. The door checks the token before it reads the body, so a request refused for its size (413), its path (400), or by the policy has used its token too. A second request that sends the same token is `failed`, and the person sees another 403. The outcome is a signal, not a class: a `verified` agent that also passes a challenge is still the agent its grant names, and an `unknown` arrival that passes is still `unknown`, with `challenge.outcome: "passed"` beside it. What the provider's pass means, and what it does not, is in [door signals](door-signals.md). Passkeys are not a provider here: a passkey proves possession of a credential the site registered, which is a login, not a challenge, and belongs to the origin.
86
+
87
+ ## How an arrival becomes a Cedar request
88
+
89
+ | Cedar slot | value |
90
+ | --- | --- |
91
+ | `principal` | `Agent::"<agent>"` for the agent a verified grant names; `Agent::"unknown"` for every other arrival. A declared name and the agent a rejected grant names stay in the arrival fact: a permit on `principal == Agent::"shopping-agent"` cannot be satisfied by sending a header |
92
+ | `action` | `Action::"<route>"` |
93
+ | `resource` | `Tool::"<route>"` |
94
+ | `context.args` | `{ method, path, query, headers, body?, bodyBytes, bodyDigest }`. `query` holds every parameter by name, as own properties, so `?constructor=x` is a parameter. `headers` carries `user-agent`, `content-type`, `accept`, and `host` only. `body` is present for a JSON body of at most 64 KiB; every body the door read is recorded by `bodyDigest` (sha256 of the raw bytes) and `bodyBytes`. A body above `maxBodyBytes` is dropped as it passes the limit and recorded as `bodyBytes` read so far and `bodyOversized: true`, with no digest and no `body`. The policy reads a copy that Cedar accepts: Cedar has no `null` and no non-integer number, and refuses the whole request on either, so in the copy a `null` member is dropped and a number that is not a safe integer becomes its string (`9.99` becomes `"9.99"`). A rule that compares such a value as a number then errors, and that rule's deny is the answer. The receipt keeps the body as it arrived. **Provenance: claimed** |
95
+ | `context.facts.arrival` | the fact above. **Provenance: observed** |
96
+ | `context.grant` | `{ principal, scopes }`, present only when the arrival is `verified`. **Provenance: attested** |
97
+
98
+ Every rule the gateway's policies obey applies: default deny, `forbid` wins, an evaluation error is a deny, the policy digest is in the receipt. A policy for the shop in the tutorial:
99
+
100
+ ```cedar
101
+ // The catalogue is public: humans, agents, anyone.
102
+ permit(principal, action == Action::"catalogue", resource);
103
+
104
+ // Refunds: a verified agent, in its grant's scope, for a positive amount of at most £50.
105
+ permit(principal, action == Action::"refund", resource)
106
+ when {
107
+ context.facts.arrival.class == "verified" &&
108
+ context.args.body.amount > 0 &&
109
+ context.args.body.amount <= 5000
110
+ };
111
+
112
+ // Everything else on the API is for verified agents.
113
+ permit(principal, action == Action::"api", resource)
114
+ when { context.facts.arrival.class == "verified" };
115
+ ```
116
+
117
+ A refund without a JSON body, with no `amount`, or with an `amount` that is not an integer (`45.5` reaches the policy as `"45.5"`), is an evaluation error and a deny. That is the behaviour you want in front of a payments route. The bound has two ends on purpose: `amount <= 5000` alone admits `{"amount": -1}`, and the door relays the body as it came.
118
+
119
+ A permit that names an agent, `permit(principal == Agent::"shopping-agent", action == Action::"refund", resource)`, admits only an arrival whose verified grant names that agent, since nothing else reaches the principal slot. `agent-custody check` still warns on such a permit when it does not also require `context.facts.arrival.class == "verified"`: the same text in a gateway policy reads differently, and the condition says what the permit relies on.
120
+
121
+ ## Before the origin hears of it
122
+
123
+ A request that can change something at the origin, any method but GET, HEAD, and OPTIONS, and any arrival at a route named in `precommit`, is committed to the log before it is relayed, exactly as the gateway's precommit does for a consequential tool call: the door signs an authorization statement (the receipt without its outcome), appends it, writes it as `receipts/<receiptId>.authorization.json`, and only then relays. The receipt embeds it as `authorization`, and the verifier checks that it names this receipt and sits in the log before it. A door that dies between the relay and the receipt leaves the authorization behind, so the side effect has a record and a retry can be told from a first attempt. If the log will not take the authorization, the request is not relayed: 503 and a `withheld` receipt. In observe mode it is relayed and the missing authorization is printed.
124
+
125
+ ## What the arrival gets back
126
+
127
+ | the door's decision | HTTP | body | receipt `execution.status` |
128
+ | --- | --- | --- | --- |
129
+ | policy allows, origin answered | the origin's status and body, plus the door's headers | the origin's | `executed`, or `failed` when the origin answered 5xx |
130
+ | policy denies, whatever the body's size | 403 | `{ error, reason, receipt }`, plus `challenge: { provider, siteKey, header }` when a challenge is configured and this arrival has not passed it | `denied` |
131
+ | origin unreachable: the connection was refused or the host did not resolve | 502 | `{ error, detail, receipt }`, "the origin could not be reached" | `error`; the request never left the door |
132
+ | the request left, and its answer did not arrive: a timeout, a reset, or a body that stopped after the headers | 504 | `{ error, detail, receipt }`, "the origin may have acted on the request ... Do not retry" | `error`, and `execution.error` says the origin may have acted. Find out from the origin before retrying a refund |
133
+ | policy allows, body above `maxBodyBytes` | 413 | `{ error, reason, receipt }` | `withheld`; nothing was relayed |
134
+ | policy allows, the log refused the authorization | 503 | `{ error, reason, receipt }` | `withheld`; nothing was relayed |
135
+ | policy allows, the path does not decode cleanly | 400 | `{ error, reason, receipt }` | `withheld`; nothing was relayed |
136
+ | policy allows, the origin's response above `maxResponseBytes` | 502 | `{ error, receipt }`, and "do not retry" | `executed` or `failed`: the origin acted; `result` carries the status and `bodyOversized: true`, no digest |
137
+ | the receipt could not be written | 500 | `{ error, outcome, receipt }` | none on disk; `outcome` says whether the origin acted, so that a refund is not retried on the strength of a 500 |
138
+ | more than `maxInFlight` arrivals at once | 503, `Retry-After: 1` | `{ error }` | none: the arrival was not read, decided, or relayed |
139
+
140
+ A redirect from the origin to its own host, on any scheme or port, is rewritten to a path, so the client's next request comes back through the door and is classified again. A path under the origin's path loses that prefix; any other path, including one that `..` takes out of it, is kept as it is. A redirect to another host is relayed as sent. Every `Set-Cookie` the origin sent reaches the client. An `Expect: 100-continue` is the client's conversation with the door, which answers it; the origin does not see the header.
141
+
142
+ Every answer carries `X-Agent-Custody-Receipt` and `X-Agent-Custody-Class`. When the log did not take the receipt, it waits in `receipts/outbox/` and the answer also carries `X-Agent-Custody-Log-Pending: true`; a serving door appends the outbox every 30 seconds, as the gateway does.
143
+
144
+ `GET /.well-known/agent-custody-door` answers the door's key id, the policy digest in force, the version, and the count of pending receipts.
145
+
146
+ ## What a receipt records of the query and the body
147
+
148
+ A query can carry an API key (`?api_key=sk_live_...`) and a JSON body a password. When the config gives a route no `capture` rule, and has no `"*"` rule, the door applies its own private rule to it: `method`, `path`, `headers` (the four above), `bodyBytes`, and `bodyOversized` stay in clear, and the query, the body, and `bodyDigest` leave one salted commitment, `request.args.$rest`, in their place. The policy still decides on the real values, because the rule is applied after the decision, and the receipt still verifies. As under any private rule, the denial reason and the policy's error messages are withheld too; the client's 403 still carries the reason. The facts (the arrival) and the result (the origin's status and digest) stay in clear.
149
+
150
+ To record more in clear, give the route a rule of its own, as for the gateway ([private evidence](configuration.md)): `{ "capture": { "refund": { "args": { "mode": "digest", "clear": ["method", "path", "body"] } } } }` keeps a refund's body in clear, and `{ "capture": { "*": { "args": { "mode": "clear" } } } }` keeps every route's arguments in clear, as before.
151
+
152
+ ## The receipt
153
+
154
+ A door receipt is a v0.2 receipt with `issuer.kind: "door"` and `issuer.framework: "http"`. The route is the tool, observed. `request.args` is the arrival as the table above describes it, claimed. `facts.arrival` is the door's observation. When the arrival was verified, `principal` and `agent` are attested and `delegation` carries the grant; otherwise `principal` is `{ id: null, provenance: "claimed" }` and `agent` is the subject, claimed. `execution.result` for a relayed call is `{ status, contentType?, bodyBytes, bodyDigest }`: the origin's body is never copied into the receipt, only committed to.
155
+
156
+ The verifier runs `door receipt carries a policy decision` in place of the gateway's two checks, and otherwise the same checks: a verified arrival's receipt passes `delegation binds principal and agent` and `executed tool within delegated scope`; an unknown arrival's passes `principal is claimed, not attested`; a receipt that carries an `authorization` passes the authorization checks, including `authorization logged before execution`. Both verifiers, the Python verifier, and `policy simulate` accept door receipts; the conformance vectors `door-unknown-executed`, `door-unknown-denied`, and `door-verified-executed` pin them.
157
+
158
+ ## What it does not do yet
159
+
160
+ - Detect agents in web or API traffic. The only signals are the ones in the arrival fact: `signature` and `declared` are claims, and `rate` is a pace ([door signals](door-signals.md)).
161
+ - Check RFC 9421 HTTP message signatures, Web Bot Auth directories, or AP2 mandates. The grant is the only passport today.
162
+ - Challenge an arrival with a passkey. Turnstile and hCaptcha are the providers; see [challenging a human](#challenging-a-human).
163
+ - Revoke a grant by a revocation list; a grant stands until it expires.
164
+ - Bind a grant to its sender. A verified arrival is bearer-grade: see [presenting a passport](#what-the-door-knows-about-an-arrival).
165
+ - Stream a request body: the body is read whole, up to `maxBodyBytes`, so that the policy can read it and the receipt can commit to it.
166
+ - Relay a response larger than `maxResponseBytes`, or stream one: the body is relayed whole so that its digest can be recorded. A larger one is not held: reading stops at the limit, the client gets 502, and the receipt records that the origin answered.
167
+
168
+ Tutorial: [40-door.ts](../examples/40-door.ts).