This repository has been archived by the owner on Sep 17, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 134
/
Copy pathserver_test.go
2252 lines (2064 loc) · 60.7 KB
/
server_test.go
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
// Copyright 2014 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// See https://code.google.com/p/go/source/browse/CONTRIBUTORS
// Licensed under the same terms as Go itself:
// https://code.google.com/p/go/source/browse/LICENSE
package http2
import (
"bytes"
"crypto/tls"
"errors"
"flag"
"fmt"
"io"
"io/ioutil"
"log"
"net"
"net/http"
"net/http/httptest"
"os"
"reflect"
"runtime"
"strconv"
"strings"
"sync"
"sync/atomic"
"testing"
"time"
"github.com/bradfitz/http2/hpack"
)
var stderrVerbose = flag.Bool("stderr_verbose", false, "Mirror verbosity to stderr, unbuffered")
type serverTester struct {
cc net.Conn // client conn
t testing.TB
ts *httptest.Server
fr *Framer
logBuf *bytes.Buffer
logFilter []string // substrings to filter out
scMu sync.Mutex // guards sc
sc *serverConn
// writing headers:
headerBuf bytes.Buffer
hpackEnc *hpack.Encoder
// reading frames:
frc chan Frame
frErrc chan error
readTimer *time.Timer
}
func init() {
testHookOnPanicMu = new(sync.Mutex)
}
func resetHooks() {
testHookOnPanicMu.Lock()
testHookOnPanic = nil
testHookOnPanicMu.Unlock()
}
type serverTesterOpt string
var optOnlyServer = serverTesterOpt("only_server")
func newServerTester(t testing.TB, handler http.HandlerFunc, opts ...interface{}) *serverTester {
resetHooks()
logBuf := new(bytes.Buffer)
ts := httptest.NewUnstartedServer(handler)
tlsConfig := &tls.Config{
InsecureSkipVerify: true,
// The h2-14 is temporary, until curl is updated. (as used by unit tests
// in Docker)
NextProtos: []string{NextProtoTLS, "h2-14"},
}
onlyServer := false
for _, opt := range opts {
switch v := opt.(type) {
case func(*tls.Config):
v(tlsConfig)
case func(*httptest.Server):
v(ts)
case serverTesterOpt:
onlyServer = (v == optOnlyServer)
default:
t.Fatalf("unknown newServerTester option type %T", v)
}
}
ConfigureServer(ts.Config, &Server{})
st := &serverTester{
t: t,
ts: ts,
logBuf: logBuf,
frc: make(chan Frame, 1),
frErrc: make(chan error, 1),
}
st.hpackEnc = hpack.NewEncoder(&st.headerBuf)
var stderrv io.Writer = ioutil.Discard
if *stderrVerbose {
stderrv = os.Stderr
}
ts.TLS = ts.Config.TLSConfig // the httptest.Server has its own copy of this TLS config
ts.Config.ErrorLog = log.New(io.MultiWriter(stderrv, twriter{t: t, st: st}, logBuf), "", log.LstdFlags)
ts.StartTLS()
if VerboseLogs {
t.Logf("Running test server at: %s", ts.URL)
}
testHookGetServerConn = func(v *serverConn) {
st.scMu.Lock()
defer st.scMu.Unlock()
st.sc = v
st.sc.testHookCh = make(chan func())
}
log.SetOutput(io.MultiWriter(stderrv, twriter{t: t, st: st}))
if !onlyServer {
cc, err := tls.Dial("tcp", ts.Listener.Addr().String(), tlsConfig)
if err != nil {
t.Fatal(err)
}
st.cc = cc
st.fr = NewFramer(cc, cc)
}
return st
}
func (st *serverTester) closeConn() {
st.scMu.Lock()
defer st.scMu.Unlock()
st.sc.conn.Close()
}
func (st *serverTester) addLogFilter(phrase string) {
st.logFilter = append(st.logFilter, phrase)
}
func (st *serverTester) stream(id uint32) *stream {
ch := make(chan *stream, 1)
st.sc.testHookCh <- func() {
ch <- st.sc.streams[id]
}
return <-ch
}
func (st *serverTester) streamState(id uint32) streamState {
ch := make(chan streamState, 1)
st.sc.testHookCh <- func() {
state, _ := st.sc.state(id)
ch <- state
}
return <-ch
}
func (st *serverTester) Close() {
st.ts.Close()
if st.cc != nil {
st.cc.Close()
}
log.SetOutput(os.Stderr)
}
// greet initiates the client's HTTP/2 connection into a state where
// frames may be sent.
func (st *serverTester) greet() {
st.writePreface()
st.writeInitialSettings()
st.wantSettings()
st.writeSettingsAck()
st.wantSettingsAck()
}
func (st *serverTester) writePreface() {
n, err := st.cc.Write(clientPreface)
if err != nil {
st.t.Fatalf("Error writing client preface: %v", err)
}
if n != len(clientPreface) {
st.t.Fatalf("Writing client preface, wrote %d bytes; want %d", n, len(clientPreface))
}
}
func (st *serverTester) writeInitialSettings() {
if err := st.fr.WriteSettings(); err != nil {
st.t.Fatalf("Error writing initial SETTINGS frame from client to server: %v", err)
}
}
func (st *serverTester) writeSettingsAck() {
if err := st.fr.WriteSettingsAck(); err != nil {
st.t.Fatalf("Error writing ACK of server's SETTINGS: %v", err)
}
}
func (st *serverTester) writeHeaders(p HeadersFrameParam) {
if err := st.fr.WriteHeaders(p); err != nil {
st.t.Fatalf("Error writing HEADERS: %v", err)
}
}
func (st *serverTester) encodeHeaderField(k, v string) {
err := st.hpackEnc.WriteField(hpack.HeaderField{Name: k, Value: v})
if err != nil {
st.t.Fatalf("HPACK encoding error for %q/%q: %v", k, v, err)
}
}
// encodeHeader encodes headers and returns their HPACK bytes. headers
// must contain an even number of key/value pairs. There may be
// multiple pairs for keys (e.g. "cookie"). The :method, :path, and
// :scheme headers default to GET, / and https.
func (st *serverTester) encodeHeader(headers ...string) []byte {
if len(headers)%2 == 1 {
panic("odd number of kv args")
}
st.headerBuf.Reset()
if len(headers) == 0 {
// Fast path, mostly for benchmarks, so test code doesn't pollute
// profiles when we're looking to improve server allocations.
st.encodeHeaderField(":method", "GET")
st.encodeHeaderField(":path", "/")
st.encodeHeaderField(":scheme", "https")
return st.headerBuf.Bytes()
}
if len(headers) == 2 && headers[0] == ":method" {
// Another fast path for benchmarks.
st.encodeHeaderField(":method", headers[1])
st.encodeHeaderField(":path", "/")
st.encodeHeaderField(":scheme", "https")
return st.headerBuf.Bytes()
}
pseudoCount := map[string]int{}
keys := []string{":method", ":path", ":scheme"}
vals := map[string][]string{
":method": {"GET"},
":path": {"/"},
":scheme": {"https"},
}
for len(headers) > 0 {
k, v := headers[0], headers[1]
headers = headers[2:]
if _, ok := vals[k]; !ok {
keys = append(keys, k)
}
if strings.HasPrefix(k, ":") {
pseudoCount[k]++
if pseudoCount[k] == 1 {
vals[k] = []string{v}
} else {
// Allows testing of invalid headers w/ dup pseudo fields.
vals[k] = append(vals[k], v)
}
} else {
vals[k] = append(vals[k], v)
}
}
st.headerBuf.Reset()
for _, k := range keys {
for _, v := range vals[k] {
st.encodeHeaderField(k, v)
}
}
return st.headerBuf.Bytes()
}
// bodylessReq1 writes a HEADERS frames with StreamID 1 and EndStream and EndHeaders set.
func (st *serverTester) bodylessReq1(headers ...string) {
st.writeHeaders(HeadersFrameParam{
StreamID: 1, // clients send odd numbers
BlockFragment: st.encodeHeader(headers...),
EndStream: true,
EndHeaders: true,
})
}
func (st *serverTester) writeData(streamID uint32, endStream bool, data []byte) {
if err := st.fr.WriteData(streamID, endStream, data); err != nil {
st.t.Fatalf("Error writing DATA: %v", err)
}
}
func (st *serverTester) readFrame() (Frame, error) {
go func() {
fr, err := st.fr.ReadFrame()
if err != nil {
st.frErrc <- err
} else {
st.frc <- fr
}
}()
t := st.readTimer
if t == nil {
t = time.NewTimer(2 * time.Second)
st.readTimer = t
}
t.Reset(2 * time.Second)
defer t.Stop()
select {
case f := <-st.frc:
return f, nil
case err := <-st.frErrc:
return nil, err
case <-t.C:
return nil, errors.New("timeout waiting for frame")
}
}
func (st *serverTester) wantHeaders() *HeadersFrame {
f, err := st.readFrame()
if err != nil {
st.t.Fatalf("Error while expecting a HEADERS frame: %v", err)
}
hf, ok := f.(*HeadersFrame)
if !ok {
st.t.Fatalf("got a %T; want *HeadersFrame", f)
}
return hf
}
func (st *serverTester) wantContinuation() *ContinuationFrame {
f, err := st.readFrame()
if err != nil {
st.t.Fatalf("Error while expecting a CONTINUATION frame: %v", err)
}
cf, ok := f.(*ContinuationFrame)
if !ok {
st.t.Fatalf("got a %T; want *ContinuationFrame", f)
}
return cf
}
func (st *serverTester) wantData() *DataFrame {
f, err := st.readFrame()
if err != nil {
st.t.Fatalf("Error while expecting a DATA frame: %v", err)
}
df, ok := f.(*DataFrame)
if !ok {
st.t.Fatalf("got a %T; want *DataFrame", f)
}
return df
}
func (st *serverTester) wantSettings() *SettingsFrame {
f, err := st.readFrame()
if err != nil {
st.t.Fatalf("Error while expecting a SETTINGS frame: %v", err)
}
sf, ok := f.(*SettingsFrame)
if !ok {
st.t.Fatalf("got a %T; want *SettingsFrame", f)
}
return sf
}
func (st *serverTester) wantPing() *PingFrame {
f, err := st.readFrame()
if err != nil {
st.t.Fatalf("Error while expecting a PING frame: %v", err)
}
pf, ok := f.(*PingFrame)
if !ok {
st.t.Fatalf("got a %T; want *PingFrame", f)
}
return pf
}
func (st *serverTester) wantGoAway() *GoAwayFrame {
f, err := st.readFrame()
if err != nil {
st.t.Fatalf("Error while expecting a GOAWAY frame: %v", err)
}
gf, ok := f.(*GoAwayFrame)
if !ok {
st.t.Fatalf("got a %T; want *GoAwayFrame", f)
}
return gf
}
func (st *serverTester) wantRSTStream(streamID uint32, errCode ErrCode) {
f, err := st.readFrame()
if err != nil {
st.t.Fatalf("Error while expecting an RSTStream frame: %v", err)
}
rs, ok := f.(*RSTStreamFrame)
if !ok {
st.t.Fatalf("got a %T; want *RSTStreamFrame", f)
}
if rs.FrameHeader.StreamID != streamID {
st.t.Fatalf("RSTStream StreamID = %d; want %d", rs.FrameHeader.StreamID, streamID)
}
if rs.ErrCode != errCode {
st.t.Fatalf("RSTStream ErrCode = %d (%s); want %d (%s)", rs.ErrCode, rs.ErrCode, errCode, errCode)
}
}
func (st *serverTester) wantWindowUpdate(streamID, incr uint32) {
f, err := st.readFrame()
if err != nil {
st.t.Fatalf("Error while expecting a WINDOW_UPDATE frame: %v", err)
}
wu, ok := f.(*WindowUpdateFrame)
if !ok {
st.t.Fatalf("got a %T; want *WindowUpdateFrame", f)
}
if wu.FrameHeader.StreamID != streamID {
st.t.Fatalf("WindowUpdate StreamID = %d; want %d", wu.FrameHeader.StreamID, streamID)
}
if wu.Increment != incr {
st.t.Fatalf("WindowUpdate increment = %d; want %d", wu.Increment, incr)
}
}
func (st *serverTester) wantSettingsAck() {
f, err := st.readFrame()
if err != nil {
st.t.Fatal(err)
}
sf, ok := f.(*SettingsFrame)
if !ok {
st.t.Fatalf("Wanting a settings ACK, received a %T", f)
}
if !sf.Header().Flags.Has(FlagSettingsAck) {
st.t.Fatal("Settings Frame didn't have ACK set")
}
}
func TestServer(t *testing.T) {
gotReq := make(chan bool, 1)
st := newServerTester(t, func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Foo", "Bar")
gotReq <- true
})
defer st.Close()
covers("3.5", `
The server connection preface consists of a potentially empty
SETTINGS frame ([SETTINGS]) that MUST be the first frame the
server sends in the HTTP/2 connection.
`)
st.writePreface()
st.writeInitialSettings()
st.wantSettings()
st.writeSettingsAck()
st.wantSettingsAck()
st.writeHeaders(HeadersFrameParam{
StreamID: 1, // clients send odd numbers
BlockFragment: st.encodeHeader(),
EndStream: true, // no DATA frames
EndHeaders: true,
})
select {
case <-gotReq:
case <-time.After(2 * time.Second):
t.Error("timeout waiting for request")
}
}
func TestServer_Request_Get(t *testing.T) {
testServerRequest(t, func(st *serverTester) {
st.writeHeaders(HeadersFrameParam{
StreamID: 1, // clients send odd numbers
BlockFragment: st.encodeHeader("foo-bar", "some-value"),
EndStream: true, // no DATA frames
EndHeaders: true,
})
}, func(r *http.Request) {
if r.Method != "GET" {
t.Errorf("Method = %q; want GET", r.Method)
}
if r.URL.Path != "/" {
t.Errorf("URL.Path = %q; want /", r.URL.Path)
}
if r.ContentLength != 0 {
t.Errorf("ContentLength = %v; want 0", r.ContentLength)
}
if r.Close {
t.Error("Close = true; want false")
}
if !strings.Contains(r.RemoteAddr, ":") {
t.Errorf("RemoteAddr = %q; want something with a colon", r.RemoteAddr)
}
if r.Proto != "HTTP/2.0" || r.ProtoMajor != 2 || r.ProtoMinor != 0 {
t.Errorf("Proto = %q Major=%v,Minor=%v; want HTTP/2.0", r.Proto, r.ProtoMajor, r.ProtoMinor)
}
wantHeader := http.Header{
"Foo-Bar": []string{"some-value"},
}
if !reflect.DeepEqual(r.Header, wantHeader) {
t.Errorf("Header = %#v; want %#v", r.Header, wantHeader)
}
if n, err := r.Body.Read([]byte(" ")); err != io.EOF || n != 0 {
t.Errorf("Read = %d, %v; want 0, EOF", n, err)
}
})
}
func TestServer_Request_Get_PathSlashes(t *testing.T) {
testServerRequest(t, func(st *serverTester) {
st.writeHeaders(HeadersFrameParam{
StreamID: 1, // clients send odd numbers
BlockFragment: st.encodeHeader(":path", "/%2f/"),
EndStream: true, // no DATA frames
EndHeaders: true,
})
}, func(r *http.Request) {
if r.RequestURI != "/%2f/" {
t.Errorf("RequestURI = %q; want /%%2f/", r.RequestURI)
}
if r.URL.Path != "///" {
t.Errorf("URL.Path = %q; want ///", r.URL.Path)
}
})
}
// TODO: add a test with EndStream=true on the HEADERS but setting a
// Content-Length anyway. Should we just omit it and force it to
// zero?
func TestServer_Request_Post_NoContentLength_EndStream(t *testing.T) {
testServerRequest(t, func(st *serverTester) {
st.writeHeaders(HeadersFrameParam{
StreamID: 1, // clients send odd numbers
BlockFragment: st.encodeHeader(":method", "POST"),
EndStream: true,
EndHeaders: true,
})
}, func(r *http.Request) {
if r.Method != "POST" {
t.Errorf("Method = %q; want POST", r.Method)
}
if r.ContentLength != 0 {
t.Errorf("ContentLength = %v; want 0", r.ContentLength)
}
if n, err := r.Body.Read([]byte(" ")); err != io.EOF || n != 0 {
t.Errorf("Read = %d, %v; want 0, EOF", n, err)
}
})
}
func TestServer_Request_Post_Body_ImmediateEOF(t *testing.T) {
testBodyContents(t, -1, "", func(st *serverTester) {
st.writeHeaders(HeadersFrameParam{
StreamID: 1, // clients send odd numbers
BlockFragment: st.encodeHeader(":method", "POST"),
EndStream: false, // to say DATA frames are coming
EndHeaders: true,
})
st.writeData(1, true, nil) // just kidding. empty body.
})
}
func TestServer_Request_Post_Body_OneData(t *testing.T) {
const content = "Some content"
testBodyContents(t, -1, content, func(st *serverTester) {
st.writeHeaders(HeadersFrameParam{
StreamID: 1, // clients send odd numbers
BlockFragment: st.encodeHeader(":method", "POST"),
EndStream: false, // to say DATA frames are coming
EndHeaders: true,
})
st.writeData(1, true, []byte(content))
})
}
func TestServer_Request_Post_Body_TwoData(t *testing.T) {
const content = "Some content"
testBodyContents(t, -1, content, func(st *serverTester) {
st.writeHeaders(HeadersFrameParam{
StreamID: 1, // clients send odd numbers
BlockFragment: st.encodeHeader(":method", "POST"),
EndStream: false, // to say DATA frames are coming
EndHeaders: true,
})
st.writeData(1, false, []byte(content[:5]))
st.writeData(1, true, []byte(content[5:]))
})
}
func TestServer_Request_Post_Body_ContentLength_Correct(t *testing.T) {
const content = "Some content"
testBodyContents(t, int64(len(content)), content, func(st *serverTester) {
st.writeHeaders(HeadersFrameParam{
StreamID: 1, // clients send odd numbers
BlockFragment: st.encodeHeader(
":method", "POST",
"content-length", strconv.Itoa(len(content)),
),
EndStream: false, // to say DATA frames are coming
EndHeaders: true,
})
st.writeData(1, true, []byte(content))
})
}
func TestServer_Request_Post_Body_ContentLength_TooLarge(t *testing.T) {
testBodyContentsFail(t, 3, "request declared a Content-Length of 3 but only wrote 2 bytes",
func(st *serverTester) {
st.writeHeaders(HeadersFrameParam{
StreamID: 1, // clients send odd numbers
BlockFragment: st.encodeHeader(
":method", "POST",
"content-length", "3",
),
EndStream: false, // to say DATA frames are coming
EndHeaders: true,
})
st.writeData(1, true, []byte("12"))
})
}
func TestServer_Request_Post_Body_ContentLength_TooSmall(t *testing.T) {
testBodyContentsFail(t, 4, "sender tried to send more than declared Content-Length of 4 bytes",
func(st *serverTester) {
st.writeHeaders(HeadersFrameParam{
StreamID: 1, // clients send odd numbers
BlockFragment: st.encodeHeader(
":method", "POST",
"content-length", "4",
),
EndStream: false, // to say DATA frames are coming
EndHeaders: true,
})
st.writeData(1, true, []byte("12345"))
})
}
func testBodyContents(t *testing.T, wantContentLength int64, wantBody string, write func(st *serverTester)) {
testServerRequest(t, write, func(r *http.Request) {
if r.Method != "POST" {
t.Errorf("Method = %q; want POST", r.Method)
}
if r.ContentLength != wantContentLength {
t.Errorf("ContentLength = %v; want %d", r.ContentLength, wantContentLength)
}
all, err := ioutil.ReadAll(r.Body)
if err != nil {
t.Fatal(err)
}
if string(all) != wantBody {
t.Errorf("Read = %q; want %q", all, wantBody)
}
if err := r.Body.Close(); err != nil {
t.Fatalf("Close: %v", err)
}
})
}
func testBodyContentsFail(t *testing.T, wantContentLength int64, wantReadError string, write func(st *serverTester)) {
testServerRequest(t, write, func(r *http.Request) {
if r.Method != "POST" {
t.Errorf("Method = %q; want POST", r.Method)
}
if r.ContentLength != wantContentLength {
t.Errorf("ContentLength = %v; want %d", r.ContentLength, wantContentLength)
}
all, err := ioutil.ReadAll(r.Body)
if err == nil {
t.Fatalf("expected an error (%q) reading from the body. Successfully read %q instead.",
wantReadError, all)
}
if !strings.Contains(err.Error(), wantReadError) {
t.Fatalf("Body.Read = %v; want substring %q", err, wantReadError)
}
if err := r.Body.Close(); err != nil {
t.Fatalf("Close: %v", err)
}
})
}
// Using a Host header, instead of :authority
func TestServer_Request_Get_Host(t *testing.T) {
const host = "example.com"
testServerRequest(t, func(st *serverTester) {
st.writeHeaders(HeadersFrameParam{
StreamID: 1, // clients send odd numbers
BlockFragment: st.encodeHeader("host", host),
EndStream: true,
EndHeaders: true,
})
}, func(r *http.Request) {
if r.Host != host {
t.Errorf("Host = %q; want %q", r.Host, host)
}
})
}
// Using an :authority pseudo-header, instead of Host
func TestServer_Request_Get_Authority(t *testing.T) {
const host = "example.com"
testServerRequest(t, func(st *serverTester) {
st.writeHeaders(HeadersFrameParam{
StreamID: 1, // clients send odd numbers
BlockFragment: st.encodeHeader(":authority", host),
EndStream: true,
EndHeaders: true,
})
}, func(r *http.Request) {
if r.Host != host {
t.Errorf("Host = %q; want %q", r.Host, host)
}
})
}
func TestServer_Request_WithContinuation(t *testing.T) {
wantHeader := http.Header{
"Foo-One": []string{"value-one"},
"Foo-Two": []string{"value-two"},
"Foo-Three": []string{"value-three"},
}
testServerRequest(t, func(st *serverTester) {
fullHeaders := st.encodeHeader(
"foo-one", "value-one",
"foo-two", "value-two",
"foo-three", "value-three",
)
remain := fullHeaders
chunks := 0
for len(remain) > 0 {
const maxChunkSize = 5
chunk := remain
if len(chunk) > maxChunkSize {
chunk = chunk[:maxChunkSize]
}
remain = remain[len(chunk):]
if chunks == 0 {
st.writeHeaders(HeadersFrameParam{
StreamID: 1, // clients send odd numbers
BlockFragment: chunk,
EndStream: true, // no DATA frames
EndHeaders: false, // we'll have continuation frames
})
} else {
err := st.fr.WriteContinuation(1, len(remain) == 0, chunk)
if err != nil {
t.Fatal(err)
}
}
chunks++
}
if chunks < 2 {
t.Fatal("too few chunks")
}
}, func(r *http.Request) {
if !reflect.DeepEqual(r.Header, wantHeader) {
t.Errorf("Header = %#v; want %#v", r.Header, wantHeader)
}
})
}
// Concatenated cookie headers. ("8.1.2.5 Compressing the Cookie Header Field")
func TestServer_Request_CookieConcat(t *testing.T) {
const host = "example.com"
testServerRequest(t, func(st *serverTester) {
st.bodylessReq1(
":authority", host,
"cookie", "a=b",
"cookie", "c=d",
"cookie", "e=f",
)
}, func(r *http.Request) {
const want = "a=b; c=d; e=f"
if got := r.Header.Get("Cookie"); got != want {
t.Errorf("Cookie = %q; want %q", got, want)
}
})
}
func TestServer_Request_Reject_CapitalHeader(t *testing.T) {
testRejectRequest(t, func(st *serverTester) { st.bodylessReq1("UPPER", "v") })
}
func TestServer_Request_Reject_Pseudo_Missing_method(t *testing.T) {
testRejectRequest(t, func(st *serverTester) { st.bodylessReq1(":method", "") })
}
func TestServer_Request_Reject_Pseudo_ExactlyOne(t *testing.T) {
// 8.1.2.3 Request Pseudo-Header Fields
// "All HTTP/2 requests MUST include exactly one valid value" ...
testRejectRequest(t, func(st *serverTester) {
st.addLogFilter("duplicate pseudo-header")
st.bodylessReq1(":method", "GET", ":method", "POST")
})
}
func TestServer_Request_Reject_Pseudo_AfterRegular(t *testing.T) {
// 8.1.2.3 Request Pseudo-Header Fields
// "All pseudo-header fields MUST appear in the header block
// before regular header fields. Any request or response that
// contains a pseudo-header field that appears in a header
// block after a regular header field MUST be treated as
// malformed (Section 8.1.2.6)."
testRejectRequest(t, func(st *serverTester) {
st.addLogFilter("pseudo-header after regular header")
var buf bytes.Buffer
enc := hpack.NewEncoder(&buf)
enc.WriteField(hpack.HeaderField{Name: ":method", Value: "GET"})
enc.WriteField(hpack.HeaderField{Name: "regular", Value: "foobar"})
enc.WriteField(hpack.HeaderField{Name: ":path", Value: "/"})
enc.WriteField(hpack.HeaderField{Name: ":scheme", Value: "https"})
st.writeHeaders(HeadersFrameParam{
StreamID: 1, // clients send odd numbers
BlockFragment: buf.Bytes(),
EndStream: true,
EndHeaders: true,
})
})
}
func TestServer_Request_Reject_Pseudo_Missing_path(t *testing.T) {
testRejectRequest(t, func(st *serverTester) { st.bodylessReq1(":path", "") })
}
func TestServer_Request_Reject_Pseudo_Missing_scheme(t *testing.T) {
testRejectRequest(t, func(st *serverTester) { st.bodylessReq1(":scheme", "") })
}
func TestServer_Request_Reject_Pseudo_scheme_invalid(t *testing.T) {
testRejectRequest(t, func(st *serverTester) { st.bodylessReq1(":scheme", "bogus") })
}
func TestServer_Request_Reject_Pseudo_Unknown(t *testing.T) {
testRejectRequest(t, func(st *serverTester) {
st.addLogFilter(`invalid pseudo-header ":unknown_thing"`)
st.bodylessReq1(":unknown_thing", "")
})
}
func testRejectRequest(t *testing.T, send func(*serverTester)) {
st := newServerTester(t, func(w http.ResponseWriter, r *http.Request) {
t.Fatal("server request made it to handler; should've been rejected")
})
defer st.Close()
st.greet()
send(st)
st.wantRSTStream(1, ErrCodeProtocol)
}
func TestServer_Ping(t *testing.T) {
st := newServerTester(t, nil)
defer st.Close()
st.greet()
// Server should ignore this one, since it has ACK set.
ackPingData := [8]byte{1, 2, 4, 8, 16, 32, 64, 128}
if err := st.fr.WritePing(true, ackPingData); err != nil {
t.Fatal(err)
}
// But the server should reply to this one, since ACK is false.
pingData := [8]byte{1, 2, 3, 4, 5, 6, 7, 8}
if err := st.fr.WritePing(false, pingData); err != nil {
t.Fatal(err)
}
pf := st.wantPing()
if !pf.Flags.Has(FlagPingAck) {
t.Error("response ping doesn't have ACK set")
}
if pf.Data != pingData {
t.Errorf("response ping has data %q; want %q", pf.Data, pingData)
}
}
func TestServer_RejectsLargeFrames(t *testing.T) {
st := newServerTester(t, nil)
defer st.Close()
st.greet()
// Write too large of a frame (too large by one byte)
// We ignore the return value because it's expected that the server
// will only read the first 9 bytes (the headre) and then disconnect.
st.fr.WriteRawFrame(0xff, 0, 0, make([]byte, defaultMaxReadFrameSize+1))
gf := st.wantGoAway()
if gf.ErrCode != ErrCodeFrameSize {
t.Errorf("GOAWAY err = %v; want %v", gf.ErrCode, ErrCodeFrameSize)
}
}
func TestServer_Handler_Sends_WindowUpdate(t *testing.T) {
puppet := newHandlerPuppet()
st := newServerTester(t, func(w http.ResponseWriter, r *http.Request) {
puppet.act(w, r)
})
defer st.Close()
defer puppet.done()
st.greet()
st.writeHeaders(HeadersFrameParam{
StreamID: 1, // clients send odd numbers
BlockFragment: st.encodeHeader(":method", "POST"),
EndStream: false, // data coming
EndHeaders: true,
})
st.writeData(1, false, []byte("abcdef"))
puppet.do(readBodyHandler(t, "abc"))
st.wantWindowUpdate(0, 3)
st.wantWindowUpdate(1, 3)
puppet.do(readBodyHandler(t, "def"))
st.wantWindowUpdate(0, 3)
st.wantWindowUpdate(1, 3)
st.writeData(1, true, []byte("ghijkl")) // END_STREAM here
puppet.do(readBodyHandler(t, "ghi"))
puppet.do(readBodyHandler(t, "jkl"))
st.wantWindowUpdate(0, 3)
st.wantWindowUpdate(0, 3) // no more stream-level, since END_STREAM
}
func TestServer_Send_GoAway_After_Bogus_WindowUpdate(t *testing.T) {
st := newServerTester(t, nil)
defer st.Close()
st.greet()
if err := st.fr.WriteWindowUpdate(0, 1<<31-1); err != nil {
t.Fatal(err)
}
gf := st.wantGoAway()
if gf.ErrCode != ErrCodeFlowControl {
t.Errorf("GOAWAY err = %v; want %v", gf.ErrCode, ErrCodeFlowControl)
}
if gf.LastStreamID != 0 {
t.Errorf("GOAWAY last stream ID = %v; want %v", gf.LastStreamID, 0)
}
}
func TestServer_Send_RstStream_After_Bogus_WindowUpdate(t *testing.T) {
inHandler := make(chan bool)
blockHandler := make(chan bool)
st := newServerTester(t, func(w http.ResponseWriter, r *http.Request) {
inHandler <- true
<-blockHandler
})
defer st.Close()
defer close(blockHandler)
st.greet()
st.writeHeaders(HeadersFrameParam{
StreamID: 1,
BlockFragment: st.encodeHeader(":method", "POST"),
EndStream: false, // keep it open
EndHeaders: true,
})
<-inHandler
// Send a bogus window update:
if err := st.fr.WriteWindowUpdate(1, 1<<31-1); err != nil {
t.Fatal(err)
}
st.wantRSTStream(1, ErrCodeFlowControl)
}
// testServerPostUnblock sends a hanging POST with unsent data to handler,
// then runs fn once in the handler, and verifies that the error returned from
// handler is acceptable. It fails if takes over 5 seconds for handler to exit.
func testServerPostUnblock(t *testing.T,
handler func(http.ResponseWriter, *http.Request) error,
fn func(*serverTester),
checkErr func(error),
otherHeaders ...string) {
inHandler := make(chan bool)
errc := make(chan error, 1)
st := newServerTester(t, func(w http.ResponseWriter, r *http.Request) {
inHandler <- true
errc <- handler(w, r)
})
st.greet()
st.writeHeaders(HeadersFrameParam{
StreamID: 1,
BlockFragment: st.encodeHeader(append([]string{":method", "POST"}, otherHeaders...)...),
EndStream: false, // keep it open
EndHeaders: true,
})
<-inHandler
fn(st)
select {
case err := <-errc:
if checkErr != nil {