@nabasolution/runtime 0.0.0-stage → 0.1.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/LICENSE +21 -0
- package/dist/src/app.d.ts +60 -0
- package/dist/src/app.d.ts.map +1 -0
- package/dist/src/app.js +649 -0
- package/dist/src/app.js.map +1 -0
- package/dist/src/audit.d.ts +42 -0
- package/dist/src/audit.d.ts.map +1 -0
- package/dist/src/audit.js +53 -0
- package/dist/src/audit.js.map +1 -0
- package/dist/src/auth-guard.d.ts +27 -0
- package/dist/src/auth-guard.d.ts.map +1 -0
- package/dist/src/auth-guard.js +29 -0
- package/dist/src/auth-guard.js.map +1 -0
- package/dist/src/index.d.ts +14 -0
- package/dist/src/index.d.ts.map +1 -0
- package/dist/src/index.js +9 -0
- package/dist/src/index.js.map +1 -0
- package/dist/src/metrics.d.ts +26 -0
- package/dist/src/metrics.d.ts.map +1 -0
- package/dist/src/metrics.js +54 -0
- package/dist/src/metrics.js.map +1 -0
- package/dist/src/rate-limit.d.ts +40 -0
- package/dist/src/rate-limit.d.ts.map +1 -0
- package/dist/src/rate-limit.js +71 -0
- package/dist/src/rate-limit.js.map +1 -0
- package/dist/src/router.d.ts +21 -0
- package/dist/src/router.d.ts.map +1 -0
- package/dist/src/router.js +55 -0
- package/dist/src/router.js.map +1 -0
- package/dist/src/security.d.ts +35 -0
- package/dist/src/security.d.ts.map +1 -0
- package/dist/src/security.js +106 -0
- package/dist/src/security.js.map +1 -0
- package/dist/src/services.d.ts +10 -0
- package/dist/src/services.d.ts.map +1 -0
- package/dist/src/services.js +23 -0
- package/dist/src/services.js.map +1 -0
- package/dist/test/hardening.test.d.ts +2 -0
- package/dist/test/hardening.test.d.ts.map +1 -0
- package/dist/test/hardening.test.js +795 -0
- package/dist/test/hardening.test.js.map +1 -0
- package/dist/test/runtime.test.d.ts +2 -0
- package/dist/test/runtime.test.d.ts.map +1 -0
- package/dist/test/runtime.test.js +143 -0
- package/dist/test/runtime.test.js.map +1 -0
- package/package.json +47 -3
- package/README.md +0 -3
|
@@ -0,0 +1,795 @@
|
|
|
1
|
+
import assert from "node:assert/strict";
|
|
2
|
+
import { mkdtemp, readFile, rm } from "node:fs/promises";
|
|
3
|
+
import { tmpdir } from "node:os";
|
|
4
|
+
import { join } from "node:path";
|
|
5
|
+
import test from "node:test";
|
|
6
|
+
import { defineConfig } from "@nabasolution/core";
|
|
7
|
+
import { NabaError } from "@nabasolution/core";
|
|
8
|
+
import { createApp, createAuthGuard, json, routeContext } from "../src/index.js";
|
|
9
|
+
function testConfig(runtime = {}, environment = "test") {
|
|
10
|
+
return defineConfig({
|
|
11
|
+
app: { name: "runtime-hardening-test", environment },
|
|
12
|
+
country: { primary: "BD", supported: ["BD"] },
|
|
13
|
+
modules: ["demo"],
|
|
14
|
+
integrations: { payments: [], shipping: [] },
|
|
15
|
+
runtime: { port: 0, ...runtime }
|
|
16
|
+
});
|
|
17
|
+
}
|
|
18
|
+
function demoModule() {
|
|
19
|
+
return {
|
|
20
|
+
name: "demo",
|
|
21
|
+
register(context) {
|
|
22
|
+
context.services.set("greeting", "hello");
|
|
23
|
+
context.addRoute({
|
|
24
|
+
method: "GET",
|
|
25
|
+
path: "/api/ctx",
|
|
26
|
+
handler: (ctx) => {
|
|
27
|
+
const runtimeContext = routeContext(ctx);
|
|
28
|
+
return new Response(JSON.stringify({
|
|
29
|
+
requestId: runtimeContext.requestId,
|
|
30
|
+
clientKey: runtimeContext.clientKey,
|
|
31
|
+
tenantId: runtimeContext.tenantId,
|
|
32
|
+
headerId: ctx.request.headers.get("x-request-id")
|
|
33
|
+
}), { headers: { "content-type": "application/json" } });
|
|
34
|
+
}
|
|
35
|
+
});
|
|
36
|
+
context.addRoute({
|
|
37
|
+
method: "GET",
|
|
38
|
+
path: "/api/auth/echo",
|
|
39
|
+
handler: () => new Response(JSON.stringify({ ok: true }), {
|
|
40
|
+
headers: { "content-type": "application/json" }
|
|
41
|
+
})
|
|
42
|
+
});
|
|
43
|
+
context.addRoute({
|
|
44
|
+
method: "GET",
|
|
45
|
+
path: "/api/webhooks/echo",
|
|
46
|
+
handler: () => new Response(JSON.stringify({ ok: true }), {
|
|
47
|
+
headers: { "content-type": "application/json" }
|
|
48
|
+
})
|
|
49
|
+
});
|
|
50
|
+
context.addRoute({
|
|
51
|
+
method: "GET",
|
|
52
|
+
path: "/api/exempt",
|
|
53
|
+
handler: () => new Response(JSON.stringify({ ok: true }), {
|
|
54
|
+
headers: { "content-type": "application/json" }
|
|
55
|
+
})
|
|
56
|
+
});
|
|
57
|
+
context.addRoute({
|
|
58
|
+
method: "POST",
|
|
59
|
+
path: "/api/echo",
|
|
60
|
+
handler: async (ctx) => new Response(JSON.stringify({ body: await ctx.json() }), {
|
|
61
|
+
status: 201,
|
|
62
|
+
headers: { "content-type": "application/json" }
|
|
63
|
+
})
|
|
64
|
+
});
|
|
65
|
+
context.addRoute({
|
|
66
|
+
method: "GET",
|
|
67
|
+
path: "/api/explode",
|
|
68
|
+
handler: () => {
|
|
69
|
+
throw new Error("boom");
|
|
70
|
+
}
|
|
71
|
+
});
|
|
72
|
+
}
|
|
73
|
+
};
|
|
74
|
+
}
|
|
75
|
+
function postEcho(app, headers = {}, body = "{}") {
|
|
76
|
+
return app.handle(new Request("http://localhost/api/echo", {
|
|
77
|
+
method: "POST",
|
|
78
|
+
headers: { "content-type": "application/json", ...headers },
|
|
79
|
+
body
|
|
80
|
+
}));
|
|
81
|
+
}
|
|
82
|
+
function assertBaselineHeaders(response) {
|
|
83
|
+
assert.equal(response.headers.get("access-control-allow-origin"), "*");
|
|
84
|
+
assert.equal(response.headers.get("x-content-type-options"), "nosniff");
|
|
85
|
+
assert.equal(response.headers.get("x-frame-options"), "DENY");
|
|
86
|
+
assert.equal(response.headers.get("referrer-policy"), "no-referrer");
|
|
87
|
+
assert.equal(response.headers.get("permissions-policy"), "camera=(), microphone=(), geolocation=()");
|
|
88
|
+
assert.ok(response.headers.get("x-request-id"));
|
|
89
|
+
}
|
|
90
|
+
test("fixed-window rate limit rejects with 429, retry-after and headers", async () => {
|
|
91
|
+
const app = createApp({
|
|
92
|
+
config: testConfig({ rateLimit: { windowMs: 60_000, max: 2 } }),
|
|
93
|
+
modules: [demoModule()]
|
|
94
|
+
});
|
|
95
|
+
assert.equal((await postEcho(app)).status, 201);
|
|
96
|
+
assert.equal((await postEcho(app)).status, 201);
|
|
97
|
+
const limited = await postEcho(app);
|
|
98
|
+
assert.equal(limited.status, 429);
|
|
99
|
+
assertBaselineHeaders(limited);
|
|
100
|
+
assert.equal((await limited.json()).error.code, "RATE_LIMITED");
|
|
101
|
+
const retryAfter = Number(limited.headers.get("retry-after"));
|
|
102
|
+
assert.ok(Number.isInteger(retryAfter) && retryAfter > 0, `retry-after=${retryAfter}`);
|
|
103
|
+
// Exempt paths never consume quota, even after the bucket is exhausted.
|
|
104
|
+
for (let i = 0; i < 5; i += 1) {
|
|
105
|
+
assert.equal((await app.handle(new Request("http://localhost/api/health"))).status, 200);
|
|
106
|
+
}
|
|
107
|
+
for (let i = 0; i < 3; i += 1) {
|
|
108
|
+
assert.equal((await app.handle(new Request("http://localhost/metrics"))).status, 200);
|
|
109
|
+
}
|
|
110
|
+
assert.equal((await app.handle(new Request("http://localhost/"))).status, 200);
|
|
111
|
+
await app.close();
|
|
112
|
+
});
|
|
113
|
+
test("configured exempt paths and OPTIONS preflights bypass the limiter", async () => {
|
|
114
|
+
const app = createApp({
|
|
115
|
+
config: testConfig({
|
|
116
|
+
rateLimit: { windowMs: 60_000, max: 1, exemptPaths: ["/api/exempt"] }
|
|
117
|
+
}),
|
|
118
|
+
modules: [demoModule()]
|
|
119
|
+
});
|
|
120
|
+
assert.equal((await app.handle(new Request("http://localhost/api/exempt"))).status, 200);
|
|
121
|
+
assert.equal((await app.handle(new Request("http://localhost/api/exempt"))).status, 200);
|
|
122
|
+
assert.equal((await app.handle(new Request("http://localhost/api/meta"))).status, 200);
|
|
123
|
+
const limited = await app.handle(new Request("http://localhost/api/meta"));
|
|
124
|
+
assert.equal(limited.status, 429);
|
|
125
|
+
const preflight = await app.handle(new Request("http://localhost/api/meta", { method: "OPTIONS" }));
|
|
126
|
+
assert.equal(preflight.status, 204);
|
|
127
|
+
await app.close();
|
|
128
|
+
});
|
|
129
|
+
test("client key honours trustProxy x-forwarded-for and falls back to x-real-ip", async () => {
|
|
130
|
+
const proxied = createApp({
|
|
131
|
+
config: testConfig({ rateLimit: { windowMs: 60_000, max: 1, trustProxy: true } }),
|
|
132
|
+
modules: [demoModule()]
|
|
133
|
+
});
|
|
134
|
+
const ipA = { "x-forwarded-for": "203.0.113.7, 10.0.0.1" };
|
|
135
|
+
const ipB = { "x-forwarded-for": "203.0.113.8, 10.0.0.1" };
|
|
136
|
+
assert.equal((await postEcho(proxied, ipA)).status, 201);
|
|
137
|
+
assert.equal((await postEcho(proxied, ipA)).status, 429);
|
|
138
|
+
assert.equal((await postEcho(proxied, ipB)).status, 201);
|
|
139
|
+
await proxied.close();
|
|
140
|
+
const direct = createApp({
|
|
141
|
+
config: testConfig({ rateLimit: { windowMs: 60_000, max: 1 } }),
|
|
142
|
+
modules: [demoModule()]
|
|
143
|
+
});
|
|
144
|
+
// trustProxy is false: x-forwarded-for and x-real-ip are ignored; the key is
|
|
145
|
+
// the socket address injected by the Node adapter (simulated here).
|
|
146
|
+
assert.equal((await postEcho(direct, { "x-forwarded-for": "198.51.100.1" })).status, 201);
|
|
147
|
+
assert.equal((await postEcho(direct, { "x-forwarded-for": "198.51.100.2" })).status, 429);
|
|
148
|
+
assert.equal((await postEcho(direct, { "x-real-ip": "198.51.100.9" })).status, 429);
|
|
149
|
+
assert.equal((await postEcho(direct, { "x-naba-remote-address": "198.51.100.9" })).status, 201);
|
|
150
|
+
await direct.close();
|
|
151
|
+
});
|
|
152
|
+
test("request ids are honoured, generated, exposed and returned everywhere", async () => {
|
|
153
|
+
const app = createApp({ config: testConfig(), modules: [demoModule()] });
|
|
154
|
+
const supplied = await app.handle(new Request("http://localhost/api/ctx", {
|
|
155
|
+
headers: { "x-request-id": "client-request-0001", "x-naba-remote-address": "198.51.100.5" }
|
|
156
|
+
}));
|
|
157
|
+
assert.equal(supplied.status, 200);
|
|
158
|
+
assert.equal(supplied.headers.get("x-request-id"), "client-request-0001");
|
|
159
|
+
const suppliedBody = (await supplied.json());
|
|
160
|
+
assert.equal(suppliedBody.requestId, "client-request-0001");
|
|
161
|
+
assert.equal(suppliedBody.clientKey, "198.51.100.5");
|
|
162
|
+
assert.equal(suppliedBody.headerId, "client-request-0001");
|
|
163
|
+
const tooShort = await app.handle(new Request("http://localhost/api/ctx", { headers: { "x-request-id": "tiny" } }));
|
|
164
|
+
const generated = tooShort.headers.get("x-request-id") ?? "";
|
|
165
|
+
assert.match(generated, /^req_[A-Za-z0-9_-]+$/);
|
|
166
|
+
assert.equal((await tooShort.json()).requestId, generated);
|
|
167
|
+
const missing = await app.handle(new Request("http://localhost/api/nope"));
|
|
168
|
+
assert.equal(missing.status, 404);
|
|
169
|
+
assertBaselineHeaders(missing);
|
|
170
|
+
const oversized = await app.handle(new Request("http://localhost/api/echo", {
|
|
171
|
+
method: "POST",
|
|
172
|
+
headers: {
|
|
173
|
+
"content-type": "application/json",
|
|
174
|
+
"content-length": String(6 * 1024 * 1024),
|
|
175
|
+
"x-request-id": "oversized-request-1"
|
|
176
|
+
},
|
|
177
|
+
body: "{}"
|
|
178
|
+
}));
|
|
179
|
+
assert.equal(oversized.status, 413);
|
|
180
|
+
assert.equal(oversized.headers.get("x-request-id"), "oversized-request-1");
|
|
181
|
+
assertBaselineHeaders(oversized);
|
|
182
|
+
const failed = await app.handle(new Request("http://localhost/api/explode"));
|
|
183
|
+
assert.equal(failed.status, 500);
|
|
184
|
+
assertBaselineHeaders(failed);
|
|
185
|
+
const options = await app.handle(new Request("http://localhost/api/health", { method: "OPTIONS" }));
|
|
186
|
+
assert.equal(options.status, 204);
|
|
187
|
+
assertBaselineHeaders(options);
|
|
188
|
+
await app.close();
|
|
189
|
+
});
|
|
190
|
+
test("metrics endpoint exposes Prometheus counters without high-cardinality labels", async () => {
|
|
191
|
+
const app = createApp({ config: testConfig(), modules: [demoModule()] });
|
|
192
|
+
assert.equal((await app.handle(new Request("http://localhost/api/health"))).status, 200);
|
|
193
|
+
assert.equal((await postEcho(app)).status, 201);
|
|
194
|
+
const metrics = await app.handle(new Request("http://localhost/metrics"));
|
|
195
|
+
assert.equal(metrics.status, 200);
|
|
196
|
+
assertBaselineHeaders(metrics);
|
|
197
|
+
assert.match(metrics.headers.get("content-type") ?? "", /^text\/plain/);
|
|
198
|
+
const text = await metrics.text();
|
|
199
|
+
assert.match(text, /naba_http_requests_total 2\n/);
|
|
200
|
+
assert.match(text, /naba_http_responses_total\{status="200"\} 1/);
|
|
201
|
+
assert.match(text, /naba_http_responses_total\{status="201"\} 1/);
|
|
202
|
+
assert.match(text, /naba_http_request_duration_ms_sum [0-9.]+/);
|
|
203
|
+
assert.match(text, /naba_http_request_duration_ms_count 2/);
|
|
204
|
+
assert.match(text, /naba_app_uptime_seconds [0-9.]+/);
|
|
205
|
+
assert.match(text, /naba_rate_limited_total 0/);
|
|
206
|
+
assert.doesNotMatch(text, /path=/, "request paths must not be labels");
|
|
207
|
+
await app.close();
|
|
208
|
+
});
|
|
209
|
+
test("metrics count rate-limited responses", async () => {
|
|
210
|
+
const app = createApp({
|
|
211
|
+
config: testConfig({ rateLimit: { windowMs: 60_000, max: 1 } }),
|
|
212
|
+
modules: [demoModule()]
|
|
213
|
+
});
|
|
214
|
+
assert.equal((await postEcho(app)).status, 201);
|
|
215
|
+
assert.equal((await postEcho(app)).status, 429);
|
|
216
|
+
const text = await (await app.handle(new Request("http://localhost/metrics"))).text();
|
|
217
|
+
assert.match(text, /naba_rate_limited_total 1/);
|
|
218
|
+
assert.match(text, /naba_http_responses_total\{status="429"\} 1/);
|
|
219
|
+
await app.close();
|
|
220
|
+
});
|
|
221
|
+
test("metrics can be disabled", async () => {
|
|
222
|
+
const app = createApp({
|
|
223
|
+
config: testConfig({ metrics: false }),
|
|
224
|
+
modules: [demoModule()]
|
|
225
|
+
});
|
|
226
|
+
const metrics = await app.handle(new Request("http://localhost/metrics"));
|
|
227
|
+
assert.equal(metrics.status, 404);
|
|
228
|
+
assert.equal((await metrics.json()).error.code, "ROUTE_NOT_FOUND");
|
|
229
|
+
await app.close();
|
|
230
|
+
});
|
|
231
|
+
test("audit log appends one JSONL line per state-changing request and flushes on close", async () => {
|
|
232
|
+
const directory = await mkdtemp(join(tmpdir(), "naba-audit-"));
|
|
233
|
+
const auditPath = join(directory, "nested", "audit.jsonl");
|
|
234
|
+
const previousTenantFlag = process.env.NABA_ALLOW_TENANT_HEADER;
|
|
235
|
+
process.env.NABA_ALLOW_TENANT_HEADER = "1";
|
|
236
|
+
try {
|
|
237
|
+
const app = createApp({
|
|
238
|
+
config: testConfig({ auditLog: auditPath }),
|
|
239
|
+
modules: [demoModule()]
|
|
240
|
+
});
|
|
241
|
+
assert.equal((await app.handle(new Request("http://localhost/api/health"))).status, 200);
|
|
242
|
+
const created = await postEcho(app, { "x-request-id": "audit-request-0001", "x-naba-tenant": "Acme" }, JSON.stringify({ password: "super-secret-value" }));
|
|
243
|
+
assert.equal(created.status, 201);
|
|
244
|
+
await app.close();
|
|
245
|
+
const raw = await readFile(auditPath, "utf8");
|
|
246
|
+
const lines = raw.trim().split("\n");
|
|
247
|
+
assert.equal(lines.length, 1, raw);
|
|
248
|
+
const entry = JSON.parse(lines[0] ?? "{}");
|
|
249
|
+
assert.equal(entry.method, "POST");
|
|
250
|
+
assert.equal(entry.path, "/api/echo");
|
|
251
|
+
assert.equal(entry.status, 201);
|
|
252
|
+
assert.equal(entry.requestId, "audit-request-0001");
|
|
253
|
+
assert.equal(entry.clientKey, "local");
|
|
254
|
+
assert.equal(entry.tenantId, "acme");
|
|
255
|
+
assert.equal(typeof entry.durationMs, "number");
|
|
256
|
+
assert.match(String(entry.timestamp), /^\d{4}-\d{2}-\d{2}T/);
|
|
257
|
+
assert.doesNotMatch(raw, /super-secret-value/);
|
|
258
|
+
}
|
|
259
|
+
finally {
|
|
260
|
+
await rm(directory, { recursive: true, force: true });
|
|
261
|
+
}
|
|
262
|
+
});
|
|
263
|
+
test("audit log uses NABA_AUDIT_LOG when config is unset, and false disables it", async () => {
|
|
264
|
+
const directory = await mkdtemp(join(tmpdir(), "naba-audit-env-"));
|
|
265
|
+
const envPath = join(directory, "env-audit.jsonl");
|
|
266
|
+
const previous = process.env.NABA_AUDIT_LOG;
|
|
267
|
+
try {
|
|
268
|
+
process.env.NABA_AUDIT_LOG = envPath;
|
|
269
|
+
const fromEnv = createApp({ config: testConfig(), modules: [demoModule()] });
|
|
270
|
+
assert.equal((await postEcho(fromEnv)).status, 201);
|
|
271
|
+
await fromEnv.close();
|
|
272
|
+
assert.equal((await readFile(envPath, "utf8")).trim().split("\n").length, 1);
|
|
273
|
+
const disabledPath = join(directory, "disabled.jsonl");
|
|
274
|
+
process.env.NABA_AUDIT_LOG = disabledPath;
|
|
275
|
+
const disabled = createApp({
|
|
276
|
+
config: testConfig({ auditLog: false }),
|
|
277
|
+
modules: [demoModule()]
|
|
278
|
+
});
|
|
279
|
+
assert.equal((await postEcho(disabled)).status, 201);
|
|
280
|
+
await disabled.close();
|
|
281
|
+
await assert.rejects(readFile(disabledPath, "utf8"));
|
|
282
|
+
}
|
|
283
|
+
finally {
|
|
284
|
+
if (previous === undefined)
|
|
285
|
+
delete process.env.NABA_AUDIT_LOG;
|
|
286
|
+
else
|
|
287
|
+
process.env.NABA_AUDIT_LOG = previous;
|
|
288
|
+
await rm(directory, { recursive: true, force: true });
|
|
289
|
+
}
|
|
290
|
+
});
|
|
291
|
+
test("audit path excludes query strings", async () => {
|
|
292
|
+
const directory = await mkdtemp(join(tmpdir(), "naba-audit-query-"));
|
|
293
|
+
const auditPath = join(directory, "audit.jsonl");
|
|
294
|
+
try {
|
|
295
|
+
const app = createApp({
|
|
296
|
+
config: testConfig({ auditLog: auditPath }),
|
|
297
|
+
modules: [demoModule()]
|
|
298
|
+
});
|
|
299
|
+
const response = await app.handle(new Request("http://localhost/api/echo?token=should-not-be-logged", {
|
|
300
|
+
method: "POST",
|
|
301
|
+
headers: { "content-type": "application/json" },
|
|
302
|
+
body: "{}"
|
|
303
|
+
}));
|
|
304
|
+
assert.equal(response.status, 201);
|
|
305
|
+
await app.close();
|
|
306
|
+
const raw = await readFile(auditPath, "utf8");
|
|
307
|
+
assert.doesNotMatch(raw, /should-not-be-logged/);
|
|
308
|
+
assert.match(raw, /"path":"\/api\/echo"/);
|
|
309
|
+
}
|
|
310
|
+
finally {
|
|
311
|
+
await rm(directory, { recursive: true, force: true });
|
|
312
|
+
}
|
|
313
|
+
});
|
|
314
|
+
test("rate limit, metrics and audit work over a real HTTP socket", async () => {
|
|
315
|
+
const directory = await mkdtemp(join(tmpdir(), "naba-audit-http-"));
|
|
316
|
+
const auditPath = join(directory, "audit.jsonl");
|
|
317
|
+
try {
|
|
318
|
+
const app = createApp({
|
|
319
|
+
config: testConfig({
|
|
320
|
+
rateLimit: { windowMs: 60_000, max: 1 },
|
|
321
|
+
auditLog: auditPath
|
|
322
|
+
}),
|
|
323
|
+
modules: [demoModule()]
|
|
324
|
+
});
|
|
325
|
+
const server = await app.listen(0, "127.0.0.1");
|
|
326
|
+
const post = () => fetch(`${server.url}/api/echo`, {
|
|
327
|
+
method: "POST",
|
|
328
|
+
headers: {
|
|
329
|
+
"content-type": "application/json",
|
|
330
|
+
"x-request-id": "socket-request-0001"
|
|
331
|
+
},
|
|
332
|
+
body: "{}"
|
|
333
|
+
});
|
|
334
|
+
const first = await post();
|
|
335
|
+
assert.equal(first.status, 201);
|
|
336
|
+
assert.equal(first.headers.get("x-request-id"), "socket-request-0001");
|
|
337
|
+
await first.arrayBuffer();
|
|
338
|
+
const second = await post();
|
|
339
|
+
assert.equal(second.status, 429);
|
|
340
|
+
assert.equal(second.headers.get("access-control-allow-origin"), "*");
|
|
341
|
+
assert.equal(second.headers.get("x-frame-options"), "DENY");
|
|
342
|
+
assert.ok(Number(second.headers.get("retry-after")) > 0);
|
|
343
|
+
assert.equal((await second.json()).error.code, "RATE_LIMITED");
|
|
344
|
+
const metrics = await fetch(`${server.url}/metrics`);
|
|
345
|
+
assert.equal(metrics.status, 200);
|
|
346
|
+
const text = await metrics.text();
|
|
347
|
+
assert.match(text, /naba_rate_limited_total 1/);
|
|
348
|
+
await server.close();
|
|
349
|
+
const lines = (await readFile(auditPath, "utf8")).trim().split("\n");
|
|
350
|
+
assert.equal(lines.length, 2, "both POST attempts are audited");
|
|
351
|
+
const statuses = lines.map((line) => JSON.parse(line).status);
|
|
352
|
+
assert.deepEqual(statuses, [201, 429]);
|
|
353
|
+
}
|
|
354
|
+
finally {
|
|
355
|
+
await rm(directory, { recursive: true, force: true });
|
|
356
|
+
}
|
|
357
|
+
});
|
|
358
|
+
test("oversized bodies over HTTP return a headered 413 and are audited", async () => {
|
|
359
|
+
const directory = await mkdtemp(join(tmpdir(), "naba-audit-413-"));
|
|
360
|
+
const auditPath = join(directory, "audit.jsonl");
|
|
361
|
+
try {
|
|
362
|
+
const app = createApp({
|
|
363
|
+
config: testConfig({ auditLog: auditPath }),
|
|
364
|
+
modules: [demoModule()]
|
|
365
|
+
});
|
|
366
|
+
const server = await app.listen(0, "127.0.0.1");
|
|
367
|
+
const response = await fetch(`${server.url}/api/echo`, {
|
|
368
|
+
method: "POST",
|
|
369
|
+
headers: {
|
|
370
|
+
"content-type": "application/json",
|
|
371
|
+
"x-request-id": "oversized-socket-1"
|
|
372
|
+
},
|
|
373
|
+
body: "x".repeat(6 * 1024 * 1024)
|
|
374
|
+
});
|
|
375
|
+
assert.equal(response.status, 413);
|
|
376
|
+
assert.equal(response.headers.get("x-request-id"), "oversized-socket-1");
|
|
377
|
+
assert.equal(response.headers.get("access-control-allow-origin"), "*");
|
|
378
|
+
assert.equal(response.headers.get("x-content-type-options"), "nosniff");
|
|
379
|
+
assert.equal(response.headers.get("x-frame-options"), "DENY");
|
|
380
|
+
const body = (await response.json());
|
|
381
|
+
assert.equal(body.error.code, "PAYLOAD_TOO_LARGE");
|
|
382
|
+
await server.close();
|
|
383
|
+
const lines = (await readFile(auditPath, "utf8")).trim().split("\n");
|
|
384
|
+
assert.equal(lines.length, 1);
|
|
385
|
+
const entry = JSON.parse(lines[0] ?? "{}");
|
|
386
|
+
assert.equal(entry.method, "POST");
|
|
387
|
+
assert.equal(entry.status, 413);
|
|
388
|
+
assert.equal(entry.path, "/api/echo");
|
|
389
|
+
assert.equal(entry.tenantId, "default");
|
|
390
|
+
}
|
|
391
|
+
finally {
|
|
392
|
+
await rm(directory, { recursive: true, force: true });
|
|
393
|
+
}
|
|
394
|
+
});
|
|
395
|
+
test("runtime createAuthGuard enforces Bearer auth against any authorize() service", () => {
|
|
396
|
+
const service = {
|
|
397
|
+
authorize(token, requirement) {
|
|
398
|
+
if (!token) {
|
|
399
|
+
throw new NabaError("UNAUTHORIZED", "missing", { status: 401 });
|
|
400
|
+
}
|
|
401
|
+
if (requirement.role && token !== requirement.role) {
|
|
402
|
+
throw new NabaError("FORBIDDEN", "role", { status: 403 });
|
|
403
|
+
}
|
|
404
|
+
return { sub: `user_${token}` };
|
|
405
|
+
}
|
|
406
|
+
};
|
|
407
|
+
const guard = createAuthGuard(service, { role: "admin" });
|
|
408
|
+
assert.deepEqual(guard("Bearer admin"), { sub: "user_admin" });
|
|
409
|
+
assert.throws(() => guard(""), (error) => error.code === "UNAUTHORIZED");
|
|
410
|
+
assert.throws(() => guard("Bearer user"), (error) => error.code === "FORBIDDEN");
|
|
411
|
+
assert.deepEqual(createAuthGuard(service)(`Bearer ${"x"}`), { sub: "user_x" });
|
|
412
|
+
});
|
|
413
|
+
test("close() stops modules even when listen() was never called", async () => {
|
|
414
|
+
let stopped = 0;
|
|
415
|
+
let registered = 0;
|
|
416
|
+
const module = {
|
|
417
|
+
name: "stoppable",
|
|
418
|
+
register(context) {
|
|
419
|
+
registered += 1;
|
|
420
|
+
context.addRoute({
|
|
421
|
+
method: "GET",
|
|
422
|
+
path: "/api/ping",
|
|
423
|
+
handler: () => json({ ok: true })
|
|
424
|
+
});
|
|
425
|
+
},
|
|
426
|
+
stop() {
|
|
427
|
+
stopped += 1;
|
|
428
|
+
}
|
|
429
|
+
};
|
|
430
|
+
const app = createApp({ config: testConfig(), modules: [module] });
|
|
431
|
+
assert.equal((await app.handle(new Request("http://localhost/api/health"))).status, 200);
|
|
432
|
+
assert.equal(registered, 1);
|
|
433
|
+
await app.close();
|
|
434
|
+
assert.equal(stopped, 1, "module.stop must run without listen()");
|
|
435
|
+
await app.close();
|
|
436
|
+
assert.equal(stopped, 1, "close is idempotent");
|
|
437
|
+
});
|
|
438
|
+
test("authorization failures consume the rate-limit budget", async () => {
|
|
439
|
+
const app = createApp({
|
|
440
|
+
config: testConfig({ rateLimit: { windowMs: 60_000, max: 2 } }),
|
|
441
|
+
modules: [demoModule()],
|
|
442
|
+
authorize: () => {
|
|
443
|
+
throw new NabaError("UNAUTHORIZED", "no token", { status: 401 });
|
|
444
|
+
}
|
|
445
|
+
});
|
|
446
|
+
assert.equal((await app.handle(new Request("http://localhost/api/ctx"))).status, 401);
|
|
447
|
+
assert.equal((await app.handle(new Request("http://localhost/api/ctx"))).status, 401);
|
|
448
|
+
const limited = await app.handle(new Request("http://localhost/api/ctx"));
|
|
449
|
+
assert.equal(limited.status, 429);
|
|
450
|
+
await app.close();
|
|
451
|
+
});
|
|
452
|
+
test("tenant header is accepted only when explicitly enabled and normalized", async () => {
|
|
453
|
+
const previous = process.env.NABA_ALLOW_TENANT_HEADER;
|
|
454
|
+
process.env.NABA_ALLOW_TENANT_HEADER = "1";
|
|
455
|
+
const app = createApp({
|
|
456
|
+
config: testConfig({ rateLimit: { windowMs: 60_000, max: 100, trustProxy: true } }, "development"),
|
|
457
|
+
modules: [demoModule()]
|
|
458
|
+
});
|
|
459
|
+
const withHeader = await app.handle(new Request("http://localhost/api/ctx", {
|
|
460
|
+
headers: {
|
|
461
|
+
"x-naba-tenant": " Acme-Store ",
|
|
462
|
+
"x-forwarded-for": "203.0.113.9"
|
|
463
|
+
}
|
|
464
|
+
}));
|
|
465
|
+
assert.equal(withHeader.status, 200);
|
|
466
|
+
const body = (await withHeader.json());
|
|
467
|
+
assert.equal(body.tenantId, "acme-store", "trimmed and lowercased");
|
|
468
|
+
assert.equal(body.clientKey, "203.0.113.9", "client key still uses x-forwarded-for when trusted");
|
|
469
|
+
const missing = await app.handle(new Request("http://localhost/api/ctx"));
|
|
470
|
+
assert.equal((await missing.json()).tenantId, "default");
|
|
471
|
+
const invalid = await app.handle(new Request("http://localhost/api/ctx", { headers: { "x-naba-tenant": "ACME STORE!" } }));
|
|
472
|
+
assert.equal((await invalid.json()).tenantId, "default");
|
|
473
|
+
const preflight = await app.handle(new Request("http://localhost/api/ctx", {
|
|
474
|
+
method: "OPTIONS",
|
|
475
|
+
headers: { "access-control-request-headers": "x-naba-tenant" }
|
|
476
|
+
}));
|
|
477
|
+
assert.equal(preflight.status, 204);
|
|
478
|
+
assert.match(preflight.headers.get("access-control-allow-headers") ?? "", /x-naba-tenant/, "browser preflights must allow the tenant header");
|
|
479
|
+
// x-forwarded-* must never be treated as a tenant.
|
|
480
|
+
const forwardedOnly = await app.handle(new Request("http://localhost/api/ctx", { headers: { "x-forwarded-host": "acme" } }));
|
|
481
|
+
assert.equal((await forwardedOnly.json()).tenantId, "default");
|
|
482
|
+
await app.close();
|
|
483
|
+
if (previous === undefined)
|
|
484
|
+
delete process.env.NABA_ALLOW_TENANT_HEADER;
|
|
485
|
+
else
|
|
486
|
+
process.env.NABA_ALLOW_TENANT_HEADER = previous;
|
|
487
|
+
});
|
|
488
|
+
test("production ignores the tenant header unless NABA_ALLOW_TENANT_HEADER=1", async () => {
|
|
489
|
+
const previous = process.env.NABA_ALLOW_TENANT_HEADER;
|
|
490
|
+
delete process.env.NABA_ALLOW_TENANT_HEADER;
|
|
491
|
+
try {
|
|
492
|
+
const app = createApp({ config: testConfig({}, "production"), modules: [demoModule()] });
|
|
493
|
+
const ignored = await app.handle(new Request("http://localhost/api/ctx", { headers: { "x-naba-tenant": "acme" } }));
|
|
494
|
+
assert.equal((await ignored.json()).tenantId, "default");
|
|
495
|
+
await app.close();
|
|
496
|
+
process.env.NABA_ALLOW_TENANT_HEADER = "1";
|
|
497
|
+
const trustedApp = createApp({ config: testConfig({}, "production"), modules: [demoModule()] });
|
|
498
|
+
const accepted = await trustedApp.handle(new Request("http://localhost/api/ctx", { headers: { "x-naba-tenant": "Acme" } }));
|
|
499
|
+
assert.equal((await accepted.json()).tenantId, "acme");
|
|
500
|
+
const invalid = await trustedApp.handle(new Request("http://localhost/api/ctx", { headers: { "x-naba-tenant": "not a tenant" } }));
|
|
501
|
+
assert.equal((await invalid.json()).tenantId, "default");
|
|
502
|
+
await trustedApp.close();
|
|
503
|
+
}
|
|
504
|
+
finally {
|
|
505
|
+
if (previous === undefined)
|
|
506
|
+
delete process.env.NABA_ALLOW_TENANT_HEADER;
|
|
507
|
+
else
|
|
508
|
+
process.env.NABA_ALLOW_TENANT_HEADER = previous;
|
|
509
|
+
}
|
|
510
|
+
});
|
|
511
|
+
test("authorize hook runs for protected routes only", async () => {
|
|
512
|
+
const seen = [];
|
|
513
|
+
const app = createApp({
|
|
514
|
+
config: testConfig(),
|
|
515
|
+
modules: [demoModule()],
|
|
516
|
+
authorize: (request) => {
|
|
517
|
+
seen.push(new URL(request.url).pathname);
|
|
518
|
+
}
|
|
519
|
+
});
|
|
520
|
+
assert.equal((await app.handle(new Request("http://localhost/api/ctx"))).status, 200);
|
|
521
|
+
assert.deepEqual(seen, ["/api/ctx"]);
|
|
522
|
+
const exempt = [
|
|
523
|
+
["GET", "http://localhost/"],
|
|
524
|
+
["GET", "http://localhost/api/health"],
|
|
525
|
+
["GET", "http://localhost/api/meta"],
|
|
526
|
+
["GET", "http://localhost/metrics"],
|
|
527
|
+
["GET", "http://localhost/api/auth/echo"],
|
|
528
|
+
["GET", "http://localhost/api/webhooks/echo"],
|
|
529
|
+
["OPTIONS", "http://localhost/api/echo"]
|
|
530
|
+
];
|
|
531
|
+
for (const [method, url] of exempt) {
|
|
532
|
+
const response = await app.handle(new Request(url, { method }));
|
|
533
|
+
assert.notEqual(response.status, 401, `${method} ${url} must bypass authorization`);
|
|
534
|
+
assert.notEqual(response.status, 403, `${method} ${url} must bypass authorization`);
|
|
535
|
+
}
|
|
536
|
+
assert.deepEqual(seen, ["/api/ctx"], "exempt paths never call the hook");
|
|
537
|
+
// Unknown protected paths are still checked before the router 404s.
|
|
538
|
+
assert.equal((await app.handle(new Request("http://localhost/api/unknown"))).status, 404);
|
|
539
|
+
assert.deepEqual(seen, ["/api/ctx", "/api/unknown"]);
|
|
540
|
+
await app.close();
|
|
541
|
+
});
|
|
542
|
+
test("authorize hook rejections map to 401/403 with CORS headers intact", async () => {
|
|
543
|
+
let hookCalls = 0;
|
|
544
|
+
const unauthorized = createApp({
|
|
545
|
+
config: testConfig(),
|
|
546
|
+
modules: [demoModule()],
|
|
547
|
+
authorize: () => {
|
|
548
|
+
hookCalls += 1;
|
|
549
|
+
throw new NabaError("UNAUTHORIZED", "missing bearer token", { status: 401 });
|
|
550
|
+
}
|
|
551
|
+
});
|
|
552
|
+
const denied = await unauthorized.handle(new Request("http://localhost/api/ctx"));
|
|
553
|
+
assert.equal(denied.status, 401);
|
|
554
|
+
assert.equal(denied.headers.get("access-control-allow-origin"), "*");
|
|
555
|
+
assert.equal(denied.headers.get("x-frame-options"), "DENY");
|
|
556
|
+
assertBaselineHeaders(denied);
|
|
557
|
+
assert.equal((await denied.json()).error.code, "UNAUTHORIZED");
|
|
558
|
+
assert.equal(hookCalls, 1);
|
|
559
|
+
const health = await unauthorized.handle(new Request("http://localhost/api/health"));
|
|
560
|
+
assert.equal(health.status, 200);
|
|
561
|
+
assert.equal(hookCalls, 1, "exempt routes do not invoke a rejecting hook");
|
|
562
|
+
// Metrics remain scrapeable even when the hook denies everything else.
|
|
563
|
+
const metrics = await unauthorized.handle(new Request("http://localhost/metrics"));
|
|
564
|
+
assert.equal(metrics.status, 200);
|
|
565
|
+
assert.equal(hookCalls, 1);
|
|
566
|
+
await unauthorized.close();
|
|
567
|
+
let asyncCalls = 0;
|
|
568
|
+
const forbidden = createApp({
|
|
569
|
+
config: testConfig(),
|
|
570
|
+
modules: [demoModule()],
|
|
571
|
+
authorize: async () => {
|
|
572
|
+
await Promise.resolve();
|
|
573
|
+
asyncCalls += 1;
|
|
574
|
+
throw new NabaError("FORBIDDEN", "insufficient role", { status: 403 });
|
|
575
|
+
}
|
|
576
|
+
});
|
|
577
|
+
const forbiddenResponse = await forbidden.handle(new Request("http://localhost/api/ctx"));
|
|
578
|
+
assert.equal(forbiddenResponse.status, 403);
|
|
579
|
+
assert.equal((await forbiddenResponse.json()).error.code, "FORBIDDEN");
|
|
580
|
+
assert.equal(asyncCalls, 1);
|
|
581
|
+
await forbidden.close();
|
|
582
|
+
// "Mapped error (401/403)" also holds when the hook omits the status.
|
|
583
|
+
const statusless = createApp({
|
|
584
|
+
config: testConfig(),
|
|
585
|
+
modules: [demoModule()],
|
|
586
|
+
authorize: () => {
|
|
587
|
+
throw new NabaError("UNAUTHORIZED", "no bearer token");
|
|
588
|
+
}
|
|
589
|
+
});
|
|
590
|
+
const statuslessResponse = await statusless.handle(new Request("http://localhost/api/ctx"));
|
|
591
|
+
assert.equal(statuslessResponse.status, 401);
|
|
592
|
+
await statusless.close();
|
|
593
|
+
});
|
|
594
|
+
test("no authorize hook means routes remain public by default", async () => {
|
|
595
|
+
const app = createApp({ config: testConfig(), modules: [demoModule()] });
|
|
596
|
+
assert.equal((await app.handle(new Request("http://localhost/api/ctx"))).status, 200);
|
|
597
|
+
await app.close();
|
|
598
|
+
});
|
|
599
|
+
test("injected async rate limiter is awaited and keeps 429/metrics behaviour", async () => {
|
|
600
|
+
let calls = 0;
|
|
601
|
+
const limiter = {
|
|
602
|
+
async consume() {
|
|
603
|
+
await Promise.resolve();
|
|
604
|
+
calls += 1;
|
|
605
|
+
const allowed = calls <= 2;
|
|
606
|
+
return {
|
|
607
|
+
allowed,
|
|
608
|
+
retryAfter: allowed ? 30 : 7,
|
|
609
|
+
remaining: allowed ? 2 - calls : 0,
|
|
610
|
+
limit: 2
|
|
611
|
+
};
|
|
612
|
+
}
|
|
613
|
+
};
|
|
614
|
+
const app = createApp({
|
|
615
|
+
config: testConfig(),
|
|
616
|
+
modules: [demoModule()],
|
|
617
|
+
rateLimiter: limiter
|
|
618
|
+
});
|
|
619
|
+
assert.equal((await postEcho(app)).status, 201);
|
|
620
|
+
assert.equal((await postEcho(app)).status, 201);
|
|
621
|
+
const limited = await postEcho(app);
|
|
622
|
+
assert.equal(limited.status, 429);
|
|
623
|
+
assert.equal(limited.headers.get("retry-after"), "7");
|
|
624
|
+
assertBaselineHeaders(limited);
|
|
625
|
+
assert.equal(calls, 3, "every request awaited consume()");
|
|
626
|
+
const metrics = await (await app.handle(new Request("http://localhost/metrics"))).text();
|
|
627
|
+
assert.match(metrics, /naba_rate_limited_total 1/);
|
|
628
|
+
assert.match(metrics, /naba_http_responses_total\{status="429"\} 1/);
|
|
629
|
+
await app.close();
|
|
630
|
+
});
|
|
631
|
+
test("injected sync rate limiter is supported", async () => {
|
|
632
|
+
let calls = 0;
|
|
633
|
+
const limiter = {
|
|
634
|
+
consume() {
|
|
635
|
+
calls += 1;
|
|
636
|
+
return {
|
|
637
|
+
allowed: calls <= 1,
|
|
638
|
+
retryAfter: 12,
|
|
639
|
+
remaining: calls <= 1 ? 0 : 0,
|
|
640
|
+
limit: 1
|
|
641
|
+
};
|
|
642
|
+
}
|
|
643
|
+
};
|
|
644
|
+
const app = createApp({
|
|
645
|
+
config: testConfig(),
|
|
646
|
+
modules: [demoModule()],
|
|
647
|
+
rateLimiter: limiter
|
|
648
|
+
});
|
|
649
|
+
assert.equal((await postEcho(app)).status, 201);
|
|
650
|
+
const limited = await postEcho(app);
|
|
651
|
+
assert.equal(limited.status, 429);
|
|
652
|
+
assert.equal(limited.headers.get("retry-after"), "12");
|
|
653
|
+
assert.equal(calls, 2);
|
|
654
|
+
await app.close();
|
|
655
|
+
});
|
|
656
|
+
test("injected audit sink receives metadata and is flushed/closed on close", async () => {
|
|
657
|
+
const entries = [];
|
|
658
|
+
let flushes = 0;
|
|
659
|
+
let closes = 0;
|
|
660
|
+
const sink = {
|
|
661
|
+
record(entry) {
|
|
662
|
+
entries.push(entry);
|
|
663
|
+
},
|
|
664
|
+
async flush() {
|
|
665
|
+
flushes += 1;
|
|
666
|
+
},
|
|
667
|
+
async close() {
|
|
668
|
+
closes += 1;
|
|
669
|
+
}
|
|
670
|
+
};
|
|
671
|
+
const app = createApp({
|
|
672
|
+
config: testConfig(),
|
|
673
|
+
modules: [demoModule()],
|
|
674
|
+
auditSink: sink
|
|
675
|
+
});
|
|
676
|
+
assert.equal((await app.handle(new Request("http://localhost/api/health"))).status, 200);
|
|
677
|
+
const posted = await postEcho(app, { "x-naba-tenant": "Acme", "x-request-id": "sink-request-0001" }, JSON.stringify({ card: "4111111111111111" }));
|
|
678
|
+
assert.equal(posted.status, 201);
|
|
679
|
+
assert.equal(entries.length, 1, "only state-changing requests are audited");
|
|
680
|
+
const entry = entries[0];
|
|
681
|
+
assert.equal(entry.method, "POST");
|
|
682
|
+
assert.equal(entry.path, "/api/echo");
|
|
683
|
+
assert.equal(entry.status, 201);
|
|
684
|
+
assert.equal(entry.requestId, "sink-request-0001");
|
|
685
|
+
assert.equal(entry.tenantId, "acme");
|
|
686
|
+
assert.equal(JSON.stringify(entries).includes("4111111111111111"), false, "no bodies");
|
|
687
|
+
await app.close();
|
|
688
|
+
assert.equal(flushes, 1);
|
|
689
|
+
assert.equal(closes, 1);
|
|
690
|
+
});
|
|
691
|
+
test("injected audit sink closes even when no request was handled", async () => {
|
|
692
|
+
let flushes = 0;
|
|
693
|
+
let closes = 0;
|
|
694
|
+
const sink = {
|
|
695
|
+
record() { },
|
|
696
|
+
async flush() {
|
|
697
|
+
flushes += 1;
|
|
698
|
+
},
|
|
699
|
+
async close() {
|
|
700
|
+
closes += 1;
|
|
701
|
+
}
|
|
702
|
+
};
|
|
703
|
+
const app = createApp({ config: testConfig(), modules: [demoModule()], auditSink: sink });
|
|
704
|
+
await app.close();
|
|
705
|
+
assert.equal(flushes, 1);
|
|
706
|
+
assert.equal(closes, 1);
|
|
707
|
+
await app.close();
|
|
708
|
+
assert.equal(closes, 1, "close is idempotent");
|
|
709
|
+
});
|
|
710
|
+
test("injected audit sink wins over runtime.auditLog", async () => {
|
|
711
|
+
const directory = await mkdtemp(join(tmpdir(), "naba-audit-sink-"));
|
|
712
|
+
const auditPath = join(directory, "should-not-exist.jsonl");
|
|
713
|
+
const entries = [];
|
|
714
|
+
const sink = {
|
|
715
|
+
record(entry) {
|
|
716
|
+
entries.push(entry);
|
|
717
|
+
},
|
|
718
|
+
async flush() { },
|
|
719
|
+
async close() { }
|
|
720
|
+
};
|
|
721
|
+
try {
|
|
722
|
+
const app = createApp({
|
|
723
|
+
config: testConfig({ auditLog: auditPath }),
|
|
724
|
+
modules: [demoModule()],
|
|
725
|
+
auditSink: sink
|
|
726
|
+
});
|
|
727
|
+
assert.equal((await postEcho(app)).status, 201);
|
|
728
|
+
await app.close();
|
|
729
|
+
assert.equal(entries.length, 1);
|
|
730
|
+
await assert.rejects(readFile(auditPath, "utf8"));
|
|
731
|
+
}
|
|
732
|
+
finally {
|
|
733
|
+
await rm(directory, { recursive: true, force: true });
|
|
734
|
+
}
|
|
735
|
+
});
|
|
736
|
+
test("rate limiting runs before authorization and rejected auth consumes quota", async () => {
|
|
737
|
+
const order = [];
|
|
738
|
+
const allowedLimiter = {
|
|
739
|
+
consume() {
|
|
740
|
+
order.push("limit");
|
|
741
|
+
return { allowed: true, retryAfter: 30, remaining: 9, limit: 10 };
|
|
742
|
+
}
|
|
743
|
+
};
|
|
744
|
+
const denied = createApp({
|
|
745
|
+
config: testConfig(),
|
|
746
|
+
modules: [demoModule()],
|
|
747
|
+
rateLimiter: allowedLimiter,
|
|
748
|
+
authorize: () => {
|
|
749
|
+
order.push("auth");
|
|
750
|
+
throw new NabaError("UNAUTHORIZED", "missing token", { status: 401 });
|
|
751
|
+
}
|
|
752
|
+
});
|
|
753
|
+
assert.equal((await denied.handle(new Request("http://localhost/api/ctx"))).status, 401);
|
|
754
|
+
assert.deepEqual(order, ["limit", "auth"]);
|
|
755
|
+
await denied.close();
|
|
756
|
+
order.length = 0;
|
|
757
|
+
const allowed = createApp({
|
|
758
|
+
config: testConfig(),
|
|
759
|
+
modules: [demoModule()],
|
|
760
|
+
rateLimiter: allowedLimiter,
|
|
761
|
+
authorize: () => {
|
|
762
|
+
order.push("auth");
|
|
763
|
+
}
|
|
764
|
+
});
|
|
765
|
+
assert.equal((await allowed.handle(new Request("http://localhost/api/ctx"))).status, 200);
|
|
766
|
+
assert.deepEqual(order, ["limit", "auth"]);
|
|
767
|
+
await allowed.close();
|
|
768
|
+
});
|
|
769
|
+
test("oversized requests still get 413 headers with an injected audit sink", async () => {
|
|
770
|
+
const entries = [];
|
|
771
|
+
const sink = {
|
|
772
|
+
record(entry) {
|
|
773
|
+
entries.push(entry);
|
|
774
|
+
},
|
|
775
|
+
async flush() { },
|
|
776
|
+
async close() { }
|
|
777
|
+
};
|
|
778
|
+
const app = createApp({ config: testConfig(), modules: [demoModule()], auditSink: sink });
|
|
779
|
+
const response = await app.handle(new Request("http://localhost/api/echo", {
|
|
780
|
+
method: "POST",
|
|
781
|
+
headers: {
|
|
782
|
+
"content-type": "application/json",
|
|
783
|
+
"content-length": String(6 * 1024 * 1024),
|
|
784
|
+
"x-request-id": "injected-413"
|
|
785
|
+
},
|
|
786
|
+
body: "{}"
|
|
787
|
+
}));
|
|
788
|
+
assert.equal(response.status, 413);
|
|
789
|
+
assert.equal(response.headers.get("x-request-id"), "injected-413");
|
|
790
|
+
assertBaselineHeaders(response);
|
|
791
|
+
assert.equal(entries.length, 1);
|
|
792
|
+
assert.equal(entries[0].status, 413);
|
|
793
|
+
await app.close();
|
|
794
|
+
});
|
|
795
|
+
//# sourceMappingURL=hardening.test.js.map
|