-
Notifications
You must be signed in to change notification settings - Fork 2.8k
/
fetch.tls.test.ts
342 lines (313 loc) · 9.62 KB
/
fetch.tls.test.ts
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
import { expect, it } from "bun:test";
import { bunEnv, bunExe, tmpdirSync } from "harness";
import { join } from "node:path";
import tls from "node:tls";
type TLSOptions = {
cert: string;
key: string;
passphrase?: string;
};
import { tls as cert1, expiredTls as cert2 } from "harness";
const CERT_LOCALHOST_IP = { ...cert1 };
const CERT_EXPIRED = { ...cert2 };
// Note: Do not use bun.sh as the example domain
// Cloudflare sometimes blocks automated requests to it.
// so it will cause flaky tests.
async function createServer(cert: TLSOptions, callback: (port: number) => Promise<any>) {
using server = Bun.serve({
port: 0,
tls: cert,
fetch() {
return new Response("Hello World");
},
});
await callback(server.port);
}
it("can handle multiple requests with non native checkServerIdentity", async () => {
async function request() {
let called = false;
const result = await fetch("https://www.example.com", {
keepalive: false,
tls: {
checkServerIdentity(hostname: string, cert: tls.PeerCertificate) {
called = true;
return tls.checkServerIdentity(hostname, cert);
},
},
}).then((res: Response) => res.blob());
expect(result?.size).toBeGreaterThan(0);
expect(called).toBe(true);
}
const promises = [];
for (let i = 0; i < 5; i++) {
promises.push(request());
}
await Promise.all(promises);
});
it("fetch with valid tls should not throw", async () => {
const promises = [`https://example.com`, `https://www.example.com`].map(async url => {
const result = await fetch(url, { keepalive: false }).then((res: Response) => res.blob());
expect(result?.size).toBeGreaterThan(0);
});
await Promise.all(promises);
});
it("fetch with valid tls and non-native checkServerIdentity should work", async () => {
for (const isBusy of [true, false]) {
let count = 0;
const promises = [`https://example.com`, `https://www.example.com`].map(async url => {
await fetch(url, {
keepalive: false,
tls: {
checkServerIdentity(hostname: string, cert: tls.PeerCertificate) {
count++;
expect(url).toContain(hostname);
return tls.checkServerIdentity(hostname, cert);
},
},
}).then((res: Response) => res.blob());
});
if (isBusy) {
const start = performance.now();
while (performance.now() - start < 500) {}
}
await Promise.all(promises);
expect(count).toBe(2);
}
});
it("fetch with valid tls and non-native checkServerIdentity should work", async () => {
let count = 0;
const promises = [`https://example.com`, `https://www.example.com`].map(async url => {
await fetch(url, {
keepalive: false,
tls: {
checkServerIdentity(hostname: string, cert: tls.PeerCertificate) {
count++;
expect(url).toContain(hostname);
throw new Error("CustomError");
},
},
});
});
const start = performance.now();
while (performance.now() - start < 1000) {}
expect((await Promise.allSettled(promises)).every(p => p.status === "rejected")).toBe(true);
expect(count).toBe(2);
});
it("fetch with rejectUnauthorized: false should not call checkServerIdentity", async () => {
let count = 0;
await fetch("https://example.com", {
keepalive: false,
tls: {
rejectUnauthorized: false,
checkServerIdentity(hostname: string, cert: tls.PeerCertificate) {
count++;
return tls.checkServerIdentity(hostname, cert);
},
},
}).then((res: Response) => res.blob());
expect(count).toBe(0);
});
it("fetch with self-sign tls should throw", async () => {
await createServer(CERT_LOCALHOST_IP, async port => {
const urls = [`https://localhost:${port}`, `https://127.0.0.1:${port}`];
await Promise.all(
urls.map(async url => {
try {
await fetch(url).then((res: Response) => res.blob());
expect.unreachable();
} catch (e: any) {
expect(e.code).toBe("DEPTH_ZERO_SELF_SIGNED_CERT");
}
}),
);
});
});
it("fetch with invalid tls should throw", async () => {
await createServer(CERT_EXPIRED, async port => {
await Promise.all(
[`https://localhost:${port}`, `https://127.0.0.1:${port}`].map(async url => {
try {
await fetch(url).then((res: Response) => res.blob());
expect.unreachable();
} catch (e: any) {
expect(e.code).toBe("CERT_HAS_EXPIRED");
}
}),
);
});
});
it("fetch with checkServerIdentity failing should throw", async () => {
try {
await fetch(`https://example.com`, {
keepalive: false,
tls: {
checkServerIdentity() {
return new Error("CustomError");
},
},
}).then((res: Response) => res.blob());
expect.unreachable();
} catch (e: any) {
expect(e.message).toBe("CustomError");
}
});
it("fetch with self-sign certificate tls + rejectUnauthorized: false should not throw", async () => {
await createServer(CERT_LOCALHOST_IP, async port => {
const urls = [`https://localhost:${port}`, `https://127.0.0.1:${port}`];
await Promise.all(
urls.map(async url => {
try {
const result = await fetch(url, { tls: { rejectUnauthorized: false } }).then((res: Response) => res.text());
expect(result).toBe("Hello World");
} catch {
expect.unreachable();
}
}),
);
});
});
it("fetch with invalid tls + rejectUnauthorized: false should not throw", async () => {
await createServer(CERT_EXPIRED, async port => {
const urls = [`https://localhost:${port}`, `https://127.0.0.1:${port}`];
await Promise.all(
urls.map(async url => {
try {
const result = await fetch(url, { tls: { rejectUnauthorized: false } }).then((res: Response) => res.text());
expect(result).toBe("Hello World");
} catch (e) {
expect.unreachable();
}
}),
);
});
});
it("fetch should respect rejectUnauthorized env", async () => {
await createServer(CERT_EXPIRED, async port => {
const url = `https://localhost:${port}`;
const promises = [];
for (let i = 0; i < 2; i++) {
const proc = Bun.spawn({
env: {
...bunEnv,
SERVER: url,
NODE_TLS_REJECT_UNAUTHORIZED: i.toString(),
},
stderr: "inherit",
stdout: "inherit",
stdin: "inherit",
cmd: [bunExe(), join(import.meta.dir, "fetch-reject-authorized-env-fixture.js")],
});
promises.push(proc.exited);
}
const [exitCode1, exitCode2] = await Promise.all(promises);
expect(exitCode1).toBe(0);
expect(exitCode2).toBe(1);
});
});
it("fetch timeout works on tls", async () => {
using server = Bun.serve({
tls: cert1,
hostname: "localhost",
port: 0,
rejectUnauthorized: false,
async fetch() {
async function* body() {
yield "Hello, ";
await Bun.sleep(700); // should only take 200ms-350ms
yield "World!";
}
return new Response(body);
},
});
const start = performance.now();
const TIMEOUT = 200;
const THRESHOLD = 150;
try {
await fetch(server.url, {
signal: AbortSignal.timeout(TIMEOUT),
tls: { ca: cert1.cert },
}).then(res => res.text());
expect.unreachable();
} catch (e) {
expect(e.name).toBe("TimeoutError");
} finally {
const total = performance.now() - start;
expect(total).toBeGreaterThanOrEqual(TIMEOUT - THRESHOLD);
expect(total).toBeLessThanOrEqual(TIMEOUT + THRESHOLD);
}
});
for (const timeout of [0, 1, 10, 20, 100, 300]) {
it(`fetch should abort as soon as possible under tls using AbortSignal.timeout(${timeout})`, async () => {
using server = Bun.serve({
port: 0,
tls: CERT_LOCALHOST_IP,
async fetch() {
await Bun.sleep(1000);
return new Response("Hello World");
},
});
const THRESHOLD = 50;
const time = performance.now();
try {
await fetch(server.url, {
//@ts-ignore
tls: { ca: CERT_LOCALHOST_IP.cert },
signal: AbortSignal.timeout(timeout),
}).then(res => res.text());
expect.unreachable();
} catch (err) {
expect((err as Error).name).toBe("TimeoutError");
} finally {
const diff = performance.now() - time;
expect(diff).toBeLessThanOrEqual(timeout + THRESHOLD);
expect(diff).toBeGreaterThanOrEqual(timeout - THRESHOLD);
}
});
}
it("fetch should use NODE_EXTRA_CA_CERTS", async () => {
using server = Bun.serve({
port: 0,
tls: cert1,
fetch() {
return new Response("OK");
},
});
const cert_path = join(tmpdirSync(), "cert.pem");
await Bun.write(cert_path, cert1.cert);
const proc = Bun.spawn({
env: {
...bunEnv,
SERVER: server.url,
NODE_EXTRA_CA_CERTS: cert_path,
},
stderr: "inherit",
stdout: "inherit",
stdin: "inherit",
cmd: [bunExe(), join(import.meta.dir, "fetch.tls.extra-cert.fixture.js")],
});
expect(await proc.exited).toBe(0);
});
it("fetch should ignore invalid NODE_EXTRA_CA_CERTS", async () => {
using server = Bun.serve({
port: 0,
tls: cert1,
fetch() {
return new Response("OK");
},
});
for (const invalid of ["invalid.pem", "", " "]) {
const proc = Bun.spawn({
env: {
...bunEnv,
SERVER: server.url,
NODE_EXTRA_CA_CERTS: invalid,
},
stderr: "pipe",
stdout: "inherit",
stdin: "inherit",
cmd: [bunExe(), join(import.meta.dir, "fetch.tls.extra-cert.fixture.js")],
});
expect(await proc.exited).toBe(1);
expect(await Bun.readableStreamToText(proc.stderr)).toContain("DEPTH_ZERO_SELF_SIGNED_CERT");
}
});