generated from xmidt-org/.go-template
/
jwtAcquireParser.go
76 lines (65 loc) · 1.83 KB
/
jwtAcquireParser.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
// SPDX-FileCopyrightText: 2022 Comcast Cable Communications Management, LLC
// SPDX-License-Identifier: Apache-2.0
package ancla
import (
"errors"
"time"
"github.com/golang-jwt/jwt"
"github.com/spf13/cast"
"github.com/xmidt-org/bascule/acquire"
)
type jwtAcquireParserType string
const (
simpleType jwtAcquireParserType = "simple"
rawType jwtAcquireParserType = "raw"
)
var (
errMissingExpClaim = errors.New("missing exp claim in jwt")
errUnexpectedCasting = errors.New("unexpected casting error")
)
type jwtAcquireParser struct {
token acquire.TokenParser
expiration acquire.ParseExpiration
}
func rawTokenParser(data []byte) (string, error) {
return string(data), nil
}
func rawTokenExpirationParser(data []byte) (time.Time, error) {
p := jwt.Parser{SkipClaimsValidation: true}
token, _, err := p.ParseUnverified(string(data), jwt.MapClaims{})
if err != nil {
return time.Time{}, err
}
claims, ok := token.Claims.(jwt.MapClaims)
if !ok {
return time.Time{}, errUnexpectedCasting
}
expVal, ok := claims["exp"]
if !ok {
return time.Time{}, errMissingExpClaim
}
exp, err := cast.ToInt64E(expVal)
if err != nil {
return time.Time{}, err
}
return time.Unix(exp, 0), nil
}
func newJWTAcquireParser(pType jwtAcquireParserType) (jwtAcquireParser, error) {
if pType == "" {
pType = simpleType
}
if pType != simpleType && pType != rawType {
return jwtAcquireParser{}, errors.New("only 'simple' or 'raw' are supported as jwt acquire parser types")
}
// nil defaults are fine (bascule/acquire will use the simple
// default parsers internally).
var (
tokenParser acquire.TokenParser
expirationParser acquire.ParseExpiration
)
if pType == rawType {
tokenParser = rawTokenParser
expirationParser = rawTokenExpirationParser
}
return jwtAcquireParser{expiration: expirationParser, token: tokenParser}, nil
}