@@ -5,17 +5,53 @@ import (
55 "crypto/x509"
66 "errors"
77 "fmt"
8+ "os"
9+
810 "google.golang.org/grpc"
911 "google.golang.org/grpc/credentials"
10- "os"
1112)
1213
13- func LoadTLSCredentials (RootCAPath * string , withInsecure bool ) (grpc.DialOption , error ) {
14+ func LoadTLSCredentials (rootCAPath * string , withInsecure bool ) (grpc.DialOption , error ) {
15+ tlsConfig , err := buildTLSConfig (rootCAPath , withInsecure )
16+ if err != nil {
17+ return nil , err
18+ }
19+ return grpc .WithTransportCredentials (credentials .NewTLS (tlsConfig )), nil
20+ }
21+
22+ func LoadMTLSCredentials (
23+ rootCAPath * string ,
24+ clientCertPath * string ,
25+ clientKeyPath * string ,
26+ withInsecure bool ,
27+ ) (grpc.DialOption , error ) {
28+ if clientCertPath == nil || len (* clientCertPath ) == 0 {
29+ return nil , fmt .Errorf ("client certificate path is required for mTLS" )
30+ }
31+ if clientKeyPath == nil || len (* clientKeyPath ) == 0 {
32+ return nil , fmt .Errorf ("client key path is required for mTLS" )
33+ }
34+
35+ tlsConfig , err := buildTLSConfig (rootCAPath , withInsecure )
36+ if err != nil {
37+ return nil , err
38+ }
39+
40+ cert , err := tls .LoadX509KeyPair (* clientCertPath , * clientKeyPath )
41+ if err != nil {
42+ return nil , fmt .Errorf ("failed to load client certificate/key: %w" , err )
43+ }
44+ tlsConfig .Certificates = []tls.Certificate {cert }
45+
46+ return grpc .WithTransportCredentials (credentials .NewTLS (tlsConfig )), nil
47+ }
48+
49+ func buildTLSConfig (rootCAPath * string , withInsecure bool ) (* tls.Config , error ) {
1450 var certPool * x509.CertPool
15- if RootCAPath != nil && len (* RootCAPath ) > 0 {
16- caBundle , err := os .ReadFile (* RootCAPath )
51+ if rootCAPath != nil && len (* rootCAPath ) > 0 {
52+ caBundle , err := os .ReadFile (* rootCAPath )
1753 if err != nil {
18- return nil , fmt .Errorf ("unable to read root ca bundle from file %s: %w" , * RootCAPath , err )
54+ return nil , fmt .Errorf ("unable to read root ca bundle from file %s: %w" , * rootCAPath , err )
1955 }
2056 certPool = x509 .NewCertPool ()
2157 if ok := certPool .AppendCertsFromPEM (caBundle ); ! ok {
@@ -36,5 +72,5 @@ func LoadTLSCredentials(RootCAPath *string, withInsecure bool) (grpc.DialOption,
3672 if withInsecure {
3773 tlsConfig .InsecureSkipVerify = true
3874 }
39- return grpc . WithTransportCredentials ( credentials . NewTLS ( tlsConfig )) , nil
75+ return tlsConfig , nil
4076}
0 commit comments