-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtrust.go
74 lines (61 loc) · 1.62 KB
/
trust.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
package trust
import (
"crypto/x509"
"fmt"
"io/ioutil"
)
// Pool is a representation of a CA Cert Pool that can have multiple items
// appended into it
type Pool struct {
pool *x509.CertPool
files []string
}
// New returns a newly initialized CA Pool that can then have additional actions
// performed on it
func New() *Pool {
return &Pool{
pool: x509.NewCertPool(),
}
}
// AddCAFile adds the specified files to the list of CA files which will be
// appended to the resulting pool
func (p *Pool) AddCAFile(files ...string) {
p.files = append(p.files, files...)
}
// CACerts builds an X.509 certificate pool containing the Mozilla CA
// Certificate bundle. Returns nil on error along with an appropriate error
// code.
func (p *Pool) CACerts() (*x509.CertPool, error) {
if p.pool == nil {
p.pool = x509.NewCertPool()
}
err := p.appendDefaultCerts()
if err != nil {
return nil, fmt.Errorf("failed to append default certs to pool: %v", err.Error())
}
err = p.appendFileCerts()
if err != nil {
return nil, fmt.Errorf("failed to append file certs to pool: %v", err.Error())
}
return p.pool, nil
}
func (p *Pool) appendDefaultCerts() error {
ok := p.pool.AppendCertsFromPEM([]byte(globalPemCerts))
if !ok {
return fmt.Errorf("failed to append global CAs to cert pool")
}
return nil
}
func (p *Pool) appendFileCerts() error {
for _, file := range p.files {
b, err := ioutil.ReadFile(file)
if err != nil {
return fmt.Errorf("failed to read cert file: %v", err.Error())
}
ok := p.pool.AppendCertsFromPEM(b)
if !ok {
return fmt.Errorf("failed to append cert file (%v) to cert pool", file)
}
}
return nil
}