forked from improbable-eng/grpc-web
-
Notifications
You must be signed in to change notification settings - Fork 0
/
wrapper.go
238 lines (209 loc) · 8.56 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
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
//Copyright 2017 Improbable. All Rights Reserved.
// See LICENSE for licensing terms.
package grpcweb
import (
"context"
"encoding/base64"
"io"
"net/http"
"strings"
"time"
"github.com/gorilla/websocket"
"github.com/rs/cors"
"google.golang.org/grpc"
"google.golang.org/grpc/grpclog"
)
var (
internalRequestHeadersWhitelist = []string{
"U-A", // for gRPC-Web User Agent indicator.
}
)
// https://github.com/grpc/grpc/blob/master/doc/PROTOCOL-WEB.md#protocol-differences-vs-grpc-over-http2
const grpcContentType = "application/grpc"
const grpcWebContentType = "application/grpc-web"
const grpcWebTextContentType = "application/grpc-web-text"
type WrappedGrpcServer struct {
server *grpc.Server
opts *options
corsWrapper *cors.Cors
originFunc func(origin string) bool
enableWebsockets bool
websocketOriginFunc func(req *http.Request) bool
}
// 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 :( )
})
websocketOriginFunc := opts.websocketOriginFunc
if websocketOriginFunc == nil {
websocketOriginFunc = defaultWebsocketOriginFunc
}
return &WrappedGrpcServer{
server: server,
opts: opts,
corsWrapper: corsWrapper,
originFunc: opts.originFunc,
enableWebsockets: opts.enableWebsockets,
websocketOriginFunc: websocketOriginFunc,
}
}
// 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.enableWebsockets && w.IsGrpcWebSocketRequest(req) {
if w.websocketOriginFunc(req) {
if !w.opts.corsForRegisteredEndpointsOnly || w.isRequestForRegisteredEndpoint(req) {
w.HandleGrpcWebsocketRequest(resp, req)
return
}
}
resp.WriteHeader(403)
resp.Write(make([]byte, 0))
return
}
if w.IsAcceptableGrpcCorsRequest(req) || w.IsGrpcWebRequest(req) {
w.corsWrapper.Handler(http.HandlerFunc(w.HandleGrpcWebRequest)).ServeHTTP(resp, req)
return
}
w.server.ServeHTTP(resp, req)
}
// IsGrpcWebSocketRequest determines if a request is a gRPC-Web request by checking that the "Sec-Websocket-Protocol"
// header value is "grpc-websockets"
func (w *WrappedGrpcServer) IsGrpcWebSocketRequest(req *http.Request) bool {
return req.Header.Get("Upgrade") == "websocket" && req.Header.Get("Sec-Websocket-Protocol") == "grpc-websockets"
}
// 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, isTextFormat := hackIntoNormalGrpcRequest(req)
intResp := newGrpcWebResponse(resp, isTextFormat)
w.server.ServeHTTP(intResp, intReq)
intResp.finishRequest(req)
}
var websocketUpgrader = websocket.Upgrader{
ReadBufferSize: 1024,
WriteBufferSize: 1024,
CheckOrigin: func(r *http.Request) bool { return true },
Subprotocols: []string{"grpc-websockets"},
}
// HandleGrpcWebsocketRequest takes a HTTP request that is assumed to be a gRPC-Websocket 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) HandleGrpcWebsocketRequest(resp http.ResponseWriter, req *http.Request) {
conn, err := websocketUpgrader.Upgrade(resp, req, nil)
if err != nil {
grpclog.Errorf("Unable to upgrade websocket request: %v", err)
return
}
w.handleWebSocket(conn, req)
}
func (w *WrappedGrpcServer) handleWebSocket(wsConn *websocket.Conn, req *http.Request) {
messageType, readBytes, err := wsConn.ReadMessage()
if err != nil {
grpclog.Errorf("Unable to read first websocket message: %v", err)
return
}
if messageType != websocket.BinaryMessage {
grpclog.Errorf("First websocket message is non-binary")
return
}
headers, err := parseHeaders(string(readBytes))
if err != nil {
grpclog.Errorf("Unable to parse websocket headers: %v", err)
return
}
ctx, cancelFunc := context.WithCancel(req.Context())
defer cancelFunc()
respWriter := newWebSocketResponseWriter(wsConn)
wrappedReader := newWebsocketWrappedReader(wsConn, respWriter, cancelFunc)
req.Body = wrappedReader
req.Method = http.MethodPost
req.Header = headers
interceptedRequest, isTextFormat := hackIntoNormalGrpcRequest(req.WithContext(ctx))
if isTextFormat {
grpclog.Errorf("web socket text format requests not yet supported")
return
}
w.server.ServeHTTP(respWriter, interceptedRequest)
}
// 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"), grpcWebContentType)
}
// 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
}
// readerCloser combines an io.Reader and an io.Closer into an io.ReadCloser.
type readerCloser struct {
reader io.Reader
closer io.Closer
}
func (r *readerCloser) Read(dest []byte) (int, error) {
return r.reader.Read(dest)
}
func (r *readerCloser) Close() error {
return r.closer.Close()
}
func hackIntoNormalGrpcRequest(req *http.Request) (*http.Request, bool) {
// 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")
incomingContentType := grpcWebContentType
isTextFormat := strings.HasPrefix(contentType, grpcWebTextContentType)
if isTextFormat {
// body is base64-encoded: decode it; Wrap it in readerCloser so Body is still closed
decoder := base64.NewDecoder(base64.StdEncoding, req.Body)
req.Body = &readerCloser{reader: decoder, closer: req.Body}
incomingContentType = grpcWebTextContentType
}
req.Header.Set("content-type", strings.Replace(contentType, incomingContentType, grpcContentType, 1))
return req, isTextFormat
}
func defaultWebsocketOriginFunc(req *http.Request) bool {
origin, err := WebsocketRequestOrigin(req)
if err != nil {
grpclog.Warning(err)
return false
}
return origin == req.Host
}