/
grpc.go
58 lines (50 loc) · 1.49 KB
/
grpc.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
package credentials
import (
"crypto/tls"
"crypto/x509"
"errors"
"fmt"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials"
"google.golang.org/grpc/credentials/insecure"
)
func GetServerOptions(certChain *CertChain) ([]grpc.ServerOption, error) {
opts := []grpc.ServerOption{}
if certChain == nil {
return nil, nil
}
cp := x509.NewCertPool()
cp.AppendCertsFromPEM(certChain.RootCA)
cert, err := tls.X509KeyPair(certChain.Cert, certChain.Key)
if err != nil {
return nil, err
}
config := &tls.Config{
ClientCAs: cp,
// Require cert verification
ClientAuth: tls.RequireAndVerifyClientCert,
Certificates: []tls.Certificate{cert},
MinVersion: tls.VersionTLS12,
}
opts = append(opts, grpc.Creds(credentials.NewTLS(config)))
return opts, nil
}
func GetClientOptions(certChain *CertChain, serverName string) ([]grpc.DialOption, error) {
opts := []grpc.DialOption{}
if certChain != nil {
cp := x509.NewCertPool()
ok := cp.AppendCertsFromPEM(certChain.RootCA)
if !ok {
return nil, errors.New("failed to append PEM root cert to x509 CertPool")
}
config, err := TLSConfigFromCertAndKey(certChain.Cert, certChain.Key, serverName, cp)
config.MinVersion = tls.VersionTLS12
if err != nil {
return nil, fmt.Errorf("failed to create tls config from cert and key: %w", err)
}
opts = append(opts, grpc.WithTransportCredentials(credentials.NewTLS(config)))
} else {
opts = append(opts, grpc.WithTransportCredentials(insecure.NewCredentials()))
}
return opts, nil
}