-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathmain_test.go
More file actions
1040 lines (936 loc) · 27.8 KB
/
Copy pathmain_test.go
File metadata and controls
1040 lines (936 loc) · 27.8 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 main
import (
"bytes"
"compress/gzip"
"compress/zlib"
"encoding/json"
"flag"
"fmt"
"io"
"log"
"net/http"
"net/http/httptest"
"os"
"runtime"
"strings"
"testing"
"github.com/andybalholm/brotli"
)
// The configuration variables are package-level and shared, so every test that
// changes one must restore it. These helpers make that automatic: restoring by
// hand is what previously leaked state between tests and made the suite
// order-dependent.
// setBool sets a package-level bool for the duration of the test.
func setBool(t *testing.T, target *bool, v bool) {
t.Helper()
orig := *target
t.Cleanup(func() { *target = orig })
*target = v
}
// setString sets a package-level string for the duration of the test.
func setString(t *testing.T, target *string, v string) {
t.Helper()
orig := *target
t.Cleanup(func() { *target = orig })
*target = v
}
// setNoColor controls color output for the duration of the test.
func setNoColor(t *testing.T, v bool) {
t.Helper()
setBool(t, &noColor, v)
}
// compressGzip returns gzip-compressed bytes.
func compressGzip(t *testing.T, data []byte) []byte {
t.Helper()
var buf bytes.Buffer
w := gzip.NewWriter(&buf)
if _, err := w.Write(data); err != nil {
t.Fatal(err)
}
if err := w.Close(); err != nil {
t.Fatal(err)
}
return buf.Bytes()
}
// compressDeflate returns zlib-compressed bytes.
func compressDeflate(t *testing.T, data []byte) []byte {
t.Helper()
var buf bytes.Buffer
w := zlib.NewWriter(&buf)
if _, err := w.Write(data); err != nil {
t.Fatal(err)
}
if err := w.Close(); err != nil {
t.Fatal(err)
}
return buf.Bytes()
}
// compressBrotli returns brotli-compressed bytes.
func compressBrotli(t *testing.T, data []byte) []byte {
t.Helper()
var buf bytes.Buffer
w := brotli.NewWriter(&buf)
if _, err := w.Write(data); err != nil {
t.Fatal(err)
}
if err := w.Close(); err != nil {
t.Fatal(err)
}
return buf.Bytes()
}
func TestDecodeBody(t *testing.T) {
original := []byte("hello, world!")
tests := []struct {
name string
encoding string
body []byte
want string
wantErr bool
}{
{
name: "gzip",
encoding: "gzip",
body: compressGzip(t, original),
want: "hello, world!",
},
{
name: "gzip with whitespace",
encoding: " Gzip ",
body: compressGzip(t, original),
want: "hello, world!",
},
{
name: "deflate",
encoding: "deflate",
body: compressDeflate(t, original),
want: "hello, world!",
},
{
name: "brotli",
encoding: "br",
body: compressBrotli(t, original),
want: "hello, world!",
},
{
name: "no encoding",
encoding: "",
body: original,
want: "hello, world!",
},
{
name: "unknown encoding",
encoding: "identity",
body: original,
want: "hello, world!",
},
{
name: "invalid gzip data",
encoding: "gzip",
body: []byte("not gzip"),
wantErr: true,
},
{
name: "invalid deflate data",
encoding: "deflate",
body: []byte("not deflate"),
wantErr: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got, err := decodeBody(tt.encoding, tt.body)
if tt.wantErr {
if err == nil {
t.Error("expected error, got nil")
}
return
}
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if string(got) != tt.want {
t.Errorf("got %q, want %q", string(got), tt.want)
}
})
}
}
func TestRoundTrip(t *testing.T) {
setNoColor(t, true)
t.Run("proxies response correctly", func(t *testing.T) {
upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
_, _ = fmt.Fprint(w, `{"status":"ok"}`)
}))
defer upstream.Close()
transport := DebugTransport{}
req, err := http.NewRequest(http.MethodGet, upstream.URL+"/test", nil)
if err != nil {
t.Fatal(err)
}
resp, err := transport.RoundTrip(req)
if err != nil {
t.Fatalf("RoundTrip failed: %v", err)
}
defer func() { _ = resp.Body.Close() }()
if resp.StatusCode != http.StatusOK {
t.Errorf("got status %d, want %d", resp.StatusCode, http.StatusOK)
}
body, err := io.ReadAll(resp.Body)
if err != nil {
t.Fatal(err)
}
if string(body) != `{"status":"ok"}` {
t.Errorf("body not preserved for proxying: got %q", string(body))
}
})
t.Run("proxies gzip response", func(t *testing.T) {
original := `{"compressed":true}`
compressed := compressGzip(t, []byte(original))
upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
w.Header().Set("Content-Encoding", "gzip")
w.WriteHeader(http.StatusOK)
_, _ = w.Write(compressed)
}))
defer upstream.Close()
transport := DebugTransport{}
req, err := http.NewRequest(http.MethodGet, upstream.URL, nil)
if err != nil {
t.Fatal(err)
}
resp, err := transport.RoundTrip(req)
if err != nil {
t.Fatalf("RoundTrip failed: %v", err)
}
defer func() { _ = resp.Body.Close() }()
// Go's DefaultTransport auto-decompresses gzip and strips Content-Encoding,
// so the body available to the client is already decompressed.
body, err := io.ReadAll(resp.Body)
if err != nil {
t.Fatal(err)
}
if string(body) != original {
t.Errorf("got %q, want %q", string(body), original)
}
})
t.Run("handles POST with request body", func(t *testing.T) {
var receivedBody string
upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
b, _ := io.ReadAll(r.Body)
receivedBody = string(b)
w.WriteHeader(http.StatusCreated)
_, _ = fmt.Fprint(w, "created")
}))
defer upstream.Close()
transport := DebugTransport{}
req, err := http.NewRequest(http.MethodPost, upstream.URL, strings.NewReader(`{"name":"test"}`))
if err != nil {
t.Fatal(err)
}
req.Header.Set("Content-Type", "application/json")
resp, err := transport.RoundTrip(req)
if err != nil {
t.Fatalf("RoundTrip failed: %v", err)
}
defer func() { _ = resp.Body.Close() }()
if resp.StatusCode != http.StatusCreated {
t.Errorf("got status %d, want %d", resp.StatusCode, http.StatusCreated)
}
if receivedBody != `{"name":"test"}` {
t.Errorf("upstream received %q, want %q", receivedBody, `{"name":"test"}`)
}
})
t.Run("handles upstream error", func(t *testing.T) {
transport := DebugTransport{}
req, err := http.NewRequest(http.MethodGet, "http://127.0.0.1:1", nil)
if err != nil {
t.Fatal(err)
}
_, err = transport.RoundTrip(req)
if err == nil {
t.Error("expected error for unreachable upstream, got nil")
}
})
t.Run("large body triggers truncation message", func(t *testing.T) {
// Create a response body larger than maxLogBodySize
largeBody := strings.Repeat("x", maxLogBodySize+1)
upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/plain")
w.WriteHeader(http.StatusOK)
_, _ = fmt.Fprint(w, largeBody)
}))
defer upstream.Close()
transport := DebugTransport{}
req, err := http.NewRequest(http.MethodGet, upstream.URL, nil)
if err != nil {
t.Fatal(err)
}
resp, err := transport.RoundTrip(req)
if err != nil {
t.Fatalf("RoundTrip failed: %v", err)
}
defer func() { _ = resp.Body.Close() }()
// Body should still be fully preserved for the client
body, err := io.ReadAll(resp.Body)
if err != nil {
t.Fatal(err)
}
if len(body) != maxLogBodySize+1 {
t.Errorf("body length = %d, want %d", len(body), maxLogBodySize+1)
}
})
t.Run("logging flags are respected", func(t *testing.T) {
upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
}))
defer upstream.Close()
// Disable both logging flags
setBool(t, &logRequests, false)
setBool(t, &logResponses, false)
transport := DebugTransport{}
req, err := http.NewRequest(http.MethodGet, upstream.URL, nil)
if err != nil {
t.Fatal(err)
}
resp, err := transport.RoundTrip(req)
if err != nil {
t.Fatalf("RoundTrip failed: %v", err)
}
_ = resp.Body.Close()
// No assertion on log output — just verify it doesn't panic with logging disabled
})
}
func TestGetEnv(t *testing.T) {
tests := []struct {
name string
key string
envVal string
setEnv bool
fallback string
want string
}{
{
name: "returns env value when set",
key: "TEST_HTTP_PROXY_LOGGER_VAR",
envVal: "from-env",
setEnv: true,
fallback: "default",
want: "from-env",
},
{
name: "returns fallback when not set",
key: "TEST_HTTP_PROXY_LOGGER_UNSET",
setEnv: false,
fallback: "default",
want: "default",
},
{
name: "returns empty string when env is empty",
key: "TEST_HTTP_PROXY_LOGGER_EMPTY",
envVal: "",
setEnv: true,
fallback: "default",
want: "",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if tt.setEnv {
t.Setenv(tt.key, tt.envVal)
} else {
_ = os.Unsetenv(tt.key)
}
got := getEnv(tt.key, tt.fallback)
if got != tt.want {
t.Errorf("getEnv(%q, %q) = %q, want %q", tt.key, tt.fallback, got, tt.want)
}
})
}
}
func TestGetListenAddress(t *testing.T) {
setString(t, &cliPort, "")
t.Run("uses CLI flag when set", func(t *testing.T) {
cliPort = "9090"
got := getListenAddress()
if got != ":9090" {
t.Errorf("got %q, want %q", got, ":9090")
}
})
t.Run("uses env when flag is empty", func(t *testing.T) {
cliPort = ""
t.Setenv("PORT", "8080")
got := getListenAddress()
if got != ":8080" {
t.Errorf("got %q, want %q", got, ":8080")
}
})
t.Run("uses default when both empty", func(t *testing.T) {
cliPort = ""
_ = os.Unsetenv("PORT")
got := getListenAddress()
if got != ":1338" {
t.Errorf("got %q, want %q", got, ":1338")
}
})
}
func TestGetTarget(t *testing.T) {
setString(t, &cliTarget, "")
t.Run("uses CLI flag when set", func(t *testing.T) {
cliTarget = "http://myserver.com"
got := getTarget()
if got != "http://myserver.com" {
t.Errorf("got %q, want %q", got, "http://myserver.com")
}
})
t.Run("uses env when flag is empty", func(t *testing.T) {
cliTarget = ""
t.Setenv("TARGET", "http://envserver.com")
got := getTarget()
if got != "http://envserver.com" {
t.Errorf("got %q, want %q", got, "http://envserver.com")
}
})
t.Run("uses default when both empty", func(t *testing.T) {
cliTarget = ""
_ = os.Unsetenv("TARGET")
got := getTarget()
if got != "http://example.com" {
t.Errorf("got %q, want %q", got, "http://example.com")
}
})
}
func TestRoundTripPreservesJSONBody(t *testing.T) {
// Verify that JSON response body is preserved exactly for proxying,
setNoColor(t, true)
payload := map[string]interface{}{
"users": []interface{}{
map[string]interface{}{"id": float64(1), "name": "Alice"},
map[string]interface{}{"id": float64(2), "name": "Bob"},
},
}
responseJSON, _ := json.Marshal(payload)
upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
_, _ = w.Write(responseJSON)
}))
defer upstream.Close()
transport := DebugTransport{}
req, err := http.NewRequest(http.MethodGet, upstream.URL, nil)
if err != nil {
t.Fatal(err)
}
resp, err := transport.RoundTrip(req)
if err != nil {
t.Fatalf("RoundTrip failed: %v", err)
}
defer func() { _ = resp.Body.Close() }()
body, err := io.ReadAll(resp.Body)
if err != nil {
t.Fatal(err)
}
if !bytes.Equal(body, responseJSON) {
t.Errorf("JSON body not preserved.\ngot: %s\nwant: %s", body, responseJSON)
}
}
// captureLog redirects the standard logger into a buffer for the duration of
// the test, so log notices can be asserted on and test output stays quiet.
func captureLog(t *testing.T) *bytes.Buffer {
t.Helper()
var buf bytes.Buffer
origOut, origFlags := log.Writer(), log.Flags()
log.SetOutput(&buf)
log.SetFlags(0)
t.Cleanup(func() {
log.SetOutput(origOut)
log.SetFlags(origFlags)
})
return &buf
}
// fakeTransport returns a canned response instead of contacting a server.
type fakeTransport struct {
response *http.Response
}
func (f fakeTransport) RoundTrip(*http.Request) (*http.Response, error) {
return f.response, nil
}
// recordingConn is a response body that records how it was used. It implements
// io.ReadWriteCloser so it can stand in for a hijacked connection.
type recordingConn struct {
readCalled bool
closeCount int
}
func (c *recordingConn) Read([]byte) (int, error) { c.readCalled = true; return 0, io.EOF }
func (c *recordingConn) Write(p []byte) (int, error) { return len(p), nil }
func (c *recordingConn) Close() error { c.closeCount++; return nil }
// roundTripCanned runs a canned response through DebugTransport.
func roundTripCanned(t *testing.T, response *http.Response) (*http.Response, error) {
t.Helper()
req, err := http.NewRequest(http.MethodGet, "http://example.invalid/", nil)
if err != nil {
t.Fatal(err)
}
return DebugTransport{Transport: fakeTransport{response: response}}.RoundTrip(req)
}
func TestRoundTripDoesNotBufferStreamingResponses(t *testing.T) {
setNoColor(t, true)
setBool(t, &logRequests, false)
tests := []struct {
name string
response *http.Response
wantNotice string
}{
{
name: "protocol upgrade",
response: &http.Response{
StatusCode: http.StatusSwitchingProtocols,
Status: "101 Switching Protocols",
Proto: "HTTP/1.1", ProtoMajor: 1, ProtoMinor: 1,
Header: http.Header{"Upgrade": {"websocket"}},
},
wantNotice: "[connection upgraded: body not captured]",
},
{
name: "server-sent events",
response: &http.Response{
StatusCode: http.StatusOK,
Status: "200 OK",
Proto: "HTTP/1.1", ProtoMajor: 1, ProtoMinor: 1,
Header: http.Header{"Content-Type": {"text/event-stream"}},
},
wantNotice: "[event stream: body not captured]",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
logged := captureLog(t)
conn := &recordingConn{}
tt.response.Body = conn
got, err := roundTripCanned(t, tt.response)
if err != nil {
t.Fatalf("RoundTrip failed: %v", err)
}
if conn.readCalled {
t.Error("body was buffered; it must be streamed straight to the client")
}
// httputil.ReverseProxy asserts the body of a 101 back to
// io.ReadWriteCloser to splice the two connections together.
if _, ok := got.Body.(io.ReadWriteCloser); !ok {
t.Errorf("body type %T is not an io.ReadWriteCloser", got.Body)
}
// The headers are still logged even though the body is not.
if out := logged.String(); !strings.Contains(out, tt.wantNotice) {
t.Errorf("log missing %q, got:\n%s", tt.wantNotice, out)
}
})
}
}
func TestRoundTripSkipsBodyWhenResponseLoggingDisabled(t *testing.T) {
setNoColor(t, true)
setBool(t, &logRequests, false)
setBool(t, &logResponses, false)
captureLog(t)
conn := &recordingConn{}
got, err := roundTripCanned(t, &http.Response{
StatusCode: http.StatusOK,
Status: "200 OK",
Proto: "HTTP/1.1", ProtoMajor: 1, ProtoMinor: 1,
Header: http.Header{"Content-Type": {"application/json"}},
Body: conn,
})
if err != nil {
t.Fatalf("RoundTrip failed: %v", err)
}
if conn.readCalled {
t.Error("body was read even though response logging is disabled")
}
if got.Body != conn {
t.Error("body was replaced even though response logging is disabled")
}
// The caller still owns the body here, so RoundTrip must not have closed it.
if conn.closeCount != 0 {
t.Errorf("body closed %d times; it is being handed back to the caller", conn.closeCount)
}
}
func TestRoundTripClosesUpstreamBody(t *testing.T) {
// Buffering the body for logging leaves the upstream body owned by
// RoundTrip, which must close it exactly once so the connection is released.
setNoColor(t, true)
setBool(t, &logRequests, false)
setBool(t, &logResponses, true)
captureLog(t)
conn := &recordingConn{}
got, err := roundTripCanned(t, &http.Response{
StatusCode: http.StatusOK,
Status: "200 OK",
Proto: "HTTP/1.1", ProtoMajor: 1, ProtoMinor: 1,
Header: http.Header{"Content-Type": {"application/json"}},
Body: conn,
})
if err != nil {
t.Fatalf("RoundTrip failed: %v", err)
}
if conn.closeCount != 1 {
t.Errorf("upstream body closed %d times, want exactly 1", conn.closeCount)
}
// The client must still get a usable body, and closing it must not reach
// the upstream body a second time.
if err := got.Body.Close(); err != nil {
t.Errorf("closing the returned body failed: %v", err)
}
if conn.closeCount != 1 {
t.Errorf("upstream body closed %d times after the client closed its own", conn.closeCount)
}
}
func TestDecodeBodyCapsDecompressionBomb(t *testing.T) {
// A small payload that expands to far more than the log limit.
bomb := compressGzip(t, bytes.Repeat([]byte("A"), 64*maxLogBodySize))
if len(bomb) > maxLogBodySize {
t.Fatalf("test payload is not small: %d bytes", len(bomb))
}
got, err := decodeBody(encodingGzip, bomb)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if len(got) != maxLogBodySize+1 {
t.Errorf("decoded %d bytes, want the read to stop at %d", len(got), maxLogBodySize+1)
}
}
func TestDecodeBodyEncodingLists(t *testing.T) {
original := []byte("hello, world!")
tests := []struct {
name string
encoding string
body []byte
want string
}{
{
name: "gzip alias",
encoding: "x-gzip",
body: compressGzip(t, original),
want: "hello, world!",
},
{
name: "deflate alias",
encoding: "x-deflate",
body: compressDeflate(t, original),
want: "hello, world!",
},
{
// Codings are listed in the order they were applied, so brotli was
// applied last and must be undone first.
name: "gzip then brotli",
encoding: "gzip, br",
body: compressBrotli(t, compressGzip(t, original)),
want: "hello, world!",
},
{
name: "identity is a no-op in a list",
encoding: "identity, gzip",
body: compressGzip(t, original),
want: "hello, world!",
},
{
name: "unsupported coding is left alone",
encoding: "compress",
body: original,
want: "hello, world!",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got, err := decodeBody(tt.encoding, tt.body)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if string(got) != tt.want {
t.Errorf("got %q, want %q", string(got), tt.want)
}
})
}
}
func TestFormatBodyForLog(t *testing.T) {
setNoColor(t, true)
original := []byte("hello, world!")
tests := []struct {
name string
body []byte
wireSize int64
encoding string
contentType string
want string
}{
{
name: "decode failure is reported instead of dumping raw bytes",
body: []byte("not gzip"),
wireSize: 8,
encoding: encodingGzip,
want: "[decode failed:",
},
{
name: "unsupported coding is reported",
body: original,
wireSize: int64(len(original)),
encoding: "compress",
want: "[not decoded: unsupported content-encoding",
},
{
name: "oversized plain body reports its exact size",
body: bytes.Repeat([]byte("x"), maxLogBodySize+1),
wireSize: maxLogBodySize + 1,
want: fmt.Sprintf("[body too large to display: %d bytes]", maxLogBodySize+1),
},
{
name: "oversized body of unknown length",
body: bytes.Repeat([]byte("x"), maxLogBodySize+1),
wireSize: -1,
want: fmt.Sprintf("[body too large to display: over %d bytes]", maxLogBodySize),
},
{
name: "oversized decompressed body",
body: compressGzip(t, bytes.Repeat([]byte("A"), 4*maxLogBodySize)),
wireSize: 4 * maxLogBodySize,
encoding: encodingGzip,
want: fmt.Sprintf("[decompressed body exceeds the %d byte log limit]", maxLogBodySize),
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got := string(formatBodyForLog(tt.body, tt.wireSize, tt.encoding, tt.contentType))
if !strings.Contains(got, tt.want) {
t.Errorf("got %q, want it to contain %q", got, tt.want)
}
})
}
}
func TestFormatBodyForLogPutsNoticeBeforeBody(t *testing.T) {
// An undecodable body is still shown, but the explanation has to come
// first: the raw bytes may be long or binary and would otherwise push the
// notice out of view.
setNoColor(t, true)
body := []byte("this is not gzip at all")
got := string(formatBodyForLog(body, int64(len(body)), encodingGzip, "text/plain"))
notice := strings.Index(got, "[decode failed:")
payload := strings.Index(got, string(body))
if notice < 0 || payload < 0 {
t.Fatalf("expected both the notice and the raw body, got %q", got)
}
if notice > payload {
t.Errorf("notice must precede the body, got %q", got)
}
}
func TestRoundTripPreservesLargeRequestBody(t *testing.T) {
// The request body is captured for logging only up to maxLogBodySize, so
// the captured prefix must be spliced back in front of the remainder.
setNoColor(t, true)
captureLog(t)
payload := bytes.Repeat([]byte("z"), maxLogBodySize+1024)
var received []byte
upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
received, _ = io.ReadAll(r.Body)
w.WriteHeader(http.StatusOK)
}))
defer upstream.Close()
req, err := http.NewRequest(http.MethodPost, upstream.URL, bytes.NewReader(payload))
if err != nil {
t.Fatal(err)
}
req.Header.Set("Content-Type", "text/plain")
resp, err := DebugTransport{}.RoundTrip(req)
if err != nil {
t.Fatalf("RoundTrip failed: %v", err)
}
defer func() { _ = resp.Body.Close() }()
if !bytes.Equal(received, payload) {
t.Errorf("upstream received %d bytes, want %d (request body was corrupted)", len(received), len(payload))
}
}
func TestResolveNoColor(t *testing.T) {
tests := []struct {
name string
args []string
env string
setEnv bool
want bool
}{
{name: "no flag, no env", args: nil, want: false},
{name: "NO_COLOR set disables color", args: nil, env: "1", setEnv: true, want: true},
{name: "empty NO_COLOR is ignored", args: nil, env: "", setEnv: true, want: false},
{name: "explicit -no-color wins", args: []string{"-no-color"}, want: true},
{
// The project documents CLI flag > env var, so an explicit
// -no-color=false keeps colors on even when NO_COLOR is set.
name: "explicit -no-color=false beats NO_COLOR",
args: []string{"-no-color=false"},
env: "1",
setEnv: true,
want: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if tt.setEnv {
t.Setenv("NO_COLOR", tt.env)
} else {
_ = os.Unsetenv("NO_COLOR")
}
// registerFlags writes every default straight into its target, so
// all five must be guarded, not just the one under test.
setNoColor(t, false)
setBool(t, &logRequests, logRequests)
setBool(t, &logResponses, logResponses)
setString(t, &cliTarget, cliTarget)
setString(t, &cliPort, cliPort)
fs := flag.NewFlagSet("test", flag.ContinueOnError)
registerFlags(fs)
if err := fs.Parse(tt.args); err != nil {
t.Fatal(err)
}
if got := resolveNoColor(fs, noColor); got != tt.want {
t.Errorf("resolveNoColor() = %v, want %v", got, tt.want)
}
})
}
}
func TestValidateListenPort(t *testing.T) {
tests := []struct {
name string
flag string
env string
setEnv bool
wantErr bool
}{
{name: "flag port", flag: "9090"},
{name: "env port", env: "8080", setEnv: true},
{name: "default when unset"},
{name: "port zero picks a free port", flag: "0"},
{name: "empty env is rejected", env: "", setEnv: true, wantErr: true},
{name: "non-numeric is rejected", flag: "http", wantErr: true},
{name: "out of range is rejected", flag: "70000", wantErr: true},
{name: "host:port is rejected", flag: "0.0.0.0:8080", wantErr: true},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
setString(t, &cliPort, tt.flag)
if tt.setEnv {
t.Setenv("PORT", tt.env)
} else {
_ = os.Unsetenv("PORT")
}
err := validateListenPort()
if tt.wantErr && err == nil {
t.Error("expected an error, got nil")
}
if !tt.wantErr && err != nil {
t.Errorf("unexpected error: %v", err)
}
})
}
}
func TestDumpRequestHeadersDoesNotMaterializeDeclaredBody(t *testing.T) {
// httputil.DumpRequestOut writes a dummy body of ContentLength bytes into
// its buffer before slicing it off, so dumping the request directly would
// let a client allocate gigabytes by declaring a Content-Length it never
// sends. The dump must stay proportional to the headers.
const declared = 1 << 30 // 1 GiB
req, err := http.NewRequest(http.MethodPost, "http://example.invalid/upload", strings.NewReader(""))
if err != nil {
t.Fatal(err)
}
req.Header.Set("Content-Type", "text/plain")
req.ContentLength = declared
var before, after runtime.MemStats
runtime.GC()
runtime.ReadMemStats(&before)
dump, err := dumpRequestHeaders(req)
runtime.ReadMemStats(&after)
if err != nil {
t.Fatalf("dumpRequestHeaders failed: %v", err)
}
if len(dump) > 4096 {
t.Errorf("header dump is %d bytes; the declared body must not be materialized", len(dump))
}
if allocated := after.TotalAlloc - before.TotalAlloc; allocated > 1<<20 {
t.Errorf("dumping allocated %d bytes for a %d byte declared body", allocated, declared)
}
// The real length must still be reported, not the empty copy's.
if want := fmt.Sprintf("Content-Length: %d\r\n", declared); !strings.Contains(string(dump), want) {
t.Errorf("dump does not report the real length %q, got:\n%s", want, dump)
}
}
func TestDumpRequestHeadersReportsFraming(t *testing.T) {
tests := []struct {
name string
contentLength int64
body string
want string
notWant string
}{
{name: "known length", contentLength: 15, body: "0123456789abcde", want: "Content-Length: 15\r\n"},
{name: "no body", contentLength: 0, body: "", notWant: "Content-Length: 1"},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
req, err := http.NewRequest(http.MethodPost, "http://example.invalid/", strings.NewReader(tt.body))
if err != nil {
t.Fatal(err)
}
req.ContentLength = tt.contentLength
dump, err := dumpRequestHeaders(req)
if err != nil {
t.Fatalf("dumpRequestHeaders failed: %v", err)
}
got := string(dump)
if tt.want != "" && !strings.Contains(got, tt.want) {
t.Errorf("dump missing %q, got:\n%s", tt.want, got)
}
if tt.notWant != "" && strings.Contains(got, tt.notWant) {
t.Errorf("dump unexpectedly contains %q, got:\n%s", tt.notWant, got)
}
// The request body must be left intact for the transport to send.
sent, err := io.ReadAll(req.Body)
if err != nil {
t.Fatal(err)
}
if string(sent) != tt.body {
t.Errorf("request body was consumed: got %q, want %q", sent, tt.body)
}
})