-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
certificate.go
104 lines (80 loc) · 2.13 KB
/
certificate.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
package main
import (
"errors"
"fmt"
"path/filepath"
"strings"
"github.com/spf13/afero"
)
const (
CertificatePath = "/certs"
)
// Certificate holds config a certificate
type Certificate struct {
Name string
Fs afero.Fs
}
// NewCertificate returns a new Certificate
func NewCertificate(name string, fs afero.Fs) *Certificate {
cert := &Certificate{
Name: name,
Fs: fs,
}
return cert
}
// FindAllCertificates scans the /certs directory for .pem files and returns a collection of Certificates
func FindAllCertificates(fs afero.Fs) ([]*Certificate, error) {
var certs []*Certificate
files, err := afero.ReadDir(fs, CertificatePath)
if err != nil {
return nil, err
}
for _, file := range files {
name := file.Name()
if !strings.HasSuffix(name, ".pem") {
continue
}
cert := NewCertificate(name, fs)
certs = append(certs, cert)
}
return certs, nil
}
// VerifyCertificates returns an error if no valid certificates are found
func VerifyCertificates(fs afero.Fs) error {
certs, err := FindAllCertificates(fs)
if err != nil || len(certs) == 0 {
return errors.New("No certificates found")
}
for _, cert := range certs {
log.Infof("Found certificate: %s", cert.Name)
}
return nil
}
// FindCertificateForHost returns the Certificate associated with the given hostname
func FindCertificateForHost(hostname string, fs afero.Fs) (*Certificate, error) {
certs, err := FindAllCertificates(fs)
if err != nil {
return nil, fmt.Errorf("Unable to scan for available certificates: %s", err)
}
for _, cert := range certs {
if cert.belongsToHost(hostname) {
return cert, nil
}
}
return nil, fmt.Errorf("Unable to find certificate for %s", hostname)
}
// FullPath returns the full path of a certificate file
func (c *Certificate) FullPath() string {
return filepath.Join(CertificatePath, c.Name)
}
func (c *Certificate) belongsToHost(host string) bool {
baseCertName := strings.Split(c.Name, ".pem")[0]
return host == baseCertName
}
func (c *Certificate) isExist() bool {
exists, err := afero.Exists(c.Fs, c.FullPath())
if err != nil {
log.Errorf("Unable to check certificate: %s", err)
}
return exists
}