-
Notifications
You must be signed in to change notification settings - Fork 189
/
chainsbuilder.go
92 lines (77 loc) · 2.59 KB
/
chainsbuilder.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
package certchains
import (
"fmt"
"os"
)
type CertificateChainsBuilder interface {
WithSigners(signers ...CertificateSignerBuilder) CertificateChainsBuilder
WithCABundle(bundlePath string, signerNames ...[]string) CertificateChainsBuilder
Complete() (*CertificateChains, error)
}
type certificateChains struct {
signers []CertificateSignerBuilder
// fileBundles maps fileName -> signers, where fileName is the filename of a CA bundle
// where PEM certificates should be stored
fileBundles map[string][][]string
}
//nolint:ireturn
func NewCertificateChains(signers ...CertificateSignerBuilder) CertificateChainsBuilder {
return &certificateChains{
signers: signers,
fileBundles: make(map[string][][]string),
}
}
//nolint:ireturn
func (cs *certificateChains) WithSigners(signers ...CertificateSignerBuilder) CertificateChainsBuilder {
cs.signers = append(cs.signers, signers...)
return cs
}
//nolint:ireturn
func (cs *certificateChains) WithCABundle(bundlePath string, signerNames ...[]string) CertificateChainsBuilder {
cs.fileBundles[bundlePath] = signerNames
return cs
}
//nolint:ireturn
func (cs *certificateChains) Complete() (*CertificateChains, error) {
completeChains := &CertificateChains{
signers: make(map[string]*CertificateSigner),
}
// Library-go crypto package warns via stderr prints about CA
// and cert validity time when they exceed 5 and 2 years
// respectively. This is not configurable and the introduction
// of such a possibility involves changing the API in a massively
// used library across OpenShift. Temporarily disable stderr as
// a shortcut to clean logs.
newstderr, err := os.Open("/dev/null")
if err == nil {
originalStderr := os.Stderr
os.Stderr = newstderr
defer newstderr.Close()
defer func() {
os.Stderr = originalStderr
}()
}
for _, signer := range cs.signers {
signer := signer
if _, ok := completeChains.signers[signer.Name()]; ok {
return nil, fmt.Errorf("signer name clash: %s", signer.Name())
}
completedSigner, err := signer.Complete()
if err != nil {
return nil, fmt.Errorf("failed to complete signer %q: %w", signer.Name(), err)
}
completeChains.signers[completedSigner.signerName] = completedSigner
}
for bundle, signers := range cs.fileBundles {
for _, s := range signers {
signerObj := completeChains.GetSigner(s...)
if signerObj == nil {
return nil, NewSignerNotFound(signerObj.signerName)
}
if err := signerObj.AddToBundles(bundle); err != nil {
return nil, fmt.Errorf("failed adding the signer %q to CA bundle %q: %v", signerObj.signerName, bundle, err)
}
}
}
return completeChains, nil
}