@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/README.md +17 -7
- package/dist/check.d.ts +19 -0
- package/dist/check.js +288 -0
- package/dist/cli.js +114 -8
- 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 +521 -0
- package/dist/gateway.d.ts +4 -0
- package/dist/gateway.js +54 -32
- package/dist/index.d.ts +6 -2
- package/dist/index.js +4 -1
- package/dist/log-store.d.ts +3 -2
- package/dist/log-store.js +2 -0
- package/dist/policy.d.ts +2 -0
- package/dist/policy.js +10 -0
- package/dist/portal.d.ts +78 -4
- package/dist/portal.js +516 -26
- package/dist/sso.d.ts +47 -0
- package/dist/sso.js +161 -0
- package/dist/verify.js +4 -2
- package/docs/codex-recovery.md +132 -0
- package/docs/configuration.md +224 -0
- package/docs/console.md +79 -0
- package/docs/policies.md +1 -0
- package/docs/threat-model.md +13 -0
- package/docs/tutorials.md +4 -0
- package/docs/usage.md +21 -2
- package/package.json +8 -2
- package/vectors/audit.json +27 -27
- package/vectors/receipts.json +1135 -929
package/dist/console.js
ADDED
|
@@ -0,0 +1,521 @@
|
|
|
1
|
+
// The gateway console: a small admin service, separate from the gateway, for the person who runs it. It shows what the
|
|
2
|
+
// gateway is configured to do and what it has done, validates and simulates a policy change before it is saved, and
|
|
3
|
+
// revokes a grant. It never holds a principal's private key and never signs; everything it shows is read from the
|
|
4
|
+
// gateway's own config, receipts, and revocation file, and everything it changes is the policy file or the revocation
|
|
5
|
+
// file, both of which the gateway reads. Every change is recorded in an append-only audit file.
|
|
6
|
+
import * as cedar from "@cedar-policy/cedar-wasm/nodejs";
|
|
7
|
+
import { createHash, timingSafeEqual } from "node:crypto";
|
|
8
|
+
import { appendFileSync, closeSync, existsSync, mkdirSync, openSync, readdirSync, readFileSync, renameSync, statSync, unlinkSync, writeFileSync } from "node:fs";
|
|
9
|
+
import { createServer } from "node:http";
|
|
10
|
+
import { basename, dirname, join } from "node:path";
|
|
11
|
+
import { checkConfig } from "./check.js";
|
|
12
|
+
import { loadConfig } from "./config.js";
|
|
13
|
+
import { loadPrivateKey, loadPublicKey } from "./crypto.js";
|
|
14
|
+
import { decodeDelegation, delegationValidAt, grantDigest, verifyDelegation } from "./delegation.js";
|
|
15
|
+
import { writeRevokedGrants } from "./gateway.js";
|
|
16
|
+
import { CONSOLE_CSP, CONSOLE_HTML } from "./console-page.js";
|
|
17
|
+
import { hasPermitRule, policyDigest } from "./policy.js";
|
|
18
|
+
import { simulatePolicy } from "./simulate.js";
|
|
19
|
+
import { verifyBundle } from "./verify.js";
|
|
20
|
+
const MAX_BODY = 1_000_000;
|
|
21
|
+
const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
|
|
22
|
+
class HttpError extends Error {
|
|
23
|
+
status;
|
|
24
|
+
constructor(status, message) {
|
|
25
|
+
super(message);
|
|
26
|
+
this.status = status;
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
const sha = (s) => createHash("sha256").update(s).digest();
|
|
30
|
+
function atomicWrite(path, text) {
|
|
31
|
+
const tmp = `${path}.${process.pid}.tmp`;
|
|
32
|
+
writeFileSync(tmp, text);
|
|
33
|
+
renameSync(tmp, path);
|
|
34
|
+
}
|
|
35
|
+
async function readBody(req) {
|
|
36
|
+
const chunks = [];
|
|
37
|
+
let size = 0;
|
|
38
|
+
for await (const chunk of req) {
|
|
39
|
+
size += chunk.length;
|
|
40
|
+
if (size > MAX_BODY)
|
|
41
|
+
throw new HttpError(413, "the request body is too large");
|
|
42
|
+
chunks.push(chunk);
|
|
43
|
+
}
|
|
44
|
+
if (!size)
|
|
45
|
+
return {};
|
|
46
|
+
try {
|
|
47
|
+
return JSON.parse(Buffer.concat(chunks).toString("utf8"));
|
|
48
|
+
}
|
|
49
|
+
catch {
|
|
50
|
+
throw new HttpError(400, "the body is not JSON");
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
const object = (v) => {
|
|
54
|
+
if (!v || typeof v !== "object" || Array.isArray(v))
|
|
55
|
+
throw new HttpError(400, "the body must be a JSON object");
|
|
56
|
+
return v;
|
|
57
|
+
};
|
|
58
|
+
const decodePredicate = (bundle) => {
|
|
59
|
+
try {
|
|
60
|
+
return JSON.parse(Buffer.from(bundle.envelope.payload, "base64").toString("utf8")).predicate;
|
|
61
|
+
}
|
|
62
|
+
catch {
|
|
63
|
+
return null;
|
|
64
|
+
}
|
|
65
|
+
};
|
|
66
|
+
/**
|
|
67
|
+
* What an operator should be asked to confirm before a policy is saved: no permit rule at all, or a permit rule that has no
|
|
68
|
+
* condition and names no action, which allows every tool in a grant's scopes. Replaying recorded calls cannot show the
|
|
69
|
+
* second one: it changes nothing for a history that never used what it allows.
|
|
70
|
+
*/
|
|
71
|
+
function policyIssues(text) {
|
|
72
|
+
const issues = [];
|
|
73
|
+
if (!hasPermitRule(text))
|
|
74
|
+
issues.push("The policy has no permit rule, so every call would be denied.");
|
|
75
|
+
const parts = cedar.policySetTextToParts(text);
|
|
76
|
+
if (parts.type === "success") {
|
|
77
|
+
for (const p of parts.policies) {
|
|
78
|
+
const j = cedar.policyToJson(p);
|
|
79
|
+
if (j.type === "success" && j.json.effect === "permit" && j.json.action?.op === "All" && !(j.json.conditions?.length)) {
|
|
80
|
+
const who = j.json.principal?.op === "All" ? "for every agent" : "for the agent it names";
|
|
81
|
+
issues.push(`A permit rule has no action and no condition: it allows every tool in a grant's scopes, ${who}. A replay cannot show this, because it only re-decides calls that already happened.`);
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
return issues;
|
|
86
|
+
}
|
|
87
|
+
export async function serveConsole(options) {
|
|
88
|
+
const log = options.log ?? ((m) => console.error(m));
|
|
89
|
+
const tokenHash = sha(options.token);
|
|
90
|
+
if (!options.token)
|
|
91
|
+
throw new Error("the console needs a token");
|
|
92
|
+
loadConfig(options.configFile);
|
|
93
|
+
const state = options.stateDir ?? join(dirname(loadConfig(options.configFile).receiptsDir), "console");
|
|
94
|
+
mkdirSync(join(state, "policy-history"), { recursive: true });
|
|
95
|
+
const auditFile = join(state, "audit.jsonl");
|
|
96
|
+
let connecting = false;
|
|
97
|
+
const audit = (action, detail, by) => {
|
|
98
|
+
appendFileSync(auditFile, JSON.stringify({ at: new Date().toISOString(), by, action, ...detail }) + "\n");
|
|
99
|
+
};
|
|
100
|
+
/** the keys the console verifies receipts with: the gateway's own public key and the trusted principals' */
|
|
101
|
+
const keysOf = (cfg) => {
|
|
102
|
+
const problems = [];
|
|
103
|
+
const issuerKeys = [];
|
|
104
|
+
try {
|
|
105
|
+
if (existsSync(cfg.identity.keyFile)) {
|
|
106
|
+
const k = loadPrivateKey(cfg.identity.keyFile);
|
|
107
|
+
issuerKeys.push({ publicKey: k.publicKey, keyid: k.keyid });
|
|
108
|
+
}
|
|
109
|
+
else
|
|
110
|
+
problems.push("the gateway key does not exist yet, so receipts cannot be verified");
|
|
111
|
+
}
|
|
112
|
+
catch (e) {
|
|
113
|
+
problems.push(`the gateway key: ${e instanceof Error ? e.message : String(e)}`);
|
|
114
|
+
}
|
|
115
|
+
const principalKeys = [];
|
|
116
|
+
for (const f of cfg.trustedPrincipalKeys) {
|
|
117
|
+
try {
|
|
118
|
+
principalKeys.push(loadPublicKey(f));
|
|
119
|
+
}
|
|
120
|
+
catch (e) {
|
|
121
|
+
problems.push(`${f}: ${e instanceof Error ? e.message : String(e)}`);
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
return { issuerKeys, principalKeys, problems };
|
|
125
|
+
};
|
|
126
|
+
const revokedList = (cfg) => {
|
|
127
|
+
if (!cfg.revokedGrants || !existsSync(cfg.revokedGrants))
|
|
128
|
+
return [];
|
|
129
|
+
const list = JSON.parse(readFileSync(cfg.revokedGrants, "utf8"));
|
|
130
|
+
return Array.isArray(list) ? list.filter((d) => typeof d === "string") : [];
|
|
131
|
+
};
|
|
132
|
+
/** the receipt files, newest first; an authorization that has no receipt is not one */
|
|
133
|
+
const receiptFiles = (cfg) => {
|
|
134
|
+
if (!existsSync(cfg.receiptsDir))
|
|
135
|
+
return [];
|
|
136
|
+
return readdirSync(cfg.receiptsDir)
|
|
137
|
+
.filter((n) => n.endsWith(".json") && !n.endsWith(".authorization.json") && UUID.test(n.slice(0, -5)))
|
|
138
|
+
.map((n) => ({ id: n.slice(0, -5), file: join(cfg.receiptsDir, n), mtime: statSync(join(cfg.receiptsDir, n)).mtimeMs }))
|
|
139
|
+
.sort((a, b) => b.mtime - a.mtime);
|
|
140
|
+
};
|
|
141
|
+
const verifyOptionsFor = (cfg, keys) => ({
|
|
142
|
+
issuerKeys: keys.issuerKeys,
|
|
143
|
+
principalKeys: keys.principalKeys,
|
|
144
|
+
...(cfg.logFile && existsSync(cfg.logFile) ? { logFile: cfg.logFile } : {}),
|
|
145
|
+
});
|
|
146
|
+
const summarize = (id, file, cfg, keys) => {
|
|
147
|
+
let bundle;
|
|
148
|
+
try {
|
|
149
|
+
bundle = JSON.parse(readFileSync(file, "utf8"));
|
|
150
|
+
}
|
|
151
|
+
catch {
|
|
152
|
+
return { id, readable: false, verified: false, failing: ["the file is not readable JSON"] };
|
|
153
|
+
}
|
|
154
|
+
const p = decodePredicate(bundle);
|
|
155
|
+
const v = keys.issuerKeys.length ? verifyBundle(bundle, verifyOptionsFor(cfg, keys)) : null;
|
|
156
|
+
const execution = (p?.execution ?? {});
|
|
157
|
+
return {
|
|
158
|
+
id,
|
|
159
|
+
readable: true,
|
|
160
|
+
timestamp: p?.timestamp ?? null,
|
|
161
|
+
tool: p?.tool?.name ?? null,
|
|
162
|
+
agent: p?.agent?.id ?? null,
|
|
163
|
+
principal: p?.principal?.id ?? null,
|
|
164
|
+
decision: p?.policy?.decision ?? null,
|
|
165
|
+
enforced: p?.policy?.enforced !== false,
|
|
166
|
+
status: execution.status ?? null,
|
|
167
|
+
reason: execution.reason ?? null,
|
|
168
|
+
issuer: p?.issuer?.kind ?? null,
|
|
169
|
+
verified: v ? v.ok : false,
|
|
170
|
+
failing: v ? v.checks.filter((c) => !c.ok).map((c) => c.name) : ["no gateway key to verify with"],
|
|
171
|
+
};
|
|
172
|
+
};
|
|
173
|
+
const gatewayHealth = async () => {
|
|
174
|
+
if (!options.gatewayUrl)
|
|
175
|
+
return null;
|
|
176
|
+
try {
|
|
177
|
+
const r = await fetch(new URL("health", options.gatewayUrl.endsWith("/") ? options.gatewayUrl : `${options.gatewayUrl}/`), { signal: AbortSignal.timeout(2000) });
|
|
178
|
+
const body = (await r.json());
|
|
179
|
+
return { reachable: r.ok, sessions: body.sessions ?? null, keyid: body.keyid ?? null };
|
|
180
|
+
}
|
|
181
|
+
catch (e) {
|
|
182
|
+
return { reachable: false, error: e instanceof Error ? e.message : String(e) };
|
|
183
|
+
}
|
|
184
|
+
};
|
|
185
|
+
const upstreamsOf = (cfg) => (cfg.upstreams ?? (cfg.upstream ? [{ name: "upstream", ...cfg.upstream }] : [])).map((u) => {
|
|
186
|
+
const name = "name" in u ? u.name : "upstream";
|
|
187
|
+
if ("rest" in u)
|
|
188
|
+
return { name, kind: "rest", target: u.rest.baseUrl, tools: u.rest.tools.map((t) => t.name) };
|
|
189
|
+
if ("a2a" in u)
|
|
190
|
+
return { name, kind: "a2a", target: u.a2a.url, tools: [`${u.a2a.prefix}.send`, `${u.a2a.prefix}.card`] };
|
|
191
|
+
if ("url" in u)
|
|
192
|
+
return { name, kind: "mcp-http", target: u.url, tools: null };
|
|
193
|
+
return { name, kind: "mcp-stdio", target: [u.command, ...u.args].join(" "), tools: null };
|
|
194
|
+
});
|
|
195
|
+
// saves are serialised in this process, and a lock file in the state directory serialises another console on the same one
|
|
196
|
+
const lockFile = join(state, "policy.lock");
|
|
197
|
+
let saving = Promise.resolve();
|
|
198
|
+
const withPolicyLock = (fn) => {
|
|
199
|
+
const run = saving.then(async () => {
|
|
200
|
+
const deadline = Date.now() + 5_000;
|
|
201
|
+
for (;;) {
|
|
202
|
+
try {
|
|
203
|
+
closeSync(openSync(lockFile, "wx"));
|
|
204
|
+
break;
|
|
205
|
+
}
|
|
206
|
+
catch (e) {
|
|
207
|
+
if (e.code !== "EEXIST")
|
|
208
|
+
throw e;
|
|
209
|
+
try {
|
|
210
|
+
if (Date.now() - statSync(lockFile).mtimeMs > 30_000) {
|
|
211
|
+
unlinkSync(lockFile);
|
|
212
|
+
continue;
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
catch {
|
|
216
|
+
continue;
|
|
217
|
+
}
|
|
218
|
+
if (Date.now() > deadline)
|
|
219
|
+
throw new HttpError(409, "another save is in progress; try again");
|
|
220
|
+
await new Promise((r) => setTimeout(r, 50));
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
try {
|
|
224
|
+
return fn();
|
|
225
|
+
}
|
|
226
|
+
finally {
|
|
227
|
+
try {
|
|
228
|
+
unlinkSync(lockFile);
|
|
229
|
+
}
|
|
230
|
+
catch {
|
|
231
|
+
/* already gone */
|
|
232
|
+
}
|
|
233
|
+
}
|
|
234
|
+
});
|
|
235
|
+
saving = run.catch(() => { });
|
|
236
|
+
return run;
|
|
237
|
+
};
|
|
238
|
+
const routes = {
|
|
239
|
+
"GET /api/overview": async () => {
|
|
240
|
+
const cfg = loadConfig(options.configFile);
|
|
241
|
+
const keys = keysOf(cfg);
|
|
242
|
+
const receipts = receiptFiles(cfg);
|
|
243
|
+
return {
|
|
244
|
+
configFile: options.configFile,
|
|
245
|
+
mode: cfg.mode ?? "enforce",
|
|
246
|
+
precommit: cfg.precommit,
|
|
247
|
+
log: cfg.log ? { kind: "remote", url: cfg.log.url, hashOnly: !!cfg.log.hashOnly } : { kind: "local", file: cfg.logFile },
|
|
248
|
+
upstreams: upstreamsOf(cfg),
|
|
249
|
+
facts: cfg.facts.map((f) => ({ name: f.name, tool: f.tool, forTools: f.forTools })),
|
|
250
|
+
gatewayKeyid: keys.issuerKeys[0]?.keyid ?? null,
|
|
251
|
+
principals: keys.principalKeys.map((k) => k.keyid),
|
|
252
|
+
keyProblems: keys.problems,
|
|
253
|
+
revokedCount: revokedList(cfg).length,
|
|
254
|
+
revocationFile: cfg.revokedGrants ?? null,
|
|
255
|
+
receiptCount: receipts.length,
|
|
256
|
+
lastReceiptAt: receipts[0] ? new Date(receipts[0].mtime).toISOString() : null,
|
|
257
|
+
gateway: await gatewayHealth(),
|
|
258
|
+
findings: await checkConfig(options.configFile, { environment: "skip" }),
|
|
259
|
+
};
|
|
260
|
+
},
|
|
261
|
+
"POST /api/check": async (req) => {
|
|
262
|
+
const connect = object(await readBody(req)).connect === true;
|
|
263
|
+
if (connect) {
|
|
264
|
+
if (connecting)
|
|
265
|
+
throw new HttpError(409, "a connect check is already running");
|
|
266
|
+
connecting = true;
|
|
267
|
+
}
|
|
268
|
+
const stop = new AbortController();
|
|
269
|
+
const timer = connect ? setTimeout(() => stop.abort(), options.checkTimeoutMs ?? 60_000) : undefined;
|
|
270
|
+
try {
|
|
271
|
+
const findings = await checkConfig(options.configFile, { connect, environment: "skip", signal: stop.signal });
|
|
272
|
+
if (stop.signal.aborted)
|
|
273
|
+
throw new HttpError(504, "the check took too long and was stopped; the upstreams it started were closed");
|
|
274
|
+
return { findings };
|
|
275
|
+
}
|
|
276
|
+
finally {
|
|
277
|
+
clearTimeout(timer);
|
|
278
|
+
if (connect)
|
|
279
|
+
connecting = false;
|
|
280
|
+
}
|
|
281
|
+
},
|
|
282
|
+
"GET /api/policy": async () => {
|
|
283
|
+
const cfg = loadConfig(options.configFile);
|
|
284
|
+
const text = readFileSync(cfg.policyFile, "utf8");
|
|
285
|
+
return { path: cfg.policyFile, text, digest: policyDigest(text), history: readdirSync(join(state, "policy-history")).sort().reverse().slice(0, 20) };
|
|
286
|
+
},
|
|
287
|
+
"POST /api/policy/validate": async (req) => {
|
|
288
|
+
const text = String(object(await readBody(req)).text ?? "");
|
|
289
|
+
const r = cedar.checkParsePolicySet({ staticPolicies: text });
|
|
290
|
+
const errors = r.type === "success" ? [] : r.errors.map((e) => e.message);
|
|
291
|
+
return { ok: r.type === "success", errors, digest: policyDigest(text), issues: r.type === "success" ? policyIssues(text) : [] };
|
|
292
|
+
},
|
|
293
|
+
"POST /api/policy/simulate": async (req) => {
|
|
294
|
+
const text = String(object(await readBody(req)).text ?? "");
|
|
295
|
+
const cfg = loadConfig(options.configFile);
|
|
296
|
+
const keys = keysOf(cfg);
|
|
297
|
+
if (!keys.issuerKeys.length)
|
|
298
|
+
throw new HttpError(409, "there is no gateway key to verify receipts with, so there is nothing to replay");
|
|
299
|
+
const predicates = [];
|
|
300
|
+
let unverified = 0;
|
|
301
|
+
for (const f of receiptFiles(cfg).slice(0, 1000)) {
|
|
302
|
+
try {
|
|
303
|
+
const bundle = JSON.parse(readFileSync(f.file, "utf8"));
|
|
304
|
+
const p = decodePredicate(bundle);
|
|
305
|
+
if (p && verifyBundle(bundle, verifyOptionsFor(cfg, keys)).ok)
|
|
306
|
+
predicates.push(p);
|
|
307
|
+
else
|
|
308
|
+
unverified++;
|
|
309
|
+
}
|
|
310
|
+
catch {
|
|
311
|
+
unverified++;
|
|
312
|
+
}
|
|
313
|
+
}
|
|
314
|
+
let report;
|
|
315
|
+
try {
|
|
316
|
+
report = simulatePolicy(text, predicates);
|
|
317
|
+
}
|
|
318
|
+
catch (e) {
|
|
319
|
+
throw new HttpError(400, e instanceof Error ? e.message : String(e));
|
|
320
|
+
}
|
|
321
|
+
return {
|
|
322
|
+
replayed: predicates.length,
|
|
323
|
+
unverified,
|
|
324
|
+
report: {
|
|
325
|
+
policyDigest: report.policyDigest,
|
|
326
|
+
total: report.total,
|
|
327
|
+
evaluated: report.evaluated,
|
|
328
|
+
unchanged: report.unchanged,
|
|
329
|
+
complete: report.complete,
|
|
330
|
+
changes: report.changes.slice(0, 200).map((c) => ({ receiptId: c.receiptId, tool: c.tool, from: c.previous.decision, to: c.proposed.decision })),
|
|
331
|
+
changeCount: report.changes.length,
|
|
332
|
+
skipped: report.skipped.slice(0, 50),
|
|
333
|
+
},
|
|
334
|
+
};
|
|
335
|
+
},
|
|
336
|
+
"PUT /api/policy": async (req, _url, by) => {
|
|
337
|
+
const body = object(await readBody(req));
|
|
338
|
+
const text = String(body.text ?? "");
|
|
339
|
+
const parsed = cedar.checkParsePolicySet({ staticPolicies: text });
|
|
340
|
+
if (parsed.type !== "success")
|
|
341
|
+
throw new HttpError(400, `the policy does not parse: ${parsed.errors.map((e) => e.message).join("; ")}`);
|
|
342
|
+
const issues = policyIssues(text);
|
|
343
|
+
if (issues.length && body.confirm !== true)
|
|
344
|
+
throw new HttpError(400, `confirm before saving: ${issues.join(" ")}`);
|
|
345
|
+
// from reading the digest to the rename, nothing else may save: two tabs that loaded the same digest would otherwise both pass the
|
|
346
|
+
// check, the later rename would win, and the history of the lost edit would not even be the version it replaced
|
|
347
|
+
return withPolicyLock(() => {
|
|
348
|
+
const cfg = loadConfig(options.configFile);
|
|
349
|
+
const current = readFileSync(cfg.policyFile, "utf8");
|
|
350
|
+
if (body.expectDigest !== policyDigest(current))
|
|
351
|
+
throw new HttpError(409, "the policy file changed since you loaded it; reload and try again");
|
|
352
|
+
writeFileSync(join(state, "policy-history", `${new Date().toISOString().replace(/[:.]/g, "-")}-${policyDigest(current).slice(0, 12)}.cedar`), current);
|
|
353
|
+
try {
|
|
354
|
+
atomicWrite(cfg.policyFile, text);
|
|
355
|
+
}
|
|
356
|
+
catch (e) {
|
|
357
|
+
throw new HttpError(500, `the policy file cannot be written (${e instanceof Error ? e.message : String(e)}); mount the config directory read-write for the console`);
|
|
358
|
+
}
|
|
359
|
+
audit("policy.save", { file: cfg.policyFile, from: policyDigest(current), to: policyDigest(text), bytes: text.length, confirmed: issues }, by);
|
|
360
|
+
return { digest: policyDigest(text), note: "saved; the gateway reads the policy when it starts, so restart it to apply the change" };
|
|
361
|
+
});
|
|
362
|
+
},
|
|
363
|
+
"POST /api/grants/inspect": async (req) => {
|
|
364
|
+
const body = object(await readBody(req));
|
|
365
|
+
const cfg = loadConfig(options.configFile);
|
|
366
|
+
const keys = keysOf(cfg);
|
|
367
|
+
const env = (typeof body.grant === "string" ? safeJson(body.grant) : body.grant);
|
|
368
|
+
if (!env || typeof env !== "object")
|
|
369
|
+
throw new HttpError(400, "send the grant as a JSON object or a JSON string");
|
|
370
|
+
const decoded = decodeDelegation(env);
|
|
371
|
+
if (!decoded)
|
|
372
|
+
throw new HttpError(400, "this is not a delegation grant");
|
|
373
|
+
const digest = grantDigest(env);
|
|
374
|
+
const verified = verifyDelegation(env, keys.principalKeys);
|
|
375
|
+
const revoked = revokedList(cfg).includes(digest);
|
|
376
|
+
const now = new Date().toISOString();
|
|
377
|
+
let status;
|
|
378
|
+
if (!verified.ok)
|
|
379
|
+
status = "invalid";
|
|
380
|
+
else if (revoked)
|
|
381
|
+
status = "revoked";
|
|
382
|
+
else if (!delegationValidAt(verified.delegation, now))
|
|
383
|
+
status = Date.parse(verified.delegation.expiresAt) < Date.now() ? "expired" : "not yet valid";
|
|
384
|
+
else
|
|
385
|
+
status = "valid";
|
|
386
|
+
return {
|
|
387
|
+
status,
|
|
388
|
+
error: verified.ok ? null : verified.error,
|
|
389
|
+
digest,
|
|
390
|
+
agent: decoded.agent,
|
|
391
|
+
principal: decoded.principal,
|
|
392
|
+
scopes: decoded.scopes,
|
|
393
|
+
issuedAt: decoded.issuedAt,
|
|
394
|
+
expiresAt: decoded.expiresAt,
|
|
395
|
+
delegated: !!decoded.parent,
|
|
396
|
+
canDelegate: !!decoded.agentKey,
|
|
397
|
+
revoked,
|
|
398
|
+
};
|
|
399
|
+
},
|
|
400
|
+
"POST /api/grants/revoke": async (req, _url, by) => {
|
|
401
|
+
const body = object(await readBody(req));
|
|
402
|
+
const cfg = loadConfig(options.configFile);
|
|
403
|
+
if (!cfg.revokedGrants)
|
|
404
|
+
throw new HttpError(409, "the config has no revokedGrants file, which is where the gateway looks for revoked grants");
|
|
405
|
+
const env = (typeof body.grant === "string" ? safeJson(body.grant) : body.grant);
|
|
406
|
+
if (!env || typeof env !== "object")
|
|
407
|
+
throw new HttpError(400, "send the grant as a JSON object or a JSON string");
|
|
408
|
+
const decoded = decodeDelegation(env);
|
|
409
|
+
if (!decoded)
|
|
410
|
+
throw new HttpError(400, "this is not a delegation grant");
|
|
411
|
+
const digest = grantDigest(env);
|
|
412
|
+
const list = revokedList(cfg);
|
|
413
|
+
if (!list.includes(digest))
|
|
414
|
+
writeRevokedGrants(cfg.revokedGrants, [...list, digest]);
|
|
415
|
+
audit("grant.revoke", { agent: decoded.agent, principal: decoded.principal, digest, already: list.includes(digest) }, by);
|
|
416
|
+
return { digest, agent: decoded.agent, note: "the gateway refuses this grant, and every grant delegated from it, on its next call" };
|
|
417
|
+
},
|
|
418
|
+
"GET /api/revocations": async () => ({ digests: revokedList(loadConfig(options.configFile)) }),
|
|
419
|
+
"GET /api/receipts": async (_req, url) => {
|
|
420
|
+
const cfg = loadConfig(options.configFile);
|
|
421
|
+
const keys = keysOf(cfg);
|
|
422
|
+
const limit = Math.min(Math.max(Number(url.searchParams.get("limit") ?? 50) || 50, 1), 200);
|
|
423
|
+
const files = receiptFiles(cfg);
|
|
424
|
+
return { total: files.length, receipts: files.slice(0, limit).map((f) => summarize(f.id, f.file, cfg, keys)), problems: keys.problems };
|
|
425
|
+
},
|
|
426
|
+
"GET /api/audit": async () => ({
|
|
427
|
+
entries: existsSync(auditFile) ? readFileSync(auditFile, "utf8").trim().split("\n").filter(Boolean).slice(-200).reverse().map((l) => JSON.parse(l)) : [],
|
|
428
|
+
}),
|
|
429
|
+
};
|
|
430
|
+
const safeJson = (s) => {
|
|
431
|
+
try {
|
|
432
|
+
return JSON.parse(s);
|
|
433
|
+
}
|
|
434
|
+
catch {
|
|
435
|
+
throw new HttpError(400, "the grant is not valid JSON");
|
|
436
|
+
}
|
|
437
|
+
};
|
|
438
|
+
const json = (res, status, body) => {
|
|
439
|
+
// a body that was refused unread leaves the connection with data on it: close it, so the next request does not reuse it
|
|
440
|
+
res.writeHead(status, { "content-type": "application/json", "cache-control": "no-store", "x-content-type-options": "nosniff", ...(status === 413 ? { connection: "close" } : {}) });
|
|
441
|
+
res.end(JSON.stringify(body));
|
|
442
|
+
};
|
|
443
|
+
// a wrong token is slow to retry: five misses from one address lock it out for a minute
|
|
444
|
+
const misses = new Map();
|
|
445
|
+
const authorized = (req) => {
|
|
446
|
+
const ip = req.socket.remoteAddress ?? "unknown";
|
|
447
|
+
const m = misses.get(ip);
|
|
448
|
+
if (m && m.until > Date.now())
|
|
449
|
+
return { ok: false, status: 429, message: "too many wrong tokens; try again in a minute" };
|
|
450
|
+
const header = req.headers.authorization ?? "";
|
|
451
|
+
const presented = header.startsWith("Bearer ") ? header.slice(7) : "";
|
|
452
|
+
if (presented && timingSafeEqual(sha(presented), tokenHash)) {
|
|
453
|
+
misses.delete(ip);
|
|
454
|
+
return { ok: true, by: `console@${ip}` };
|
|
455
|
+
}
|
|
456
|
+
// a request with no token at all is not a guess at one, so it does not count towards the lockout
|
|
457
|
+
if (presented) {
|
|
458
|
+
const n = (m?.n ?? 0) + 1;
|
|
459
|
+
misses.set(ip, n >= 5 ? { n: 0, until: Date.now() + 60_000 } : { n, until: 0 });
|
|
460
|
+
}
|
|
461
|
+
return { ok: false, status: 401, message: "a valid bearer token is required" };
|
|
462
|
+
};
|
|
463
|
+
const server = createServer(async (req, res) => {
|
|
464
|
+
try {
|
|
465
|
+
const url = new URL(req.url ?? "/", "http://localhost");
|
|
466
|
+
if (req.method === "GET" && url.pathname === "/healthz")
|
|
467
|
+
return json(res, 200, { ok: true });
|
|
468
|
+
if (req.method === "GET" && url.pathname === "/") {
|
|
469
|
+
res.writeHead(200, {
|
|
470
|
+
"content-type": "text/html; charset=utf-8",
|
|
471
|
+
"content-security-policy": CONSOLE_CSP,
|
|
472
|
+
"x-content-type-options": "nosniff",
|
|
473
|
+
"x-frame-options": "DENY",
|
|
474
|
+
"referrer-policy": "no-referrer",
|
|
475
|
+
"cache-control": "no-store",
|
|
476
|
+
});
|
|
477
|
+
return void res.end(CONSOLE_HTML);
|
|
478
|
+
}
|
|
479
|
+
if (!url.pathname.startsWith("/api/"))
|
|
480
|
+
return json(res, 404, { error: "not found" });
|
|
481
|
+
const auth = authorized(req);
|
|
482
|
+
if (!auth.ok)
|
|
483
|
+
return json(res, auth.status, { error: auth.message });
|
|
484
|
+
const receiptId = url.pathname.match(/^\/api\/receipts\/([^/]+)$/);
|
|
485
|
+
if (req.method === "GET" && receiptId) {
|
|
486
|
+
const id = receiptId[1];
|
|
487
|
+
if (!UUID.test(id))
|
|
488
|
+
return json(res, 400, { error: "a receipt id is a UUID" });
|
|
489
|
+
const cfg = loadConfig(options.configFile);
|
|
490
|
+
const file = join(cfg.receiptsDir, `${id}.json`);
|
|
491
|
+
if (!existsSync(file) || basename(file) !== `${id}.json`)
|
|
492
|
+
return json(res, 404, { error: "no such receipt" });
|
|
493
|
+
const bundle = JSON.parse(readFileSync(file, "utf8"));
|
|
494
|
+
return json(res, 200, { summary: summarize(id, file, cfg, keysOf(cfg)), statement: decodePredicate(bundle) });
|
|
495
|
+
}
|
|
496
|
+
const handler = routes[`${req.method} ${url.pathname}`];
|
|
497
|
+
if (!handler)
|
|
498
|
+
return json(res, 404, { error: "not found" });
|
|
499
|
+
json(res, 200, await handler(req, url, auth.by));
|
|
500
|
+
}
|
|
501
|
+
catch (e) {
|
|
502
|
+
if (e instanceof HttpError)
|
|
503
|
+
return json(res, e.status, { error: e.message });
|
|
504
|
+
log(`agent-custody console: ${e instanceof Error ? e.stack ?? e.message : String(e)}`);
|
|
505
|
+
json(res, 500, { error: e instanceof Error ? e.message : "internal error" });
|
|
506
|
+
}
|
|
507
|
+
});
|
|
508
|
+
await new Promise((resolve, reject) => {
|
|
509
|
+
server.once("error", reject);
|
|
510
|
+
server.listen(options.port ?? 8795, options.host ?? "127.0.0.1", resolve);
|
|
511
|
+
});
|
|
512
|
+
const addr = server.address();
|
|
513
|
+
const host = options.host ?? "127.0.0.1";
|
|
514
|
+
return {
|
|
515
|
+
url: `http://${host === "0.0.0.0" ? "127.0.0.1" : host}:${addr.port}/`,
|
|
516
|
+
close: () => new Promise((resolve) => {
|
|
517
|
+
server.close(() => resolve());
|
|
518
|
+
server.closeAllConnections();
|
|
519
|
+
}),
|
|
520
|
+
};
|
|
521
|
+
}
|
package/dist/gateway.d.ts
CHANGED
|
@@ -44,6 +44,8 @@ export interface GatewayOptions {
|
|
|
44
44
|
log?: LogSink;
|
|
45
45
|
/** told about every receipt after it is written, in place of the exporter the config names */
|
|
46
46
|
exporter?: ReceiptExporter;
|
|
47
|
+
/** cancels the start while it is connecting to the upstreams: every upstream already started is closed and the call rejects */
|
|
48
|
+
signal?: AbortSignal;
|
|
47
49
|
}
|
|
48
50
|
/**
|
|
49
51
|
* The shared part of a gateway: the key, the policy, the issuer, the log, the upstreams, and the fact lookups. One host
|
|
@@ -57,6 +59,8 @@ export interface GatewayHost {
|
|
|
57
59
|
revoke(grantDigest: string): void;
|
|
58
60
|
/** the digests revoked so far */
|
|
59
61
|
revoked(): string[];
|
|
62
|
+
/** the names of every tool the upstreams offer, before any grant narrows them */
|
|
63
|
+
tools(): string[];
|
|
60
64
|
/** Operator-only provider lookup. Never exposed as an agent tool. Unknown/pending reservations remain held until a terminal reconciliation receipt is committed. */
|
|
61
65
|
reconcile(operationId: string): Promise<ReceiptBundle>;
|
|
62
66
|
/** closes the upstreams; every session opened from this host is finished with */
|
package/dist/gateway.js
CHANGED
|
@@ -156,41 +156,62 @@ export async function createGatewayHost(cfg, options = {}) {
|
|
|
156
156
|
const upstreams = new Map();
|
|
157
157
|
const owner = new Map();
|
|
158
158
|
const advertised = [];
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
}
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
159
|
+
const cancelled = options.signal
|
|
160
|
+
? new Promise((_, reject) => {
|
|
161
|
+
const stop = () => reject(new Error("the gateway start was cancelled"));
|
|
162
|
+
if (options.signal.aborted)
|
|
163
|
+
stop();
|
|
164
|
+
else
|
|
165
|
+
options.signal.addEventListener("abort", stop, { once: true });
|
|
166
|
+
})
|
|
167
|
+
: null;
|
|
168
|
+
cancelled?.catch(() => { });
|
|
169
|
+
/** a connection that hangs must not hold the start: it loses the race to a cancel */
|
|
170
|
+
const guard = (p) => (cancelled ? Promise.race([p, cancelled]) : p);
|
|
171
|
+
try {
|
|
172
|
+
for (const { name, cfg: u } of upstreamConfigs) {
|
|
173
|
+
options.signal?.throwIfAborted();
|
|
174
|
+
let client;
|
|
175
|
+
if ("rest" in u) {
|
|
176
|
+
client = restUpstream(name, { ...u.rest, tools: u.rest.tools.map((tool) => {
|
|
177
|
+
const rule = operationRule(tool.name);
|
|
178
|
+
return rule ? { ...tool, idempotencyHeader: rule.idempotencyHeader } : tool;
|
|
179
|
+
}) });
|
|
180
|
+
upstreams.set(name, client);
|
|
181
|
+
}
|
|
182
|
+
else if ("a2a" in u) {
|
|
183
|
+
client = a2aUpstream(name, u.a2a);
|
|
184
|
+
upstreams.set(name, client);
|
|
185
|
+
}
|
|
186
|
+
else if ("url" in u) {
|
|
187
|
+
client = new Client({ name: "agent-custody-gateway", version: GATEWAY_VERSION });
|
|
188
|
+
upstreams.set(name, client);
|
|
189
|
+
const token = u.tokenEnv ? process.env[u.tokenEnv] : undefined;
|
|
190
|
+
if (u.tokenEnv && !token)
|
|
191
|
+
throw new Error(`upstream ${name}: environment variable ${u.tokenEnv} is not set`);
|
|
192
|
+
await guard(client.connect(new StreamableHTTPClientTransport(new URL(u.url), token ? { requestInit: { headers: { authorization: `Bearer ${token}` } } } : {})));
|
|
193
|
+
}
|
|
194
|
+
else {
|
|
195
|
+
client = new Client({ name: "agent-custody-gateway", version: GATEWAY_VERSION });
|
|
196
|
+
upstreams.set(name, client);
|
|
197
|
+
await guard(client.connect(new StdioClientTransport({ command: u.command, args: u.args, env: upstreamEnv(u.env), stderr: "inherit" })));
|
|
198
|
+
}
|
|
199
|
+
const { tools } = await guard(client.listTools());
|
|
200
|
+
for (const t of tools) {
|
|
201
|
+
const other = owner.get(t.name);
|
|
202
|
+
if (other)
|
|
203
|
+
throw new Error(`tool "${t.name}" is offered by both upstream "${other}" and upstream "${name}"; a gateway needs one owner per tool`);
|
|
204
|
+
owner.set(t.name, name);
|
|
205
|
+
advertised.push(t);
|
|
189
206
|
}
|
|
190
|
-
owner.set(t.name, name);
|
|
191
|
-
advertised.push(t);
|
|
192
207
|
}
|
|
193
208
|
}
|
|
209
|
+
catch (e) {
|
|
210
|
+
// an upstream that was started stays running unless it is closed here: a failed or cancelled start leaves nothing behind
|
|
211
|
+
for (const c of upstreams.values())
|
|
212
|
+
await c.close().catch(() => { });
|
|
213
|
+
throw e;
|
|
214
|
+
}
|
|
194
215
|
for (const rule of cfg.operations?.tools ?? []) {
|
|
195
216
|
const via = upstreamConfigs.find((u) => u.name === owner.get(rule.tool));
|
|
196
217
|
const readVia = upstreamConfigs.find((u) => u.name === owner.get(rule.reconcile.tool));
|
|
@@ -593,6 +614,7 @@ export async function createGatewayHost(cfg, options = {}) {
|
|
|
593
614
|
keyid: issuer.keyid,
|
|
594
615
|
open,
|
|
595
616
|
revoke,
|
|
617
|
+
tools: () => advertised.map((t) => t.name),
|
|
596
618
|
revoked: () => {
|
|
597
619
|
reloadRevoked();
|
|
598
620
|
return [...revokedSet];
|
package/dist/index.d.ts
CHANGED
|
@@ -4,11 +4,15 @@ export type { GatewayOptions } from "./gateway.ts";
|
|
|
4
4
|
export { buildRequest, restUpstream } from "./rest.ts";
|
|
5
5
|
export { openExporter, otlpExporter, spanFor } from "./otel.ts";
|
|
6
6
|
export { hecEvent, splunkExporter } from "./splunk.ts";
|
|
7
|
+
export { serveConsole, type ConsoleOptions, type RunningConsole } from "./console.ts";
|
|
8
|
+
export { checkConfig, formatFindings, type CheckFinding, type CheckOptions } from "./check.ts";
|
|
7
9
|
export { GRANT_HEADER, grantHeader, parseGrantHeader, serveHttp } from "./gateway-http.ts";
|
|
8
10
|
export * from "./capture.ts";
|
|
9
11
|
export { A2A_CARD_PATH, A2A_RECEIPT_METADATA_KEY, A2A_STREAM_META_KEY, a2aUpstream, fetchAgentCard, serveA2a, textOf } from "./a2a.ts";
|
|
10
|
-
export { deliverMail, founderNote, PortalStore, portalHandler, readSession, sendFollowUps, servePortal, signSession, stripeRequest, verifyStripeSignature } from "./portal.ts";
|
|
11
|
-
export type { MailOptions, OAuthOptions, PortalOptions, PortalUser, Profile, RunningPortal, StripeOptions } from "./portal.ts";
|
|
12
|
+
export { deliverMail, founderNote, PortalStore, portalHandler, readSession, readSessionVia, sendFollowUps, servePortal, signSession, SsoRefusedError, stripeRequest, verifyStripeSignature } from "./portal.ts";
|
|
13
|
+
export type { MailOptions, OAuthOptions, PortalOptions, PortalUser, Profile, RunningPortal, SsoSetting, StripeOptions } from "./portal.ts";
|
|
14
|
+
export { oidcAuthorizeUrl, oidcExchange, pkce, samlAuthorizeUrl, samlValidate } from "./sso.ts";
|
|
15
|
+
export type { OidcConfig, SamlConfig, SsoIdentity } from "./sso.ts";
|
|
12
16
|
export type { HttpGatewayOptions, RunningHttpGateway } from "./gateway-http.ts";
|
|
13
17
|
export type { A2aServerOptions, AgentCard, ResolvedCard, RunningA2aServer } from "./a2a.ts";
|
|
14
18
|
export { exportLog, formatExport } from "./log-export.ts";
|