forked from improbable-eng/grpc-web
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathwrapper.go
114 lines (101 loc) · 4.49 KB
/
wrapper.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
//Copyright 2017 Improbable. All Rights Reserved.
// See LICENSE for licensing terms.
package grpcweb
import (
"net/http"
"strings"
"time"
"github.com/rs/cors"
"google.golang.org/grpc"
)
var (
internalRequestHeadersWhitelist = []string{
"U-A", // for gRPC-Web User Agent indicator.
}
)
type WrappedGrpcServer struct {
server *grpc.Server
opts *options
corsWrapper *cors.Cors
}
// WrapServer takes a gRPC Server in Go and returns a WrappedGrpcServer that provides gRPC-Web Compatibility.
//
// The internal implementation fakes out a http.Request that carries standard gRPC, and performs the remapping inside
// http.ResponseWriter, i.e. mostly the re-encoding of Trailers (that carry gRPC status).
//
// You can control the behaviour of the wrapper (e.g. modifying CORS behaviour) using `With*` options.
func WrapServer(server *grpc.Server, options ...Option) *WrappedGrpcServer {
opts := evaluateOptions(options)
corsWrapper := cors.New(cors.Options{
AllowOriginFunc: opts.originFunc,
AllowedHeaders: append(opts.allowedRequestHeaders, internalRequestHeadersWhitelist...),
ExposedHeaders: nil, // make sure that this is *nil*, otherwise the WebResponse overwrite will not work.
AllowCredentials: true, // always allow credentials, otherwise :authorization headers won't work
MaxAge: int(10 * time.Minute / time.Second), // make sure pre-flights don't happen too often (every 5s for Chromium :( )
})
return &WrappedGrpcServer{
server: server,
opts: opts,
corsWrapper: corsWrapper,
}
}
// ServeHTTP takes a HTTP request and if it is a gRPC-Web request wraps it with a compatibility layer to transform it to
// a standard gRPC request for the wrapped gRPC server and transforms the response to comply with the gRPC-Web protocol.
//
// The gRPC-Web compatibility is only invoked if the request is a gRPC-Web request as determined by IsGrpcWebRequest or
// the request is a pre-flight (CORS) request as determined by IsAcceptableGrpcCorsRequest.
//
// You can control the CORS behaviour using `With*` options in the WrapServer function.
func (w *WrappedGrpcServer) ServeHTTP(resp http.ResponseWriter, req *http.Request) {
if w.IsAcceptableGrpcCorsRequest(req) || w.IsGrpcWebRequest(req) {
w.corsWrapper.Handler(http.HandlerFunc(w.HandleGrpcWebRequest)).ServeHTTP(resp, req)
return
}
w.server.ServeHTTP(resp, req)
}
// HandleGrpcWebRequest takes a HTTP request that is assumed to be a gRPC-Web request and wraps it with a compatibility
// layer to transform it to a standard gRPC request for the wrapped gRPC server and transforms the response to comply
// with the gRPC-Web protocol.
func (w *WrappedGrpcServer) HandleGrpcWebRequest(resp http.ResponseWriter, req *http.Request) {
intReq := hackIntoNormalGrpcRequest(req)
intResp := newGrpcWebResponse(resp)
w.server.ServeHTTP(intResp, intReq)
intResp.finishRequest(req)
}
// IsGrpcWebRequest determines if a request is a gRPC-Web request by checking that the "content-type" is
// "application/grpc-web" and that the method is POST.
func (w *WrappedGrpcServer) IsGrpcWebRequest(req *http.Request) bool {
return req.Method == http.MethodPost && strings.HasPrefix(req.Header.Get("content-type"), "application/grpc-web")
}
// IsAcceptableGrpcCorsRequest determines if a request is a CORS pre-flight request for a gRPC-Web request and that this
// request is acceptable for CORS.
//
// You can control the CORS behaviour using `With*` options in the WrapServer function.
func (w *WrappedGrpcServer) IsAcceptableGrpcCorsRequest(req *http.Request) bool {
accessControlHeaders := strings.ToLower(req.Header.Get("Access-Control-Request-Headers"))
if req.Method == http.MethodOptions && strings.Contains(accessControlHeaders, "x-grpc-web") {
if w.opts.corsForRegisteredEndpointsOnly {
return w.isRequestForRegisteredEndpoint(req)
}
return true
}
return false
}
func (w *WrappedGrpcServer) isRequestForRegisteredEndpoint(req *http.Request) bool {
registeredEndpoints := ListGRPCResources(w.server)
requestedEndpoint := req.URL.Path
for _, v := range registeredEndpoints {
if v == requestedEndpoint {
return true
}
}
return false
}
func hackIntoNormalGrpcRequest(req *http.Request) *http.Request {
// Hack, this should be a shallow copy, but let's see if this works
req.ProtoMajor = 2
req.ProtoMinor = 0
contentType := req.Header.Get("content-type")
req.Header.Set("content-type", strings.Replace(contentType, "application/grpc-web", "application/grpc", 1))
return req
}