From 1a36d08a467cd61715e2abe709fb46b21da9b730 Mon Sep 17 00:00:00 2001 From: finlab Date: Sun, 17 Jan 2021 22:11:42 +0800 Subject: [PATCH] add: gateway-tls --- cmd/gateway-tls/main.go | 106 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 106 insertions(+) create mode 100644 cmd/gateway-tls/main.go diff --git a/cmd/gateway-tls/main.go b/cmd/gateway-tls/main.go new file mode 100644 index 0000000..722247c --- /dev/null +++ b/cmd/gateway-tls/main.go @@ -0,0 +1,106 @@ +package main + +import ( + "context" + "crypto/tls" + "crypto/x509" + "flag" + "io/ioutil" + "net/http" + + "github.com/golang/glog" + "github.com/grpc-ecosystem/grpc-gateway/v2/runtime" + log "github.com/sirupsen/logrus" + "google.golang.org/grpc" + "google.golang.org/grpc/credentials" + + gw "github.com/esinio/geco/gen/proto/echo/v1" // Update +) + +var ( + grpcServerEndpoint string +) + +func init() { + flag.StringVar(&grpcServerEndpoint, "grpc-server-endpoint", "localhost:9090", "gRPC server endpoint") +} + +func run() error { + ctx := context.Background() + ctx, cancel := context.WithCancel(ctx) + defer cancel() + + // Register gRPC server endpoint + // Note: Make sure the gRPC server is running properly and accessible + mux := runtime.NewServeMux() + opts := []grpc.DialOption{ + grpcServerClientCreds(), + } + err := gw.RegisterEchoServiceHandlerFromEndpoint(ctx, mux, grpcServerEndpoint, opts) + if err != nil { + return err + } + + // Start HTTP server (and proxy calls to gRPC server endpoint) + return http.ListenAndServe(":8081", mux) +} + +func main() { + flag.Parse() + defer glog.Flush() + + if err := run(); err != nil { + glog.Fatal(err) + } +} + +func gwCreds() credentials.TransportCredentials { + cert, err := tls.LoadX509KeyPair("./cert/server.pem", "./cert/server.key") + if err != nil { + log.Fatal(err) + } + + certPool := x509.NewCertPool() + ca, err := ioutil.ReadFile("./cert/ca.pem") + if err != nil { + log.Fatal(err) + } + if ok := certPool.AppendCertsFromPEM(ca); !ok { + log.Fatal("failed to append certs") + } + + creds := credentials.NewTLS(&tls.Config{ + Certificates: []tls.Certificate{cert}, + ClientAuth: tls.RequireAndVerifyClientCert, // NOTE: this is optional! + ClientCAs: certPool, + }) + + return creds +} + +func grpcServerClientCreds() grpc.DialOption { + cert, err := tls.LoadX509KeyPair("./cert/client.pem", "./cert/client.key") + if err != nil { + log.Fatalf("tls.LoadX509KeyPair err: %v", err) + return nil + } + + certPool := x509.NewCertPool() + ca, err := ioutil.ReadFile("./cert/ca.pem") + if err != nil { + log.Fatalf("ioutil.ReadFile err: %v", err) + return nil + } + + if ok := certPool.AppendCertsFromPEM(ca); !ok { + log.Fatalf("certPool.AppendCertsFromPEM err") + return nil + } + + creds := credentials.NewTLS(&tls.Config{ + Certificates: []tls.Certificate{cert}, + ServerName: "example.grpc.io", + RootCAs: certPool, + }) + return grpc.WithTransportCredentials(creds) +}