-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwebsocket_test.go
More file actions
1720 lines (1560 loc) · 54.6 KB
/
websocket_test.go
File metadata and controls
1720 lines (1560 loc) · 54.6 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
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
package websocket
import (
"bufio"
"bytes"
"context"
"encoding/binary"
"errors"
"fmt"
"io"
"log"
"net"
"net/http"
"net/http/httptest"
"os"
"slices"
"strings"
"sync"
"sync/atomic"
"testing"
"time"
"unicode/utf8"
"github.com/mccutchen/websocket/internal/testing/assert"
)
func TestHandshake(t *testing.T) {
testCases := map[string]struct {
reqHeaders map[string]string
wantStatus int
wantRespHeaders map[string]string
}{
"valid handshake": {
reqHeaders: map[string]string{
"Connection": "upgrade",
"Upgrade": "websocket",
"Sec-WebSocket-Key": "dGhlIHNhbXBsZSBub25jZQ==",
"Sec-WebSocket-Version": "13",
},
wantRespHeaders: map[string]string{
"Connection": "upgrade",
"Upgrade": "websocket",
"Sec-Websocket-Accept": "s3pPLMBiTxaQ9kYGzzhZRbK+xOo=",
},
wantStatus: http.StatusSwitchingProtocols,
},
"valid handshake, header values case insensitive": {
reqHeaders: map[string]string{
"Connection": "Upgrade",
"Upgrade": "WebSocket",
"Sec-WebSocket-Key": "dGhlIHNhbXBsZSBub25jZQ==",
"Sec-WebSocket-Version": "13",
},
wantRespHeaders: map[string]string{
"Connection": "upgrade",
"Upgrade": "websocket",
"Sec-Websocket-Accept": "s3pPLMBiTxaQ9kYGzzhZRbK+xOo=",
},
wantStatus: http.StatusSwitchingProtocols,
},
"missing Connection header is okay": {
reqHeaders: map[string]string{
"Upgrade": "websocket",
"Sec-WebSocket-Key": "dGhlIHNhbXBsZSBub25jZQ==",
"Sec-WebSocket-Version": "13",
},
wantStatus: http.StatusSwitchingProtocols,
},
"incorrect Connection header is also okay": {
reqHeaders: map[string]string{
"Connection": "foo",
"Upgrade": "websocket",
"Sec-WebSocket-Key": "dGhlIHNhbXBsZSBub25jZQ==",
"Sec-WebSocket-Version": "13",
},
wantStatus: http.StatusSwitchingProtocols,
},
"missing Upgrade header": {
reqHeaders: map[string]string{
"Connection": "Upgrade",
"Sec-WebSocket-Key": "dGhlIHNhbXBsZSBub25jZQ==",
"Sec-WebSocket-Version": "13",
},
wantStatus: http.StatusBadRequest,
},
"incorrect Upgrade header": {
reqHeaders: map[string]string{
"Connection": "Upgrade",
"Upgrade": "http/2",
"Sec-WebSocket-Key": "dGhlIHNhbXBsZSBub25jZQ==",
"Sec-WebSocket-Version": "13",
},
wantStatus: http.StatusBadRequest,
},
"missing version": {
reqHeaders: map[string]string{
"Connection": "upgrade",
"Upgrade": "websocket",
"Sec-WebSocket-Key": "dGhlIHNhbXBsZSBub25jZQ==",
},
wantStatus: http.StatusBadRequest,
},
"incorrect version": {
reqHeaders: map[string]string{
"Connection": "upgrade",
"Upgrade": "websocket",
"Sec-WebSocket-Key": "dGhlIHNhbXBsZSBub25jZQ==",
"Sec-WebSocket-Version": "12",
},
wantStatus: http.StatusBadRequest,
},
"missing Sec-WebSocket-Key": {
reqHeaders: map[string]string{
"Connection": "upgrade",
"Upgrade": "websocket",
"Sec-WebSocket-Version": "13",
},
wantStatus: http.StatusBadRequest,
},
}
for name, tc := range testCases {
t.Run(name, func(t *testing.T) {
t.Parallel()
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
_, err := Accept(w, r, Options{})
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
}))
defer srv.Close()
req, _ := http.NewRequest(http.MethodGet, srv.URL, nil)
for k, v := range tc.reqHeaders {
req.Header.Set(k, v)
}
resp, err := http.DefaultClient.Do(req)
assert.NilError(t, err)
defer func() { _ = resp.Body.Close() }()
assert.Equal(t, resp.StatusCode, tc.wantStatus, "incorrect status code")
for k, v := range tc.wantRespHeaders {
assert.Equal(t, resp.Header.Get(k), v, "incorrect value for %q response header", k)
}
})
}
// hijack failure cases w/ shared setup
{
handshakeReq := httptest.NewRequest(http.MethodGet, "/websocket/echo", nil)
for k, v := range map[string]string{
"Connection": "upgrade",
"Upgrade": "websocket",
"Sec-WebSocket-Key": "dGhlIHNhbXBsZSBub25jZQ==",
"Sec-WebSocket-Version": "13",
} {
handshakeReq.Header.Set(k, v)
}
t.Run("http.Hijack not implemented", func(t *testing.T) {
t.Parallel()
// confirm that httptest.ResponseRecorder does not implmeent
// http.Hjijacker
var w http.ResponseWriter = httptest.NewRecorder()
_, ok := w.(http.Hijacker)
assert.Equal(t, ok, false, "expected httptest.ResponseRecorder not to implement http.Hijacker")
_, err := Accept(w, handshakeReq, Options{})
assert.Error(t, err, "websocket: accept: hijack failed: server does not support hijacking")
})
t.Run("hijack failed", func(t *testing.T) {
t.Parallel()
_, err := Accept(&brokenHijackResponseWriter{}, handshakeReq, Options{})
assert.Error(t, err, "websocket: accept: hijack failed: error hijacking connection")
})
}
}
func TestConnectionLimits(t *testing.T) {
t.Run("server enforces read deadline", func(t *testing.T) {
t.Parallel()
// this test ensures that the server will close the connection if it
// gets a timeout while reading a message.
//
// because the server has a read timeout and the client never sends a
// message, the server's read loop will time out and it will start the
// closing handshake.
//
// at that point, the client should be able to read the close frame
// from the server, write its ACK, and then the connection should be
// closed.
maxDuration := 250 * time.Millisecond
clientServerTest{
// client never sends a message, just waits for the server to
// timeout and then completes the closing handshake
clientTest: func(t testing.TB, ws *Websocket) {
start := time.Now()
mustReadCloseFrame(t, ws.conn, StatusAbnormalClose, errors.New("error reading frame header"))
elapsed := time.Since(start)
assert.Equal(t, elapsed >= maxDuration, true, "not enough time passed")
assertConnClosed(t, ws.conn)
},
// server runs echo handler with read timeout, which should timeout
// after maxDuration and start closing handshake
serverOpts: Options{
ReadTimeout: maxDuration,
WriteTimeout: maxDuration,
Hooks: newTestHooks(t),
},
serverTest: func(t testing.TB, ws *Websocket) {
start := time.Now()
err := ws.Handle(t.Context(), EchoHandler)
elapsed := time.Since(start)
assert.Equal(t, elapsed >= maxDuration, true, "not enough time passed")
assert.Error(t, err, os.ErrDeadlineExceeded)
},
}.Run(t)
})
t.Run("client closing connection", func(t *testing.T) {
t.Parallel()
var (
clientTimeout = 250 * time.Millisecond
serverTimeout = time.Hour // should never be reached
)
clientServerTest{
// client closes its end of the connection, which should interrupt
// the server's blocking read and cause it to return.
clientTest: func(t testing.TB, ws *Websocket) {
time.Sleep(clientTimeout)
assert.NilError(t, ws.conn.Close())
},
// server tries to read, which should be interrupted by client
// closing connection
serverOpts: Options{
ReadTimeout: serverTimeout,
},
serverTest: func(t testing.TB, ws *Websocket) {
start := time.Now()
msg, err := ws.ReadMessage(t.Context())
elapsed := time.Since(start)
assert.Error(t, err, io.EOF)
assert.Equal(t, msg, nil, "msg should be nil on error")
assert.True(t, elapsed >= clientTimeout, "server should block until client timeout")
assert.Equal(t, elapsed <= serverTimeout, true, "server should not reach its own timeout")
},
}.Run(t)
})
}
func TestProtocolOkay(t *testing.T) {
t.Run("single frame round trip", func(t *testing.T) {
t.Parallel()
wantFrame := NewFrame(OpcodeText, true, []byte("hello"))
clientServerTest{
// client writes a single frame and ensures the server echoes the
// same frame back
clientTest: func(t testing.TB, ws *Websocket) {
mustWriteFrame(t, ws.conn, true, wantFrame)
gotFrame := mustReadFrame(t, ws.conn, len(wantFrame.Payload))
assert.Equal(t, gotFrame, wantFrame, "frames should match")
},
// server reads a single frame, ensures it matches the frame
// written by the client, and then echoes it back.
serverTest: func(t testing.TB, ws *Websocket) {
serverFrame := mustReadFrame(t, ws.conn, len(wantFrame.Payload))
assert.Equal(t, serverFrame, wantFrame, "frames should match")
mustWriteFrame(t, ws.conn, false, serverFrame)
},
}.Run(t)
})
t.Run("fragmented round trip", func(t *testing.T) {
t.Parallel()
var (
// msg size must be double frame size for this test case
maxFrameSize = 128
maxMessageSize = maxFrameSize * 2
wantMessage = &Message{
Payload: bytes.Repeat([]byte("X"), maxMessageSize),
}
)
clientServerTest{
// client manually writes a fragmented message and reads reply
// from server to ensure correct round trip
clientOpts: Options{
MaxFrameSize: maxFrameSize,
MaxMessageSize: maxMessageSize,
Hooks: newTestHooks(t),
},
clientTest: func(t testing.TB, ws *Websocket) {
// manually write fragmented message to ensure server reassembles
// correctly
mustWriteFrames(t, ws.conn, true, FrameMessage(wantMessage, maxFrameSize))
// read reply to verify round-trip
assert.Equal(t, mustReadMessage(t, ws), wantMessage, "incorect message received in reply from server")
},
// server reads entire message and ensures that it is reassembled
// correctly before echoing back to client
serverOpts: Options{
MaxFrameSize: maxFrameSize,
MaxMessageSize: maxMessageSize,
Hooks: newTestHooks(t),
},
serverTest: func(t testing.TB, ws *Websocket) {
msg := mustReadMessage(t, ws)
assert.Equal(t, msg, wantMessage, "incorrect messaage received from client")
assert.NilError(t, ws.WriteMessage(t.Context(), msg))
},
}.Run(t)
})
t.Run("utf8 handling okay", func(t *testing.T) {
t.Parallel()
clientServerTest{
// client sends a variety of valid utf8-encoded messages and
// ensures that the server echoes them correctly.
clientTest: func(t testing.TB, ws *Websocket) {
// valid UTF-8 accepted and echoed back
{
frame := NewFrame(OpcodeText, true, []byte("Iñtërnâtiônàlizætiøn"))
mustWriteFrame(t, ws.conn, true, frame)
msg := mustReadMessage(t, ws)
assert.Equal(t, msg.Payload, frame.Payload, "incorrect message payloady")
}
// valid UTF-8 fragmented on codepoint boundaries is okay
{
mustWriteFrames(t, ws.conn, true, []*Frame{
NewFrame(OpcodeText, false, []byte("Iñtër")),
NewFrame(OpcodeContinuation, false, []byte("nâtiônàl")),
NewFrame(OpcodeContinuation, true, []byte("izætiøn")),
})
msg := mustReadMessage(t, ws)
assert.Equal(t, msg.Payload, []byte("Iñtërnâtiônàlizætiøn"), "incorrect message payloady")
}
// valid UTF-8 fragmented in the middle of a codepoint is reassembled
// into a valid message
{
mustWriteFrames(t, ws.conn, true, []*Frame{
NewFrame(OpcodeText, false, []byte("jalape\xc3")),
NewFrame(OpcodeContinuation, true, []byte("\xb1o")),
})
msg := mustReadMessage(t, ws)
assert.Equal(t, msg.Payload, []byte("jalapeño"), "payload")
}
assert.NilError(t, ws.Close())
},
// server just runs EchoHandler to reply to client
serverTest: func(t testing.TB, ws *Websocket) {
assert.NilError(t, ws.Handle(t.Context(), EchoHandler))
},
}.Run(t)
})
t.Run("binary messages can be invalid UTF-8", func(t *testing.T) {
t.Parallel()
wantMessage := &Message{Binary: true, Payload: []byte{0xc3}}
assert.Equal(t, utf8.Valid(wantMessage.Payload), false, "test payload should not be valid utf8")
clientServerTest{
clientTest: func(t testing.TB, ws *Websocket) {
mustWriteFrames(t, ws.conn, true, FrameMessage(wantMessage, len(wantMessage.Payload)))
msg := mustReadMessage(t, ws)
assert.Equal(t, msg, wantMessage, "client received incorrect message in reply")
},
serverTest: func(t testing.TB, ws *Websocket) {
msg := mustReadMessage(t, ws)
assert.Equal(t, msg, wantMessage, "server received incorrect message")
assert.NilError(t, ws.WriteMessage(t.Context(), msg))
},
}.Run(t)
})
t.Run("jumbo frames okay", func(t *testing.T) {
t.Parallel()
// Ensure we're exercising extended payload length parsing, where
// payloads of length 65536 (64 KiB) or more must be encoded as 8
// bytes
jumboSize := 65536
clientServerTest{
clientOpts: Options{
MaxFrameSize: jumboSize,
MaxMessageSize: jumboSize,
Hooks: newTestHooks(t),
},
clientTest: func(t testing.TB, ws *Websocket) {
clientFrame := NewFrame(OpcodeText, true, bytes.Repeat([]byte("*"), jumboSize))
mustWriteFrame(t, ws.conn, true, clientFrame)
respFrame := mustReadFrame(t, ws.conn, jumboSize)
assert.Equal(t, respFrame.Payload, clientFrame.Payload, "payload")
},
serverOpts: Options{
MaxFrameSize: jumboSize,
MaxMessageSize: jumboSize,
Hooks: newTestHooks(t),
},
serverTest: func(t testing.TB, ws *Websocket) {
msg := mustReadMessage(t, ws)
assert.NilError(t, ws.WriteMessage(t.Context(), msg))
},
}.Run(t)
})
t.Run("ping frames handled between fragments", func(t *testing.T) {
t.Parallel()
clientServerTest{
// client writes a fragmented message with a ping control frame
// between fragments and ensures that the server handles the ping
// and then replies with the correct response.
clientTest: func(t testing.TB, ws *Websocket) {
mustWriteFrames(t, ws.conn, true, []*Frame{
NewFrame(OpcodeText, false, []byte("0")),
NewFrame(OpcodePing, true, nil),
NewFrame(OpcodeContinuation, true, []byte("1")),
})
// should get a pong control frame first, even though ping was sent
// as second frame
pongFrame := mustReadFrame(t, ws.conn, 125)
assert.Equal(t, pongFrame.Opcode(), OpcodePong, "opcode")
// then should get the echo'd message from the two fragments
msg := mustReadMessage(t, ws)
assert.Equal(t, msg.Payload, []byte("01"), "incorrect messaage payload")
assert.NilError(t, ws.Close())
},
// server just echoes messages from the client
serverTest: func(t testing.TB, ws *Websocket) {
assert.NilError(t, ws.Handle(t.Context(), EchoHandler))
},
}.Run(t)
})
t.Run("pong frames from client are ignored", func(t *testing.T) {
t.Parallel()
clientServerTest{
// client writes a pong control frame followed by a text frame and
// ensures that the server ignores the pong frame and echoes the
// text frame.
clientTest: func(t testing.TB, ws *Websocket) {
wantPayload := []byte("hi")
mustWriteFrames(t, ws.conn, true, []*Frame{
NewFrame(OpcodePong, true, nil),
NewFrame(OpcodeText, true, wantPayload),
})
respFrame := mustReadFrame(t, ws.conn, len(wantPayload))
assert.Equal(t, respFrame.Payload, wantPayload, "payload")
assert.NilError(t, ws.Close())
},
// server just echoes messages from the client
serverTest: func(t testing.TB, ws *Websocket) {
assert.NilError(t, ws.Handle(t.Context(), EchoHandler))
},
}.Run(t)
})
}
func TestProtocolErrors(t *testing.T) {
var (
maxFrameSize = 128
maxMessageSize = maxFrameSize * 2
)
newOpts := func(t *testing.T) Options {
return Options{
MaxFrameSize: maxFrameSize,
MaxMessageSize: maxMessageSize,
Hooks: newTestHooks(t),
}
}
testCases := map[string]struct {
frames []*Frame
wantCloseCode StatusCode
wantCloseReason error
// further customize behavior
unmasked bool
}{
"unexpected continuation frame": {
frames: []*Frame{
NewFrame(OpcodeContinuation, true, []byte("0")),
},
wantCloseCode: StatusProtocolError,
wantCloseReason: ErrContinuationUnexpected,
},
"max frame size": {
frames: []*Frame{
NewFrame(OpcodeText, true, bytes.Repeat([]byte("0"), maxFrameSize+1)),
},
wantCloseCode: StatusTooLarge,
wantCloseReason: ErrFrameTooLarge,
},
"max message size": {
// 3rd frame will exceed max message size
frames: []*Frame{
NewFrame(OpcodeText, false, bytes.Repeat([]byte("0"), maxFrameSize)),
NewFrame(OpcodeContinuation, false, bytes.Repeat([]byte("1"), maxFrameSize)),
NewFrame(OpcodeContinuation, true, []byte("2")),
},
wantCloseCode: StatusTooLarge,
wantCloseReason: ErrMessageTooLarge,
},
"server requires masked frames": {
frames: []*Frame{
NewFrame(OpcodeText, true, []byte("hello")),
},
unmasked: true,
wantCloseCode: StatusProtocolError,
wantCloseReason: ErrClientFrameUnmasked,
},
"server rejects RSV bits": {
frames: []*Frame{
NewFrame(OpcodeText, true, []byte("hello"), RSV1),
},
wantCloseCode: StatusProtocolError,
wantCloseReason: ErrRSVBitsUnsupported,
},
"control frames must not be fragmented": {
frames: []*Frame{
NewFrame(OpcodeClose, false, nil),
},
wantCloseCode: StatusProtocolError,
wantCloseReason: ErrControlFrameFragmented,
},
"control frames must be less than 125 bytes": {
frames: []*Frame{
NewFrame(OpcodeClose, true, bytes.Repeat([]byte("0"), 126)),
},
wantCloseCode: StatusProtocolError,
wantCloseReason: ErrControlFrameTooLarge,
},
"text messages must be valid utf8": {
frames: []*Frame{
NewFrame(OpcodeText, true, []byte{0xc3}),
},
wantCloseCode: StatusInvalidFramePayload,
wantCloseReason: ErrInvalidFramePayload,
},
"missing continuation frame": {
frames: []*Frame{
NewFrame(OpcodeText, false, bytes.Repeat([]byte("0"), maxFrameSize)),
NewFrame(OpcodeText, true, bytes.Repeat([]byte("1"), maxFrameSize)),
},
wantCloseCode: StatusProtocolError,
wantCloseReason: ErrContinuationExpected,
},
"unknown opcode": {
frames: []*Frame{
NewFrame(Opcode(255), true, nil),
},
wantCloseCode: StatusProtocolError,
wantCloseReason: ErrOpcodeUnknown,
},
}
for name, tc := range testCases {
t.Run(name, func(t *testing.T) {
t.Parallel()
clientServerTest{
// client writes erroneous our invalid frames, which should
// cause the server to send a close frame.
//
// for these protocol-level errors, the server closes the
// conection immediately after sending its close frame, not
// waiting for the client to reply.
clientTest: func(t testing.TB, ws *Websocket) {
mustWriteFrames(t, ws.conn, !tc.unmasked, tc.frames)
mustReadCloseFrame(t, ws.conn, tc.wantCloseCode, tc.wantCloseReason)
assertConnClosed(t, ws.conn)
},
// server just runs echo handler, which should process all
// protocol errors automatically
serverOpts: newOpts(t),
serverTest: func(t testing.TB, ws *Websocket) {
assert.Error(t, ws.Handle(t.Context(), EchoHandler), tc.wantCloseReason)
},
}.Run(t)
})
}
}
func TestCloseFrameValidation(t *testing.T) {
// construct a special close frame with an invalid utf8 reason outside of
// test table because it can't be defined inline in a struct literal
frameWithInvalidUTF8Reason := func() *Frame {
payload := make([]byte, 0, 3)
payload = binary.BigEndian.AppendUint16(payload, uint16(StatusNormalClosure))
payload = append(payload, 0xc3)
return NewFrame(OpcodeClose, true, payload)
}
testCases := map[string]struct {
frame *Frame
wantCode StatusCode
wantErr error
}{
"empty payload ok": {
frame: NewFrame(OpcodeClose, true, nil),
wantCode: StatusNormalClosure,
},
"one byte payload is illegal": {
frame: NewFrame(OpcodeClose, true, []byte("X")),
wantCode: StatusProtocolError,
wantErr: ErrClosePayloadInvalid,
},
"invalid close code (too low)": {
frame: NewCloseFrame(StatusCode(999), ""),
wantCode: StatusProtocolError,
wantErr: ErrCloseStatusInvalid,
},
"invalid close code (too high))": {
frame: NewCloseFrame(StatusCode(5001), ""),
wantCode: StatusProtocolError,
wantErr: ErrCloseStatusInvalid,
},
"reserved close code": {
frame: NewCloseFrame(StatusCode(1015), ""),
wantCode: StatusProtocolError,
wantErr: ErrCloseStatusReserved,
},
"invalid utf8 in close reason": {
frame: frameWithInvalidUTF8Reason(),
wantCode: StatusInvalidFramePayload,
wantErr: ErrInvalidFramePayload,
},
}
for name, tc := range testCases {
t.Run(name, func(t *testing.T) {
clientServerTest{
// client writes erroneous our invalid frames, which should
// cause the server to send a close frame.
//
// for these protocol-level errors, the server closes the
// conection immediately after sending its close frame, not
// waiting for the client to reply.
clientTest: func(t testing.TB, ws *Websocket) {
assert.NilError(t, WriteFrame(ws.conn, NewMaskingKey(), tc.frame))
mustReadCloseFrame(t, ws.conn, tc.wantCode, tc.wantErr)
},
// server just runs echo handler, which should process all
// protocol errors automatically
serverTest: func(t testing.TB, ws *Websocket) {
assert.Error(t, ws.Handle(t.Context(), EchoHandler), tc.wantErr)
},
}.Run(t)
})
}
}
func TestCloseHandshake(t *testing.T) {
t.Run("normal server-initiated closing handshake", func(t *testing.T) {
// this test ensures that calling Close() on the server will initiate
// and complete the full 2 way closing handshake with well-behaved
// client.
t.Parallel()
clientServerTest{
// client manually finishes closing handshake
clientTest: func(t testing.TB, ws *Websocket) {
mustReadCloseFrame(t, ws.conn, StatusNormalClosure, nil)
mustWriteFrame(t, ws.conn, true, NewCloseFrame(StatusNormalClosure, ""))
assertConnClosed(t, ws.conn)
},
// server starts closing handshake, will get no error if the client
// finishes the handshake as expected
serverOpts: Options{
CloseTimeout: 1 * time.Second,
},
serverTest: func(t testing.TB, ws *Websocket) {
assert.NilError(t, ws.Close())
assertConnClosed(t, ws.conn)
},
}.Run(t)
})
t.Run("normal client-initiated closing handshake", func(t *testing.T) {
// this test ensures that a server will complete the 2 way closing
// handshake when it is initiated by a well-behaved client.
t.Parallel()
closeStatus := StatusGoingAway
clientServerTest{
// client initiates closing handshake and expects an appropriate reply
// from the server
clientTest: func(t testing.TB, ws *Websocket) {
mustWriteFrame(t, ws.conn, true, NewCloseFrame(closeStatus, ""))
mustReadCloseFrame(t, ws.conn, closeStatus, nil)
assertConnClosed(t, ws.conn)
},
// server replies to close frame automatically during a ReadMessage
// call, which returns io.EOF when the connection is closed.
serverTest: func(t testing.TB, ws *Websocket) {
msg, err := ws.ReadMessage(t.Context())
assert.Error(t, err, io.EOF)
assert.Equal(t, msg, nil, "expected nil message")
assertConnClosed(t, ws.conn)
},
}.Run(t)
})
t.Run("timeout waiting for handshake reply", func(t *testing.T) {
// this test ensures the server enforces a timeout when waiting for a
// misbehaving client to reply to a closing handshake.
t.Parallel()
closeTimeout := 250 * time.Millisecond
clientServerTest{
// client gets the closing handshake message but does not reply,
// causing the server to time out while waiting
clientTest: func(t testing.TB, ws *Websocket) {
mustReadCloseFrame(t, ws.conn, StatusNormalClosure, nil)
},
// server starts closing handshake, which should end with a timeout
// error when the client does not reply in time
serverOpts: Options{
CloseTimeout: closeTimeout,
},
serverTest: func(t testing.TB, ws *Websocket) {
start := time.Now()
closeErr := ws.Close()
elapsed := time.Since(start)
assert.Error(t, closeErr, os.ErrDeadlineExceeded)
assert.Equal(t, elapsed > closeTimeout, true, "close should have waited for timeout")
},
}.Run(t)
})
t.Run("server initiates close but client closes conn without replying", func(t *testing.T) {
// this tests the case where a client closes the connection without
// replying when it receives the server's intitial closing handshake
t.Parallel()
clientServerTest{
// server closes connection, expects io.EOF error when reading
// reply from client, which is not treated as an error.
serverTest: func(t testing.TB, ws *Websocket) {
assert.NilError(t, ws.Close())
},
// client gets intitial closing frame from server but closes its
// end immediately
clientTest: func(t testing.TB, ws *Websocket) {
mustReadCloseFrame(t, ws.conn, StatusNormalClosure, nil)
assert.NilError(t, ws.conn.Close())
},
}.Run(t)
})
t.Run("client sends additional non-close frames before completing handshake", func(t *testing.T) {
// this test ensures that the server properly receives but ignores any
// additional data frames sent by the client after the closing
// handshake is initiated but before the client replies with its own
// close frame.
t.Parallel()
closeTimeout := 1 * time.Second
clientServerTest{
// client receives initial closing handshake but sends additional data
// before closing its end.
clientTest: func(t testing.TB, ws *Websocket) {
mustReadCloseFrame(t, ws.conn, StatusNormalClosure, nil)
mustWriteFrames(t, ws.conn, true, []*Frame{
NewFrame(OpcodePing, true, nil),
NewFrame(OpcodeText, true, []byte("ignore me")),
NewCloseFrame(StatusNormalClosure, ""),
})
assertConnClosed(t, ws.conn)
},
// server initiates closing handshake, which should complete without
// error despite additional data frames sent by the client.
serverOpts: Options{
CloseTimeout: closeTimeout,
},
serverTest: func(t testing.TB, ws *Websocket) {
assert.NilError(t, ws.Close())
},
}.Run(t)
})
t.Run("client initiates close but server reply fails", func(t *testing.T) {
// this tests an edge case where the server gets a closing handshake
// from the client but cannot reply for whatever reason.
t.Parallel()
// Define the error we'll inject when the server tries to write
writeErr := errors.New("simulated write error")
clientServerTest{
// client starts closing handshake
clientTest: func(t testing.TB, ws *Websocket) {
mustWriteFrame(t, ws.conn, true, NewCloseFrame(StatusNormalClosure, ""))
},
// server conn has write failures injected, which will prevent
// the server from replying to the client's closing handshake.
serverConn: func(conn net.Conn) net.Conn {
return &wrappedConn{
conn: conn,
write: func(b []byte) (int, error) {
return 0, writeErr
},
}
},
serverTest: func(t testing.TB, ws *Websocket) {
msg, err := ws.ReadMessage(t.Context())
assert.Error(t, err, writeErr)
assert.Equal(t, msg, nil, "msg should be nil on error")
},
}.Run(t)
})
t.Run("server fails to initiate close", func(t *testing.T) {
// this tests an edge case where the server cannot even begin the
// closing handshake due to a write error.
t.Parallel()
// Define the error we'll inject when the server tries to write
writeErr := errors.New("simulated write error")
clientServerTest{
// client should get an error on any action it takes because the
// server will close the connection when its write fails
clientTest: func(t testing.TB, ws *Websocket) {
msg, err := ws.ReadMessage(t.Context())
assert.Error(t, err, io.EOF)
assert.Equal(t, msg, nil, "expected nil message on error")
},
// server wraps the connection to inject write errors, then tries
// to close which should fail immediately
serverConn: func(conn net.Conn) net.Conn {
return &wrappedConn{
conn: conn,
write: func(b []byte) (int, error) {
return 0, writeErr
},
}
},
serverTest: func(t testing.TB, ws *Websocket) {
assert.Error(t, ws.Close(), writeErr)
},
}.Run(t)
})
}
func TestErrorHandling(t *testing.T) {
t.Run("a write error should cause the server to close the connection", func(t *testing.T) {
t.Parallel()
// the error we will inject into the wrapped writer, which will be
// verified in the close frame
writeErr := errors.New("simulated write failure")
clientServerTest{
// client writes a frame, but the server's attempt to write the echo
// response should fail. The server should then write a close frame
// (which succeeds). Client reads the close frame and then closes
// the connection to unblock the server.
clientTest: func(t testing.TB, ws *Websocket) {
mustWriteFrame(t, ws.conn, true, NewFrame(OpcodeText, true, []byte("hello")))
mustReadCloseFrame(t, ws.conn, StatusAbnormalClose, writeErr)
// reply to the close frame to complete the closing handshake
mustWriteFrame(t, ws.conn, true, NewCloseFrame(StatusNormalClosure, ""))
assertConnClosed(t, ws.conn)
},
// server conn has write failures injected: first write fails,
// subsequent writes succeed. This allows the echo handler to fail
// on the first write but succeed when writing the close frame.
serverConn: func(conn net.Conn) net.Conn {
var writeCount atomic.Int64
return &wrappedConn{
conn: conn,
write: func(b []byte) (int, error) {
count := writeCount.Add(1)
// return an error on first write
if count == 1 {
return 0, writeErr
}
// otherwise pass thru to underlying conn
return conn.Write(b)
},
}
},
serverTest: func(t testing.TB, ws *Websocket) {
err := ws.Handle(t.Context(), EchoHandler)
assert.Error(t, err, writeErr)
},
}.Run(t)
})
t.Run("handle context cancelation between reads of multi frame message", func(t *testing.T) {
// In this test, the client writes a partial message (fin=false) and
// then the context is canceled, so we ensure that the server properly
// handles cancelation between reads of multi-frame messages
t.Parallel()
ctx, cancel := context.WithCancel(t.Context())
defer cancel()
clientServerTest{
// client writes partial message, cancels context, then reads close frame
clientTest: func(t testing.TB, ws *Websocket) {
mustWriteFrame(t, ws.conn, true, NewFrame(OpcodeText, false, []byte("frame 1")))
cancel()
mustReadCloseFrame(t, ws.conn, StatusInternalError, context.Canceled)
},
// server tries to read message with the cancelable context, which
// should be canceled while waiting for the continuation frame.
serverTest: func(t testing.TB, ws *Websocket) {
assert.Error(t, ws.Handle(ctx, EchoHandler), context.Canceled)
},
}.Run(t)
})
t.Run("handle context cancelation between writes of multi frame message", func(t *testing.T) {
// In this test, the client writes a partial message (fin=false) and
// then the context is canceled, so we ensure that the server properly
// handles cancelation between reads of multi-frame messages
t.Parallel()
ctx, cancel := context.WithCancel(t.Context())
defer cancel()
maxFrameSize := 16
var payload []byte
payload = append(payload, bytes.Repeat([]byte("0"), maxFrameSize)...)
payload = append(payload, bytes.Repeat([]byte("1"), maxFrameSize)...)
clientServerTest{
// client reads first frame from multi-frame message, but then
// the connection is closed after server fails to write second
// frame
clientTest: func(t testing.TB, ws *Websocket) {
frame := mustReadFrame(t, ws.conn, maxFrameSize*2)
assert.Equal(t, frame.Payload, payload[:maxFrameSize], "incorrect payload")
// complete closing handshake
mustReadCloseFrame(t, ws.conn, StatusNormalClosure, nil)
mustWriteFrame(t, ws.conn, true, NewCloseFrame(StatusNormalClosure, ""))
},
// server writes a multi-frame message, but the context is
// canceled after the first frame is written.
serverConn: func(conn net.Conn) net.Conn {
var writeCount atomic.Int64
return &wrappedConn{
conn: conn,
write: func(b []byte) (int, error) {
n, err := conn.Write(b)
// after first write, sleep until context is canceled
// to ensure the write loop in WriteMessage sees the
// context cancelation between frames
if writeCount.Add(1) == 1 {
<-ctx.Done()
}
return n, err
},
}
},
serverOpts: Options{
MaxFrameSize: maxFrameSize,
},
serverTest: func(t testing.TB, ws *Websocket) {
go func() {
time.Sleep(100 * time.Millisecond)
cancel()
}()
msg := &Message{Payload: payload}
assert.Error(t, ws.WriteMessage(ctx, msg), context.Canceled)
assert.NilError(t, ws.Close())
},
}.Run(t)
})
t.Run("write error handling ping frame", func(t *testing.T) {
// test behavior when a ping frame is received but writing the pong
// reply fails