/
client.go
52 lines (43 loc) · 1.33 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
package cdr
import (
"crypto/tls"
"crypto/x509"
"fmt"
"net/http"
"os"
)
var (
// ErrInvalidKeys is when certificates cannot be created for an http client.
ErrInvalidKeys = fmt.Errorf("cdr : invalid mTLS cert/key combination")
)
// New creates a new http client with certificates attached to it. Most of the funcitons in this cdr package require a *http.Client as an argument. This is the way to build that client.
func New(cert []byte, privKey []byte) (*http.Client, error) {
certificate, err := tls.X509KeyPair(cert, privKey)
if err != nil {
return nil, ErrInvalidKeys
}
caCertPool := x509.NewCertPool()
caCertPool.AppendCertsFromPEM(cert)
/* #nosec */
rt := &http.Transport{
TLSClientConfig: &tls.Config{
RootCAs: caCertPool,
Certificates: []tls.Certificate{certificate},
InsecureSkipVerify: true,
Renegotiation: tls.RenegotiateOnceAsClient,
},
}
client := &http.Client{
Transport: rt,
}
return client, nil
}
// NewFromEnv creates a new http client taking its certificates from environment variables. This ishelpful if the certificates are const.
// The environment variables are:
// CDR_MTLS_CERTIFICATE
// CDR_MTLS_PRIVATE_KEY
func NewFromEnv() (*http.Client, error) {
cert := os.Getenv("CDR_MTLS_CERTIFICATE")
pk := os.Getenv("CDR_MTLS_PRIVATE_KEY")
return New([]byte(cert), []byte(pk))
}