-
Notifications
You must be signed in to change notification settings - Fork 437
/
Copy pathwrapper_test.go
730 lines (651 loc) · 27 KB
/
wrapper_test.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
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
//Copyright 2017 Improbable. All Rights Reserved.
// See LICENSE for licensing terms.
package grpcweb_test
import (
"bufio"
"bytes"
"crypto/tls"
"encoding/base64"
"encoding/binary"
"fmt"
"io"
"io/ioutil"
"log"
"net"
"net/http"
"net/http/httptest"
"net/textproto"
"os"
"strconv"
"strings"
"testing"
"time"
"github.com/golang/protobuf/proto"
google_protobuf "github.com/golang/protobuf/ptypes/empty"
"github.com/improbable-eng/grpc-web/go/grpcweb"
testproto "github.com/improbable-eng/grpc-web/integration_test/go/_proto/improbable/grpcweb/test"
"github.com/mwitkow/go-conntrack/connhelpers"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/stretchr/testify/suite"
"golang.org/x/net/context"
"golang.org/x/net/http2"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/credentials"
"google.golang.org/grpc/grpclog"
"google.golang.org/grpc/metadata"
)
var (
expectedListResponses = 3000
expectedHeaders = metadata.Pairs("HeaderTestKey1", "Value1", "HeaderTestKey2", "Value2")
expectedTrailers = metadata.Pairs("TrailerTestKey1", "Value1", "TrailerTestKey2", "Value2")
useFlushForHeaders = "test-internal-use-flush-for-headers"
)
const (
grpcWebContentType = "application/grpc-web"
grpcWebTextContentType = "application/grpc-web-text"
)
type GrpcWebWrapperTestSuite struct {
suite.Suite
httpMajorVersion int
listener net.Listener
grpcServer *grpc.Server
wrappedServer *grpcweb.WrappedGrpcServer
}
func TestHttp2GrpcWebWrapperTestSuite(t *testing.T) {
suite.Run(t, &GrpcWebWrapperTestSuite{httpMajorVersion: 2})
}
func TestHttp1GrpcWebWrapperTestSuite(t *testing.T) {
suite.Run(t, &GrpcWebWrapperTestSuite{httpMajorVersion: 1})
}
func TestNonRootResource(t *testing.T) {
grpcServer := grpc.NewServer()
testproto.RegisterTestServiceServer(grpcServer, &testServiceImpl{})
wrappedServer := grpcweb.WrapServer(grpcServer,
grpcweb.WithAllowNonRootResource(true),
grpcweb.WithOriginFunc(func(origin string) bool {
return true
}))
headers := http.Header{}
headers.Add("Access-Control-Request-Method", "POST")
headers.Add("Access-Control-Request-Headers", "origin, x-something-custom, x-grpc-web, accept")
req := httptest.NewRequest("OPTIONS", "http://host/grpc/improbable.grpcweb.test.TestService/Echo", nil)
req.Header = headers
resp := httptest.NewRecorder()
wrappedServer.ServeHTTP(resp, req)
assert.Equal(t, http.StatusOK, resp.Code)
}
func (s *GrpcWebWrapperTestSuite) SetupTest() {
var err error
s.grpcServer = grpc.NewServer()
testproto.RegisterTestServiceServer(s.grpcServer, &testServiceImpl{})
grpclog.SetLogger(log.New(os.Stderr, "grpc: ", log.LstdFlags))
s.wrappedServer = grpcweb.WrapServer(s.grpcServer)
httpServer := http.Server{
Handler: http.HandlerFunc(func(resp http.ResponseWriter, req *http.Request) {
require.EqualValues(s.T(), s.httpMajorVersion, req.ProtoMajor, "Requests in this test are served over the wrong protocol")
s.T().Logf("Serving over: %d", req.ProtoMajor)
s.wrappedServer.ServeHTTP(resp, req)
}),
}
s.listener, err = net.Listen("tcp", "127.0.0.1:0")
require.NoError(s.T(), err, "failed to set up server socket for test")
tlsConfig, err := connhelpers.TlsConfigForServerCerts("../../misc/localhost.crt", "../../misc/localhost.key")
require.NoError(s.T(), err, "failed loading keys")
if s.httpMajorVersion == 2 {
tlsConfig, err = connhelpers.TlsConfigWithHttp2Enabled(tlsConfig)
require.NoError(s.T(), err, "failed setting http2")
}
s.listener = tls.NewListener(s.listener, tlsConfig)
go func() {
httpServer.Serve(s.listener)
}()
// Wait for the grpcServer to start serving requests.
time.Sleep(10 * time.Millisecond)
}
func (s *GrpcWebWrapperTestSuite) ctxForTest() context.Context {
ctx, _ := context.WithTimeout(context.TODO(), 1*time.Second)
return ctx
}
func (s *GrpcWebWrapperTestSuite) makeRequest(
verb string, method string, headers http.Header, body io.Reader, isText bool,
) (*http.Response, error) {
contentType := "application/grpc-web"
if isText {
// base64 encode the body
encodedBody := &bytes.Buffer{}
encoder := base64.NewEncoder(base64.StdEncoding, encodedBody)
_, err := io.Copy(encoder, body)
if err != nil {
return nil, err
}
err = encoder.Close()
if err != nil {
return nil, err
}
body = encodedBody
contentType = "application/grpc-web-text"
}
url := fmt.Sprintf("https://%s%s", s.listener.Addr().String(), method)
req, err := http.NewRequest(verb, url, body)
req = req.WithContext(s.ctxForTest())
require.NoError(s.T(), err, "failed creating a request")
req.Header = headers
req.Header.Set("Content-Type", contentType)
client := &http.Client{
Transport: &http2.Transport{TLSClientConfig: &tls.Config{InsecureSkipVerify: true}},
}
if s.httpMajorVersion < 2 {
client.Transport = &http.Transport{TLSClientConfig: &tls.Config{InsecureSkipVerify: true}}
}
resp, err := client.Do(req)
return resp, err
}
func decodeMultipleBase64Chunks(b []byte) ([]byte, error) {
// grpc-web allows multiple base64 chunks: the implementation may send base64-encoded
// "chunks" with potential padding whenever the runtime needs to flush a byte buffer.
// https://github.com/grpc/grpc/blob/master/doc/PROTOCOL-WEB.md
output := make([]byte, base64.StdEncoding.DecodedLen(len(b)))
outputEnd := 0
for inputEnd := 0; inputEnd < len(b); {
chunk := b[inputEnd:]
paddingIndex := bytes.IndexByte(chunk, '=')
if paddingIndex != -1 {
// find the consecutive =
for {
paddingIndex += 1
if paddingIndex >= len(chunk) || chunk[paddingIndex] != '=' {
break
}
}
chunk = chunk[:paddingIndex]
}
inputEnd += len(chunk)
n, err := base64.StdEncoding.Decode(output[outputEnd:], chunk)
if err != nil {
return nil, err
}
outputEnd += n
}
return output[:outputEnd], nil
}
func (s *GrpcWebWrapperTestSuite) makeGrpcRequest(
method string, reqHeaders http.Header, requestMessages [][]byte, isText bool,
) (headers http.Header, trailers grpcweb.Trailer, responseMessages [][]byte, err error) {
writer := new(bytes.Buffer)
for _, msgBytes := range requestMessages {
grpcPreamble := []byte{0, 0, 0, 0, 0}
binary.BigEndian.PutUint32(grpcPreamble[1:], uint32(len(msgBytes)))
writer.Write(grpcPreamble)
writer.Write(msgBytes)
}
resp, err := s.makeRequest("POST", method, reqHeaders, writer, isText)
if err != nil {
return nil, grpcweb.Trailer{}, nil, err
}
defer resp.Body.Close()
contents, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, grpcweb.Trailer{}, nil, err
}
if isText {
contents, err = decodeMultipleBase64Chunks(contents)
if err != nil {
return nil, grpcweb.Trailer{}, nil, err
}
}
reader := bytes.NewReader(contents)
for {
grpcPreamble := []byte{0, 0, 0, 0, 0}
readCount, err := reader.Read(grpcPreamble)
if err == io.EOF {
break
}
if readCount != 5 || err != nil {
return nil, grpcweb.Trailer{}, nil, fmt.Errorf("Unexpected end of body in preamble: %v", err)
}
payloadLength := binary.BigEndian.Uint32(grpcPreamble[1:])
payloadBytes := make([]byte, payloadLength)
readCount, err = reader.Read(payloadBytes)
if uint32(readCount) != payloadLength || err != nil {
return nil, grpcweb.Trailer{}, nil, fmt.Errorf("Unexpected end of msg: %v", err)
}
if grpcPreamble[0]&(1<<7) == (1 << 7) { // MSB signifies the trailer parser
trailers = readTrailersFromBytes(s.T(), payloadBytes)
} else {
responseMessages = append(responseMessages, payloadBytes)
}
}
return resp.Header, trailers, responseMessages, nil
}
func (s *GrpcWebWrapperTestSuite) TestPingEmpty() {
headers, trailers, responses, err := s.makeGrpcRequest(
"/improbable.grpcweb.test.TestService/PingEmpty",
headerWithFlag(),
serializeProtoMessages([]proto.Message{&google_protobuf.Empty{}}),
false)
require.NoError(s.T(), err, "No error on making request")
assert.Equal(s.T(), 1, len(responses), "PingEmpty is an unary response")
s.assertTrailerGrpcCode(trailers, codes.OK, "")
s.assertHeadersContainMetadata(headers, expectedHeaders)
s.assertTrailersContainMetadata(trailers, expectedTrailers)
s.assertContentTypeSet(headers, grpcWebContentType)
}
func (s *GrpcWebWrapperTestSuite) TestPing() {
// test both the text and binary formats
for _, contentType := range []string{grpcWebContentType, grpcWebTextContentType} {
headers, trailers, responses, err := s.makeGrpcRequest(
"/improbable.grpcweb.test.TestService/Ping",
headerWithFlag(),
serializeProtoMessages([]proto.Message{&testproto.PingRequest{Value: "foo"}}),
contentType == grpcWebTextContentType)
require.NoError(s.T(), err, "No error on making request")
assert.Equal(s.T(), 1, len(responses), "PingEmpty is an unary response")
s.assertTrailerGrpcCode(trailers, codes.OK, "")
s.assertHeadersContainMetadata(headers, expectedHeaders)
s.assertTrailersContainMetadata(trailers, expectedTrailers)
s.assertHeadersContainCorsExpectedHeaders(headers, expectedHeaders)
s.assertContentTypeSet(headers, contentType)
}
}
func (s *GrpcWebWrapperTestSuite) TestPingError_WithTrailersInData() {
// gRPC-Web spec says that if there is no payload to an answer, the trailers (including grpc-status) must be in the
// headers and not in trailers. However, that's not true if SendHeaders are pushed before. This tests this.
headers, trailers, responses, err := s.makeGrpcRequest(
"/improbable.grpcweb.test.TestService/PingError",
headerWithFlag(useFlushForHeaders),
serializeProtoMessages([]proto.Message{&google_protobuf.Empty{}}),
false)
require.NoError(s.T(), err, "No error on making request")
assert.Equal(s.T(), 0, len(responses), "PingError is an unary response that has no payload")
s.assertTrailerGrpcCode(trailers, codes.Unimplemented, "Not implemented PingError")
s.assertHeadersContainMetadata(headers, expectedHeaders)
s.assertTrailersContainMetadata(trailers, expectedTrailers)
s.assertHeadersContainCorsExpectedHeaders(headers, expectedHeaders)
s.assertContentTypeSet(headers, grpcWebContentType)
}
func (s *GrpcWebWrapperTestSuite) TestPingError_WithTrailersInHeaders() {
// gRPC-Web spec says that if there is no payload to an answer, the trailers (including grpc-status) must be in the
// headers and not in trailers.
headers, _, responses, err := s.makeGrpcRequest(
"/improbable.grpcweb.test.TestService/PingError",
http.Header{},
serializeProtoMessages([]proto.Message{&google_protobuf.Empty{}}),
false)
require.NoError(s.T(), err, "No error on making request")
assert.Equal(s.T(), 0, len(responses), "PingError is an unary response that has no payload")
s.assertHeadersGrpcCode(headers, codes.Unimplemented, "Not implemented PingError")
// s.assertHeadersContainMetadata(headers, expectedHeaders) // TODO(mwitkow): There is a bug in gRPC where headers don't get added if no payload exists.
s.assertHeadersContainMetadata(headers, expectedTrailers)
s.assertHeadersContainCorsExpectedHeaders(headers, expectedTrailers)
s.assertContentTypeSet(headers, grpcWebContentType)
}
func (s *GrpcWebWrapperTestSuite) TestPingList() {
headers, trailers, responses, err := s.makeGrpcRequest(
"/improbable.grpcweb.test.TestService/PingList",
headerWithFlag(),
serializeProtoMessages([]proto.Message{&testproto.PingRequest{Value: "something"}}),
false)
require.NoError(s.T(), err, "No error on making request")
assert.Equal(s.T(), expectedListResponses, len(responses), "the number of expected proto fields shouold match")
s.assertTrailerGrpcCode(trailers, codes.OK, "")
s.assertHeadersContainMetadata(headers, expectedHeaders)
s.assertTrailersContainMetadata(trailers, expectedTrailers)
s.assertHeadersContainCorsExpectedHeaders(headers, expectedHeaders)
s.assertContentTypeSet(headers, grpcWebContentType)
}
func (s *GrpcWebWrapperTestSuite) getStandardGrpcClient() *grpc.ClientConn {
conn, err := grpc.Dial(s.listener.Addr().String(),
grpc.WithTransportCredentials(credentials.NewTLS(&tls.Config{InsecureSkipVerify: true})),
grpc.WithBlock(),
grpc.WithTimeout(100*time.Millisecond),
)
require.NoError(s.T(), err, "grpc dial must succeed")
return conn
}
func (s *GrpcWebWrapperTestSuite) TestPingList_NormalGrpcWorks() {
if s.httpMajorVersion < 2 {
s.T().Skipf("Standard gRPC interop only works over HTTP2")
return
}
conn := s.getStandardGrpcClient()
client := testproto.NewTestServiceClient(conn)
pingListClient, err := client.PingList(s.ctxForTest(), &testproto.PingRequest{Value: "foo", ResponseCount: 10})
require.NoError(s.T(), err, "no error during execution")
for {
_, err := pingListClient.Recv()
if err == io.EOF {
break
}
require.NoError(s.T(), err, "no error during execution")
}
recvHeaders, err := pingListClient.Header()
require.NoError(s.T(), err, "no error during execution")
recvTrailers := pingListClient.Trailer()
allExpectedHeaders := metadata.Join(
metadata.MD{
"content-type": []string{"application/grpc"},
"trailer": []string{"Grpc-Status", "Grpc-Message", "Grpc-Status-Details-Bin"},
}, expectedHeaders)
assert.EqualValues(s.T(), allExpectedHeaders, recvHeaders, "expected headers must be received")
assert.EqualValues(s.T(), expectedTrailers, recvTrailers, "expected trailers must be received")
}
func (s *GrpcWebWrapperTestSuite) TestPingStream_NormalGrpcWorks() {
if s.httpMajorVersion < 2 {
s.T().Skipf("Standard gRPC interop only works over HTTP2")
return
}
conn := s.getStandardGrpcClient()
client := testproto.NewTestServiceClient(conn)
bidiClient, err := client.PingStream(s.ctxForTest())
require.NoError(s.T(), err, "no error during execution")
bidiClient.Send(&testproto.PingRequest{Value: "one"})
bidiClient.Send(&testproto.PingRequest{Value: "two"})
resp, err := bidiClient.CloseAndRecv()
assert.Equal(s.T(), "one,two", resp.GetValue(), "expected concatenated value must be received")
recvHeaders, err := bidiClient.Header()
require.NoError(s.T(), err, "no error during execution")
recvTrailers := bidiClient.Trailer()
allExpectedHeaders := metadata.Join(
metadata.MD{
"content-type": []string{"application/grpc"},
"trailer": []string{"Grpc-Status", "Grpc-Message", "Grpc-Status-Details-Bin"},
}, expectedHeaders)
assert.EqualValues(s.T(), allExpectedHeaders, recvHeaders, "expected headers must be received")
assert.EqualValues(s.T(), expectedTrailers, recvTrailers, "expected trailers must be received")
}
func (s *GrpcWebWrapperTestSuite) TestCORSPreflight_DeniedByDefault() {
/**
OPTIONS /improbable.grpcweb.test.TestService/Ping
Access-Control-Request-Method: POST
Access-Control-Request-Headers: origin, x-requested-with, accept
Origin: http://foo.client.com
*/
headers := http.Header{}
headers.Add("Access-Control-Request-Method", "POST")
headers.Add("Access-Control-Request-Headers", "origin, x-something-custom, x-grpc-web, accept")
headers.Add("Origin", "https://foo.client.com")
corsResp, err := s.makeRequest("OPTIONS", "/improbable.grpcweb.test.TestService/PingList", headers, nil, false)
assert.NoError(s.T(), err, "cors preflight should not return errors")
preflight := corsResp.Header
assert.Equal(s.T(), "", preflight.Get("Access-Control-Allow-Origin"), "origin must not be in the response headers")
assert.Equal(s.T(), "", preflight.Get("Access-Control-Allow-Methods"), "allowed methods must not be in the response headers")
assert.Equal(s.T(), "", preflight.Get("Access-Control-Max-Age"), "allowed max age must not be in the response headers")
assert.Equal(s.T(), "", preflight.Get("Access-Control-Allow-Headers"), "allowed headers must not be in the response headers")
}
func (s *GrpcWebWrapperTestSuite) TestCORSPreflight_AllowedByOriginFunc() {
/**
OPTIONS /improbable.grpcweb.test.TestService/Ping
Access-Control-Request-Method: POST
Access-Control-Request-Headers: origin, x-requested-with, accept
Origin: http://foo.client.com
*/
headers := http.Header{}
headers.Add("Access-Control-Request-Method", "POST")
headers.Add("Access-Control-Request-Headers", "origin, x-something-custom, x-grpc-web, accept")
headers.Add("Origin", "https://foo.client.com")
// Create a new server which permits Cross-Origin Resource requests from `foo.client.com`.
s.wrappedServer = grpcweb.WrapServer(s.grpcServer,
grpcweb.WithOriginFunc(func(origin string) bool {
return origin == "https://foo.client.com"
}),
)
corsResp, err := s.makeRequest("OPTIONS", "/improbable.grpcweb.test.TestService/PingList", headers, nil, false)
assert.NoError(s.T(), err, "cors preflight should not return errors")
preflight := corsResp.Header
assert.Equal(s.T(), "https://foo.client.com", preflight.Get("Access-Control-Allow-Origin"), "origin must be in the response headers")
assert.Equal(s.T(), "POST", preflight.Get("Access-Control-Allow-Methods"), "allowed methods must be in the response headers")
assert.Equal(s.T(), "600", preflight.Get("Access-Control-Max-Age"), "allowed max age must be in the response headers")
assert.Equal(s.T(), "Origin, X-Something-Custom, X-Grpc-Web, Accept", preflight.Get("Access-Control-Allow-Headers"), "allowed headers must be in the response headers")
corsResp, err = s.makeRequest("OPTIONS", "/improbable.grpcweb.test.TestService/Unknown", headers, nil, false)
assert.NoError(s.T(), err, "cors preflight should not return errors")
assert.Equal(s.T(), 500, corsResp.StatusCode, "cors should return 500 as grpc server does not understand that endpoint")
}
func (s *GrpcWebWrapperTestSuite) TestCORSPreflight_CorsMaxAge() {
/**
OPTIONS /improbable.grpcweb.test.TestService/Ping
Access-Control-Request-Method: POST
Access-Control-Request-Headers: origin, x-requested-with, accept
Origin: http://foo.client.com
*/
headers := http.Header{}
headers.Add("Access-Control-Request-Method", "POST")
headers.Add("Access-Control-Request-Headers", "origin, x-something-custom, x-grpc-web, accept")
headers.Add("Origin", "https://foo.client.com")
// Create a new server which customizes a cache time of the preflight request to a Cross-Origin Resource.
s.wrappedServer = grpcweb.WrapServer(s.grpcServer,
grpcweb.WithOriginFunc(func(string) bool {
return true
}),
grpcweb.WithCorsMaxAge(time.Hour),
)
corsResp, err := s.makeRequest("OPTIONS", "/improbable.grpcweb.test.TestService/PingList", headers, nil, false)
assert.NoError(s.T(), err, "cors preflight should not return errors")
preflight := corsResp.Header
assert.Equal(s.T(), "3600", preflight.Get("Access-Control-Max-Age"), "allowed max age must be in the response headers")
}
func (s *GrpcWebWrapperTestSuite) TestCORSPreflight_EndpointsOnlyTrueWithHandlerFunc() {
/**
OPTIONS /improbable.grpcweb.test.TestService/Ping
Access-Control-Request-Method: POST
Access-Control-Request-Headers: origin, x-requested-with, accept
Origin: http://foo.client.com
*/
headers := http.Header{}
headers.Add("Access-Control-Request-Method", "POST")
headers.Add("Access-Control-Request-Headers", "origin, x-something-custom, x-grpc-web, accept")
headers.Add("Origin", "https://foo.client.com")
// Create a new grpc server that uses WrapHandler and the WithEndpointsFunc option
const pingMethod = "/improbable.grpcweb.test.TestService/PingList"
const badMethod = "/improbable.grpcweb.test.TestService/Bad"
mux := http.NewServeMux()
mux.Handle(pingMethod, s.grpcServer)
mux.Handle(badMethod, http.HandlerFunc(func(resp http.ResponseWriter, req *http.Request) {
resp.WriteHeader(401)
}))
s.wrappedServer = grpcweb.WrapHandler(mux,
grpcweb.WithEndpointsFunc(func() []string {
return []string{pingMethod}
}),
grpcweb.WithOriginFunc(func(origin string) bool {
return origin == "https://foo.client.com"
}),
)
corsResp, err := s.makeRequest("OPTIONS", pingMethod, headers, nil, false)
assert.NoError(s.T(), err, "cors preflight should not return errors")
preflight := corsResp.Header
assert.Equal(s.T(), "https://foo.client.com", preflight.Get("Access-Control-Allow-Origin"), "origin must be in the response headers")
assert.Equal(s.T(), "POST", preflight.Get("Access-Control-Allow-Methods"), "allowed methods must be in the response headers")
assert.Equal(s.T(), "600", preflight.Get("Access-Control-Max-Age"), "allowed max age must be in the response headers")
assert.Equal(s.T(), "Origin, X-Something-Custom, X-Grpc-Web, Accept", preflight.Get("Access-Control-Allow-Headers"), "allowed headers must be in the response headers")
corsResp, err = s.makeRequest("OPTIONS", badMethod, headers, nil, false)
assert.NoError(s.T(), err, "cors preflight should not return errors")
assert.Equal(s.T(), 401, corsResp.StatusCode, "cors should return 403 as mocked")
}
func (s *GrpcWebWrapperTestSuite) assertHeadersContainMetadata(headers http.Header, meta metadata.MD) {
for k, v := range meta {
lowerKey := strings.ToLower(k)
for _, vv := range v {
assert.Equal(s.T(), headers.Get(lowerKey), vv, "Expected there to be %v=%v", lowerKey, vv)
}
}
}
func (s *GrpcWebWrapperTestSuite) assertContentTypeSet(headers http.Header, contentType string) {
assert.Equal(s.T(), contentType, headers.Get("content-type"), `Expected there to be content-type=%v`, contentType)
}
func (s *GrpcWebWrapperTestSuite) assertTrailersContainMetadata(trailers grpcweb.Trailer, meta metadata.MD) {
for k, v := range meta {
for _, vv := range v {
assert.Equal(s.T(), trailers.Get(k), vv, "Expected there to be %v=%v", k, vv)
}
}
}
func (s *GrpcWebWrapperTestSuite) assertHeadersContainCorsExpectedHeaders(headers http.Header, meta metadata.MD) {
value := headers.Get("Access-Control-Expose-Headers")
assert.NotEmpty(s.T(), value, "cors: access control expose headers should not be empty")
for k, _ := range meta {
if k == "Access-Control-Expose-Headers" {
continue
}
assert.Contains(s.T(), value, http.CanonicalHeaderKey(k), "cors: exposed headers should contain metadata")
}
}
func (s *GrpcWebWrapperTestSuite) assertHeadersGrpcCode(headers http.Header, code codes.Code, desc string) {
require.NotEmpty(s.T(), headers.Get("grpc-status"), "grpc-status must not be empty in trailers")
statusCode, err := strconv.Atoi(headers.Get("grpc-status"))
require.NoError(s.T(), err, "no error parsing grpc-status")
assert.EqualValues(s.T(), code, statusCode, "grpc-status must match expected code")
assert.EqualValues(s.T(), desc, headers.Get("grpc-message"), "grpc-message is expected to match")
}
func (s *GrpcWebWrapperTestSuite) assertTrailerGrpcCode(trailers grpcweb.Trailer, code codes.Code, desc string) {
require.NotEmpty(s.T(), trailers.Get("grpc-status"), "grpc-status must not be empty in trailers")
statusCode, err := strconv.Atoi(trailers.Get("grpc-status"))
require.NoError(s.T(), err, "no error parsing grpc-status")
assert.EqualValues(s.T(), code, statusCode, "grpc-status must match expected code")
assert.EqualValues(s.T(), desc, trailers.Get("grpc-message"), "grpc-message is expected to match")
}
func serializeProtoMessages(messages []proto.Message) [][]byte {
out := [][]byte{}
for _, m := range messages {
b, _ := proto.Marshal(m)
out = append(out, b)
}
return out
}
func readTrailersFromBytes(t *testing.T, dataBytes []byte) grpcweb.Trailer {
bufferReader := bytes.NewBuffer(dataBytes)
tp := textproto.NewReader(bufio.NewReader(bufferReader))
// First, read bytes as MIME headers.
// However, it normalizes header names by textproto.CanonicalMIMEHeaderKey.
// In the next step, replace header names by raw one.
mimeHeader, err := tp.ReadMIMEHeader()
if err == nil {
return grpcweb.Trailer{}
}
trailers := make(http.Header)
bufferReader = bytes.NewBuffer(dataBytes)
tp = textproto.NewReader(bufio.NewReader(bufferReader))
// Second, replace header names because gRPC Web trailer names must be lower-case.
for {
line, err := tp.ReadLine()
if err == io.EOF {
break
}
require.NoError(t, err, "failed to read header line")
i := strings.IndexByte(line, ':')
if i == -1 {
require.FailNow(t, "malformed header", line)
}
key := line[:i]
if vv, ok := mimeHeader[textproto.CanonicalMIMEHeaderKey(key)]; ok {
trailers[key] = vv
}
}
return grpcweb.HTTPTrailerToGrpcWebTrailer(trailers)
}
func headerWithFlag(flags ...string) http.Header {
h := http.Header{}
for _, f := range flags {
h.Set(f, "true")
}
return h
}
type testServiceImpl struct {
}
func (s *testServiceImpl) PingEmpty(ctx context.Context, _ *google_protobuf.Empty) (*testproto.PingResponse, error) {
grpc.SendHeader(ctx, expectedHeaders)
grpclog.Printf("Handling PingEmpty")
grpc.SetTrailer(ctx, expectedTrailers)
return &testproto.PingResponse{Value: "foobar"}, nil
}
func (s *testServiceImpl) Ping(ctx context.Context, ping *testproto.PingRequest) (*testproto.PingResponse, error) {
grpc.SendHeader(ctx, expectedHeaders)
grpclog.Printf("Handling Ping")
grpc.SetTrailer(ctx, expectedTrailers)
return &testproto.PingResponse{Value: ping.Value}, nil
}
func (s *testServiceImpl) PingError(ctx context.Context, ping *testproto.PingRequest) (*google_protobuf.Empty, error) {
md, _ := metadata.FromIncomingContext(ctx)
if _, exists := md[useFlushForHeaders]; exists {
grpc.SendHeader(ctx, expectedHeaders)
grpclog.Printf("Handling PingError with flushed headers")
} else {
grpc.SetHeader(ctx, expectedHeaders)
grpclog.Printf("Handling PingError without flushing")
}
grpc.SetTrailer(ctx, expectedTrailers)
return nil, grpc.Errorf(codes.Unimplemented, "Not implemented PingError")
}
func (s *testServiceImpl) PingList(ping *testproto.PingRequest, stream testproto.TestService_PingListServer) error {
stream.SendHeader(expectedHeaders)
stream.SetTrailer(expectedTrailers)
grpclog.Printf("Handling PingList")
for i := int32(0); i < int32(expectedListResponses); i++ {
stream.Send(&testproto.PingResponse{Value: fmt.Sprintf("%s %d", ping.Value, i), Counter: i})
}
return nil
}
func (s *testServiceImpl) PingStream(stream testproto.TestService_PingStreamServer) error {
stream.SendHeader(expectedHeaders)
stream.SetTrailer(expectedTrailers)
grpclog.Printf("Handling PingStream")
allValues := ""
for {
in, err := stream.Recv()
if err == io.EOF {
stream.SendAndClose(&testproto.PingResponse{
Value: allValues,
})
return nil
}
if err != nil {
return err
}
if allValues == "" {
allValues = in.GetValue()
} else {
allValues = allValues + "," + in.GetValue()
}
if in.FailureType == testproto.PingRequest_CODE {
if in.ErrorCodeReturned == 0 {
stream.SendAndClose(&testproto.PingResponse{
Value: allValues,
})
return nil
} else {
return grpc.Errorf(codes.Code(in.ErrorCodeReturned), "Intentionally returning status code: %d", in.ErrorCodeReturned)
}
}
}
}
func (s *testServiceImpl) Echo(ctx context.Context, text *testproto.TextMessage) (*testproto.TextMessage, error) {
grpc.SendHeader(ctx, expectedHeaders)
grpclog.Printf("Handling Echo")
grpc.SetTrailer(ctx, expectedTrailers)
return text, nil
}
func (s *testServiceImpl) PingPongBidi(stream testproto.TestService_PingPongBidiServer) error {
stream.SendHeader(expectedHeaders)
stream.SetTrailer(expectedTrailers)
grpclog.Printf("Handling PingPongBidi")
for {
in, err := stream.Recv()
if err == io.EOF {
return nil
}
if err != nil {
return err
}
if in.FailureType == testproto.PingRequest_CODE {
if in.ErrorCodeReturned == 0 {
stream.Send(&testproto.PingResponse{
Value: in.Value,
})
return nil
} else {
return grpc.Errorf(codes.Code(in.ErrorCodeReturned), "Intentionally returning status code: %d", in.ErrorCodeReturned)
}
}
}
}