-
Notifications
You must be signed in to change notification settings - Fork 4
/
client.go
96 lines (73 loc) · 1.64 KB
/
client.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
package main
import (
"crypto/x509"
"encoding/pem"
"fmt"
"io"
"io/ioutil"
"os"
)
type Client struct {
httpClient HTTPClient
out io.Writer
}
func NewClient(httpClient HTTPClient, out io.Writer) *Client {
client := &Client{}
client.httpClient = httpClient
client.out = out
return client
}
func (c *Client) GetIssuerCertificate(cert *x509.Certificate) (*x509.Certificate, error) {
var issCert *x509.Certificate
for _, url := range cert.IssuingCertificateURL {
resp, err := c.httpClient.Get(url)
if err != nil {
continue
}
if err != nil {
return nil, errFailedToGetResource
}
defer func() {
if cerr := resp.Body.Close(); err == nil {
err = cerr
}
}()
in, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, errFailedToReadResponseBody
}
issCert, err = certificateFromBytes(in)
if err != nil {
return nil, errNoIssuerCertificate
}
break
}
if issCert == nil {
return nil, errNoIssuerCertificate
}
return issCert, nil
}
func certificateFromBytes(bytes []byte) (*x509.Certificate, error) {
block, bytes := pem.Decode(bytes)
if block != nil {
if block.Type != "CERTIFICATE" {
return nil, errNoCertificate
}
bytes = block.Bytes
}
return x509.ParseCertificate(bytes)
}
func readCertificate(path string) (*x509.Certificate, error) {
in, err := ioutil.ReadFile(path)
if err != nil {
fmt.Fprintf(os.Stderr, "[error] %v\n", err)
return nil, errFailedToReadCertificate
}
var cert *x509.Certificate
cert, err = certificateFromBytes(in)
if err != nil {
fmt.Fprintf(os.Stderr, "[error] %v\n", err)
return nil, errFailedToReadCertificate
}
return cert, nil
}