-
Notifications
You must be signed in to change notification settings - Fork 121
/
metadata.go
105 lines (84 loc) · 2.16 KB
/
metadata.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
// Copyright 2021-2024 Zenauth Ltd.
// SPDX-License-Identifier: Apache-2.0
package audit
import (
"context"
"fmt"
auditv1 "github.com/cerbos/cerbos/api/genpb/cerbos/audit/v1"
"google.golang.org/grpc/metadata"
)
var alwaysExcludeMetadataKeys = map[string]struct{}{
"authorization": {},
"grpc-trace-bin": {},
}
type MetadataExtractor func(context.Context) map[string]*auditv1.MetaValues
func NewMetadataExtractor() (MetadataExtractor, error) {
conf, err := GetConf()
if err != nil {
return nil, fmt.Errorf("failed to read audit conf: %w", err)
}
return NewMetadataExtractorFromConf(conf), nil
}
func NewMetadataExtractorFromConf(conf *Conf) MetadataExtractor {
if len(conf.ExcludeMetadataKeys) == 0 && len(conf.IncludeMetadataKeys) == 0 {
return func(_ context.Context) map[string]*auditv1.MetaValues {
return nil
}
}
exclude := sliceToLookupMap(conf.ExcludeMetadataKeys)
include := sliceToLookupMap(conf.IncludeMetadataKeys)
var shouldInclude func(string) bool
switch {
case len(exclude) > 0 && len(include) == 0:
shouldInclude = func(k string) bool {
if _, ok := alwaysExcludeMetadataKeys[k]; ok {
return false
}
_, ok := exclude[k]
return !ok
}
case len(exclude) == 0 && len(include) > 0:
shouldInclude = func(k string) bool {
if _, ok := alwaysExcludeMetadataKeys[k]; ok {
return false
}
_, ok := include[k]
return ok
}
default:
shouldInclude = func(k string) bool {
if _, ok := alwaysExcludeMetadataKeys[k]; ok {
return false
}
if _, ok := exclude[k]; ok {
return false
}
_, ok := include[k]
return ok
}
}
return func(ctx context.Context) map[string]*auditv1.MetaValues {
md, ok := metadata.FromIncomingContext(ctx)
if !ok || len(md) == 0 {
return nil
}
extracted := make(map[string]*auditv1.MetaValues, len(md))
for key, values := range md {
if !shouldInclude(key) {
continue
}
extracted[key] = &auditv1.MetaValues{Values: values}
}
if len(extracted) == 0 {
return nil
}
return extracted
}
}
func sliceToLookupMap(slice []string) map[string]struct{} {
m := make(map[string]struct{})
for _, k := range slice {
m[k] = struct{}{}
}
return m
}