-
Notifications
You must be signed in to change notification settings - Fork 14
/
jwt.go
493 lines (426 loc) · 11.5 KB
/
jwt.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
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
package accesscontrol
import (
"context"
"crypto/rsa"
"crypto/x509"
"encoding/pem"
"fmt"
"net/http"
"strings"
"time"
"github.com/dgrijalva/jwt-go/v4"
"github.com/hashicorp/hcl/v2"
acjwt "github.com/avenga/couper/accesscontrol/jwt"
"github.com/avenga/couper/config/request"
"github.com/avenga/couper/errors"
"github.com/avenga/couper/eval"
"github.com/avenga/couper/internal/seetie"
)
const (
Invalid JWTSourceType = iota
Cookie
Header
Value
)
var _ AccessControl = &JWT{}
type (
JWTSourceType uint8
JWTSource struct {
Expr hcl.Expression
Name string
Type JWTSourceType
}
)
type JWT struct {
algorithms []acjwt.Algorithm
claims hcl.Expression
claimsRequired []string
source JWTSource
hmacSecret []byte
name string
pubKey *rsa.PublicKey
rolesClaim string
rolesMap map[string][]string
scopeClaim string
jwks *JWKS
}
type JWTOptions struct {
Algorithm string
Claims hcl.Expression
ClaimsRequired []string
Name string // TODO: more generic (validate)
RolesClaim string
RolesMap map[string][]string
ScopeClaim string
Source JWTSource
Key []byte
JWKS *JWKS
}
func NewJWTSource(cookie, header string, value hcl.Expression) JWTSource {
c, h := strings.TrimSpace(cookie), strings.TrimSpace(header)
if value != nil {
v, _ := value.Value(nil)
if !v.IsNull() {
if h != "" || c != "" {
return JWTSource{}
}
return JWTSource{
Name: "",
Type: Value,
Expr: value,
}
}
}
if c != "" && h == "" {
return JWTSource{
Name: c,
Type: Cookie,
}
}
if h != "" && c == "" {
return JWTSource{
Name: h,
Type: Header,
}
}
return JWTSource{}
}
// NewJWT parses the key and creates Validation obj which can be referenced in related handlers.
func NewJWT(options *JWTOptions) (*JWT, error) {
jwtAC, err := newJWT(options)
if err != nil {
return nil, err
}
algorithm := acjwt.NewAlgorithm(options.Algorithm)
if algorithm == acjwt.AlgorithmUnknown {
return nil, fmt.Errorf("algorithm %q is not supported", options.Algorithm)
}
jwtAC.algorithms = []acjwt.Algorithm{algorithm}
if algorithm.IsHMAC() {
jwtAC.hmacSecret = options.Key
return jwtAC, nil
}
pubKey, err := parsePublicPEMKey(options.Key)
if err != nil {
return nil, err
}
jwtAC.pubKey = pubKey
return jwtAC, nil
}
func NewJWTFromJWKS(options *JWTOptions) (*JWT, error) {
jwtAC, err := newJWT(options)
if err != nil {
return nil, err
}
if options.JWKS == nil {
return nil, fmt.Errorf("invalid JWKS")
}
jwtAC.algorithms = acjwt.RSAAlgorithms
jwtAC.jwks = options.JWKS
return jwtAC, nil
}
func newJWT(options *JWTOptions) (*JWT, error) {
if options.Source.Type == Invalid {
return nil, fmt.Errorf("token source is invalid")
}
if options.RolesClaim != "" && options.RolesMap == nil {
return nil, fmt.Errorf("missing beta_roles_map")
}
jwtAC := &JWT{
claims: options.Claims,
claimsRequired: options.ClaimsRequired,
name: options.Name,
rolesClaim: options.RolesClaim,
rolesMap: options.RolesMap,
scopeClaim: options.ScopeClaim,
source: options.Source,
}
return jwtAC, nil
}
// Validate reading the token from configured source and validates against the key.
func (j *JWT) Validate(req *http.Request) error {
var tokenValue string
var err error
switch j.source.Type {
case Cookie:
cookie, cerr := req.Cookie(j.source.Name)
if cerr != http.ErrNoCookie && cookie != nil {
tokenValue = cookie.Value
}
case Header:
if strings.ToLower(j.source.Name) == "authorization" {
if tokenValue = req.Header.Get(j.source.Name); tokenValue != "" {
if tokenValue, err = getBearer(tokenValue); err != nil {
return err
}
}
} else {
tokenValue = req.Header.Get(j.source.Name)
}
case Value:
requestContext := eval.ContextFromRequest(req).HCLContext()
value, diags := eval.Value(requestContext, j.source.Expr)
if diags != nil {
return diags
}
tokenValue = seetie.ValueToString(value)
}
if tokenValue == "" {
return errors.JwtTokenMissing.Message("token required")
}
claims := make(map[string]interface{})
if j.claims != nil {
val, verr := eval.Value(eval.ContextFromRequest(req).HCLContext(), j.claims)
if verr != nil {
return verr
}
claims = seetie.ValueToMap(val)
}
parser, err := newParser(j.algorithms, claims)
if err != nil {
return err
}
token, err := parser.Parse(tokenValue, j.getValidationKey)
if err != nil {
switch err := err.(type) {
case *jwt.TokenExpiredError:
return errors.JwtTokenExpired.With(err)
case *jwt.UnverfiableTokenError:
return err.ErrorWrapper.Unwrap()
default:
return err
}
}
tokenClaims, err := j.validateClaims(token, claims)
if err != nil {
return err
}
ctx := req.Context()
acMap, ok := ctx.Value(request.AccessControls).(map[string]interface{})
if !ok {
acMap = make(map[string]interface{})
}
acMap[j.name] = tokenClaims
ctx = context.WithValue(ctx, request.AccessControls, acMap)
scopesValues, err := j.getScopeValues(tokenClaims)
if err != nil {
return err
}
if len(scopesValues) > 0 {
scopes, ok := ctx.Value(request.Scopes).([]string)
if !ok {
scopes = []string{}
}
scopes = append(scopes, scopesValues...)
ctx = context.WithValue(ctx, request.Scopes, scopes)
}
*req = *req.WithContext(ctx)
return nil
}
func (j *JWT) getValidationKey(token *jwt.Token) (interface{}, error) {
if j.jwks != nil {
id := token.Header["kid"]
algorithm := token.Header["alg"]
if id == nil {
return nil, fmt.Errorf("missing \"kid\" in JOSE header")
}
if algorithm == nil {
return nil, fmt.Errorf("missing \"alg\" in JOSE header")
}
jwk, err := j.jwks.GetKey(id.(string), algorithm.(string), "sig")
if err != nil {
return nil, err
}
if jwk == nil {
return nil, fmt.Errorf("no matching %s JWK for kid %q", algorithm, id)
}
return jwk.Key, nil
}
switch j.algorithms[0] {
case acjwt.AlgorithmRSA256, acjwt.AlgorithmRSA384, acjwt.AlgorithmRSA512:
return j.pubKey, nil
case acjwt.AlgorithmHMAC256, acjwt.AlgorithmHMAC384, acjwt.AlgorithmHMAC512:
return j.hmacSecret, nil
default: // this error case gets normally caught on configuration level
return nil, errors.Configuration.Message("algorithm is not supported")
}
}
func (j *JWT) validateClaims(token *jwt.Token, claims map[string]interface{}) (map[string]interface{}, error) {
var tokenClaims jwt.MapClaims
if tc, ok := token.Claims.(jwt.MapClaims); ok {
tokenClaims = tc
}
if tokenClaims == nil {
return nil, errors.JwtTokenInvalid.Message("token has no claims")
}
for _, key := range j.claimsRequired {
if _, ok := tokenClaims[key]; !ok {
return nil, errors.JwtTokenInvalid.Message("required claim is missing: " + key)
}
}
for k, v := range claims {
if k == "iss" || k == "aud" { // gets validated during parsing
continue
}
val, exist := tokenClaims[k]
if !exist {
return nil, errors.JwtTokenInvalid.Message("required claim is missing: " + k)
}
if val != v {
return nil, errors.JwtTokenInvalid.Messagef("unexpected value for claim %s: %q, expected %q", k, val, v)
}
}
return tokenClaims, nil
}
const errValueMsg = "value of %s claim must either be a string containing a space-separated list of %s or a list of string %s"
var errScopeValue = fmt.Errorf(errValueMsg, "scope", "scope values", "scope values")
var errRolesValue = fmt.Errorf(errValueMsg, "roles", "roles", "roles")
func (j *JWT) getScopeValues(tokenClaims map[string]interface{}) ([]string, error) {
var scopeValues []string
if j.scopeClaim != "" {
scopesFromClaim, exists := tokenClaims[j.scopeClaim]
if !exists {
return nil, fmt.Errorf("missing expected scope claim %q", j.scopeClaim)
}
// ["foo", "bar"] is stored as []interface{}, not []string, unfortunately
scopesArray, ok := scopesFromClaim.([]interface{})
if ok {
for _, v := range scopesArray {
s, ok := v.(string)
if !ok {
return nil, errScopeValue
}
scopeValues = addScopeValue(scopeValues, s)
}
} else {
scopesString, ok := scopesFromClaim.(string)
if !ok {
return nil, errScopeValue
}
for _, s := range strings.Split(scopesString, " ") {
scopeValues = addScopeValue(scopeValues, s)
}
}
}
if j.rolesClaim != "" {
rolesClaimValue, exists := tokenClaims[j.rolesClaim]
if !exists {
return nil, fmt.Errorf("missing expected roles claim %q", j.rolesClaim)
}
var roleValues []string
// ["foo", "bar"] is stored as []interface{}, not []string, unfortunately
rolesArray, ok := rolesClaimValue.([]interface{})
if ok {
for _, v := range rolesArray {
r, ok := v.(string)
if !ok {
return nil, errRolesValue
}
roleValues = append(roleValues, r)
}
} else {
rolesString, ok := rolesClaimValue.(string)
if !ok {
return nil, errRolesValue
}
roleValues = strings.Split(rolesString, " ")
}
for _, r := range roleValues {
if scopes, exist := j.rolesMap[r]; exist {
for _, s := range scopes {
scopeValues = addScopeValue(scopeValues, s)
}
}
}
if scopes, exist := j.rolesMap["*"]; exist {
for _, s := range scopes {
scopeValues = addScopeValue(scopeValues, s)
}
}
}
return scopeValues, nil
}
func addScopeValue(scopeValues []string, scope string) []string {
scope = strings.TrimSpace(scope)
if scope == "" {
return scopeValues
}
for _, s := range scopeValues {
if s == scope {
return scopeValues
}
}
return append(scopeValues, scope)
}
func getBearer(val string) (string, error) {
const bearer = "bearer "
if strings.HasPrefix(strings.ToLower(val), bearer) {
return strings.Trim(val[len(bearer):], " "), nil
}
return "", errors.JwtTokenExpired.Message("bearer required with authorization header")
}
func newParser(algos []acjwt.Algorithm, claims map[string]interface{}) (*jwt.Parser, error) {
var algorithms []string
for _, a := range algos {
algorithms = append(algorithms, a.String())
}
options := []jwt.ParserOption{
jwt.WithValidMethods(algorithms),
jwt.WithLeeway(time.Second),
}
if claims == nil {
options = append(options, jwt.WithoutAudienceValidation())
return jwt.NewParser(options...), nil
}
if iss, ok := claims["iss"]; ok {
if err := isStringType(iss); err != nil {
return nil, fmt.Errorf("iss: %w", err)
}
options = append(options, jwt.WithIssuer(iss.(string)))
}
if aud, ok := claims["aud"]; ok {
if err := isStringType(aud); err != nil {
return nil, fmt.Errorf("aud: %w", err)
}
options = append(options, jwt.WithAudience(aud.(string)))
} else {
options = append(options, jwt.WithoutAudienceValidation())
}
return jwt.NewParser(options...), nil
}
// parsePublicPEMKey tries to parse all supported publicKey variations which
// must be given in PEM encoded format.
func parsePublicPEMKey(key []byte) (pub *rsa.PublicKey, err error) {
pemBlock, _ := pem.Decode(key)
if pemBlock == nil {
return nil, jwt.ErrKeyMustBePEMEncoded
}
pubKey, pubErr := x509.ParsePKCS1PublicKey(pemBlock.Bytes)
if pubErr != nil {
pkixKey, pkerr := x509.ParsePKIXPublicKey(pemBlock.Bytes)
if pkerr != nil {
cert, cerr := x509.ParseCertificate(pemBlock.Bytes)
if cerr != nil {
return nil, jwt.ErrNotRSAPublicKey
}
if k, ok := cert.PublicKey.(*rsa.PublicKey); ok {
return k, nil
}
return nil, jwt.ErrNotRSAPublicKey
}
k, ok := pkixKey.(*rsa.PublicKey)
if !ok {
return nil, jwt.ErrNotRSAPublicKey
}
pubKey = k
}
return pubKey, nil
}
func isStringType(val interface{}) error {
switch val.(type) {
case string:
return nil
default:
return fmt.Errorf("invalid value type")
}
}