-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathverify_test.go
More file actions
3121 lines (2960 loc) · 95.5 KB
/
Copy pathverify_test.go
File metadata and controls
3121 lines (2960 loc) · 95.5 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 internal
import (
"context"
"crypto"
"crypto/ecdsa"
"crypto/ed25519"
"crypto/elliptic"
"crypto/rand"
"crypto/rsa"
"crypto/x509"
"crypto/x509/pkix"
"encoding/asn1"
"encoding/json"
"fmt"
"math/big"
"net/http"
"net/http/httptest"
"slices"
"strings"
"sync/atomic"
"testing"
"time"
"github.com/sensiblebit/certkit"
"golang.org/x/crypto/ocsp"
)
func TestVerifyCert_KeyMatch(t *testing.T) {
// WHY: Verifies VerifyCert correctly detects both key-certificate match
// and mismatch. A false negative excludes valid keys; a false positive
// allows deploying certs with wrong keys.
t.Parallel()
ca := newRSACA(t)
leaf := newRSALeaf(t, ca, "verify-rsa.example.com", []string{"verify-rsa.example.com"}, nil)
ecdsaCA := newECDSACA(t)
ecdsaLeaf := newECDSALeaf(t, ecdsaCA, "verify-ecdsa.example.com", []string{"verify-ecdsa.example.com"})
edPublic, edPrivate, err := ed25519.GenerateKey(rand.Reader)
if err != nil {
t.Fatal(err)
}
edTemplate := &x509.Certificate{
SerialNumber: randomSerial(t),
Subject: pkix.Name{CommonName: "verify-ed25519.example.com"},
NotBefore: time.Now().Add(-time.Hour),
NotAfter: time.Now().Add(24 * time.Hour),
KeyUsage: x509.KeyUsageDigitalSignature,
ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
}
edDER, err := x509.CreateCertificate(rand.Reader, edTemplate, ca.cert, edPublic, ca.key.(*rsa.PrivateKey))
if err != nil {
t.Fatal(err)
}
edCert, err := x509.ParseCertificate(edDER)
if err != nil {
t.Fatal(err)
}
wrongKey, err := rsa.GenerateKey(rand.Reader, 2048)
if err != nil {
t.Fatal(err)
}
matchTrue := true
matchFalse := false
tests := []struct {
name string
cert *x509.Certificate
key any
wantMatch *bool
wantKeyErr bool
wantErrors bool
wantKeyInfo bool
wantErrSubs []string
}{
{"matching RSA key", leaf.cert, leaf.key, &matchTrue, false, false, true, nil},
{"matching ECDSA key", ecdsaLeaf.cert, ecdsaLeaf.key, &matchTrue, false, false, true, nil},
{"matching Ed25519 key", edCert, edPrivate, &matchTrue, false, false, true, nil},
{"mismatched key", leaf.cert, wrongKey, &matchFalse, false, true, true, []string{"key does not match certificate"}},
{"cross-algorithm mismatch", leaf.cert, ecdsaLeaf.key, &matchFalse, false, true, true, []string{"key does not match certificate"}},
{"unsupported key type", leaf.cert, struct{}{}, nil, true, true, false, []string{"unsupported private key type"}},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
// WHY: Ensures VerifyCert key matching handles this key input correctly.
t.Parallel()
result, err := VerifyCert(context.Background(), &VerifyInput{
Cert: tt.cert,
Key: tt.key,
CheckKeyMatch: true,
TrustStore: "custom",
})
if err != nil {
t.Fatal(err)
}
if tt.wantMatch == nil {
if result.KeyMatch != nil {
t.Errorf("expected KeyMatch to be nil, got %v", *result.KeyMatch)
}
} else {
if result.KeyMatch == nil {
t.Fatal("expected KeyMatch to be set")
}
if *result.KeyMatch != *tt.wantMatch {
t.Errorf("KeyMatch = %v, want %v", *result.KeyMatch, *tt.wantMatch)
}
}
if tt.wantKeyErr {
if result.KeyMatchErr == "" {
t.Error("expected KeyMatchErr to be set")
}
} else if result.KeyMatchErr != "" {
t.Errorf("expected no KeyMatchErr, got %q", result.KeyMatchErr)
}
if tt.wantKeyInfo {
if result.KeyInfo == "" {
t.Error("expected KeyInfo to be set")
}
} else if result.KeyInfo != "" {
t.Errorf("expected no KeyInfo, got %q", result.KeyInfo)
}
if tt.wantErrors && len(result.Errors) == 0 {
t.Error("expected errors to be populated")
}
if !tt.wantErrors && len(result.Errors) != 0 {
t.Errorf("expected no errors, got %v", result.Errors)
}
for _, want := range tt.wantErrSubs {
found := false
for _, errMsg := range result.Errors {
if strings.Contains(errMsg, want) {
found = true
break
}
}
if !found {
t.Errorf("expected error containing %q, got %v", want, result.Errors)
}
}
})
}
}
func TestVerifyCert_NilInputs(t *testing.T) {
// WHY: VerifyCert should fail fast on nil inputs and missing certificates.
t.Parallel()
tests := []struct {
name string
input *VerifyInput
}{
{name: "nil input", input: nil},
{name: "nil certificate", input: &VerifyInput{Cert: nil, TrustStore: "mozilla"}},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
// WHY: Ensures VerifyCert rejects this nil input scenario.
t.Parallel()
_, err := VerifyCert(context.Background(), tt.input)
if err == nil {
t.Fatalf("expected error for %s", tt.name)
}
})
}
}
func TestVerifyCert_NoTrustAnchors(t *testing.T) {
// WHY: VerifyCert should report chain failure when no trust source validates the leaf.
t.Parallel()
ca := newRSACA(t)
leaf := newRSALeaf(t, ca, "invalid-store.example.com", []string{"invalid-store.example.com"}, nil)
result, err := VerifyCert(context.Background(), &VerifyInput{
Cert: leaf.cert,
CheckChain: true,
})
if err != nil {
t.Fatal(err)
}
if result.ChainValid == nil || *result.ChainValid {
t.Fatalf("expected ChainValid false, got %v", result.ChainValid)
}
if !strings.Contains(result.ChainErr, "mozilla:") {
t.Errorf("expected ChainErr to mention mozilla attempt, got %q", result.ChainErr)
}
if strings.Contains(result.ChainErr, "system:") {
t.Errorf("did not expect ChainErr to mention system attempt, got %q", result.ChainErr)
}
if strings.Contains(result.ChainErr, "file:") {
t.Errorf("expected ChainErr not to mention file trust source when no file roots were requested, got %q", result.ChainErr)
}
if len(result.TrustAnchors) != 0 {
t.Errorf("expected no trust anchors, got %v", result.TrustAnchors)
}
}
func TestVerifyCert_InvalidTrustStore(t *testing.T) {
// WHY: VerifyCert still accepts TrustStore and should reject unsupported values
// instead of silently probing the default union.
t.Parallel()
ca := newRSACA(t)
leaf := newRSALeaf(t, ca, "invalid-trust-store.example.com", []string{"invalid-trust-store.example.com"}, nil)
result, err := VerifyCert(context.Background(), &VerifyInput{
Cert: leaf.cert,
CheckChain: true,
TrustStore: "invalid",
})
if err != nil {
t.Fatal(err)
}
if result.ChainValid == nil || *result.ChainValid {
t.Fatalf("expected ChainValid false, got %v", result.ChainValid)
}
if !strings.Contains(result.ChainErr, "unknown trust_store") {
t.Fatalf("expected ChainErr to mention unknown trust_store, got %q", result.ChainErr)
}
found := false
for _, errMsg := range result.Errors {
if strings.Contains(errMsg, "unknown trust_store") {
found = true
break
}
}
if !found {
t.Fatalf("expected Errors to preserve trust_store failure, got %v", result.Errors)
}
}
func TestVerifyCert_InvalidTrustStoreFailsBeforeAIA(t *testing.T) {
// WHY: Invalid trust_store should fail fast without triggering AIA/network work.
t.Parallel()
root := newRSACA(t)
intermediate := newRSAIntermediate(t, root)
var requests atomic.Int32
aiaServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
requests.Add(1)
http.Error(w, "issuer unavailable", http.StatusInternalServerError)
}))
t.Cleanup(aiaServer.Close)
leafKey, err := rsa.GenerateKey(rand.Reader, 2048)
if err != nil {
t.Fatal(err)
}
leafTemplate := &x509.Certificate{
SerialNumber: randomSerial(t),
Subject: pkix.Name{CommonName: "invalid-trust-store-aia.example.com", Organization: []string{"TestOrg"}},
DNSNames: []string{"invalid-trust-store-aia.example.com"},
NotBefore: time.Now().Add(-1 * time.Hour),
NotAfter: time.Now().Add(365 * 24 * time.Hour),
KeyUsage: x509.KeyUsageDigitalSignature | x509.KeyUsageKeyEncipherment,
ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
SubjectKeyId: []byte{0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda, 0xdb, 0xdc, 0xdd, 0xde, 0xdf, 0xe0, 0xe1, 0xe2, 0xe3, 0xe4},
AuthorityKeyId: intermediate.cert.SubjectKeyId,
IssuingCertificateURL: []string{aiaServer.URL + "/issuer.cer"},
}
leafDER, err := x509.CreateCertificate(rand.Reader, leafTemplate, intermediate.cert, &leafKey.PublicKey, intermediate.key.(*rsa.PrivateKey))
if err != nil {
t.Fatal(err)
}
leafCert, err := x509.ParseCertificate(leafDER)
if err != nil {
t.Fatal(err)
}
result, err := VerifyCert(context.Background(), &VerifyInput{
Cert: leafCert,
CheckChain: true,
TrustStore: "invalid",
AllowPrivateNetworks: true,
})
if err != nil {
t.Fatal(err)
}
if result.ChainValid == nil || *result.ChainValid {
t.Fatalf("expected ChainValid false, got %v", result.ChainValid)
}
if requests.Load() != 0 {
t.Fatalf("expected no AIA requests for invalid trust_store, got %d", requests.Load())
}
}
func TestVerifyCert_PreVerificationBundleIgnoresSystemTrustStore(t *testing.T) {
// WHY: The AIA/intermediate assembly pass should not require system roots
// before verify probes Mozilla/system/file trust sources explicitly.
root := newRSACA(t)
leaf := newRSALeaf(t, root, "prebundle.example.com", []string{"prebundle.example.com"}, nil)
ctx := context.WithValue(context.Background(), verifyBundleFuncKey{}, func(_ context.Context, input certkit.BundleInput) (*certkit.BundleResult, error) {
if input.Options.Verify {
t.Fatal("expected pre-verification bundle call to disable verification")
}
if input.Options.TrustStore != "custom" {
t.Fatalf("pre-verification bundle TrustStore = %q, want %q", input.Options.TrustStore, "custom")
}
if !input.Options.AllowPrivateNetworks {
t.Fatal("expected AllowPrivateNetworks to propagate into pre-verification bundle call")
}
if len(input.Options.CustomRoots) != 0 {
t.Fatalf("pre-verification bundle CustomRoots = %v, want empty", input.Options.CustomRoots)
}
return &certkit.BundleResult{Leaf: input.Leaf}, nil
})
result, err := VerifyCert(ctx, &VerifyInput{
Cert: leaf.cert,
CheckChain: true,
TrustStore: "custom",
CustomRoots: []*x509.Certificate{root.cert},
AllowPrivateNetworks: true,
})
if err != nil {
t.Fatal(err)
}
if result.ChainValid == nil || !*result.ChainValid {
t.Fatalf("expected ChainValid true, got %v (err=%q)", result.ChainValid, result.ChainErr)
}
}
func TestVerifyCert_PreBundleAIAIncompleteNotMisreported(t *testing.T) {
// WHY: The pre-verification bundle walk uses TrustStore="custom" with no
// roots, so Bundle may set AIAIncomplete=true because
// countAIAUnresolvedIssuers cannot match against an empty root pool. When
// trust probing subsequently fails (e.g. custom store with wrong roots),
// the error should NOT say "AIA resolution incomplete" — it should report
// the real trust source failure.
t.Parallel()
root := newRSACA(t)
otherRoot := newRSACA(t) // wrong root — will not verify the leaf
leaf := newRSALeaf(t, root, "aia-misreport.example.com", []string{"aia-misreport.example.com"}, nil)
ctx := context.WithValue(context.Background(), verifyBundleFuncKey{}, func(_ context.Context, input certkit.BundleInput) (*certkit.BundleResult, error) {
// Simulate a bundle where AIA fetching succeeded but
// AIAIncomplete is set because the empty root pool caused a
// false positive.
return &certkit.BundleResult{
Leaf: input.Leaf,
AIAIncomplete: true,
AIAUnresolvedCount: 1,
}, nil
})
result, err := VerifyCert(ctx, &VerifyInput{
Cert: leaf.cert,
CheckChain: true,
TrustStore: "custom",
CustomRoots: []*x509.Certificate{otherRoot.cert},
})
if err != nil {
t.Fatal(err)
}
if result.ChainValid != nil && *result.ChainValid {
t.Fatal("expected chain to be invalid with wrong roots")
}
if strings.Contains(result.ChainErr, "AIA resolution incomplete") {
t.Fatalf("error should not blame AIA resolution; got %q", result.ChainErr)
}
}
func TestVerifyCert_PreBundleAIAIncompletePreservedWithoutWarnings(t *testing.T) {
// WHY: A pre-bundle result can legitimately have unresolved issuers even
// when there were no AIA fetch warnings (for example, a fetched issuer did
// not complete the chain). VerifyCert must preserve that state instead of
// collapsing it into a generic trust-source failure.
t.Parallel()
root := newRSACA(t)
intermediate := newRSAIntermediate(t, root)
otherRoot := newRSACA(t)
leafKey, err := rsa.GenerateKey(rand.Reader, 2048)
if err != nil {
t.Fatal(err)
}
leafTemplate := &x509.Certificate{
SerialNumber: randomSerial(t),
Subject: pkix.Name{CommonName: "aia-still-incomplete.example.com", Organization: []string{"TestOrg"}},
DNSNames: []string{"aia-still-incomplete.example.com"},
NotBefore: time.Now().Add(-time.Hour),
NotAfter: time.Now().Add(365 * 24 * time.Hour),
KeyUsage: x509.KeyUsageDigitalSignature | x509.KeyUsageKeyEncipherment,
ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
AuthorityKeyId: intermediate.cert.SubjectKeyId,
IssuingCertificateURL: []string{"https://aia.example.test/issuer.cer"},
}
leafDER, err := x509.CreateCertificate(rand.Reader, leafTemplate, intermediate.cert, &leafKey.PublicKey, intermediate.key.(*rsa.PrivateKey))
if err != nil {
t.Fatal(err)
}
leafCert, err := x509.ParseCertificate(leafDER)
if err != nil {
t.Fatal(err)
}
ctx := context.WithValue(context.Background(), verifyBundleFuncKey{}, func(_ context.Context, input certkit.BundleInput) (*certkit.BundleResult, error) {
return &certkit.BundleResult{
Leaf: input.Leaf,
AIAIncomplete: true,
AIAUnresolvedCount: 1,
}, nil
})
result, err := VerifyCert(ctx, &VerifyInput{
Cert: leafCert,
CheckChain: true,
TrustStore: "custom",
CustomRoots: []*x509.Certificate{otherRoot.cert},
})
if err != nil {
t.Fatal(err)
}
if result.ChainValid != nil && *result.ChainValid {
t.Fatal("expected chain to be invalid with wrong roots")
}
if !strings.Contains(result.ChainErr, "AIA resolution incomplete") {
t.Fatalf("expected AIA incomplete context to be preserved, got %q", result.ChainErr)
}
}
func TestVerifyCert_NoChainCheck_IgnoresTrustProbe(t *testing.T) {
// WHY: When CheckChain=false, VerifyCert should skip trust probing entirely.
t.Parallel()
ca := newRSACA(t)
leaf := newRSALeaf(t, ca, "invalid-store-nochain.example.com", []string{"invalid-store-nochain.example.com"}, nil)
result, err := VerifyCert(context.Background(), &VerifyInput{
Cert: leaf.cert,
CheckChain: false,
})
if err != nil {
t.Fatal(err)
}
if result.ChainValid != nil {
t.Fatalf("expected ChainValid to be nil, got %v", result.ChainValid)
}
if result.ChainErr != "" {
t.Fatalf("expected empty ChainErr, got %q", result.ChainErr)
}
if len(result.Errors) != 0 {
t.Fatalf("expected no errors, got %v", result.Errors)
}
}
func TestVerifyCert_VerboseFields(t *testing.T) {
// WHY: VerifyCert should populate verbose fields when Verbose=true.
t.Parallel()
ca := newRSACA(t)
leaf := newRSALeaf(t, ca, "verbose.example.com", []string{"verbose.example.com"}, nil)
result, err := VerifyCert(context.Background(), &VerifyInput{
Cert: leaf.cert,
CheckChain: true,
TrustStore: "custom",
CustomRoots: []*x509.Certificate{ca.cert},
Verbose: true,
})
if err != nil {
t.Fatal(err)
}
if result.Issuer == "" {
t.Error("expected Issuer to be populated")
}
if result.Serial == "" {
t.Error("expected Serial to be populated")
}
if result.NotBefore == "" {
t.Error("expected NotBefore to be populated")
}
if result.CertType == "" {
t.Error("expected CertType to be populated")
}
if result.IsCA == nil {
t.Error("expected IsCA to be populated")
} else if *result.IsCA {
t.Error("expected IsCA=false for leaf certificate")
}
if result.KeyAlgo == "" {
t.Error("expected KeyAlgo to be populated")
}
if result.KeySize == "" {
t.Error("expected KeySize to be populated")
}
if result.SigAlg == "" {
t.Error("expected SigAlg to be populated")
}
if len(result.KeyUsages) == 0 {
t.Error("expected KeyUsages to be populated")
}
if len(result.EKUs) == 0 {
t.Error("expected EKUs to be populated")
}
if result.SHA256 == "" {
t.Error("expected SHA256 to be populated")
}
if result.SHA1 == "" {
t.Error("expected SHA1 to be populated")
}
if result.AKI == "" {
t.Error("expected AKI to be populated")
}
}
func TestVerifyCert_ExpiryCheck(t *testing.T) {
// WHY: Verifies VerifyCert wires ExpiryDuration to result.Expiry correctly.
// The "already expired" case is covered by TestCertExpiresWithin in the
// root package (T-10); here we only test the wiring through VerifyCert.
t.Parallel()
ca := newRSACA(t)
leaf := newRSALeaf(t, ca, "expiry.example.com", []string{"expiry.example.com"}, nil)
tests := []struct {
name string
cert *x509.Certificate
window time.Duration
wantExpiry bool
wantExpiryInfoSubstr string
wantErrorSubstr string
wantErrors bool
}{
{
name: "within window triggers",
cert: leaf.cert,
window: 366 * 24 * time.Hour,
wantExpiry: true,
wantExpiryInfoSubstr: "expires within",
wantErrorSubstr: "certificate expires within",
wantErrors: true,
},
{
name: "outside window does not trigger",
cert: leaf.cert,
window: 30 * 24 * time.Hour,
wantExpiry: false,
wantExpiryInfoSubstr: "does not expire within",
wantErrors: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
// WHY: Ensures expiry wiring behaves for this window.
t.Parallel()
result, err := VerifyCert(context.Background(), &VerifyInput{
Cert: tt.cert,
ExpiryDuration: tt.window,
TrustStore: "mozilla",
})
if err != nil {
t.Fatal(err)
}
if result.Expiry == nil {
t.Fatal("expected Expiry to be set")
}
if *result.Expiry != tt.wantExpiry {
t.Errorf("Expiry = %v, want %v", *result.Expiry, tt.wantExpiry)
}
if tt.wantExpiryInfoSubstr != "" && !strings.Contains(result.ExpiryInfo, tt.wantExpiryInfoSubstr) {
t.Errorf("ExpiryInfo = %q, want substring %q", result.ExpiryInfo, tt.wantExpiryInfoSubstr)
}
if tt.wantErrors && len(result.Errors) == 0 {
t.Fatal("expected errors to be populated")
}
if !tt.wantErrors && len(result.Errors) != 0 {
t.Fatalf("expected no errors, got %v", result.Errors)
}
if tt.wantErrorSubstr != "" {
found := false
for _, errMsg := range result.Errors {
if strings.Contains(errMsg, tt.wantErrorSubstr) {
found = true
break
}
}
if !found {
t.Errorf("expected error containing %q, got %v", tt.wantErrorSubstr, result.Errors)
}
}
})
}
}
func TestVerifyCert_ValidityWindow(t *testing.T) {
// WHY: Chain validation must fail for expired and not-yet-valid leaf certificates.
t.Parallel()
ca := newRSACA(t)
notYetValidLeaf := func(t *testing.T) *x509.Certificate {
t.Helper()
key, err := rsa.GenerateKey(rand.Reader, 2048)
if err != nil {
t.Fatal(err)
}
leafTemplate := &x509.Certificate{
SerialNumber: randomSerial(t),
Subject: pkix.Name{CommonName: "future.example.com", Organization: []string{"TestOrg"}},
NotBefore: time.Now().Add(24 * time.Hour),
NotAfter: time.Now().Add(365 * 24 * time.Hour),
KeyUsage: x509.KeyUsageDigitalSignature,
ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
SubjectKeyId: []byte{0xaa, 0xbb, 0xcc},
AuthorityKeyId: ca.cert.SubjectKeyId,
}
leafDER, err := x509.CreateCertificate(rand.Reader, leafTemplate, ca.cert, &key.PublicKey, ca.key.(*rsa.PrivateKey))
if err != nil {
t.Fatal(err)
}
leafCert, err := x509.ParseCertificate(leafDER)
if err != nil {
t.Fatal(err)
}
return leafCert
}
tests := []struct {
name string
cert func(t *testing.T) *x509.Certificate
wantErrSubstr string
}{
{
name: "expired leaf",
cert: func(t *testing.T) *x509.Certificate {
t.Helper()
return newExpiredLeaf(t, ca).cert
},
wantErrSubstr: "expired",
},
{
name: "not yet valid leaf",
cert: notYetValidLeaf,
wantErrSubstr: "not yet valid",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
// WHY: Ensures VerifyCert rejects this validity window.
t.Parallel()
result, err := VerifyCert(context.Background(), &VerifyInput{
Cert: tt.cert(t),
CheckChain: true,
TrustStore: "custom",
CustomRoots: []*x509.Certificate{ca.cert},
})
if err != nil {
t.Fatal(err)
}
if result.ChainValid == nil || *result.ChainValid {
t.Fatalf("expected chain to be invalid, got %v", result.ChainValid)
}
if result.ChainErr == "" {
t.Fatal("expected ChainErr to be populated")
}
if !strings.Contains(result.ChainErr, tt.wantErrSubstr) {
t.Errorf("expected ChainErr to mention %q, got %q", tt.wantErrSubstr, result.ChainErr)
}
chainErrFound := false
for _, errMsg := range result.Errors {
if strings.Contains(errMsg, "chain validation") {
chainErrFound = true
break
}
}
if !chainErrFound {
t.Errorf("expected chain validation error, got %v", result.Errors)
}
})
}
}
func TestVerifyCert_ChainInvalid(t *testing.T) {
// WHY: Chain validation against an unrelated CA must report ChainValid=false with a descriptive error; silent acceptance would be a security issue.
t.Parallel()
ca := newRSACA(t)
leaf := newRSALeaf(t, ca, "untrusted.example.com", []string{"untrusted.example.com"}, nil)
// Use a custom trust store with a different CA that did not sign the leaf.
unrelatedCA := newECDSACA(t)
result, err := VerifyCert(context.Background(), &VerifyInput{
Cert: leaf.cert,
CheckChain: true,
TrustStore: "custom",
CustomRoots: []*x509.Certificate{unrelatedCA.cert},
})
if err != nil {
t.Fatal(err)
}
if result.ChainValid == nil {
t.Fatal("expected ChainValid to be set")
}
if *result.ChainValid {
t.Error("expected chain to be invalid when issuer is not in trust store")
}
if result.ChainErr == "" {
t.Error("expected ChainErr to be populated for invalid chain")
}
if !strings.Contains(result.ChainErr, "unknown authority") {
t.Errorf("expected ChainErr to mention unknown authority, got %q", result.ChainErr)
}
if len(result.Errors) == 0 {
t.Error("expected errors to be populated for invalid chain")
}
chainErrFound := false
for _, errMsg := range result.Errors {
if strings.Contains(errMsg, "chain validation") {
chainErrFound = true
break
}
}
if !chainErrFound {
t.Errorf("expected chain validation error, got %v", result.Errors)
}
}
func TestVerifyCert_KeyMatchInputs(t *testing.T) {
// WHY: Key match handling must distinguish skipped checks, unsupported key types, and disabled checks.
t.Parallel()
ca := newRSACA(t)
leaf := newRSALeaf(t, ca, "keymatch-inputs.example.com", []string{"keymatch-inputs.example.com"}, nil)
rsaKey, ok := leaf.key.(*rsa.PrivateKey)
if !ok {
t.Fatalf("expected RSA private key, got %T", leaf.key)
}
tests := []struct {
name string
key crypto.PrivateKey
checkKeyMatch bool
wantKeyMatchNil bool
wantKeyMatchErrSub string
wantKeyInfoEmpty bool
}{
{
name: "check enabled with nil key",
key: nil,
checkKeyMatch: true,
wantKeyMatchNil: true,
wantKeyInfoEmpty: true,
},
{
name: "check disabled ignores key",
key: leaf.key,
checkKeyMatch: false,
wantKeyMatchNil: true,
wantKeyInfoEmpty: true,
},
{
name: "public key returns error",
key: &rsaKey.PublicKey,
checkKeyMatch: true,
wantKeyMatchNil: true,
wantKeyMatchErrSub: "unsupported private key type",
wantKeyInfoEmpty: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
// WHY: Ensures VerifyCert handles this key input scenario correctly.
t.Parallel()
result, err := VerifyCert(context.Background(), &VerifyInput{
Cert: leaf.cert,
Key: tt.key,
CheckKeyMatch: tt.checkKeyMatch,
TrustStore: "mozilla",
})
if err != nil {
t.Fatal(err)
}
if tt.wantKeyMatchNil {
if result.KeyMatch != nil {
t.Errorf("expected KeyMatch nil, got %v", *result.KeyMatch)
}
}
if tt.wantKeyMatchErrSub != "" {
if !strings.Contains(result.KeyMatchErr, tt.wantKeyMatchErrSub) {
t.Errorf("expected KeyMatchErr containing %q, got %q", tt.wantKeyMatchErrSub, result.KeyMatchErr)
}
found := slices.Contains(result.Errors, result.KeyMatchErr)
if !found {
t.Errorf("expected Errors to include KeyMatchErr, got %v", result.Errors)
}
} else if result.KeyMatchErr != "" {
t.Errorf("expected no KeyMatchErr, got %q", result.KeyMatchErr)
}
if tt.wantKeyInfoEmpty && result.KeyInfo != "" {
t.Errorf("expected no KeyInfo, got %q", result.KeyInfo)
}
})
}
}
func TestVerifyCert_SimultaneousChainAndKeyFailures(t *testing.T) {
// WHY: Existing tests only check one failure mode at a time (key mismatch OR
// chain invalid). This verifies that when BOTH CheckChain and CheckKeyMatch
// fail, the Errors slice collects entries for both failures.
t.Parallel()
ca := newRSACA(t)
leaf := newRSALeaf(t, ca, "dual-fail.example.com", []string{"dual-fail.example.com"}, nil)
// Generate a key that does NOT match the leaf certificate
wrongKey, err := rsa.GenerateKey(rand.Reader, 2048)
if err != nil {
t.Fatal(err)
}
// Use a custom trust store with an unrelated CA so chain validation also fails
unrelatedCA := newECDSACA(t)
result, err := VerifyCert(context.Background(), &VerifyInput{
Cert: leaf.cert,
Key: wrongKey,
CheckKeyMatch: true,
CheckChain: true,
TrustStore: "custom",
CustomRoots: []*x509.Certificate{unrelatedCA.cert},
})
if err != nil {
t.Fatal(err)
}
// Verify key mismatch is reported
if result.KeyMatch == nil {
t.Fatal("expected KeyMatch to be set")
}
if *result.KeyMatch {
t.Error("expected key mismatch")
}
if result.KeyInfo == "" {
t.Error("expected KeyInfo to be set")
}
if result.KeyMatchErr != "" {
t.Errorf("expected no KeyMatchErr, got %q", result.KeyMatchErr)
}
// Verify chain is invalid
if result.ChainValid == nil {
t.Fatal("expected ChainValid to be set")
}
if *result.ChainValid {
t.Error("expected chain to be invalid")
}
if result.ChainErr == "" {
t.Error("expected ChainErr to be set")
}
// Verify Errors slice contains entries for BOTH failures
if len(result.Errors) < 2 {
t.Fatalf("expected at least 2 errors (key + chain), got %d: %v", len(result.Errors), result.Errors)
}
keyMismatchFound := false
chainErrFound := false
for _, errMsg := range result.Errors {
if strings.Contains(errMsg, "key does not match certificate") {
keyMismatchFound = true
}
if strings.Contains(errMsg, "chain validation") {
chainErrFound = true
}
}
if !keyMismatchFound {
t.Errorf("expected key mismatch error, got %v", result.Errors)
}
if !chainErrFound {
t.Errorf("expected chain validation error, got %v", result.Errors)
}
}
func TestVerifyCert_ChainAndKeyMatchSuccess(t *testing.T) {
// WHY: Verifies the full-success path when both chain and key checks pass.
t.Parallel()
ca := newRSACA(t)
leaf := newRSALeaf(t, ca, "ok.example.com", []string{"ok.example.com"}, nil)
result, err := VerifyCert(context.Background(), &VerifyInput{
Cert: leaf.cert,
Key: leaf.key,
CheckKeyMatch: true,
CheckChain: true,
TrustStore: "custom",
CustomRoots: []*x509.Certificate{ca.cert},
})
if err != nil {
t.Fatal(err)
}
if result.KeyMatch == nil || !*result.KeyMatch {
t.Fatalf("expected KeyMatch true, got %v", result.KeyMatch)
}
if result.KeyInfo == "" {
t.Error("expected KeyInfo to be set")
}
if result.ChainValid == nil || !*result.ChainValid {
t.Fatalf("expected ChainValid true, got %v", result.ChainValid)
}
if result.ChainErr != "" {
t.Errorf("expected no ChainErr, got %q", result.ChainErr)
}
if len(result.Chain) == 0 {
t.Fatal("expected chain display to be populated")
}
if len(result.Errors) != 0 {
t.Errorf("expected no errors, got %v", result.Errors)
}
}
func TestVerifyCert_SelfSigned(t *testing.T) {
// WHY: Self-signed inputs should only validate when trusted explicitly.
t.Parallel()
ca := newRSACA(t)
tests := []struct {
name string
customRoots []*x509.Certificate
wantValid bool
wantErr bool
}{
{
name: "trusted root",
customRoots: []*x509.Certificate{ca.cert},
wantValid: true,
},
{
name: "untrusted",
wantErr: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
// WHY: Ensures VerifyCert handles this self-signed trust scenario.
t.Parallel()
result, err := VerifyCert(context.Background(), &VerifyInput{
Cert: ca.cert,
CheckChain: true,
TrustStore: "custom",
CustomRoots: tt.customRoots,
})
if err != nil {
t.Fatal(err)
}
if result.ChainValid == nil {
t.Fatal("expected ChainValid to be set")
}
if *result.ChainValid != tt.wantValid {
t.Fatalf("expected ChainValid %v, got %v", tt.wantValid, result.ChainValid)
}
if tt.wantErr {
if result.ChainErr == "" {
t.Error("expected ChainErr to be populated")
}
return
}
if result.ChainErr != "" {
t.Errorf("expected no ChainErr, got %q", result.ChainErr)
}
if len(result.Chain) == 0 {
t.Fatal("expected chain display to be populated")
}
if len(result.Errors) != 0 {
t.Errorf("expected no errors, got %v", result.Errors)
}
})
}
}
func TestVerifyCert_ExtraIntermediates(t *testing.T) {
// WHY: ExtraCerts should allow chain validation to succeed when intermediates are missing.
t.Parallel()
root := newRSACA(t)
intermediate := newRSAIntermediate(t, root)
leaf := newRSALeaf(t, intermediate, "extra-intermediate.example.com", []string{"extra-intermediate.example.com"}, nil)
missingResult, err := VerifyCert(context.Background(), &VerifyInput{
Cert: leaf.cert,
CheckChain: true,
TrustStore: "custom",
CustomRoots: []*x509.Certificate{root.cert},
})
if err != nil {
t.Fatal(err)
}
if missingResult.ChainValid == nil || *missingResult.ChainValid {
t.Fatalf("expected chain to be invalid without intermediates, got %v", missingResult.ChainValid)
}
if missingResult.ChainErr == "" {
t.Error("expected ChainErr to be populated for missing intermediate")
}
chainErrFound := false
for _, errMsg := range missingResult.Errors {
if strings.Contains(errMsg, "chain validation") {
chainErrFound = true
break
}
}
if !chainErrFound {
t.Errorf("expected chain validation error, got %v", missingResult.Errors)
}
missingRootsResult, err := VerifyCert(context.Background(), &VerifyInput{
Cert: leaf.cert,
CheckChain: true,