-
-
Notifications
You must be signed in to change notification settings - Fork 606
/
wfe_test.go
4467 lines (3977 loc) · 163 KB
/
wfe_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package wfe2
import (
"bytes"
"context"
"crypto"
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand"
"crypto/rsa"
"crypto/x509"
"encoding/asn1"
"encoding/base64"
"encoding/json"
"encoding/pem"
"errors"
"fmt"
"io"
"math/big"
"net/http"
"net/http/httptest"
"net/url"
"os"
"sort"
"strconv"
"strings"
"testing"
"time"
"github.com/go-jose/go-jose/v4"
"github.com/jmhodges/clock"
"github.com/prometheus/client_golang/prometheus"
"golang.org/x/crypto/ocsp"
"google.golang.org/grpc"
"google.golang.org/protobuf/types/known/emptypb"
"google.golang.org/protobuf/types/known/timestamppb"
"github.com/letsencrypt/boulder/cmd"
"github.com/letsencrypt/boulder/core"
corepb "github.com/letsencrypt/boulder/core/proto"
berrors "github.com/letsencrypt/boulder/errors"
"github.com/letsencrypt/boulder/features"
"github.com/letsencrypt/boulder/goodkey"
"github.com/letsencrypt/boulder/identifier"
"github.com/letsencrypt/boulder/issuance"
blog "github.com/letsencrypt/boulder/log"
"github.com/letsencrypt/boulder/metrics"
"github.com/letsencrypt/boulder/mocks"
"github.com/letsencrypt/boulder/must"
"github.com/letsencrypt/boulder/nonce"
noncepb "github.com/letsencrypt/boulder/nonce/proto"
"github.com/letsencrypt/boulder/probs"
rapb "github.com/letsencrypt/boulder/ra/proto"
"github.com/letsencrypt/boulder/ratelimits"
bredis "github.com/letsencrypt/boulder/redis"
"github.com/letsencrypt/boulder/revocation"
sapb "github.com/letsencrypt/boulder/sa/proto"
"github.com/letsencrypt/boulder/test"
inmemnonce "github.com/letsencrypt/boulder/test/inmem/nonce"
"github.com/letsencrypt/boulder/unpause"
"github.com/letsencrypt/boulder/web"
)
const (
agreementURL = "http://example.invalid/terms"
test1KeyPublicJSON = `
{
"kty":"RSA",
"n":"yNWVhtYEKJR21y9xsHV-PD_bYwbXSeNuFal46xYxVfRL5mqha7vttvjB_vc7Xg2RvgCxHPCqoxgMPTzHrZT75LjCwIW2K_klBYN8oYvTww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+p5yMmeOIBnSSF
MEPxEkK7zDlRETPzfP0Kf86WoLNviz2XfFmOXqXIj2w5RuOvB/6DdmwOpr/aiPLj
EulwPw0CgYAMSzsWOt6vU+y/G5NyhUCHvY50TdnGOj2btBk9rYVwWGWxCpg2QF0R
pcKXgGzXEVZKFAqB8V1c/mmCo8ojPgmqGM+GzX2Bj4seVBW7PsTeZUjrHpADshjV
F7o5b7y92NlxO5kwQzRKEAhwS5PbKJdx90iCuG+JlI1YgWlA1VcJMw==
-----END RSA PRIVATE KEY-----
`
testE1KeyPrivatePEM = `
-----BEGIN EC PRIVATE KEY-----
MHcCAQEEIH+p32RUnqT/iICBEGKrLIWFcyButv0S0lU/BLPOyHn2oAoGCCqGSM49
AwEHoUQDQgAEFwvSZpu06i3frSk/mz9HcD9nETn4wf3mQ+zDtG21GapLytH7R1Zr
ycBzDV9u6cX9qNLc9Bn5DAumz7Zp2AuA+Q==
-----END EC PRIVATE KEY-----
`
testE2KeyPrivatePEM = `
-----BEGIN EC PRIVATE KEY-----
MHcCAQEEIFRcPxQ989AY6se2RyIoF1ll9O6gHev4oY15SWJ+Jf5eoAoGCCqGSM49
AwEHoUQDQgAES8FOmrZ3ywj4yyFqt0etAD90U+EnkNaOBSLfQmf7pNi8y+kPKoUN
EeMZ9nWyIM6bktLrE11HnFOnKhAYsM5fZA==
-----END EC PRIVATE KEY-----`
)
type MockRegistrationAuthority struct {
rapb.RegistrationAuthorityClient
clk clock.Clock
lastRevocationReason revocation.Reason
}
func (ra *MockRegistrationAuthority) NewRegistration(ctx context.Context, in *corepb.Registration, _ ...grpc.CallOption) (*corepb.Registration, error) {
in.Id = 1
created := time.Date(2021, 1, 1, 0, 0, 0, 0, time.UTC)
in.CreatedAt = timestamppb.New(created)
return in, nil
}
func (ra *MockRegistrationAuthority) UpdateRegistration(ctx context.Context, in *rapb.UpdateRegistrationRequest, _ ...grpc.CallOption) (*corepb.Registration, error) {
if !bytes.Equal(in.Base.Key, in.Update.Key) {
in.Base.Key = in.Update.Key
}
return in.Base, nil
}
func (ra *MockRegistrationAuthority) PerformValidation(context.Context, *rapb.PerformValidationRequest, ...grpc.CallOption) (*corepb.Authorization, error) {
return &corepb.Authorization{}, nil
}
func (ra *MockRegistrationAuthority) RevokeCertByApplicant(ctx context.Context, in *rapb.RevokeCertByApplicantRequest, _ ...grpc.CallOption) (*emptypb.Empty, error) {
ra.lastRevocationReason = revocation.Reason(in.Code)
return &emptypb.Empty{}, nil
}
func (ra *MockRegistrationAuthority) RevokeCertByKey(ctx context.Context, in *rapb.RevokeCertByKeyRequest, _ ...grpc.CallOption) (*emptypb.Empty, error) {
ra.lastRevocationReason = revocation.Reason(ocsp.KeyCompromise)
return &emptypb.Empty{}, nil
}
// GetAuthorization returns a different authorization depending on the requested
// ID. All authorizations are associated with RegID 1, except for the one that isn't.
func (ra *MockRegistrationAuthority) GetAuthorization(_ context.Context, in *rapb.GetAuthorizationRequest, _ ...grpc.CallOption) (*corepb.Authorization, error) {
switch in.Id {
case 1: // Return a valid authorization with a single valid challenge.
return &corepb.Authorization{
Id: "1",
RegistrationID: 1,
DnsName: "not-an-example.com",
Status: string(core.StatusValid),
Expires: timestamppb.New(ra.clk.Now().AddDate(100, 0, 0)),
Challenges: []*corepb.Challenge{
{Id: 1, Type: "http-01", Status: string(core.StatusValid), Token: "token"},
},
}, nil
case 2: // Return a pending authorization with three pending challenges.
return &corepb.Authorization{
Id: "2",
RegistrationID: 1,
DnsName: "not-an-example.com",
Status: string(core.StatusPending),
Expires: timestamppb.New(ra.clk.Now().AddDate(100, 0, 0)),
Challenges: []*corepb.Challenge{
{Id: 1, Type: "http-01", Status: string(core.StatusPending), Token: "token"},
{Id: 2, Type: "dns-01", Status: string(core.StatusPending), Token: "token"},
{Id: 3, Type: "tls-alpn-01", Status: string(core.StatusPending), Token: "token"},
},
}, nil
case 3: // Return an expired authorization with three pending (but expired) challenges.
return &corepb.Authorization{
Id: "3",
RegistrationID: 1,
DnsName: "not-an-example.com",
Status: string(core.StatusPending),
Expires: timestamppb.New(ra.clk.Now().AddDate(-1, 0, 0)),
Challenges: []*corepb.Challenge{
{Id: 1, Type: "http-01", Status: string(core.StatusPending), Token: "token"},
{Id: 2, Type: "dns-01", Status: string(core.StatusPending), Token: "token"},
{Id: 3, Type: "tls-alpn-01", Status: string(core.StatusPending), Token: "token"},
},
}, nil
case 4: // Return an internal server error.
return nil, fmt.Errorf("unspecified error")
case 5: // Return a pending authorization as above, but associated with RegID 2.
return &corepb.Authorization{
Id: "5",
RegistrationID: 2,
DnsName: "not-an-example.com",
Status: string(core.StatusPending),
Expires: timestamppb.New(ra.clk.Now().AddDate(100, 0, 0)),
Challenges: []*corepb.Challenge{
{Id: 1, Type: "http-01", Status: string(core.StatusPending), Token: "token"},
{Id: 2, Type: "dns-01", Status: string(core.StatusPending), Token: "token"},
{Id: 3, Type: "tls-alpn-01", Status: string(core.StatusPending), Token: "token"},
},
}, nil
}
return nil, berrors.NotFoundError("no authorization found with id %q", in.Id)
}
func (ra *MockRegistrationAuthority) DeactivateAuthorization(context.Context, *corepb.Authorization, ...grpc.CallOption) (*emptypb.Empty, error) {
return &emptypb.Empty{}, nil
}
func (ra *MockRegistrationAuthority) DeactivateRegistration(context.Context, *corepb.Registration, ...grpc.CallOption) (*emptypb.Empty, error) {
return &emptypb.Empty{}, nil
}
func (ra *MockRegistrationAuthority) NewOrder(ctx context.Context, in *rapb.NewOrderRequest, _ ...grpc.CallOption) (*corepb.Order, error) {
created := time.Date(2021, 1, 1, 1, 1, 1, 0, time.UTC)
expires := time.Date(2021, 2, 1, 1, 1, 1, 0, time.UTC)
return &corepb.Order{
Id: 1,
RegistrationID: in.RegistrationID,
Created: timestamppb.New(created),
Expires: timestamppb.New(expires),
DnsNames: in.DnsNames,
Status: string(core.StatusPending),
V2Authorizations: []int64{1},
}, nil
}
func (ra *MockRegistrationAuthority) FinalizeOrder(ctx context.Context, in *rapb.FinalizeOrderRequest, _ ...grpc.CallOption) (*corepb.Order, error) {
in.Order.Status = string(core.StatusProcessing)
return in.Order, nil
}
func makeBody(s string) io.ReadCloser {
return io.NopCloser(strings.NewReader(s))
}
// loadKey loads a private key from PEM/DER-encoded data and returns
// a `crypto.Signer`.
func loadKey(t *testing.T, keyBytes []byte) crypto.Signer {
// pem.Decode does not return an error as its 2nd arg, but instead the "rest"
// that was leftover from parsing the PEM block. We only care if the decoded
// PEM block was empty for this test function.
block, _ := pem.Decode(keyBytes)
if block == nil {
t.Fatal("Unable to decode private key PEM bytes")
}
// Try decoding as an RSA private key
if rsaKey, err := x509.ParsePKCS1PrivateKey(block.Bytes); err == nil {
return rsaKey
}
// Try decoding as a PKCS8 private key
if key, err := x509.ParsePKCS8PrivateKey(block.Bytes); err == nil {
// Determine the key's true type and return it as a crypto.Signer
switch k := key.(type) {
case *rsa.PrivateKey:
return k
case *ecdsa.PrivateKey:
return k
}
}
// Try as an ECDSA private key
if ecdsaKey, err := x509.ParseECPrivateKey(block.Bytes); err == nil {
return ecdsaKey
}
// Nothing worked! Fail hard.
t.Fatalf("Unable to decode private key PEM bytes")
// NOOP - the t.Fatal() call will abort before this return
return nil
}
var ctx = context.Background()
func setupWFE(t *testing.T) (WebFrontEndImpl, clock.FakeClock, requestSigner) {
features.Reset()
fc := clock.NewFake()
stats := metrics.NoopRegisterer
testKeyPolicy, err := goodkey.NewPolicy(nil, nil)
test.AssertNotError(t, err, "creating test keypolicy")
certChains := map[issuance.NameID][][]byte{}
issuerCertificates := map[issuance.NameID]*issuance.Certificate{}
for _, files := range [][]string{
{
"../test/hierarchy/int-r3.cert.pem",
"../test/hierarchy/root-x1.cert.pem",
},
{
"../test/hierarchy/int-r3-cross.cert.pem",
"../test/hierarchy/root-dst.cert.pem",
},
{
"../test/hierarchy/int-e1.cert.pem",
"../test/hierarchy/root-x2.cert.pem",
},
{
"../test/hierarchy/int-e1.cert.pem",
"../test/hierarchy/root-x2-cross.cert.pem",
"../test/hierarchy/root-x1-cross.cert.pem",
"../test/hierarchy/root-dst.cert.pem",
},
} {
certs, err := issuance.LoadChain(files)
test.AssertNotError(t, err, "Unable to load chain")
var buf bytes.Buffer
for _, cert := range certs {
buf.Write([]byte("\n"))
buf.Write(pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: cert.Raw}))
}
id := certs[0].NameID()
certChains[id] = append(certChains[id], buf.Bytes())
issuerCertificates[id] = certs[0]
}
mockSA := mocks.NewStorageAuthorityReadOnly(fc)
log := blog.NewMock()
// Use derived nonces.
noncePrefix := nonce.DerivePrefix("192.168.1.1:8080", "b8c758dd85e113ea340ce0b3a99f389d40a308548af94d1730a7692c1874f1f")
nonceService, err := nonce.NewNonceService(metrics.NoopRegisterer, 100, noncePrefix)
test.AssertNotError(t, err, "making nonceService")
inmemNonceService := &inmemnonce.Service{NonceService: nonceService}
gnc := inmemNonceService
rnc := inmemNonceService
// Setup rate limiting.
rc := bredis.Config{
Username: "unittest-rw",
TLS: cmd.TLSConfig{
CACertFile: "../test/certs/ipki/minica.pem",
CertFile: "../test/certs/ipki/localhost/cert.pem",
KeyFile: "../test/certs/ipki/localhost/key.pem",
},
Lookups: []cmd.ServiceDomain{
{
Service: "redisratelimits",
Domain: "service.consul",
},
},
LookupDNSAuthority: "consul.service.consul",
}
rc.PasswordConfig = cmd.PasswordConfig{
PasswordFile: "../test/secrets/ratelimits_redis_password",
}
ring, err := bredis.NewRingFromConfig(rc, stats, log)
test.AssertNotError(t, err, "making redis ring client")
source := ratelimits.NewRedisSource(ring.Ring, fc, stats)
test.AssertNotNil(t, source, "source should not be nil")
limiter, err := ratelimits.NewLimiter(fc, source, stats)
test.AssertNotError(t, err, "making limiter")
txnBuilder, err := ratelimits.NewTransactionBuilder("../test/config-next/wfe2-ratelimit-defaults.yml", "")
test.AssertNotError(t, err, "making transaction composer")
var unpauseSigner unpause.JWTSigner
var unpauseLifetime time.Duration
var unpauseURL string
if os.Getenv("BOULDER_CONFIG_DIR") == "test/config-next" {
unpauseSigner, err = unpause.NewJWTSigner(cmd.HMACKeyConfig{KeyFile: "../test/secrets/sfe_unpause_key"})
test.AssertNotError(t, err, "making unpause signer")
unpauseLifetime = time.Hour * 24 * 14
unpauseURL = "https://boulder.service.consul:4003"
}
wfe, err := NewWebFrontEndImpl(
stats,
fc,
testKeyPolicy,
certChains,
issuerCertificates,
blog.NewMock(),
10*time.Second,
10*time.Second,
30*24*time.Hour,
7*24*time.Hour,
&MockRegistrationAuthority{clk: fc},
mockSA,
gnc,
rnc,
"rncKey",
mockSA,
limiter,
txnBuilder,
100,
nil,
unpauseSigner,
unpauseLifetime,
unpauseURL,
)
test.AssertNotError(t, err, "Unable to create WFE")
wfe.SubscriberAgreementURL = agreementURL
return wfe, fc, requestSigner{t, inmemNonceService.AsSource()}
}
// makePostRequestWithPath creates an http.Request for localhost with method
// POST, the provided body, and the correct Content-Length. The path provided
// will be parsed as a URL and used to populate the request URL and RequestURI
func makePostRequestWithPath(path string, body string) *http.Request {
request := &http.Request{
Method: "POST",
RemoteAddr: "1.1.1.1:7882",
Header: map[string][]string{
"Content-Length": {strconv.Itoa(len(body))},
"Content-Type": {expectedJWSContentType},
},
Body: makeBody(body),
Host: "localhost",
}
url := mustParseURL(path)
request.URL = url
request.RequestURI = url.Path
return request
}
// signAndPost constructs a JWS signed by the account with ID 1, over the given
// payload, with the protected URL set to the provided signedURL. An HTTP
// request constructed to the provided path with the encoded JWS body as the
// POST body is returned.
func signAndPost(signer requestSigner, path, signedURL, payload string) *http.Request {
_, _, body := signer.byKeyID(1, nil, signedURL, payload)
return makePostRequestWithPath(path, body)
}
func mustParseURL(s string) *url.URL {
return must.Do(url.Parse(s))
}
func sortHeader(s string) string {
a := strings.Split(s, ", ")
sort.Strings(a)
return strings.Join(a, ", ")
}
func addHeadIfGet(s []string) []string {
for _, a := range s {
if a == "GET" {
return append(s, "HEAD")
}
}
return s
}
func TestHandleFunc(t *testing.T) {
wfe, _, _ := setupWFE(t)
var mux *http.ServeMux
var rw *httptest.ResponseRecorder
var stubCalled bool
runWrappedHandler := func(req *http.Request, pattern string, allowed ...string) {
mux = http.NewServeMux()
rw = httptest.NewRecorder()
stubCalled = false
wfe.HandleFunc(mux, pattern, func(context.Context, *web.RequestEvent, http.ResponseWriter, *http.Request) {
stubCalled = true
}, allowed...)
req.URL = mustParseURL(pattern)
mux.ServeHTTP(rw, req)
}
// Plain requests (no CORS)
type testCase struct {
allowed []string
reqMethod string
shouldCallStub bool
shouldSucceed bool
pattern string
}
var lastNonce string
for _, c := range []testCase{
{[]string{"GET", "POST"}, "GET", true, true, "/test"},
{[]string{"GET", "POST"}, "GET", true, true, newNoncePath},
{[]string{"GET", "POST"}, "POST", true, true, "/test"},
{[]string{"GET"}, "", false, false, "/test"},
{[]string{"GET"}, "POST", false, false, "/test"},
{[]string{"GET"}, "OPTIONS", false, true, "/test"},
{[]string{"GET"}, "MAKE-COFFEE", false, false, "/test"}, // 405, or 418?
{[]string{"GET"}, "GET", true, true, directoryPath},
} {
runWrappedHandler(&http.Request{Method: c.reqMethod}, c.pattern, c.allowed...)
test.AssertEquals(t, stubCalled, c.shouldCallStub)
if c.shouldSucceed {
test.AssertEquals(t, rw.Code, http.StatusOK)
} else {
test.AssertEquals(t, rw.Code, http.StatusMethodNotAllowed)
test.AssertEquals(t, sortHeader(rw.Header().Get("Allow")), sortHeader(strings.Join(addHeadIfGet(c.allowed), ", ")))
test.AssertUnmarshaledEquals(t,
rw.Body.String(),
`{"type":"`+probs.ErrorNS+`malformed","detail":"Method not allowed","status":405}`)
}
if c.reqMethod == "GET" && c.pattern != newNoncePath {
nonce := rw.Header().Get("Replay-Nonce")
test.AssertEquals(t, nonce, "")
} else {
nonce := rw.Header().Get("Replay-Nonce")
test.AssertNotEquals(t, nonce, lastNonce)
test.AssertNotEquals(t, nonce, "")
lastNonce = nonce
}
linkHeader := rw.Header().Get("Link")
if c.pattern != directoryPath {
// If the pattern wasn't the directory there should be a Link header for the index
test.AssertEquals(t, linkHeader, `<http://localhost/directory>;rel="index"`)
} else {
// The directory resource shouldn't get a link header
test.AssertEquals(t, linkHeader, "")
}
}
// Disallowed method returns error JSON in body
runWrappedHandler(&http.Request{Method: "PUT"}, "/test", "GET", "POST")
test.AssertEquals(t, rw.Header().Get("Content-Type"), "application/problem+json")
test.AssertUnmarshaledEquals(t, rw.Body.String(), `{"type":"`+probs.ErrorNS+`malformed","detail":"Method not allowed","status":405}`)
test.AssertEquals(t, sortHeader(rw.Header().Get("Allow")), "GET, HEAD, POST")
// Disallowed method special case: response to HEAD has got no body
runWrappedHandler(&http.Request{Method: "HEAD"}, "/test", "GET", "POST")
test.AssertEquals(t, stubCalled, true)
test.AssertEquals(t, rw.Body.String(), "")
// HEAD doesn't work with POST-only endpoints
runWrappedHandler(&http.Request{Method: "HEAD"}, "/test", "POST")
test.AssertEquals(t, stubCalled, false)
test.AssertEquals(t, rw.Code, http.StatusMethodNotAllowed)
test.AssertEquals(t, rw.Header().Get("Content-Type"), "application/problem+json")
test.AssertEquals(t, rw.Header().Get("Allow"), "POST")
test.AssertUnmarshaledEquals(t, rw.Body.String(), `{"type":"`+probs.ErrorNS+`malformed","detail":"Method not allowed","status":405}`)
wfe.AllowOrigins = []string{"*"}
testOrigin := "https://example.com"
// CORS "actual" request for disallowed method
runWrappedHandler(&http.Request{
Method: "POST",
Header: map[string][]string{
"Origin": {testOrigin},
},
}, "/test", "GET")
test.AssertEquals(t, stubCalled, false)
test.AssertEquals(t, rw.Code, http.StatusMethodNotAllowed)
// CORS "actual" request for allowed method
runWrappedHandler(&http.Request{
Method: "GET",
Header: map[string][]string{
"Origin": {testOrigin},
},
}, "/test", "GET", "POST")
test.AssertEquals(t, stubCalled, true)
test.AssertEquals(t, rw.Code, http.StatusOK)
test.AssertEquals(t, rw.Header().Get("Access-Control-Allow-Methods"), "")
test.AssertEquals(t, rw.Header().Get("Access-Control-Allow-Origin"), "*")
test.AssertEquals(t, rw.Header().Get("Access-Control-Allow-Headers"), "Content-Type")
test.AssertEquals(t, sortHeader(rw.Header().Get("Access-Control-Expose-Headers")), "Link, Location, Replay-Nonce")
// CORS preflight request for disallowed method
runWrappedHandler(&http.Request{
Method: "OPTIONS",
Header: map[string][]string{
"Origin": {testOrigin},
"Access-Control-Request-Method": {"POST"},
},
}, "/test", "GET")
test.AssertEquals(t, stubCalled, false)
test.AssertEquals(t, rw.Code, http.StatusOK)
test.AssertEquals(t, rw.Header().Get("Allow"), "GET, HEAD")
test.AssertEquals(t, rw.Header().Get("Access-Control-Allow-Origin"), "")
test.AssertEquals(t, rw.Header().Get("Access-Control-Allow-Headers"), "")
// CORS preflight request for allowed method
runWrappedHandler(&http.Request{
Method: "OPTIONS",
Header: map[string][]string{
"Origin": {testOrigin},
"Access-Control-Request-Method": {"POST"},
"Access-Control-Request-Headers": {"X-Accept-Header1, X-Accept-Header2", "X-Accept-Header3"},
},
}, "/test", "GET", "POST")
test.AssertEquals(t, rw.Code, http.StatusOK)
test.AssertEquals(t, rw.Header().Get("Access-Control-Allow-Origin"), "*")
test.AssertEquals(t, rw.Header().Get("Access-Control-Allow-Headers"), "Content-Type")
test.AssertEquals(t, rw.Header().Get("Access-Control-Max-Age"), "86400")
test.AssertEquals(t, sortHeader(rw.Header().Get("Access-Control-Allow-Methods")), "GET, HEAD, POST")
test.AssertEquals(t, sortHeader(rw.Header().Get("Access-Control-Expose-Headers")), "Link, Location, Replay-Nonce")
// OPTIONS request without an Origin header (i.e., not a CORS
// preflight request)
runWrappedHandler(&http.Request{
Method: "OPTIONS",
Header: map[string][]string{
"Access-Control-Request-Method": {"POST"},
},
}, "/test", "GET", "POST")
test.AssertEquals(t, rw.Code, http.StatusOK)
test.AssertEquals(t, rw.Header().Get("Access-Control-Allow-Origin"), "")
test.AssertEquals(t, rw.Header().Get("Access-Control-Allow-Headers"), "")
test.AssertEquals(t, sortHeader(rw.Header().Get("Allow")), "GET, HEAD, POST")
// CORS preflight request missing optional Request-Method
// header. The "actual" request will be GET.
for _, allowedMethod := range []string{"GET", "POST"} {
runWrappedHandler(&http.Request{
Method: "OPTIONS",
Header: map[string][]string{
"Origin": {testOrigin},
},
}, "/test", allowedMethod)
test.AssertEquals(t, rw.Code, http.StatusOK)
if allowedMethod == "GET" {
test.AssertEquals(t, rw.Header().Get("Access-Control-Allow-Origin"), "*")
test.AssertEquals(t, rw.Header().Get("Access-Control-Allow-Headers"), "Content-Type")
test.AssertEquals(t, rw.Header().Get("Access-Control-Allow-Methods"), "GET, HEAD")
} else {
test.AssertEquals(t, rw.Header().Get("Access-Control-Allow-Origin"), "")
test.AssertEquals(t, rw.Header().Get("Access-Control-Allow-Headers"), "")
}
}
// No CORS headers are given when configuration does not list
// "*" or the client-provided origin.
for _, wfe.AllowOrigins = range [][]string{
{},
{"http://example.com", "https://other.example"},
{""}, // Invalid origin is never matched
} {
runWrappedHandler(&http.Request{
Method: "OPTIONS",
Header: map[string][]string{
"Origin": {testOrigin},
"Access-Control-Request-Method": {"POST"},
},
}, "/test", "POST")
test.AssertEquals(t, rw.Code, http.StatusOK)
for _, h := range []string{
"Access-Control-Allow-Methods",
"Access-Control-Allow-Origin",
"Access-Control-Allow-Headers",
"Access-Control-Expose-Headers",
"Access-Control-Request-Headers",
} {
test.AssertEquals(t, rw.Header().Get(h), "")
}
}
// CORS headers are offered when configuration lists "*" or
// the client-provided origin.
for _, wfe.AllowOrigins = range [][]string{
{testOrigin, "http://example.org", "*"},
{"", "http://example.org", testOrigin}, // Invalid origin is harmless
} {
runWrappedHandler(&http.Request{
Method: "OPTIONS",
Header: map[string][]string{
"Origin": {testOrigin},
"Access-Control-Request-Method": {"POST"},
},
}, "/test", "POST")
test.AssertEquals(t, rw.Code, http.StatusOK)
test.AssertEquals(t, rw.Header().Get("Access-Control-Allow-Origin"), testOrigin)
// http://www.w3.org/TR/cors/ section 6.4:
test.AssertEquals(t, rw.Header().Get("Vary"), "Origin")
}
}
func TestPOST404(t *testing.T) {
wfe, _, _ := setupWFE(t)
responseWriter := httptest.NewRecorder()
url, _ := url.Parse("/foobar")
wfe.Index(ctx, newRequestEvent(), responseWriter, &http.Request{
Method: "POST",
URL: url,
})
test.AssertEquals(t, responseWriter.Code, http.StatusNotFound)
}
func TestIndex(t *testing.T) {
wfe, _, _ := setupWFE(t)
responseWriter := httptest.NewRecorder()
url, _ := url.Parse("/")
wfe.Index(ctx, newRequestEvent(), responseWriter, &http.Request{
Method: "GET",
URL: url,
})
test.AssertEquals(t, responseWriter.Code, http.StatusOK)
test.AssertNotEquals(t, responseWriter.Body.String(), "404 page not found\n")
test.Assert(t, strings.Contains(responseWriter.Body.String(), directoryPath),
"directory path not found")
test.AssertEquals(t, responseWriter.Header().Get("Cache-Control"), "public, max-age=0, no-cache")
responseWriter.Body.Reset()
responseWriter.Header().Del("Cache-Control")
url, _ = url.Parse("/foo")
wfe.Index(ctx, newRequestEvent(), responseWriter, &http.Request{
URL: url,
})
//test.AssertEquals(t, responseWriter.Code, http.StatusNotFound)
test.AssertEquals(t, responseWriter.Body.String(), "404 page not found\n")
test.AssertEquals(t, responseWriter.Header().Get("Cache-Control"), "")
}
// randomDirectoryKeyPresent unmarshals the given buf of JSON and returns true
// if `randomDirKeyExplanationLink` appears as the value of a key in the directory
// object.
func randomDirectoryKeyPresent(t *testing.T, buf []byte) bool {
var dir map[string]interface{}
err := json.Unmarshal(buf, &dir)
if err != nil {
t.Errorf("Failed to unmarshal directory: %s", err)
}
for _, v := range dir {
if v == randomDirKeyExplanationLink {
return true
}
}
return false
}
type fakeRand struct{}
func (fr fakeRand) Read(p []byte) (int, error) {
return len(p), nil
}
func TestDirectory(t *testing.T) {
wfe, _, signer := setupWFE(t)
mux := wfe.Handler(metrics.NoopRegisterer)
core.RandReader = fakeRand{}
defer func() { core.RandReader = rand.Reader }()
dirURL, _ := url.Parse("/directory")
getReq := &http.Request{
Method: http.MethodGet,
URL: dirURL,
Host: "localhost:4300",
}
_, _, jwsBody := signer.byKeyID(1, nil, "http://localhost/directory", "")
postAsGetReq := makePostRequestWithPath("/directory", jwsBody)
testCases := []struct {
name string
caaIdent string
website string
expectedJSON string
request *http.Request
}{
{
name: "standard GET, no CAA ident/website meta",
request: getReq,
expectedJSON: `{
"keyChange": "http://localhost:4300/acme/key-change",
"meta": {
"termsOfService": "http://example.invalid/terms"
},
"newNonce": "http://localhost:4300/acme/new-nonce",
"newAccount": "http://localhost:4300/acme/new-acct",
"newOrder": "http://localhost:4300/acme/new-order",
"revokeCert": "http://localhost:4300/acme/revoke-cert",
"AAAAAAAAAAA": "https://community.letsencrypt.org/t/adding-random-entries-to-the-directory/33417"
}`,
},
{
name: "standard GET, CAA ident/website meta",
caaIdent: "Radiant Lock",
website: "zombo.com",
request: getReq,
expectedJSON: `{
"AAAAAAAAAAA": "https://community.letsencrypt.org/t/adding-random-entries-to-the-directory/33417",
"keyChange": "http://localhost:4300/acme/key-change",
"meta": {
"caaIdentities": [
"Radiant Lock"
],
"termsOfService": "http://example.invalid/terms",
"website": "zombo.com"
},
"newAccount": "http://localhost:4300/acme/new-acct",
"newNonce": "http://localhost:4300/acme/new-nonce",
"newOrder": "http://localhost:4300/acme/new-order",
"revokeCert": "http://localhost:4300/acme/revoke-cert"
}`,
},
{
name: "POST-as-GET, CAA ident/website meta",
caaIdent: "Radiant Lock",
website: "zombo.com",
request: postAsGetReq,
expectedJSON: `{
"AAAAAAAAAAA": "https://community.letsencrypt.org/t/adding-random-entries-to-the-directory/33417",
"keyChange": "http://localhost/acme/key-change",
"meta": {
"caaIdentities": [
"Radiant Lock"
],
"termsOfService": "http://example.invalid/terms",
"website": "zombo.com"
},
"newAccount": "http://localhost/acme/new-acct",
"newNonce": "http://localhost/acme/new-nonce",
"newOrder": "http://localhost/acme/new-order",
"revokeCert": "http://localhost/acme/revoke-cert"
}`,
},
}
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
// Configure a caaIdentity and website for the /directory meta based on the tc
wfe.DirectoryCAAIdentity = tc.caaIdent // "Radiant Lock"
wfe.DirectoryWebsite = tc.website //"zombo.com"
responseWriter := httptest.NewRecorder()
// Serve the /directory response for this request into a recorder
mux.ServeHTTP(responseWriter, tc.request)
// We expect all directory requests to return a json object with a good HTTP status
test.AssertEquals(t, responseWriter.Header().Get("Content-Type"), "application/json")
// We expect all requests to return status OK
test.AssertEquals(t, responseWriter.Code, http.StatusOK)
// The response should match expected
test.AssertUnmarshaledEquals(t, responseWriter.Body.String(), tc.expectedJSON)
// Check that the random directory key is present
test.AssertEquals(t,
randomDirectoryKeyPresent(t, responseWriter.Body.Bytes()),
true)
})
}
}
func TestRelativeDirectory(t *testing.T) {
wfe, _, _ := setupWFE(t)
mux := wfe.Handler(metrics.NoopRegisterer)
core.RandReader = fakeRand{}
defer func() { core.RandReader = rand.Reader }()
expectedDirectory := func(hostname string) string {
expected := new(bytes.Buffer)
fmt.Fprintf(expected, "{")
fmt.Fprintf(expected, `"keyChange":"%s/acme/key-change",`, hostname)
fmt.Fprintf(expected, `"newNonce":"%s/acme/new-nonce",`, hostname)
fmt.Fprintf(expected, `"newAccount":"%s/acme/new-acct",`, hostname)
fmt.Fprintf(expected, `"newOrder":"%s/acme/new-order",`, hostname)
fmt.Fprintf(expected, `"revokeCert":"%s/acme/revoke-cert",`, hostname)
fmt.Fprintf(expected, `"AAAAAAAAAAA":"https://community.letsencrypt.org/t/adding-random-entries-to-the-directory/33417",`)
fmt.Fprintf(expected, `"meta":{"termsOfService":"http://example.invalid/terms"}`)
fmt.Fprintf(expected, "}")
return expected.String()
}
dirTests := []struct {
host string
protoHeader string
result string
}{
// Test '' (No host header) with no proto header
{"", "", expectedDirectory("http://localhost")},
// Test localhost:4300 with no proto header
{"localhost:4300", "", expectedDirectory("http://localhost:4300")},
// Test 127.0.0.1:4300 with no proto header
{"127.0.0.1:4300", "", expectedDirectory("http://127.0.0.1:4300")},
// Test localhost:4300 with HTTP proto header
{"localhost:4300", "http", expectedDirectory("http://localhost:4300")},
// Test localhost:4300 with HTTPS proto header
{"localhost:4300", "https", expectedDirectory("https://localhost:4300")},
}
for _, tt := range dirTests {
var headers map[string][]string
responseWriter := httptest.NewRecorder()
if tt.protoHeader != "" {
headers = map[string][]string{
"X-Forwarded-Proto": {tt.protoHeader},
}
}
mux.ServeHTTP(responseWriter, &http.Request{
Method: "GET",
Host: tt.host,
URL: mustParseURL(directoryPath),
Header: headers,
})
test.AssertEquals(t, responseWriter.Header().Get("Content-Type"), "application/json")
test.AssertEquals(t, responseWriter.Code, http.StatusOK)
test.AssertUnmarshaledEquals(t, responseWriter.Body.String(), tt.result)
}
}
// TestNonceEndpoint tests requests to the WFE2's new-nonce endpoint
func TestNonceEndpoint(t *testing.T) {
wfe, _, signer := setupWFE(t)
mux := wfe.Handler(metrics.NoopRegisterer)
getReq := &http.Request{
Method: http.MethodGet,
URL: mustParseURL(newNoncePath),
}
headReq := &http.Request{
Method: http.MethodHead,
URL: mustParseURL(newNoncePath),
}
_, _, jwsBody := signer.byKeyID(1, nil, fmt.Sprintf("http://localhost%s", newNoncePath), "")
postAsGetReq := makePostRequestWithPath(newNoncePath, jwsBody)
testCases := []struct {
name string
request *http.Request
expectedStatus int
}{
{
name: "GET new-nonce request",
request: getReq,
expectedStatus: http.StatusNoContent,
},
{
name: "HEAD new-nonce request",