-
Notifications
You must be signed in to change notification settings - Fork 3
/
grpcserver.go
134 lines (113 loc) · 3.74 KB
/
grpcserver.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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
package main
import (
"context"
"errors"
"github.com/gcash/bchd/bchrpc"
"github.com/improbable-eng/grpc-web/go/grpcweb"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials"
"google.golang.org/grpc/metadata"
"google.golang.org/grpc/peer"
"net"
"net/http"
"strings"
)
// AuthenticationTokenKey is the key used in the context to authenticate clients.
// If this is set to anything other than "" in the config, then the server expects
// the client to set a key value in the context metadata to 'AuthenticationToken: cfg.AuthToken'
const AuthenticationTokenKey = "AuthenticationToken"
func newGrpcServer(netAddrs []net.Addr, rpcCfg *bchrpc.GrpcServerConfig, svr *server) (*bchrpc.GrpcServer, error) {
for _, addr := range netAddrs {
rpcCfg.NetMgr = svr
opts := []grpc.ServerOption{grpc.StreamInterceptor(interceptStreaming), grpc.UnaryInterceptor(interceptUnary)}
creds, err := credentials.NewServerTLSFromFile(cfg.RPCCert, cfg.RPCKey)
if err != nil {
return nil, err
}
opts = append(opts, grpc.Creds(creds))
server := grpc.NewServer(opts...)
allowAllOrigins := grpcweb.WithOriginFunc(func(origin string) bool {
return true
})
wrappedGrpc := grpcweb.WrapServer(server, allowAllOrigins)
rpcCfg.Server = server
handler := func(resp http.ResponseWriter, req *http.Request) {
if wrappedGrpc.IsGrpcWebRequest(req) || wrappedGrpc.IsAcceptableGrpcCorsRequest(req) {
wrappedGrpc.ServeHTTP(resp, req)
} else {
server.ServeHTTP(resp, req)
}
}
httpServer := &http.Server{
Addr: addr.String(),
Handler: http.HandlerFunc(handler),
}
rpcCfg.HTTPServer = httpServer
gRPCServer := bchrpc.NewGrpcServer(rpcCfg)
grpcLog.Infof("Experimental gRPC server listening on %s", addr)
go func() {
if err := httpServer.ListenAndServeTLS(cfg.RPCCert, cfg.RPCKey); err != nil {
grpcLog.Tracef("Finished serving expimental gRPC: %v", err)
}
}()
return gRPCServer, nil
}
return nil, nil
}
// serviceName returns the package.service segment from the full gRPC method
// name `/package.service/method`.
func serviceName(method string) string {
// Slice off first /
method = method[1:]
// Keep everything before the next /
return method[:strings.IndexRune(method, '/')]
}
func interceptStreaming(srv interface{}, ss grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler) error {
p, ok := peer.FromContext(ss.Context())
if ok {
grpcLog.Infof("Streaming method %s invoked by %s", info.FullMethod,
p.Addr.String())
}
err := validateAuthenticationToken(ss.Context())
if err != nil {
return err
}
err = bchrpc.ServiceReady(serviceName(info.FullMethod))
if err != nil {
return err
}
err = handler(srv, ss)
if err != nil && ok {
grpcLog.Errorf("Streaming method %s invoked by %s errored: %v",
info.FullMethod, p.Addr.String(), err)
}
return err
}
func interceptUnary(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (resp interface{}, err error) {
p, ok := peer.FromContext(ctx)
if ok {
grpcLog.Infof("Unary method %s invoked by %s", info.FullMethod,
p.Addr.String())
}
err = validateAuthenticationToken(ctx)
if err != nil {
return nil, err
}
err = bchrpc.ServiceReady(serviceName(info.FullMethod))
if err != nil {
return nil, err
}
resp, err = handler(ctx, req)
if err != nil && ok {
grpcLog.Errorf("Unary method %s invoked by %s errored: %v",
info.FullMethod, p.Addr.String(), err)
}
return resp, err
}
func validateAuthenticationToken(ctx context.Context) error {
md, ok := metadata.FromIncomingContext(ctx)
if cfg.GrpcAuthToken != "" && (!ok || len(md.Get(AuthenticationTokenKey)) == 0 || md.Get(AuthenticationTokenKey)[0] != cfg.GrpcAuthToken) {
return errors.New("invalid authentication token")
}
return nil
}