-
Notifications
You must be signed in to change notification settings - Fork 28
/
jwt.go
253 lines (209 loc) · 6.18 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
package impl
import (
"context"
"encoding/json"
"fmt"
"net/http"
"net/url"
"path"
"time"
cerr "github.com/aserto-dev/errors"
"github.com/aserto-dev/go-authorizer/aserto/authorizer/v2/api"
"github.com/aserto-dev/go-authorizer/pkg/aerr"
v2 "github.com/aserto-dev/go-directory/aserto/directory/common/v2"
ds2 "github.com/aserto-dev/go-directory/aserto/directory/reader/v2"
"github.com/aserto-dev/go-directory/pkg/derr"
"github.com/aserto-dev/topaz/builtins/edge/ds"
"github.com/google/uuid"
"github.com/lestrrat-go/jwx/jwk"
"github.com/lestrrat-go/jwx/jwt"
"github.com/pkg/errors"
"google.golang.org/protobuf/proto"
)
var (
// ErrMissingMetadata - metadata element missing.
ErrMissingMetadata = aerr.ErrInvalidArgument.Msg("missing metadata")
// ErrMissingToken - token missing from metadata.
ErrMissingToken = aerr.ErrInvalidArgument.Msg("missing token")
// ErrInvalidToken - token not valid.
ErrInvalidToken = aerr.ErrAuthenticationFailed.Msg("invalid token")
)
// getUserFromJWT.
func (s *AuthorizerServer) getUserFromJWT(ctx context.Context, bearerJWT string) (proto.Message, error) {
resp := v2.Object{}
ident, err := s.getIdentityFromJWT(ctx, bearerJWT)
if err != nil {
return &resp, err
}
user, err := s.getUserFromIdentity(ctx, ident)
if err != nil {
return &resp, err
}
return user, nil
}
// getIdentityFromJWT.
func (s *AuthorizerServer) getIdentityFromJWT(ctx context.Context, bearerJWT string) (string, error) {
log := s.logger
jwtTemp, err := jwt.ParseString(bearerJWT, jwt.WithValidate(false))
if err != nil {
log.Error().Err(err).Msg("jwt parse without validation")
return "", err
}
options := []jwt.ParseOption{
jwt.WithValidate(true),
jwt.WithAcceptableSkew(time.Duration(s.cfg.JWT.AcceptableTimeSkewSeconds) * time.Second),
}
jwksURL, err := s.jwksURL(ctx, jwtTemp.Issuer())
if err != nil {
log.Debug().Str("issuer", jwtTemp.Issuer()).Msg("token didn't have a JWKS endpoint we could use for verification")
} else {
jwkSet, errX := jwk.Fetch(ctx, jwksURL.String())
if errX != nil {
return "", errors.Wrap(errX, "failed to fetch JWK set for validation")
}
options = append(options, jwt.WithKeySet(jwkSet))
}
jwtToken, err := jwt.ParseString(
bearerJWT,
options...,
)
if err != nil {
log.Error().Err(err).Msg("jwt parse with validation")
return "", err
}
ident := jwtToken.Subject()
return ident, nil
}
// jwksURL.
func (s *AuthorizerServer) jwksURL(ctx context.Context, baseURL string) (*url.URL, error) {
const (
wellknownConfig = `.well-known/openid-configuration`
wellknownJWKS = `.well-known/jwks.json`
)
u, err := url.Parse(baseURL)
if err != nil {
return nil, err
}
if u.Scheme == "" {
return nil, errors.New("no scheme defined for baseURL")
}
originalPath := u.Path
u.Path = path.Join(originalPath, wellknownConfig)
req, err := http.NewRequestWithContext(ctx, "GET", u.String(), http.NoBody)
if err != nil {
return nil, err
}
client := &http.Client{}
resp, err := client.Do(req)
if err == nil {
defer resp.Body.Close()
var config struct {
URI string `json:"jwks_uri"`
}
if err := json.NewDecoder(resp.Body).Decode(&config); err == nil {
if u, err = url.Parse(config.URI); err == nil {
return u, nil
}
}
}
u.Path = path.Join(originalPath, wellknownJWKS)
return u, nil
}
// getUserFromIdentityContext.
func (s *AuthorizerServer) getUserFromIdentityContext(ctx context.Context, identityContext *api.IdentityContext) (proto.Message, error) {
if identityContext == nil {
return nil, aerr.ErrInvalidArgument.Msg("identity context not set")
}
// nolint: exhaustive
switch identityContext.Type {
case api.IdentityType_IDENTITY_TYPE_NONE:
return nil, nil
case api.IdentityType_IDENTITY_TYPE_SUB:
if identityContext.Identity == "" {
return nil, fmt.Errorf("identity value not set (type: %s)", identityContext.Type.String())
}
user, err := s.getUserFromIdentity(ctx, identityContext.Identity)
if err != nil {
return nil, err
}
return user, nil
case api.IdentityType_IDENTITY_TYPE_JWT:
if identityContext.Identity == "" {
return nil, fmt.Errorf("identity value not set (type: %s)", identityContext.Type.String())
}
user, err := s.getUserFromJWT(ctx, identityContext.Identity)
if err != nil {
return nil, err
}
return user, nil
default:
return nil, fmt.Errorf("invalid identity type %s", identityContext.Type.String())
}
}
func (s *AuthorizerServer) getUserFromIdentity(ctx context.Context, identity string) (proto.Message, error) {
uid, err := s.getIdentityV2(ctx, identity)
switch {
case errors.Is(err, aerr.ErrDirectoryObjectNotFound):
if !ds.IsValidID(identity) {
return nil, err
}
uid = identity
case err != nil:
return nil, err
default:
}
user, err := s.getUserV2(ctx, uid)
if err != nil {
return nil, err
}
return user, nil
}
func (s *AuthorizerServer) getIdentityV2(ctx context.Context, identity string) (string, error) {
client, err := s.resolver.GetDirectoryResolver().GetDS(ctx)
if err != nil {
return "", err
}
identityString := "identity"
obj := v2.ObjectIdentifier{Type: &identityString, Key: &identity}
_, err = uuid.Parse(identity)
if err == nil {
obj = v2.ObjectIdentifier{Id: &identity}
}
relationString := "identifier"
subjectType := "user"
relResp, err := client.GetRelation(ctx, &ds2.GetRelationRequest{
Param: &v2.RelationIdentifier{
Object: &obj,
Relation: &v2.RelationTypeIdentifier{Name: &relationString, ObjectType: &identityString},
Subject: &v2.ObjectIdentifier{Type: &subjectType},
},
})
if err != nil {
return "", err
}
if relResp.Results == nil {
return "", aerr.ErrDirectoryObjectNotFound
}
uid := relResp.Results[0].Subject.Id
return *uid, nil
}
func (s *AuthorizerServer) getUserV2(ctx context.Context, uid string) (*v2.Object, error) {
client, err := s.resolver.GetDirectoryResolver().GetDS(ctx)
if err != nil {
return nil, err
}
userResp, err := client.GetObject(ctx, &ds2.GetObjectRequest{
Param: &v2.ObjectIdentifier{
Id: &uid,
},
})
switch {
case cerr.Equals(err, derr.ErrNotFound):
return nil, aerr.ErrDirectoryObjectNotFound
case err != nil:
return nil, err
case userResp.Result == nil:
return nil, aerr.ErrDirectoryObjectNotFound
}
return userResp.Result, nil
}