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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
|
// Copyright 2018-2021 the Deno authors. All rights reserved. MIT license.
import {
assert,
assertEquals,
assertNotEquals,
assertStrictEquals,
assertThrows,
assertThrowsAsync,
Deferred,
deferred,
unitTest,
} from "./test_util.ts";
import { BufReader, BufWriter } from "../../../test_util/std/io/bufio.ts";
import { readAll } from "../../../test_util/std/io/util.ts";
import { TextProtoReader } from "../../../test_util/std/textproto/mod.ts";
const encoder = new TextEncoder();
const decoder = new TextDecoder();
async function sleep(msec: number) {
await new Promise((res, _rej) => setTimeout(res, msec));
}
function unreachable(): never {
throw new Error("Unreachable code reached");
}
unitTest(async function connectTLSNoPerm() {
await assertThrowsAsync(async () => {
await Deno.connectTls({ hostname: "deno.land", port: 443 });
}, Deno.errors.PermissionDenied);
});
unitTest(
{ perms: { read: true, net: true } },
async function connectTLSInvalidHost() {
const listener = await Deno.listenTls({
hostname: "localhost",
port: 3567,
certFile: "cli/tests/testdata/tls/localhost.crt",
keyFile: "cli/tests/testdata/tls/localhost.key",
});
await assertThrowsAsync(async () => {
await Deno.connectTls({ hostname: "127.0.0.1", port: 3567 });
}, TypeError);
listener.close();
},
);
unitTest(async function connectTLSCertFileNoReadPerm() {
await assertThrowsAsync(async () => {
await Deno.connectTls({
hostname: "deno.land",
port: 443,
certFile: "cli/tests/testdata/tls/RootCA.crt",
});
}, Deno.errors.PermissionDenied);
});
unitTest(
{ perms: { read: true, net: true } },
function listenTLSNonExistentCertKeyFiles() {
const options = {
hostname: "localhost",
port: 3500,
certFile: "cli/tests/testdata/tls/localhost.crt",
keyFile: "cli/tests/testdata/tls/localhost.key",
};
assertThrows(() => {
Deno.listenTls({
...options,
certFile: "./non/existent/file",
});
}, Deno.errors.NotFound);
assertThrows(() => {
Deno.listenTls({
...options,
keyFile: "./non/existent/file",
});
}, Deno.errors.NotFound);
},
);
unitTest({ perms: { net: true } }, function listenTLSNoReadPerm() {
assertThrows(() => {
Deno.listenTls({
hostname: "localhost",
port: 3500,
certFile: "cli/tests/testdata/tls/localhost.crt",
keyFile: "cli/tests/testdata/tls/localhost.key",
});
}, Deno.errors.PermissionDenied);
});
unitTest(
{
perms: { read: true, write: true, net: true },
},
function listenTLSEmptyKeyFile() {
const options = {
hostname: "localhost",
port: 3500,
certFile: "cli/tests/testdata/tls/localhost.crt",
keyFile: "cli/tests/testdata/tls/localhost.key",
};
const testDir = Deno.makeTempDirSync();
const keyFilename = testDir + "/key.pem";
Deno.writeFileSync(keyFilename, new Uint8Array([]), {
mode: 0o666,
});
assertThrows(() => {
Deno.listenTls({
...options,
keyFile: keyFilename,
});
}, Error);
},
);
unitTest(
{ perms: { read: true, write: true, net: true } },
function listenTLSEmptyCertFile() {
const options = {
hostname: "localhost",
port: 3500,
certFile: "cli/tests/testdata/tls/localhost.crt",
keyFile: "cli/tests/testdata/tls/localhost.key",
};
const testDir = Deno.makeTempDirSync();
const certFilename = testDir + "/cert.crt";
Deno.writeFileSync(certFilename, new Uint8Array([]), {
mode: 0o666,
});
assertThrows(() => {
Deno.listenTls({
...options,
certFile: certFilename,
});
}, Error);
},
);
unitTest(
{ perms: { read: true, net: true } },
async function dialAndListenTLS() {
const resolvable = deferred();
const hostname = "localhost";
const port = 3500;
const listener = Deno.listenTls({
hostname,
port,
certFile: "cli/tests/testdata/tls/localhost.crt",
keyFile: "cli/tests/testdata/tls/localhost.key",
});
const response = encoder.encode(
"HTTP/1.1 200 OK\r\nContent-Length: 12\r\n\r\nHello World\n",
);
listener.accept().then(
async (conn) => {
assert(conn.remoteAddr != null);
assert(conn.localAddr != null);
await conn.write(response);
// TODO(bartlomieju): this might be a bug
setTimeout(() => {
conn.close();
resolvable.resolve();
}, 0);
},
);
const conn = await Deno.connectTls({
hostname,
port,
certFile: "cli/tests/testdata/tls/RootCA.pem",
});
assert(conn.rid > 0);
const w = new BufWriter(conn);
const r = new BufReader(conn);
const body = `GET / HTTP/1.1\r\nHost: ${hostname}:${port}\r\n\r\n`;
const writeResult = await w.write(encoder.encode(body));
assertEquals(body.length, writeResult);
await w.flush();
const tpr = new TextProtoReader(r);
const statusLine = await tpr.readLine();
assert(statusLine !== null, `line must be read: ${String(statusLine)}`);
const m = statusLine.match(/^(.+?) (.+?) (.+?)$/);
assert(m !== null, "must be matched");
const [_, proto, status, ok] = m;
assertEquals(proto, "HTTP/1.1");
assertEquals(status, "200");
assertEquals(ok, "OK");
const headers = await tpr.readMIMEHeader();
assert(headers !== null);
const contentLength = parseInt(headers.get("content-length")!);
const bodyBuf = new Uint8Array(contentLength);
await r.readFull(bodyBuf);
assertEquals(decoder.decode(bodyBuf), "Hello World\n");
conn.close();
listener.close();
await resolvable;
},
);
let nextPort = 3501;
function getPort() {
return nextPort++;
}
async function tlsPair(): Promise<[Deno.Conn, Deno.Conn]> {
const port = getPort();
const listener = Deno.listenTls({
hostname: "localhost",
port,
certFile: "cli/tests/testdata/tls/localhost.crt",
keyFile: "cli/tests/testdata/tls/localhost.key",
});
const acceptPromise = listener.accept();
const connectPromise = Deno.connectTls({
hostname: "localhost",
port,
certFile: "cli/tests/testdata/tls/RootCA.pem",
});
const endpoints = await Promise.all([acceptPromise, connectPromise]);
listener.close();
return endpoints;
}
async function sendThenCloseWriteThenReceive(
conn: Deno.Conn,
chunkCount: number,
chunkSize: number,
) {
const byteCount = chunkCount * chunkSize;
const buf = new Uint8Array(chunkSize); // Note: buf is size of _chunk_.
let n: number;
// Slowly send 42s.
buf.fill(42);
for (let remaining = byteCount; remaining > 0; remaining -= n) {
n = await conn.write(buf.subarray(0, remaining));
assert(n >= 1);
await sleep(10);
}
// Send EOF.
await conn.closeWrite();
// Receive 69s.
for (let remaining = byteCount; remaining > 0; remaining -= n) {
buf.fill(0);
n = await conn.read(buf) as number;
assert(n >= 1);
assertStrictEquals(buf[0], 69);
assertStrictEquals(buf[n - 1], 69);
}
conn.close();
}
async function receiveThenSend(
conn: Deno.Conn,
chunkCount: number,
chunkSize: number,
) {
const byteCount = chunkCount * chunkSize;
const buf = new Uint8Array(byteCount); // Note: buf size equals `byteCount`.
let n: number;
// Receive 42s.
for (let remaining = byteCount; remaining > 0; remaining -= n) {
buf.fill(0);
n = await conn.read(buf) as number;
assert(n >= 1);
assertStrictEquals(buf[0], 42);
assertStrictEquals(buf[n - 1], 42);
}
// Slowly send 69s.
buf.fill(69);
for (let remaining = byteCount; remaining > 0; remaining -= n) {
n = await conn.write(buf.subarray(0, remaining));
assert(n >= 1);
await sleep(10);
}
conn.close();
}
unitTest(
{ perms: { read: true, net: true } },
async function tlsServerStreamHalfCloseSendOneByte() {
const [serverConn, clientConn] = await tlsPair();
await Promise.all([
sendThenCloseWriteThenReceive(serverConn, 1, 1),
receiveThenSend(clientConn, 1, 1),
]);
},
);
unitTest(
{ perms: { read: true, net: true } },
async function tlsClientStreamHalfCloseSendOneByte() {
const [serverConn, clientConn] = await tlsPair();
await Promise.all([
sendThenCloseWriteThenReceive(clientConn, 1, 1),
receiveThenSend(serverConn, 1, 1),
]);
},
);
unitTest(
{ perms: { read: true, net: true } },
async function tlsServerStreamHalfCloseSendOneChunk() {
const [serverConn, clientConn] = await tlsPair();
await Promise.all([
sendThenCloseWriteThenReceive(serverConn, 1, 1 << 20 /* 1 MB */),
receiveThenSend(clientConn, 1, 1 << 20 /* 1 MB */),
]);
},
);
unitTest(
{ perms: { read: true, net: true } },
async function tlsClientStreamHalfCloseSendOneChunk() {
const [serverConn, clientConn] = await tlsPair();
await Promise.all([
sendThenCloseWriteThenReceive(clientConn, 1, 1 << 20 /* 1 MB */),
receiveThenSend(serverConn, 1, 1 << 20 /* 1 MB */),
]);
},
);
unitTest(
{ perms: { read: true, net: true } },
async function tlsServerStreamHalfCloseSendManyBytes() {
const [serverConn, clientConn] = await tlsPair();
await Promise.all([
sendThenCloseWriteThenReceive(serverConn, 100, 1),
receiveThenSend(clientConn, 100, 1),
]);
},
);
unitTest(
{ perms: { read: true, net: true } },
async function tlsClientStreamHalfCloseSendManyBytes() {
const [serverConn, clientConn] = await tlsPair();
await Promise.all([
sendThenCloseWriteThenReceive(clientConn, 100, 1),
receiveThenSend(serverConn, 100, 1),
]);
},
);
unitTest(
{ perms: { read: true, net: true } },
async function tlsServerStreamHalfCloseSendManyChunks() {
const [serverConn, clientConn] = await tlsPair();
await Promise.all([
sendThenCloseWriteThenReceive(serverConn, 100, 1 << 16 /* 64 kB */),
receiveThenSend(clientConn, 100, 1 << 16 /* 64 kB */),
]);
},
);
unitTest(
{ perms: { read: true, net: true } },
async function tlsClientStreamHalfCloseSendManyChunks() {
const [serverConn, clientConn] = await tlsPair();
await Promise.all([
sendThenCloseWriteThenReceive(clientConn, 100, 1 << 16 /* 64 kB */),
receiveThenSend(serverConn, 100, 1 << 16 /* 64 kB */),
]);
},
);
async function sendAlotReceiveNothing(conn: Deno.Conn) {
// Start receive op.
const readBuf = new Uint8Array(1024);
const readPromise = conn.read(readBuf);
// Send 1 MB of data.
const writeBuf = new Uint8Array(1 << 20 /* 1 MB */);
writeBuf.fill(42);
await conn.write(writeBuf);
// Send EOF.
await conn.closeWrite();
// Close the connection.
conn.close();
// Read op should be canceled.
await assertThrowsAsync(
async () => await readPromise,
Deno.errors.Interrupted,
);
}
async function receiveAlotSendNothing(conn: Deno.Conn) {
const readBuf = new Uint8Array(1024);
let n: number | null;
// Receive 1 MB of data.
for (let nread = 0; nread < 1 << 20 /* 1 MB */; nread += n!) {
n = await conn.read(readBuf);
assertStrictEquals(typeof n, "number");
assert(n! > 0);
assertStrictEquals(readBuf[0], 42);
}
// Close the connection, without sending anything at all.
conn.close();
}
unitTest(
{ perms: { read: true, net: true } },
async function tlsServerStreamCancelRead() {
const [serverConn, clientConn] = await tlsPair();
await Promise.all([
sendAlotReceiveNothing(serverConn),
receiveAlotSendNothing(clientConn),
]);
},
);
unitTest(
{ perms: { read: true, net: true } },
async function tlsClientStreamCancelRead() {
const [serverConn, clientConn] = await tlsPair();
await Promise.all([
sendAlotReceiveNothing(clientConn),
receiveAlotSendNothing(serverConn),
]);
},
);
async function sendReceiveEmptyBuf(conn: Deno.Conn) {
const byteBuf = new Uint8Array([1]);
const emptyBuf = new Uint8Array(0);
let n: number | null;
n = await conn.write(emptyBuf);
assertStrictEquals(n, 0);
n = await conn.read(emptyBuf);
assertStrictEquals(n, 0);
n = await conn.write(byteBuf);
assertStrictEquals(n, 1);
n = await conn.read(byteBuf);
assertStrictEquals(n, 1);
await conn.closeWrite();
n = await conn.write(emptyBuf);
assertStrictEquals(n, 0);
await assertThrowsAsync(async () => {
await conn.write(byteBuf);
}, Deno.errors.BrokenPipe);
n = await conn.write(emptyBuf);
assertStrictEquals(n, 0);
n = await conn.read(byteBuf);
assertStrictEquals(n, null);
conn.close();
}
unitTest(
{ perms: { read: true, net: true } },
async function tlsStreamSendReceiveEmptyBuf() {
const [serverConn, clientConn] = await tlsPair();
await Promise.all([
sendReceiveEmptyBuf(serverConn),
sendReceiveEmptyBuf(clientConn),
]);
},
);
function immediateClose(conn: Deno.Conn) {
conn.close();
return Promise.resolve();
}
async function closeWriteAndClose(conn: Deno.Conn) {
await conn.closeWrite();
if (await conn.read(new Uint8Array(1)) !== null) {
throw new Error("did not expect to receive data on TLS stream");
}
conn.close();
}
unitTest(
{ perms: { read: true, net: true } },
async function tlsServerStreamImmediateClose() {
const [serverConn, clientConn] = await tlsPair();
await Promise.all([
immediateClose(serverConn),
closeWriteAndClose(clientConn),
]);
},
);
unitTest(
{ perms: { read: true, net: true } },
async function tlsClientStreamImmediateClose() {
const [serverConn, clientConn] = await tlsPair();
await Promise.all([
closeWriteAndClose(serverConn),
immediateClose(clientConn),
]);
},
);
unitTest(
{ perms: { read: true, net: true } },
async function tlsClientAndServerStreamImmediateClose() {
const [serverConn, clientConn] = await tlsPair();
await Promise.all([
immediateClose(serverConn),
immediateClose(clientConn),
]);
},
);
async function tlsWithTcpFailureTestImpl(
phase: "handshake" | "traffic",
cipherByteCount: number,
failureMode: "corruption" | "shutdown",
reverse: boolean,
) {
const tlsPort = getPort();
const tlsListener = Deno.listenTls({
hostname: "localhost",
port: tlsPort,
certFile: "cli/tests/testdata/tls/localhost.crt",
keyFile: "cli/tests/testdata/tls/localhost.key",
});
const tcpPort = getPort();
const tcpListener = Deno.listen({ hostname: "localhost", port: tcpPort });
const [tlsServerConn, tcpServerConn] = await Promise.all([
tlsListener.accept(),
Deno.connect({ hostname: "localhost", port: tlsPort }),
]);
const [tcpClientConn, tlsClientConn] = await Promise.all([
tcpListener.accept(),
Deno.connectTls({
hostname: "localhost",
port: tcpPort,
certFile: "cli/tests/testdata/tls/RootCA.crt",
}),
]);
tlsListener.close();
tcpListener.close();
const {
tlsConn1,
tlsConn2,
tcpConn1,
tcpConn2,
} = reverse
? {
tlsConn1: tlsClientConn,
tlsConn2: tlsServerConn,
tcpConn1: tcpClientConn,
tcpConn2: tcpServerConn,
}
: {
tlsConn1: tlsServerConn,
tlsConn2: tlsClientConn,
tcpConn1: tcpServerConn,
tcpConn2: tcpClientConn,
};
const tcpForwardingInterruptPromise1 = deferred<void>();
const tcpForwardingPromise1 = forwardBytes(
tcpConn2,
tcpConn1,
cipherByteCount,
tcpForwardingInterruptPromise1,
);
const tcpForwardingInterruptPromise2 = deferred<void>();
const tcpForwardingPromise2 = forwardBytes(
tcpConn1,
tcpConn2,
Infinity,
tcpForwardingInterruptPromise2,
);
switch (phase) {
case "handshake": {
let expectedError;
switch (failureMode) {
case "corruption":
expectedError = Deno.errors.InvalidData;
break;
case "shutdown":
expectedError = Deno.errors.UnexpectedEof;
break;
default:
unreachable();
}
const tlsTrafficPromise1 = Promise.all([
assertThrowsAsync(
() => sendBytes(tlsConn1, 0x01, 1),
expectedError,
),
assertThrowsAsync(
() => receiveBytes(tlsConn1, 0x02, 1),
expectedError,
),
]);
const tlsTrafficPromise2 = Promise.all([
assertThrowsAsync(
() => sendBytes(tlsConn2, 0x02, 1),
Deno.errors.UnexpectedEof,
),
assertThrowsAsync(
() => receiveBytes(tlsConn2, 0x01, 1),
Deno.errors.UnexpectedEof,
),
]);
await tcpForwardingPromise1;
switch (failureMode) {
case "corruption":
await sendBytes(tcpConn1, 0xff, 1 << 14 /* 16 kB */);
break;
case "shutdown":
await tcpConn1.closeWrite();
break;
default:
unreachable();
}
await tlsTrafficPromise1;
tcpForwardingInterruptPromise2.resolve();
await tcpForwardingPromise2;
await tcpConn2.closeWrite();
await tlsTrafficPromise2;
break;
}
case "traffic": {
await Promise.all([
sendBytes(tlsConn2, 0x88, 8888),
receiveBytes(tlsConn1, 0x88, 8888),
sendBytes(tlsConn1, 0x99, 99999),
receiveBytes(tlsConn2, 0x99, 99999),
]);
tcpForwardingInterruptPromise1.resolve();
await tcpForwardingPromise1;
switch (failureMode) {
case "corruption":
await sendBytes(tcpConn1, 0xff, 1 << 14 /* 16 kB */);
await assertThrowsAsync(
() => receiveEof(tlsConn1),
Deno.errors.InvalidData,
);
tcpForwardingInterruptPromise2.resolve();
break;
case "shutdown":
// Receiving a TCP FIN packet without receiving a TLS CloseNotify
// alert is not the expected mode of operation, but it is not a
// problem either, so it should be treated as if the TLS session was
// gracefully closed.
await Promise.all([
tcpConn1.closeWrite(),
await receiveEof(tlsConn1),
await tlsConn1.closeWrite(),
await receiveEof(tlsConn2),
]);
break;
default:
unreachable();
}
await tcpForwardingPromise2;
break;
}
default:
unreachable();
}
tlsServerConn.close();
tlsClientConn.close();
tcpServerConn.close();
tcpClientConn.close();
async function sendBytes(
conn: Deno.Conn,
byte: number,
count: number,
) {
let buf = new Uint8Array(1 << 12 /* 4 kB */);
buf.fill(byte);
while (count > 0) {
buf = buf.subarray(0, Math.min(buf.length, count));
const nwritten = await conn.write(buf);
assertStrictEquals(nwritten, buf.length);
count -= nwritten;
}
}
async function receiveBytes(
conn: Deno.Conn,
byte: number,
count: number,
) {
let buf = new Uint8Array(1 << 12 /* 4 kB */);
while (count > 0) {
buf = buf.subarray(0, Math.min(buf.length, count));
const r = await conn.read(buf);
assertNotEquals(r, null);
assert(buf.subarray(0, r!).every((b) => b === byte));
count -= r!;
}
}
async function receiveEof(conn: Deno.Conn) {
const buf = new Uint8Array(1);
const r = await conn.read(buf);
assertStrictEquals(r, null);
}
async function forwardBytes(
source: Deno.Conn,
sink: Deno.Conn,
count: number,
interruptPromise: Deferred<void>,
) {
let buf = new Uint8Array(1 << 12 /* 4 kB */);
while (count > 0) {
buf = buf.subarray(0, Math.min(buf.length, count));
const nread = await Promise.race([source.read(buf), interruptPromise]);
if (nread == null) break; // Either EOF or interrupted.
const nwritten = await sink.write(buf.subarray(0, nread));
assertStrictEquals(nread, nwritten);
count -= nwritten;
}
}
}
unitTest(
{ perms: { read: true, net: true } },
async function tlsHandshakeWithTcpCorruptionImmediately() {
await tlsWithTcpFailureTestImpl("handshake", 0, "corruption", false);
await tlsWithTcpFailureTestImpl("handshake", 0, "corruption", true);
},
);
unitTest(
{ perms: { read: true, net: true } },
async function tlsHandshakeWithTcpShutdownImmediately() {
await tlsWithTcpFailureTestImpl("handshake", 0, "shutdown", false);
await tlsWithTcpFailureTestImpl("handshake", 0, "shutdown", true);
},
);
unitTest(
{ perms: { read: true, net: true } },
async function tlsHandshakeWithTcpCorruptionAfter70Bytes() {
await tlsWithTcpFailureTestImpl("handshake", 76, "corruption", false);
await tlsWithTcpFailureTestImpl("handshake", 78, "corruption", true);
},
);
unitTest(
{ perms: { read: true, net: true } },
async function tlsHandshakeWithTcpShutdownAfter70bytes() {
await tlsWithTcpFailureTestImpl("handshake", 77, "shutdown", false);
await tlsWithTcpFailureTestImpl("handshake", 79, "shutdown", true);
},
);
unitTest(
{ perms: { read: true, net: true } },
async function tlsHandshakeWithTcpCorruptionAfter200Bytes() {
await tlsWithTcpFailureTestImpl("handshake", 200, "corruption", false);
await tlsWithTcpFailureTestImpl("handshake", 202, "corruption", true);
},
);
unitTest(
{ perms: { read: true, net: true } },
async function tlsHandshakeWithTcpShutdownAfter200bytes() {
await tlsWithTcpFailureTestImpl("handshake", 201, "shutdown", false);
await tlsWithTcpFailureTestImpl("handshake", 203, "shutdown", true);
},
);
unitTest(
{ perms: { read: true, net: true } },
async function tlsTrafficWithTcpCorruption() {
await tlsWithTcpFailureTestImpl("traffic", Infinity, "corruption", false);
await tlsWithTcpFailureTestImpl("traffic", Infinity, "corruption", true);
},
);
unitTest(
{ perms: { read: true, net: true } },
async function tlsTrafficWithTcpShutdown() {
await tlsWithTcpFailureTestImpl("traffic", Infinity, "shutdown", false);
await tlsWithTcpFailureTestImpl("traffic", Infinity, "shutdown", true);
},
);
function createHttpsListener(port: number): Deno.Listener {
// Query format: `curl --insecure https://localhost:8443/z/12345`
// The server returns a response consisting of 12345 times the letter 'z'.
const listener = Deno.listenTls({
hostname: "localhost",
port,
certFile: "./cli/tests/testdata/tls/localhost.crt",
keyFile: "./cli/tests/testdata/tls/localhost.key",
});
serve(listener);
return listener;
async function serve(listener: Deno.Listener) {
for await (const conn of listener) {
const EOL = "\r\n";
// Read GET request plus headers.
const buf = new Uint8Array(1 << 12 /* 4 kB */);
const decoder = new TextDecoder();
let req = "";
while (!req.endsWith(EOL + EOL)) {
const n = await conn.read(buf);
if (n === null) throw new Error("Unexpected EOF");
req += decoder.decode(buf.subarray(0, n));
}
// Parse GET request.
const { filler, count, version } =
/^GET \/(?<filler>[^\/]+)\/(?<count>\d+) HTTP\/(?<version>1\.\d)\r\n/
.exec(req)!.groups as {
filler: string;
count: string;
version: string;
};
// Generate response.
const resBody = new TextEncoder().encode(filler.repeat(+count));
const resHead = new TextEncoder().encode(
[
`HTTP/${version} 200 OK`,
`Content-Length: ${resBody.length}`,
"Content-Type: text/plain",
].join(EOL) + EOL + EOL,
);
// Send response.
await conn.write(resHead);
await conn.write(resBody);
// Close TCP connection.
conn.close();
}
}
}
async function curl(url: string): Promise<string> {
const curl = Deno.run({
cmd: ["curl", "--insecure", url],
stdout: "piped",
});
try {
const [status, output] = await Promise.all([curl.status(), curl.output()]);
if (!status.success) {
throw new Error(`curl ${url} failed: ${status.code}`);
}
return new TextDecoder().decode(output);
} finally {
curl.close();
}
}
unitTest(
{ perms: { read: true, net: true, run: true } },
async function curlFakeHttpsServer() {
const port = getPort();
const listener = createHttpsListener(port);
const res1 = await curl(`https://localhost:${port}/d/1`);
assertStrictEquals(res1, "d");
const res2 = await curl(`https://localhost:${port}/e/12345`);
assertStrictEquals(res2, "e".repeat(12345));
const count3 = 1 << 17; // 128 kB.
const res3 = await curl(`https://localhost:${port}/n/${count3}`);
assertStrictEquals(res3, "n".repeat(count3));
const count4 = 12345678;
const res4 = await curl(`https://localhost:${port}/o/${count4}`);
assertStrictEquals(res4, "o".repeat(count4));
listener.close();
},
);
unitTest(
{ perms: { read: true, net: true } },
async function startTls() {
const hostname = "smtp.gmail.com";
const port = 587;
const encoder = new TextEncoder();
let conn = await Deno.connect({
hostname,
port,
});
let writer = new BufWriter(conn);
let reader = new TextProtoReader(new BufReader(conn));
let line: string | null = (await reader.readLine()) as string;
assert(line.startsWith("220"));
await writer.write(encoder.encode(`EHLO ${hostname}\r\n`));
await writer.flush();
while ((line = (await reader.readLine()) as string)) {
assert(line.startsWith("250"));
if (line.startsWith("250 ")) break;
}
await writer.write(encoder.encode("STARTTLS\r\n"));
await writer.flush();
line = await reader.readLine();
// Received the message that the server is ready to establish TLS
assertEquals(line, "220 2.0.0 Ready to start TLS");
conn = await Deno.startTls(conn, { hostname });
writer = new BufWriter(conn);
reader = new TextProtoReader(new BufReader(conn));
// After that use TLS communication again
await writer.write(encoder.encode(`EHLO ${hostname}\r\n`));
await writer.flush();
while ((line = (await reader.readLine()) as string)) {
assert(line.startsWith("250"));
if (line.startsWith("250 ")) break;
}
conn.close();
},
);
unitTest(
{ perms: { read: true, net: true } },
async function connectTLSBadClientCertPrivateKey(): Promise<void> {
await assertThrowsAsync(async () => {
await Deno.connectTls({
hostname: "deno.land",
port: 443,
certChain: "bad data",
privateKey: await Deno.readTextFile(
"cli/tests/testdata/tls/localhost.key",
),
});
}, Deno.errors.InvalidData);
},
);
unitTest(
{ perms: { read: true, net: true } },
async function connectTLSBadPrivateKey(): Promise<void> {
await assertThrowsAsync(async () => {
await Deno.connectTls({
hostname: "deno.land",
port: 443,
certChain: await Deno.readTextFile(
"cli/tests/testdata/tls/localhost.crt",
),
privateKey: "bad data",
});
}, Deno.errors.InvalidData);
},
);
unitTest(
{ perms: { read: true, net: true } },
async function connectTLSNotPrivateKey(): Promise<void> {
await assertThrowsAsync(async () => {
await Deno.connectTls({
hostname: "deno.land",
port: 443,
certChain: await Deno.readTextFile(
"cli/tests/testdata/tls/localhost.crt",
),
privateKey: "",
});
}, Deno.errors.InvalidData);
},
);
unitTest(
{ perms: { read: true, net: true } },
async function connectWithClientCert() {
// The test_server running on port 4552 responds with 'PASS' if client
// authentication was successful. Try it by running test_server and
// curl --key cli/tests/testdata/tls/localhost.key \
// --cert cli/tests/testdata/tls/localhost.crt \
// --cacert cli/tests/testdata/tls/RootCA.crt https://localhost:4552/
const conn = await Deno.connectTls({
hostname: "localhost",
port: 4552,
certChain: await Deno.readTextFile(
"cli/tests/testdata/tls/localhost.crt",
),
privateKey: await Deno.readTextFile(
"cli/tests/testdata/tls/localhost.key",
),
certFile: "cli/tests/testdata/tls/RootCA.crt",
});
const result = decoder.decode(await readAll(conn));
assertEquals(result, "PASS");
conn.close();
},
);
|