-
Notifications
You must be signed in to change notification settings - Fork 180
/
jwt.go
450 lines (364 loc) · 10.6 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
/*
* Copyright (c) 2018. Abstrium SAS <team (at) pydio.com>
* This file is part of Pydio Cells.
*
* Pydio Cells is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Pydio Cells is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with Pydio Cells. If not, see <http://www.gnu.org/licenses/>.
*
* The latest code can be found at <https://pydio.com>.
*/
package auth
import (
"context"
"errors"
"net/url"
"sort"
"strings"
context2 "github.com/pydio/cells/common/utils/context"
errors2 "github.com/micro/go-micro/errors"
"github.com/micro/go-micro/metadata"
"go.uber.org/zap"
"golang.org/x/oauth2"
"github.com/pydio/cells/common"
"github.com/pydio/cells/common/auth/claim"
"github.com/pydio/cells/common/log"
"github.com/pydio/cells/common/proto/idm"
"github.com/pydio/cells/common/utils/permissions"
)
type ProviderType int
const (
ProviderTypeOry ProviderType = iota
ProviderTypeGrpc
ProviderTypePAT
)
type Provider interface {
GetType() ProviderType
}
type Verifier interface {
Verify(context.Context, string) (IDToken, error)
}
type ContextVerifier interface {
Verify(ctx context.Context, user *idm.User) error
}
type Exchanger interface {
Exchange(context.Context, string) (*oauth2.Token, error)
}
// An AuthCodeOption is passed to Config.AuthCodeURL.
type TokenOption interface {
setValue(url.Values)
}
type setParam struct{ k, v string }
func (p setParam) setValue(m url.Values) { m.Set(p.k, p.v) }
// SetChallenge builds a TokenOption which passes key/value parameters
// to a provider's token exchange endpoint.
func SetChallenge(value string) TokenOption {
return setParam{"challenge", value}
}
// SetAccesToken builds a TokenOption for passing the access tokens
func SetAccessToken(value string) TokenOption {
return setParam{"access_token", value}
}
// SetAccesToken builds a TokenOption for passing the refresh tokens
func SetRefreshToken(value string) TokenOption {
return setParam{"refresh_token", value}
}
type PasswordCredentialsTokenExchanger interface {
PasswordCredentialsToken(context.Context, string, string) (*oauth2.Token, error)
}
type PasswordCredentialsCodeExchanger interface {
PasswordCredentialsCode(context.Context, string, string, ...TokenOption) (string, error)
}
type LoginChallengeCodeExchanger interface {
LoginChallengeCode(context.Context, claim.Claims, ...TokenOption) (string, error)
}
type LogoutProvider interface {
Logout(context.Context, string, string, string, ...TokenOption) error
}
type IDToken interface {
Claims(interface{}) error
ScopedClaims(claims *claim.Claims) error
}
var (
providers []Provider
contextVerifiers []ContextVerifier
)
// AddContextVerifier registers an additional verifier
func AddContextVerifier(v ContextVerifier) {
contextVerifiers = append(contextVerifiers, v)
}
func VerifyContext(ctx context.Context, user *idm.User) error {
for _, v := range contextVerifiers {
if err := v.Verify(ctx, user); err != nil {
return err
}
}
return nil
}
type JWTVerifier struct {
types []ProviderType
}
// DefaultJWTVerifier creates a ready to use JWTVerifier
func DefaultJWTVerifier() *JWTVerifier {
return &JWTVerifier{
types: []ProviderType{ProviderTypeGrpc, ProviderTypeOry, ProviderTypePAT},
}
}
func LocalJWTVerifier() *JWTVerifier {
return &JWTVerifier{
types: []ProviderType{ProviderTypeOry, ProviderTypePAT},
}
}
func (j *JWTVerifier) getProviders() []Provider {
var res []Provider
for _, provider := range providers {
for _, t := range j.types {
if provider.GetType() == t {
res = append(res, provider)
}
}
}
return res
}
func (j *JWTVerifier) loadClaims(ctx context.Context, token IDToken, claims *claim.Claims) error {
// Extract custom claims
if err := token.Claims(claims); err != nil {
log.Logger(ctx).Error("cannot extract custom claims from idToken", zap.Error(err))
return err
}
if err := token.ScopedClaims(claims); err != nil {
log.Logger(ctx).Error("cannot extract custom Scopes from claims", zap.Error(err))
}
// Search by name or by email
var user *idm.User
var uE error
// Search by subject
if claims.Subject != "" {
if u, err := permissions.SearchUniqueUser(ctx, "", claims.Subject); err == nil {
user = u
}
} else if claims.Name != "" {
if u, err := permissions.SearchUniqueUser(ctx, claims.Name, ""); err == nil {
user = u
}
}
if user == nil {
if u, err := permissions.SearchUniqueUser(ctx, claims.Email, ""); err == nil {
user = u
// Now replace claims.Name
claims.Name = claims.Email
} else {
uE = err
}
}
if user == nil {
if uE != nil {
return uE
} else {
return errors2.NotFound("user.not.found", "user not found neither by name or email")
}
}
// Check if User is locked
if e := VerifyContext(ctx, user); e != nil {
return errors2.Unauthorized("user.context", e.Error())
}
displayName, ok := user.Attributes["displayName"]
if !ok {
displayName = ""
}
profile, ok := user.Attributes["profile"]
if !ok {
profile = "standard"
}
var roles []string
for _, role := range user.Roles {
roles = append(roles, role.Uuid)
}
claims.Name = user.Login
claims.DisplayName = displayName
claims.Profile = profile
claims.Roles = strings.Join(roles, ",")
claims.GroupPath = user.GroupPath
return nil
}
func (j *JWTVerifier) verifyTokenWithRetry(ctx context.Context, rawIDToken string, isRetry bool) (IDToken, error) {
var idToken IDToken
var err error
for _, provider := range j.getProviders() {
verifier, ok := provider.(Verifier)
if !ok {
continue
}
idToken, err = verifier.Verify(ctx, rawIDToken)
if err == nil {
break
}
log.Logger(ctx).Debug("jwt rawIdToken verify: failed", zap.Error(err))
}
if (idToken == nil || err != nil) && !isRetry {
return j.verifyTokenWithRetry(ctx, rawIDToken, true)
}
if idToken == nil {
return nil, errors.New("empty idToken")
}
return idToken, nil
}
// Exchange retrives a oauth2 Token from a code
func (j *JWTVerifier) Exchange(ctx context.Context, code string) (*oauth2.Token, error) {
var oauth2Token *oauth2.Token
var err error
for _, provider := range j.getProviders() {
exch, ok := provider.(Exchanger)
if !ok {
continue
}
// Verify state and errors.
oauth2Token, err = exch.Exchange(ctx, code)
if err == nil {
break
}
}
if err != nil {
return nil, err
}
return oauth2Token, nil
}
// Verify validates an existing JWT token against the OIDC service that issued it
func (j *JWTVerifier) Verify(ctx context.Context, rawIDToken string) (context.Context, claim.Claims, error) {
idToken, err := j.verifyTokenWithRetry(ctx, rawIDToken, false)
if err != nil {
log.Logger(ctx).Debug("error verifying token", zap.String("token", rawIDToken), zap.Error(err))
return ctx, claim.Claims{}, err
}
claims := &claim.Claims{}
if err := j.loadClaims(ctx, idToken, claims); err != nil {
log.Logger(ctx).Error("got a token but failed to load claims", zap.Error(err))
return ctx, *claims, err
}
ctx = context.WithValue(ctx, claim.ContextKey, *claims)
md := make(map[string]string)
if existing, ok := metadata.FromContext(ctx); ok {
for k, v := range existing {
md[k] = v
}
}
md[common.PydioContextUserKey] = claims.Name
ctx = metadata.NewContext(ctx, md)
ctx = ToMetadata(ctx, *claims)
return ctx, *claims, nil
}
// PasswordCredentialsToken will perform a call to the OIDC service with grantType "password"
// to get a valid token from a given user/pass credentials
func (j *JWTVerifier) PasswordCredentialsToken(ctx context.Context, userName string, password string) (*oauth2.Token, error) {
var token *oauth2.Token
var err error
for _, provider := range j.getProviders() {
recl, ok := provider.(PasswordCredentialsTokenExchanger)
if !ok {
continue
}
token, err = recl.PasswordCredentialsToken(ctx, userName, password)
if err == nil {
break
}
}
return token, err
}
// LoginChallengeCode will perform an implicit flow
// to get a valid code from given claims and challenge
func (j *JWTVerifier) LoginChallengeCode(ctx context.Context, claims claim.Claims, opts ...TokenOption) (string, error) {
var code string
var err error
for _, provider := range j.getProviders() {
p, ok := provider.(LoginChallengeCodeExchanger)
if !ok {
continue
}
code, err = p.LoginChallengeCode(ctx, claims, opts...)
if err == nil {
break
}
}
return code, err
}
// PasswordCredentialsCode will perform an implicit flow
// to get a valid code from given claims and challenge
func (j *JWTVerifier) PasswordCredentialsCode(ctx context.Context, username, password string, opts ...TokenOption) (string, error) {
var code string
var err error
for _, provider := range j.getProviders() {
p, ok := provider.(PasswordCredentialsCodeExchanger)
if !ok {
continue
}
code, err = p.PasswordCredentialsCode(ctx, username, password, opts...)
if err == nil {
break
}
}
return code, err
}
// Logout
func (j *JWTVerifier) Logout(ctx context.Context, url, subject, sessionID string, opts ...TokenOption) error {
for _, provider := range j.getProviders() {
p, ok := provider.(LogoutProvider)
if !ok {
continue
}
if err := p.Logout(ctx, url, subject, sessionID, opts...); err != nil {
return err
}
}
return nil
}
// Add a fake Claims in context to impersonate user
func WithImpersonate(ctx context.Context, user *idm.User) context.Context {
roles := make([]string, len(user.Roles))
for _, r := range user.Roles {
roles = append(roles, r.Uuid)
}
// Build Claims Now
c := claim.Claims{
Name: user.Login,
GroupPath: user.GroupPath,
Roles: strings.Join(roles, ","),
}
if user.Attributes != nil {
if p, o := user.Attributes[idm.UserAttrProfile]; o {
c.Profile = p
}
if e, o := user.Attributes[idm.UserAttrEmail]; o {
c.Email = e
}
}
ctx = context2.WithMetadata(ctx, map[string]string{common.PydioContextUserKey: user.Login})
return context.WithValue(ctx, claim.ContextKey, c)
}
func addProvider(p Provider) {
providers = append(providers, p)
sortProviders()
}
func delProviders(f func(p Provider) bool) {
b := providers[:0]
for _, p := range providers {
if !f(p) {
b = append(b, p)
}
}
providers = b
sortProviders()
}
func sortProviders() {
sort.Slice(providers, func(i, j int) bool {
return providers[i].GetType() < providers[j].GetType()
})
}