/
oidc_introspection.go
197 lines (167 loc) · 4.71 KB
/
oidc_introspection.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
package auth
import (
"encoding/json"
"fmt"
"strings"
"sync"
"github.com/tidwall/gjson"
log "github.com/sirupsen/logrus"
"github.com/zalando/skipper/filters"
)
const (
// Deprecated, use filters.OidcClaimsQueryName instead
OidcClaimsQueryName = filters.OidcClaimsQueryName
oidcClaimsCacheKey = "oidcclaimscachekey"
)
var gjsonModifierMutex = sync.RWMutex{}
type (
oidcIntrospectionSpec struct {
typ roleCheckType
}
oidcIntrospectionFilter struct {
typ roleCheckType
paths []pathQuery
}
pathQuery struct {
path string
queries []string
}
)
func NewOIDCQueryClaimsFilter() filters.Spec {
return &oidcIntrospectionSpec{
typ: checkOIDCQueryClaims,
}
}
func (spec *oidcIntrospectionSpec) Name() string {
switch spec.typ {
case checkOIDCQueryClaims:
return filters.OidcClaimsQueryName
}
return AuthUnknown
}
func (spec *oidcIntrospectionSpec) CreateFilter(args []interface{}) (filters.Filter, error) {
sargs, err := getStrings(args)
if err != nil {
return nil, err
}
if len(sargs) == 0 {
return nil, filters.ErrInvalidFilterParameters
}
filter := &oidcIntrospectionFilter{typ: spec.typ}
switch filter.typ {
case checkOIDCQueryClaims:
for _, arg := range sargs {
path, queries, found := strings.Cut(arg, ":")
if !found || path == "" {
return nil, fmt.Errorf("%v: malformatted filter arg %s", filters.ErrInvalidFilterParameters, arg)
}
pq := pathQuery{path: path}
for _, query := range splitQueries(queries) {
if query == "" {
return nil, fmt.Errorf("%v: %s", errUnsupportedClaimSpecified, arg)
}
pq.queries = append(pq.queries, trimQuotes(query))
}
if len(pq.queries) == 0 {
return nil, fmt.Errorf("%v: %s", errUnsupportedClaimSpecified, arg)
}
filter.paths = append(filter.paths, pq)
}
if len(filter.paths) == 0 {
return nil, fmt.Errorf("%v: no queries could be parsed", errUnsupportedClaimSpecified)
}
default:
return nil, filters.ErrInvalidFilterParameters
}
gjsonModifierMutex.RLock()
// method is not thread safe
modExists := gjson.ModifierExists("_", gjsonThisModifier)
gjsonModifierMutex.RUnlock()
if !modExists {
gjsonModifierMutex.Lock()
// method is not thread safe
gjson.AddModifier("_", gjsonThisModifier)
gjsonModifierMutex.Unlock()
}
return filter, nil
}
func (filter *oidcIntrospectionFilter) String() string {
var str []string
for _, query := range filter.paths {
str = append(str, query.String())
}
return fmt.Sprintf("%s(%s)", filters.OidcClaimsQueryName, strings.Join(str, "; "))
}
func (filter *oidcIntrospectionFilter) Request(ctx filters.FilterContext) {
r := ctx.Request()
token, ok := ctx.StateBag()[oidcClaimsCacheKey].(tokenContainer)
if !ok || &token == (&tokenContainer{}) || len(token.Claims) == 0 {
log.Errorf("Error retrieving %s for OIDC token introspection", oidcClaimsCacheKey)
unauthorized(ctx, "", missingToken, r.Host, oidcClaimsCacheKey+" is unavailable in StateBag")
return
}
switch filter.typ {
case checkOIDCQueryClaims:
if !filter.validateClaimsQuery(r.URL.Path, token.Claims) {
unauthorized(ctx, "", invalidAccess, r.Host, "Path not permitted")
return
}
default:
unauthorized(ctx, fmt.Sprint(filter.typ), invalidClaim, r.Host, "Wrong oidcIntrospectionFilter type")
return
}
sub := token.Claims["sub"].(string)
authorized(ctx, sub)
}
func (filter *oidcIntrospectionFilter) Response(filters.FilterContext) {}
func gjsonThisModifier(json, arg string) string {
return gjson.Get(json, "[@this].#("+arg+")").Raw
}
func (filter *oidcIntrospectionFilter) validateClaimsQuery(reqPath string, gotToken map[string]interface{}) bool {
l := len(filter.paths)
if l == 0 {
return false
}
json, err := json.Marshal(gotToken)
if err != nil || !gjson.ValidBytes(json) {
log.Errorf("Failed to serialize in validateClaimsQuery: %v", err)
return false
}
parsed := gjson.ParseBytes(json)
for _, path := range filter.paths {
if !strings.HasPrefix(reqPath, path.path) {
continue
}
for _, query := range path.queries {
match := parsed.Get(query)
log.Debugf("claim: %s results:%s", query, match.String())
if match.Exists() {
return true
}
}
return false
}
return false
}
func (p pathQuery) String() string {
return fmt.Sprintf("path: '%s*', matching: %s", p.path, strings.Join(p.queries, " ,"))
}
// Splits space-delimited GJSON queries ignoring spaces within quoted strings
func splitQueries(s string) (q []string) {
for _, p := range strings.Split(s, " ") {
if len(q) == 0 || strings.Count(q[len(q)-1], `"`)%2 == 0 {
q = append(q, p)
} else {
q[len(q)-1] = q[len(q)-1] + " " + p
}
}
return
}
func trimQuotes(s string) string {
if len(s) >= 2 {
if c := s[len(s)-1]; s[0] == c && (c == '"' || c == '\'') {
return s[1 : len(s)-1]
}
}
return s
}