@agent-custody/receipts 0.8.0 → 0.10.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/README.md +19 -7
- package/dist/check.d.ts +19 -0
- package/dist/check.js +288 -0
- package/dist/cli.js +119 -11
- package/dist/config.d.ts +1 -0
- package/dist/config.js +3 -0
- package/dist/console-page.d.ts +4 -0
- package/dist/console-page.js +342 -0
- package/dist/console.d.ts +20 -0
- package/dist/console.js +522 -0
- package/dist/gateway-http.js +1 -1
- package/dist/gateway.d.ts +18 -0
- package/dist/gateway.js +196 -48
- package/dist/index.d.ts +6 -2
- package/dist/index.js +4 -1
- package/dist/issue.d.ts +31 -1
- package/dist/issue.js +261 -10
- package/dist/log-store.d.ts +3 -2
- package/dist/log-store.js +2 -0
- package/dist/policy.d.ts +4 -0
- package/dist/policy.js +15 -0
- package/dist/portal.d.ts +78 -4
- package/dist/portal.js +517 -26
- package/dist/simulate.d.ts +7 -1
- package/dist/simulate.js +27 -2
- package/dist/sso.d.ts +47 -0
- package/dist/sso.js +161 -0
- package/dist/verify.js +8 -4
- package/docs/codex-recovery.md +132 -0
- package/docs/configuration.md +226 -0
- package/docs/console.md +78 -0
- package/docs/policies.md +4 -1
- package/docs/threat-model.md +13 -0
- package/docs/tutorials.md +4 -0
- package/docs/usage.md +38 -4
- package/package.json +8 -2
- package/vectors/audit.json +27 -27
- package/vectors/receipts.json +1135 -929
package/README.md
CHANGED
|
@@ -10,9 +10,12 @@ Two producers, one receipt format, one verifier.
|
|
|
10
10
|
Anyone holding the public keys can verify a receipt offline. The agent is not trusted. The layer around it is, and the receipt says exactly how far that trust extends, starting with who issued it. What the receipt file carries of a call is a choice per tool: a field can be withheld as a commitment or encrypted under your key, and the verifier recomputes the digests when it is shown the values.
|
|
11
11
|
|
|
12
12
|
- [Reference](https://docs.agent-custody.dev/reference/): every function, endpoint, MCP tool, and command with its request and response
|
|
13
|
-
- [Tutorials](docs/tutorials.md): thirty runnable examples, one per aspect of the code, all executed by the test suite
|
|
13
|
+
- [Tutorials](docs/tutorials.md): thirty-two runnable examples, one per aspect of the code, all executed by the test suite
|
|
14
14
|
- [Financial operations](docs/financial-operations.md): durable operation ids, provider idempotency keys, atomic daily budget reservations, and reconciliation receipts for uncertain outcomes
|
|
15
|
-
- [
|
|
15
|
+
- [The gateway console](docs/console.md): an admin service for the person who runs a gateway: config, tools, receipts with a verdict each, a policy editor that replays recorded calls before it saves, grant revocation, and an audit trail
|
|
16
|
+
- [Configuring the gateway](docs/configuration.md): who may use which tools and where the tools live, a worked example with two agents, the Docker image, and `agent-custody check` to validate a config before it starts
|
|
17
|
+
- [Usage guide](docs/usage.md): gateway setup, wiring into Claude Desktop, Claude Code, or your own agent loop, and the gateway as an A2A agent between agents that delegate to each other, private evidence: what the receipt file carries of each call, and searching receipts and exporting offline cases with the state package's review console
|
|
18
|
+
- [Live Codex recovery demo](docs/codex-recovery.md): a real support agent, incorrect CRM memory, operator-reviewed compensation, and verified receipts; an opt-in live run with offline regression coverage
|
|
16
19
|
- [Human approvals](docs/approvals.md): short-lived signatures over the exact action, two-person thresholds, single-use enforcement, and offline verification
|
|
17
20
|
- [The interceptor SDK](docs/sdk.md): Claude Code hooks, the Claude Agent SDK, adapters for the OpenAI Agents SDK, Vercel AI SDK, LangChain, OpenClaw and DeepSeek Harness, a Hermes Agent plugin and Google ADK callbacks through the Python package, and wrapping tool functions in anything else
|
|
18
21
|
- [Writing policies](docs/policies.md): how a tool call becomes a Cedar request, with tested examples, and replaying history against a proposed policy with `policy simulate`
|
|
@@ -53,6 +56,8 @@ Framework hooks and adapters, including Claude Code, the OpenAI Agents SDK, the
|
|
|
53
56
|
|
|
54
57
|
## How it fits together
|
|
55
58
|
|
|
59
|
+
The [architecture guide](../../site/guide/architecture.md) adds the customer-side and hosted split, the data model, and sequence diagrams for onboarding, revocation, and verification.
|
|
60
|
+
|
|
56
61
|
```mermaid
|
|
57
62
|
flowchart LR
|
|
58
63
|
P["Principal<br/>(human or org, holds a signing key)"]
|
|
@@ -104,6 +109,7 @@ Every receipt names its issuer, and the verifier prints what that issuer kind is
|
|
|
104
109
|
| host or framework | producer | enforce + record | record only | tested against |
|
|
105
110
|
| --- | --- | --- | --- | --- |
|
|
106
111
|
| any MCP host: Claude Desktop, Claude Code, Cursor, custom | gateway | yes | | a real MCP client and upstream over stdio |
|
|
112
|
+
| Codex CLI (headless) | gateway | yes | | a manual `codex exec` run and offline MCP recovery checks; [guide](docs/codex-recovery.md) |
|
|
107
113
|
| Claude Code | SDK | `hook` command, PreToolUse deny | PostToolUse | the documented hook contract, via stdin |
|
|
108
114
|
| Claude Agent SDK | SDK | `claudeAgentHooks` | same | the same handler |
|
|
109
115
|
| OpenAI Agents SDK (JS) | SDK | `wrapTools` | `observeRunner` | a real `Runner` with a scripted model |
|
|
@@ -120,7 +126,7 @@ Every receipt names its issuer, and the verifier prints what that issuer kind is
|
|
|
120
126
|
| any REST API, as tools the agent reaches through the gateway | gateway, `rest` upstream | yes | | a stand-in HTTP API; [usage.md](docs/usage.md#setup-step-by-step) |
|
|
121
127
|
| any agent reached over A2A (Google ADK `RemoteA2aAgent`, or any A2A client) | gateway, `a2a` upstream and `gateway --a2a` | yes | | stand-in A2A agents in both wire formats; ADK's own `to_a2a` and `RemoteA2aAgent` in the Python suite; [usage.md](docs/usage.md#the-gateway-as-an-a2a-agent) |
|
|
122
128
|
|
|
123
|
-
The framework packages are optional peer dependencies. Each adapter imports only from its own package.
|
|
129
|
+
The framework packages, `pg`, and `@node-saml/node-saml` (for SAML sign-in to the portal) are optional peer dependencies. Each adapter imports only from its own package.
|
|
124
130
|
|
|
125
131
|
## One tool call, end to end
|
|
126
132
|
|
|
@@ -183,7 +189,7 @@ Every field carries a provenance label. This is the design decision that matters
|
|
|
183
189
|
bun install # from the repository root, once for the workspace
|
|
184
190
|
cd packages/receipts
|
|
185
191
|
node scripts/demo.ts # gateway: keys, grant, policy, four tool calls, verification, a tampering attempt; then the SDK wrapping the same tool
|
|
186
|
-
node examples/01-keys-and-signing.ts # first of thirty step-by-step examples, see docs/tutorials.md
|
|
192
|
+
node examples/01-keys-and-signing.ts # first of thirty-two step-by-step examples, see docs/tutorials.md
|
|
187
193
|
bun run test # this package; `bun run test` at the root runs every package
|
|
188
194
|
```
|
|
189
195
|
|
|
@@ -236,7 +242,8 @@ src/config.ts gateway and SDK config schemas, path resolution
|
|
|
236
242
|
src/crypto.ts canonical JSON, sha256, Ed25519 keys, DSSE sign/verify
|
|
237
243
|
src/log.ts Merkle log: append, root, inclusion and consistency proofs, verify, JSONL persistence
|
|
238
244
|
src/log-check.ts the outside monitor: verifies the head, checkpoints, and witness of a running log
|
|
239
|
-
src/portal.ts the tenant portal: register, first key, usage against plan, keys, Stripe billing, export, on the log's Postgres
|
|
245
|
+
src/portal.ts the tenant portal: register, first key, usage against plan, keys, Stripe billing, export, member roles, TOTP MFA, single sign-on, on the log's Postgres
|
|
246
|
+
src/sso.ts enterprise sign-in for the portal: OIDC (code and PKCE, id_token checked against the IdP's key set) and SAML 2.0 (signed assertions only, through @node-saml/node-saml)
|
|
240
247
|
src/log-export.ts a tenant's export of their own log, self-checked, as a log file the verifier reads
|
|
241
248
|
src/witness.ts the witness: countersigns the log's checkpoints from another operator's machine, or refuses with an alarm
|
|
242
249
|
src/signer.ts the signer: the log's key in its own process, the key document verifiers fetch
|
|
@@ -269,10 +276,10 @@ src/retention.ts pruning the log: leaves become their hashes, bundles are remo
|
|
|
269
276
|
src/index.ts the package's public surface; adapters are exported on ./sdk/<framework> subpaths
|
|
270
277
|
tsconfig.build.json emits dist/ (JavaScript plus declarations) for consumers; the repo itself runs the .ts directly
|
|
271
278
|
scripts/ fake Stripe upstream (signs its results with --key), a second fake upstream, fixture builders for gateway and SDK, the replay builder (`replay.ts`: example 27 and state example 07 as a folder of receipts and public keys anyone can verify with the published packages), demo
|
|
272
|
-
examples/ thirty runnable tutorials, plus examples/languages/: Python, Go, Java, and Rust clients of the sidecar, run by the test suite, one per aspect; each is run by the test suite
|
|
279
|
+
examples/ thirty-two runnable tutorials, plus examples/languages/: Python, Go, Java, and Rust clients of the sidecar, run by the test suite, one per aspect; each is run by the test suite
|
|
273
280
|
test/ unit tests per module, end-to-end gateway test, SDK and hook tests,
|
|
274
281
|
adapter tests against the real packages, and a test that runs every policy in docs/policies.md
|
|
275
|
-
docs/ tutorials, usage (gateway), approvals, sdk, policies, verification
|
|
282
|
+
docs/ tutorials, usage (gateway), codex-recovery (live demo), approvals, sdk, policies, verification
|
|
276
283
|
```
|
|
277
284
|
|
|
278
285
|
## Plan
|
|
@@ -281,6 +288,8 @@ The design is two producers feeding one verifier. The SDK is the top of the funn
|
|
|
281
288
|
|
|
282
289
|
**Done**
|
|
283
290
|
|
|
291
|
+
- Policy reload: the gateway re-reads `policy.cedar` whenever it changes and applies it from the next call, with no restart and no dropped session; a policy that does not parse is refused and the one in force stays, and every change or refusal is recorded in `receipts/policy-reloads.jsonl` ([usage](docs/usage.md)).
|
|
292
|
+
- Live Codex support recovery demo: model-selected MCP calls, incorrect CRM memory, a reviewed recovery plan, simulated credit compensation, and verified evidence; [guide](docs/codex-recovery.md), with offline regression coverage.
|
|
284
293
|
- Payload-bound human approvals: short-lived signatures over the principal, agent, tool, full arguments, amount, currency, and beneficiary; configurable one- or two-key thresholds, enforced even in observe mode, a configurable lifetime cap, persistent atomic single-use consumption before forwarding, and independent approval-key verification. [Guide](docs/approvals.md), tutorial 30.
|
|
285
294
|
- Gateway: MCP proxy, signed delegation, gateway-fetched facts, Cedar policy, denial receipts, Merkle log, offline verifier.
|
|
286
295
|
- Receipt schema carries the issuer kind, so a verifier reads gateway versus SDK before anything else.
|
|
@@ -319,6 +328,9 @@ The design is two producers feeding one verifier. The SDK is the top of the funn
|
|
|
319
328
|
- The grant on every call (issue #97): expiry and revocation are checked on every call and again before the forward, in every mode, on the MCP, HTTP, and A2A fronts; `agent-custody revoke` revokes a grant and every grant delegated from it. The remote log's answer is verified against pinned keys before a pre-committed call goes upstream (issue #99). The portal verifies an address only from the account's own session before a provider sign-in can link to it (issue #103). The verifier recomputes the execution result digest (issue #104). The Stripe webhook ignores a repeated or out-of-order event (issue #105).
|
|
320
329
|
- Agent-to-agent delegation under custody: the A2A upstream and the gateway's A2A front; receipts per delegation with the delegate's card as a fact. A Google ADK `RemoteA2aAgent`, or any A2A client, is pointed at the gateway and a refused delegation comes back as a rejected task the delegate never saw. The delegate does not yet countersign its answer; the receipt attests what the gateway sent and observed, not what the delegate did with it.
|
|
321
330
|
- Private evidence: per-tool capture rules, applied by the issuer to the whole statement so nothing outside a fixed structural list is in clear under a private rule; withheld values as salted commitments whose salts never enter the receipt, encrypted under the customer's key, revealed and recomputed by the verifier; the commitments do not confirm a guess of a withheld value. A human approval envelope carries the action fields and an unsalted argument digest, so a private rule withholds it as a commitment; the [privacy limits](docs/approvals.md#privacy-limits) apply.
|
|
331
|
+
- Enterprise identity for the hosted portal: member roles (`owner`, `admin`, `reviewer`, `readonly`) with invites, TOTP MFA with single-use codes and an operator reset (`log-admin user mfa-reset`), and single sign-on per tenant through the tenant's own IdP, OIDC or SAML 2.0, set by the operator (`log-admin sso set`), with an enforce mode that closes the password, GitHub, and Google paths to members. Revoking an agent's authority mid-session already shipped (`agent-custody revoke`, example 27); example 31 shows the enterprise sign-in and the roles.
|
|
332
|
+
- The [state review console](../state/README.md#explain-one-action): search receipts by transaction, customer, agent or time, read the ten answers, and hand over a portable HTML/JSON case whose signatures, authorizations and inclusion proofs can be verified offline.
|
|
333
|
+
- A log outage after an ordinary call (issue #149): the signed receipt waits in `receipts/outbox/` and the gateway appends it when the log is back, the agent gets the real outcome marked `log-pending`, `GET /health` counts the pending receipts, and `requirePrecommit` refuses a remote log with an empty `precommit`. The [failure table](docs/usage.md#when-the-log-fails) gives each case.
|
|
322
334
|
|
|
323
335
|
**Next, in the order it pays off**
|
|
324
336
|
|
package/dist/check.d.ts
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
export interface CheckFinding {
|
|
2
|
+
level: "ok" | "warn" | "error";
|
|
3
|
+
check: string;
|
|
4
|
+
message: string;
|
|
5
|
+
}
|
|
6
|
+
export interface CheckOptions {
|
|
7
|
+
/** start the upstreams and compare tool names with what they offer */
|
|
8
|
+
connect?: boolean;
|
|
9
|
+
/**
|
|
10
|
+
* "check" (the default) requires every credential variable the config names to be set in this process. "skip" is for a
|
|
11
|
+
* process that is not the gateway and deliberately does not hold its credentials, such as the console: they are not
|
|
12
|
+
* checked, and an upstream that needs one is not started.
|
|
13
|
+
*/
|
|
14
|
+
environment?: "check" | "skip";
|
|
15
|
+
/** cancels --connect while it is starting the upstreams; whatever was started is closed */
|
|
16
|
+
signal?: AbortSignal;
|
|
17
|
+
}
|
|
18
|
+
export declare function checkConfig(configPath: string, options?: CheckOptions): Promise<CheckFinding[]>;
|
|
19
|
+
export declare function formatFindings(findings: CheckFinding[]): string;
|
package/dist/check.js
ADDED
|
@@ -0,0 +1,288 @@
|
|
|
1
|
+
// `agent-custody check`: what a gateway config would fail on at startup, found before it starts. Static checks read the
|
|
2
|
+
// config, the keys, the policy, the grant, the environment, and the paths; --connect also starts the upstreams, which
|
|
3
|
+
// is where tool-name collisions and unreachable servers show up, and compares every tool name the config mentions with
|
|
4
|
+
// the tools the upstreams actually offer.
|
|
5
|
+
import * as cedar from "@cedar-policy/cedar-wasm/nodejs";
|
|
6
|
+
import { accessSync, constants, existsSync, mkdtempSync, readFileSync, rmSync, statSync } from "node:fs";
|
|
7
|
+
import { tmpdir } from "node:os";
|
|
8
|
+
import { delimiter, dirname, isAbsolute, join, resolve } from "node:path";
|
|
9
|
+
import { GatewayConfigSchema, loadConfig } from "./config.js";
|
|
10
|
+
import { generateKeyPair, loadPrivateKey, loadPublicKey, writeKeyPair } from "./crypto.js";
|
|
11
|
+
import { delegationValidAt, verifyDelegation } from "./delegation.js";
|
|
12
|
+
import { hasPermitRule } from "./policy.js";
|
|
13
|
+
import { createGatewayHost } from "./gateway.js";
|
|
14
|
+
const distance = (a, b) => {
|
|
15
|
+
const row = Array.from({ length: b.length + 1 }, (_, i) => i);
|
|
16
|
+
for (let i = 1; i <= a.length; i++) {
|
|
17
|
+
let prev = row[0];
|
|
18
|
+
row[0] = i;
|
|
19
|
+
for (let j = 1; j <= b.length; j++) {
|
|
20
|
+
const keep = row[j];
|
|
21
|
+
row[j] = Math.min(row[j] + 1, row[j - 1] + 1, prev + (a[i - 1] === b[j - 1] ? 0 : 1));
|
|
22
|
+
prev = keep;
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
return row[b.length];
|
|
26
|
+
};
|
|
27
|
+
/** the nearest existing directory above a path, to ask whether something can be created there */
|
|
28
|
+
function writableAncestor(path) {
|
|
29
|
+
let dir = resolve(path);
|
|
30
|
+
while (!existsSync(dir)) {
|
|
31
|
+
const up = dirname(dir);
|
|
32
|
+
if (up === dir)
|
|
33
|
+
return null;
|
|
34
|
+
dir = up;
|
|
35
|
+
}
|
|
36
|
+
try {
|
|
37
|
+
accessSync(dir, constants.W_OK);
|
|
38
|
+
return dir;
|
|
39
|
+
}
|
|
40
|
+
catch {
|
|
41
|
+
return null;
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
function onPath(command) {
|
|
45
|
+
if (isAbsolute(command) || command.includes("/"))
|
|
46
|
+
return existsSync(command);
|
|
47
|
+
return (process.env.PATH ?? "").split(delimiter).some((d) => d && existsSync(join(d, command)));
|
|
48
|
+
}
|
|
49
|
+
export async function checkConfig(configPath, options = {}) {
|
|
50
|
+
const out = [];
|
|
51
|
+
const add = (level, check, message) => out.push({ level, check, message });
|
|
52
|
+
let raw;
|
|
53
|
+
try {
|
|
54
|
+
raw = JSON.parse(readFileSync(configPath, "utf8"));
|
|
55
|
+
}
|
|
56
|
+
catch (e) {
|
|
57
|
+
add("error", "config", `${configPath} is not readable JSON: ${e instanceof Error ? e.message : String(e)}`);
|
|
58
|
+
return out;
|
|
59
|
+
}
|
|
60
|
+
const known = Object.keys(GatewayConfigSchema.shape);
|
|
61
|
+
if (raw && typeof raw === "object" && !Array.isArray(raw)) {
|
|
62
|
+
for (const key of Object.keys(raw)) {
|
|
63
|
+
if (known.includes(key))
|
|
64
|
+
continue;
|
|
65
|
+
const near = known.find((k) => distance(k.toLowerCase(), key.toLowerCase()) <= 2);
|
|
66
|
+
add("error", "config", `unknown key "${key}" is ignored by the gateway${near ? `; did you mean "${near}"?` : ""} A mistyped key leaves the setting it was meant for at its default`);
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
const parsed = GatewayConfigSchema.safeParse(raw);
|
|
70
|
+
if (!parsed.success) {
|
|
71
|
+
for (const issue of parsed.error.issues)
|
|
72
|
+
add("error", "config", `${issue.path.join(".") || "(root)"}: ${issue.message}`);
|
|
73
|
+
return out;
|
|
74
|
+
}
|
|
75
|
+
add("ok", "config", "the config parses");
|
|
76
|
+
const cfg = loadConfig(configPath);
|
|
77
|
+
// the gateway's key
|
|
78
|
+
if (!existsSync(cfg.identity.keyFile)) {
|
|
79
|
+
add("warn", "key", `${cfg.identity.keyFile} does not exist yet; \`agent-custody keygen\` creates it, and the container creates it on first start`);
|
|
80
|
+
}
|
|
81
|
+
else {
|
|
82
|
+
try {
|
|
83
|
+
loadPrivateKey(cfg.identity.keyFile);
|
|
84
|
+
add("ok", "key", `the gateway key at ${cfg.identity.keyFile} loads`);
|
|
85
|
+
if (process.platform !== "win32" && (statSync(cfg.identity.keyFile).mode & 0o077) !== 0)
|
|
86
|
+
add("warn", "key", `${cfg.identity.keyFile} is readable by other users; make it mode 0600`);
|
|
87
|
+
}
|
|
88
|
+
catch (e) {
|
|
89
|
+
add("error", "key", `${cfg.identity.keyFile}: ${e instanceof Error ? e.message : String(e)}`);
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
// the principals whose grants are trusted
|
|
93
|
+
const principals = [];
|
|
94
|
+
for (const f of cfg.trustedPrincipalKeys) {
|
|
95
|
+
try {
|
|
96
|
+
principals.push(loadPublicKey(f));
|
|
97
|
+
}
|
|
98
|
+
catch (e) {
|
|
99
|
+
add("error", "principal keys", `${f}: ${e instanceof Error ? e.message : String(e)}`);
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
if (principals.length === cfg.trustedPrincipalKeys.length)
|
|
103
|
+
add("ok", "principal keys", `${principals.length} trusted principal key${principals.length === 1 ? "" : "s"} load`);
|
|
104
|
+
// the policy
|
|
105
|
+
if (!existsSync(cfg.policyFile)) {
|
|
106
|
+
add("error", "policy", `${cfg.policyFile} does not exist`);
|
|
107
|
+
}
|
|
108
|
+
else {
|
|
109
|
+
const text = readFileSync(cfg.policyFile, "utf8");
|
|
110
|
+
const r = cedar.checkParsePolicySet({ staticPolicies: text });
|
|
111
|
+
if (r.type !== "success")
|
|
112
|
+
for (const e of r.errors)
|
|
113
|
+
add("error", "policy", `${cfg.policyFile}: ${e.message}`);
|
|
114
|
+
else if (!hasPermitRule(text))
|
|
115
|
+
add("warn", "policy", `${cfg.policyFile} has no permit rule, so every call is denied`);
|
|
116
|
+
else
|
|
117
|
+
add("ok", "policy", "the policy parses");
|
|
118
|
+
}
|
|
119
|
+
if (cfg.mode === "observe")
|
|
120
|
+
add("warn", "mode", "observe mode forwards every call the grant allows and records what the policy would have decided; nothing is denied by policy");
|
|
121
|
+
// credentials: a variable the config names must be set where the gateway runs
|
|
122
|
+
const envNames = [];
|
|
123
|
+
for (const u of cfg.upstreams ?? (cfg.upstream ? [{ name: "upstream", ...cfg.upstream }] : [])) {
|
|
124
|
+
const name = "name" in u ? u.name : "upstream";
|
|
125
|
+
if ("tokenEnv" in u && u.tokenEnv)
|
|
126
|
+
envNames.push([`upstream ${name}`, u.tokenEnv]);
|
|
127
|
+
if ("rest" in u)
|
|
128
|
+
for (const v of Object.values(u.rest.headerEnv ?? {}))
|
|
129
|
+
envNames.push([`upstream ${name}`, v]);
|
|
130
|
+
if ("a2a" in u)
|
|
131
|
+
for (const v of Object.values(u.a2a.headerEnv ?? {}))
|
|
132
|
+
envNames.push([`upstream ${name}`, v]);
|
|
133
|
+
}
|
|
134
|
+
if (cfg.log?.tokenEnv)
|
|
135
|
+
envNames.push(["log", cfg.log.tokenEnv]);
|
|
136
|
+
if (cfg.splunk?.tokenEnv)
|
|
137
|
+
envNames.push(["splunk", cfg.splunk.tokenEnv]);
|
|
138
|
+
for (const v of Object.values(cfg.otel?.headersEnv ?? {}))
|
|
139
|
+
envNames.push(["otel", v]);
|
|
140
|
+
if (cfg.captureKeyEnv)
|
|
141
|
+
envNames.push(["capture", cfg.captureKeyEnv]);
|
|
142
|
+
const skipEnvironment = options.environment === "skip";
|
|
143
|
+
const missing = skipEnvironment ? [] : envNames.filter(([, v]) => !process.env[v]);
|
|
144
|
+
for (const [who, v] of missing)
|
|
145
|
+
add("error", "environment", `${who}: the variable ${v} is not set here, and a gateway does not start without it`);
|
|
146
|
+
if (envNames.length && skipEnvironment)
|
|
147
|
+
add("ok", "environment", `not checked here: this process does not hold the gateway's credentials (${[...new Set(envNames.map(([, v]) => v))].join(", ")}); run agent-custody check where the gateway runs`);
|
|
148
|
+
else if (envNames.length && !missing.length)
|
|
149
|
+
add("ok", "environment", `${envNames.length} credential variable${envNames.length === 1 ? " is" : "s are"} set`);
|
|
150
|
+
// stdio upstreams: the command must exist where the gateway runs
|
|
151
|
+
for (const u of cfg.upstreams ?? (cfg.upstream ? [{ name: "upstream", ...cfg.upstream }] : [])) {
|
|
152
|
+
if ("command" in u && !onPath(u.command))
|
|
153
|
+
add("error", "upstream", `${"name" in u ? u.name : "upstream"}: the command "${u.command}" is not on the PATH or at that path; in a container it must be inside the image`);
|
|
154
|
+
}
|
|
155
|
+
// a script or file a stdio upstream is started with has to be where the gateway runs, which in a container is inside the image
|
|
156
|
+
for (const u of cfg.upstreams ?? (cfg.upstream ? [{ name: "upstream", ...cfg.upstream }] : [])) {
|
|
157
|
+
if (!("command" in u))
|
|
158
|
+
continue;
|
|
159
|
+
for (const a of u.args)
|
|
160
|
+
if ((a.startsWith("/") || a.startsWith("./")) && !existsSync(a))
|
|
161
|
+
add("warn", "upstream", `${"name" in u ? u.name : "upstream"}: the argument ${a} does not exist here; if it is a file the upstream needs, it must be inside the image`);
|
|
162
|
+
}
|
|
163
|
+
// a REST tool with an idempotency header is a financial operation: every call to it fails unless `operations` configures it
|
|
164
|
+
const operationTools = new Set((cfg.operations?.tools ?? []).map((t) => t.tool));
|
|
165
|
+
for (const u of cfg.upstreams ?? (cfg.upstream ? [{ name: "upstream", ...cfg.upstream }] : [])) {
|
|
166
|
+
if (!("rest" in u))
|
|
167
|
+
continue;
|
|
168
|
+
for (const t of u.rest.tools) {
|
|
169
|
+
if (t.idempotencyHeader && !operationTools.has(t.name))
|
|
170
|
+
add("error", "upstream", `${"name" in u ? u.name : "upstream"}: the tool ${t.name} sets idempotencyHeader, which makes it a financial operation, and every call to it fails unless it is also listed under "operations"; remove idempotencyHeader, or configure it under operations (financial-operations.md)`);
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
// where the gateway writes
|
|
174
|
+
const writes = [["receiptsDir", cfg.receiptsDir]];
|
|
175
|
+
if (cfg.operations)
|
|
176
|
+
writes.push(["operations.database", cfg.operations.database]);
|
|
177
|
+
if (cfg.approvals)
|
|
178
|
+
writes.push(["approvals.usedDir", cfg.approvals.usedDir]);
|
|
179
|
+
if (cfg.logFile)
|
|
180
|
+
writes.push(["logFile", cfg.logFile]);
|
|
181
|
+
if (cfg.revokedGrants)
|
|
182
|
+
writes.push(["revokedGrants", cfg.revokedGrants]);
|
|
183
|
+
let writable = true;
|
|
184
|
+
for (const [key, path] of writes) {
|
|
185
|
+
if (!writableAncestor(path)) {
|
|
186
|
+
writable = false;
|
|
187
|
+
add("error", "paths", `${key} ${path} cannot be created or written; in a container, use an absolute path under /data (/config is read-only)`);
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
if (writable)
|
|
191
|
+
add("ok", "paths", "every path the gateway writes can be written");
|
|
192
|
+
if (cfg.revokedGrants && existsSync(cfg.revokedGrants)) {
|
|
193
|
+
try {
|
|
194
|
+
if (!Array.isArray(JSON.parse(readFileSync(cfg.revokedGrants, "utf8"))))
|
|
195
|
+
throw new Error("expected a JSON array of grant digests");
|
|
196
|
+
}
|
|
197
|
+
catch (e) {
|
|
198
|
+
add("error", "revokedGrants", `${cfg.revokedGrants}: ${e instanceof Error ? e.message : String(e)}; a revocation file that cannot be read denies every call`);
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
// the grant a single-grant gateway serves
|
|
202
|
+
let scopes = [];
|
|
203
|
+
if (cfg.grantFile) {
|
|
204
|
+
try {
|
|
205
|
+
const env = JSON.parse(readFileSync(cfg.grantFile, "utf8"));
|
|
206
|
+
const v = verifyDelegation(env, principals);
|
|
207
|
+
if (!v.ok)
|
|
208
|
+
add("error", "grant", `${cfg.grantFile}: ${v.error}`);
|
|
209
|
+
else {
|
|
210
|
+
scopes = v.delegation.scopes;
|
|
211
|
+
const now = new Date().toISOString();
|
|
212
|
+
if (!delegationValidAt(v.delegation, now))
|
|
213
|
+
add("error", "grant", `${cfg.grantFile} for ${v.delegation.agent} is outside its validity window (${v.delegation.issuedAt} to ${v.delegation.expiresAt})`);
|
|
214
|
+
else if (Date.parse(v.delegation.expiresAt) - Date.now() < 24 * 3600_000)
|
|
215
|
+
add("warn", "grant", `${cfg.grantFile} for ${v.delegation.agent} expires at ${v.delegation.expiresAt}`);
|
|
216
|
+
else
|
|
217
|
+
add("ok", "grant", `the grant for ${v.delegation.agent} verifies; scopes: ${scopes.join(", ")}`);
|
|
218
|
+
}
|
|
219
|
+
}
|
|
220
|
+
catch (e) {
|
|
221
|
+
add("error", "grant", `${cfg.grantFile}: ${e instanceof Error ? e.message : String(e)}`);
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
else {
|
|
225
|
+
add("ok", "grant", "no grantFile: each connection over HTTP presents its own grant");
|
|
226
|
+
}
|
|
227
|
+
// what a log outage costs
|
|
228
|
+
if (cfg.log && !cfg.precommit.length)
|
|
229
|
+
add("warn", "precommit", "a remote log is set and precommit is empty: every call is forwarded before its receipt is logged, so a log outage after a call puts its receipt in the outbox and the side effect is in the log only later. Name the consequential tools in precommit, or [\"*\"]; requirePrecommit makes this an error");
|
|
230
|
+
// tool names the config mentions, against the tools the upstreams offer
|
|
231
|
+
const mentioned = () => [
|
|
232
|
+
...cfg.precommit.filter((t) => t !== "*").map((t) => ["precommit", t]),
|
|
233
|
+
...cfg.facts.flatMap((f) => [["facts", f.tool], ...f.forTools.map((t) => ["facts.forTools", t])]),
|
|
234
|
+
...(cfg.approvals?.tools ?? []).map((t) => ["approvals", t.tool]),
|
|
235
|
+
...(cfg.operations?.tools ?? []).flatMap((t) => [["operations", t.tool], ["operations.reconcile", t.reconcile.tool]]),
|
|
236
|
+
...scopes.map((t) => ["grant scope", t]),
|
|
237
|
+
];
|
|
238
|
+
if (!options.connect) {
|
|
239
|
+
add("warn", "upstreams", "not started: run with --connect to start the upstreams, catch tool-name collisions and unreachable servers, and compare the tool names above with the tools offered");
|
|
240
|
+
return out;
|
|
241
|
+
}
|
|
242
|
+
// a gateway key that does not exist yet (the container creates it on first start) must not stop the upstreams being tried
|
|
243
|
+
if (skipEnvironment && envNames.length) {
|
|
244
|
+
add("warn", "upstreams", "not started: the upstreams need credentials that this process does not hold, by design. Run `agent-custody check --connect` where the gateway runs, for example `docker compose exec gateway agent-custody check --config /config/gateway.json --connect`");
|
|
245
|
+
return out;
|
|
246
|
+
}
|
|
247
|
+
let connectCfg = cfg;
|
|
248
|
+
let scratch;
|
|
249
|
+
if (!existsSync(cfg.identity.keyFile)) {
|
|
250
|
+
scratch = mkdtempSync(join(tmpdir(), "agent-custody-check-"));
|
|
251
|
+
connectCfg = { ...cfg, identity: { keyFile: writeKeyPair(generateKeyPair(), scratch, "check").keyFile } };
|
|
252
|
+
}
|
|
253
|
+
let tools;
|
|
254
|
+
try {
|
|
255
|
+
const host = await createGatewayHost(connectCfg, options.signal ? { signal: options.signal } : {});
|
|
256
|
+
try {
|
|
257
|
+
tools = host.tools();
|
|
258
|
+
}
|
|
259
|
+
finally {
|
|
260
|
+
await host.close();
|
|
261
|
+
}
|
|
262
|
+
add("ok", "upstreams", `the upstreams start and offer ${tools.length} tool${tools.length === 1 ? "" : "s"}: ${tools.join(", ")}`);
|
|
263
|
+
}
|
|
264
|
+
catch (e) {
|
|
265
|
+
add("error", "upstreams", `the gateway would not start: ${e instanceof Error ? e.message : String(e)}`);
|
|
266
|
+
}
|
|
267
|
+
finally {
|
|
268
|
+
if (scratch)
|
|
269
|
+
rmSync(scratch, { recursive: true, force: true });
|
|
270
|
+
}
|
|
271
|
+
if (tools) {
|
|
272
|
+
const unknown = mentioned().filter(([, t]) => !tools.includes(t));
|
|
273
|
+
// a scope that names nothing is harmless; a precommit name that matches nothing leaves that tool forwarded with no authorization committed first
|
|
274
|
+
for (const [where, t] of unknown)
|
|
275
|
+
add(where === "grant scope" ? "warn" : "error", "tool names", `${where} names "${t}", which no upstream offers${where === "precommit" ? "; the tool you meant is forwarded before it is logged" : ""}`);
|
|
276
|
+
if (!unknown.length)
|
|
277
|
+
add("ok", "tool names", "every tool the config and the grant name is offered by an upstream");
|
|
278
|
+
}
|
|
279
|
+
return out;
|
|
280
|
+
}
|
|
281
|
+
export function formatFindings(findings) {
|
|
282
|
+
const mark = { ok: "ok ", warn: "warn ", error: "ERROR" };
|
|
283
|
+
const lines = findings.map((f) => `${mark[f.level]} ${f.check}: ${f.message}`);
|
|
284
|
+
const errors = findings.filter((f) => f.level === "error").length;
|
|
285
|
+
const warns = findings.filter((f) => f.level === "warn").length;
|
|
286
|
+
lines.push("", errors ? `${errors} error${errors === 1 ? "" : "s"}, ${warns} warning${warns === 1 ? "" : "s"}: the gateway would not start cleanly` : `no errors, ${warns} warning${warns === 1 ? "" : "s"}`);
|
|
287
|
+
return lines.join("\n");
|
|
288
|
+
}
|