forked from adamlaska/boulder
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhttp_test.go
More file actions
1557 lines (1434 loc) · 55.2 KB
/
http_test.go
File metadata and controls
1557 lines (1434 loc) · 55.2 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 va
import (
"bytes"
"context"
"encoding/base64"
"errors"
"fmt"
mrand "math/rand"
"net"
"net/http"
"net/http/httptest"
"net/url"
"regexp"
"strconv"
"strings"
"time"
"unicode/utf8"
"github.com/letsencrypt/boulder/bdns"
"github.com/letsencrypt/boulder/core"
berrors "github.com/letsencrypt/boulder/errors"
"github.com/letsencrypt/boulder/identifier"
"github.com/letsencrypt/boulder/probs"
"github.com/letsencrypt/boulder/test"
"github.com/miekg/dns"
"testing"
)
func httpChallenge() core.Challenge {
return createChallenge(core.ChallengeTypeHTTP01)
}
// TestDialerMismatchError tests that using a preresolvedDialer for one host for
// a dial to another host produces the expected dialerMismatchError.
func TestDialerMismatchError(t *testing.T) {
d := preresolvedDialer{
ip: net.ParseIP("127.0.0.1"),
port: 1337,
hostname: "letsencrypt.org",
}
expectedErr := dialerMismatchError{
dialerHost: d.hostname,
dialerIP: d.ip.String(),
dialerPort: d.port,
host: "lettuceencrypt.org",
}
_, err := d.DialContext(
context.Background(),
"tincan-and-string",
"lettuceencrypt.org:80")
test.AssertEquals(t, err.Error(), expectedErr.Error())
}
// TestPreresolvedDialerTimeout tests that the preresolvedDialer's DialContext
// will timeout after the expected singleDialTimeout. This ensures timeouts at
// the TCP level are handled correctly.
func TestPreresolvedDialerTimeout(t *testing.T) {
va, _ := setup(nil, 0, "", nil)
// Timeouts below 50ms tend to be flaky.
va.singleDialTimeout = 50 * time.Millisecond
// The context timeout needs to be larger than the singleDialTimeout
ctxTimeout := 500 * time.Millisecond
ctx, cancel := context.WithTimeout(context.Background(), ctxTimeout)
defer cancel()
started := time.Now()
va.dnsClient = dnsMockReturnsUnroutable{&bdns.MockClient{}}
// NOTE(@jsha): The only method I've found so far to trigger a connect timeout
// is to connect to an unrouteable IP address. This usually generates
// a connection timeout, but will rarely return "Network unreachable" instead.
// If we get that, just retry until we get something other than "Network unreachable".
var prob *probs.ProblemDetails
for i := 0; i < 20; i++ {
_, _, prob = va.fetchHTTP(ctx, "unroutable.invalid", "/.well-known/acme-challenge/whatever")
if prob != nil && strings.Contains(prob.Detail, "Network unreachable") {
continue
} else {
break
}
}
if prob == nil {
t.Fatalf("Connection should've timed out")
}
took := time.Since(started)
// Check that the HTTP connection doesn't return too fast, and times
// out after the expected time
if took < va.singleDialTimeout {
t.Fatalf("fetch returned before %s (%s) with %#v", va.singleDialTimeout, took, prob)
}
if took > 2*va.singleDialTimeout {
t.Fatalf("fetch didn't timeout after %s", va.singleDialTimeout)
}
test.AssertEquals(t, prob.Type, probs.ConnectionProblem)
expectMatch := regexp.MustCompile(
"Fetching http://unroutable.invalid/.well-known/acme-challenge/.*: Timeout during connect")
if !expectMatch.MatchString(prob.Detail) {
t.Errorf("Problem details incorrect. Got %q, expected to match %q",
prob.Detail, expectMatch)
}
}
func TestHTTPTransport(t *testing.T) {
dummyDialerFunc := func(_ context.Context, _, _ string) (net.Conn, error) {
return nil, nil
}
transport := httpTransport(dummyDialerFunc)
// The HTTP Transport should have a TLS config that skips verifying
// certificates.
test.AssertEquals(t, transport.TLSClientConfig.InsecureSkipVerify, true)
// Keep alives should be disabled
test.AssertEquals(t, transport.DisableKeepAlives, true)
test.AssertEquals(t, transport.MaxIdleConns, 1)
test.AssertEquals(t, transport.IdleConnTimeout.String(), "1s")
test.AssertEquals(t, transport.TLSHandshakeTimeout.String(), "10s")
}
func TestHTTPValidationTarget(t *testing.T) {
// NOTE(@cpu): See `bdns/mocks.go` and the mock `LookupHost` function for the
// hostnames used in this test.
testCases := []struct {
Name string
Host string
ExpectedError error
ExpectedIPs []string
}{
{
Name: "No IPs for host",
Host: "always.invalid",
ExpectedError: berrors.DNSError("No valid IP addresses found for always.invalid"),
},
{
Name: "Only IPv4 addrs for host",
Host: "some.example.com",
ExpectedIPs: []string{"127.0.0.1"},
},
{
Name: "Only IPv6 addrs for host",
Host: "ipv6.localhost",
ExpectedIPs: []string{"::1"},
},
{
Name: "Both IPv6 and IPv4 addrs for host",
Host: "ipv4.and.ipv6.localhost",
// In this case we expect 1 IPv6 address first, and then 1 IPv4 address
ExpectedIPs: []string{"::1", "127.0.0.1"},
},
}
const (
examplePort = 1234
examplePath = "/.well-known/path/i/took"
exampleQuery = "my-path=was&my=own"
)
va, _ := setup(nil, 0, "", nil)
for _, tc := range testCases {
t.Run(tc.Name, func(t *testing.T) {
target, err := va.newHTTPValidationTarget(
context.Background(),
tc.Host,
examplePort,
examplePath,
exampleQuery)
if err != nil && tc.ExpectedError == nil {
t.Fatalf("Unexpected error from NewHTTPValidationTarget: %v", err)
} else if err != nil && tc.ExpectedError != nil {
test.AssertMarshaledEquals(t, err, tc.ExpectedError)
} else if err == nil {
// The target should be populated.
test.AssertNotEquals(t, target.host, "")
test.AssertNotEquals(t, target.port, 0)
test.AssertNotEquals(t, target.path, "")
// Calling ip() on the target should give the expected IPs in the right
// order.
for i, expectedIP := range tc.ExpectedIPs {
gotIP := target.ip()
if gotIP == nil {
t.Errorf("Expected IP %d to be %s got nil", i, expectedIP)
} else {
test.AssertEquals(t, gotIP.String(), expectedIP)
}
// Advance to the next IP
_ = target.nextIP()
}
}
})
}
}
func TestExtractRequestTarget(t *testing.T) {
mustURL := func(t *testing.T, rawURL string) *url.URL {
urlOb, err := url.Parse(rawURL)
if err != nil {
t.Fatalf("Unable to parse raw URL %q: %v", rawURL, err)
return nil
}
return urlOb
}
testCases := []struct {
Name string
Req *http.Request
ExpectedError error
ExpectedHost string
ExpectedPort int
}{
{
Name: "nil input req",
ExpectedError: fmt.Errorf("redirect HTTP request was nil"),
},
{
Name: "invalid protocol scheme",
Req: &http.Request{
URL: mustURL(t, "gopher://letsencrypt.org"),
},
ExpectedError: fmt.Errorf("Invalid protocol scheme in redirect target. " +
`Only "http" and "https" protocol schemes are supported, ` +
`not "gopher"`),
},
{
Name: "invalid explicit port",
Req: &http.Request{
URL: mustURL(t, "https://weird.port.letsencrypt.org:9999"),
},
ExpectedError: fmt.Errorf("Invalid port in redirect target. Only ports 80 " +
"and 443 are supported, not 9999"),
},
{
Name: "invalid empty hostname",
Req: &http.Request{
URL: mustURL(t, "https:///who/needs/a/hostname?not=me"),
},
ExpectedError: errors.New("Invalid empty hostname in redirect target"),
},
{
Name: "invalid .well-known hostname",
Req: &http.Request{
URL: mustURL(t, "https://my.webserver.is.misconfigured.well-known/acme-challenge/xxx"),
},
ExpectedError: errors.New(`Invalid host in redirect target "my.webserver.is.misconfigured.well-known". Check webserver config for missing '/' in redirect target.`),
},
{
Name: "invalid non-iana hostname",
Req: &http.Request{
URL: mustURL(t, "https://my.tld.is.cpu/pretty/cool/right?yeah=Ithoughtsotoo"),
},
ExpectedError: errors.New("Invalid hostname in redirect target, must end in IANA registered TLD"),
},
{
Name: "bare IP",
Req: &http.Request{
URL: mustURL(t, "https://10.10.10.10"),
},
ExpectedError: fmt.Errorf(`Invalid host in redirect target "10.10.10.10". ` +
"Only domain names are supported, not IP addresses"),
},
{
Name: "valid HTTP redirect, explicit port",
Req: &http.Request{
URL: mustURL(t, "http://cpu.letsencrypt.org:80"),
},
ExpectedHost: "cpu.letsencrypt.org",
ExpectedPort: 80,
},
{
Name: "valid HTTP redirect, implicit port",
Req: &http.Request{
URL: mustURL(t, "http://cpu.letsencrypt.org"),
},
ExpectedHost: "cpu.letsencrypt.org",
ExpectedPort: 80,
},
{
Name: "valid HTTPS redirect, explicit port",
Req: &http.Request{
URL: mustURL(t, "https://cpu.letsencrypt.org:443/hello.world"),
},
ExpectedHost: "cpu.letsencrypt.org",
ExpectedPort: 443,
},
{
Name: "valid HTTPS redirect, implicit port",
Req: &http.Request{
URL: mustURL(t, "https://cpu.letsencrypt.org/hello.world"),
},
ExpectedHost: "cpu.letsencrypt.org",
ExpectedPort: 443,
},
}
va, _ := setup(nil, 0, "", nil)
for _, tc := range testCases {
t.Run(tc.Name, func(t *testing.T) {
host, port, err := va.extractRequestTarget(tc.Req)
if err != nil && tc.ExpectedError == nil {
t.Errorf("Expected nil err got %v", err)
} else if err != nil && tc.ExpectedError != nil {
test.AssertEquals(t, err.Error(), tc.ExpectedError.Error())
} else if err == nil && tc.ExpectedError != nil {
t.Errorf("Expected err %v, got nil", tc.ExpectedError)
} else {
test.AssertEquals(t, host, tc.ExpectedHost)
test.AssertEquals(t, port, tc.ExpectedPort)
}
})
}
}
// TestHTTPValidationDNSError attempts validation for a domain name that always
// generates a DNS error, and checks that a log line with the detailed error is
// generated.
func TestHTTPValidationDNSError(t *testing.T) {
va, mockLog := setup(nil, 0, "", nil)
_, _, prob := va.fetchHTTP(ctx, "always.error", "/.well-known/acme-challenge/whatever")
test.AssertError(t, prob, "Expected validation fetch to fail")
matchingLines := mockLog.GetAllMatching(`read udp: some net error`)
if len(matchingLines) != 1 {
t.Errorf("Didn't see expected DNS error logged. Instead, got:\n%s",
strings.Join(mockLog.GetAllMatching(`.*`), "\n"))
}
}
// TestHTTPValidationDNSIdMismatchError tests that performing an HTTP-01
// challenge with a domain name that always returns a DNS ID mismatch error from
// the mock resolver results in valid query/response data being logged in
// a format we can decode successfully.
func TestHTTPValidationDNSIdMismatchError(t *testing.T) {
va, mockLog := setup(nil, 0, "", nil)
_, _, prob := va.fetchHTTP(ctx, "id.mismatch", "/.well-known/acme-challenge/whatever")
test.AssertError(t, prob, "Expected validation fetch to fail")
matchingLines := mockLog.GetAllMatching(`logDNSError ID mismatch`)
if len(matchingLines) != 1 {
t.Errorf("Didn't see expected DNS error logged. Instead, got:\n%s",
strings.Join(mockLog.GetAllMatching(`.*`), "\n"))
}
expectedRegex := regexp.MustCompile(
`INFO: logDNSError ID mismatch ` +
`chosenServer=\[mock.server\] ` +
`hostname=\[id\.mismatch\] ` +
`respHostname=\[id\.mismatch\.\] ` +
`queryType=\[A\] ` +
`err\=\[dns: id mismatch\] ` +
`msg=\[([A-Za-z0-9+=/\=]+)\] ` +
`resp=\[([A-Za-z0-9+=/\=]+)\]`,
)
matches := expectedRegex.FindAllStringSubmatch(matchingLines[0], -1)
test.AssertEquals(t, len(matches), 1)
submatches := matches[0]
test.AssertEquals(t, len(submatches), 3)
msgBytes, err := base64.StdEncoding.DecodeString(submatches[1])
test.AssertNotError(t, err, "bad base64 encoded query msg")
msg := new(dns.Msg)
err = msg.Unpack(msgBytes)
test.AssertNotError(t, err, "bad packed query msg")
respBytes, err := base64.StdEncoding.DecodeString(submatches[2])
test.AssertNotError(t, err, "bad base64 encoded resp msg")
resp := new(dns.Msg)
err = resp.Unpack(respBytes)
test.AssertNotError(t, err, "bad packed response msg")
}
func TestSetupHTTPValidation(t *testing.T) {
va, _ := setup(nil, 0, "", nil)
mustTarget := func(t *testing.T, host string, port int, path string) *httpValidationTarget {
target, err := va.newHTTPValidationTarget(
context.Background(),
host,
port,
path,
"")
if err != nil {
t.Fatalf("Failed to construct httpValidationTarget for %q", host)
return nil
}
return target
}
httpInputURL := "http://ipv4.and.ipv6.localhost/yellow/brick/road"
httpsInputURL := "https://ipv4.and.ipv6.localhost/yellow/brick/road"
testCases := []struct {
Name string
InputURL string
InputTarget *httpValidationTarget
ExpectedRecord core.ValidationRecord
ExpectedDialer *preresolvedDialer
ExpectedError error
}{
{
Name: "nil target",
InputURL: httpInputURL,
ExpectedError: fmt.Errorf("httpValidationTarget can not be nil"),
},
{
Name: "empty input URL",
InputTarget: &httpValidationTarget{},
ExpectedError: fmt.Errorf("reqURL can not be nil"),
},
{
Name: "target with no IPs",
InputURL: httpInputURL,
InputTarget: &httpValidationTarget{
host: "foobar",
port: va.httpPort,
path: "idk",
},
ExpectedRecord: core.ValidationRecord{
URL: "http://ipv4.and.ipv6.localhost/yellow/brick/road",
Hostname: "foobar",
Port: strconv.Itoa(va.httpPort),
},
ExpectedError: fmt.Errorf(`host "foobar" has no IP addresses remaining to use`),
},
{
Name: "HTTP input req",
InputTarget: mustTarget(t, "ipv4.and.ipv6.localhost", va.httpPort, "/yellow/brick/road"),
InputURL: httpInputURL,
ExpectedRecord: core.ValidationRecord{
Hostname: "ipv4.and.ipv6.localhost",
Port: strconv.Itoa(va.httpPort),
URL: "http://ipv4.and.ipv6.localhost/yellow/brick/road",
AddressesResolved: []net.IP{net.ParseIP("::1"), net.ParseIP("127.0.0.1")},
AddressUsed: net.ParseIP("::1"),
},
ExpectedDialer: &preresolvedDialer{
ip: net.ParseIP("::1"),
port: va.httpPort,
timeout: va.singleDialTimeout,
},
},
{
Name: "HTTPS input req",
InputTarget: mustTarget(t, "ipv4.and.ipv6.localhost", va.httpsPort, "/yellow/brick/road"),
InputURL: httpsInputURL,
ExpectedRecord: core.ValidationRecord{
Hostname: "ipv4.and.ipv6.localhost",
Port: strconv.Itoa(va.httpsPort),
URL: "https://ipv4.and.ipv6.localhost/yellow/brick/road",
AddressesResolved: []net.IP{net.ParseIP("::1"), net.ParseIP("127.0.0.1")},
AddressUsed: net.ParseIP("::1"),
},
ExpectedDialer: &preresolvedDialer{
ip: net.ParseIP("::1"),
port: va.httpsPort,
timeout: va.singleDialTimeout,
},
},
}
for _, tc := range testCases {
t.Run(tc.Name, func(t *testing.T) {
outDialer, outRecord, err := va.setupHTTPValidation(
context.Background(),
tc.InputURL,
tc.InputTarget)
if err != nil && tc.ExpectedError == nil {
t.Errorf("Expected nil error, got %v", err)
} else if err == nil && tc.ExpectedError != nil {
t.Errorf("Expected %v error, got nil", tc.ExpectedError)
} else if err != nil && tc.ExpectedError != nil {
test.AssertEquals(t, err.Error(), tc.ExpectedError.Error())
}
if tc.ExpectedDialer == nil && outDialer != nil {
t.Errorf("Expected nil dialer, got %v", outDialer)
} else if tc.ExpectedDialer != nil {
test.AssertMarshaledEquals(t, outDialer, tc.ExpectedDialer)
}
// In all cases we expect there to have been a validation record
test.AssertMarshaledEquals(t, outRecord, tc.ExpectedRecord)
})
}
}
// A more concise version of httpSrv() that supports http.go tests
func httpTestSrv(t *testing.T) *httptest.Server {
mux := http.NewServeMux()
server := httptest.NewUnstartedServer(mux)
server.Start()
httpPort := getPort(server)
// A path that always returns an OK response
mux.HandleFunc("/ok", func(resp http.ResponseWriter, req *http.Request) {
resp.WriteHeader(http.StatusOK)
fmt.Fprint(resp, "ok")
})
// A path that always times out by sleeping longer than the validation context
// allows
mux.HandleFunc("/timeout", func(resp http.ResponseWriter, req *http.Request) {
time.Sleep(time.Second)
resp.WriteHeader(http.StatusOK)
fmt.Fprint(resp, "sorry, I'm a slow server")
})
// A path that always redirects to itself, creating a loop that will terminate
// when detected.
mux.HandleFunc("/loop", func(resp http.ResponseWriter, req *http.Request) {
http.Redirect(
resp,
req,
fmt.Sprintf("http://example.com:%d/loop", httpPort),
http.StatusMovedPermanently)
})
// A path that sequentially redirects, creating an incrementing redirect
// that will terminate when the redirect limit is reached and ensures each
// URL is different than the last.
for i := 0; i <= maxRedirect+1; i++ {
// Need to re-scope i so it iterates properly in the function
i := i
mux.HandleFunc(fmt.Sprintf("/max-redirect/%d", i),
func(resp http.ResponseWriter, req *http.Request) {
http.Redirect(
resp,
req,
fmt.Sprintf("http://example.com:%d/max-redirect/%d", httpPort, i+1),
http.StatusMovedPermanently,
)
})
}
// A path that always redirects to a URL with a non-HTTP/HTTPs protocol scheme
mux.HandleFunc("/redir-bad-proto", func(resp http.ResponseWriter, req *http.Request) {
http.Redirect(
resp,
req,
"gopher://example.com",
http.StatusMovedPermanently,
)
})
// A path that always redirects to a URL with a port other than the configured
// HTTP/HTTPS port
mux.HandleFunc("/redir-bad-port", func(resp http.ResponseWriter, req *http.Request) {
http.Redirect(
resp,
req,
"https://example.com:1987",
http.StatusMovedPermanently,
)
})
// A path that always redirects to a URL with a bare IP address
mux.HandleFunc("/redir-bad-host", func(resp http.ResponseWriter, req *http.Request) {
http.Redirect(
resp,
req,
"https://127.0.0.1",
http.StatusMovedPermanently,
)
})
mux.HandleFunc("/bad-status-code", func(resp http.ResponseWriter, req *http.Request) {
resp.WriteHeader(http.StatusGone)
fmt.Fprint(resp, "sorry, I'm gone")
})
// A path that always responds with a 303 redirect
mux.HandleFunc("/303-see-other", func(resp http.ResponseWriter, req *http.Request) {
http.Redirect(
resp,
req,
"http://example.org/303-see-other",
http.StatusSeeOther,
)
})
tooLargeBuf := bytes.NewBuffer([]byte{})
for i := 0; i < maxResponseSize+10; i++ {
tooLargeBuf.WriteByte(byte(97))
}
mux.HandleFunc("/resp-too-big", func(resp http.ResponseWriter, req *http.Request) {
resp.WriteHeader(http.StatusOK)
fmt.Fprint(resp, tooLargeBuf)
})
// Create a buffer that starts with invalid UTF8 and is bigger than
// maxResponseSize
tooLargeInvalidUTF8 := bytes.NewBuffer([]byte{})
tooLargeInvalidUTF8.WriteString("f\xffoo")
tooLargeInvalidUTF8.Write(tooLargeBuf.Bytes())
// invalid-utf8-body Responds with body that is larger than
// maxResponseSize and starts with an invalid UTF8 string. This is to
// test the codepath where invalid UTF8 is converted to valid UTF8
// that can be passed as an error message via grpc.
mux.HandleFunc("/invalid-utf8-body", func(resp http.ResponseWriter, req *http.Request) {
resp.WriteHeader(http.StatusOK)
fmt.Fprint(resp, tooLargeInvalidUTF8)
})
mux.HandleFunc("/redir-path-too-long", func(resp http.ResponseWriter, req *http.Request) {
http.Redirect(
resp,
req,
"https://example.com/this-is-too-long-01234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789",
http.StatusMovedPermanently)
})
// A path that redirects to an uppercase public suffix (#4215)
mux.HandleFunc("/redir-uppercase-publicsuffix", func(resp http.ResponseWriter, req *http.Request) {
http.Redirect(
resp,
req,
"http://example.COM/ok",
http.StatusMovedPermanently)
})
// A path that returns a body containing printf formatting verbs
mux.HandleFunc("/printf-verbs", func(resp http.ResponseWriter, req *http.Request) {
resp.WriteHeader(http.StatusOK)
fmt.Fprint(resp, "%"+"2F.well-known%"+"2F"+tooLargeBuf.String())
})
return server
}
type testNetErr struct{}
func (e *testNetErr) Error() string {
return "testNetErr"
}
func (e *testNetErr) Temporary() bool {
return false
}
func (e *testNetErr) Timeout() bool {
return false
}
func TestFallbackErr(t *testing.T) {
untypedErr := errors.New("the least interesting kind of error")
berr := berrors.InternalServerError("code violet: class neptune")
netOpErr := &net.OpError{
Op: "siphon",
Err: fmt.Errorf("port was clogged. please empty packets"),
}
netDialOpErr := &net.OpError{
Op: "dial",
Err: fmt.Errorf("your call is important to us - please stay on the line"),
}
netErr := &testNetErr{}
testCases := []struct {
Name string
Err error
ExpectFallback bool
}{
{
Name: "Nil error",
Err: nil,
},
{
Name: "Standard untyped error",
Err: untypedErr,
},
{
Name: "A Boulder error instance",
Err: berr,
},
{
Name: "A non-dial net.OpError instance",
Err: netOpErr,
},
{
Name: "A dial net.OpError instance",
Err: netDialOpErr,
ExpectFallback: true,
},
{
Name: "A generic net.Error instance",
Err: netErr,
},
{
Name: "A URL error wrapping a standard error",
Err: &url.Error{
Op: "ivy",
URL: "https://en.wikipedia.org/wiki/Operation_Ivy_(band)",
Err: errors.New("take warning"),
},
},
{
Name: "A URL error wrapping a nil error",
Err: &url.Error{
Err: nil,
},
},
{
Name: "A URL error wrapping a Boulder error instance",
Err: &url.Error{
Err: berr,
},
},
{
Name: "A URL error wrapping a non-dial net OpError",
Err: &url.Error{
Err: netOpErr,
},
},
{
Name: "A URL error wrapping a dial net.OpError",
Err: &url.Error{
Err: netDialOpErr,
},
ExpectFallback: true,
},
{
Name: "A URL error wrapping a generic net Error",
Err: &url.Error{
Err: netErr,
},
},
}
for _, tc := range testCases {
t.Run(tc.Name, func(t *testing.T) {
if isFallback := fallbackErr(tc.Err); isFallback != tc.ExpectFallback {
t.Errorf(
"Expected fallbackErr for %t to be %v was %v\n",
tc.Err, tc.ExpectFallback, isFallback)
}
})
}
}
func TestFetchHTTP(t *testing.T) {
// Create a test server
testSrv := httpTestSrv(t)
defer testSrv.Close()
// Setup a VA. By providing the testSrv to setup the VA will use the testSrv's
// randomly assigned port as its HTTP port.
va, _ := setup(testSrv, 0, "", nil)
// We need to know the randomly assigned HTTP port for testcases as well
httpPort := getPort(testSrv)
// For the looped test case we expect one validation record per redirect
// until boulder detects that a url has been used twice indicating a
// redirect loop. Because it is hitting the /loop endpoint it will encounter
// this scenario after the base url and fail on the second time hitting the
// redirect with a port definition. On i=0 it will encounter the first
// redirect to the url with a port definition and on i=1 it will encounter
// the second redirect to the url with the port and get an expected error.
expectedLoopRecords := []core.ValidationRecord{}
for i := 0; i < 2; i++ {
// The first request will not have a port # in the URL.
url := "http://example.com/loop"
if i != 0 {
url = fmt.Sprintf("http://example.com:%d/loop", httpPort)
}
expectedLoopRecords = append(expectedLoopRecords,
core.ValidationRecord{
Hostname: "example.com",
Port: strconv.Itoa(httpPort),
URL: url,
AddressesResolved: []net.IP{net.ParseIP("127.0.0.1")},
AddressUsed: net.ParseIP("127.0.0.1"),
})
}
// For the too many redirect test case we expect one validation record per
// redirect up to maxRedirect (inclusive). There is also +1 record for the
// base lookup, giving a termination criteria of > maxRedirect+1
expectedTooManyRedirRecords := []core.ValidationRecord{}
for i := 0; i <= maxRedirect+1; i++ {
// The first request will not have a port # in the URL.
url := "http://example.com/max-redirect/0"
if i != 0 {
url = fmt.Sprintf("http://example.com:%d/max-redirect/%d", httpPort, i)
}
expectedTooManyRedirRecords = append(expectedTooManyRedirRecords,
core.ValidationRecord{
Hostname: "example.com",
Port: strconv.Itoa(httpPort),
URL: url,
AddressesResolved: []net.IP{net.ParseIP("127.0.0.1")},
AddressUsed: net.ParseIP("127.0.0.1"),
})
}
expectedTruncatedResp := bytes.NewBuffer([]byte{})
for i := 0; i < maxResponseSize; i++ {
expectedTruncatedResp.WriteByte(byte(97))
}
testCases := []struct {
Name string
Host string
Path string
ExpectedBody string
ExpectedRecords []core.ValidationRecord
ExpectedProblem *probs.ProblemDetails
}{
{
Name: "No IPs for host",
Host: "always.invalid",
Path: "/.well-known/whatever",
ExpectedProblem: probs.DNS(
"No valid IP addresses found for always.invalid"),
// There are no validation records in this case because the base record
// is only constructed once a URL is made.
ExpectedRecords: nil,
},
{
Name: "Timeout for host",
Host: "example.com",
Path: "/timeout",
ExpectedProblem: probs.ConnectionFailure(
"Fetching http://example.com/timeout: " +
"Timeout after connect (your server may be slow or overloaded)"),
ExpectedRecords: []core.ValidationRecord{
{
Hostname: "example.com",
Port: strconv.Itoa(httpPort),
URL: "http://example.com/timeout",
AddressesResolved: []net.IP{net.ParseIP("127.0.0.1")},
AddressUsed: net.ParseIP("127.0.0.1"),
},
},
},
{
Name: "Redirect loop",
Host: "example.com",
Path: "/loop",
ExpectedProblem: probs.ConnectionFailure(fmt.Sprintf(
"Fetching http://example.com:%d/loop: Redirect loop detected", httpPort)),
ExpectedRecords: expectedLoopRecords,
},
{
Name: "Too many redirects",
Host: "example.com",
Path: "/max-redirect/0",
ExpectedProblem: probs.ConnectionFailure(fmt.Sprintf(
"Fetching http://example.com:%d/max-redirect/12: Too many redirects", httpPort)),
ExpectedRecords: expectedTooManyRedirRecords,
},
{
Name: "Redirect to bad protocol",
Host: "example.com",
Path: "/redir-bad-proto",
ExpectedProblem: probs.ConnectionFailure(
"Fetching gopher://example.com: Invalid protocol scheme in " +
`redirect target. Only "http" and "https" protocol schemes ` +
`are supported, not "gopher"`),
ExpectedRecords: []core.ValidationRecord{
{
Hostname: "example.com",
Port: strconv.Itoa(httpPort),
URL: "http://example.com/redir-bad-proto",
AddressesResolved: []net.IP{net.ParseIP("127.0.0.1")},
AddressUsed: net.ParseIP("127.0.0.1"),
},
},
},
{
Name: "Redirect to bad port",
Host: "example.com",
Path: "/redir-bad-port",
ExpectedProblem: probs.ConnectionFailure(fmt.Sprintf(
"Fetching https://example.com:1987: Invalid port in redirect target. "+
"Only ports %d and 443 are supported, not 1987", httpPort)),
ExpectedRecords: []core.ValidationRecord{
{
Hostname: "example.com",
Port: strconv.Itoa(httpPort),
URL: "http://example.com/redir-bad-port",
AddressesResolved: []net.IP{net.ParseIP("127.0.0.1")},
AddressUsed: net.ParseIP("127.0.0.1"),
},
},
},
{
Name: "Redirect to bad host (bare IP address)",
Host: "example.com",
Path: "/redir-bad-host",
ExpectedProblem: probs.ConnectionFailure(
"Fetching https://127.0.0.1: Invalid host in redirect target " +
`"127.0.0.1". Only domain names are supported, not IP addresses`),
ExpectedRecords: []core.ValidationRecord{
{
Hostname: "example.com",
Port: strconv.Itoa(httpPort),
URL: "http://example.com/redir-bad-host",
AddressesResolved: []net.IP{net.ParseIP("127.0.0.1")},
AddressUsed: net.ParseIP("127.0.0.1"),
},
},
},
{
Name: "Redirect to long path",
Host: "example.com",
Path: "/redir-path-too-long",
ExpectedProblem: probs.ConnectionFailure(
"Fetching https://example.com/this-is-too-long-01234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789: Redirect target too long"),
ExpectedRecords: []core.ValidationRecord{
{
Hostname: "example.com",
Port: strconv.Itoa(httpPort),
URL: "http://example.com/redir-path-too-long",
AddressesResolved: []net.IP{net.ParseIP("127.0.0.1")},
AddressUsed: net.ParseIP("127.0.0.1"),
},
},
},
{
Name: "Wrong HTTP status code",
Host: "example.com",
Path: "/bad-status-code",
ExpectedProblem: probs.Unauthorized(
"Invalid response from http://example.com/bad-status-code " +
"[127.0.0.1]: 410"),
ExpectedRecords: []core.ValidationRecord{
{
Hostname: "example.com",
Port: strconv.Itoa(httpPort),
URL: "http://example.com/bad-status-code",
AddressesResolved: []net.IP{net.ParseIP("127.0.0.1")},
AddressUsed: net.ParseIP("127.0.0.1"),
},
},
},
{
Name: "HTTP status code 303 redirect",
Host: "example.com",
Path: "/303-see-other",
ExpectedProblem: probs.ConnectionFailure(
"Fetching http://example.org/303-see-other: received disallowed redirect status code"),
ExpectedRecords: []core.ValidationRecord{
{
Hostname: "example.com",
Port: strconv.Itoa(httpPort),
URL: "http://example.com/303-see-other",
AddressesResolved: []net.IP{net.ParseIP("127.0.0.1")},
AddressUsed: net.ParseIP("127.0.0.1"),
},
},
},
{
Name: "Response too large",
Host: "example.com",
Path: "/resp-too-big",
ExpectedProblem: probs.Unauthorized(fmt.Sprintf(
"Invalid response from http://example.com/resp-too-big "+
"[127.0.0.1]: %q", expectedTruncatedResp.String(),
)),
ExpectedRecords: []core.ValidationRecord{
{
Hostname: "example.com",
Port: strconv.Itoa(httpPort),
URL: "http://example.com/resp-too-big",
AddressesResolved: []net.IP{net.ParseIP("127.0.0.1")},
AddressUsed: net.ParseIP("127.0.0.1"),
},
},
},
{
Name: "Broken IPv6 only",
Host: "ipv6.localhost",
Path: "/ok",
ExpectedProblem: probs.ConnectionFailure(
"Fetching http://ipv6.localhost/ok: Error getting validation data"),
ExpectedRecords: []core.ValidationRecord{
{
Hostname: "ipv6.localhost",
Port: strconv.Itoa(httpPort),
URL: "http://ipv6.localhost/ok",
AddressesResolved: []net.IP{net.ParseIP("::1")},
AddressUsed: net.ParseIP("::1"),
},
},
},
{
Name: "Dual homed w/ broken IPv6, working IPv4",
Host: "ipv4.and.ipv6.localhost",
Path: "/ok",
ExpectedBody: "ok",
ExpectedRecords: []core.ValidationRecord{
{
Hostname: "ipv4.and.ipv6.localhost",
Port: strconv.Itoa(httpPort),
URL: "http://ipv4.and.ipv6.localhost/ok",
AddressesResolved: []net.IP{net.ParseIP("::1"), net.ParseIP("127.0.0.1")},
// The first validation record should have used the IPv6 addr
AddressUsed: net.ParseIP("::1"),