forked from electron/electron
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapi-net-spec.ts
2342 lines (2146 loc) · 91.3 KB
/
api-net-spec.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
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
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { expect } from 'chai';
import * as dns from 'node:dns';
import { net, session, ClientRequest, BrowserWindow, ClientRequestConstructorOptions, protocol } from 'electron/main';
import * as http from 'node:http';
import * as url from 'node:url';
import * as path from 'node:path';
import { Socket } from 'node:net';
import { defer, listen } from './lib/spec-helpers';
import { once } from 'node:events';
import { setTimeout } from 'node:timers/promises';
// See https://github.com/nodejs/node/issues/40702.
dns.setDefaultResultOrder('ipv4first');
const kOneKiloByte = 1024;
const kOneMegaByte = kOneKiloByte * kOneKiloByte;
function randomBuffer (size: number, start: number = 0, end: number = 255) {
const range = 1 + end - start;
const buffer = Buffer.allocUnsafe(size);
for (let i = 0; i < size; ++i) {
buffer[i] = start + Math.floor(Math.random() * range);
}
return buffer;
}
function randomString (length: number) {
const buffer = randomBuffer(length, '0'.charCodeAt(0), 'z'.charCodeAt(0));
return buffer.toString();
}
async function getResponse (urlRequest: Electron.ClientRequest) {
return new Promise<Electron.IncomingMessage>((resolve, reject) => {
urlRequest.on('error', reject);
urlRequest.on('abort', reject);
urlRequest.on('response', (response) => resolve(response));
urlRequest.end();
});
}
async function collectStreamBody (response: Electron.IncomingMessage | http.IncomingMessage) {
return (await collectStreamBodyBuffer(response)).toString();
}
function collectStreamBodyBuffer (response: Electron.IncomingMessage | http.IncomingMessage) {
return new Promise<Buffer>((resolve, reject) => {
response.on('error', reject);
(response as NodeJS.EventEmitter).on('aborted', reject);
const data: Buffer[] = [];
response.on('data', (chunk) => data.push(chunk));
response.on('end', (chunk?: Buffer) => {
if (chunk) data.push(chunk);
resolve(Buffer.concat(data));
});
});
}
async function respondNTimes (fn: http.RequestListener, n: number): Promise<string> {
const server = http.createServer((request, response) => {
fn(request, response);
// don't close if a redirect was returned
if ((response.statusCode < 300 || response.statusCode >= 399) && n <= 0) {
n--;
server.close();
}
});
const sockets: Socket[] = [];
server.on('connection', s => sockets.push(s));
defer(() => {
server.close();
sockets.forEach(s => s.destroy());
});
return (await listen(server)).url;
}
function respondOnce (fn: http.RequestListener) {
return respondNTimes(fn, 1);
}
let routeFailure = false;
respondNTimes.toRoutes = (routes: Record<string, http.RequestListener>, n: number) => {
return respondNTimes((request, response) => {
if (Object.hasOwn(routes, request.url || '')) {
(async () => {
await Promise.resolve(routes[request.url || ''](request, response));
})().catch((err) => {
routeFailure = true;
console.error('Route handler failed, this is probably why your test failed', err);
response.statusCode = 500;
response.end();
});
} else {
response.statusCode = 500;
response.end();
expect.fail(`Unexpected URL: ${request.url}`);
}
}, n);
};
respondOnce.toRoutes = (routes: Record<string, http.RequestListener>) => respondNTimes.toRoutes(routes, 1);
respondNTimes.toURL = (url: string, fn: http.RequestListener, n: number) => {
return respondNTimes.toRoutes({ [url]: fn }, n);
};
respondOnce.toURL = (url: string, fn: http.RequestListener) => respondNTimes.toURL(url, fn, 1);
respondNTimes.toSingleURL = (fn: http.RequestListener, n: number) => {
const requestUrl = '/requestUrl';
return respondNTimes.toURL(requestUrl, fn, n).then(url => `${url}${requestUrl}`);
};
respondOnce.toSingleURL = (fn: http.RequestListener) => respondNTimes.toSingleURL(fn, 1);
describe('net module', () => {
beforeEach(() => {
routeFailure = false;
});
afterEach(async function () {
await session.defaultSession.clearCache();
if (routeFailure && this.test) {
if (!this.test.isFailed()) {
throw new Error('Failing this test due an unhandled error in the respondOnce route handler, check the logs above for the actual error');
}
}
});
describe('HTTP basics', () => {
it('should be able to issue a basic GET request', async () => {
const serverUrl = await respondOnce.toSingleURL((request, response) => {
expect(request.method).to.equal('GET');
response.end();
});
const urlRequest = net.request(serverUrl);
const response = await getResponse(urlRequest);
expect(response.statusCode).to.equal(200);
await collectStreamBody(response);
});
it('should be able to issue a basic POST request', async () => {
const serverUrl = await respondOnce.toSingleURL((request, response) => {
expect(request.method).to.equal('POST');
response.end();
});
const urlRequest = net.request({
method: 'POST',
url: serverUrl
});
const response = await getResponse(urlRequest);
expect(response.statusCode).to.equal(200);
await collectStreamBody(response);
});
it('should fetch correct data in a GET request', async () => {
const expectedBodyData = 'Hello World!';
const serverUrl = await respondOnce.toSingleURL((request, response) => {
expect(request.method).to.equal('GET');
response.end(expectedBodyData);
});
const urlRequest = net.request(serverUrl);
const response = await getResponse(urlRequest);
expect(response.statusCode).to.equal(200);
const body = await collectStreamBody(response);
expect(body).to.equal(expectedBodyData);
});
it('should post the correct data in a POST request', async () => {
const bodyData = 'Hello World!';
let postedBodyData: string = '';
const serverUrl = await respondOnce.toSingleURL(async (request, response) => {
postedBodyData = await collectStreamBody(request);
response.end();
});
const urlRequest = net.request({
method: 'POST',
url: serverUrl
});
urlRequest.write(bodyData);
const response = await getResponse(urlRequest);
expect(response.statusCode).to.equal(200);
expect(postedBodyData).to.equal(bodyData);
});
it('a 307 redirected POST request preserves the body', async () => {
const bodyData = 'Hello World!';
let postedBodyData: string = '';
let methodAfterRedirect: string | undefined;
const serverUrl = await respondNTimes.toRoutes({
'/redirect': (req, res) => {
res.statusCode = 307;
res.setHeader('location', serverUrl);
return res.end();
},
'/': async (req, res) => {
methodAfterRedirect = req.method;
postedBodyData = await collectStreamBody(req);
res.end();
}
}, 2);
const urlRequest = net.request({
method: 'POST',
url: serverUrl + '/redirect'
});
urlRequest.write(bodyData);
const response = await getResponse(urlRequest);
expect(response.statusCode).to.equal(200);
await collectStreamBody(response);
expect(methodAfterRedirect).to.equal('POST');
expect(postedBodyData).to.equal(bodyData);
});
it('a 302 redirected POST request DOES NOT preserve the body', async () => {
const bodyData = 'Hello World!';
let postedBodyData: string = '';
let methodAfterRedirect: string | undefined;
const serverUrl = await respondNTimes.toRoutes({
'/redirect': (req, res) => {
res.statusCode = 302;
res.setHeader('location', serverUrl);
return res.end();
},
'/': async (req, res) => {
methodAfterRedirect = req.method;
postedBodyData = await collectStreamBody(req);
res.end();
}
}, 2);
const urlRequest = net.request({
method: 'POST',
url: serverUrl + '/redirect'
});
urlRequest.write(bodyData);
const response = await getResponse(urlRequest);
expect(response.statusCode).to.equal(200);
await collectStreamBody(response);
expect(methodAfterRedirect).to.equal('GET');
expect(postedBodyData).to.equal('');
});
it('should support chunked encoding', async () => {
let receivedRequest: http.IncomingMessage = null as any;
const serverUrl = await respondOnce.toSingleURL((request, response) => {
response.statusCode = 200;
response.statusMessage = 'OK';
response.chunkedEncoding = true;
receivedRequest = request;
request.on('data', (chunk: Buffer) => {
response.write(chunk);
});
request.on('end', (chunk: Buffer) => {
response.end(chunk);
});
});
const urlRequest = net.request({
method: 'POST',
url: serverUrl
});
let chunkIndex = 0;
const chunkCount = 100;
let sent = Buffer.alloc(0);
urlRequest.chunkedEncoding = true;
while (chunkIndex < chunkCount) {
chunkIndex += 1;
const chunk = randomBuffer(kOneKiloByte);
sent = Buffer.concat([sent, chunk]);
urlRequest.write(chunk);
}
const response = await getResponse(urlRequest);
expect(receivedRequest.method).to.equal('POST');
expect(receivedRequest.headers['transfer-encoding']).to.equal('chunked');
expect(receivedRequest.headers['content-length']).to.equal(undefined);
expect(response.statusCode).to.equal(200);
const received = await collectStreamBodyBuffer(response);
expect(sent.equals(received)).to.be.true();
expect(chunkIndex).to.be.equal(chunkCount);
});
for (const extraOptions of [{}, { credentials: 'include' }, { useSessionCookies: false, credentials: 'include' }] as ClientRequestConstructorOptions[]) {
describe(`authentication when ${JSON.stringify(extraOptions)}`, () => {
it('should emit the login event when 401', async () => {
const [user, pass] = ['user', 'pass'];
const serverUrl = await respondOnce.toSingleURL((request, response) => {
if (!request.headers.authorization) {
return response.writeHead(401, { 'WWW-Authenticate': 'Basic realm="Foo"' }).end();
}
response.writeHead(200).end('ok');
});
let loginAuthInfo: Electron.AuthInfo;
const request = net.request({ method: 'GET', url: serverUrl, ...extraOptions });
request.on('login', (authInfo, cb) => {
loginAuthInfo = authInfo;
cb(user, pass);
});
const response = await getResponse(request);
expect(response.statusCode).to.equal(200);
expect(loginAuthInfo!.realm).to.equal('Foo');
expect(loginAuthInfo!.scheme).to.equal('basic');
});
it('should receive 401 response when cancelling authentication', async () => {
const serverUrl = await respondOnce.toSingleURL((request, response) => {
if (!request.headers.authorization) {
response.writeHead(401, { 'WWW-Authenticate': 'Basic realm="Foo"' });
response.end('unauthenticated');
} else {
response.writeHead(200).end('ok');
}
});
const request = net.request({ method: 'GET', url: serverUrl, ...extraOptions });
request.on('login', (authInfo, cb) => {
cb();
});
const response = await getResponse(request);
const body = await collectStreamBody(response);
expect(response.statusCode).to.equal(401);
expect(body).to.equal('unauthenticated');
});
it('should share credentials with WebContents', async () => {
const [user, pass] = ['user', 'pass'];
const serverUrl = await respondNTimes.toSingleURL((request, response) => {
if (!request.headers.authorization) {
return response.writeHead(401, { 'WWW-Authenticate': 'Basic realm="Foo"' }).end();
}
return response.writeHead(200).end('ok');
}, 2);
const bw = new BrowserWindow({ show: false });
bw.webContents.on('login', (event, details, authInfo, cb) => {
event.preventDefault();
cb(user, pass);
});
await bw.loadURL(serverUrl);
bw.close();
const request = net.request({ method: 'GET', url: serverUrl, ...extraOptions });
let logInCount = 0;
request.on('login', () => {
logInCount++;
});
const response = await getResponse(request);
await collectStreamBody(response);
expect(logInCount).to.equal(0, 'should not receive a login event, credentials should be cached');
});
it('should share proxy credentials with WebContents', async () => {
const [user, pass] = ['user', 'pass'];
const proxyUrl = await respondNTimes((request, response) => {
if (!request.headers['proxy-authorization']) {
return response.writeHead(407, { 'Proxy-Authenticate': 'Basic realm="Foo"' }).end();
}
return response.writeHead(200).end('ok');
}, 2);
const customSession = session.fromPartition(`net-proxy-test-${Math.random()}`);
await customSession.setProxy({ proxyRules: proxyUrl.replace('http://', ''), proxyBypassRules: '<-loopback>' });
const bw = new BrowserWindow({ show: false, webPreferences: { session: customSession } });
bw.webContents.on('login', (event, details, authInfo, cb) => {
event.preventDefault();
cb(user, pass);
});
await bw.loadURL('http://127.0.0.1:9999');
bw.close();
const request = net.request({ method: 'GET', url: 'http://127.0.0.1:9999', session: customSession, ...extraOptions });
let logInCount = 0;
request.on('login', () => {
logInCount++;
});
const response = await getResponse(request);
const body = await collectStreamBody(response);
expect(response.statusCode).to.equal(200);
expect(body).to.equal('ok');
expect(logInCount).to.equal(0, 'should not receive a login event, credentials should be cached');
});
it('should upload body when 401', async () => {
const [user, pass] = ['user', 'pass'];
const serverUrl = await respondOnce.toSingleURL((request, response) => {
if (!request.headers.authorization) {
return response.writeHead(401, { 'WWW-Authenticate': 'Basic realm="Foo"' }).end();
}
response.writeHead(200);
request.on('data', (chunk) => response.write(chunk));
request.on('end', () => response.end());
});
const requestData = randomString(kOneKiloByte);
const request = net.request({ method: 'GET', url: serverUrl, ...extraOptions });
request.on('login', (authInfo, cb) => {
cb(user, pass);
});
request.write(requestData);
const response = await getResponse(request);
const responseData = await collectStreamBody(response);
expect(responseData).to.equal(requestData);
});
});
}
describe('authentication when {"credentials":"omit"}', () => {
it('should not emit the login event when 401', async () => {
const serverUrl = await respondOnce.toSingleURL((request, response) => {
if (!request.headers.authorization) {
return response.writeHead(401, { 'WWW-Authenticate': 'Basic realm="Foo"' }).end();
}
response.writeHead(200).end('ok');
});
const request = net.request({ method: 'GET', url: serverUrl, credentials: 'omit' });
request.on('login', () => {
expect.fail('unexpected login event');
});
const response = await getResponse(request);
expect(response.statusCode).to.equal(401);
expect(response.headers['www-authenticate']).to.equal('Basic realm="Foo"');
});
it('should not share credentials with WebContents', async () => {
const [user, pass] = ['user', 'pass'];
const serverUrl = await respondNTimes.toSingleURL((request, response) => {
if (!request.headers.authorization) {
return response.writeHead(401, { 'WWW-Authenticate': 'Basic realm="Foo"' }).end();
}
return response.writeHead(200).end('ok');
}, 2);
const bw = new BrowserWindow({ show: false });
bw.webContents.on('login', (event, details, authInfo, cb) => {
event.preventDefault();
cb(user, pass);
});
await bw.loadURL(serverUrl);
bw.close();
const request = net.request({ method: 'GET', url: serverUrl, credentials: 'omit' });
request.on('login', () => {
expect.fail();
});
const response = await getResponse(request);
expect(response.statusCode).to.equal(401);
expect(response.headers['www-authenticate']).to.equal('Basic realm="Foo"');
});
it('should share proxy credentials with WebContents', async () => {
const [user, pass] = ['user', 'pass'];
const proxyUrl = await respondNTimes((request, response) => {
if (!request.headers['proxy-authorization']) {
return response.writeHead(407, { 'Proxy-Authenticate': 'Basic realm="Foo"' }).end();
}
return response.writeHead(200).end('ok');
}, 2);
const customSession = session.fromPartition(`net-proxy-test-${Math.random()}`);
await customSession.setProxy({ proxyRules: proxyUrl.replace('http://', ''), proxyBypassRules: '<-loopback>' });
const bw = new BrowserWindow({ show: false, webPreferences: { session: customSession } });
bw.webContents.on('login', (event, details, authInfo, cb) => {
event.preventDefault();
cb(user, pass);
});
await bw.loadURL('http://127.0.0.1:9999');
bw.close();
const request = net.request({ method: 'GET', url: 'http://127.0.0.1:9999', session: customSession, credentials: 'omit' });
request.on('login', () => {
expect.fail();
});
const response = await getResponse(request);
const body = await collectStreamBody(response);
expect(response.statusCode).to.equal(200);
expect(body).to.equal('ok');
});
});
});
describe('ClientRequest API', () => {
it('request/response objects should emit expected events', async () => {
const bodyData = randomString(kOneKiloByte);
const serverUrl = await respondOnce.toSingleURL((request, response) => {
response.end(bodyData);
});
const urlRequest = net.request(serverUrl);
// request close event
const closePromise = once(urlRequest, 'close');
// request finish event
const finishPromise = once(urlRequest, 'close');
// request "response" event
const response = await getResponse(urlRequest);
response.on('error', (error: Error) => {
expect(error).to.be.an('Error');
});
const statusCode = response.statusCode;
expect(statusCode).to.equal(200);
// response data event
// respond end event
const body = await collectStreamBody(response);
expect(body).to.equal(bodyData);
urlRequest.on('error', (error) => {
expect(error).to.be.an('Error');
});
await Promise.all([closePromise, finishPromise]);
});
it('should be able to set a custom HTTP request header before first write', async () => {
const customHeaderName = 'Some-Custom-Header-Name';
const customHeaderValue = 'Some-Customer-Header-Value';
const serverUrl = await respondOnce.toSingleURL((request, response) => {
expect(request.headers[customHeaderName.toLowerCase()]).to.equal(customHeaderValue);
response.statusCode = 200;
response.statusMessage = 'OK';
response.end();
});
const urlRequest = net.request(serverUrl);
urlRequest.setHeader(customHeaderName, customHeaderValue);
expect(urlRequest.getHeader(customHeaderName)).to.equal(customHeaderValue);
expect(urlRequest.getHeader(customHeaderName.toLowerCase())).to.equal(customHeaderValue);
urlRequest.write('');
expect(urlRequest.getHeader(customHeaderName)).to.equal(customHeaderValue);
expect(urlRequest.getHeader(customHeaderName.toLowerCase())).to.equal(customHeaderValue);
const response = await getResponse(urlRequest);
expect(response.statusCode).to.equal(200);
await collectStreamBody(response);
});
it('should be able to set a non-string object as a header value', async () => {
const customHeaderName = 'Some-Integer-Value';
const customHeaderValue = 900;
const serverUrl = await respondOnce.toSingleURL((request, response) => {
expect(request.headers[customHeaderName.toLowerCase()]).to.equal(customHeaderValue.toString());
response.statusCode = 200;
response.statusMessage = 'OK';
response.end();
});
const urlRequest = net.request(serverUrl);
urlRequest.setHeader(customHeaderName, customHeaderValue as any);
expect(urlRequest.getHeader(customHeaderName)).to.equal(customHeaderValue);
expect(urlRequest.getHeader(customHeaderName.toLowerCase())).to.equal(customHeaderValue);
urlRequest.write('');
expect(urlRequest.getHeader(customHeaderName)).to.equal(customHeaderValue);
expect(urlRequest.getHeader(customHeaderName.toLowerCase())).to.equal(customHeaderValue);
const response = await getResponse(urlRequest);
expect(response.statusCode).to.equal(200);
await collectStreamBody(response);
});
it('should not change the case of header name', async () => {
const customHeaderName = 'X-Header-Name';
const customHeaderValue = 'value';
const serverUrl = await respondOnce.toSingleURL((request, response) => {
expect(request.headers[customHeaderName.toLowerCase()]).to.equal(customHeaderValue.toString());
expect(request.rawHeaders.includes(customHeaderName)).to.equal(true);
response.statusCode = 200;
response.statusMessage = 'OK';
response.end();
});
const urlRequest = net.request(serverUrl);
urlRequest.setHeader(customHeaderName, customHeaderValue);
expect(urlRequest.getHeader(customHeaderName)).to.equal(customHeaderValue);
urlRequest.write('');
const response = await getResponse(urlRequest);
expect(response.statusCode).to.equal(200);
await collectStreamBody(response);
});
it('should not be able to set a custom HTTP request header after first write', async () => {
const customHeaderName = 'Some-Custom-Header-Name';
const customHeaderValue = 'Some-Customer-Header-Value';
const serverUrl = await respondOnce.toSingleURL((request, response) => {
expect(request.headers[customHeaderName.toLowerCase()]).to.equal(undefined);
response.statusCode = 200;
response.statusMessage = 'OK';
response.end();
});
const urlRequest = net.request(serverUrl);
urlRequest.write('');
expect(() => {
urlRequest.setHeader(customHeaderName, customHeaderValue);
}).to.throw();
expect(urlRequest.getHeader(customHeaderName)).to.equal(undefined);
const response = await getResponse(urlRequest);
expect(response.statusCode).to.equal(200);
await collectStreamBody(response);
});
it('should be able to remove a custom HTTP request header before first write', async () => {
const customHeaderName = 'Some-Custom-Header-Name';
const customHeaderValue = 'Some-Customer-Header-Value';
const serverUrl = await respondOnce.toSingleURL((request, response) => {
expect(request.headers[customHeaderName.toLowerCase()]).to.equal(undefined);
response.statusCode = 200;
response.statusMessage = 'OK';
response.end();
});
const urlRequest = net.request(serverUrl);
urlRequest.setHeader(customHeaderName, customHeaderValue);
expect(urlRequest.getHeader(customHeaderName)).to.equal(customHeaderValue);
urlRequest.removeHeader(customHeaderName);
expect(urlRequest.getHeader(customHeaderName)).to.equal(undefined);
urlRequest.write('');
const response = await getResponse(urlRequest);
expect(response.statusCode).to.equal(200);
await collectStreamBody(response);
});
it('should not be able to remove a custom HTTP request header after first write', async () => {
const customHeaderName = 'Some-Custom-Header-Name';
const customHeaderValue = 'Some-Customer-Header-Value';
const serverUrl = await respondOnce.toSingleURL((request, response) => {
expect(request.headers[customHeaderName.toLowerCase()]).to.equal(customHeaderValue);
response.statusCode = 200;
response.statusMessage = 'OK';
response.end();
});
const urlRequest = net.request(serverUrl);
urlRequest.setHeader(customHeaderName, customHeaderValue);
expect(urlRequest.getHeader(customHeaderName)).to.equal(customHeaderValue);
urlRequest.write('');
expect(() => {
urlRequest.removeHeader(customHeaderName);
}).to.throw();
expect(urlRequest.getHeader(customHeaderName)).to.equal(customHeaderValue);
const response = await getResponse(urlRequest);
expect(response.statusCode).to.equal(200);
await collectStreamBody(response);
});
it('should keep the order of headers', async () => {
const customHeaderNameA = 'X-Header-100';
const customHeaderNameB = 'X-Header-200';
const serverUrl = await respondOnce.toSingleURL((request, response) => {
const headerNames = Array.from(Object.keys(request.headers));
const headerAIndex = headerNames.indexOf(customHeaderNameA.toLowerCase());
const headerBIndex = headerNames.indexOf(customHeaderNameB.toLowerCase());
expect(headerBIndex).to.be.below(headerAIndex);
response.statusCode = 200;
response.statusMessage = 'OK';
response.end();
});
const urlRequest = net.request(serverUrl);
urlRequest.setHeader(customHeaderNameB, 'b');
urlRequest.setHeader(customHeaderNameA, 'a');
const response = await getResponse(urlRequest);
expect(response.statusCode).to.equal(200);
await collectStreamBody(response);
});
it('should be able to set cookie header line', async () => {
const cookieHeaderName = 'Cookie';
const cookieHeaderValue = 'test=12345';
const customSession = session.fromPartition(`test-cookie-header-${Math.random()}`);
const serverUrl = await respondOnce.toSingleURL((request, response) => {
expect(request.headers[cookieHeaderName.toLowerCase()]).to.equal(cookieHeaderValue);
response.statusCode = 200;
response.statusMessage = 'OK';
response.end();
});
await customSession.cookies.set({
url: `${serverUrl}`,
name: 'test',
value: '11111',
expirationDate: 0
});
const urlRequest = net.request({
method: 'GET',
url: serverUrl,
session: customSession
});
urlRequest.setHeader(cookieHeaderName, cookieHeaderValue);
expect(urlRequest.getHeader(cookieHeaderName)).to.equal(cookieHeaderValue);
const response = await getResponse(urlRequest);
expect(response.statusCode).to.equal(200);
await collectStreamBody(response);
});
it('should be able to receive cookies', async () => {
const cookie = ['cookie1', 'cookie2'];
const serverUrl = await respondOnce.toSingleURL((request, response) => {
response.statusCode = 200;
response.statusMessage = 'OK';
response.setHeader('set-cookie', cookie);
response.end();
});
const urlRequest = net.request(serverUrl);
const response = await getResponse(urlRequest);
expect(response.headers['set-cookie']).to.have.same.members(cookie);
});
it('should be able to receive content-type', async () => {
const contentType = 'mime/test; charset=test';
const serverUrl = await respondOnce.toSingleURL((request, response) => {
response.statusCode = 200;
response.statusMessage = 'OK';
response.setHeader('content-type', contentType);
response.end();
});
const urlRequest = net.request(serverUrl);
const response = await getResponse(urlRequest);
expect(response.headers['content-type']).to.equal(contentType);
});
it('should not use the sessions cookie store by default', async () => {
const serverUrl = await respondOnce.toSingleURL((request, response) => {
response.statusCode = 200;
response.statusMessage = 'OK';
response.setHeader('x-cookie', `${request.headers.cookie!}`);
response.end();
});
const sess = session.fromPartition(`cookie-tests-${Math.random()}`);
const cookieVal = `${Date.now()}`;
await sess.cookies.set({
url: serverUrl,
name: 'wild_cookie',
value: cookieVal
});
const urlRequest = net.request({
url: serverUrl,
session: sess
});
const response = await getResponse(urlRequest);
expect(response.headers['x-cookie']).to.equal('undefined');
});
for (const extraOptions of [{ useSessionCookies: true }, { credentials: 'include' }] as ClientRequestConstructorOptions[]) {
describe(`when ${JSON.stringify(extraOptions)}`, () => {
it('should be able to use the sessions cookie store', async () => {
const serverUrl = await respondOnce.toSingleURL((request, response) => {
response.statusCode = 200;
response.statusMessage = 'OK';
response.setHeader('x-cookie', request.headers.cookie!);
response.end();
});
const sess = session.fromPartition(`cookie-tests-${Math.random()}`);
const cookieVal = `${Date.now()}`;
await sess.cookies.set({
url: serverUrl,
name: 'wild_cookie',
value: cookieVal
});
const urlRequest = net.request({
url: serverUrl,
session: sess,
...extraOptions
});
const response = await getResponse(urlRequest);
expect(response.headers['x-cookie']).to.equal(`wild_cookie=${cookieVal}`);
});
it('should be able to use the sessions cookie store with set-cookie', async () => {
const serverUrl = await respondOnce.toSingleURL((request, response) => {
response.statusCode = 200;
response.statusMessage = 'OK';
response.setHeader('set-cookie', 'foo=bar');
response.end();
});
const sess = session.fromPartition(`cookie-tests-${Math.random()}`);
let cookies = await sess.cookies.get({});
expect(cookies).to.have.lengthOf(0);
const urlRequest = net.request({
url: serverUrl,
session: sess,
...extraOptions
});
await collectStreamBody(await getResponse(urlRequest));
cookies = await sess.cookies.get({});
expect(cookies).to.have.lengthOf(1);
expect(cookies[0]).to.deep.equal({
name: 'foo',
value: 'bar',
domain: '127.0.0.1',
hostOnly: true,
path: '/',
secure: false,
httpOnly: false,
session: true,
sameSite: 'unspecified'
});
});
['Lax', 'Strict'].forEach((mode) => {
it(`should be able to use the sessions cookie store with same-site ${mode} cookies`, async () => {
const serverUrl = await respondNTimes.toSingleURL((request, response) => {
response.statusCode = 200;
response.statusMessage = 'OK';
response.setHeader('set-cookie', `same=site; SameSite=${mode}`);
response.setHeader('x-cookie', `${request.headers.cookie}`);
response.end();
}, 2);
const sess = session.fromPartition(`cookie-tests-${Math.random()}`);
let cookies = await sess.cookies.get({});
expect(cookies).to.have.lengthOf(0);
const urlRequest = net.request({
url: serverUrl,
session: sess,
...extraOptions
});
const response = await getResponse(urlRequest);
expect(response.headers['x-cookie']).to.equal('undefined');
await collectStreamBody(response);
cookies = await sess.cookies.get({});
expect(cookies).to.have.lengthOf(1);
expect(cookies[0]).to.deep.equal({
name: 'same',
value: 'site',
domain: '127.0.0.1',
hostOnly: true,
path: '/',
secure: false,
httpOnly: false,
session: true,
sameSite: mode.toLowerCase()
});
const urlRequest2 = net.request({
url: serverUrl,
session: sess,
...extraOptions
});
const response2 = await getResponse(urlRequest2);
expect(response2.headers['x-cookie']).to.equal('same=site');
});
});
it('should be able to use the sessions cookie store safely across redirects', async () => {
const serverUrl = await respondOnce.toSingleURL(async (request, response) => {
response.statusCode = 302;
response.statusMessage = 'Moved';
const newUrl = await respondOnce.toSingleURL((req, res) => {
res.statusCode = 200;
res.statusMessage = 'OK';
res.setHeader('x-cookie', req.headers.cookie!);
res.end();
});
response.setHeader('x-cookie', request.headers.cookie!);
response.setHeader('location', newUrl.replace('127.0.0.1', 'localhost'));
response.end();
});
const sess = session.fromPartition(`cookie-tests-${Math.random()}`);
const cookie127Val = `${Date.now()}-127`;
const cookieLocalVal = `${Date.now()}-local`;
const localhostUrl = serverUrl.replace('127.0.0.1', 'localhost');
expect(localhostUrl).to.not.equal(serverUrl);
// cookies with lax or strict same-site settings will not
// persist after redirects. no_restriction must be used
await Promise.all([
sess.cookies.set({
url: serverUrl,
name: 'wild_cookie',
sameSite: 'no_restriction',
value: cookie127Val
}), sess.cookies.set({
url: localhostUrl,
name: 'wild_cookie',
sameSite: 'no_restriction',
value: cookieLocalVal
})
]);
const urlRequest = net.request({
url: serverUrl,
session: sess,
...extraOptions
});
urlRequest.on('redirect', (status, method, url, headers) => {
// The initial redirect response should have received the 127 value here
expect(headers['x-cookie'][0]).to.equal(`wild_cookie=${cookie127Val}`);
urlRequest.followRedirect();
});
const response = await getResponse(urlRequest);
// We expect the server to have received the localhost value here
// The original request was to a 127.0.0.1 URL
// That request would have the cookie127Val cookie attached
// The request is then redirect to a localhost URL (different site)
// Because we are using the session cookie store it should do the safe / secure thing
// and attach the cookies for the new target domain
expect(response.headers['x-cookie']).to.equal(`wild_cookie=${cookieLocalVal}`);
});
});
}
it('should be able correctly filter out cookies that are secure', async () => {
const sess = session.fromPartition(`cookie-tests-${Math.random()}`);
await Promise.all([
sess.cookies.set({
url: 'https://electronjs.org',
domain: 'electronjs.org',
name: 'cookie1',
value: '1',
secure: true
}),
sess.cookies.set({
url: 'https://electronjs.org',
domain: 'electronjs.org',
name: 'cookie2',
value: '2',
secure: false
})
]);
const secureCookies = await sess.cookies.get({
secure: true
});
expect(secureCookies).to.have.lengthOf(1);
expect(secureCookies[0].name).to.equal('cookie1');
const cookies = await sess.cookies.get({
secure: false
});
expect(cookies).to.have.lengthOf(1);
expect(cookies[0].name).to.equal('cookie2');
});
it('throws when an invalid domain is passed', async () => {
const sess = session.fromPartition(`cookie-tests-${Math.random()}`);
await expect(sess.cookies.set({
url: 'https://electronjs.org',
domain: 'wssss.iamabaddomain.fun',
name: 'cookie1'
})).to.eventually.be.rejectedWith(/Failed to set cookie with an invalid domain attribute/);
});
it('should be able correctly filter out cookies that are session', async () => {
const sess = session.fromPartition(`cookie-tests-${Math.random()}`);
await Promise.all([
sess.cookies.set({
url: 'https://electronjs.org',
domain: 'electronjs.org',
name: 'cookie1',
value: '1'
}),
sess.cookies.set({
url: 'https://electronjs.org',
domain: 'electronjs.org',
name: 'cookie2',
value: '2',
expirationDate: Math.round(Date.now() / 1000) + 10000
})
]);
const sessionCookies = await sess.cookies.get({
session: true
});
expect(sessionCookies).to.have.lengthOf(1);
expect(sessionCookies[0].name).to.equal('cookie1');
const cookies = await sess.cookies.get({
session: false
});
expect(cookies).to.have.lengthOf(1);
expect(cookies[0].name).to.equal('cookie2');
});
it('should be able correctly filter out cookies that are httpOnly', async () => {
const sess = session.fromPartition(`cookie-tests-${Math.random()}`);
await Promise.all([
sess.cookies.set({
url: 'https://electronjs.org',
domain: 'electronjs.org',
name: 'cookie1',
value: '1',
httpOnly: true
}),
sess.cookies.set({
url: 'https://electronjs.org',
domain: 'electronjs.org',
name: 'cookie2',
value: '2',
httpOnly: false
})
]);
const httpOnlyCookies = await sess.cookies.get({
httpOnly: true
});
expect(httpOnlyCookies).to.have.lengthOf(1);
expect(httpOnlyCookies[0].name).to.equal('cookie1');
const cookies = await sess.cookies.get({
httpOnly: false
});
expect(cookies).to.have.lengthOf(1);
expect(cookies[0].name).to.equal('cookie2');
});
describe('when {"credentials":"omit"}', () => {
it('should not send cookies');
it('should not store cookies');
});
it('should set sec-fetch-site to same-origin for request from same origin', async () => {
const serverUrl = await respondOnce.toSingleURL((request, response) => {
expect(request.headers['sec-fetch-site']).to.equal('same-origin');
response.statusCode = 200;
response.statusMessage = 'OK';
response.end();
});
const urlRequest = net.request({
url: serverUrl,
origin: serverUrl
});
await collectStreamBody(await getResponse(urlRequest));
});
it('should set sec-fetch-site to same-origin for request with the same origin header', async () => {