File: test_functions.go

package info (click to toggle)
golang-github-google-certificate-transparency 0.0~git20160709.0.0f6e3d1~ds1-3
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, bullseye, buster
  • size: 5,676 kB
  • sloc: cpp: 35,278; python: 11,838; java: 1,911; sh: 1,885; makefile: 950; xml: 520; ansic: 225
file content (236 lines) | stat: -rw-r--r-- 5,831 bytes parent folder | download
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
package fixchain

import (
	"bytes"
	"encoding/json"
	"encoding/pem"
	"errors"
	"fmt"
	"log"
	"strings"
	"sync"
	"testing"

	"github.com/google/certificate-transparency/go/x509"
	"github.com/google/certificate-transparency/go/x509/pkix"
)

type nilLimiter struct{}

func (l *nilLimiter) Wait() {
	return
}

func newNilLimiter() *nilLimiter {
	return &nilLimiter{}
}

type bytesReadCloser struct {
	*bytes.Reader
}

func (rc bytesReadCloser) Close() error {
	return nil
}

// CertificateFromPEM takes a string representing a certificate in PEM format
// and returns the corresponding x509.Certificate object.
func CertificateFromPEM(pemBytes string) (*x509.Certificate, error) {
	block, _ := pem.Decode([]byte(pemBytes))
	if block == nil {
		return nil, errors.New("failed to decode PEM")
	}
	return x509.ParseCertificate(block.Bytes)
}

// GetTestCertificateFromPEM returns an x509.Certificate from a certificate in
// PEM format for testing purposes.  Any errors in the PEM decoding process are
// reported to the testing framework.
func GetTestCertificateFromPEM(t *testing.T, pemBytes string) *x509.Certificate {
	cert, err := CertificateFromPEM(pemBytes)
	if err != nil {
		t.Errorf("Failed to parse leaf: %s", err)
	}
	return cert
}

func nameToKey(name *pkix.Name) string {
	return fmt.Sprintf("%s/%s/%s/%s", strings.Join(name.Country, ","),
		strings.Join(name.Organization, ","),
		strings.Join(name.OrganizationalUnit, ","), name.CommonName)
}

func chainToDebugString(chain []*x509.Certificate) string {
	var chainStr string
	for _, cert := range chain {
		if len(chainStr) > 0 {
			chainStr += " -> "
		}
		chainStr += nameToKey(&cert.Subject)
	}
	return chainStr
}

func matchTestChainList(t *testing.T, i int, want [][]string, got [][]*x509.Certificate) {
	if len(want) != len(got) {
		t.Errorf("#%d: Wanted %d chains, got back %d", i, len(want), len(got))
	}

	seen := make([]bool, len(want))
NextOutputChain:
	for _, chain := range got {
	TryNextExpected:
		for j, expChain := range want {
			if seen[j] {
				continue
			}
			if len(chain) != len(expChain) {
				continue
			}
			for k, cert := range chain {
				if !strings.Contains(nameToKey(&cert.Subject), expChain[k]) {
					continue TryNextExpected
				}
			}
			seen[j] = true
			continue NextOutputChain
		}
		t.Errorf("#%d: No expected chain matched output chain %s", i,
			chainToDebugString(chain))
	}

	for j, val := range seen {
		if !val {
			t.Errorf("#%d: No output chain matched expected chain %s", i,
				strings.Join(want[j], " -> "))
		}
	}
}

func matchTestErrorList(t *testing.T, i int, want []errorType, got []*FixError) {
	if len(want) != len(got) {
		t.Errorf("#%d: Wanted %d errors, got back %d", i, len(want), len(got))
	}

	seen := make([]bool, len(want))
NextOutputErr:
	for _, err := range got {
		for j, expErr := range want {
			if seen[j] {
				continue
			}
			if err.Type == expErr {
				seen[j] = true
				continue NextOutputErr
			}
		}
		t.Errorf("#%d: No expected error matched output error %s", i, err.TypeString())
	}

	for j, val := range seen {
		if !val {
			t.Errorf("#%d: No output error matched expected error %s", i,
				FixError{Type: want[j]}.TypeString())
		}
	}
}

func matchTestChain(t *testing.T, i int, want []string, got []*x509.Certificate) {
	if len(got) != len(want) {
		t.Errorf("#%d: Expected a chain of length %d, got one of length %d",
			i, len(want), len(got))
		return
	}

	if want != nil {
		for j, cert := range got {
			if !strings.Contains(nameToKey(&cert.Subject), want[j]) {
				t.Errorf("#%d: Chain does not match expected chain at position %d", i, j)
			}
		}
	}
}

func matchTestRoots(t *testing.T, i int, want []string, got *x509.CertPool) {
	if len(got.Subjects()) != len(want) {
		t.Errorf("#%d: received %d roots, expected %d", i, len(got.Subjects()), len(want))
	}
	testRoots := extractTestChain(t, i, want)
	seen := make([]bool, len(testRoots))
NextRoot:
	for _, rootSub := range got.Subjects() {
		for j, testRoot := range testRoots {
			if seen[j] {
				continue
			}
			if bytes.Equal(rootSub, testRoot.RawSubject) {
				seen[j] = true
				continue NextRoot
			}
		}
		t.Errorf("#%d: No expected root matches one of the output roots", i)
	}

	for j, val := range seen {
		if !val {
			t.Errorf("#%d: No output root matches expected root %s", i, nameToKey(&testRoots[j].Subject))
		}
	}
}

func extractTestChain(t *testing.T, i int, testChain []string) []*x509.Certificate {
	var chain []*x509.Certificate
	for _, cert := range testChain {
		chain = append(chain, GetTestCertificateFromPEM(t, cert))
	}
	return chain

}

func extractTestRoots(t *testing.T, i int, testRoots []string) *x509.CertPool {
	roots := x509.NewCertPool()
	for j, cert := range testRoots {
		ok := roots.AppendCertsFromPEM([]byte(cert))
		if !ok {
			t.Errorf("#%d: Failed to parse root #%d", i, j)
		}
	}
	return roots
}

func testChains(t *testing.T, i int, expectedChains [][]string, chains chan []*x509.Certificate, wg *sync.WaitGroup) {
	defer wg.Done()
	var allChains [][]*x509.Certificate
	for chain := range chains {
		allChains = append(allChains, chain)
	}
	matchTestChainList(t, i, expectedChains, allChains)
}

func testErrors(t *testing.T, i int, expectedErrs []errorType, errors chan *FixError, wg *sync.WaitGroup) {
	defer wg.Done()
	var allFerrs []*FixError
	for ferr := range errors {
		allFerrs = append(allFerrs, ferr)
	}
	matchTestErrorList(t, i, expectedErrs, allFerrs)
}

func stringRootsToJSON(roots []string) []byte {
	type Roots struct {
		Certs [][]byte `json:"certificates"`
	}
	var r Roots
	for _, root := range roots {
		cert, err := CertificateFromPEM(root)
		if err != nil {
			log.Fatalf("Failed to parse certificate: %s", err)
		}
		r.Certs = append(r.Certs, cert.Raw)
	}
	b, err := json.Marshal(r)
	if err != nil {
		log.Fatalf("Can't marshal JSON: %s", err)
	}
	return b
}