-
Notifications
You must be signed in to change notification settings - Fork 0
/
mtls_client.go
66 lines (58 loc) · 1.66 KB
/
mtls_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
package util
import (
"crypto/tls"
"crypto/x509"
"fmt"
"net/http"
"time"
)
type TLSAuthClient struct {
CA []byte
Cert []byte
Key []byte
}
func (auth *TLSAuthClient) GetHTTPSClient() (http.Client, error) {
caCertPool := x509.NewCertPool()
caCertPool.AppendCertsFromPEM(auth.CA)
cert, err := tls.X509KeyPair(auth.Cert, auth.Key)
if err != nil {
return http.Client{}, fmt.Errorf("(cert: [ %s ], key: [ %s ]): %w", string(auth.Cert), string(auth.Key), err)
}
tlsConfig := &tls.Config{
RootCAs: caCertPool,
Certificates: []tls.Certificate{cert},
}
if tlsConfig.NextProtos == nil {
tlsConfig.NextProtos = []string{"http/1.1"}
}
tlsConfig.BuildNameToCertificate()
return http.Client{
Transport: &http.Transport{
TLSClientConfig: tlsConfig,
},
Timeout: time.Duration(10 * time.Second),
}, nil
}
// GetTLSConfig returns a tls config object to be used by mTLS HTTP/ETCD
// clients etc.
func (auth *TLSAuthClient) GetTLSConfig() (*tls.Config, error) {
caCertPool := x509.NewCertPool()
caCertPool.AppendCertsFromPEM(auth.CA)
cert, err := tls.X509KeyPair(auth.Cert, auth.Key)
if err != nil {
return &tls.Config{}, fmt.Errorf("(cert: [ %s ], key: [ %s ]): %w", string(auth.Cert), string(auth.Key), err)
}
tlsConfig := &tls.Config{
RootCAs: caCertPool,
Certificates: []tls.Certificate{cert},
}
if tlsConfig.NextProtos == nil {
tlsConfig.NextProtos = []string{"http/1.1"}
}
tlsConfig.BuildNameToCertificate()
return tlsConfig, nil
}
// String implements Stringer for printing
func (auth *TLSAuthClient) String() string {
return fmt.Sprintf("(cert: [ %s ], key: [ %s ], ca: [ %s ])", string(auth.Cert), string(auth.Key), string(auth.CA))
}