Debian Codegraph @

libgo/go/crypto/x509/root_windows_test.go

raw
1 // Copyright 2021 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
4
5 package x509_test
6
7 import (
8 "crypto/tls"
9 "crypto/x509"
10 "internal/testenv"
11 "testing"
12 "time"
13 )
14
15 func TestPlatformVerifier(t *testing.T) {
16 if !testenv.HasExternalNetwork() {
17 t.Skip()
18 }
19
20 getChain := func(host string) []*x509.Certificate {
21 t.Helper()
22 c, err := tls.Dial("tcp", host+":443", &tls.Config{InsecureSkipVerify: true})
23 if err != nil {
24 t.Fatalf("tls connection failed: %s", err)
25 }
26 return c.ConnectionState().PeerCertificates
27 }
28
29 tests := []struct {
30 name string
31 host string
32 verifyName string
33 verifyTime time.Time
34 expectedErr string
35 }{
36 {
37 // whatever google.com serves should, hopefully, be trusted
38 name: "valid chain",
39 host: "google.com",
40 },
41 {
42 name: "expired leaf",
43 host: "expired.badssl.com",
44 expectedErr: "x509: certificate has expired or is not yet valid: ",
45 },
46 {
47 name: "wrong host for leaf",
48 host: "wrong.host.badssl.com",
49 verifyName: "wrong.host.badssl.com",
50 expectedErr: "x509: certificate is valid for *.badssl.com, badssl.com, not wrong.host.badssl.com",
51 },
52 {
53 name: "self-signed leaf",
54 host: "self-signed.badssl.com",
55 expectedErr: "x509: certificate signed by unknown authority",
56 },
57 {
58 name: "untrusted root",
59 host: "untrusted-root.badssl.com",
60 expectedErr: "x509: certificate signed by unknown authority",
61 },
62 {
63 name: "expired leaf (custom time)",
64 host: "google.com",
65 verifyTime: time.Time{}.Add(time.Hour),
66 expectedErr: "x509: certificate has expired or is not yet valid: ",
67 },
68 {
69 name: "valid chain (custom time)",
70 host: "google.com",
71 verifyTime: time.Now(),
72 },
73 }
74
75 for _, tc := range tests {
76 t.Run(tc.name, func(t *testing.T) {
77 chain := getChain(tc.host)
78 var opts x509.VerifyOptions
79 if len(chain) > 1 {
80 opts.Intermediates = x509.NewCertPool()
81 for _, c := range chain[1:] {
82 opts.Intermediates.AddCert(c)
83 }
84 }
85 if tc.verifyName != "" {
86 opts.DNSName = tc.verifyName
87 }
88 if !tc.verifyTime.IsZero() {
89 opts.CurrentTime = tc.verifyTime
90 }
91
92 _, err := chain[0].Verify(opts)
93 if err != nil && tc.expectedErr == "" {
94 t.Errorf("unexpected verification error: %s", err)
95 } else if err != nil && err.Error() != tc.expectedErr {
96 t.Errorf("unexpected verification error: got %q, want %q", err.Error(), tc.expectedErr)
97 } else if err == nil && tc.expectedErr != "" {
98 t.Errorf("unexpected verification success: want %q", tc.expectedErr)
99 }
100 })
101 }
102 }