@agent-custody/receipts 0.14.0 → 0.15.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 +33 -20
- package/dist/check.d.ts +10 -0
- package/dist/check.js +179 -3
- package/dist/cli.js +82 -11
- package/dist/config.d.ts +128 -1
- package/dist/config.js +92 -3
- package/dist/console.js +16 -7
- package/dist/deny-report.js +1 -1
- package/dist/door.d.ts +203 -0
- package/dist/door.js +712 -0
- package/dist/export.d.ts +39 -0
- package/dist/export.js +95 -0
- package/dist/gateway.js +53 -21
- package/dist/index.d.ts +6 -0
- package/dist/index.js +5 -0
- package/dist/issue.js +5 -65
- package/dist/lock.d.ts +12 -0
- package/dist/lock.js +124 -0
- package/dist/log.d.ts +11 -5
- package/dist/log.js +55 -42
- package/dist/opa-server.d.ts +34 -0
- package/dist/opa-server.js +93 -0
- package/dist/policy-rego.d.ts +30 -0
- package/dist/policy-rego.js +114 -0
- package/dist/pr-summary.d.ts +25 -0
- package/dist/pr-summary.js +87 -0
- package/dist/receipt.d.ts +3 -1
- package/dist/retention.d.ts +1 -1
- package/dist/retention.js +14 -4
- package/dist/sdk/index.js +10 -3
- package/dist/simulate.d.ts +3 -1
- package/dist/simulate.js +15 -7
- package/dist/verify.js +6 -3
- package/docs/configuration.md +3 -3
- package/docs/door-signals.md +66 -0
- package/docs/door.md +168 -0
- package/docs/github-action.md +164 -0
- package/docs/policies.md +112 -1
- package/docs/sdk.md +25 -9
- package/docs/tutorials.md +3 -0
- package/docs/usage.md +2 -2
- package/docs/verification.md +9 -2
- package/package.json +14 -13
- package/templates/claude-code.cedar +287 -10
- package/vectors/audit.json +27 -27
- package/vectors/canonical.json +5 -5
- package/vectors/merkle.json +123 -0
- package/vectors/receipts.json +1258 -1005
package/dist/door.js
ADDED
|
@@ -0,0 +1,712 @@
|
|
|
1
|
+
// The door: a reverse proxy in front of a business's own HTTP surface, where the gateway is a proxy in front of an
|
|
2
|
+
// agent's tools. Every arrival, a browser, an API client, or an agent, is classified by what it presented, decided by
|
|
3
|
+
// the Cedar policy for its route, forwarded to the origin or refused, and receipted either way. Nothing here detects
|
|
4
|
+
// an agent: `unknown` means nothing was presented, `claimed` means something was asserted and could not be checked,
|
|
5
|
+
// and `verified` means a grant signed by a trusted principal names this agent for this route. The same key, policy
|
|
6
|
+
// language, issuer, log, and verifier as the gateway; the receipt's issuer kind is `door`.
|
|
7
|
+
import { randomUUID } from "node:crypto";
|
|
8
|
+
import { closeSync, fstatSync, openSync, readFileSync } from "node:fs";
|
|
9
|
+
import { createServer } from "node:http";
|
|
10
|
+
import { captureKeyFrom } from "./capture.js";
|
|
11
|
+
import { digestOf, loadPrivateKey, loadPublicKey, sha256Hex } from "./crypto.js";
|
|
12
|
+
import { decodeDelegation, delegationValidAt, verifyDelegation } from "./delegation.js";
|
|
13
|
+
import { parseGrantHeader, GRANT_HEADER } from "./gateway-http.js";
|
|
14
|
+
import { createIssuer, ReceiptPending } from "./issue.js";
|
|
15
|
+
import { openLog } from "./log-sink.js";
|
|
16
|
+
import { openExporter } from "./otel.js";
|
|
17
|
+
import { evaluate, hasPermitRule, policyDigest, policyParseErrors } from "./policy.js";
|
|
18
|
+
export const DOOR_VERSION = "0.1.0";
|
|
19
|
+
/** on every answer the door gives: the receipt that records the decision */
|
|
20
|
+
export const RECEIPT_HEADER = "x-agent-custody-receipt";
|
|
21
|
+
/** on every answer: `verified`, `claimed`, or `unknown`, what the door made of the arrival */
|
|
22
|
+
export const CLASS_HEADER = "x-agent-custody-class";
|
|
23
|
+
/** the fact the door records for every arrival, and the policy reads as `context.facts.arrival` */
|
|
24
|
+
export const ARRIVAL_FACT = "arrival";
|
|
25
|
+
/** the header an agent may use to name itself without a grant; recorded as claimed, never checked */
|
|
26
|
+
export const AGENT_HEADER = "x-agent-custody-agent";
|
|
27
|
+
const CHALLENGE_VERIFY_URL = { turnstile: "https://challenges.cloudflare.com/turnstile/v0/siteverify", hcaptcha: "https://api.hcaptcha.com/siteverify" };
|
|
28
|
+
/** a provider token is about 2 KB; a longer value is refused as failed without calling the provider */
|
|
29
|
+
export const MAX_CHALLENGE_TOKEN = 4096;
|
|
30
|
+
/**
|
|
31
|
+
* Error codes that are the provider's or the operator's fault, not the token's: a rotated secret, a site key that does not
|
|
32
|
+
* match it, an outage. Every person would get one, so they are `unavailable`, which a policy handles as the provider's
|
|
33
|
+
* state, and never `failed`, which a policy may treat as an attack. Token faults (`invalid-input-response`,
|
|
34
|
+
* `timeout-or-duplicate`, `expired-input-response`, `already-seen-response`, `missing-input-response`) stay `failed`.
|
|
35
|
+
*/
|
|
36
|
+
const PROVIDER_FAULT_CODES = new Set(["internal-error", "missing-input-secret", "invalid-input-secret", "bad-request", "sitekey-secret-mismatch", "invalid-sitekey", "missing-sitekey", "invalid-remoteip"]);
|
|
37
|
+
/**
|
|
38
|
+
* Asks the provider whether the token is good. The token and the secret go to the provider only; neither is recorded,
|
|
39
|
+
* and a redirect is never followed, since it would resend both to the Location's host. `success` is not enough: the
|
|
40
|
+
* token must have been issued on one of the site's own hostnames, and for the configured action, or a token solved on
|
|
41
|
+
* another site with this site key, or for another widget, would pass.
|
|
42
|
+
*/
|
|
43
|
+
export async function verifyChallengeToken(check, f) {
|
|
44
|
+
const { provider } = check;
|
|
45
|
+
// any client can send a value in the header: one no provider would issue costs no call
|
|
46
|
+
if (check.token.length > MAX_CHALLENGE_TOKEN)
|
|
47
|
+
return { provider, outcome: "failed", error: `the token is longer than ${MAX_CHALLENGE_TOKEN} characters and was not sent to the provider` };
|
|
48
|
+
const body = new URLSearchParams({ secret: check.secret, response: check.token, ...(check.remoteIp ? { remoteip: check.remoteIp } : {}), ...(provider === "hcaptcha" && check.siteKey ? { sitekey: check.siteKey } : {}) });
|
|
49
|
+
try {
|
|
50
|
+
const res = await f(CHALLENGE_VERIFY_URL[provider], { method: "POST", headers: { "content-type": "application/x-www-form-urlencoded" }, body, redirect: "manual", signal: AbortSignal.timeout(check.timeoutMs) });
|
|
51
|
+
if (res.status >= 300 && res.status < 400)
|
|
52
|
+
return { provider, outcome: "unavailable", error: `the provider answered a redirect (${res.status}); the secret is not resent` };
|
|
53
|
+
if (!res.ok)
|
|
54
|
+
return { provider, outcome: "unavailable", error: `the provider answered ${res.status}` };
|
|
55
|
+
const answer = (await res.json());
|
|
56
|
+
if (answer.success !== true) {
|
|
57
|
+
const codes = Array.isArray(answer["error-codes"]) ? answer["error-codes"].filter((c) => typeof c === "string") : [];
|
|
58
|
+
if (codes.some((c) => PROVIDER_FAULT_CODES.has(c)))
|
|
59
|
+
return { provider, outcome: "unavailable", error: `the provider could not check the token: ${codes.join(", ")}` };
|
|
60
|
+
return { provider, outcome: "failed", error: codes.join(", ") || "the provider refused the token" };
|
|
61
|
+
}
|
|
62
|
+
const host = typeof answer.hostname === "string" ? answer.hostname.toLowerCase() : undefined;
|
|
63
|
+
if (!host || !check.hostnames.includes(host))
|
|
64
|
+
return { provider, outcome: "failed", error: `the token was issued on ${host ?? "no hostname"}, not a hostname this door serves` };
|
|
65
|
+
if (check.action !== undefined && answer.action !== check.action)
|
|
66
|
+
return { provider, outcome: "failed", error: `the token was issued for action ${typeof answer.action === "string" ? answer.action : "(none)"}, not ${check.action}` };
|
|
67
|
+
return { provider, outcome: "passed" };
|
|
68
|
+
}
|
|
69
|
+
catch (e) {
|
|
70
|
+
return { provider, outcome: "unavailable", error: e instanceof Error ? e.message : String(e) };
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
export const RATE_BURST_MS = 10_000;
|
|
74
|
+
export const RATE_MINUTE_MS = 60_000;
|
|
75
|
+
/**
|
|
76
|
+
* Counts arrivals per source over the two windows. Each source keeps its arrival times in order with two heads that only
|
|
77
|
+
* move forward, so one arrival costs the same however many came before it in the window; the array is compacted once
|
|
78
|
+
* half of it is behind the minute head. The source key comes from the arrival, and with `trustProxy` the client may
|
|
79
|
+
* choose it, so the map bounds itself: at most `maxSources` keys, none longer than `maxKeyLength`, and a source with no
|
|
80
|
+
* arrival in the last minute is dropped every minute whether or not traffic goes on. A source forgotten early counts
|
|
81
|
+
* again from 1, which only lowers what a pace rule sees for a client that floods the map. The clock is monotonic
|
|
82
|
+
* (`performance.now`), so a step of the wall clock (an NTP correction, a VM resume) neither keeps old arrivals inside
|
|
83
|
+
* the windows nor drops new ones; an injected clock that goes back is held at the last time seen. `now` is for tests.
|
|
84
|
+
*/
|
|
85
|
+
export function createRateTracker(now = () => performance.now(), limits = {}) {
|
|
86
|
+
const maxSources = limits.maxSources ?? 10_000;
|
|
87
|
+
const maxKeyLength = limits.maxKeyLength ?? 256;
|
|
88
|
+
// least recently seen first: a hit moves its key to the end
|
|
89
|
+
const seen = new Map();
|
|
90
|
+
let last = -Infinity;
|
|
91
|
+
const clock = () => (last = Math.max(last, now()));
|
|
92
|
+
const sweep = () => {
|
|
93
|
+
const cutoff = clock() - RATE_MINUTE_MS;
|
|
94
|
+
for (const [k, v] of seen)
|
|
95
|
+
if (v.times[v.times.length - 1] <= cutoff)
|
|
96
|
+
seen.delete(k);
|
|
97
|
+
};
|
|
98
|
+
const timer = setInterval(sweep, RATE_MINUTE_MS);
|
|
99
|
+
timer.unref();
|
|
100
|
+
return {
|
|
101
|
+
hit(source) {
|
|
102
|
+
const key = source.length > maxKeyLength ? `sha256:${sha256Hex(source)}` : source;
|
|
103
|
+
const t = clock();
|
|
104
|
+
const s = seen.get(key) ?? { times: [], minuteHead: 0, burstHead: 0 };
|
|
105
|
+
s.times.push(t);
|
|
106
|
+
while (s.times[s.minuteHead] <= t - RATE_MINUTE_MS)
|
|
107
|
+
s.minuteHead += 1;
|
|
108
|
+
if (s.burstHead < s.minuteHead)
|
|
109
|
+
s.burstHead = s.minuteHead;
|
|
110
|
+
while (s.times[s.burstHead] <= t - RATE_BURST_MS)
|
|
111
|
+
s.burstHead += 1;
|
|
112
|
+
if (s.minuteHead > 64 && s.minuteHead * 2 > s.times.length) {
|
|
113
|
+
s.times = s.times.slice(s.minuteHead);
|
|
114
|
+
s.burstHead -= s.minuteHead;
|
|
115
|
+
s.minuteHead = 0;
|
|
116
|
+
}
|
|
117
|
+
seen.delete(key);
|
|
118
|
+
seen.set(key, s);
|
|
119
|
+
if (seen.size > maxSources)
|
|
120
|
+
sweep();
|
|
121
|
+
while (seen.size > maxSources)
|
|
122
|
+
seen.delete(seen.keys().next().value);
|
|
123
|
+
return { burst: s.times.length - s.burstHead, minute: s.times.length - s.minuteHead };
|
|
124
|
+
},
|
|
125
|
+
size: () => seen.size,
|
|
126
|
+
close: () => clearInterval(timer),
|
|
127
|
+
};
|
|
128
|
+
}
|
|
129
|
+
const HOP_BY_HOP = new Set(["connection", "keep-alive", "proxy-authenticate", "proxy-authorization", "te", "trailer", "transfer-encoding", "upgrade", "proxy-connection"]);
|
|
130
|
+
/** request headers the receipt records in clear; everything else is relayed and not recorded */
|
|
131
|
+
const RECORDED_HEADERS = ["user-agent", "content-type", "accept", "host"];
|
|
132
|
+
/** a JSON body up to this size is recorded in the receipt's arguments; a larger or non-JSON body is recorded by digest and size only */
|
|
133
|
+
const RECORDED_BODY_BYTES = 64 * 1024;
|
|
134
|
+
/**
|
|
135
|
+
* Headers that name the client's address or the scheme and host it used. Without trustProxy the client wrote them, and an
|
|
136
|
+
* origin that reads one (an allowlist on `X-Real-IP`, a rate limit on `Forwarded`) would trust the client's word: they
|
|
137
|
+
* are dropped, and the door sets `X-Forwarded-For`, `X-Forwarded-Host`, `X-Forwarded-Proto`, and `X-Real-IP` itself.
|
|
138
|
+
*/
|
|
139
|
+
const CLIENT_ADDRESS_HEADERS = new Set(["forwarded", "x-real-ip", "true-client-ip", "cf-connecting-ip", "x-client-ip", "x-cluster-client-ip", "fastly-client-ip"]);
|
|
140
|
+
/** connection failures in which the request never left the door: the origin cannot have acted on it */
|
|
141
|
+
const UNREACHED_CODES = new Set(["ECONNREFUSED", "ENOTFOUND", "EHOSTUNREACH", "ENETUNREACH", "EAI_AGAIN"]);
|
|
142
|
+
/**
|
|
143
|
+
* The record of the call keeps what arrived; the policy reads a copy Cedar accepts. Cedar has no `null` and no
|
|
144
|
+
* non-integer number, and refuses the whole request on either, so a body with `"coupon": null` or `"price": 9.99` would
|
|
145
|
+
* be denied whatever the policy says. In the copy a `null` is dropped and a number that is not a safe integer becomes its
|
|
146
|
+
* string; a rule that compares `price` as a number then errors, and the call is denied by that rule rather than by Cedar.
|
|
147
|
+
*/
|
|
148
|
+
export function cedarArgs(value) {
|
|
149
|
+
if (Array.isArray(value))
|
|
150
|
+
return value.filter((v) => v !== null).map(cedarArgs);
|
|
151
|
+
if (typeof value === "number")
|
|
152
|
+
return Number.isSafeInteger(value) ? value : String(value);
|
|
153
|
+
if (value && typeof value === "object") {
|
|
154
|
+
const out = {};
|
|
155
|
+
for (const [k, v] of Object.entries(value))
|
|
156
|
+
if (v !== null)
|
|
157
|
+
Object.defineProperty(out, k, { value: cedarArgs(v), enumerable: true, writable: true, configurable: true });
|
|
158
|
+
return out;
|
|
159
|
+
}
|
|
160
|
+
return value;
|
|
161
|
+
}
|
|
162
|
+
/**
|
|
163
|
+
* What a receipt records of an arrival when the config gives its route no capture rule: the method, the path, the
|
|
164
|
+
* recorded headers, and the body's size in clear; the query and the body withheld, each a salted commitment. A query can
|
|
165
|
+
* carry an API key and a form body a password. Set a rule for the route (or `"*"`) to record more in clear.
|
|
166
|
+
*/
|
|
167
|
+
export const DOOR_DEFAULT_CAPTURE = { args: { mode: "digest", clear: ["method", "path", "headers", "bodyBytes", "bodyOversized"] }, result: { mode: "clear" }, facts: { mode: "clear" } };
|
|
168
|
+
/**
|
|
169
|
+
* The path as the origin will read it: each segment percent-decoded once, so that `/%61dmin` falls under `/admin/*`, and
|
|
170
|
+
* empty segments merged, so that `//admin/users` and `/admin//users` fall under it too (nginx, Apache, and many
|
|
171
|
+
* frameworks merge them, and the origin would serve the admin page to an arrival the door matched as something else).
|
|
172
|
+
* A trailing slash is kept. Refused when a segment does not decode, or decodes to a slash, a backslash, or a dot
|
|
173
|
+
* segment: the origin would then read a path the door did not match. `relay` is the merged, decoded path encoded once
|
|
174
|
+
* more, the form the origin is sent, so the door and the origin read one path.
|
|
175
|
+
*/
|
|
176
|
+
export function normalizePath(pathname) {
|
|
177
|
+
const segments = [];
|
|
178
|
+
for (const raw of pathname.split("/")) {
|
|
179
|
+
if (raw === "")
|
|
180
|
+
continue;
|
|
181
|
+
let segment;
|
|
182
|
+
try {
|
|
183
|
+
segment = decodeURIComponent(raw);
|
|
184
|
+
}
|
|
185
|
+
catch {
|
|
186
|
+
return { problem: `the path segment "${raw}" does not percent-decode` };
|
|
187
|
+
}
|
|
188
|
+
if (segment.includes("/") || segment.includes("\\"))
|
|
189
|
+
return { problem: `the path segment "${raw}" decodes to a slash` };
|
|
190
|
+
if (segment === "." || segment === "..")
|
|
191
|
+
return { problem: `the path segment "${raw}" decodes to a dot segment` };
|
|
192
|
+
if (segment === "")
|
|
193
|
+
return { problem: `the path segment "${raw}" decodes to nothing` };
|
|
194
|
+
segments.push(segment);
|
|
195
|
+
}
|
|
196
|
+
const tail = segments.length > 0 && pathname.endsWith("/") ? "/" : "";
|
|
197
|
+
return { path: `/${segments.join("/")}${tail}`, relay: `/${segments.map(encodeSegment).join("/")}${tail}` };
|
|
198
|
+
}
|
|
199
|
+
/** A path segment encoded once: what `encodeURIComponent` does, except that the characters a path segment may carry in clear stay in clear. */
|
|
200
|
+
function encodeSegment(segment) {
|
|
201
|
+
return encodeURIComponent(segment).replace(/%(3A|40|24|26|2B|2C|3B|3D)/gi, (m) => decodeURIComponent(m));
|
|
202
|
+
}
|
|
203
|
+
/** The request target as a URL whose host is the door's own: an origin-form target `//x/y` is a path, never a scheme-relative URL. */
|
|
204
|
+
function requestUrl(req) {
|
|
205
|
+
const raw = req.url ?? "/";
|
|
206
|
+
return raw.startsWith("/") ? new URL(`http://door${raw}`) : new URL(raw, "http://door");
|
|
207
|
+
}
|
|
208
|
+
/** A path without its trailing slash: `/refunds/` and `/refunds` are one route. */
|
|
209
|
+
const bare = (p) => (p.length > 1 && p.endsWith("/") ? p.slice(0, -1) : p);
|
|
210
|
+
/** The route an arrival falls under: the first configured route whose methods and decoded path match, else the unmatched name. A trailing slash matches as no trailing slash. */
|
|
211
|
+
export function matchRoute(routes, unmatched, method, pathname) {
|
|
212
|
+
const path = bare(pathname);
|
|
213
|
+
for (const r of routes) {
|
|
214
|
+
if (r.methods && !r.methods.includes(method))
|
|
215
|
+
continue;
|
|
216
|
+
if (r.path === "*")
|
|
217
|
+
return r.name;
|
|
218
|
+
if (r.path.endsWith("/*")) {
|
|
219
|
+
const prefix = bare(r.path.slice(0, -2)) || "/";
|
|
220
|
+
if (path === prefix || path.startsWith(prefix === "/" ? "/" : `${prefix}/`))
|
|
221
|
+
return r.name;
|
|
222
|
+
}
|
|
223
|
+
else if (bare(r.path) === path)
|
|
224
|
+
return r.name;
|
|
225
|
+
}
|
|
226
|
+
return unmatched;
|
|
227
|
+
}
|
|
228
|
+
/**
|
|
229
|
+
* The arrival's address: the socket's, or with trustProxy the last address in `X-Forwarded-For`, the one the proxy in
|
|
230
|
+
* front of the door appended. Everything before it was sent by the client, which may write what it likes there.
|
|
231
|
+
*/
|
|
232
|
+
export function remoteOf(req, trustProxy) {
|
|
233
|
+
if (trustProxy) {
|
|
234
|
+
const xff = req.headers["x-forwarded-for"];
|
|
235
|
+
const last = (Array.isArray(xff) ? xff.join(",") : xff)?.split(",").map((a) => a.trim()).filter(Boolean).pop();
|
|
236
|
+
if (last)
|
|
237
|
+
return last;
|
|
238
|
+
}
|
|
239
|
+
return req.socket.remoteAddress ?? "unknown";
|
|
240
|
+
}
|
|
241
|
+
/**
|
|
242
|
+
* What the arrival presented, checked where it can be. A grant signed by a trusted principal, in its window, naming this
|
|
243
|
+
* route among its scopes, makes the arrival `verified` and its principal attested. A grant that is out of scope, expired,
|
|
244
|
+
* or signed by a stranger leaves the arrival `claimed`: it asserted an identity the door could not accept for this route.
|
|
245
|
+
* An `x-agent-custody-agent` header or an HTTP signature header alone is `claimed`. Nothing at all is `unknown`.
|
|
246
|
+
*/
|
|
247
|
+
export function classifyArrival(req, trusted, route, trustProxy, at) {
|
|
248
|
+
const url = requestUrl(req);
|
|
249
|
+
const method = (req.method ?? "GET").toUpperCase();
|
|
250
|
+
const declaredRaw = req.headers[AGENT_HEADER];
|
|
251
|
+
const declared = typeof declaredRaw === "string" && declaredRaw.trim() ? declaredRaw.trim().slice(0, 200) : undefined;
|
|
252
|
+
const signature = typeof req.headers["signature-input"] === "string";
|
|
253
|
+
const norm = normalizePath(url.pathname);
|
|
254
|
+
const base = { signature, ...(declared ? { declared } : {}), remote: remoteOf(req, trustProxy), method, path: "path" in norm ? norm.path : url.pathname, route };
|
|
255
|
+
const envelope = parseGrantHeader(req);
|
|
256
|
+
if (!envelope) {
|
|
257
|
+
const claimed = !!declared || signature;
|
|
258
|
+
return { arrival: { class: claimed ? "claimed" : "unknown", subject: declared ?? "unknown", grant: "absent", ...base } };
|
|
259
|
+
}
|
|
260
|
+
const checked = verifyDelegation(envelope, trusted);
|
|
261
|
+
const asserted = decodeDelegation(envelope)?.agent;
|
|
262
|
+
const subject = declared ?? asserted ?? "unknown";
|
|
263
|
+
if (!checked.ok)
|
|
264
|
+
return { arrival: { class: "claimed", subject, grant: "invalid", grantError: checked.error, ...base } };
|
|
265
|
+
const grant = checked.delegation;
|
|
266
|
+
if (!delegationValidAt(grant, at))
|
|
267
|
+
return { arrival: { class: "claimed", subject: grant.agent, grant: "invalid", grantError: "the grant is outside its validity window", ...base } };
|
|
268
|
+
if (!grant.scopes.includes(route))
|
|
269
|
+
return { arrival: { class: "claimed", subject: grant.agent, grant: "out-of-scope", grantError: `route "${route}" is not in the grant's scopes`, ...base } };
|
|
270
|
+
return { arrival: { class: "verified", subject: grant.agent, grant: "verified", ...base }, delegation: { envelope, grant, principalKeyid: checked.keyid } };
|
|
271
|
+
}
|
|
272
|
+
/** methods that must not change anything at the origin; every other method is relayed only after its receipt is committed to the log */
|
|
273
|
+
const SAFE_METHODS = new Set(["GET", "HEAD", "OPTIONS"]);
|
|
274
|
+
/** The body, or how many bytes had arrived when it passed the limit; the rest is drained and dropped. */
|
|
275
|
+
function readBody(req, max) {
|
|
276
|
+
return new Promise((resolve, reject) => {
|
|
277
|
+
const chunks = [];
|
|
278
|
+
let size = 0;
|
|
279
|
+
req.on("data", (c) => {
|
|
280
|
+
size += c.length;
|
|
281
|
+
if (size > max) {
|
|
282
|
+
resolve({ oversized: true, bytes: size });
|
|
283
|
+
req.removeAllListeners("data");
|
|
284
|
+
req.resume();
|
|
285
|
+
return;
|
|
286
|
+
}
|
|
287
|
+
chunks.push(c);
|
|
288
|
+
});
|
|
289
|
+
req.on("end", () => resolve({ body: Buffer.concat(chunks) }));
|
|
290
|
+
req.on("error", reject);
|
|
291
|
+
});
|
|
292
|
+
}
|
|
293
|
+
/** The origin's answer, or how many bytes had arrived when it passed the limit; the rest is not read. */
|
|
294
|
+
async function readResponse(upstream, max) {
|
|
295
|
+
if (!upstream.body)
|
|
296
|
+
return { body: Buffer.alloc(0) };
|
|
297
|
+
const reader = upstream.body.getReader();
|
|
298
|
+
const chunks = [];
|
|
299
|
+
let size = 0;
|
|
300
|
+
for (;;) {
|
|
301
|
+
const { done, value } = await reader.read();
|
|
302
|
+
if (done)
|
|
303
|
+
return { body: Buffer.concat(chunks) };
|
|
304
|
+
size += value.length;
|
|
305
|
+
if (size > max) {
|
|
306
|
+
await reader.cancel().catch(() => undefined);
|
|
307
|
+
return { oversized: true, bytes: size };
|
|
308
|
+
}
|
|
309
|
+
chunks.push(value);
|
|
310
|
+
}
|
|
311
|
+
}
|
|
312
|
+
/** The query as own properties: a parameter named `constructor` or `__proto__` is a parameter, never an inherited member or the prototype. */
|
|
313
|
+
export function queryOf(url) {
|
|
314
|
+
const pairs = new Map();
|
|
315
|
+
for (const [k, v] of url.searchParams) {
|
|
316
|
+
const prior = pairs.get(k);
|
|
317
|
+
pairs.set(k, prior === undefined ? v : Array.isArray(prior) ? [...prior, v] : [prior, v]);
|
|
318
|
+
}
|
|
319
|
+
return Object.fromEntries(pairs);
|
|
320
|
+
}
|
|
321
|
+
/** Whether a failed fetch never left the door: a refused or unresolved connection. Anything else (a timeout, a reset) may have reached the origin. */
|
|
322
|
+
function unreached(e) {
|
|
323
|
+
const cause = e?.cause;
|
|
324
|
+
if (!cause)
|
|
325
|
+
return false;
|
|
326
|
+
if (typeof cause.code === "string")
|
|
327
|
+
return UNREACHED_CODES.has(cause.code);
|
|
328
|
+
// fetch refuses a port on its blocked list before it connects
|
|
329
|
+
if (cause.message === "bad port")
|
|
330
|
+
return true;
|
|
331
|
+
return Array.isArray(cause.errors) && cause.errors.length > 0 && cause.errors.every((x) => typeof x?.code === "string" && UNREACHED_CODES.has(x.code));
|
|
332
|
+
}
|
|
333
|
+
export async function createDoorHost(cfg, options = {}) {
|
|
334
|
+
const key = loadPrivateKey(cfg.identity.keyFile);
|
|
335
|
+
const trusted = cfg.trustedPrincipalKeys.map(loadPublicKey);
|
|
336
|
+
const captureKey = cfg.captureKeyEnv ? captureKeyFrom(process.env[cfg.captureKeyEnv] ?? (() => { throw new Error(`capture key: environment variable ${cfg.captureKeyEnv} is not set`); })()) : undefined;
|
|
337
|
+
for (const [route, rule] of Object.entries(cfg.capture ?? {})) {
|
|
338
|
+
for (const side of [rule.args, rule.result, rule.facts])
|
|
339
|
+
if (side?.mode === "encrypted" && !captureKey)
|
|
340
|
+
throw new Error(`capture for ${route} uses mode encrypted, which needs captureKeyEnv`);
|
|
341
|
+
}
|
|
342
|
+
const originHeaders = { ...(cfg.origin.headers ?? {}) };
|
|
343
|
+
for (const [header, variable] of Object.entries(cfg.origin.headerEnv ?? {})) {
|
|
344
|
+
const v = process.env[variable];
|
|
345
|
+
if (!v)
|
|
346
|
+
throw new Error(`origin: environment variable ${variable} is not set`);
|
|
347
|
+
originHeaders[header] = v;
|
|
348
|
+
}
|
|
349
|
+
const origin = new URL(cfg.origin.url);
|
|
350
|
+
const originPath = origin.pathname.replace(/\/$/, "");
|
|
351
|
+
const f = options.fetch ?? fetch;
|
|
352
|
+
const challengeSecret = cfg.challenge ? process.env[cfg.challenge.secretEnv] : undefined;
|
|
353
|
+
if (cfg.challenge && !challengeSecret)
|
|
354
|
+
throw new Error(`challenge: environment variable ${cfg.challenge.secretEnv} is not set`);
|
|
355
|
+
const challengeHeader = cfg.challenge?.header.toLowerCase();
|
|
356
|
+
let challengesInFlight = 0;
|
|
357
|
+
const sink = options.log ?? openLog(cfg, key);
|
|
358
|
+
// a route the config gives no rule falls to "*", and without a "*" rule of the config's own, to the door's default
|
|
359
|
+
const rules = cfg.capture && Object.hasOwn(cfg.capture, "*") ? cfg.capture : { ...(cfg.capture ?? {}), "*": DOOR_DEFAULT_CAPTURE };
|
|
360
|
+
const issuer = createIssuer(key, cfg.receiptsDir, sink, { exporter: options.exporter ?? openExporter(cfg), capture: { rules, key: captureKey } });
|
|
361
|
+
const issuedBy = { kind: "door", keyid: issuer.keyid, version: DOOR_VERSION, framework: "http" };
|
|
362
|
+
const precommit = new Set(cfg.precommit);
|
|
363
|
+
const rates = createRateTracker();
|
|
364
|
+
// The policy, re-read when the file changes, as the gateway does; a file that does not parse is refused and the
|
|
365
|
+
// policy in force stays. The bytes and the metadata come from one open file.
|
|
366
|
+
const readPolicy = () => {
|
|
367
|
+
const fd = openSync(cfg.policyFile, "r");
|
|
368
|
+
try {
|
|
369
|
+
const st = fstatSync(fd);
|
|
370
|
+
return { text: readFileSync(fd, "utf8"), key: `${st.ino}:${st.mtimeMs}:${st.ctimeMs}:${st.size}` };
|
|
371
|
+
}
|
|
372
|
+
finally {
|
|
373
|
+
closeSync(fd);
|
|
374
|
+
}
|
|
375
|
+
};
|
|
376
|
+
const first = readPolicy();
|
|
377
|
+
const errors = policyParseErrors(first.text);
|
|
378
|
+
if (errors.length)
|
|
379
|
+
throw new Error(`policy ${cfg.policyFile} does not parse: ${errors.join("; ")}`);
|
|
380
|
+
if (!hasPermitRule(first.text))
|
|
381
|
+
console.error(`agent-custody door: ${cfg.policyFile} has no permit rule, so every arrival is refused`);
|
|
382
|
+
let policyNow = { text: first.text, digest: policyDigest(first.text), key: first.key };
|
|
383
|
+
const currentPolicy = () => {
|
|
384
|
+
try {
|
|
385
|
+
const next = readPolicy();
|
|
386
|
+
if (next.key !== policyNow.key) {
|
|
387
|
+
const problems = policyParseErrors(next.text);
|
|
388
|
+
if (problems.length)
|
|
389
|
+
console.error(`agent-custody door: POLICY NOT RELOADED: ${cfg.policyFile} ${problems.join("; ")}; policy ${policyNow.digest} stays in force`);
|
|
390
|
+
else
|
|
391
|
+
policyNow = { text: next.text, digest: policyDigest(next.text), key: next.key };
|
|
392
|
+
}
|
|
393
|
+
}
|
|
394
|
+
catch (e) {
|
|
395
|
+
console.error(`agent-custody door: cannot read ${cfg.policyFile}: ${e instanceof Error ? e.message : String(e)}; policy ${policyNow.digest} stays in force`);
|
|
396
|
+
}
|
|
397
|
+
return policyNow;
|
|
398
|
+
};
|
|
399
|
+
const json = (res, status, headers, body) => {
|
|
400
|
+
res.writeHead(status, { "content-type": "application/json", "cache-control": "no-store", ...headers });
|
|
401
|
+
res.end(JSON.stringify(body));
|
|
402
|
+
};
|
|
403
|
+
// Each arrival holds its body (up to maxBodyBytes) and the origin's answer (up to maxResponseBytes) in memory until it
|
|
404
|
+
// is answered. Past maxInFlight arrivals at once, the next is answered 503 before its body is read: it is not decided,
|
|
405
|
+
// relayed, or receipted.
|
|
406
|
+
let inFlight = 0;
|
|
407
|
+
async function handle(req, res) {
|
|
408
|
+
if (inFlight >= cfg.maxInFlight) {
|
|
409
|
+
req.resume();
|
|
410
|
+
res.writeHead(503, { "content-type": "application/json", "cache-control": "no-store", "retry-after": "1" });
|
|
411
|
+
res.end(JSON.stringify({ error: `the door is handling ${cfg.maxInFlight} requests; this one was not read, decided, or relayed. Retry` }));
|
|
412
|
+
return;
|
|
413
|
+
}
|
|
414
|
+
inFlight += 1;
|
|
415
|
+
try {
|
|
416
|
+
await decideAndAnswer(req, res);
|
|
417
|
+
}
|
|
418
|
+
finally {
|
|
419
|
+
inFlight -= 1;
|
|
420
|
+
}
|
|
421
|
+
}
|
|
422
|
+
async function decideAndAnswer(req, res) {
|
|
423
|
+
const receiptId = randomUUID();
|
|
424
|
+
const timestamp = new Date().toISOString();
|
|
425
|
+
res.setHeader(RECEIPT_HEADER, receiptId);
|
|
426
|
+
const url = requestUrl(req);
|
|
427
|
+
const method = (req.method ?? "GET").toUpperCase();
|
|
428
|
+
// A path that does not decode cleanly is never relayed; it falls under the unmatched route for the receipt.
|
|
429
|
+
const norm = normalizePath(url.pathname);
|
|
430
|
+
const path = "path" in norm ? norm.path : url.pathname;
|
|
431
|
+
const route = "path" in norm ? matchRoute(cfg.routes, cfg.unmatchedRoute, method, path) : cfg.unmatchedRoute;
|
|
432
|
+
const { arrival, delegation } = classifyArrival(req, trusted, route, !!cfg.trustProxy, timestamp);
|
|
433
|
+
const by = delegation ? "agent" : "remote";
|
|
434
|
+
arrival.rate = { by, ...rates.hit(`${by}:${delegation ? arrival.subject : arrival.remote}`) };
|
|
435
|
+
if (cfg.challenge && challengeHeader) {
|
|
436
|
+
const c = cfg.challenge;
|
|
437
|
+
const token = req.headers[challengeHeader];
|
|
438
|
+
if (typeof token !== "string" || !token.trim())
|
|
439
|
+
arrival.challenge = { provider: c.provider, outcome: "absent" };
|
|
440
|
+
// every arrival with a token waits on the provider, so the checks at once are bounded; past that, unavailable
|
|
441
|
+
else if (challengesInFlight >= c.maxInFlight)
|
|
442
|
+
arrival.challenge = { provider: c.provider, outcome: "unavailable", error: `${c.maxInFlight} challenge checks are already waiting on the provider` };
|
|
443
|
+
else {
|
|
444
|
+
challengesInFlight++;
|
|
445
|
+
try {
|
|
446
|
+
// without trustProxy the socket's address may be a proxy's, and the provider would refuse the client's token on it
|
|
447
|
+
arrival.challenge = await verifyChallengeToken({ provider: c.provider, secret: challengeSecret, token: token.trim(), ...(cfg.trustProxy ? { remoteIp: arrival.remote } : {}), hostnames: c.hostnames, ...(c.action ? { action: c.action } : {}), siteKey: c.siteKey, timeoutMs: c.timeoutMs }, f);
|
|
448
|
+
}
|
|
449
|
+
finally {
|
|
450
|
+
challengesInFlight--;
|
|
451
|
+
}
|
|
452
|
+
}
|
|
453
|
+
}
|
|
454
|
+
const { text: policyText, digest: pDigest } = currentPolicy();
|
|
455
|
+
const read = await readBody(req, cfg.maxBodyBytes);
|
|
456
|
+
const body = "body" in read ? read.body : null;
|
|
457
|
+
const headers = {};
|
|
458
|
+
for (const name of RECORDED_HEADERS) {
|
|
459
|
+
const v = req.headers[name];
|
|
460
|
+
if (typeof v === "string")
|
|
461
|
+
headers[name] = v;
|
|
462
|
+
}
|
|
463
|
+
const contentType = req.headers["content-type"] ?? "";
|
|
464
|
+
let recordedBody;
|
|
465
|
+
if (body && body.length > 0 && body.length <= RECORDED_BODY_BYTES && /^application\/json\b/i.test(contentType)) {
|
|
466
|
+
try {
|
|
467
|
+
recordedBody = JSON.parse(body.toString("utf8"));
|
|
468
|
+
}
|
|
469
|
+
catch {
|
|
470
|
+
recordedBody = undefined;
|
|
471
|
+
}
|
|
472
|
+
}
|
|
473
|
+
// An oversized body is dropped before anything is decided: the receipt records how far it was read and that there
|
|
474
|
+
// is no digest of it, rather than a digest of nothing.
|
|
475
|
+
const args = {
|
|
476
|
+
method,
|
|
477
|
+
path,
|
|
478
|
+
query: queryOf(url),
|
|
479
|
+
headers,
|
|
480
|
+
...(recordedBody !== undefined ? { body: recordedBody } : {}),
|
|
481
|
+
...(body ? { bodyBytes: body.length, bodyDigest: sha256Hex(body) } : { bodyBytes: read.bytes, bodyOversized: true }),
|
|
482
|
+
};
|
|
483
|
+
const facts = { [ARRIVAL_FACT]: { tool: "door.arrival", args: {}, value: arrival, resultDigest: digestOf(arrival), provenance: "observed" } };
|
|
484
|
+
// The Cedar principal is an agent the door checked: the one a verified grant names. A declared name, or the agent a
|
|
485
|
+
// rejected grant names, stays in the arrival fact as a claim, so a permit on `principal == Agent::"x"` cannot be
|
|
486
|
+
// satisfied by sending a header.
|
|
487
|
+
let policy;
|
|
488
|
+
try {
|
|
489
|
+
policy = evaluate(policyText, {
|
|
490
|
+
agentId: delegation ? delegation.grant.agent : "unknown",
|
|
491
|
+
tool: route,
|
|
492
|
+
context: { args: cedarArgs(args), facts: { [ARRIVAL_FACT]: arrival }, ...(delegation ? { grant: { principal: delegation.grant.principal, scopes: delegation.grant.scopes } } : {}) },
|
|
493
|
+
});
|
|
494
|
+
}
|
|
495
|
+
catch (e) {
|
|
496
|
+
policy = { decision: "deny", reasons: [], errors: [String(e instanceof Error ? e.message : e)], policyDigest: pDigest };
|
|
497
|
+
}
|
|
498
|
+
if (cfg.mode === "observe")
|
|
499
|
+
policy = { ...policy, enforced: false };
|
|
500
|
+
const forward = policy.decision === "allow" || policy.enforced === false;
|
|
501
|
+
const head = {
|
|
502
|
+
receiptId,
|
|
503
|
+
timestamp,
|
|
504
|
+
issuer: issuedBy,
|
|
505
|
+
principal: delegation ? { id: delegation.grant.principal, keyid: delegation.principalKeyid, provenance: "attested" } : { id: null, provenance: "claimed" },
|
|
506
|
+
agent: { id: arrival.subject, provenance: delegation ? "attested" : "claimed" },
|
|
507
|
+
...(delegation ? { delegation: { envelope: delegation.envelope, provenance: "attested" } } : {}),
|
|
508
|
+
tool: { name: route, provenance: "observed" },
|
|
509
|
+
request: { args, argsDigest: digestOf(args), provenance: "claimed" },
|
|
510
|
+
facts,
|
|
511
|
+
policy: { ...policy, provenance: "observed" },
|
|
512
|
+
};
|
|
513
|
+
let execution;
|
|
514
|
+
let authorization;
|
|
515
|
+
let answer;
|
|
516
|
+
let withheldStatus = 503;
|
|
517
|
+
// set when the relay failed before the request left the door; any other relay failure leaves the outcome unknown
|
|
518
|
+
let notSent = false;
|
|
519
|
+
if (!forward) {
|
|
520
|
+
execution = { status: "denied", reason: [...policy.reasons, ...policy.errors].join("; ") || "no permit policy matched", provenance: "observed" };
|
|
521
|
+
}
|
|
522
|
+
else if ("problem" in norm) {
|
|
523
|
+
withheldStatus = 400;
|
|
524
|
+
execution = { status: "withheld", reason: `the path was not relayed: ${norm.problem}`, provenance: "observed" };
|
|
525
|
+
}
|
|
526
|
+
else if (body === null) {
|
|
527
|
+
withheldStatus = 413;
|
|
528
|
+
execution = { status: "withheld", reason: `the request body is larger than ${cfg.maxBodyBytes} bytes and was not relayed`, provenance: "observed" };
|
|
529
|
+
}
|
|
530
|
+
else {
|
|
531
|
+
if (!SAFE_METHODS.has(method) || precommit.has("*") || precommit.has(route)) {
|
|
532
|
+
// A request that can change something at the origin is committed to the log before it is relayed, so that
|
|
533
|
+
// evidence of the side effect exists before the side effect does. If the log will not take it, the request
|
|
534
|
+
// is not relayed; in observe mode it is relayed and the missing authorization is printed.
|
|
535
|
+
try {
|
|
536
|
+
authorization = await issuer.authorize(head);
|
|
537
|
+
}
|
|
538
|
+
catch (e) {
|
|
539
|
+
if (cfg.mode === "observe")
|
|
540
|
+
console.error(`agent-custody door (observe mode): the log did not commit the authorization for ${route}, receipt ${receiptId}; the request was relayed without it: ${String(e instanceof Error ? e.message : e)}`);
|
|
541
|
+
else
|
|
542
|
+
execution = { status: "withheld", reason: `the log did not commit the authorization, so the request was not relayed: ${String(e instanceof Error ? e.message : e)}`, provenance: "observed" };
|
|
543
|
+
}
|
|
544
|
+
}
|
|
545
|
+
}
|
|
546
|
+
if (!execution) {
|
|
547
|
+
let upstream;
|
|
548
|
+
try {
|
|
549
|
+
// The path is set on a copy of the origin's URL, never resolved against it: resolving `//evil.example/x` would
|
|
550
|
+
// move the relay, with the origin's credentials, to another host.
|
|
551
|
+
const target = new URL(origin);
|
|
552
|
+
target.pathname = originPath + norm.relay;
|
|
553
|
+
target.search = url.search;
|
|
554
|
+
const out = new Headers();
|
|
555
|
+
for (const [name, value] of Object.entries(req.headers)) {
|
|
556
|
+
// `expect` is the client's conversation with the door, which Node answered; fetch refuses to carry it
|
|
557
|
+
if (value === undefined || HOP_BY_HOP.has(name) || name === "host" || name === "expect" || name === GRANT_HEADER || name === AGENT_HEADER || name === challengeHeader || name === "accept-encoding")
|
|
558
|
+
continue;
|
|
559
|
+
if (!cfg.trustProxy && (CLIENT_ADDRESS_HEADERS.has(name) || name.startsWith("x-forwarded-")))
|
|
560
|
+
continue;
|
|
561
|
+
// the grant travelled in Authorization: it is the door's credential, not the origin's
|
|
562
|
+
if (name === "authorization" && arrival.grant !== "absent" && !req.headers[GRANT_HEADER])
|
|
563
|
+
continue;
|
|
564
|
+
out.set(name, Array.isArray(value) ? value.join(", ") : value);
|
|
565
|
+
}
|
|
566
|
+
out.set("accept-encoding", "identity");
|
|
567
|
+
// Behind a trusted proxy the chain it sent is kept and the socket's address appended, as any proxy does; otherwise
|
|
568
|
+
// whatever the client wrote in these headers is replaced.
|
|
569
|
+
const inbound = (name) => (cfg.trustProxy ? (Array.isArray(req.headers[name]) ? req.headers[name].join(", ") : req.headers[name]) : undefined);
|
|
570
|
+
const socketAddress = req.socket.remoteAddress ?? "unknown";
|
|
571
|
+
const chain = inbound("x-forwarded-for");
|
|
572
|
+
out.set("x-forwarded-for", chain ? `${chain}, ${socketAddress}` : socketAddress);
|
|
573
|
+
out.set("x-forwarded-host", inbound("x-forwarded-host") || req.headers.host || "");
|
|
574
|
+
out.set("x-forwarded-proto", inbound("x-forwarded-proto") || "http");
|
|
575
|
+
if (!cfg.trustProxy)
|
|
576
|
+
out.set("x-real-ip", socketAddress);
|
|
577
|
+
out.set(RECEIPT_HEADER, receiptId);
|
|
578
|
+
out.set(CLASS_HEADER, arrival.class);
|
|
579
|
+
for (const [h, v] of Object.entries(originHeaders))
|
|
580
|
+
out.set(h, v);
|
|
581
|
+
upstream = await f(target, { method, headers: out, ...(method === "GET" || method === "HEAD" ? {} : { body: new Uint8Array(body) }), redirect: "manual", signal: AbortSignal.timeout(cfg.origin.timeoutMs) });
|
|
582
|
+
const got = await readResponse(upstream, cfg.maxResponseBytes);
|
|
583
|
+
const back = {};
|
|
584
|
+
upstream.headers.forEach((v, k) => { if (!HOP_BY_HOP.has(k) && k !== "content-length" && k !== "content-encoding" && k !== "set-cookie")
|
|
585
|
+
back[k] = v; });
|
|
586
|
+
// every cookie the origin set, not the last one: `forEach` gives them one at a time under the same name
|
|
587
|
+
const cookies = upstream.headers.getSetCookie();
|
|
588
|
+
if (cookies.length)
|
|
589
|
+
back["set-cookie"] = cookies;
|
|
590
|
+
// A redirect to the origin's own host would take the client's next request around the door: it is rewritten to a
|
|
591
|
+
// path on the door, which the client follows back through it, whatever the scheme or port. A path under the
|
|
592
|
+
// origin's path loses that prefix; any other path, including one the parser normalised out of it (`/shop/../admin`),
|
|
593
|
+
// is kept as it is, so the request still arrives at the door and meets its route and policy there.
|
|
594
|
+
if (typeof back.location === "string") {
|
|
595
|
+
try {
|
|
596
|
+
const loc = new URL(back.location, target);
|
|
597
|
+
if (loc.hostname === origin.hostname) {
|
|
598
|
+
const inside = loc.pathname === originPath || loc.pathname.startsWith(`${originPath}/`);
|
|
599
|
+
back.location = (inside ? loc.pathname.slice(originPath.length) || "/" : loc.pathname) + loc.search + loc.hash;
|
|
600
|
+
}
|
|
601
|
+
}
|
|
602
|
+
catch { /* not a URL: relayed as the origin sent it */ }
|
|
603
|
+
}
|
|
604
|
+
const contentType = typeof back["content-type"] === "string" ? { contentType: back["content-type"] } : {};
|
|
605
|
+
// The origin has answered either way, so the request happened: a response too large to relay is still recorded
|
|
606
|
+
// as executed, by its size, so that nobody retries a refund on the strength of the 502 the client gets.
|
|
607
|
+
const result = "body" in got
|
|
608
|
+
? { status: upstream.status, ...contentType, bodyBytes: got.body.length, bodyDigest: sha256Hex(got.body) }
|
|
609
|
+
: { status: upstream.status, ...contentType, bodyBytes: got.bytes, bodyOversized: true };
|
|
610
|
+
if ("body" in got)
|
|
611
|
+
answer = { status: upstream.status, headers: back, body: got.body };
|
|
612
|
+
execution = { status: upstream.status >= 500 ? "failed" : "executed", result, resultDigest: digestOf(result), provenance: "observed" };
|
|
613
|
+
}
|
|
614
|
+
catch (e) {
|
|
615
|
+
// The request may have reached the origin unless the connection was refused or the host did not resolve: a
|
|
616
|
+
// timeout while the origin works, a reset, or a body that stops after the headers all leave the outcome unknown,
|
|
617
|
+
// and the client is told not to retry rather than that the origin could not be reached.
|
|
618
|
+
const message = String(e instanceof Error ? e.message : e);
|
|
619
|
+
notSent = !upstream && unreached(e);
|
|
620
|
+
execution = { status: "error", error: notSent ? `the origin could not be reached: ${message}` : `the origin may have acted on the request${upstream ? ` (it answered ${upstream.status} and its body did not arrive)` : ""}: ${message}`, provenance: "observed" };
|
|
621
|
+
}
|
|
622
|
+
}
|
|
623
|
+
let logPending = false;
|
|
624
|
+
try {
|
|
625
|
+
await issuer.issue({
|
|
626
|
+
...head,
|
|
627
|
+
session: { id: null, toolUseId: null, provenance: "claimed" },
|
|
628
|
+
model: { id: null, provenance: "claimed" },
|
|
629
|
+
...(authorization ? { authorization } : {}),
|
|
630
|
+
execution,
|
|
631
|
+
}, undefined, undefined, { deferLog: true });
|
|
632
|
+
}
|
|
633
|
+
catch (e) {
|
|
634
|
+
if (!(e instanceof ReceiptPending)) {
|
|
635
|
+
// The decision was carried out and the receipt of it could not be written. The client is told what happened at
|
|
636
|
+
// the origin rather than "not relayed", which would invite a retry of a refund that went through.
|
|
637
|
+
console.error(`agent-custody door: receipt ${receiptId} was not written: ${e instanceof Error ? e.message : String(e)}`);
|
|
638
|
+
const outcome = execution.status === "executed" || execution.status === "failed" ? "the origin acted on the request; its answer is not relayed because there is no receipt of it. Do not retry" : execution.status === "error" ? (notSent ? "the origin could not be reached" : "the origin may have acted on the request. Do not retry") : "nothing was relayed";
|
|
639
|
+
return json(res, 500, { [CLASS_HEADER]: arrival.class }, { error: "the door could not record this request", outcome, receipt: receiptId });
|
|
640
|
+
}
|
|
641
|
+
console.error(`agent-custody door: ${e.message}`);
|
|
642
|
+
logPending = true;
|
|
643
|
+
}
|
|
644
|
+
const mark = { [RECEIPT_HEADER]: receiptId, [CLASS_HEADER]: arrival.class, ...(logPending ? { "x-agent-custody-log-pending": "true" } : {}) };
|
|
645
|
+
switch (execution.status) {
|
|
646
|
+
case "denied":
|
|
647
|
+
// A refused arrival that could have passed a challenge is told how: the provider, the public site key, and the header
|
|
648
|
+
return json(res, 403, mark, { error: "refused by the door's policy", reason: execution.reason, receipt: receiptId, ...(cfg.challenge && arrival.challenge?.outcome !== "passed" ? { challenge: { provider: cfg.challenge.provider, siteKey: cfg.challenge.siteKey, header: cfg.challenge.header } } : {}) });
|
|
649
|
+
case "withheld":
|
|
650
|
+
return json(res, withheldStatus, mark, { error: "not relayed", reason: execution.reason, receipt: receiptId });
|
|
651
|
+
case "error":
|
|
652
|
+
return notSent
|
|
653
|
+
? json(res, 502, mark, { error: "the origin could not be reached", detail: execution.error, receipt: receiptId })
|
|
654
|
+
: json(res, 504, mark, { error: "the origin may have acted on the request; its answer did not arrive. Do not retry", detail: execution.error, receipt: receiptId });
|
|
655
|
+
default: {
|
|
656
|
+
if (!answer)
|
|
657
|
+
return json(res, 502, mark, { error: `the origin answered, but its response is larger than ${cfg.maxResponseBytes} bytes and was not relayed. Do not retry`, receipt: receiptId });
|
|
658
|
+
res.writeHead(answer.status, { ...answer.headers, ...mark });
|
|
659
|
+
res.end(answer.body);
|
|
660
|
+
}
|
|
661
|
+
}
|
|
662
|
+
}
|
|
663
|
+
let timer;
|
|
664
|
+
if (options.autoFlush) {
|
|
665
|
+
const flush = () => void issuer.flushOutbox().catch((e) => console.error(`agent-custody door: outbox flush failed: ${e instanceof Error ? e.message : String(e)}`));
|
|
666
|
+
flush();
|
|
667
|
+
timer = setInterval(flush, 30_000);
|
|
668
|
+
timer.unref?.();
|
|
669
|
+
}
|
|
670
|
+
return {
|
|
671
|
+
keyid: issuer.keyid,
|
|
672
|
+
policyDigest: () => currentPolicy().digest,
|
|
673
|
+
handle,
|
|
674
|
+
flushOutbox: () => issuer.flushOutbox(),
|
|
675
|
+
pendingReceipts: () => issuer.pending(),
|
|
676
|
+
async close() {
|
|
677
|
+
if (timer)
|
|
678
|
+
clearInterval(timer);
|
|
679
|
+
rates.close();
|
|
680
|
+
},
|
|
681
|
+
};
|
|
682
|
+
}
|
|
683
|
+
/** Serves a door host over plain HTTP. Bind to loopback or put TLS in front. `GET /.well-known/agent-custody-door` answers the key id and the policy digest. */
|
|
684
|
+
export async function serveDoor(host, opts) {
|
|
685
|
+
const bind = opts.host ?? "127.0.0.1";
|
|
686
|
+
const log = opts.log ?? ((m) => console.error(m));
|
|
687
|
+
const server = createServer((req, res) => {
|
|
688
|
+
if (req.method === "GET" && req.url === "/.well-known/agent-custody-door") {
|
|
689
|
+
res.writeHead(200, { "content-type": "application/json", "cache-control": "no-store" });
|
|
690
|
+
res.end(JSON.stringify({ keyid: host.keyid, policyDigest: host.policyDigest(), version: DOOR_VERSION, pendingReceipts: host.pendingReceipts() }));
|
|
691
|
+
return;
|
|
692
|
+
}
|
|
693
|
+
host.handle(req, res).catch((e) => {
|
|
694
|
+
log(`agent-custody door: ${e instanceof Error ? e.message : String(e)}`);
|
|
695
|
+
if (!res.headersSent) {
|
|
696
|
+
res.writeHead(500, { "content-type": "application/json" });
|
|
697
|
+
res.end(JSON.stringify({ error: "the door failed before it could answer; whether the origin acted on the request is unknown", receipt: res.getHeader(RECEIPT_HEADER) ?? null }));
|
|
698
|
+
}
|
|
699
|
+
else
|
|
700
|
+
res.end();
|
|
701
|
+
});
|
|
702
|
+
});
|
|
703
|
+
await new Promise((resolve) => server.listen(opts.port, bind, resolve));
|
|
704
|
+
const { port } = server.address();
|
|
705
|
+
return {
|
|
706
|
+
url: `http://${bind}:${port}`,
|
|
707
|
+
async close() {
|
|
708
|
+
server.closeAllConnections?.();
|
|
709
|
+
await new Promise((resolve) => server.close(() => resolve()));
|
|
710
|
+
},
|
|
711
|
+
};
|
|
712
|
+
}
|