Repository navigation
Expand file tree
/
Copy pathhttp_test.go
More file actions
7052 lines (6700 loc) · 277 KB
/
Copy pathhttp_test.go
File metadata and controls
7052 lines (6700 loc) · 277 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
// Copyright 2025 Sylvain Müller. All rights reserved.
// Mount of this source code is governed by a Apache-2.0 license that can be found
// at https://github.com/stdapi/edge/blob/main/LICENSE.txt.
package edge
import (
"bufio"
"bytes"
"compress/gzip"
"context"
"crypto/tls"
"crypto/x509"
"encoding/base64"
"errors"
"fmt"
"io"
"net"
"net/http"
"net/http/httptest"
"net/http/httptrace"
"net/netip"
"net/textproto"
"net/url"
"regexp"
"runtime"
"slices"
"strconv"
"strings"
"sync"
"sync/atomic"
"syscall"
"testing"
"testing/iotest"
"time"
"github.com/quic-go/qpack"
"github.com/quic-go/quic-go"
"github.com/quic-go/quic-go/http3"
"github.com/quic-go/quic-go/quicvarint"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"golang.org/x/net/http/httpguts"
"golang.org/x/net/http2"
"golang.org/x/net/http2/hpack"
)
func TestHTTP_ShortCircuit(t *testing.T) {
var originHits int
origin := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
originHits++
fmt.Fprint(w, "should not be reached")
}))
defer origin.Close()
originURL, _ := url.Parse(origin.URL)
ca, _ := GenerateCA()
tr := DefaultTransport()
tr.RootCAs = originPool(t, origin)
p, err := New(WithCA(ca), WithTransport(tr))
if err != nil {
t.Fatalf("new proxy: %v", err)
}
p.MustAdd(originHost(originURL)+"/v1/charges", func(c *HTTPCtx) (*http.Response, error) {
if c.Request().Header.Get("Idempotency-Key") == "" {
return Text(http.StatusBadRequest, "missing idempotency key"), nil
}
return c.Forward()
}, WithMethods[HTTP](http.MethodPost))
addr := startProxy(t, p)
client := proxyClient(addr, ca.CertPool())
resp, err := client.Post(origin.URL+"/v1/charges", "application/json", strings.NewReader(`{}`))
if err != nil {
t.Fatalf("post through proxy: %v", err)
}
defer func() { _ = resp.Body.Close() }()
if resp.StatusCode != http.StatusBadRequest {
t.Fatalf("status = %d, want 400", resp.StatusCode)
}
body, _ := io.ReadAll(resp.Body)
if string(body) != "missing idempotency key" {
t.Fatalf("body = %q", body)
}
if originHits != 0 {
t.Fatalf("origin was reached %d times, want 0", originHits)
}
}
func TestHTTP_PlainHTTPAbsoluteTarget(t *testing.T) {
origin := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "plain %s", r.URL.Path)
}))
defer origin.Close()
originURL, _ := url.Parse(origin.URL)
ca, _ := GenerateCA()
p, err := New(WithCA(ca))
if err != nil {
t.Fatalf("new proxy: %v", err)
}
p.MustAdd(originHost(originURL)+"/hello", func(c *HTTPCtx) (*http.Response, error) {
if c.Scheme() != "http" {
return nil, fmt.Errorf("scheme = %q, want http", c.Scheme())
}
resp, err := c.Forward()
if err != nil {
return nil, err
}
body, _ := ReadBody(resp, 0)
return Rewrite(resp, []byte(strings.ToUpper(string(body)))), nil
}, WithMethods[HTTP](http.MethodGet))
addr := startProxy(t, p)
client := proxyClient(addr, nil)
resp, err := client.Get(origin.URL + "/hello")
if err != nil {
t.Fatalf("get through proxy: %v", err)
}
defer func() { _ = resp.Body.Close() }()
body, _ := io.ReadAll(resp.Body)
if string(body) != "PLAIN /HELLO" {
t.Fatalf("body = %q, want PLAIN /HELLO", body)
}
}
func TestHTTP_StreamsWithoutBuffering(t *testing.T) {
release := make(chan struct{})
origin := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/event-stream")
w.WriteHeader(http.StatusOK)
rc := http.NewResponseController(w)
fmt.Fprint(w, "data: first\n\n")
_ = rc.Flush()
<-release
fmt.Fprint(w, "data: second\n\n")
_ = rc.Flush()
}))
defer origin.Close()
originURL, _ := url.Parse(origin.URL)
ca, _ := GenerateCA()
tr := DefaultTransport()
tr.RootCAs = originPool(t, origin)
p, err := New(WithCA(ca), WithTransport(tr))
if err != nil {
t.Fatalf("new proxy: %v", err)
}
p.MustAdd(originHost(originURL)+"/events", func(c *HTTPCtx) (*http.Response, error) {
return c.Forward()
}, WithMethods[HTTP](http.MethodGet))
addr := startProxy(t, p)
client := proxyClient(addr, ca.CertPool())
resp, err := client.Get(origin.URL + "/events")
if err != nil {
t.Fatalf("get events: %v", err)
}
defer func() { _ = resp.Body.Close() }()
br := bufio.NewReader(resp.Body)
line, err := br.ReadString('\n')
if err != nil {
t.Fatalf("read first event: %v", err)
}
// Reaching this before the origin has written the second event proves the proxy is not
// waiting for the body to end before relaying it.
if strings.TrimSpace(line) != "data: first" {
t.Fatalf("first event = %q", line)
}
close(release)
rest, _ := io.ReadAll(br)
if !strings.Contains(string(rest), "data: second") {
t.Fatalf("second event missing from %q", rest)
}
}
func TestHTTP_ForwardsTrailers(t *testing.T) {
origin := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Trailer", "X-Checksum")
w.WriteHeader(http.StatusOK)
fmt.Fprint(w, "payload")
w.Header().Set("X-Checksum", "deadbeef")
}))
defer origin.Close()
originURL, _ := url.Parse(origin.URL)
ca, _ := GenerateCA()
tr := DefaultTransport()
tr.RootCAs = originPool(t, origin)
p, err := New(WithCA(ca), WithTransport(tr))
if err != nil {
t.Fatalf("new proxy: %v", err)
}
p.MustAdd(originHost(originURL)+"/*{any}", forwardHandler)
addr := startProxy(t, p)
client := proxyClient(addr, ca.CertPool())
resp, err := client.Get(origin.URL + "/")
if err != nil {
t.Fatalf("get: %v", err)
}
defer func() { _ = resp.Body.Close() }()
body, _ := io.ReadAll(resp.Body)
if string(body) != "payload" {
t.Fatalf("body = %q", body)
}
if got := resp.Trailer.Get("X-Checksum"); got != "deadbeef" {
t.Fatalf("trailer X-Checksum = %q, want deadbeef", got)
}
}
func TestHTTP_EmptyRequestAnnouncingTrailersEndsUpstream(t *testing.T) {
o := prefaceOrigin(t, func(_ *rawOrigin, _ *wire, fr *http2.Framer) {
if _, err := fr.ReadFrame(); err != nil || fr.WriteSettings() != nil || fr.WriteSettingsAck() != nil {
return
}
for {
f, err := fr.ReadFrame()
if err != nil {
return
}
if end, ok := f.(interface{ StreamEnded() bool }); ok && end.StreamEnded() && writeOK(fr, f.Header().StreamID) != nil {
return
}
}
})
p := testProxy(t)
p.MustAdd("origin.test/*{any}", forwardHandler)
c := dialDeclared(t, viaRedirected, p, netip.MustParseAddrPort(o.addr))
_, err := io.WriteString(c, http2.ClientPreface)
require.NoError(t, err)
h := newH2Wire(c)
require.NoError(t, h.fr.WriteSettings())
h.headers(t, 1, false, hf(":method", "POST"), hf(":scheme", "http"), hf(":authority", "origin.test"), hf(":path", "/"),
hf("content-length", "0"), hf("trailer", "x-checksum"))
h.headers(t, 1, true, hf("x-checksum", "deadbeef"))
assert.Equal(t, "ok", string(h.reply(t, 1).body))
}
func TestHTTP_ContentPastAZeroLengthIsMalformed(t *testing.T) {
for _, version := range []string{viaH2, viaH3} {
t.Run(version, func(t *testing.T) {
errs := make(chan error, 1)
p := testProxy(t)
p.MustAdd("origin.test/*{any}", func(c *HTTPCtx) (*http.Response, error) {
resp, err := c.Forward()
errs <- err
return resp, err
})
if version == viaH3 {
(&proxyBench{p: p}).dialH3Front(t).roundTrip(t, h3Request("POST", "origin.test", "/", hf("content-length", "0")), h3Data("abcd"))
} else {
h := dialH2Wire(t, viaH2C, p, "origin.test")
h.headers(t, 1, false, hf(":method", "POST"), hf(":scheme", "http"), hf(":authority", "origin.test"), hf(":path", "/"),
hf("content-length", "0"))
require.NoError(t, h.fr.WriteData(1, true, []byte("abcd")))
h.reply(t, 1)
}
select {
case err := <-errs:
require.True(t, errors.Is(err, errMalformedRequest), "forward failed with %v", err)
case <-time.After(5 * time.Second):
t.Fatal("the handler did not return")
}
})
}
}
func TestHTTP_RequestWithoutContentEndsWithItsHeadersOverHTTP2(t *testing.T) {
eachDeclaredFront(t, func(t *testing.T, front string) {
for _, req := range []struct {
method string
want string
extra []hpack.HeaderField
}{
{method: "GET", want: `HEADERS stream=1 end_stream=true content-length=""`},
{method: "POST", want: `HEADERS stream=1 end_stream=true content-length="0"`, extra: []hpack.HeaderField{hf("content-length", "0")}},
} {
t.Run(req.method, func(t *testing.T) {
o := prefaceOrigin(t, respondH2)
got := h2cRequest(t, front, o, req.method, req.extra...)
assert.Equal(t, "ok", string(got.body))
require.Equal(t, http2.ClientPreface, o.nextNote(t))
require.Equal(t, "SETTINGS stream=0 ack=false", o.nextNote(t))
assert.Equal(t, req.want, o.nextNote(t))
})
}
})
}
func TestHTTP_ZeroLengthEndedByAnEmptyDataFrameEndsWithItsHeadersOverHTTP2(t *testing.T) {
eachDeclaredFront(t, func(t *testing.T, front string) {
o := prefaceOrigin(t, respondH2)
h := h2cStream(t, front, o, false, "POST", hf("content-length", "0"))
// The response to stream 3 shows the handler of stream 1 started before its DATA frame.
h.headers(t, 3, true, hf(":method", "GET"), hf(":scheme", "http"), hf(":authority", "origin.test"), hf(":path", "/"))
require.Equal(t, "ok", string(h.reply(t, 3).body))
require.NoError(t, h.fr.WriteData(1, true, nil))
assert.Equal(t, "ok", string(h.reply(t, 1).body))
require.Equal(t, http2.ClientPreface, o.nextNote(t))
require.Equal(t, "SETTINGS stream=0 ack=false", o.nextNote(t))
assert.Equal(t, `HEADERS stream=1 end_stream=true content-length=""`, o.nextNote(t))
assert.Equal(t, `HEADERS stream=3 end_stream=true content-length="0"`, o.nextNote(t))
})
}
func TestHTTP_ZeroLengthFromHTTP3EndsWithItsHeadersOverHTTP2(t *testing.T) {
b := newH2OriginBench(t, respondH2)
got := b.dialH3Front(t).roundTrip(t, h3Request("POST", "origin.test", "/", hf("content-length", "0")))
require.NoError(t, got.err)
assert.Equal(t, "ok", string(got.body))
require.Equal(t, "SETTINGS stream=0 ack=false", b.origin.nextNote(t))
assert.Equal(t, `HEADERS stream=1 end_stream=true content-length="0"`, b.origin.nextNote(t))
}
func TestHTTP_ZeroLengthEndsWithItsHeadersOverHTTP3(t *testing.T) {
b := newH3OriginBench(t, func(o *rawOrigin, _ *h3Conn, s *h3Stream) {
for {
typ, payload, err := s.next()
if err != nil {
o.note(fmt.Sprintf("end %v", err))
break
}
switch typ {
case h3FrameHeaders:
fields, _ := qpackFields(payload)
cl, _ := h2Field(fields, "content-length")
o.note(fmt.Sprintf("HEADERS content-length=%q", cl))
case h3FrameData:
o.note(fmt.Sprintf("DATA len=%d", len(payload)))
}
}
if _, err := s.Write(slices.Concat(h3Headers([]hpack.HeaderField{hf(":status", "200")}), h3Data("ok"))); err == nil {
_ = s.Close()
}
})
got := b.dialH3Front(t).roundTrip(t, h3Request("POST", "origin.test", "/", hf("content-length", "0")))
require.NoError(t, got.err)
assert.Equal(t, "ok", string(got.body))
assert.Equal(t, `HEADERS content-length="0"`, b.origin.nextNote(t))
assert.Equal(t, "end EOF", b.origin.nextNote(t), "a DATA frame followed the header section")
}
func TestHTTP_CompleteResponseStopsTheClientWithNoErrorOverHTTP3(t *testing.T) {
b := newH2OriginBench(t, respondH2)
s := b.dialH3Front(t).open(t, h3Request("POST", "origin.test", "/"), h3Data("a"))
m := s.message(true)
require.NoError(t, m.err)
assert.Equal(t, "200", m.status())
assert.Equal(t, "ok", string(m.body))
assert.Equal(t, http3.ErrCodeNoError, stopSending(t, s, h3Data("b")))
}
func TestHTTP_ResetOfTheRequestStreamResetsTheResponseOverHTTP3(t *testing.T) {
b := newH2OriginBench(t, func(o *rawOrigin, _ *wire, fr *http2.Framer) {
f, err := fr.ReadFrame()
if err != nil || !isSettings(f) || fr.WriteSettings() != nil || fr.WriteSettingsAck() != nil {
return
}
for {
f, err := fr.ReadFrame()
if err != nil {
return
}
switch f := f.(type) {
case *http2.SettingsFrame:
if !f.IsAck() {
_ = fr.WriteSettingsAck()
}
case *http2.DataFrame:
if len(f.Data()) > 0 {
o.note("DATA")
}
case *http2.RSTStreamFrame:
o.note("RST_STREAM " + f.ErrCode.String())
}
}
})
s := b.dialH3Front(t).open(t, h3Request("POST", "origin.test", "/"), h3Data("a"))
require.Equal(t, "DATA", b.origin.nextNote(t))
s.CancelWrite(quic.StreamErrorCode(http3.ErrCodeRequestCanceled))
m := s.message(true)
code, ok := h3ErrCode(m.err)
require.True(t, ok, "the response ended with %v", m.err)
assert.Equal(t, http3.ErrCodeInternalError, code, "quic-go gives a reset before the response header no other code")
assert.Nil(t, m.fields, "a response preceded the reset")
assert.Equal(t, "RST_STREAM CANCEL", b.origin.nextNote(t))
}
func TestHTTP_HTTP3TrailerSectionRefusedByQUICGoIsMalformed(t *testing.T) {
for _, tc := range []struct {
name string
field hpack.HeaderField
}{
{name: "name with a space", field: hf("x check", "sum")},
{name: "value with a NUL", field: hf("x-check", "s\x00m")},
{name: "field not allowed in trailers", field: hf("content-length", "1")},
} {
t.Run(tc.name, func(t *testing.T) {
b := newTLSProxyBench(t, always(okReply))
got := b.dialH3Front(t).roundTrip(t, h3Request("POST", "origin.test", "/"), h3Data("a"), h3Headers([]hpack.HeaderField{tc.field}))
require.NoError(t, got.err)
assert.Equal(t, strconv.Itoa(http.StatusBadRequest), got.status())
})
}
}
func TestHTTP_AnnouncesTETrailersOverHTTP2(t *testing.T) {
origin := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "te=%s proto=%s", r.Header.Get("Te"), r.Proto)
}))
origin.EnableHTTP2 = true
origin.StartTLS()
defer origin.Close()
originURL, _ := url.Parse(origin.URL)
ca, _ := GenerateCA()
tr := DefaultTransport()
tr.RootCAs = originPool(t, origin)
p, err := New(WithCA(ca), WithTransport(tr))
if err != nil {
t.Fatalf("new proxy: %v", err)
}
p.MustAdd(originHost(originURL)+"/*{any}", forwardHandler)
addr := startProxy(t, p)
client := h2Client(addr, ca.CertPool())
req, err := http.NewRequest(http.MethodGet, origin.URL+"/", nil)
if err != nil {
t.Fatalf("new request: %v", err)
}
req.Header.Set("TE", "trailers")
resp, err := client.Do(req)
if err != nil {
t.Fatalf("get through proxy: %v", err)
}
defer func() { _ = resp.Body.Close() }()
body, _ := io.ReadAll(resp.Body)
if string(body) != "te=trailers proto=HTTP/2.0" {
t.Fatalf("origin saw %q, want te=trailers proto=HTTP/2.0", body)
}
}
func TestHTTP_HeadHasNoBody(t *testing.T) {
origin := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Length", "5")
if r.Method != http.MethodHead {
_, _ = w.Write([]byte("hello"))
}
}))
defer origin.Close()
_, _, client := interceptingProxy(t, origin)
resp, err := client.Head(origin.URL + "/")
require.NoError(t, err)
defer func() { _ = resp.Body.Close() }()
body, err := io.ReadAll(resp.Body)
require.NoError(t, err)
assert.Empty(t, body)
assert.Equal(t, "5", resp.Header.Get("Content-Length"))
}
func TestHTTP_NoContentAndNotModified(t *testing.T) {
origin := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch r.URL.Path {
case "/204":
w.WriteHeader(http.StatusNoContent)
case "/304":
w.WriteHeader(http.StatusNotModified)
}
}))
defer origin.Close()
_, _, client := interceptingProxy(t, origin)
for _, path := range []string{"/204", "/304"} {
resp, err := client.Get(origin.URL + path)
require.NoError(t, err, path)
body, err := io.ReadAll(resp.Body)
require.NoError(t, err)
_ = resp.Body.Close()
assert.Empty(t, body, path)
}
}
func TestHTTP_RequestBodyStreams(t *testing.T) {
const size = 4 << 20
origin := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
n, err := io.Copy(io.Discard, r.Body)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
fmt.Fprintf(w, "received %d", n)
}))
defer origin.Close()
_, _, client := interceptingProxy(t, origin)
body := bytes.Repeat([]byte("x"), size)
resp, err := client.Post(origin.URL+"/upload", "application/octet-stream", bytes.NewReader(body))
require.NoError(t, err)
defer func() { _ = resp.Body.Close() }()
got, _ := io.ReadAll(resp.Body)
assert.Equal(t, fmt.Sprintf("received %d", size), string(got))
}
func TestHTTP_ContentEncodingIsNotTouched(t *testing.T) {
var payload bytes.Buffer
zw := gzip.NewWriter(&payload)
_, _ = zw.Write([]byte("compressed payload"))
require.NoError(t, zw.Close())
origin := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if !strings.Contains(r.Header.Get("Accept-Encoding"), "gzip") {
http.Error(w, "proxy dropped or rewrote Accept-Encoding", http.StatusBadRequest)
return
}
w.Header().Set("Content-Encoding", "gzip")
w.Header().Set("Content-Type", "text/plain")
_, _ = w.Write(payload.Bytes())
}))
defer origin.Close()
_, _, client := interceptingProxy(t, origin)
req, err := http.NewRequest(http.MethodGet, origin.URL+"/gz", nil)
require.NoError(t, err)
req.Header.Set("Accept-Encoding", "gzip")
resp, err := client.Do(req)
require.NoError(t, err)
defer func() { _ = resp.Body.Close() }()
// The client asked for gzip, so it must get gzip: a proxy that decompresses on the way
// through changes what the application under test observes.
assert.Equal(t, "gzip", resp.Header.Get("Content-Encoding"))
raw, _ := io.ReadAll(resp.Body)
assert.Equal(t, payload.Bytes(), raw)
}
func TestHTTP_HopByHopHeadersAreStripped(t *testing.T) {
origin := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
var leaked []string
for _, h := range []string{"Proxy-Connection", "Keep-Alive", "X-Hop", "Connection"} {
if r.Header.Get(h) != "" {
leaked = append(leaked, h)
}
}
fmt.Fprintf(w, "leaked=%s", strings.Join(leaked, ","))
}))
defer origin.Close()
_, _, client := interceptingProxy(t, origin)
req, _ := http.NewRequest(http.MethodGet, origin.URL+"/", nil)
req.Header.Set("Proxy-Connection", "keep-alive")
req.Header.Set("Keep-Alive", "timeout=5")
// A header named in Connection is hop-by-hop by declaration and must go too.
req.Header.Set("Connection", "X-Hop")
req.Header.Set("X-Hop", "secret")
resp, err := client.Do(req)
require.NoError(t, err)
defer func() { _ = resp.Body.Close() }()
body, _ := io.ReadAll(resp.Body)
assert.Equal(t, "leaked=", string(body))
}
func TestHTTP_TETrailersIsAnnouncedForTheProxy(t *testing.T) {
origin := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "te=%s", strings.Join(r.Header.Values("Te"), "|"))
}))
defer origin.Close()
_, _, client := interceptingProxy(t, origin)
cases := []struct {
name string
conn string
want string
sent []string
}{
{name: "nothing announced", want: "te="},
{name: "trailers", sent: []string{"trailers"}, want: "te=trailers"},
{name: "transfer coding only", sent: []string{"gzip"}, want: "te="},
{name: "trailers among codings", sent: []string{"gzip", "trailers"}, want: "te=trailers"},
{name: "listed in connection", sent: []string{"trailers"}, conn: "TE", want: "te=trailers"},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
req, err := http.NewRequest(http.MethodGet, origin.URL+"/", nil)
require.NoError(t, err)
for _, v := range tc.sent {
req.Header.Add("TE", v)
}
if tc.conn != "" {
req.Header.Set("Connection", tc.conn)
}
resp, err := client.Do(req)
require.NoError(t, err)
defer func() { _ = resp.Body.Close() }()
body, _ := io.ReadAll(resp.Body)
// TE stops at the first hop, so the proxy makes the announcement for itself
// rather than relaying the client's. A transfer coding it does not implement is
// not announced at all.
assert.Equal(t, tc.want, string(body))
})
}
}
func TestHTTP_HandlerPanicBecomesAnError(t *testing.T) {
origin := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, "origin")
}))
defer origin.Close()
p, authority, client := interceptingProxy(t, origin)
p.MustAdd(authority+"/boom", func(c *HTTPCtx) (*http.Response, error) {
panic("handler exploded")
}, WithMethods[HTTP](http.MethodGet))
p.MustAdd(authority+"/fine", func(c *HTTPCtx) (*http.Response, error) {
return Text(http.StatusOK, "still alive"), nil
}, WithMethods[HTTP](http.MethodGet))
resp, err := client.Get(origin.URL + "/boom")
require.NoError(t, err)
body, _ := io.ReadAll(resp.Body)
_ = resp.Body.Close()
assert.Equal(t, http.StatusInternalServerError, resp.StatusCode,
"a panic is a failure of the proxy, not an answer from the upstream")
assert.Equal(t, http.StatusText(http.StatusInternalServerError), string(body), "the client learns the status and nothing else")
// The connection must survive: an application under test should not see a transport
// failure because a handler had a bug.
resp, err = client.Get(origin.URL + "/fine")
require.NoError(t, err)
body, _ = io.ReadAll(resp.Body)
_ = resp.Body.Close()
assert.Equal(t, "still alive", string(body))
}
func TestHTTP_PanicReachesTheErrorHandler(t *testing.T) {
origin := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {}))
defer origin.Close()
sentinel := errors.New("boom")
var got *PanicError
p, authority, client := interceptingProxy(t, origin, WithErrorHandler(func(c *HTTPCtx, err error) *http.Response {
got, _ = errors.AsType[*PanicError](err)
return Status(http.StatusTeapot)
}))
p.MustAdd(authority+"/boom", func(c *HTTPCtx) (*http.Response, error) {
panic(sentinel)
}, WithMethods[HTTP](http.MethodGet))
resp, err := client.Get(origin.URL + "/boom")
require.NoError(t, err)
_ = resp.Body.Close()
assert.Equal(t, http.StatusTeapot, resp.StatusCode)
require.NotZero(t, got)
assert.Equal(t, sentinel, got.Value)
assert.ErrorIs(t, got, sentinel, "a panic carrying an error stays reachable through Unwrap")
assert.Contains(t, got.Stack, "TestHTTP_PanicReachesTheErrorHandler",
"the first frame captured must be the one that panicked")
}
func TestHTTP_ErrorHandler(t *testing.T) {
origin := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {}))
defer origin.Close()
sentinel := errors.New("upstream refused")
p, authority, client := interceptingProxy(t, origin, WithErrorHandler(func(c *HTTPCtx, err error) *http.Response {
if errors.Is(err, sentinel) {
return Text(http.StatusServiceUnavailable, "handled: "+err.Error())
}
return Status(http.StatusBadGateway)
}))
p.MustAdd(authority+"/fail", func(c *HTTPCtx) (*http.Response, error) {
return nil, sentinel
}, WithMethods[HTTP](http.MethodGet))
resp, err := client.Get(origin.URL + "/fail")
require.NoError(t, err)
defer func() { _ = resp.Body.Close() }()
assert.Equal(t, http.StatusServiceUnavailable, resp.StatusCode)
body, _ := io.ReadAll(resp.Body)
assert.Equal(t, "handled: upstream refused", string(body))
}
func TestHTTP_MalformedRequestOverEachUpstream(t *testing.T) {
t.Run("h1", func(t *testing.T) {
b := newProxyBench(t, always(okReply))
w := b.dial(t)
w.send(t, "POST http://origin.test/ HTTP/1.1\r\nHost: origin.test\r\nContent-Length: 10\r\n\r\nabcd")
require.NoError(t, w.Conn.(*net.TCPConn).CloseWrite())
assert.Equal(t, http.StatusBadRequest, w.readResponse(t, "POST").resp.StatusCode)
})
t.Run("h3", func(t *testing.T) {
b := newH3OriginBench(t, func(_ *rawOrigin, _ *h3Conn, s *h3Stream) {
if s.message(false).err != nil {
s.CancelWrite(quic.StreamErrorCode(http3.ErrCodeRequestIncomplete))
return
}
_, _ = s.Write(h3Headers([]hpack.HeaderField{hf(":status", "200")}))
_ = s.Close()
})
h := b.dialH3Front(t)
got := h.roundTrip(t, h3Request("POST", "origin.test", "/", hf("content-length", "10")), h3Data("abcd"))
require.NoError(t, got.err)
assert.Equal(t, "400", got.status())
})
}
func TestHTTP_MalformedRequestReachesTheErrorHandler(t *testing.T) {
o := newRawOrigin(t, always(okReply))
tr := DefaultTransport()
tr.DialContext = pinnedDialer(o.addr)
got := make(chan error, 1)
p := testProxy(t, WithTransport(tr), WithErrorHandler(func(_ *HTTPCtx, err error) *http.Response {
got <- err
return Status(http.StatusTeapot)
}))
p.MustAdd("origin.test/*{any}", forwardHandler)
w := dialWire(t, startProxy(t, p))
w.send(t, "POST http://origin.test/ HTTP/1.1\r\nHost: origin.test\r\nContent-Length: 10\r\n\r\nabcd")
require.NoError(t, w.Conn.(*net.TCPConn).CloseWrite())
assert.Equal(t, http.StatusTeapot, w.readResponse(t, "POST").resp.StatusCode)
err := <-got
require.Error(t, err)
assert.NotContains(t, err.Error(), "malformed")
}
func TestHTTP_ClientCancelIsNotMalformed(t *testing.T) {
o := newRawOrigin(t, func(o *rawOrigin, w *wire) {
req, err := http.ReadRequest(w.br)
if err != nil {
return
}
o.note(req.Method)
_, _ = io.ReadAll(req.Body)
})
tr := DefaultTransport()
tr.DialContext = pinnedDialer(o.addr)
got := make(chan error, 1)
p := testProxy(t, WithTransport(tr), WithErrorHandler(func(_ *HTTPCtx, err error) *http.Response {
got <- err
return Status(http.StatusTeapot)
}))
p.MustAdd("origin.test/*{any}", forwardHandler)
h := dialH2(t, startProxy(t, p))
h.headers(t, 1, false, hf(":method", "POST"), hf(":scheme", "http"), hf(":authority", "origin.test"), hf(":path", "/"),
hf("content-length", "10"))
require.NoError(t, h.fr.WriteData(1, false, []byte("abcd")))
require.Equal(t, "POST", o.nextNote(t))
require.NoError(t, h.fr.WriteRSTStream(1, http2.ErrCodeCancel))
select {
case err := <-got:
assert.NotErrorIs(t, err, errMalformedRequest)
case <-time.After(5 * time.Second):
t.Fatal("the forward did not fail")
}
}
func TestHTTP_FailedBodyOfTheHandlerIsBadGateway(t *testing.T) {
b := newProxyBench(t, always(okReply))
b.p.MustAdd("origin.test/own", func(c *HTTPCtx) (*http.Response, error) {
r := c.Request()
r.Body = io.NopCloser(io.MultiReader(strings.NewReader("ab"), iotest.ErrReader(errors.New("handler body failed"))))
r.ContentLength = 10
return c.Forward()
})
got := b.exchange(t, "POST", "POST http://origin.test/own HTTP/1.1\r\nHost: origin.test\r\nContent-Length: 2\r\n\r\nok")
assert.Equal(t, http.StatusBadGateway, got.resp.StatusCode)
}
func TestHTTP_MiddlewareOrder(t *testing.T) {
origin := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {}))
defer origin.Close()
var order []string
record := func(name string) Middleware[HTTP] {
return func(next HTTP) HTTP {
return func(c *HTTPCtx) (*http.Response, error) {
order = append(order, "→"+name)
resp, err := next(c)
order = append(order, "←"+name)
return resp, err
}
}
}
p, authority, client := interceptingProxy(t, origin, WithMiddleware(record("outer"), record("inner")))
p.MustAdd(authority+"/x", func(c *HTTPCtx) (*http.Response, error) {
order = append(order, "handler")
return Status(http.StatusOK), nil
}, WithMiddleware(record("interceptor")), WithMethods[HTTP](http.MethodGet))
resp, err := client.Get(origin.URL + "/x")
require.NoError(t, err)
_ = resp.Body.Close()
assert.Equal(t, []string{"→outer", "→inner", "→interceptor", "handler", "←interceptor", "←inner", "←outer"}, order)
}
func TestHTTP_NoInterceptorForwardsUnchanged(t *testing.T) {
origin := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "origin got %s", r.URL.Path)
}))
defer origin.Close()
p, authority, client := interceptingProxy(t, origin)
p.MustAdd(authority+"/known", func(c *HTTPCtx) (*http.Response, error) {
return Text(http.StatusOK, "handled"), nil
}, WithMethods[HTTP](http.MethodGet))
resp, err := client.Get(origin.URL + "/unknown")
require.NoError(t, err)
defer func() { _ = resp.Body.Close() }()
body, _ := io.ReadAll(resp.Body)
assert.Equal(t, "origin got /unknown", string(body))
}
func TestHTTP_RawPathIsPreserved(t *testing.T) {
var seen string
origin := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
seen = r.RequestURI
fmt.Fprint(w, "ok")
}))
defer origin.Close()
originURL, err := url.Parse(origin.URL)
require.NoError(t, err)
ca, err := GenerateCA()
require.NoError(t, err)
tr := DefaultTransport()
tr.RootCAs = originPool(t, origin)
p, err := New(WithCA(ca), WithTransport(tr))
require.NoError(t, err)
var routed string
p.MustAdd(originHost(originURL)+"/*{any}", func(c *HTTPCtx) (*http.Response, error) {
routed = c.RoutingPath()
return c.Forward()
}, WithMethods[HTTP](http.MethodGet))
client := proxyClient(startProxy(t, p), ca.CertPool())
cases := []struct{ wire, wantRouted string }{
{"/v1/charges", "/v1/charges"},
// %2F stays encoded on the wire and is never matched as a path separator.
{"/files/a%2Fb?q=1%2B2", "/files/a%2Fb"},
{"/v1%2fcharges", "/v1%2Fcharges"},
// An escaped unreserved character is decoded for matching, not on the wire.
{"/v1/%63harges", "/v1/charges"},
{"/v1/%2e%2e/charges", "/v1/../charges"},
// Nothing collapses a dot segment or a double slash, in either direction.
{"//v1/./sub/../charges", "//v1/./sub/../charges"},
{"/v1/charges;x=1", "/v1/charges;x=1"},
}
for _, tc := range cases {
seen, routed = "", ""
resp, err := client.Get(origin.URL + tc.wire)
require.NoError(t, err, tc.wire)
_ = resp.Body.Close()
assert.Equal(t, tc.wire, seen, "the request target must reach the origin byte for byte")
assert.Equal(t, tc.wantRouted, routed, "routing form of %q", tc.wire)
}
}
func TestConformanceProxy(t *testing.T) {
runConformance(t, proxyConformance)
}
// wire reads HTTP/1.1 messages off a connection and keeps every byte it read, so a message is
// checked as it crossed the wire.
type wire struct {
net.Conn
br *bufio.Reader
rec bytes.Buffer
// originForm rewrites every absolute-form request line sent to origin-form.
originForm bool
}
func newWire(c net.Conn) *wire {
w := &wire{Conn: c}
w.br = bufio.NewReader(io.TeeReader(c, &w.rec))
return w
}
func dialWire(t *testing.T, addr string) *wire {
t.Helper()
c, err := net.DialTimeout("tcp", addr, 5*time.Second)
require.NoError(t, err)
t.Cleanup(func() { _ = c.Close() })
require.NoError(t, c.SetDeadline(time.Now().Add(10*time.Second)))
return newWire(c)
}
func (w *wire) consumed() int { return w.rec.Len() - w.br.Buffered() }
func (w *wire) headFrom(start int) string {
raw := w.rec.Bytes()[start:]
if i := bytes.Index(raw, []byte("\r\n\r\n")); i >= 0 {
return string(raw[:i+4])
}
return string(raw)
}
// absoluteTarget matches the method, the scheme and the authority of an absolute-form request
// line.
var absoluteTarget = regexp.MustCompile(`(?m)^([A-Z]+) https?://[^/?# \r\n]*/?`)
func (w *wire) send(t *testing.T, s string) {
t.Helper()
if w.originForm {
s = absoluteTarget.ReplaceAllString(s, "${1} /")
}
_, err := io.WriteString(w.Conn, s)
require.NoError(t, err)
}
type wireRequest struct {
req *http.Request
head string
body []byte
}
func (w *wire) readRequest() (wireRequest, error) {
start := w.consumed()
req, err := http.ReadRequest(w.br)
if err != nil {
return wireRequest{}, err
}
body, err := io.ReadAll(req.Body)
if err != nil {
return wireRequest{}, err
}
return wireRequest{head: w.headFrom(start), req: req, body: body}, nil
}
type wireResponse struct {
resp *http.Response
err error
head string
body []byte
}
func (w *wire) readResponse(t *testing.T, method string) wireResponse {
t.Helper()
start := w.consumed()
resp, err := http.ReadResponse(w.br, &http.Request{Method: method})
require.NoError(t, err)
body, berr := io.ReadAll(resp.Body)
return wireResponse{head: w.headFrom(start), resp: resp, body: body, err: berr}
}
// readHead reads a header section and nothing past it, for an answer to CONNECT whose
// framing fields the client must ignore.
func (w *wire) readHead(t *testing.T) string {
t.Helper()
start := w.consumed()
for {
line, err := w.br.ReadString('\n')
require.NoError(t, err)
if line == "\r\n" {