forked from heroiclabs/nakama
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapi.go
596 lines (546 loc) · 22.8 KB
/
api.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
// Copyright 2018 The Nakama Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package server
import (
"compress/flate"
"compress/gzip"
"context"
"crypto"
"crypto/tls"
"crypto/x509"
"database/sql"
"encoding/base64"
"fmt"
"math"
"net"
"net/http"
"strings"
"time"
"github.com/gofrs/uuid/v5"
jwt "github.com/golang-jwt/jwt/v4"
"github.com/gorilla/handlers"
"github.com/gorilla/mux"
grpcgw "github.com/grpc-ecosystem/grpc-gateway/v2/runtime"
"github.com/heroiclabs/nakama-common/api"
"github.com/heroiclabs/nakama/v3/apigrpc"
"github.com/heroiclabs/nakama/v3/social"
"go.uber.org/zap"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/credentials"
"google.golang.org/grpc/credentials/insecure"
_ "google.golang.org/grpc/encoding/gzip" // enable gzip compression on server for grpc
"google.golang.org/grpc/metadata"
"google.golang.org/grpc/peer"
"google.golang.org/grpc/status"
"google.golang.org/protobuf/encoding/protojson"
"google.golang.org/protobuf/types/known/emptypb"
)
// Used as part of JSON input validation.
const byteBracket byte = '{'
// Keys used for storing/retrieving user information in the context of a request after authentication.
type ctxUserIDKey struct{}
type ctxUsernameKey struct{}
type ctxVarsKey struct{}
type ctxExpiryKey struct{}
type ctxFullMethodKey struct{}
type ApiServer struct {
apigrpc.UnimplementedNakamaServer
logger *zap.Logger
db *sql.DB
config Config
version string
socialClient *social.Client
storageIndex StorageIndex
leaderboardCache LeaderboardCache
leaderboardRankCache LeaderboardRankCache
sessionCache SessionCache
sessionRegistry SessionRegistry
statusRegistry StatusRegistry
matchRegistry MatchRegistry
tracker Tracker
router MessageRouter
streamManager StreamManager
metrics Metrics
runtime *Runtime
grpcServer *grpc.Server
grpcGatewayServer *http.Server
}
func StartApiServer(logger *zap.Logger, startupLogger *zap.Logger, db *sql.DB, protojsonMarshaler *protojson.MarshalOptions, protojsonUnmarshaler *protojson.UnmarshalOptions, config Config, version string, socialClient *social.Client, storageIndex StorageIndex, leaderboardCache LeaderboardCache, leaderboardRankCache LeaderboardRankCache, sessionRegistry SessionRegistry, sessionCache SessionCache, statusRegistry StatusRegistry, matchRegistry MatchRegistry, matchmaker Matchmaker, tracker Tracker, router MessageRouter, streamManager StreamManager, metrics Metrics, pipeline *Pipeline, runtime *Runtime) *ApiServer {
var gatewayContextTimeoutMs string
if config.GetSocket().IdleTimeoutMs > 500 {
// Ensure the GRPC Gateway timeout is just under the idle timeout (if possible) to ensure it has priority.
grpcgw.DefaultContextTimeout = time.Duration(config.GetSocket().IdleTimeoutMs-500) * time.Millisecond
gatewayContextTimeoutMs = fmt.Sprintf("%vm", config.GetSocket().IdleTimeoutMs-500)
} else {
grpcgw.DefaultContextTimeout = time.Duration(config.GetSocket().IdleTimeoutMs) * time.Millisecond
gatewayContextTimeoutMs = fmt.Sprintf("%vm", config.GetSocket().IdleTimeoutMs)
}
serverOpts := []grpc.ServerOption{
grpc.StatsHandler(&MetricsGrpcHandler{MetricsFn: metrics.Api}),
grpc.MaxRecvMsgSize(int(config.GetSocket().MaxRequestSizeBytes)),
grpc.UnaryInterceptor(func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (interface{}, error) {
ctx, err := securityInterceptorFunc(logger, config, sessionCache, ctx, req, info)
if err != nil {
return nil, err
}
return handler(ctx, req)
}),
}
if config.GetSocket().TLSCert != nil {
serverOpts = append(serverOpts, grpc.Creds(credentials.NewServerTLSFromCert(&config.GetSocket().TLSCert[0])))
}
grpcServer := grpc.NewServer(serverOpts...)
s := &ApiServer{
logger: logger,
db: db,
config: config,
version: version,
socialClient: socialClient,
leaderboardCache: leaderboardCache,
leaderboardRankCache: leaderboardRankCache,
storageIndex: storageIndex,
sessionCache: sessionCache,
sessionRegistry: sessionRegistry,
statusRegistry: statusRegistry,
matchRegistry: matchRegistry,
tracker: tracker,
router: router,
streamManager: streamManager,
metrics: metrics,
runtime: runtime,
grpcServer: grpcServer,
}
// Register and start GRPC server.
apigrpc.RegisterNakamaServer(grpcServer, s)
startupLogger.Info("Starting API server for gRPC requests", zap.Int("port", config.GetSocket().Port-1))
go func() {
listener, err := net.Listen("tcp", fmt.Sprintf("%v:%d", config.GetSocket().Address, config.GetSocket().Port-1))
if err != nil {
startupLogger.Fatal("API server listener failed to start", zap.Error(err))
}
if err := grpcServer.Serve(listener); err != nil {
startupLogger.Fatal("API server listener failed", zap.Error(err))
}
}()
// Register and start GRPC Gateway server.
// Should start after GRPC server itself because RegisterNakamaHandlerFromEndpoint below tries to dial GRPC.
ctx := context.Background()
grpcGateway := grpcgw.NewServeMux(
grpcgw.WithMetadata(func(ctx context.Context, r *http.Request) metadata.MD {
// For RPC GET operations pass through any custom query parameters.
if r.Method != "GET" || !strings.HasPrefix(r.URL.Path, "/v2/rpc/") {
return metadata.MD{}
}
q := r.URL.Query()
p := make(map[string][]string, len(q))
for k, vs := range q {
if k == "http_key" {
// Skip Nakama's own query params, only process custom ones.
continue
}
p["q_"+k] = vs
}
return metadata.MD(p)
}),
grpcgw.WithMarshalerOption(grpcgw.MIMEWildcard, &grpcgw.HTTPBodyMarshaler{
Marshaler: &grpcgw.JSONPb{
MarshalOptions: protojson.MarshalOptions{
UseProtoNames: true,
UseEnumNumbers: true,
},
UnmarshalOptions: protojson.UnmarshalOptions{
DiscardUnknown: true,
},
},
}),
)
dialAddr := fmt.Sprintf("127.0.0.1:%d", config.GetSocket().Port-1)
if config.GetSocket().Address != "" {
dialAddr = fmt.Sprintf("%v:%d", config.GetSocket().Address, config.GetSocket().Port-1)
}
dialOpts := []grpc.DialOption{
grpc.WithDefaultCallOptions(
grpc.MaxCallSendMsgSize(int(config.GetSocket().MaxRequestSizeBytes)),
grpc.MaxCallRecvMsgSize(math.MaxInt32),
),
//grpc.WithStatsHandler(&ocgrpc.ClientHandler{}),
}
if config.GetSocket().TLSCert != nil {
// GRPC-Gateway only ever dials 127.0.0.1 so we can be lenient on server certificate validation.
certPool := x509.NewCertPool()
if !certPool.AppendCertsFromPEM(config.GetSocket().CertPEMBlock) {
startupLogger.Fatal("Failed to load PEM certificate from socket SSL certificate file")
}
cert := credentials.NewTLS(&tls.Config{RootCAs: certPool, InsecureSkipVerify: true})
dialOpts = append(dialOpts, grpc.WithTransportCredentials(cert))
} else {
dialOpts = append(dialOpts, grpc.WithTransportCredentials(insecure.NewCredentials()))
}
if err := apigrpc.RegisterNakamaHandlerFromEndpoint(ctx, grpcGateway, dialAddr, dialOpts); err != nil {
startupLogger.Fatal("API server gateway registration failed", zap.Error(err))
}
//if err := apigrpc.RegisterNakamaHandlerServer(ctx, grpcGateway, s); err != nil {
// startupLogger.Fatal("API server gateway registration failed", zap.Error(err))
//}
grpcGatewayRouter := mux.NewRouter()
// Special case routes. Do NOT enable compression on WebSocket route, it results in "http: response.Write on hijacked connection" errors.
grpcGatewayRouter.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(200) }).Methods("GET")
grpcGatewayRouter.HandleFunc("/ws", NewSocketWsAcceptor(logger, config, sessionRegistry, sessionCache, statusRegistry, matchmaker, tracker, metrics, runtime, protojsonMarshaler, protojsonUnmarshaler, pipeline)).Methods("GET")
// Another nested router to hijack RPC requests bound for GRPC Gateway.
grpcGatewayMux := mux.NewRouter()
grpcGatewayMux.HandleFunc("/v2/rpc/{id:.*}", s.RpcFuncHttp).Methods("GET", "POST")
grpcGatewayMux.NewRoute().Handler(grpcGateway)
// Enable stats recording on all request paths except:
// "/" is not tracked at all.
// "/ws" implements its own separate tracking.
//handlerWithStats := &ochttp.Handler{
// Handler: grpcGatewayMux,
// IsPublicEndpoint: true,
//}
// Default to passing request to GRPC Gateway.
// Enable max size check on requests coming arriving the gateway.
// Enable compression on responses sent by the gateway.
// Enable decompression on requests received by the gateway.
handlerWithDecompressRequest := decompressHandler(logger, grpcGatewayMux)
handlerWithCompressResponse := handlers.CompressHandler(handlerWithDecompressRequest)
maxMessageSizeBytes := config.GetSocket().MaxRequestSizeBytes
handlerWithMaxBody := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Check max body size before decompressing incoming request body.
r.Body = http.MaxBytesReader(w, r.Body, maxMessageSizeBytes)
handlerWithCompressResponse.ServeHTTP(w, r)
})
grpcGatewayRouter.NewRoute().HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Ensure some request headers have required values.
// Override any value set by the client if needed.
r.Header.Set("Grpc-Timeout", gatewayContextTimeoutMs)
// Add constant response headers.
w.Header().Add("Cache-Control", "no-store, no-cache, must-revalidate")
// Allow GRPC Gateway to handle the request.
handlerWithMaxBody.ServeHTTP(w, r)
})
// Enable CORS on all requests.
CORSHeaders := handlers.AllowedHeaders([]string{"Authorization", "Content-Type", "User-Agent"})
CORSOrigins := handlers.AllowedOrigins([]string{"*"})
CORSMethods := handlers.AllowedMethods([]string{"GET", "HEAD", "POST", "PUT", "DELETE"})
handlerWithCORS := handlers.CORS(CORSHeaders, CORSOrigins, CORSMethods)(grpcGatewayRouter)
// Enable configured response headers, if any are set. Do not override values that may have been set by server processing.
optionalResponseHeaderHandler := handlerWithCORS
if headers := config.GetSocket().Headers; len(headers) > 0 {
optionalResponseHeaderHandler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Preemptively set custom response headers. Further processing will override them if needed for proper functionality.
wHeaders := w.Header()
for key, value := range headers {
if wHeaders.Get(key) == "" {
wHeaders.Set(key, value)
}
}
// Allow core server processing to handle the request.
handlerWithCORS.ServeHTTP(w, r)
})
}
// Set up and start GRPC Gateway server.
s.grpcGatewayServer = &http.Server{
ReadTimeout: time.Millisecond * time.Duration(int64(config.GetSocket().ReadTimeoutMs)),
WriteTimeout: time.Millisecond * time.Duration(int64(config.GetSocket().WriteTimeoutMs)),
IdleTimeout: time.Millisecond * time.Duration(int64(config.GetSocket().IdleTimeoutMs)),
MaxHeaderBytes: 5120,
Handler: optionalResponseHeaderHandler,
}
if config.GetSocket().TLSCert != nil {
s.grpcGatewayServer.TLSConfig = &tls.Config{Certificates: config.GetSocket().TLSCert}
}
startupLogger.Info("Starting API server gateway for HTTP requests", zap.Int("port", config.GetSocket().Port))
go func() {
listener, err := net.Listen(config.GetSocket().Protocol, fmt.Sprintf("%v:%d", config.GetSocket().Address, config.GetSocket().Port))
if err != nil {
startupLogger.Fatal("API server gateway listener failed to start", zap.Error(err))
}
if config.GetSocket().TLSCert != nil {
if err := s.grpcGatewayServer.ServeTLS(listener, "", ""); err != nil && err != http.ErrServerClosed {
startupLogger.Fatal("API server gateway listener failed", zap.Error(err))
}
} else {
if err := s.grpcGatewayServer.Serve(listener); err != nil && err != http.ErrServerClosed {
startupLogger.Fatal("API server gateway listener failed", zap.Error(err))
}
}
}()
return s
}
func (s *ApiServer) Stop() {
// 1. Stop GRPC Gateway server first as it sits above GRPC server. This also closes the underlying listener.
if err := s.grpcGatewayServer.Shutdown(context.Background()); err != nil {
s.logger.Error("API server gateway listener shutdown failed", zap.Error(err))
}
// 2. Stop GRPC server. This also closes the underlying listener.
s.grpcServer.GracefulStop()
}
func (s *ApiServer) Healthcheck(ctx context.Context, in *emptypb.Empty) (*emptypb.Empty, error) {
return &emptypb.Empty{}, nil
}
func securityInterceptorFunc(logger *zap.Logger, config Config, sessionCache SessionCache, ctx context.Context, req interface{}, info *grpc.UnaryServerInfo) (context.Context, error) {
switch info.FullMethod {
case "/nakama.api.Nakama/Healthcheck":
// Healthcheck has no security.
return ctx, nil
case "/nakama.api.Nakama/SessionRefresh":
fallthrough
case "/nakama.api.Nakama/AuthenticateApple":
fallthrough
case "/nakama.api.Nakama/AuthenticateCustom":
fallthrough
case "/nakama.api.Nakama/AuthenticateDevice":
fallthrough
case "/nakama.api.Nakama/AuthenticateEmail":
fallthrough
case "/nakama.api.Nakama/AuthenticateFacebook":
fallthrough
case "/nakama.api.Nakama/AuthenticateFacebookInstantGame":
fallthrough
case "/nakama.api.Nakama/AuthenticateGameCenter":
fallthrough
case "/nakama.api.Nakama/AuthenticateGoogle":
fallthrough
case "/nakama.api.Nakama/AuthenticateSteam":
// Session refresh and authentication functions only require server key.
md, ok := metadata.FromIncomingContext(ctx)
if !ok {
logger.Error("Cannot extract metadata from incoming context")
return nil, status.Error(codes.FailedPrecondition, "Cannot extract metadata from incoming context")
}
auth, ok := md["authorization"]
if !ok {
auth, ok = md["grpcgateway-authorization"]
}
if !ok {
// Neither "authorization" nor "grpc-authorization" were supplied.
return nil, status.Error(codes.Unauthenticated, "Server key required")
}
if len(auth) != 1 {
// Value of "authorization" or "grpc-authorization" was empty or repeated.
return nil, status.Error(codes.Unauthenticated, "Server key required")
}
username, _, ok := parseBasicAuth(auth[0])
if !ok {
// Value of "authorization" or "grpc-authorization" was malformed.
return nil, status.Error(codes.Unauthenticated, "Server key invalid")
}
if username != config.GetSocket().ServerKey {
// Value of "authorization" or "grpc-authorization" username component did not match server key.
return nil, status.Error(codes.Unauthenticated, "Server key invalid")
}
case "/nakama.api.Nakama/RpcFunc":
// RPC allows full user authentication or HTTP key authentication.
md, ok := metadata.FromIncomingContext(ctx)
if !ok {
logger.Error("Cannot extract metadata from incoming context")
return nil, status.Error(codes.FailedPrecondition, "Cannot extract metadata from incoming context")
}
auth, ok := md["authorization"]
if !ok {
auth, ok = md["grpcgateway-authorization"]
}
if !ok {
// Neither "authorization" nor "grpc-authorization" were supplied. Try to validate HTTP key instead.
in, ok := req.(*api.Rpc)
if !ok {
logger.Error("Cannot extract Rpc from incoming request")
return nil, status.Error(codes.FailedPrecondition, "Auth token or HTTP key required")
}
if in.HttpKey == "" {
// HTTP key not present.
return nil, status.Error(codes.Unauthenticated, "Auth token or HTTP key required")
}
if in.HttpKey != config.GetRuntime().HTTPKey {
// Value of HTTP key username component did not match.
return nil, status.Error(codes.Unauthenticated, "HTTP key invalid")
}
return ctx, nil
}
if len(auth) != 1 {
// Value of "authorization" or "grpc-authorization" was empty or repeated.
return nil, status.Error(codes.Unauthenticated, "Auth token invalid")
}
userID, username, vars, exp, tokenId, ok := parseBearerAuth([]byte(config.GetSession().EncryptionKey), auth[0])
if !ok {
// Value of "authorization" or "grpc-authorization" was malformed or expired.
return nil, status.Error(codes.Unauthenticated, "Auth token invalid")
}
if !sessionCache.IsValidSession(userID, exp, tokenId) {
return nil, status.Error(codes.Unauthenticated, "Auth token invalid")
}
ctx = context.WithValue(context.WithValue(context.WithValue(context.WithValue(ctx, ctxUserIDKey{}, userID), ctxUsernameKey{}, username), ctxVarsKey{}, vars), ctxExpiryKey{}, exp)
default:
// Unless explicitly defined above, handlers require full user authentication.
md, ok := metadata.FromIncomingContext(ctx)
if !ok {
logger.Error("Cannot extract metadata from incoming context")
return nil, status.Error(codes.FailedPrecondition, "Cannot extract metadata from incoming context")
}
auth, ok := md["authorization"]
if !ok {
auth, ok = md["grpcgateway-authorization"]
}
if !ok {
// Neither "authorization" nor "grpc-authorization" were supplied.
return nil, status.Error(codes.Unauthenticated, "Auth token required")
}
if len(auth) != 1 {
// Value of "authorization" or "grpc-authorization" was empty or repeated.
return nil, status.Error(codes.Unauthenticated, "Auth token invalid")
}
userID, username, vars, exp, tokenId, ok := parseBearerAuth([]byte(config.GetSession().EncryptionKey), auth[0])
if !ok {
// Value of "authorization" or "grpc-authorization" was malformed or expired.
return nil, status.Error(codes.Unauthenticated, "Auth token invalid")
}
if !sessionCache.IsValidSession(userID, exp, tokenId) {
return nil, status.Error(codes.Unauthenticated, "Auth token invalid")
}
ctx = context.WithValue(context.WithValue(context.WithValue(context.WithValue(ctx, ctxUserIDKey{}, userID), ctxUsernameKey{}, username), ctxVarsKey{}, vars), ctxExpiryKey{}, exp)
}
return context.WithValue(ctx, ctxFullMethodKey{}, info.FullMethod), nil
}
func parseBasicAuth(auth string) (username, password string, ok bool) {
if auth == "" {
return
}
const prefix = "Basic "
if !strings.HasPrefix(auth, prefix) {
return
}
c, err := base64.StdEncoding.DecodeString(auth[len(prefix):])
if err != nil {
return
}
cs := string(c)
s := strings.IndexByte(cs, ':')
if s < 0 {
return
}
return cs[:s], cs[s+1:], true
}
func parseBearerAuth(hmacSecretByte []byte, auth string) (userID uuid.UUID, username string, vars map[string]string, exp int64, tokenId string, ok bool) {
if auth == "" {
return
}
const prefix = "Bearer "
if !strings.HasPrefix(auth, prefix) {
return
}
return parseToken(hmacSecretByte, auth[len(prefix):])
}
func parseToken(hmacSecretByte []byte, tokenString string) (userID uuid.UUID, username string, vars map[string]string, exp int64, tokenId string, ok bool) {
jwtToken, err := jwt.ParseWithClaims(tokenString, &SessionTokenClaims{}, func(token *jwt.Token) (interface{}, error) {
if s, ok := token.Method.(*jwt.SigningMethodHMAC); !ok || s.Hash != crypto.SHA256 {
return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"])
}
return hmacSecretByte, nil
})
if err != nil {
return
}
claims, ok := jwtToken.Claims.(*SessionTokenClaims)
if !ok || !jwtToken.Valid {
return
}
userID, err = uuid.FromString(claims.UserId)
if err != nil {
return
}
return userID, claims.Username, claims.Vars, claims.ExpiresAt, claims.TokenId, true
}
func decompressHandler(logger *zap.Logger, h http.Handler) http.HandlerFunc {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch r.Header.Get("Content-Encoding") {
case "gzip":
gr, err := gzip.NewReader(r.Body)
if err != nil {
logger.Debug("Error processing gzip request body, attempting to read uncompressed", zap.Error(err))
break
}
r.Body = gr
case "deflate":
r.Body = flate.NewReader(r.Body)
default:
// No request compression.
}
h.ServeHTTP(w, r)
})
}
func extractClientAddressFromContext(logger *zap.Logger, ctx context.Context) (string, string) {
var clientAddr string
md, _ := metadata.FromIncomingContext(ctx)
if ips := md.Get("x-forwarded-for"); len(ips) > 0 {
// Look for gRPC-Gateway / LB header.
clientAddr = strings.Split(ips[0], ",")[0]
} else if peerInfo, ok := peer.FromContext(ctx); ok {
// If missing, try to look up gRPC peer info.
clientAddr = peerInfo.Addr.String()
}
return extractClientAddress(logger, clientAddr, ctx, "context")
}
func extractClientAddressFromRequest(logger *zap.Logger, r *http.Request) (string, string) {
var clientAddr string
if ips := r.Header.Get("x-forwarded-for"); len(ips) > 0 {
clientAddr = strings.Split(ips, ",")[0]
} else {
clientAddr = r.RemoteAddr
}
return extractClientAddress(logger, clientAddr, r, "request")
}
func extractClientAddress(logger *zap.Logger, clientAddr string, source interface{}, sourceType string) (string, string) {
var clientIP, clientPort string
if clientAddr != "" {
// It's possible the request metadata had no client address string.
clientAddr = strings.TrimSpace(clientAddr)
if host, port, err := net.SplitHostPort(clientAddr); err == nil {
clientIP = host
clientPort = port
} else if addrErr, ok := err.(*net.AddrError); ok {
switch addrErr.Err {
case "missing port in address":
fallthrough
case "too many colons in address":
clientIP = clientAddr
default:
// Unknown address error, ignore the address.
}
}
// At this point err may still be a non-nil value that's not a *net.AddrError, ignore the address.
}
if clientIP == "" {
if r, isRequest := source.(*http.Request); isRequest {
source = map[string]interface{}{"headers": r.Header, "remote_addr": r.RemoteAddr}
}
logger.Warn("cannot extract client address", zap.String("address_source_type", sourceType), zap.Any("address_source", source))
}
return clientIP, clientPort
}
func traceApiBefore(ctx context.Context, logger *zap.Logger, metrics Metrics, fullMethodName string, fn func(clientIP, clientPort string) error) error {
clientIP, clientPort := extractClientAddressFromContext(logger, ctx)
start := time.Now()
// Execute the before hook itself.
err := fn(clientIP, clientPort)
metrics.ApiBefore(fullMethodName, time.Since(start), err != nil)
return err
}
func traceApiAfter(ctx context.Context, logger *zap.Logger, metrics Metrics, fullMethodName string, fn func(clientIP, clientPort string) error) {
clientIP, clientPort := extractClientAddressFromContext(logger, ctx)
start := time.Now()
// Execute the after hook itself.
err := fn(clientIP, clientPort)
metrics.ApiAfter(fullMethodName, time.Since(start), err != nil)
}