/
validate.go
81 lines (64 loc) · 1.37 KB
/
validate.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
package saml
import (
"crypto/x509"
"encoding/pem"
"fmt"
"io/ioutil"
"os"
"sync"
"time"
"github.com/pkg/errors"
)
var (
certCache = map[string]*x509.Certificate{}
certMu sync.RWMutex
)
func retriveCertificate(file string) (cert *x509.Certificate, err error) {
certMu.RLock()
if certCache[file] != nil {
cert = certCache[file]
}
certMu.RUnlock()
if cert != nil {
return cert, nil
}
fp, err := os.Open(file)
if err != nil {
return nil, err
}
defer fp.Close()
buf, err := ioutil.ReadAll(fp)
if err != nil {
return nil, err
}
block, _ := pem.Decode(buf)
if block == nil {
return nil, fmt.Errorf("failed to decode certificate (%v)", file)
}
cert, err = x509.ParseCertificate(block.Bytes)
if err != nil {
return nil, err
}
return cert, err
}
func validateKeyFile(file string, err error) (string, error) {
if err != nil {
return "", err
}
cert, err := retriveCertificate(file)
if err != nil {
return "", errors.Wrapf(err, "failed to read certificate %v", file)
}
now := time.Now()
if now.Before(cert.NotBefore) {
return "", fmt.Errorf("security certificate is not valid yet (notBefore=%v)", cert.NotBefore)
}
if now.After(cert.NotAfter) {
return "", fmt.Errorf("security certificate has expired (notAfter=%v)", cert.NotAfter)
}
certMu.Lock()
// Cache only a valid cert
certCache[file] = cert
certMu.Unlock()
return file, err
}