@agent-custody/receipts 0.8.0 → 0.9.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.
package/dist/sso.d.ts ADDED
@@ -0,0 +1,47 @@
1
+ export interface OidcConfig {
2
+ issuer: string;
3
+ clientId: string;
4
+ clientSecret: string;
5
+ }
6
+ export interface SamlConfig {
7
+ entryPoint: string;
8
+ idpCert: string;
9
+ idpIssuer?: string;
10
+ }
11
+ export interface SsoIdentity {
12
+ subject: string;
13
+ email: string;
14
+ }
15
+ export declare function pkce(): {
16
+ verifier: string;
17
+ challenge: string;
18
+ };
19
+ export declare function oidcAuthorizeUrl(c: OidcConfig, o: {
20
+ redirectUri: string;
21
+ state: string;
22
+ nonce: string;
23
+ codeChallenge: string;
24
+ fetch?: typeof fetch;
25
+ }): Promise<string>;
26
+ export declare function oidcExchange(c: OidcConfig, o: {
27
+ code: string;
28
+ redirectUri: string;
29
+ codeVerifier: string;
30
+ nonce: string;
31
+ fetch?: typeof fetch;
32
+ now?: number;
33
+ }): Promise<SsoIdentity>;
34
+ export declare function samlAuthorizeUrl(c: SamlConfig, o: {
35
+ spEntityId: string;
36
+ acsUrl: string;
37
+ relayState?: string;
38
+ }): Promise<{
39
+ url: string;
40
+ requestId: string;
41
+ }>;
42
+ export declare function samlValidate(c: SamlConfig, o: {
43
+ spEntityId: string;
44
+ acsUrl: string;
45
+ samlResponse: string;
46
+ requestId: string;
47
+ }): Promise<SsoIdentity>;
package/dist/sso.js ADDED
@@ -0,0 +1,161 @@
1
+ // Enterprise sign-in for the portal: OIDC (code + PKCE) and SAML 2.0. The caller checks the email domain.
2
+ import { createHash, createPublicKey, randomBytes, verify as cryptoVerify } from "node:crypto";
3
+ import { createRequire } from "node:module";
4
+ const SKEW_SECONDS = 60;
5
+ const CACHE_MS = 3_600_000;
6
+ const b64url = (b) => b.toString("base64url");
7
+ export function pkce() {
8
+ const verifier = b64url(randomBytes(32));
9
+ return { verifier, challenge: b64url(createHash("sha256").update(verifier).digest()) };
10
+ }
11
+ const discoveries = new Map();
12
+ const keySets = new Map();
13
+ const getJson = async (f, url, what) => {
14
+ const r = await f(url, { headers: { accept: "application/json" }, redirect: "error", signal: AbortSignal.timeout(10_000) });
15
+ if (!r.ok)
16
+ throw new Error(`${what} answered HTTP ${r.status}`);
17
+ return r.json();
18
+ };
19
+ const httpsUrl = (u, what) => {
20
+ if (typeof u !== "string" || !URL.canParse(u) || new URL(u).protocol !== "https:")
21
+ throw new Error(`${what} must be an https URL`);
22
+ return u;
23
+ };
24
+ async function discover(c, f) {
25
+ httpsUrl(c.issuer, "the OIDC issuer");
26
+ const hit = discoveries.get(c.issuer);
27
+ if (hit && Date.now() - hit.at < CACHE_MS)
28
+ return hit.doc;
29
+ const doc = (await getJson(f, `${c.issuer.replace(/\/$/, "")}/.well-known/openid-configuration`, "OIDC discovery"));
30
+ if (doc.issuer !== c.issuer)
31
+ throw new Error("the OIDC discovery document names a different issuer");
32
+ for (const k of ["authorization_endpoint", "token_endpoint", "jwks_uri"])
33
+ httpsUrl(doc[k], `the OIDC ${k}`);
34
+ discoveries.set(c.issuer, { at: Date.now(), doc });
35
+ return doc;
36
+ }
37
+ async function jwks(c, d, f, fresh) {
38
+ const hit = keySets.get(c.issuer);
39
+ if (hit && !fresh && Date.now() - hit.at < CACHE_MS)
40
+ return hit.keys;
41
+ const keys = (await getJson(f, d.jwks_uri, "OIDC key set")).keys;
42
+ if (!Array.isArray(keys))
43
+ throw new Error("the OIDC key set has no keys");
44
+ keySets.set(c.issuer, { at: Date.now(), keys });
45
+ return keys;
46
+ }
47
+ export async function oidcAuthorizeUrl(c, o) {
48
+ const d = await discover(c, o.fetch ?? fetch);
49
+ const u = new URL(d.authorization_endpoint);
50
+ const q = { response_type: "code", client_id: c.clientId, redirect_uri: o.redirectUri, scope: "openid email profile", state: o.state, nonce: o.nonce, code_challenge: o.codeChallenge, code_challenge_method: "S256" };
51
+ for (const [k, v] of Object.entries(q))
52
+ u.searchParams.set(k, v);
53
+ return u.toString();
54
+ }
55
+ async function verifySignature(c, d, f, token) {
56
+ const parts = token.split(".");
57
+ const [h, p, s] = parts;
58
+ if (parts.length !== 3 || !h || !p || !s)
59
+ throw new Error("the id_token is not a JWS");
60
+ const header = JSON.parse(Buffer.from(h, "base64url").toString());
61
+ const kty = { RS256: "RSA", ES256: "EC" }[header.alg];
62
+ if (!kty)
63
+ throw new Error(`the id_token algorithm ${String(header.alg)} is not accepted; use RS256 or ES256`);
64
+ const candidates = (keys) => keys.filter((k) => k.kty === kty && (!k.use || k.use === "sig") && (!header.kid || k.kid === header.kid));
65
+ let found = candidates(await jwks(c, d, f, false));
66
+ if (!found.length)
67
+ found = candidates(await jwks(c, d, f, true)); // rotated keys
68
+ if (!found.length)
69
+ throw new Error("no key in the OIDC key set matches the id_token");
70
+ const ok = found.some((k) => {
71
+ if (header.alg === "ES256" && k.crv !== "P-256")
72
+ return false;
73
+ const key = createPublicKey({ key: k, format: "jwk" });
74
+ return cryptoVerify("sha256", Buffer.from(`${h}.${p}`), header.alg === "ES256" ? { key, dsaEncoding: "ieee-p1363" } : key, Buffer.from(s, "base64url"));
75
+ });
76
+ if (!ok)
77
+ throw new Error("the id_token signature is not valid");
78
+ return JSON.parse(Buffer.from(p, "base64url").toString());
79
+ }
80
+ export async function oidcExchange(c, o) {
81
+ const f = o.fetch ?? fetch;
82
+ const d = await discover(c, f);
83
+ const r = await f(d.token_endpoint, {
84
+ method: "POST",
85
+ headers: { accept: "application/json", "content-type": "application/x-www-form-urlencoded" },
86
+ body: new URLSearchParams({ grant_type: "authorization_code", code: o.code, redirect_uri: o.redirectUri, client_id: c.clientId, client_secret: c.clientSecret, code_verifier: o.codeVerifier }),
87
+ redirect: "error",
88
+ signal: AbortSignal.timeout(10_000),
89
+ });
90
+ const tok = (await r.json().catch(() => ({})));
91
+ if (!r.ok || !tok.id_token)
92
+ throw new Error(`the OIDC token endpoint refused the code (HTTP ${r.status}${tok.error ? `, ${tok.error}` : ""})`);
93
+ const claims = await verifySignature(c, d, f, tok.id_token);
94
+ const now = (o.now ?? Date.now()) / 1000;
95
+ const aud = [claims.aud].flat();
96
+ if (claims.iss !== c.issuer)
97
+ throw new Error("the id_token issuer is not the configured issuer");
98
+ if (!aud.includes(c.clientId))
99
+ throw new Error("the id_token audience does not include this client");
100
+ if (aud.length > 1 && claims.azp !== c.clientId)
101
+ throw new Error("the id_token has several audiences and its azp is not this client");
102
+ if (typeof claims.exp !== "number" || claims.exp + SKEW_SECONDS <= now)
103
+ throw new Error("the id_token has expired");
104
+ if (typeof claims.iat === "number" && claims.iat - SKEW_SECONDS > now)
105
+ throw new Error("the id_token is issued in the future");
106
+ if (claims.nonce !== o.nonce)
107
+ throw new Error("the id_token nonce does not match this sign-in");
108
+ if (typeof claims.sub !== "string" || !claims.sub)
109
+ throw new Error("the id_token has no sub claim");
110
+ if (typeof claims.email !== "string" || !claims.email.includes("@"))
111
+ throw new Error("the id_token has no email claim");
112
+ // Many enterprise IdPs omit email_verified.
113
+ if (claims.email_verified === false)
114
+ throw new Error("the provider says the email address is not verified");
115
+ return { subject: claims.sub, email: claims.email.toLowerCase() };
116
+ }
117
+ // Never verify XML signatures by hand: node-saml does it.
118
+ const EMAIL_CLAIM = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress";
119
+ const EMAIL_FORMAT = "urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress";
120
+ function samlClient(c, sp, requestId) {
121
+ let lib;
122
+ try {
123
+ lib = createRequire(import.meta.url)("@node-saml/node-saml");
124
+ }
125
+ catch (cause) {
126
+ if (cause.code !== "MODULE_NOT_FOUND")
127
+ throw cause;
128
+ throw new Error("SAML sign-in needs the optional package @node-saml/node-saml; install it beside @agent-custody/receipts", { cause });
129
+ }
130
+ return new lib.SAML({
131
+ entryPoint: c.entryPoint, idpCert: c.idpCert, issuer: sp.spEntityId, callbackUrl: sp.acsUrl, audience: sp.spEntityId,
132
+ wantAssertionsSigned: true, wantAuthnResponseSigned: false,
133
+ acceptedClockSkewMs: SKEW_SECONDS * 1000, signatureAlgorithm: "sha256", generateUniqueId: () => requestId,
134
+ });
135
+ }
136
+ export async function samlAuthorizeUrl(c, o) {
137
+ const requestId = `_${randomBytes(20).toString("hex")}`;
138
+ return { url: await samlClient(c, o, requestId).getAuthorizeUrlAsync(o.relayState ?? "", undefined, {}), requestId };
139
+ }
140
+ export async function samlValidate(c, o) {
141
+ const { profile } = await samlClient(c, o, o.requestId).validatePostResponseAsync({ SAMLResponse: o.samlResponse });
142
+ if (!profile?.nameID)
143
+ throw new Error("the SAML response has no NameID");
144
+ // Only the assertion is signed: the Response's InResponseTo proves nothing.
145
+ const assertion = profile.getAssertion().Assertion;
146
+ if (c.idpIssuer && profile.issuer !== c.idpIssuer)
147
+ throw new Error("the SAML assertion issuer is not the configured IdP");
148
+ const bearer = (assertion.Subject?.[0]?.SubjectConfirmation ?? [])
149
+ .filter((s) => s.$?.Method === "urn:oasis:names:tc:SAML:2.0:cm:bearer")
150
+ .flatMap((s) => s.SubjectConfirmationData ?? []);
151
+ const bound = bearer.some((d) => d.$?.InResponseTo === o.requestId && d.$?.Recipient === o.acsUrl && Date.parse(d.$?.NotOnOrAfter) + SKEW_SECONDS * 1000 > Date.now());
152
+ if (!bound)
153
+ throw new Error("the SAML assertion is not an answer to this sign-in request");
154
+ if (!assertion.Conditions?.[0]?.$?.NotOnOrAfter)
155
+ throw new Error("the SAML assertion has no validity period");
156
+ const attr = (name) => [profile.attributes?.[name]].flat()[0];
157
+ const email = [attr("email"), attr(EMAIL_CLAIM), profile.nameIDFormat === EMAIL_FORMAT ? profile.nameID : undefined].find((e) => typeof e === "string" && e.includes("@"));
158
+ if (!email)
159
+ throw new Error("the SAML assertion has no email address");
160
+ return { subject: profile.nameID, email: email.toLowerCase() };
161
+ }
package/dist/verify.js CHANGED
@@ -118,13 +118,15 @@ export function structuralProblem(p) {
118
118
  return "receiptId or timestamp is not a string";
119
119
  if (!isObject(p.issuer) || !isObject(p.principal) || !isObject(p.agent) || !isObject(p.session) || !isObject(p.model))
120
120
  return "issuer, principal, agent, session, or model is not an object";
121
+ if (p.principal.provenance === "attested" && typeof p.principal.keyid !== "string")
122
+ return "an attested principal has no keyid";
121
123
  if (!isObject(p.tool) || typeof p.tool.name !== "string")
122
124
  return "tool.name is not a string";
123
125
  if (!isObject(p.request) || typeof p.request.argsDigest !== "string" || !isObject(p.request.args))
124
126
  return "request.args or request.argsDigest is not what it should be";
125
127
  if (!isObject(p.execution) || typeof p.execution.status !== "string" || !["executed", "failed", "denied", "error", "withheld"].includes(p.execution.status))
126
128
  return "execution.status is not a status";
127
- if (p.policy !== null && (!isObject(p.policy) || (p.policy.decision !== "allow" && p.policy.decision !== "deny") || !Array.isArray(p.policy.reasons)))
129
+ if (p.policy !== null && (!isObject(p.policy) || (p.policy.decision !== "allow" && p.policy.decision !== "deny") || !Array.isArray(p.policy.reasons) || typeof p.policy.policyDigest !== "string"))
128
130
  return "policy is neither null nor a decision";
129
131
  if (!isObject(p.facts) || Object.values(p.facts).some((f) => !isObject(f) || typeof f.tool !== "string"))
130
132
  return "facts is not a map of facts";
@@ -132,7 +134,7 @@ export function structuralProblem(p) {
132
134
  return "consumed is not an object";
133
135
  if (p.delegation !== undefined && (!isObject(p.delegation) || !isObject(p.delegation.envelope)))
134
136
  return "delegation is not a signed envelope";
135
- if (p.authorization !== undefined && (!isObject(p.authorization) || !isObject(p.authorization.envelope)))
137
+ if (p.authorization !== undefined && (!isObject(p.authorization) || !isObject(p.authorization.envelope) || !isObject(p.authorization.treeHead) || !isObject(p.authorization.inclusion)))
136
138
  return "authorization is not a bundle";
137
139
  if (p.approval !== undefined) {
138
140
  const a = p.approval;
@@ -0,0 +1,132 @@
1
+ # A real Codex agent, a wrong plan, and recovery
2
+
3
+ The model handles a support request using MCP tools behind the custody gateway. The CRM import deliberately says `enterprise` when the account is actually on `free`. Codex decides whether to record benefits and issue a simulated service credit. An operator then introduces the correction, traces potentially affected actions and beliefs, reviews a recovery plan, and explicitly approves compensation.
4
+
5
+ The support calls come from `codex exec`, not a handwritten tool sequence. The correction and recovery are operator commands. Billing is a persistent local stand-in, not Stripe; a reversal compensates a simulated credit and preserves the original record. No real money moves.
6
+
7
+ See the [recorded live run](../../state/examples/codex-recovery/SAMPLE-RUN.md) for an actual result, including the final verification of 13 receipts.
8
+
9
+ ## Before running
10
+
11
+ Use Node 22 with native TypeScript support (or later), Bun, and a Codex CLI that supports `exec`, MCP, `--ignore-user-config`, and `--ephemeral`. Tested with Node 24 and codex-cli 0.163.0. Codex needs working authentication and model access; use `codex login` if needed. An existing ChatGPT login works; an API key is not required when that login is available. Live runs consume the account's normal model usage and require network access to the model.
12
+
13
+ From the repository root:
14
+
15
+ ```sh
16
+ bun install --frozen-lockfile
17
+ bun run build
18
+ codex login status
19
+ ```
20
+
21
+ ## Run the support task
22
+
23
+ ```sh
24
+ cd packages/state
25
+ node examples/codex-recovery/run.ts run
26
+ ```
27
+
28
+ Optionally select a model your Codex account supports:
29
+
30
+ ```sh
31
+ node examples/codex-recovery/run.ts run --model <model>
32
+ ```
33
+
34
+ The runner creates a fresh `examples-out/codex-recovery-*/case/` directory and prints its path. It imports the wrong plan, launches Codex with a task and business policy, waits up to three minutes, then simulates the operator learning about the CRM bug. The operator revokes the support grant, retracts the wrong plan, and writes `plan = free`. The runner verifies the receipts and prints a proposed recovery plan. It stops before applying that plan.
35
+
36
+ The expected story is:
37
+
38
+ ```text
39
+ CRM import: enterprise
40
+ → Codex reads the account memory
41
+ → Codex may record discount 20 / priority support and issue a 2500-pence credit
42
+ → Operator corrects the plan to free and retires the support grant
43
+ → Review possible dependencies and proposed recovery
44
+ → Explicit approval: correct stale benefits and reverse the simulated credit
45
+ → Check current state and all signed receipts
46
+ ```
47
+
48
+ The agent can decline, perform fewer actions, or encounter an error. Read `agent-answer.txt` and `codex-events.jsonl` to see what actually happened. The runner does not retry until the desired mistake appears or replace a failed model run with scripted calls. The plan reports `agentCalls` and `exposed`; zero gateway activity is explicitly labelled as not demonstrating an agent workflow. A credit without an observed dependency on the plan requires manual review rather than automatic recovery.
49
+
50
+ ## Review and recover
51
+
52
+ Read `recovery-plan.json`. It names the exact beliefs to retract, corrected values to write, and simulated credits to reverse. The plan digest binds approval to those actions and the observed state. Changes after review invalidate it.
53
+
54
+ Copy the `recover` command printed by the runner, or use:
55
+
56
+ ```sh
57
+ node examples/codex-recovery/run.ts recover \
58
+ --dir /absolute/path/to/case \
59
+ --approve <printed-plan-digest>
60
+ ```
61
+
62
+ For the typical enterprise-to-free run, expect:
63
+
64
+ - Current plan: `free`; discount: `0`; support tier: `standard`.
65
+ - Original simulated credit: preserved, with status `reversed` and its reversal receipt ID.
66
+ - Original beliefs: retained in history, with receipted retractions.
67
+ - `receiptsVerified` includes the original calls, correction, and recovery.
68
+ - The command ends with `OK: recovery complete; evidence verified.`
69
+
70
+ Repeat verification without issuing tool calls:
71
+
72
+ ```sh
73
+ node examples/codex-recovery/run.ts verify --dir /absolute/path/to/case
74
+ ```
75
+
76
+ To refresh a plan after intervening activity or a partially completed recovery:
77
+
78
+ ```sh
79
+ node examples/codex-recovery/run.ts inspect --dir /absolute/path/to/case
80
+ ```
81
+
82
+ If Codex fails, its artifacts remain. Check `codex-stderr.log` and `codex-events.jsonl`. To continue an operator investigation of that failed run, use `correct --dir /absolute/path/to/case`, then inspect its actual evidence. A new `run` always creates a separate case. Demo grants last 24 hours; after expiration, inspect/verify still work, but recovery needs newly issued operator authority.
83
+
84
+ ## Demo commands and flags
85
+
86
+ These commands belong to the example runner, not the published `agent-custody` or `agent-custody-memory` CLI. Run them from `packages/state` as `node examples/codex-recovery/run.ts <command>`.
87
+
88
+ | Command | Flags | Behavior |
89
+ | --- | --- | --- |
90
+ | `run` | optional `--model <model>` | Creates a fresh case, runs Codex, introduces the operator correction, and saves a recovery plan; stops before recovery |
91
+ | `correct` | required `--dir <case>` | Revokes support authority, retracts the wrong plan, records the corrected plan, and saves a recovery plan; useful after a failed agent run |
92
+ | `inspect` | required `--dir <case>` | Verifies existing evidence and saves a fresh plan and approval digest without issuing tool calls |
93
+ | `recover` | required `--dir <case>` and `--approve <digest>` | Rejects a changed plan or state; applies the reviewed recovery, saves the verification report, and prints `OK` on success |
94
+ | `verify` | required `--dir <case>` | Checks evidence and current recovery state without issuing tool calls; prints the report and exits nonzero if recovery is incomplete |
95
+ | `help` | none | Lists the example runner's commands |
96
+
97
+ Here `--approve` is an explicit confirmation by the local operator running the command. The digest covers the reviewed plan and snapshot; it is not a separate cryptographically signed human-approval artifact. The gateway's [payload-bound human approvals](approvals.md) are a different feature. Recovery calls still use the operator's signed delegation grant and receive signed gateway receipts; the recovery-plan digest is included in retraction and credit-reversal reasons.
98
+
99
+ ## What to inspect
100
+
101
+ | Artifact | What it tells you |
102
+ | --- | --- |
103
+ | `prompt.txt`, `codex-command.json` | The actual task and Codex invocation |
104
+ | `codex-events.jsonl`, `agent-answer.txt`, `agent-run.json` | Model events, final answer, and whether the live process completed |
105
+ | `ledger.jsonl` | Original beliefs, corrections, and retractions |
106
+ | `receipts/`, `log.jsonl`, `keys/*.pub` | Signed calls, precommitted billing authorizations, and verification material |
107
+ | `billing.json` | Simulated credits and compensation, linked to receipt IDs |
108
+ | `recovery-plan.json`, `approval.json`, `verification.json` | Reviewed actions, explicit approval, and final verification result |
109
+
110
+ The verifier checks receipt signatures, delegation, inclusion in the local log, signed upstream results, and consistency of the demo stores with those receipts. All demo keys and the log live on the same machine: this is a workflow demonstration, not evidence against a malicious operator controlling that machine.
111
+
112
+ ## Boundaries
113
+
114
+ - Blast radius records prior exposure in a gateway session. It does not prove that the model reasoned from a fact or that the fact caused an action.
115
+ - A verified receipt authenticates recorded evidence, not the truth of the customer's plan or correctness of a business decision.
116
+ - The gateway caps credits and confines writes to this account's benefits. Entitlement is intentionally left to the agent in this incident; a production policy could independently check it and prevent the credit.
117
+ - Codex runs with read-only shell sandbox settings, shell tools disabled, web search disabled, and user-configured apps/plugins disabled. Its MCP server is required and configured for this invocation only. Calls to this local demo server are preapproved in Codex; the gateway still enforces the grant and Cedar policy. The gateway owns the signing keys and the billing service; the model is not given them as tool data. These settings demonstrate controlled tool access, not adversarial OS isolation of an untrusted process.
118
+ - Recovery is deliberately limited to the two benefit predicates and simulated service credits in this case. Real refunds, customer communications, downstream caches, and model context need their own recovery decisions.
119
+ - Run operator commands sequentially for one case. The plan freshness check is not a transactional lock against concurrent operators.
120
+
121
+ ## Offline regression coverage
122
+
123
+ The regular suite never calls Codex or the network. It drives the same MCP servers and recovery functions with scripted calls, clearly labelled as scripted:
124
+
125
+ ```sh
126
+ node examples/10-support-recovery.ts
127
+ bun run test test/codex-recovery.test.ts test/examples.test.ts
128
+ ```
129
+
130
+ The checks cover approval, stale plans, revoked support authority, duplicate-credit prevention, receipt tampering, store/evidence consistency, missing observed dependencies, and runs without agent activity.
131
+
132
+ Codex integration references: [non-interactive mode](https://learn.chatgpt.com/docs/non-interactive-mode), [MCP configuration](https://learn.chatgpt.com/docs/extend/mcp?surface=cli).
@@ -0,0 +1,224 @@
1
+ # Configuring the gateway
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).
4
+
5
+ ## What you configure, and where
6
+
7
+ | what | file | written by | decides |
8
+ | --- | --- | --- | --- |
9
+ | **The grant** | `<agent>.grant.json`, signed | the principal (the person or organisation delegating), with `agent-custody grant` | which agent may use which tool names, until when |
10
+ | **The policy** | `policy.cedar` | the operator or security owner | whether this particular call, with these arguments and these facts, is allowed |
11
+ | **The gateway config** | `gateway.json` | the operator | where the tools live (the upstreams), what the gateway looks up for itself (facts), which tools are consequential (`precommit`), where receipts and the log go |
12
+ | **Credentials** | environment variables | the operator | the tokens the gateway uses to reach the tools; never in a file, never in an agent |
13
+
14
+ The agent configures none of them. It connects to the gateway as an MCP server, presents its grant, and sees only the tools the grant names.
15
+
16
+ A complete, usable layout, one config directory with a policy, is in [deploy/gateway/example](https://github.com/svayatta/agent-custody/tree/main/deploy/gateway/example).
17
+
18
+ ## How a call is decided
19
+
20
+ For each call, in this order, and a refusal at any step is a signed receipt:
21
+
22
+ 1. **The grant** is valid, signed by a trusted principal, inside its window, and not revoked.
23
+ 2. **The tool** is one of the grant's scopes.
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.
26
+ 5. **For `precommit` tools**, the authorization is committed to the log before anything is forwarded.
27
+ 6. **The call** is forwarded to the upstream that owns the tool.
28
+
29
+ The one thing that ties all of it together is the **tool name**. The grant's scopes, the policy's `action == Action::"..."`, `facts`, and `precommit` all name the tools the upstreams offer, so a name that is spelled differently in one place is a rule that never applies.
30
+
31
+ ## Tool names
32
+
33
+ - A **REST** upstream's tool names are the ones you give them in `tools[].name`.
34
+ - An **A2A** agent offers `<prefix>.send` and `<prefix>.card`, with the prefix you choose.
35
+ - An **MCP** server (stdio or HTTP) offers whatever names the server defines. Run `agent-custody check --config gateway.json --connect` to print them.
36
+ - **One owner per tool.** If two upstreams offer the same name the gateway refuses to start. Give REST and A2A tools a prefix (`billing.refund`, `docs.send`) and the collision cannot happen.
37
+
38
+ ## A worked example: two agents, one shared gateway
39
+
40
+ A support agent may look customers up and refund them up to 1,000.00, and only for customers the gateway itself found to be verified. A reporting agent may only read. Both reach the same tools through one gateway.
41
+
42
+ **1. The principal issues one grant per agent.** On the principal's machine, with a key that never goes near the gateway:
43
+
44
+ ```bash
45
+ agent-custody grant --key principal.key --principal acme-support --agent support-agent \
46
+ --scopes customer.lookup,billing.refund,kb.search,docs.send --ttl-hours 8 --out support-agent.grant.json
47
+ agent-custody grant --key principal.key --principal acme-support --agent report-agent \
48
+ --scopes customer.lookup,kb.search --ttl-hours 8 --out report-agent.grant.json
49
+ ```
50
+
51
+ The grants limit *which tools*. The report agent's grant has no `billing.refund`, so it never sees that tool and the policy is not even asked.
52
+
53
+ **2. The operator writes one policy for both.** It limits *how* a tool may be used:
54
+
55
+ ```cedar
56
+ // anything in a grant's scopes may read
57
+ permit(principal, action == Action::"customer.lookup", resource);
58
+ permit(principal, action == Action::"kb.search", resource);
59
+
60
+ // refunds: only the support agent, a positive amount of at most 1,000.00 (integer minor units), and only for a
61
+ // customer the gateway itself found to be verified. The gateway does not enforce a tool's inputSchema, so the policy
62
+ // bounds the amount from below as well. context.facts comes from the gateway's own lookup, never from the agent.
63
+ permit(principal == Agent::"support-agent", action == Action::"billing.refund", resource)
64
+ when {
65
+ context.args.amount > 0 &&
66
+ context.args.amount <= 100000 &&
67
+ context.facts has customer &&
68
+ context.facts.customer.verified == true
69
+ };
70
+
71
+ // delegating a task to the docs agent: the support agent only
72
+ permit(principal == Agent::"support-agent", action == Action::"docs.send", resource);
73
+ ```
74
+
75
+ **3. The operator writes the gateway config.** One file, four kinds of upstream, one remote log:
76
+
77
+ ```json
78
+ {
79
+ "identity": { "keyFile": "/data/keys/gateway.key" },
80
+ "upstreams": [
81
+ {
82
+ "name": "billing",
83
+ "rest": {
84
+ "baseUrl": "https://billing.internal.example.com",
85
+ "headerEnv": { "authorization": "BILLING_API_AUTHORIZATION" },
86
+ "tools": [
87
+ { "name": "customer.lookup", "method": "GET", "path": "/v1/customers/{customer_id}",
88
+ "inputSchema": { "type": "object", "properties": { "customer_id": { "type": "string" } }, "required": ["customer_id"] } },
89
+ { "name": "billing.refund", "method": "POST", "path": "/v1/refunds",
90
+ "description": "Refund a customer. amount is in minor units.",
91
+ "inputSchema": { "type": "object", "properties": { "customer_id": { "type": "string" }, "amount": { "type": "integer" } }, "required": ["customer_id", "amount"] } }
92
+ ]
93
+ }
94
+ },
95
+ { "name": "github", "url": "https://mcp.internal.example.com/github", "tokenEnv": "GITHUB_MCP_TOKEN" },
96
+ { "name": "kb", "command": "kb-mcp-server", "args": ["--root", "/srv/kb"], "env": { "KB_MODE": "read-only" } },
97
+ { "name": "docs", "a2a": { "url": "https://docs-agent.internal.example.com", "headerEnv": { "authorization": "DOCS_AGENT_BEARER" }, "prefix": "docs" } }
98
+ ],
99
+ "trustedPrincipalKeys": ["keys/principal.pub"],
100
+ "policyFile": "policy.cedar",
101
+ "facts": [
102
+ { "name": "customer", "tool": "customer.lookup", "args": { "customer_id": "$args.customer_id" }, "forTools": ["billing.refund"] }
103
+ ],
104
+ "precommit": ["billing.refund", "docs.send"],
105
+ "revokedGrants": "/data/revoked.json",
106
+ "receiptsDir": "/data/receipts",
107
+ "log": { "url": "https://log.agent-custody.dev/t/acme/", "tokenEnv": "AGENT_CUSTODY_LOG_TOKEN", "hashOnly": true, "keys": ["keys/log.pub"] }
108
+ }
109
+ ```
110
+
111
+ What each part does:
112
+
113
+ | key | what it says here |
114
+ | --- | --- |
115
+ | `identity.keyFile` | the gateway's signing key, in `/data` because the gateway writes and keeps it. Verifiers check receipts against its public half. |
116
+ | `upstreams` | four tool sources behind one gateway: a REST API described as tools, an MCP server over HTTP, an MCP server the gateway starts, and another agent over A2A. |
117
+ | `…headerEnv`, `tokenEnv` | the **name** of an environment variable holding the credential. The gateway reads it at startup and refuses to start without it. The secret is never in the file. |
118
+ | `kb.env` | what the started MCP server gets. A stdio upstream gets a minimal environment and nothing of the gateway's own, so it cannot read the other upstreams' tokens. |
119
+ | `trustedPrincipalKeys` | the public keys whose grants this gateway accepts. Only public keys go here. |
120
+ | `facts` | before a refund, the gateway calls `customer.lookup` itself with the customer id from the call, and the policy reads the answer as `context.facts.customer`. |
121
+ | `precommit` | the consequential tools: the gateway commits the authorization to the log before it forwards, and withholds the call if the log will not take it. |
122
+ | `revokedGrants` | the file `agent-custody revoke` appends to; the gateway re-reads it on every call. |
123
+ | `receiptsDir`, `log` | full receipts stay on the gateway's disk. The hosted log receives only their hashes (`hashOnly`), and its public key is pinned (`keys`), which `precommit` with a remote log requires. |
124
+
125
+ Paths in `gateway.json` are resolved relative to the file, so `keys/principal.pub` sits beside it, and absolute paths are left as they are.
126
+
127
+ **4. Each agent presents its own grant** when it connects: the grant file, base64url-encoded, as `Authorization: Bearer <value>` or `X-Agent-Custody-Grant`. [The gateway guide](usage.md#one-gateway-for-many-agents-over-http) and [wiring it into an agent host](usage.md#wiring-it-into-an-agent-host) show how for each host. Adding a third agent is issuing it a grant. The gateway config does not change.
128
+
129
+ **Retries and money.** This config does not use `operations`, so the gateway cannot tell a retry from a second refund: an agent that repeats `billing.refund` after a timeout sends a second POST. For real money, configure [financial operations](financial-operations.md): each refund gets a durable identity and an idempotency key your API must honor, its amount is reserved against a daily budget before it is forwarded, and an uncertain outcome is closed by reading your API's own record. It needs the calling agent to send a persistent operation id in the call's `_meta`, an API that honors the idempotency key, and a read tool that returns the refund by that key.
130
+
131
+ ## The principal's key
132
+
133
+ A grant is only as good as the key that signed it, so this is the key to handle with the most care. There are several keys in a deployment, and they are different:
134
+
135
+ | key | who holds the private half | what the public half is for |
136
+ | --- | --- | --- |
137
+ | **The principal's key** | the person or organisation delegating authority, on their own machine | the gateway's `trustedPrincipalKeys`: it recognises a grant as genuine because this key signed it. A verifier also takes it, as `--principal-key`. |
138
+ | **The gateway's key** | the gateway only, in `/data/keys` | verifiers check receipts against it (`--issuer-key`) |
139
+ | **The log's key** | the log's signer | a verifier or a gateway pins it (`log.keys`, `--log-key`) |
140
+
141
+ **Make it where grants are issued, not where the gateway runs.**
142
+
143
+ ```bash
144
+ agent-custody keygen --dir ./principal --name principal
145
+ ```
146
+
147
+ This writes `principal.key`, the private key, in PEM (PKCS#8) with mode 0600, and `principal.pub`, the public key, in PEM (SPKI), and prints the **key id**, the sha256 of the public key. Write the key id down: it is how you confirm, after copying, that the gateway holds the key you made.
148
+
149
+ **Keep the private key off the gateway.** The gateway never needs it, and a gateway that held it would let anyone who broke into the gateway sign grants for any agent and any tool. So `principal.key` does not go in the gateway's config directory, the image, a ConfigMap, the repository, or CI. Keep it on the machine of whoever issues grants, on an encrypted disk or in a password or secrets manager, and back it up encrypted. `agent-custody grant --key principal.key` reads it from a file, so run that command where the file is.
150
+
151
+ **Give the gateway the public key only.** Copy `principal.pub` into the gateway's config and list it:
152
+
153
+ ```json
154
+ "trustedPrincipalKeys": ["keys/principal.pub"]
155
+ ```
156
+
157
+ In the Docker image that is `/config/keys/principal.pub`, mounted read-only; on Kubernetes it can sit in the ConfigMap, because it is public. List several keys to trust several principals: a grant is accepted when any listed key signed it, and one gateway can serve more than one organisation. A grant signed by a key that is not listed is refused when the agent connects (`delegation grant rejected`). The `--principal` name in a grant (`acme-support`) is only a label that receipts record; the trust is in the key.
158
+
159
+ **Rotating it.** The gateway reads `trustedPrincipalKeys` when it starts, so a rotation is: make the new key pair; add the new public key to the list beside the old one and restart the gateway; issue new grants with the new key; when the old key's grants have expired or been revoked (grants last hours, so this is short), remove the old public key and restart. Verifiers need the new `--principal-key` as well, and accept both while old receipts matter.
160
+
161
+ **If it is lost,** nothing already issued stops working, but no new grant can be signed: make a new pair and add its public key as above. **If it leaks,** remove its public key from `trustedPrincipalKeys` and restart the gateway, which ends open sessions and refuses every grant it signed from then on, and revoke any grant you want refused before that (`agent-custody revoke`). Then make a new pair.
162
+
163
+ `agent-custody init` in the Docker image writes a *demo* principal key under `/config/demo` so that you can try the gateway in a minute. Delete that directory before production, and make the real key where grants are issued.
164
+
165
+ ## In the Docker image
166
+
167
+ The same `gateway.json` works in the [gateway image](https://github.com/svayatta/agent-custody/blob/main/deploy/gateway/README.md), with these rules:
168
+
169
+ - **Mount the config read-only at `/config`** (`gateway.json`, `policy.cedar`, and the principals' and log's **public** keys) and a **volume at `/data`**. Relative paths in the file resolve against `/config`.
170
+ - **Anything the gateway writes needs an absolute path under `/data`**: the key, `receiptsDir`, `logFile`, `revokedGrants`. `/config` is read-only, so `"receiptsDir": "receipts"` fails.
171
+ - **Credentials come from the container's environment** (`--env-file`, a compose `.env`, a Kubernetes Secret), under the variable names the config gives.
172
+ - **The gateway key is created on the first start** at the path `identity.keyFile` names, if the file is absent. Keep the volume.
173
+ - **REST, A2A, and MCP-over-HTTP upstreams work as they are.** A **stdio** MCP server (`command`) has to be inside the image. Build on it:
174
+
175
+ ```dockerfile
176
+ FROM ghcr.io/svayatta/agent-custody-gateway:<version>
177
+ USER root
178
+ RUN npm install -g kb-mcp-server
179
+ USER custody
180
+ ```
181
+
182
+ - `docker run ... <image> init` writes a starter config into an empty `/config`. [The gateway README](https://github.com/svayatta/agent-custody/blob/main/deploy/gateway/README.md) has the whole run, and the limits of a shared gateway.
183
+
184
+ ## Check it before you start it
185
+
186
+ `agent-custody check --config gateway.json` reads the config the way the gateway would and reports what would go wrong at startup:
187
+
188
+ ```bash
189
+ agent-custody check --config gateway.json --connect
190
+ docker run --rm -v "$PWD/config:/config:ro" -v gateway-data:/data --env-file .env <image> check --config /config/gateway.json --connect
191
+ ```
192
+
193
+ | it checks | an error or a warning |
194
+ | --- | --- |
195
+ | the config parses, with each problem and its path | **error** |
196
+ | 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 |
197
+ | the gateway key loads, and is not readable by other users | error, and a warning |
198
+ | every trusted principal key loads | error |
199
+ | the Cedar policy parses, and has at least one `permit` rule (a `permit(` in a comment does not count) | error, and a warning |
200
+ | 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 |
201
+ | a stdio `command` exists, and a script argument exists | error, and a warning |
202
+ | the receipts, log, revocation, operations database, and approvals paths can be written, and the revocation file is a JSON array | error |
203
+ | the grant the config names verifies, and is inside its window | error, and a warning near expiry |
204
+ | a remote log with an empty `precommit` | warning: a log outage after a call leaves its side effect without evidence |
205
+
206
+ With **`--connect`** it also starts the upstreams, which is where an unreachable server or **two upstreams offering the same tool** shows up, prints the tools they offer, and compares every tool name in `precommit`, `facts`, `approvals`, `operations`, and the grant's scopes with that list. A name in `precommit`, `facts`, `approvals`, or `operations` that no upstream offers is an **error** (for `precommit` it means the tool you meant is forwarded before it is logged); a grant scope that names nothing is a warning. `--connect` starts your stdio upstreams and may create the receipts directory. It exits 1 on any error, so it can gate a deploy.
207
+
208
+ **A console for all of this.** [The gateway console](console.md) shows the same config, the tools, and the check in a browser, and edits the policy with a replay of recorded calls before it saves.
209
+
210
+ ## When the gateway does not start
211
+
212
+ | the message | the cause | the fix |
213
+ | --- | --- | --- |
214
+ | `environment variable X is not set` | a `tokenEnv`, `headerEnv`, `log.tokenEnv`, or `captureKeyEnv` names a variable the process does not have | set it where the gateway runs |
215
+ | `tool "t" is offered by both upstream "a" and upstream "b"` | two upstreams offer one name | rename one (give REST and A2A tools a prefix) |
216
+ | `exactly one of upstream or upstreams is required` | both, or neither | use `upstream` for one source and `upstreams` for several |
217
+ | `exactly one of logFile or log is required` | both, or neither | a local file, or a remote log |
218
+ | `precommit with a remote log needs log.keys` | a remote log gating consequential calls without a pinned key | add the log's public key file to `log.keys` |
219
+ | `fact "f" uses tool t, which precommit names as consequential` | a fact lookup must be a read | use a read tool for the fact |
220
+ | `ENOENT … gateway.key` | the key file does not exist | `agent-custody keygen`, or let the container create it |
221
+ | `EROFS` or a permission error on `receipts` | a writable path points into the read-only `/config` | use an absolute path under `/data` |
222
+ | `403 delegation grant rejected: …` (an agent's connection) | the grant is expired, revoked, not signed by a trusted principal, or missing | issue a new grant, and check `trustedPrincipalKeys` |
223
+
224
+ The gateway image runs the static check every time it starts and does not start on an error (`GATEWAY_CHECK=advisory` prints the findings and starts anyway; `off` skips it), and the command exits 1 on an error, so it can gate a deploy. Run `agent-custody check --connect` first: it reports most of these together, instead of one at a time.