-
Notifications
You must be signed in to change notification settings - Fork 125
/
context.go
78 lines (60 loc) · 1.64 KB
/
context.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
// Copyright 2021-2022 Zenauth Ltd.
// SPDX-License-Identifier: Apache-2.0
package audit
import (
"context"
"strings"
grpc_ctxtags "github.com/grpc-ecosystem/go-grpc-middleware/tags"
"google.golang.org/grpc/metadata"
"google.golang.org/grpc/peer"
auditv1 "github.com/cerbos/cerbos/api/genpb/cerbos/audit/v1"
"github.com/cerbos/cerbos/internal/util"
)
const (
delimiter = "|"
grpcGWUserAgentKey = "grpcgateway-user-agent"
userAgentKey = "user-agent"
xffKey = "x-forwarded-for"
callIDTagKey = "call_id"
)
type callIDCtxKeyType struct{}
var callIDCtxKey = callIDCtxKeyType{}
func NewContextWithCallID(ctx context.Context, id ID) context.Context {
tags := grpc_ctxtags.Extract(ctx)
tagCtx := grpc_ctxtags.SetInContext(ctx, tags.Set(util.AppName, map[string]interface{}{callIDTagKey: id}))
return context.WithValue(tagCtx, callIDCtxKey, id)
}
func CallIDFromContext(ctx context.Context) (ID, bool) {
idVal := ctx.Value(callIDCtxKey)
if idVal == nil {
return "", false
}
id, ok := idVal.(ID)
if !ok {
return "", false
}
return id, true
}
func PeerFromContext(ctx context.Context) *auditv1.Peer {
p, ok := peer.FromContext(ctx)
if !ok {
return nil
}
pp := &auditv1.Peer{Address: p.Addr.String()}
if p.AuthInfo != nil {
pp.AuthInfo = p.AuthInfo.AuthType()
}
md, ok := metadata.FromIncomingContext(ctx)
if !ok {
return pp
}
if ua, ok := md[grpcGWUserAgentKey]; ok {
pp.UserAgent = strings.Join(ua, delimiter)
} else if ua, ok := md[userAgentKey]; ok {
pp.UserAgent = strings.Join(ua, delimiter)
}
if xff, ok := md[xffKey]; ok {
pp.ForwardedFor = strings.Join(xff, delimiter)
}
return pp
}