@@ -5,17 +5,64 @@ import (
55 "crypto/x509"
66 "errors"
77 "fmt"
8+ "os"
9+ "strings"
10+
811 "google.golang.org/grpc"
912 "google.golang.org/grpc/credentials"
10- "os"
1113)
1214
13- func LoadTLSCredentials (RootCAPath * string , withInsecure bool ) (grpc.DialOption , error ) {
15+ func ParseEndpoint (e string ) (string , bool ) {
16+ if strings .HasPrefix (e , "grpcs://" ) {
17+ return e [8 :], true
18+ }
19+ if strings .HasPrefix (e , "grpc://" ) {
20+ return e [7 :], false
21+ }
22+ return e , false
23+ }
24+
25+ func LoadTLSCredentials (rootCAPath * string , withInsecure bool ) (grpc.DialOption , error ) {
26+ tlsConfig , err := buildTLSConfig (rootCAPath , withInsecure )
27+ if err != nil {
28+ return nil , err
29+ }
30+ return grpc .WithTransportCredentials (credentials .NewTLS (tlsConfig )), nil
31+ }
32+
33+ func LoadMTLSCredentials (
34+ rootCAPath * string ,
35+ clientCertPath * string ,
36+ clientKeyPath * string ,
37+ withInsecure bool ,
38+ ) (grpc.DialOption , error ) {
39+ if clientCertPath == nil || len (* clientCertPath ) == 0 {
40+ return nil , fmt .Errorf ("client certificate path is required for mTLS" )
41+ }
42+ if clientKeyPath == nil || len (* clientKeyPath ) == 0 {
43+ return nil , fmt .Errorf ("client key path is required for mTLS" )
44+ }
45+
46+ tlsConfig , err := buildTLSConfig (rootCAPath , withInsecure )
47+ if err != nil {
48+ return nil , err
49+ }
50+
51+ cert , err := tls .LoadX509KeyPair (* clientCertPath , * clientKeyPath )
52+ if err != nil {
53+ return nil , fmt .Errorf ("failed to load client certificate/key: %w" , err )
54+ }
55+ tlsConfig .Certificates = []tls.Certificate {cert }
56+
57+ return grpc .WithTransportCredentials (credentials .NewTLS (tlsConfig )), nil
58+ }
59+
60+ func buildTLSConfig (rootCAPath * string , withInsecure bool ) (* tls.Config , error ) {
1461 var certPool * x509.CertPool
15- if RootCAPath != nil && len (* RootCAPath ) > 0 {
16- caBundle , err := os .ReadFile (* RootCAPath )
62+ if rootCAPath != nil && len (* rootCAPath ) > 0 {
63+ caBundle , err := os .ReadFile (* rootCAPath )
1764 if err != nil {
18- return nil , fmt .Errorf ("unable to read root ca bundle from file %s: %w" , * RootCAPath , err )
65+ return nil , fmt .Errorf ("unable to read root ca bundle from file %s: %w" , * rootCAPath , err )
1966 }
2067 certPool = x509 .NewCertPool ()
2168 if ok := certPool .AppendCertsFromPEM (caBundle ); ! ok {
@@ -36,5 +83,5 @@ func LoadTLSCredentials(RootCAPath *string, withInsecure bool) (grpc.DialOption,
3683 if withInsecure {
3784 tlsConfig .InsecureSkipVerify = true
3885 }
39- return grpc . WithTransportCredentials ( credentials . NewTLS ( tlsConfig )) , nil
86+ return tlsConfig , nil
4087}
0 commit comments