1
2
3
4
5
6
7
8
9
10
11
12
13
14
15 package x509util_test
16
17 import (
18 "encoding/pem"
19 "testing"
20
21 "github.com/google/certificate-transparency-go/x509"
22 "github.com/google/certificate-transparency-go/x509util"
23 )
24
25 func TestLoadSingleCertFromPEMs(t *testing.T) {
26 for _, p := range []string{pemCACert, pemCACertWithOtherStuff, pemCACertDuplicated} {
27 pool := x509util.NewPEMCertPool()
28
29 ok := pool.AppendCertsFromPEM([]byte(p))
30 if !ok {
31 t.Fatal("Expected to append a certificate ok")
32 }
33 if got, want := len(pool.Subjects()), 1; got != want {
34 t.Fatalf("Got %d cert(s) in the pool, expected %d", got, want)
35 }
36 }
37 }
38
39 func TestBadOrEmptyCertificateRejected(t *testing.T) {
40 for _, p := range []string{pemUnknownBlockType, pemCACertBad} {
41 pool := x509util.NewPEMCertPool()
42
43 ok := pool.AppendCertsFromPEM([]byte(p))
44 if ok {
45 t.Fatal("Expected appending no certs")
46 }
47 if got, want := len(pool.Subjects()), 0; got != want {
48 t.Fatalf("Got %d cert(s) in pool, expected %d", got, want)
49 }
50 }
51 }
52
53 func TestLoadMultipleCertsFromPEM(t *testing.T) {
54 pool := x509util.NewPEMCertPool()
55
56 ok := pool.AppendCertsFromPEM([]byte(pemCACertMultiple))
57 if !ok {
58 t.Fatal("Rejected valid multiple certs")
59 }
60 if got, want := len(pool.Subjects()), 2; got != want {
61 t.Fatalf("Got %d certs in pool, expected %d", got, want)
62 }
63 }
64
65 func TestIncluded(t *testing.T) {
66 certs := [2]*x509.Certificate{parsePEM(t, pemCACert), parsePEM(t, pemFakeCACert)}
67
68
69 tests := []struct {
70 cert *x509.Certificate
71 want [2]bool
72 }{
73 {cert: nil, want: [2]bool{false, false}},
74 {cert: nil, want: [2]bool{false, false}},
75 {cert: certs[0], want: [2]bool{true, false}},
76 {cert: nil, want: [2]bool{true, false}},
77 {cert: certs[0], want: [2]bool{true, false}},
78 {cert: certs[1], want: [2]bool{true, true}},
79 {cert: nil, want: [2]bool{true, true}},
80 {cert: certs[1], want: [2]bool{true, true}},
81 }
82
83 pool := x509util.NewPEMCertPool()
84 for _, test := range tests {
85 if test.cert != nil {
86 pool.AddCert(test.cert)
87 }
88 for i, cert := range certs {
89 got := pool.Included(cert)
90 if got != test.want[i] {
91 t.Errorf("pool.Included(cert[%d])=%v, want %v", i, got, test.want[i])
92 }
93 }
94 }
95 }
96
97 func parsePEM(t *testing.T, pemCert string) *x509.Certificate {
98 var block *pem.Block
99 block, _ = pem.Decode([]byte(pemCert))
100 if block == nil || block.Type != "CERTIFICATE" || len(block.Headers) != 0 {
101 t.Fatal("No PEM data found")
102 }
103
104 cert, err := x509.ParseCertificate(block.Bytes)
105 if x509.IsFatal(err) {
106 t.Fatalf("Failed to parse PEM certificate: %v", err)
107 }
108 return cert
109 }
110
View as plain text