-
Notifications
You must be signed in to change notification settings - Fork 293
/
cert_test.go
79 lines (70 loc) · 2.17 KB
/
cert_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
// Copyright (c) 2018 The Decred developers
// Use of this source code is governed by an ISC
// license that can be found in the LICENSE file.
package main
import (
"crypto/elliptic"
"crypto/x509"
"encoding/pem"
"os"
"testing"
)
// TestCertCreationWithHosts creates a certificate pair with extra hosts and
// ensures the extra hosts are present in the generated files.
func TestCertCreationWithHosts(t *testing.T) {
certFile, err := os.CreateTemp("", "certfile")
if err != nil {
t.Fatalf("Unable to create temp certfile: %s", err)
}
certFile.Close()
defer os.Remove(certFile.Name())
keyFile, err := os.CreateTemp("", "keyfile")
if err != nil {
t.Fatalf("Unable to create temp keyfile: %s", err)
}
keyFile.Close()
defer os.Remove(keyFile.Name())
// Generate cert pair with extra hosts.
hostnames := []string{"hostname1", "hostname2"}
err = genCertPair(certFile.Name(), keyFile.Name(), hostnames, elliptic.P521())
if err != nil {
t.Fatalf("Certificate was not created correctly: %s", err)
}
certBytes, err := os.ReadFile(certFile.Name())
if err != nil {
t.Fatalf("Unable to read the certfile: %s", err)
}
pemCert, _ := pem.Decode(certBytes)
x509Cert, err := x509.ParseCertificate(pemCert.Bytes)
if err != nil {
t.Fatalf("Unable to parse the certificate: %s", err)
}
// Ensure the specified extra hosts are present.
for _, host := range hostnames {
err := x509Cert.VerifyHostname(host)
if err != nil {
t.Fatalf("failed to verify extra host '%s'", host)
}
}
}
// TestCertCreationWithOutHosts ensures the creating a certificate pair without
// any hosts works as intended.
func TestCertCreationWithOutHosts(t *testing.T) {
certFile, err := os.CreateTemp("", "certfile")
if err != nil {
t.Fatalf("Unable to create temp certfile: %s", err)
}
certFile.Close()
defer os.Remove(certFile.Name())
keyFile, err := os.CreateTemp("", "keyfile")
if err != nil {
t.Fatalf("Unable to create temp keyfile: %s", err)
}
keyFile.Close()
defer os.Remove(keyFile.Name())
// Generate cert pair with no extra hosts.
err = genCertPair(certFile.Name(), keyFile.Name(), nil, elliptic.P521())
if err != nil {
t.Fatalf("Certificate was not created correctly: %s", err)
}
}