-
Notifications
You must be signed in to change notification settings - Fork 40
Expand file tree
/
Copy pathHTTPServer.test.ts
More file actions
782 lines (713 loc) · 20.5 KB
/
HTTPServer.test.ts
File metadata and controls
782 lines (713 loc) · 20.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
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
import { Token } from "../agent/api/Token";
import { getMajorNodeVersion } from "../helpers/getNodeVersion";
import * as t from "tap";
import { ReportingAPIForTesting } from "../agent/api/ReportingAPIForTesting";
import { getContext } from "../agent/Context";
import { fetch } from "../helpers/fetch";
import { wrap } from "../helpers/wrap";
import { HTTPServer } from "./HTTPServer";
import { join } from "path";
import { createTestAgent } from "../helpers/createTestAgent";
import type { IPList } from "../agent/api/fetchBlockedLists";
import * as fetchBlockedLists from "../agent/api/fetchBlockedLists";
import { mkdtemp, writeFile, unlink } from "fs/promises";
import { exec } from "child_process";
import { promisify } from "util";
import { FileSystem } from "../sinks/FileSystem";
import { Path } from "../sinks/Path";
const execAsync = promisify(exec);
// Before require("http")
const api = new ReportingAPIForTesting({
success: true,
configUpdatedAt: 0,
allowedIPAddresses: [],
blockedUserIds: [],
endpoints: [
{
route: "/rate-limited",
method: "GET",
forceProtectionOff: false,
allowedIPAddresses: [],
rateLimiting: {
enabled: true,
maxRequests: 3,
windowSizeInMS: 60 * 60 * 1000,
},
},
{
route: "/ip-allowed",
method: "GET",
forceProtectionOff: false,
allowedIPAddresses: ["8.8.8.8"],
// @ts-expect-error Testing
rateLimiting: undefined,
},
],
heartbeatIntervalInMS: 10 * 60 * 1000,
});
const agent = createTestAgent({
token: new Token("123"),
api,
});
agent.start([new HTTPServer(), new FileSystem(), new Path()]);
wrap(fetchBlockedLists, "fetchBlockedLists", function fetchBlockedLists() {
return async function fetchBlockedLists(): Promise<{
blockedIPAddresses: IPList[];
blockedUserAgents: string;
}> {
return {
blockedIPAddresses: [
{
source: "geoip",
ips: ["9.9.9.9"],
description: "geo restrictions",
},
],
blockedUserAgents: "",
};
};
});
t.setTimeout(30 * 1000);
t.beforeEach(() => {
delete process.env.AIKIDO_MAX_BODY_SIZE_MB;
delete process.env.NODE_ENV;
delete process.env.NEXT_DEPLOYMENT_ID;
});
const http = require("http") as typeof import("http");
const https = require("https") as typeof import("https");
const { readFileSync } = require("fs");
t.test("it wraps the createServer function of http module", async () => {
const server = http.createServer((req, res) => {
res.setHeader("Content-Type", "application/json");
res.end(JSON.stringify(getContext()));
});
http.globalAgent = new http.Agent({ keepAlive: false });
await new Promise<void>((resolve) => {
server.listen(3314, () => {
fetch({
url: new URL("http://localhost:3314"),
method: "GET",
headers: {},
timeoutInMS: 500,
}).then(({ body }) => {
const context = JSON.parse(body);
t.same(context, {
url: "/",
method: "GET",
headers: { host: "localhost:3314", connection: "close" },
query: {},
route: "/",
source: "http.createServer",
routeParams: {},
cookies: {},
remoteAddress:
getMajorNodeVersion() === 16 ? "::ffff:127.0.0.1" : "::1",
});
server.close();
resolve();
});
});
});
});
t.test("it wraps the createServer function of https module", async () => {
const { readFileSync } = require("fs");
const path = require("path");
// Otherwise, the self-signed certificate will be rejected
process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0";
const server = https.createServer(
{
key: readFileSync(path.resolve(__dirname, "fixtures/key.pem")),
cert: readFileSync(path.resolve(__dirname, "fixtures/cert.pem")),
},
(req, res) => {
res.setHeader("Content-Type", "application/json");
res.end(JSON.stringify(getContext()));
}
);
https.globalAgent = new https.Agent({ keepAlive: false });
await new Promise<void>((resolve) => {
server.listen(3315, () => {
fetch({
url: new URL("https://localhost:3315"),
method: "GET",
headers: {},
timeoutInMS: 500,
}).then(({ body }) => {
const context = JSON.parse(body);
t.same(context, {
url: "/",
method: "GET",
headers: { host: "localhost:3315", connection: "close" },
query: {},
route: "/",
source: "https.createServer",
routeParams: {},
cookies: {},
remoteAddress:
getMajorNodeVersion() === 16 ? "::ffff:127.0.0.1" : "::1",
});
server.close();
resolve();
});
});
});
});
t.test("it parses query parameters", async () => {
const server = http.createServer((req, res) => {
res.setHeader("Content-Type", "application/json");
res.end(JSON.stringify(getContext()));
});
await new Promise<void>((resolve) => {
server.listen(3317, () => {
fetch({
url: new URL("http://localhost:3317?foo=bar&baz=qux"),
method: "GET",
headers: {},
timeoutInMS: 500,
}).then(({ body }) => {
const context = JSON.parse(body);
t.same(context.query, { foo: "bar", baz: "qux" });
server.close();
resolve();
});
});
});
});
t.test("it discovers routes", async () => {
const server = http.createServer((req, res) => {
res.setHeader("Content-Type", "application/json");
res.end(JSON.stringify(getContext()));
});
await new Promise<void>((resolve) => {
server.listen(3340, () => {
fetch({
url: new URL("http://localhost:3340/foo/bar"),
method: "GET",
headers: {},
timeoutInMS: 500,
}).then(({ body }) => {
t.same(
agent
.getRoutes()
.asArray()
.find((route) => route.path === "/foo/bar"),
{
path: "/foo/bar",
method: "GET",
hits: 1,
graphql: undefined,
apispec: {},
graphQLSchema: undefined,
}
);
server.close();
resolve();
});
});
});
});
t.test(
"it does not discover route if server response is error code",
async (t) => {
const server = http.createServer((req, res) => {
res.statusCode = 404;
res.end();
});
await new Promise<void>((resolve) => {
server.listen(3341, () => {
fetch({
url: new URL("http://localhost:3341/not-found"),
method: "GET",
headers: {},
timeoutInMS: 500,
}).then(() => {
t.equal(
agent
.getRoutes()
.asArray()
.find((route) => route.path === "/not-found"),
undefined
);
server.close();
resolve();
});
});
});
}
);
t.test("it parses cookies", async (t) => {
const server = http.createServer((req, res) => {
res.setHeader("Content-Type", "application/json");
res.end(JSON.stringify(getContext()));
});
await new Promise<void>((resolve) => {
server.listen(3318, () => {
fetch({
url: new URL("http://localhost:3318"),
method: "GET",
headers: {
Cookie: "foo=bar; baz=qux",
},
timeoutInMS: 500,
}).then(({ body }) => {
const context = JSON.parse(body);
t.same(context.cookies, { foo: "bar", baz: "qux" });
server.close();
resolve();
});
});
});
});
t.test("it parses x-forwarded-for header with proxy", async (t) => {
const server = http.createServer((req, res) => {
res.setHeader("Content-Type", "application/json");
res.end(JSON.stringify(getContext()));
});
await new Promise<void>((resolve) => {
server.listen(3316, () => {
fetch({
url: new URL("http://localhost:3316"),
method: "GET",
headers: {
"x-forwarded-for":
"1.2.3.4,2001:db8:85a3:8d3:1319:8a2e:370:7348,198.51.100.178",
},
timeoutInMS: 500,
}).then(({ body }) => {
const context = JSON.parse(body);
t.same(context.remoteAddress, "1.2.3.4");
server.close();
resolve();
});
});
});
});
t.test("it uses x-forwarded-for header", async (t) => {
const server = http.createServer((req, res) => {
res.setHeader("Content-Type", "application/json");
res.end(JSON.stringify(getContext()));
});
await new Promise<void>((resolve) => {
server.listen(3350, () => {
fetch({
url: new URL("http://localhost:3350"),
method: "GET",
headers: {
"x-forwarded-for": "1.2.3.4,",
},
timeoutInMS: 500,
}).then(({ body }) => {
const context = JSON.parse(body);
t.same(context.remoteAddress, "1.2.3.4");
server.close();
resolve();
});
});
});
});
t.test("it sets body in context", async (t) => {
// Enables body parsing
process.env.NEXT_DEPLOYMENT_ID = "";
const server = http.createServer((req, res) => {
res.setHeader("Content-Type", "application/json");
res.end(JSON.stringify(getContext()));
});
await new Promise<void>((resolve) => {
server.listen(3319, () => {
fetch({
url: new URL("http://localhost:3319"),
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({ foo: "bar" }),
timeoutInMS: 500,
}).then(({ body }) => {
const context = JSON.parse(body);
t.same(context.body, { foo: "bar" });
server.close();
resolve();
});
});
});
});
function generateJsonPayload(sizeInMb: number) {
const doubleQuotes = 2;
const sizeInBytes = sizeInMb * 1024 * 1024 - doubleQuotes;
return JSON.stringify("a".repeat(sizeInBytes));
}
// Send request using curl
// Returns the response message + status code in stdout
// We need this because http.request throws EPIPE write error when the server closes the connection abruptly
// We cannot read the status code or the response message when that happens
async function sendUsingCurl({
url,
method,
headers,
body,
timeoutInMS,
}: {
url: URL;
method: string;
headers: Record<string, string>;
body: string;
timeoutInMS: number;
}) {
const headersString = Object.entries(headers)
.map(([key, value]) => `-H "${key}: ${value}"`)
.join(" ");
const tmpDir = await mkdtemp("/tmp/aikido-");
const tmpFile = join(tmpDir, "/body.json");
await writeFile(tmpFile, body, { encoding: "utf-8" });
const { stdout } = await execAsync(
`curl -X ${method} ${headersString} -d @${tmpFile} ${url} --max-time ${timeoutInMS / 1000} --write-out "%{http_code}"`
);
await unlink(tmpFile);
return stdout;
}
t.only("it sends 413 when body is larger than 20 Mb", async (t) => {
// Enables body parsing
process.env.NEXT_DEPLOYMENT_ID = "";
const server = http.createServer((req, res) => {
t.fail();
res.end();
});
await new Promise<void>((resolve) => {
server.listen(3320, () => {
sendUsingCurl({
url: new URL("http://localhost:3320"),
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: generateJsonPayload(21),
timeoutInMS: 2000,
})
.then((stdout) => {
t.equal(
stdout,
"This request was aborted by Aikido firewall because the body size exceeded the maximum allowed size. Use AIKIDO_MAX_BODY_SIZE_MB to increase the limit.413"
);
})
.catch((error) => {
t.fail(error);
})
.finally(() => {
server.close();
resolve();
});
});
});
});
t.test("body that is not JSON is ignored", async (t) => {
// Enables body parsing
process.env.NEXT_DEPLOYMENT_ID = "";
const server = http.createServer((req, res) => {
res.setHeader("Content-Type", "application/json");
res.end(JSON.stringify(getContext()));
});
await new Promise<void>((resolve) => {
server.listen(3321, () => {
fetch({
url: new URL("http://localhost:3321"),
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: "not json",
timeoutInMS: 500,
}).then(({ body }) => {
const context = JSON.parse(body);
t.same(context.body, undefined);
server.close();
resolve();
});
});
});
});
t.test("it uses limit from AIKIDO_MAX_BODY_SIZE_MB", async (t) => {
// Enables body parsing
process.env.NEXT_DEPLOYMENT_ID = "";
const server = http.createServer((req, res) => {
res.end();
});
await new Promise<void>((resolve) => {
server.listen(3322, () => {
process.env.AIKIDO_MAX_BODY_SIZE_MB = "1";
Promise.all([
sendUsingCurl({
url: new URL("http://localhost:3322"),
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: generateJsonPayload(1),
timeoutInMS: 2000,
}),
sendUsingCurl({
url: new URL("http://localhost:3322"),
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: generateJsonPayload(2),
timeoutInMS: 2000,
}),
])
.then(([response1, response2]) => {
t.equal(response1, "200");
t.same(
response2,
"This request was aborted by Aikido firewall because the body size exceeded the maximum allowed size. Use AIKIDO_MAX_BODY_SIZE_MB to increase the limit.413"
);
})
.catch((error) => {
t.fail(error);
})
.finally(() => {
server.close();
resolve();
});
});
});
});
t.test("it wraps on request event of http", async () => {
const server = http.createServer();
server.on("request", (req, res) => {
res.setHeader("Content-Type", "application/json");
res.end(JSON.stringify(getContext()));
});
http.globalAgent = new http.Agent({ keepAlive: false });
await new Promise<void>((resolve) => {
server.listen(3367, () => {
fetch({
url: new URL("http://localhost:3367"),
method: "GET",
headers: {},
timeoutInMS: 500,
}).then(({ body }) => {
const context = JSON.parse(body);
t.same(context, {
url: "/",
method: "GET",
headers: { host: "localhost:3367", connection: "close" },
query: {},
route: "/",
source: "http.createServer",
routeParams: {},
cookies: {},
remoteAddress:
getMajorNodeVersion() === 16 ? "::ffff:127.0.0.1" : "::1",
});
server.close();
resolve();
});
});
});
});
t.test("it wraps on request event of https", async () => {
const { readFileSync } = require("fs");
const path = require("path");
// Otherwise, the self-signed certificate will be rejected
process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0";
const server = https.createServer({
key: readFileSync(path.resolve(__dirname, "fixtures/key.pem")),
cert: readFileSync(path.resolve(__dirname, "fixtures/cert.pem")),
});
server.on("request", (req, res) => {
res.setHeader("Content-Type", "application/json");
res.end(JSON.stringify(getContext()));
});
https.globalAgent = new https.Agent({ keepAlive: false });
await new Promise<void>((resolve) => {
server.listen(3361, () => {
fetch({
url: new URL("https://localhost:3361"),
method: "GET",
headers: {},
timeoutInMS: 500,
}).then(({ body }) => {
const context = JSON.parse(body);
t.same(context, {
url: "/",
method: "GET",
headers: { host: "localhost:3361", connection: "close" },
query: {},
route: "/",
source: "https.createServer",
routeParams: {},
cookies: {},
remoteAddress:
getMajorNodeVersion() === 16 ? "::ffff:127.0.0.1" : "::1",
});
server.close();
resolve();
});
});
});
});
t.test("it checks if IP can access route", async (t) => {
const server = http.createServer((req, res) => {
res.setHeader("Content-Type", "text/plain");
res.end("OK");
});
process.env.NODE_ENV = "production";
await new Promise<void>((resolve) => {
server.listen(3324, () => {
Promise.all([
fetch({
url: new URL("http://localhost:3324/ip-allowed"),
method: "GET",
headers: {
"x-forwarded-for": "8.8.8.8",
},
timeoutInMS: 500,
}),
fetch({
url: new URL("http://localhost:3324/ip-allowed"),
method: "GET",
headers: {},
timeoutInMS: 500,
}),
fetch({
url: new URL("http://localhost:3324/ip-allowed"),
method: "GET",
headers: {
"x-forwarded-for": "1.2.3.4",
},
timeoutInMS: 500,
}),
]).then(([response1, response2, response3]) => {
t.equal(response1.statusCode, 200);
t.equal(response2.statusCode, 200);
t.equal(response3.statusCode, 403);
t.same(
response3.body,
"Your IP address is not allowed to access this resource. (Your IP: 1.2.3.4)"
);
server.close();
resolve();
});
});
});
});
t.test("it blocks IP address", async (t) => {
const server = http.createServer((req, res) => {
res.setHeader("Content-Type", "text/plain");
res.end("OK");
});
await new Promise<void>((resolve) => {
server.listen(3325, () => {
Promise.all([
fetch({
url: new URL("http://localhost:3325"),
method: "GET",
headers: {
"x-forwarded-for": "9.9.9.9",
},
timeoutInMS: 500,
}),
fetch({
url: new URL("http://localhost:3325"),
method: "GET",
timeoutInMS: 500,
}),
]).then(([response1, response2]) => {
t.equal(response1.statusCode, 403);
t.equal(
response1.body,
"Your IP address is blocked due to geo restrictions. (Your IP: 9.9.9.9)"
);
t.equal(response2.statusCode, 200);
server.close();
resolve();
});
});
});
});
t.test(
"it blocks IP address when there are multiple request handlers on server",
async (t) => {
const server = http.createServer((req, res) => {
res.setHeader("Content-Type", "text/plain");
res.end("OK");
});
server.on("request", (req, res) => {
if (res.headersSent) {
return;
}
res.setHeader("Content-Type", "text/plain");
res.end("OK");
});
await new Promise<void>((resolve) => {
server.listen(3326, () => {
fetch({
url: new URL("http://localhost:3326"),
method: "GET",
headers: {
"x-forwarded-for": "9.9.9.9",
},
timeoutInMS: 500,
}).then(({ statusCode, body }) => {
t.equal(statusCode, 403);
t.equal(
body,
"Your IP address is blocked due to geo restrictions. (Your IP: 9.9.9.9)"
);
server.close();
resolve();
});
});
});
}
);
t.test("it blocks path traversal in path", async (t) => {
const server = http.createServer((req, res) => {
try {
// @ts-expect-error Ignore
const file = readFileSync(join(__dirname, req.url));
res.statusCode = 200;
res.end(file);
} catch (error) {
res.statusCode = 500;
if (error instanceof Error) {
res.end(error.message);
return;
}
res.end("Internal server error");
}
});
await new Promise<void>((resolve) => {
server.listen(3327, async () => {
const response = await new Promise((resolve, reject) => {
const req = http.request(
{
hostname: "localhost",
port: 3327,
path: "/../package.json", // Path traversal attempt
method: "GET",
},
(res) => {
let data = "";
res.on("data", (chunk) => {
data += chunk;
});
res.on("end", () => {
resolve(data);
});
}
);
req.on("error", (err) => {
reject(err);
});
req.end();
});
t.equal(
response,
"Zen has blocked a path traversal attack: path.join(...) originating from url."
);
server.close();
resolve();
});
});
});