-
Notifications
You must be signed in to change notification settings - Fork 8
/
testcerts_test.go
576 lines (504 loc) · 13.8 KB
/
testcerts_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
package testcerts
import (
"crypto/tls"
"crypto/x509"
"fmt"
"math/big"
"net/http"
"os"
"path/filepath"
"testing"
"time"
)
func TestCertsUsage(t *testing.T) {
// Generate CA
ca := NewCA()
if len(ca.PrivateKey()) == 0 || len(ca.PublicKey()) == 0 {
t.Errorf("Unexpected key length from public/private key")
}
t.Run("Verify CertPool", func(t *testing.T) {
cp := x509.NewCertPool()
if cp.AppendCertsFromPEM(ca.PublicKey()) {
if cp.Equal(ca.CertPool()) {
return
}
}
t.Errorf("certpool is not valid")
})
t.Run("Write to File", func(t *testing.T) {
tempDir, err := os.MkdirTemp("", "")
if err != nil {
t.Fatalf("Error creating temporary directory: %s", err)
}
defer os.RemoveAll(tempDir)
certPath := filepath.Join(tempDir, "cert")
keyPath := filepath.Join(tempDir, "key")
err = ca.ToFile(certPath, keyPath)
if err != nil {
t.Fatalf("Error while generating certificates to files - %s", err)
}
// Check if Cert file exists
_, err = os.Stat(certPath)
if err != nil {
t.Fatalf("Error while generating certificates to files file error - %s", err)
}
// Check if Key file exists
_, err = os.Stat(keyPath)
if err != nil {
t.Fatalf("Error while generating certificates to files file error - %s", err)
}
})
t.Run("Write to Invalid File", func(t *testing.T) {
certPath := "/notValid/path/cert"
keyPath := "/notValid/path/key"
err := ca.ToFile(certPath, keyPath)
if err == nil {
t.Errorf("Unexpected success generating certificates to files")
}
// Check if Cert file exists
_, err = os.Stat(certPath)
if !os.IsNotExist(err) {
t.Errorf("Unexpected success while generating certificates to files")
}
// Check if Key file exists
_, err = os.Stat(keyPath)
if !os.IsNotExist(err) {
t.Errorf("Unexpected success while generating certificates to files")
}
})
t.Run("Write to TempFile", func(t *testing.T) {
cert, key, err := ca.ToTempFile("")
if err != nil {
t.Errorf("Error generating tempfile - %s", err)
}
_, err = os.Stat(cert.Name())
if err != nil {
t.Errorf("File does not exist - %s", cert.Name())
}
defer os.Remove(cert.Name())
_, err = os.Stat(key.Name())
if err != nil {
t.Errorf("File does not exist - %s", key.Name())
}
defer os.Remove(key.Name())
})
t.Run("Write to Invalid TempFile", func(t *testing.T) {
_, _, err := ca.ToTempFile("/notValidPath/")
if err == nil {
t.Errorf("Unexpected success with invalid tempfile directory")
}
})
for _, domains := range [][]string{{"localhost", "127.0.0.1", "example.com"}, {}} {
t.Run(fmt.Sprintf("Generate KeyPair with %d Domains", len(domains)), func(t *testing.T) {
kp, err := ca.NewKeyPair(domains...)
if err != nil {
t.Errorf("NewKeyPair() returned error when generating with domains: %s", err)
}
t.Run("Validate Key Length", func(t *testing.T) {
if len(kp.PrivateKey()) == 0 || len(kp.PublicKey()) == 0 {
t.Errorf("Unexpected key length from public/private key")
}
})
t.Run("Write to File", func(t *testing.T) {
tempDir, err := os.MkdirTemp("", "")
if err != nil {
t.Fatalf("Error creating temporary directory: %s", err)
}
defer os.RemoveAll(tempDir)
certPath := filepath.Join(tempDir, "cert")
keyPath := filepath.Join(tempDir, "key")
err = kp.ToFile(certPath, keyPath)
if err != nil {
t.Errorf("Error while generating certificates to files - %s", err)
}
// Check if Cert file exists
_, err = os.Stat(certPath)
if err != nil {
t.Errorf("Error while generating certificates to files file error - %s", err)
}
// Check if Key file exists
_, err = os.Stat(keyPath)
if err != nil {
t.Errorf("Error while generating certificates to files file error - %s", err)
}
})
t.Run("Write to Invalid File", func(t *testing.T) {
certPath := "/notValid/path/cert"
keyPath := "/notValid/path/key"
err := kp.ToFile(certPath, keyPath)
if err == nil {
t.Errorf("Unexpected success generating certificates to files")
}
// Check if Cert file exists
_, err = os.Stat(certPath)
if !os.IsNotExist(err) {
t.Errorf("Unexpected success while generating certificates to files")
}
// Check if Key file exists
_, err = os.Stat(keyPath)
if !os.IsNotExist(err) {
t.Errorf("Unexpected success while generating certificates to files")
}
})
t.Run("Write to TempFile", func(t *testing.T) {
cert, key, err := kp.ToTempFile("")
if err != nil {
t.Errorf("Error generating tempfile - %s", err)
}
_, err = os.Stat(cert.Name())
if err != nil {
t.Errorf("File does not exist - %s", cert.Name())
}
defer os.Remove(cert.Name())
_, err = os.Stat(key.Name())
if err != nil {
t.Errorf("File does not exist - %s", key.Name())
}
defer os.Remove(key.Name())
})
t.Run("Write to Invalid TempFile", func(t *testing.T) {
_, _, err := kp.ToTempFile("/notValidPath/")
if err == nil {
t.Errorf("Unexpected success with invalid tempfile directory")
}
})
})
}
}
type KeyPairConfigTestCase struct {
name string
cfg KeyPairConfig
err error
}
func TestKeyPairConfig(t *testing.T) {
tc := []KeyPairConfigTestCase{
{
name: "Happy Path - Simple Domain",
cfg: KeyPairConfig{
Domains: []string{"example.com"},
},
err: nil,
},
{
name: "Happy Path - Multiple Domains",
cfg: KeyPairConfig{
Domains: []string{"example.com", "example.org"},
},
err: nil,
},
{
name: "Happy Path - Multiple Domains with Wildcard",
cfg: KeyPairConfig{
Domains: []string{"example.com", "*.example.com"},
},
err: nil,
},
{
name: "Empty Config",
cfg: KeyPairConfig{},
err: ErrEmptyConfig,
},
{
name: "Happy Path - Valid IP",
cfg: KeyPairConfig{
IPAddresses: []string{"127.0.0.1"},
},
err: nil,
},
{
name: "Happy Path - Multiple Valid IPs",
cfg: KeyPairConfig{
IPAddresses: []string{"127.0.0.1", "10.0.0.0"},
},
err: nil,
},
{
name: "Happy Path - IPv6 Localhost",
cfg: KeyPairConfig{
IPAddresses: []string{"::1"},
},
err: nil,
},
{
name: "Happy Path - Multiple IPv6 Addresses",
cfg: KeyPairConfig{
IPAddresses: []string{"::1", "2001:0db8:85a3:0000:0000:8a2e:0370:7334"},
},
err: nil,
},
{
name: "Happy Path - Valid IP and Domain",
cfg: KeyPairConfig{
IPAddresses: []string{"127.0.0.1", "10.0.0.0"},
Domains: []string{"example.com", "localhost"},
},
err: nil,
},
{
name: "Invalid IP",
cfg: KeyPairConfig{
IPAddresses: []string{"127.0.0.1", "not an IP"},
},
err: ErrInvalidIP,
},
{
name: "Happy Path - Serial Number provided",
cfg: KeyPairConfig{
Domains: []string{"example.com"},
SerialNumber: big.NewInt(123),
},
err: nil,
},
{
name: "Happy Path - Common Name provided",
cfg: KeyPairConfig{
Domains: []string{"example.com"},
CommonName: "Example Common Name",
},
err: nil,
},
}
for _, c := range tc {
t.Run(c.name, func(t *testing.T) {
certs, err := NewCA().NewKeyPairFromConfig(c.cfg)
if err != c.err {
t.Fatalf("KeyPair Generation Failed expected %v got %v", c.err, err)
}
// Validate Key Length
if err == nil {
if len(certs.PrivateKey()) == 0 || len(certs.PublicKey()) == 0 {
t.Errorf("Unexpected key length from public/private key")
}
}
})
}
t.Run("Serial Number is correct in Key Pair", func(t *testing.T) {
certs, err := NewCA().NewKeyPairFromConfig(KeyPairConfig{
Domains: []string{"example.com"},
SerialNumber: big.NewInt(123),
})
if err != nil {
t.Fatalf("KeyPair Generation Failed expected nil got %v", err)
}
if certs.cert.SerialNumber.Cmp(big.NewInt(123)) != 0 {
t.Fatalf("Unexpected Serial Number expected 123 got %v", certs.cert.SerialNumber)
}
})
t.Run("Common Name is correct in Key Pair", func(t *testing.T) {
certs, err := NewCA().NewKeyPairFromConfig(KeyPairConfig{
Domains: []string{"example.com"},
CommonName: "Example Common Name",
})
if err != nil {
t.Fatalf("KeyPair Generation Failed expected nil got %v", err)
}
if certs.cert.Subject.CommonName != "Example Common Name" {
t.Fatalf("Unexpected Common Name expected 'Example Common Name' got %v", certs.cert.Subject.CommonName)
}
})
}
type FullFlowTestCase struct {
name string
listenAddr string
domains []string
kpCfg KeyPairConfig
kpErr error
}
func TestFullFlow(t *testing.T) {
tc := []FullFlowTestCase{
{
name: "Localhost Domain",
listenAddr: "0.0.0.0",
domains: []string{"localhost"},
kpCfg: KeyPairConfig{},
kpErr: nil,
},
{
name: "Localhost IP",
listenAddr: "0.0.0.0",
kpCfg: KeyPairConfig{
IPAddresses: []string{"127.0.0.1"},
},
kpErr: nil,
},
{
name: "Localhost IP and Domain",
listenAddr: "0.0.0.0",
kpCfg: KeyPairConfig{
IPAddresses: []string{"127.0.0.1", "::1"},
Domains: []string{"localhost"},
},
kpErr: nil,
},
{
name: "Localhost IP, Domain, Serial Number, and Common Name",
listenAddr: "0.0.0.0",
kpCfg: KeyPairConfig{
IPAddresses: []string{"127.0.0.1", "::1"},
Domains: []string{"localhost"},
SerialNumber: big.NewInt(123),
CommonName: "Example Common Name",
},
kpErr: nil,
},
}
for _, c := range tc {
t.Run(c.name, func(t *testing.T) {
var err error
var cert, clientCert *KeyPair
// Generate CA
ca := NewCA()
// Generate Server Cert if Domains are provided
if len(c.domains) > 0 {
cert, err = ca.NewKeyPair(c.domains...)
if err != c.kpErr {
t.Fatalf("KeyPair Generation Failed expected %v got %v", c.kpErr, err)
}
if err != nil {
return
}
}
// Generate Server Cert with Config
if err = c.kpCfg.Validate(); err == nil {
cert, err = ca.NewKeyPairFromConfig(c.kpCfg)
if err != c.kpErr {
t.Fatalf("KeyPair Generation Failed expected %v got %v", c.kpErr, err)
}
if err != nil {
return
}
}
if cert == nil {
t.Fatalf("Test Conditions failure to generate server keypair - %s", err)
}
// Setup Server TLS Config
serverTLSConfig, err := cert.ConfigureTLSConfig(ca.GenerateTLSConfig())
if err != nil {
t.Fatalf("Error configuring server TLS - %s", err)
}
// Require Valid Client Cert
serverTLSConfig.ClientAuth = tls.RequireAndVerifyClientCert
// Generate Client Cert
clientCert, err = ca.NewKeyPair()
if err != nil {
t.Fatalf("Error generating client keypair - %s", err)
}
// Setup Client TLS Config
clientTLSConfig, err := clientCert.ConfigureTLSConfig(ca.GenerateTLSConfig())
if err != nil {
t.Fatalf("Error configuring client TLS - %s", err)
}
// Setup HTTP Server
server := &http.Server{
Addr: c.listenAddr + ":8443",
Handler: http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
_, err := w.Write([]byte("Hello, World!"))
if err != nil {
t.Errorf("Error writing response - %s", err)
}
}),
TLSConfig: serverTLSConfig,
}
defer server.Close()
// Write Certs to Temp Files
certFile, keyFile, err := cert.ToTempFile("")
if err != nil {
t.Fatalf("Error writing certs to temp files - %s", err)
}
go func() {
// Start HTTP Listener
err = server.ListenAndServeTLS(certFile.Name(), keyFile.Name())
if err != nil && err != http.ErrServerClosed {
t.Errorf("Listener returned error - %s", err)
}
}()
// Wait for Listener to start
<-time.After(3 * time.Second)
// Setup HTTP Client
client := &http.Client{
Transport: &http.Transport{
TLSClientConfig: clientTLSConfig,
},
}
// Make an HTTPS request
var addr []string
addr = append(addr, c.domains...)
addr = append(addr, c.kpCfg.Domains...)
addr = append(addr, c.kpCfg.IPAddresses...)
for _, a := range addr {
t.Run("Client Request to "+a, func(t *testing.T) {
rsp, err := client.Get("https://" + a + ":8443")
if err != nil {
t.Errorf("Client returned error - %s", err)
}
// Check the response
if rsp.StatusCode != http.StatusOK {
t.Errorf("Unexpected response code - %d", rsp.StatusCode)
}
})
}
})
}
}
func ExampleNewCA() {
// Generate a new Certificate Authority
ca := NewCA()
// Create a new KeyPair with a list of domains
certs, err := ca.NewKeyPair("localhost")
if err != nil {
fmt.Printf("Error generating keypair - %s", err)
}
// Write the certificates to a file
cert, key, err := certs.ToTempFile("")
if err != nil {
fmt.Printf("Error writing certs to temp files - %s", err)
}
// Setup Server TLS Config
serverTLSConfig, err := certs.ConfigureTLSConfig(ca.GenerateTLSConfig())
if err != nil {
fmt.Printf("Error configuring server TLS - %s", err)
}
// Require Valid Client Cert
serverTLSConfig.ClientAuth = tls.RequireAndVerifyClientCert
// Create an HTTP Server
server := &http.Server{
Addr: "0.0.0.0:8443",
Handler: http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
_, err := w.Write([]byte("Hello, World!"))
if err != nil {
fmt.Printf("Error writing response - %s", err)
}
}),
TLSConfig: serverTLSConfig,
}
defer server.Close()
go func() {
// Start HTTP Listener
err = server.ListenAndServeTLS(cert.Name(), key.Name())
if err != nil && err != http.ErrServerClosed {
fmt.Printf("Listener returned error - %s", err)
}
}()
// Wait for Listener to start
<-time.After(3 * time.Second)
// Client TLS Config
clientTLSConfig, err := certs.ConfigureTLSConfig(ca.GenerateTLSConfig())
if err != nil {
fmt.Printf("Error configuring client TLS - %s", err)
}
// Setup HTTP Client with Cert Pool
client := &http.Client{
Transport: &http.Transport{
TLSClientConfig: clientTLSConfig,
},
}
// Make an HTTPS request
rsp, err := client.Get("https://localhost:8443")
if err != nil {
fmt.Printf("Client returned error - %s", err)
}
// Print the response
fmt.Println(rsp.Status)
// Output:
// 200 OK
}