/
jwt_metrics.go
103 lines (82 loc) · 2.49 KB
/
jwt_metrics.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
package auth
import (
"fmt"
"regexp"
"slices"
"strings"
"github.com/ghodss/yaml"
"github.com/zalando/skipper/filters"
"github.com/zalando/skipper/filters/annotate"
"github.com/zalando/skipper/jwt"
)
type (
jwtMetricsSpec struct{}
jwtMetricsFilter struct {
Issuers []string `json:"issuers,omitempty"`
OptOutAnnotations []string `json:"optOutAnnotations,omitempty"`
}
)
func NewJwtMetrics() filters.Spec {
return &jwtMetricsSpec{}
}
func (s *jwtMetricsSpec) Name() string {
return filters.JwtMetricsName
}
func (s *jwtMetricsSpec) CreateFilter(args []interface{}) (filters.Filter, error) {
f := &jwtMetricsFilter{}
if len(args) == 1 {
if config, ok := args[0].(string); !ok {
return nil, fmt.Errorf("requires single string argument")
} else if err := yaml.Unmarshal([]byte(config), f); err != nil {
return nil, fmt.Errorf("failed to parse configuration")
}
} else if len(args) > 1 {
return nil, fmt.Errorf("requires single string argument")
}
return f, nil
}
func (f *jwtMetricsFilter) Request(ctx filters.FilterContext) {}
func (f *jwtMetricsFilter) Response(ctx filters.FilterContext) {
if len(f.OptOutAnnotations) > 0 {
annotations := annotate.GetAnnotations(ctx)
for _, annotation := range f.OptOutAnnotations {
if _, ok := annotations[annotation]; ok {
return // opt-out
}
}
}
response := ctx.Response()
if response.StatusCode >= 400 && response.StatusCode < 500 {
return // ignore invalid requests
}
request := ctx.Request()
metrics := ctx.Metrics()
metricsPrefix := fmt.Sprintf("%s.%s.%d.", request.Method, escapeMetricKeySegment(request.Host), response.StatusCode)
ahead := request.Header.Get("Authorization")
if ahead == "" {
metrics.IncCounter(metricsPrefix + "missing-token")
return
}
tv := strings.TrimPrefix(ahead, "Bearer ")
if tv == ahead {
metrics.IncCounter(metricsPrefix + "invalid-token-type")
return
}
if len(f.Issuers) > 0 {
token, err := jwt.Parse(tv)
if err != nil {
metrics.IncCounter(metricsPrefix + "invalid-token")
return
}
// https://datatracker.ietf.org/doc/html/rfc7519#section-4.1.1
if issuer, ok := token.Claims["iss"].(string); !ok {
metrics.IncCounter(metricsPrefix + "missing-issuer")
} else if !slices.Contains(f.Issuers, issuer) {
metrics.IncCounter(metricsPrefix + "invalid-issuer")
}
}
}
var escapeMetricKeySegmentPattern = regexp.MustCompile("[^a-zA-Z0-9_]")
func escapeMetricKeySegment(s string) string {
return escapeMetricKeySegmentPattern.ReplaceAllLiteralString(s, "_")
}