14 "google.golang.org/grpc/codes"
15 "google.golang.org/grpc/grpclog"
16 "google.golang.org/grpc/metadata"
17 "google.golang.org/grpc/status"
20 // MetadataHeaderPrefix is the http prefix that represents custom metadata
21 // parameters to or from a gRPC call.
22 const MetadataHeaderPrefix = "Grpc-Metadata-"
24 // MetadataPrefix is prepended to permanent HTTP header keys (as specified
25 // by the IANA) when added to the gRPC context.
26 const MetadataPrefix = "grpcgateway-"
28 // MetadataTrailerPrefix is prepended to gRPC metadata as it is converted to
29 // HTTP headers in a response handled by grpc-gateway
30 const MetadataTrailerPrefix = "Grpc-Trailer-"
32 const metadataGrpcTimeout = "Grpc-Timeout"
33 const metadataHeaderBinarySuffix = "-Bin"
35 const xForwardedFor = "X-Forwarded-For"
36 const xForwardedHost = "X-Forwarded-Host"
39 // DefaultContextTimeout is used for gRPC call context.WithTimeout whenever a Grpc-Timeout inbound
40 // header isn't present. If the value is 0 the sent `context` will not have a timeout.
41 DefaultContextTimeout = 0 * time.Second
44 func decodeBinHeader(v string) ([]byte, error) {
46 // Input was padded, or padding was not necessary.
47 return base64.StdEncoding.DecodeString(v)
49 return base64.RawStdEncoding.DecodeString(v)
53 AnnotateContext adds context information such as metadata from the request.
55 At a minimum, the RemoteAddr is included in the fashion of "X-Forwarded-For",
56 except that the forwarded destination is not another HTTP service but rather
59 func AnnotateContext(ctx context.Context, mux *ServeMux, req *http.Request) (context.Context, error) {
61 timeout := DefaultContextTimeout
62 if tm := req.Header.Get(metadataGrpcTimeout); tm != "" {
64 timeout, err = timeoutDecode(tm)
66 return nil, status.Errorf(codes.InvalidArgument, "invalid grpc-timeout: %s", tm)
70 for key, vals := range req.Header {
71 for _, val := range vals {
72 key = textproto.CanonicalMIMEHeaderKey(key)
73 // For backwards-compatibility, pass through 'authorization' header with no prefix.
74 if key == "Authorization" {
75 pairs = append(pairs, "authorization", val)
77 if h, ok := mux.incomingHeaderMatcher(key); ok {
78 // Handles "-bin" metadata in grpc, since grpc will do another base64
79 // encode before sending to server, we need to decode it first.
80 if strings.HasSuffix(key, metadataHeaderBinarySuffix) {
81 b, err := decodeBinHeader(val)
83 return nil, status.Errorf(codes.InvalidArgument, "invalid binary header %s: %s", key, err)
88 pairs = append(pairs, h, val)
92 if host := req.Header.Get(xForwardedHost); host != "" {
93 pairs = append(pairs, strings.ToLower(xForwardedHost), host)
94 } else if req.Host != "" {
95 pairs = append(pairs, strings.ToLower(xForwardedHost), req.Host)
98 if addr := req.RemoteAddr; addr != "" {
99 if remoteIP, _, err := net.SplitHostPort(addr); err == nil {
100 if fwd := req.Header.Get(xForwardedFor); fwd == "" {
101 pairs = append(pairs, strings.ToLower(xForwardedFor), remoteIP)
103 pairs = append(pairs, strings.ToLower(xForwardedFor), fmt.Sprintf("%s, %s", fwd, remoteIP))
106 grpclog.Infof("invalid remote addr: %s", addr)
111 ctx, _ = context.WithTimeout(ctx, timeout)
116 md := metadata.Pairs(pairs...)
117 for _, mda := range mux.metadataAnnotators {
118 md = metadata.Join(md, mda(ctx, req))
120 return metadata.NewOutgoingContext(ctx, md), nil
123 // ServerMetadata consists of metadata sent from gRPC server.
124 type ServerMetadata struct {
126 TrailerMD metadata.MD
129 type serverMetadataKey struct{}
131 // NewServerMetadataContext creates a new context with ServerMetadata
132 func NewServerMetadataContext(ctx context.Context, md ServerMetadata) context.Context {
133 return context.WithValue(ctx, serverMetadataKey{}, md)
136 // ServerMetadataFromContext returns the ServerMetadata in ctx
137 func ServerMetadataFromContext(ctx context.Context) (md ServerMetadata, ok bool) {
138 md, ok = ctx.Value(serverMetadataKey{}).(ServerMetadata)
142 func timeoutDecode(s string) (time.Duration, error) {
145 return 0, fmt.Errorf("timeout string is too short: %q", s)
147 d, ok := timeoutUnitToDuration(s[size-1])
149 return 0, fmt.Errorf("timeout unit is not recognized: %q", s)
151 t, err := strconv.ParseInt(s[:size-1], 10, 64)
155 return d * time.Duration(t), nil
158 func timeoutUnitToDuration(u uint8) (d time.Duration, ok bool) {
161 return time.Hour, true
163 return time.Minute, true
165 return time.Second, true
167 return time.Millisecond, true
169 return time.Microsecond, true
171 return time.Nanosecond, true
177 // isPermanentHTTPHeader checks whether hdr belongs to the list of
178 // permenant request headers maintained by IANA.
179 // http://www.iana.org/assignments/message-headers/message-headers.xml
180 func isPermanentHTTPHeader(hdr string) bool {
198 "If-Schedule-Tag-Match",
199 "If-Unmodified-Since",