-
Notifications
You must be signed in to change notification settings - Fork 2k
/
client_tls.go
66 lines (56 loc) · 1.59 KB
/
client_tls.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 grpcutils
import (
"crypto/tls"
"crypto/x509"
"fmt"
"io/ioutil"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials"
)
// TLSClientConfig returns the TLS config to use for a client to
// connect to a server with the provided parameters.
func TLSClientConfig(cert, key, ca, name string) (*tls.Config, error) {
config := &tls.Config{}
// Load the client-side cert & key if any.
if cert != "" && key != "" {
crt, err := tls.LoadX509KeyPair(cert, key)
if err != nil {
return nil, fmt.Errorf("failed to load cert/key: %v", err)
}
config.Certificates = []tls.Certificate{crt}
}
// Load the server CA if any.
if ca != "" {
b, err := ioutil.ReadFile(ca)
if err != nil {
return nil, fmt.Errorf("failed to read ca file: %v", err)
}
cp := x509.NewCertPool()
if !cp.AppendCertsFromPEM(b) {
return nil, fmt.Errorf("failed to append certificates")
}
config.RootCAs = cp
}
// Set the server name if any.
if name != "" {
config.ServerName = name
}
return config, nil
}
// ClientSecureDialOption returns the gRPC dial option to use for the
// given client connection. It is either using TLS, or Insecure if
// nothing is set.
func ClientSecureDialOption(cert, key, ca, name string) (grpc.DialOption, error) {
// No security options set, just return.
if (cert == "" || key == "") && ca == "" {
return grpc.WithInsecure(), nil
}
// Load the config.
config, err := TLSClientConfig(cert, key, ca, name)
if err != nil {
return nil, err
}
// Create the creds server options.
creds := credentials.NewTLS(config)
return grpc.WithTransportCredentials(creds), nil
}