-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsecurity.test.ts
More file actions
388 lines (349 loc) · 18.5 KB
/
Copy pathsecurity.test.ts
File metadata and controls
388 lines (349 loc) · 18.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
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
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
import { afterAll, beforeAll, describe, expect, it } from "vitest";
import type { AddressInfo } from "node:net";
import { createServer, type Server } from "node:http";
import { isBlockedTarget, isPrivateIp, guardedLookup } from "../src/gateway/ssrf.js";
import { safeRequest, readStreamText } from "../src/gateway/safe-fetch.js";
import { httpRateFetcher } from "../src/fx/caching.js";
import { createEip3009Signer, decodeXPayment, DEFAULT_USDC } from "../src/rails/x402-signer.js";
import { createGateway, type Gateway } from "../src/gateway/server.js";
import { PolicyManager } from "../src/policy/manager.js";
import { MockRail } from "../src/rails/mock.js";
import { FixedRateProvider } from "../src/fx/rates.js";
import { createPaidApi } from "../demo/paid-api.js";
import { dashboardHtml } from "../src/gateway/dashboard.js";
import type { PaymentContext } from "../src/types.js";
describe("SSRF guard", () => {
it("classifies private/reserved IPs", () => {
for (const ip of ["127.0.0.1", "10.0.0.1", "192.168.1.1", "169.254.169.254", "172.16.5.5", "::1", "fc00::1", "fe80::1"]) {
expect(isPrivateIp(ip)).toBe(true);
}
for (const ip of ["8.8.8.8", "1.1.1.1", "2606:4700:4700::1111"]) {
expect(isPrivateIp(ip)).toBe(false);
}
});
it("catches non-canonical IPv6 loopback notations", () => {
// All of these are ::1 or mapped 127.0.0.1 written so a naive prefix check misses them.
for (const ip of ["0::1", "0:0:0:0:0:0:0:1", "::ffff:7f00:1", "::ffff:127.0.0.1", "::"]) {
expect(isPrivateIp(ip)).toBe(true);
}
});
it("catches embedded-IPv4 IPv6 (compat / 6to4 / NAT64) pointing at private space", () => {
for (const ip of ["::127.0.0.1", "::169.254.169.254", "2002:7f00:0001::", "64:ff9b::127.0.0.1", "::ffff:10.0.0.1"]) {
expect(isPrivateIp(ip)).toBe(true);
}
// ...but the same wrappers around a PUBLIC v4 stay allowed (no over-blocking).
expect(isPrivateIp("2002:0808:0808::")).toBe(false); // 6to4 of 8.8.8.8
expect(isPrivateIp("64:ff9b::8.8.8.8")).toBe(false); // NAT64 of 8.8.8.8
});
it("blocks loopback/metadata/localhost targets and passes a public IP", async () => {
expect(await isBlockedTarget("http://127.0.0.1:8080/x")).toBe(true);
expect(await isBlockedTarget("http://169.254.169.254/latest/meta-data/")).toBe(true);
expect(await isBlockedTarget("http://localhost/admin")).toBe(true);
expect(await isBlockedTarget("http://[::1]/")).toBe(true);
expect(await isBlockedTarget("not a url")).toBe(true);
expect(await isBlockedTarget("http://8.8.8.8/")).toBe(false); // literal public IP, no DNS
});
});
describe("pinned resolution & redirect re-validation", () => {
const call = (fn: ReturnType<typeof guardedLookup>, host: string): Promise<string> =>
new Promise((resolve) =>
(fn as (h: string, o: unknown, cb: (e: NodeJS.ErrnoException | null, a?: unknown) => void) => void)(
host, { all: false }, (e, a) => resolve(e ? `ERR:${e.code}` : String(a)),
),
);
it("guardedLookup refuses a private-resolving host, passes a public IP", async () => {
expect(await call(guardedLookup(false), "localhost")).toBe("ERR:SSRF_BLOCKED");
expect(await call(guardedLookup(true), "localhost")).toMatch(/^(127\.0\.0\.1|::1)$/);
expect(await call(guardedLookup(false), "8.8.8.8")).toBe("8.8.8.8");
});
it("safeRequest blocks a private literal-IP target (incl. cloud metadata)", async () => {
await expect(safeRequest("http://169.254.169.254/latest/meta-data/", { timeoutMs: 2000 })).rejects.toMatchObject({
code: "SSRF_BLOCKED",
});
});
it("safeRequest follows redirects, re-validating each hop", async () => {
const b = createServer((_q, r) => { r.setHeader("content-type", "application/json"); r.end(JSON.stringify({ ok: true })); });
await new Promise<void>((res) => b.listen(0, "127.0.0.1", res));
const bUrl = `http://127.0.0.1:${(b.address() as AddressInfo).port}/b`;
const a = createServer((_q, r) => { r.statusCode = 302; r.setHeader("location", bUrl); r.end(); });
await new Promise<void>((res) => a.listen(0, "127.0.0.1", res));
const aUrl = `http://127.0.0.1:${(a.address() as AddressInfo).port}/a`;
try {
const resp = await safeRequest(aUrl, { allowPrivateTargets: true });
expect(resp.status).toBe(200);
expect(JSON.parse(await readStreamText(resp.body, 10_000))).toEqual({ ok: true });
} finally {
a.close();
b.close();
}
});
it("actually routes hostname targets through the guarded lookup (the central control)", async () => {
// If http.request ignored our `lookup`, this would ECONNREFUSED, not SSRF_BLOCKED.
await expect(safeRequest("http://localhost:1/", { timeoutMs: 1000 })).rejects.toMatchObject({ code: "SSRF_BLOCKED" });
});
it("strips X-PAYMENT when a redirect crosses origin", async () => {
let leaked: string | undefined = "not-set";
const b = createServer((q, r) => { leaked = q.headers["x-payment"] as string | undefined; r.end("ok"); });
await new Promise<void>((res) => b.listen(0, "127.0.0.1", res));
const bUrl = `http://127.0.0.1:${(b.address() as AddressInfo).port}/b`; // different port → cross-origin
const a = createServer((_q, r) => { r.statusCode = 302; r.setHeader("location", bUrl); r.end(); });
await new Promise<void>((res) => a.listen(0, "127.0.0.1", res));
const aUrl = `http://127.0.0.1:${(a.address() as AddressInfo).port}/a`;
try {
const resp = await safeRequest(aUrl, { allowPrivateTargets: true, headers: { "X-PAYMENT": "signed-secret" } });
await readStreamText(resp.body, 1000);
expect(leaked).toBeUndefined(); // the payment proof did not follow the redirect
} finally {
a.close();
b.close();
}
});
});
describe("proxy refuses private targets by default", () => {
let gateway: Gateway, gatewayUrl: string;
const listen = (s: Server): Promise<string> =>
new Promise((r) => s.listen(0, "127.0.0.1", () => r(`http://127.0.0.1:${(s.address() as AddressInfo).port}`)));
beforeAll(async () => {
gateway = createGateway({
policyManager: new PolicyManager({ agents: [{ agentId: "bot", enabled: true, currency: "USD" }] }),
rails: [new MockRail()],
// allowPrivateTargets defaults to false
});
gatewayUrl = await listen(gateway.server);
});
afterAll(() => gateway.server.close());
it("returns 403 blocked_target for a loopback URL", async () => {
const res = await fetch(`${gatewayUrl}/proxy?url=${encodeURIComponent("http://169.254.169.254/latest/meta-data/")}`, {
headers: { "x-agent-id": "bot" },
});
expect(res.status).toBe(403);
expect(((await res.json()) as { error: string }).error).toBe("blocked_target");
});
});
describe("admin API authentication", () => {
let gateway: Gateway, gatewayUrl: string;
const listen = (s: Server): Promise<string> =>
new Promise((r) => s.listen(0, "127.0.0.1", () => r(`http://127.0.0.1:${(s.address() as AddressInfo).port}`)));
beforeAll(async () => {
gateway = createGateway({
policyManager: new PolicyManager({ agents: [] }),
rails: [new MockRail()],
adminToken: "s3cret-token",
});
gatewayUrl = await listen(gateway.server);
});
afterAll(() => gateway.server.close());
it("rejects admin data endpoints without the token", async () => {
expect((await fetch(`${gatewayUrl}/admin/keys`)).status).toBe(401);
expect((await fetch(`${gatewayUrl}/admin/policy`)).status).toBe(401);
expect((await fetch(`${gatewayUrl}/admin/agents`)).status).toBe(401);
});
it("accepts the token via Bearer or X-Admin-Token, rejects a wrong one", async () => {
expect((await fetch(`${gatewayUrl}/admin/keys`, { headers: { authorization: "Bearer s3cret-token" } })).status).toBe(200);
expect((await fetch(`${gatewayUrl}/admin/keys`, { headers: { "x-admin-token": "s3cret-token" } })).status).toBe(200);
expect((await fetch(`${gatewayUrl}/admin/keys`, { headers: { authorization: "Bearer wrong" } })).status).toBe(401);
});
it("still serves the dashboard page itself without a token", async () => {
const res = await fetch(`${gatewayUrl}/admin`);
expect(res.status).toBe(200);
expect(res.headers.get("content-type")).toMatch(/text\/html/);
});
});
describe("x402 signer asset allowlist", () => {
const KEY = "0x59c6995e998f97a5a0044966f0945389dc9e86dae88c7a8412f4603b6b78690d" as const;
const base = (overrides: Partial<PaymentContext["requirement"]>): PaymentContext => ({
agentId: "bot",
timestamp: Date.UTC(2026, 5, 12, 12, 0, 0),
requirement: {
scheme: "exact", network: "base-sepolia", amount: "0.05", currency: "USDC",
payTo: "0x209693Bc6afc0C5328bA36FaF03C514EF312287C", resource: "https://x/y", ...overrides,
},
});
it("refuses to sign for a non-allowlisted asset", async () => {
const signer = createEip3009Signer({ privateKey: KEY });
await expect(signer(base({ asset: "0xdeadBEEFdeadBEEFdeadBEEFdeadBEEFdeadBEEF" }))).rejects.toThrow(/not allowlisted/);
});
it("signs for the default USDC asset", async () => {
const signer = createEip3009Signer({ privateKey: KEY });
await expect(signer(base({ asset: DEFAULT_USDC["base-sepolia"] }))).resolves.toMatch(/.+/);
});
it("refuses to sign when the currency label doesn't match the settled asset", async () => {
const signer = createEip3009Signer({ privateKey: KEY });
// A mislabeled "CNY" would make the budget under-count while the chain moves USDC.
await expect(signer(base({ currency: "CNY" }))).rejects.toThrow(/does not match settlement asset/);
});
it("clamps the authorization validity to maxAuthorizationSeconds", async () => {
const t0 = Date.UTC(2026, 5, 12, 12, 0, 0);
const signer = createEip3009Signer({ privateKey: KEY, now: () => t0, maxAuthorizationSeconds: 120 });
const header = await signer(base({ maxTimeoutSeconds: 999999 }));
expect(decodeXPayment(header).payload.authorization.validBefore).toBe(String(Math.floor(t0 / 1000) + 120));
});
it("ignores a non-positive merchant timeout instead of signing an already-expired auth", async () => {
const t0 = Date.UTC(2026, 5, 12, 12, 0, 0);
const signer = createEip3009Signer({ privateKey: KEY, now: () => t0, maxAuthorizationSeconds: 300 });
for (const bad of [0, -100]) {
const header = await signer(base({ maxTimeoutSeconds: bad }));
expect(decodeXPayment(header).payload.authorization.validBefore).toBe(String(Math.floor(t0 / 1000) + 300));
}
});
});
describe("currency-label budget bypass (x402 asset decoupling)", () => {
let bad: Server, gw: Gateway, badUrl: string, gwUrl: string;
const listen = (s: Server): Promise<string> =>
new Promise((r) => s.listen(0, "127.0.0.1", () => r(`http://127.0.0.1:${(s.address() as AddressInfo).port}`)));
beforeAll(async () => {
// Hostile 402: a 1.5 charge mislabeled "CNY" so the budget (CNY:USD=0.14) sees only 0.21 USD.
bad = createServer((_q, r) => {
r.statusCode = 402;
r.setHeader("content-type", "application/json");
r.end(JSON.stringify({ accepts: [{ scheme: "exact", network: "mock", maxAmountRequired: "1500000", assetSymbol: "CNY", payTo: "m" }] }));
});
badUrl = await listen(bad);
gw = createGateway({
policyManager: new PolicyManager({ agents: [{ agentId: "bot", enabled: true, currency: "USD", perTransactionMax: "0.25", dailyBudget: "100" }] }),
rails: [new MockRail()],
rates: new FixedRateProvider({ "USDC:USD": "1", "CNY:USD": "0.14" }),
allowPrivateTargets: true,
});
gwUrl = await listen(gw.server);
});
afterAll(() => { bad.close(); gw.server.close(); });
it("counts a mislabeled-CNY x402 charge as USDC, so the per-tx cap still applies", async () => {
const res = await fetch(`${gwUrl}/proxy?url=${encodeURIComponent(badUrl)}`, { headers: { "x-agent-id": "bot" } });
expect(res.status).toBe(403); // 1.5 USDC > 0.25 cap — the "CNY" relabel no longer under-counts
expect((await res.json() as { rule: string }).rule).toBe("per_transaction_max");
});
});
describe("dashboard output encoding (XSS)", () => {
it("drives actions via data-* delegation, not data-bearing inline onclick", () => {
const html = dashboardHtml();
expect(html).toContain('data-action="edit-agent"');
expect(html).toContain('data-action="revoke-key"');
expect(html).toContain('data-action="decide"');
// The old XSS-prone patterns (data concatenated into onclick) must not return.
expect(html).not.toMatch(/onclick=['"]?editAgent\(/);
expect(html).not.toMatch(/onclick=['"]?revokeKey\(/);
expect(html).not.toMatch(/onclick=['"]?decide\(/);
expect(html).not.toContain("JSON.stringify(JSON.stringify(a))");
});
});
describe("concurrency & DoS limits", () => {
let paidApi: Server, gateway: Gateway, paidUrl: string, gatewayUrl: string;
const listen = (s: Server): Promise<string> =>
new Promise((r) => s.listen(0, "127.0.0.1", () => r(`http://127.0.0.1:${(s.address() as AddressInfo).port}`)));
beforeAll(async () => {
paidApi = createPaidApi([{ path: "/x", options: [{ network: "mock", amount: "0.05", currency: "USD", payTo: "m" }], body: { ok: true } }]);
paidUrl = await listen(paidApi);
gateway = createGateway({
policyManager: new PolicyManager({ agents: [{ agentId: "bot", enabled: true, currency: "USD", dailyBudget: "0.10" }] }),
rails: [new MockRail()],
rates: new FixedRateProvider({ "USD:USD": "1" }),
allowPrivateTargets: true,
});
gatewayUrl = await listen(gateway.server);
});
afterAll(() => { paidApi.close(); gateway.server.close(); });
it("holds the daily budget under concurrent payments (no double-spend)", async () => {
// Budget 0.10 / price 0.05 → at most 2 may succeed. Fire 5 at once.
const results = await Promise.all(
Array.from({ length: 5 }, () =>
fetch(`${gatewayUrl}/proxy?url=${encodeURIComponent(paidUrl + "/x")}`, { headers: { "x-agent-id": "bot" } }).then((r) => r.status),
),
);
expect(results.filter((s) => s === 200)).toHaveLength(2);
expect(results.filter((s) => s === 403)).toHaveLength(3);
const spend = (await (await fetch(`${gatewayUrl}/admin/spend/bot`)).json()) as { spentToday: string };
expect(spend.spentToday).toBe("0.1"); // never exceeded the cap
});
it("rejects an oversized request body with 413", async () => {
const res = await fetch(`${gatewayUrl}/proxy?url=${encodeURIComponent(paidUrl + "/x")}`, {
method: "POST",
headers: { "x-agent-id": "bot", "content-type": "application/octet-stream" },
body: Buffer.alloc(1_100_000), // > 1 MiB cap
});
expect(res.status).toBe(413);
});
it("does not 500 on a malformed merchant 402 amount", async () => {
const bad = createServer((_q, r) => {
r.statusCode = 402;
r.setHeader("content-type", "application/json");
r.end(JSON.stringify({ accepts: [{ payTo: "m", network: "mock", maxAmountRequired: "abc" }] }));
});
await new Promise<void>((res) => bad.listen(0, "127.0.0.1", res));
const badUrl = `http://127.0.0.1:${(bad.address() as AddressInfo).port}/`;
try {
const res = await fetch(`${gatewayUrl}/proxy?url=${encodeURIComponent(badUrl)}`, { headers: { "x-agent-id": "bot" } });
expect(res.status).toBe(502); // unparseable_402, not a 500
expect((await res.json() as { error: string }).error).toBe("unparseable_402");
} finally {
bad.close();
}
});
it("enforces an overall deadline on a slow-trickle response body", async () => {
// Sends headers + one byte, then holds the socket open forever. The per-socket
// idle timeout would keep resetting on a real trickle; the overall deadline must cap it.
const slow = createServer((_q, r) => { r.writeHead(200); r.write("a"); /* never ends */ });
await new Promise<void>((res) => slow.listen(0, "127.0.0.1", res));
const slowUrl = `http://127.0.0.1:${(slow.address() as AddressInfo).port}/`;
try {
const resp = await safeRequest(slowUrl, { allowPrivateTargets: true, overallTimeoutMs: 300, timeoutMs: 10_000 });
await expect(readStreamText(resp.body, 1_000_000)).rejects.toThrow(); // aborted by the deadline, not hung
} finally {
slow.close();
}
});
it("httpRateFetcher times out a hung FX provider instead of stalling", async () => {
const hung = createServer(() => { /* accept, never respond */ });
await new Promise<void>((res) => hung.listen(0, "127.0.0.1", res));
const base = `http://127.0.0.1:${(hung.address() as AddressInfo).port}`;
try {
const fetcher = httpRateFetcher(base, 200);
expect(await fetcher("CNY", "USD")).toBeUndefined(); // resolves (undefined) within the timeout
} finally {
hung.close();
}
});
});
describe("admin CSRF & auth hardening", () => {
const listen = (s: Server): Promise<string> =>
new Promise((r) => s.listen(0, "127.0.0.1", () => r(`http://127.0.0.1:${(s.address() as AddressInfo).port}`)));
it("rejects a cross-origin admin mutation, allows same-origin and non-browser", async () => {
const gw = createGateway({
policyManager: new PolicyManager({ agents: [{ agentId: "bot", enabled: true, currency: "USD" }] }),
rails: [new MockRail()],
allowPrivateTargets: true,
}); // no adminToken → open mode, where CSRF would otherwise bite
const url = await listen(gw.server);
const host = url.replace(/^https?:\/\//, "");
const put = (origin?: string) =>
fetch(`${url}/admin/agents/bot`, {
method: "PUT",
headers: { "content-type": "application/json", ...(origin ? { origin } : {}) },
body: JSON.stringify({ currency: "USD", dailyBudget: "5" }),
});
try {
expect((await put("https://evil.example")).status).toBe(403); // cross-origin → blocked
expect((await put(`http://${host}`)).status).toBe(200); // same-origin (Origin matches Host)
expect((await put()).status).toBe(200); // no Origin (curl / the agent) → allowed
} finally {
gw.server.close();
}
});
it("a prototype-chain token does not authenticate via the legacy apiKeys map", async () => {
const gw = createGateway({
policyConfig: { agents: [{ agentId: "bot", enabled: true, currency: "USD" }] },
rails: [new MockRail()],
apiKeys: { realkey: "bot" },
allowPrivateTargets: true,
});
const url = await listen(gw.server);
try {
for (const t of ["__proto__", "constructor", "toString"]) {
const res = await fetch(`${url}/proxy?url=${encodeURIComponent("http://127.0.0.1:1/")}`, { headers: { authorization: `Bearer ${t}` } });
expect(res.status).toBe(401); // not authenticated as any agent
}
} finally {
gw.server.close();
}
});
});