-
Notifications
You must be signed in to change notification settings - Fork 2
/
helpers.go
42 lines (36 loc) · 1.07 KB
/
helpers.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
package main
import (
"crypto/tls"
"crypto/x509"
"fmt"
"os"
"google.golang.org/grpc/credentials"
)
func buildCredentials(skipVerify bool, caCerts, clientCert, clientKey, serverName string) (credentials.TransportCredentials, *tls.Config, error) {
var cfg tls.Config
if clientCert != "" && clientKey != "" {
keyPair, err := tls.LoadX509KeyPair(clientCert, clientKey)
if err != nil {
return nil, &cfg, fmt.Errorf("failed to load tls client cert/key pair. error=%v", err)
}
cfg.Certificates = []tls.Certificate{keyPair}
}
if skipVerify {
cfg.InsecureSkipVerify = true
} else if caCerts != "" {
// override system roots
rootCAs := x509.NewCertPool()
pem, err := os.ReadFile(caCerts)
if err != nil {
return nil, &cfg, fmt.Errorf("failed to load root CA certificates from file (%s) error=%v", caCerts, err)
}
if !rootCAs.AppendCertsFromPEM(pem) {
return nil, &cfg, fmt.Errorf("no root CA certs parsed from file %s", caCerts)
}
cfg.RootCAs = rootCAs
}
if serverName != "" {
cfg.ServerName = serverName
}
return credentials.NewTLS(&cfg), &cfg, nil
}