-
Notifications
You must be signed in to change notification settings - Fork 180
/
jwt_ory.go
438 lines (357 loc) · 11.2 KB
/
jwt_ory.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
/*
* Copyright (c) 2019-2021. 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"
"crypto/sha256"
"encoding/base64"
"net/url"
"time"
"github.com/ory/fosite"
"github.com/ory/fosite/token/jwt"
"github.com/ory/hydra/oauth2"
"github.com/pkg/errors"
"go.uber.org/zap"
goauth "golang.org/x/oauth2"
"github.com/pydio/cells/v4/common/auth/claim"
"github.com/pydio/cells/v4/common/auth/hydra"
"github.com/pydio/cells/v4/common/config"
"github.com/pydio/cells/v4/common/log"
json "github.com/pydio/cells/v4/common/utils/jsonx"
)
type oryprovider struct {
oauth2Provider fosite.OAuth2Provider
}
type orytoken struct {
claims *jwt.IDTokenClaims
}
func RegisterOryProvider(o fosite.OAuth2Provider) {
p := new(oryprovider)
p.oauth2Provider = o
addProvider(p)
}
func (p *oryprovider) GetType() ProviderType {
return ProviderTypeOry
}
func (p *oryprovider) LoginChallengeCode(ctx context.Context, claims claim.Claims, opts ...TokenOption) (string, error) {
v := url.Values{}
for _, opt := range opts {
opt.setValue(v)
}
// Getting or creating challenge
challenge := v.Get("challenge")
if challenge == "" {
if c, err := hydra.CreateLogin(ctx, config.DefaultOAuthClientID, []string{"openid", "profile", "offline"}, []string{}); err != nil {
return "", err
} else {
challenge = c.Challenge
}
}
// Searching login challenge
login, err := hydra.GetLogin(ctx, challenge)
if err != nil {
log.Logger(ctx).Error("Failed to get login ", zap.Error(err))
return "", err
}
// Accepting login challenge
if _, err := hydra.AcceptLogin(ctx, challenge, claims.Subject); err != nil {
log.Logger(ctx).Error("Failed to accept login ", zap.Error(err))
return "", err
}
// Creating consent
consent, err := hydra.CreateConsent(ctx, challenge)
if err != nil {
log.Logger(ctx).Error("Failed to create consent ", zap.Error(err))
return "", err
}
// Accepting consent
if _, err := hydra.AcceptConsent(ctx, consent.Challenge, login.GetRequestedScope(), login.GetRequestedAudience(), map[string]string{}, map[string]string{
"name": claims.Name,
"email": claims.Email,
}); err != nil {
log.Logger(ctx).Error("Failed to accept consent ", zap.Error(err))
return "", err
}
requestURL, err := url.Parse(login.GetRequestURL())
if err != nil {
return "", err
}
requestURLValues := requestURL.Query()
redirectURL, err := GetRedirectURIFromRequestValues(requestURLValues)
if err != nil {
return "", err
}
code, err := hydra.CreateAuthCode(ctx, consent, login.GetClientID(), redirectURL, requestURLValues.Get("code_challenge"), requestURLValues.Get("code_challenge_method"))
if err != nil {
log.Logger(ctx).Error("Failed to create auth code ", zap.Error(err))
return "", err
}
if err != nil {
return "", err
}
return code, err
}
func (p *oryprovider) PasswordCredentialsCode(ctx context.Context, userName string, password string, opts ...TokenOption) (string, error) {
v := url.Values{}
for _, opt := range opts {
opt.setValue(v)
}
// Getting or creating challenge
challenge := v.Get("challenge")
if challenge == "" {
if c, err := hydra.CreateLogin(ctx, config.DefaultOAuthClientID, []string{"openid", "profile", "offline"}, []string{}); err != nil {
return "", err
} else {
challenge = c.Challenge
}
}
var identity Identity
var valid bool
var err error
connectors := GetConnectors()
source := ""
for _, c := range connectors {
cc, ok := c.Conn().(PasswordConnector)
if !ok {
continue
}
// Creating a timeout for context
loginctx, _ := context.WithTimeout(ctx, 5*time.Second)
identity, valid, err = cc.Login(loginctx, Scopes{}, userName, password)
// Error means the user is unknwown to the system, we continue to the next round
if err != nil {
continue
}
// Invalid means we found the user but did not match the password
if !valid {
err = errors.New("password does not match")
continue
}
source = c.Name()
break
}
if err != nil {
return "", err
}
// Searching login challenge
login, err := hydra.GetLogin(ctx, challenge)
if err != nil {
log.Logger(ctx).Error("Failed to get login ", zap.Error(err))
return "", err
}
// Accepting login challenge
if _, err := hydra.AcceptLogin(ctx, challenge, identity.UserID); err != nil {
log.Logger(ctx).Error("Failed to accept login ", zap.Error(err))
return "", err
}
// Creating consent
consent, err := hydra.CreateConsent(ctx, challenge)
if err != nil {
log.Logger(ctx).Error("Failed to create consent ", zap.Error(err))
return "", err
}
// Accepting consent
if _, err := hydra.AcceptConsent(
ctx,
consent.Challenge,
login.GetRequestedScope(),
login.GetRequestedAudience(),
map[string]string{},
map[string]string{
"name": identity.Username,
"email": identity.Email,
"authSource": source,
},
); err != nil {
log.Logger(ctx).Error("Failed to accept consent ", zap.Error(err))
return "", err
}
requestURL, err := url.Parse(login.GetRequestURL())
if err != nil {
return "", err
}
requestURLValues := requestURL.Query()
redirectURL, err := GetRedirectURIFromRequestValues(requestURLValues)
if err != nil {
return "", err
}
code, err := hydra.CreateAuthCode(ctx, consent, login.GetClientID(), redirectURL, requestURLValues.Get("code_challenge"), requestURLValues.Get("code_challenge_method"))
if err != nil {
log.Logger(ctx).Error("Failed to create auth code ", zap.Error(err))
return "", err
}
if err != nil {
return "", err
}
return code, err
}
func (p *oryprovider) PasswordCredentialsToken(ctx context.Context, userName string, password string) (*goauth.Token, error) {
// Getting or creating challenge
c, err := hydra.CreateLogin(ctx, config.DefaultOAuthClientID, []string{"openid", "profile", "offline"}, []string{})
if err != nil {
return nil, errors.Wrap(err, "PasswordCredentialsToken")
}
challenge := c.Challenge
var identity Identity
var valid bool
connectors := GetConnectors()
attempt := 0
source := ""
for _, c := range connectors {
cc, ok := c.Conn().(PasswordConnector)
if !ok {
continue
}
attempt++
loginctx, can := context.WithTimeout(ctx, 5*time.Second)
defer can()
identity, valid, err = cc.Login(loginctx, Scopes{}, userName, password)
// Error means the user is unknwown to the system, we continue to the next round
if err != nil {
continue
}
// Invalid means we found the user but did not match the password
if !valid {
err = errors.New("password does not match")
continue
}
source = c.Name()
break
}
if attempt == 0 {
return nil, errors.New("No password connector found")
}
if err != nil {
return nil, err
}
// Searching login challenge
login, err := hydra.GetLogin(ctx, challenge)
if err != nil {
log.Logger(ctx).Error("Failed to get login ", zap.Error(err))
return nil, err
}
// Accepting login challenge
if _, err := hydra.AcceptLogin(ctx, challenge, identity.UserID); err != nil {
log.Logger(ctx).Error("Failed to accept login ", zap.Error(err))
return nil, err
}
// Creating consent
consent, err := hydra.CreateConsent(ctx, challenge)
if err != nil {
log.Logger(ctx).Error("Failed to create consent ", zap.Error(err))
return nil, err
}
// Accepting consent
if _, err := hydra.AcceptConsent(
ctx,
consent.Challenge,
login.GetRequestedScope(),
login.GetRequestedAudience(),
map[string]string{},
map[string]string{
"name": identity.Username,
"email": identity.Email,
"authSource": source,
},
); err != nil {
log.Logger(ctx).Error("Failed to accept consent ", zap.Error(err))
return nil, err
}
requestURL, err := url.Parse(login.GetRequestURL())
if err != nil {
return nil, err
}
requestURLValues := requestURL.Query()
redirectURL, err := GetRedirectURIFromRequestValues(requestURLValues)
if err != nil {
return nil, err
}
verifier := consent.Challenge + consent.Challenge // Must be > 43 characters
hash := sha256.New()
if _, err := hash.Write([]byte(verifier)); err != nil {
return nil, err
}
codeChallenge := base64.RawURLEncoding.EncodeToString(hash.Sum([]byte{}))
codeChallengeMethod := "S256"
code, err := hydra.CreateAuthCode(ctx, consent, login.GetClientID(), redirectURL, codeChallenge, codeChallengeMethod)
if err != nil {
e := fosite.ErrorToRFC6749Error(err)
log.Logger(ctx).Error("Failed to create auth code ", zap.Error(e))
return nil, err
}
return hydra.Exchange(ctx, code, verifier)
}
func (p *oryprovider) Logout(ctx context.Context, requestUrl, username, sessionID string, opts ...TokenOption) error {
v := url.Values{}
for _, opt := range opts {
opt.setValue(v)
}
logout, err := hydra.CreateLogout(ctx, requestUrl, username, sessionID)
if err != nil {
return err
}
if err := hydra.AcceptLogout(ctx, logout.Challenge, v.Get("access_token"), v.Get("refresh_token")); err != nil {
return err
}
return nil
}
func (p *oryprovider) Verify(ctx context.Context, accessToken string) (IDToken, error) {
session := oauth2.NewSession("")
ctx2, cancel := context.WithTimeout(ctx, 50*time.Second)
defer cancel()
tokenType, ar, err := p.oauth2Provider.IntrospectToken(ctx2, accessToken, fosite.AccessToken, session)
if err != nil {
return nil, err
}
if tokenType != fosite.AccessToken {
return nil, errors.New("Only access tokens are allowed in the authorization header")
}
return &orytoken{ar.GetSession().(*oauth2.Session).IDTokenClaims()}, nil
}
func (t *orytoken) Claims(v interface{}) error {
data, err := json.Marshal(t.claims.ToMap())
if err != nil {
return err
}
if err := json.Unmarshal(data, &v); err != nil {
return err
}
return nil
}
func (t *orytoken) ScopedClaims(claims *claim.Claims) error {
return nil
}
// GetRedirectURIFromRequestValues extracts the redirect_uri from values but does not do any sort of validation.
//
// Considered specifications
// * https://tools.ietf.org/html/rfc6749#section-3.1
// The endpoint URI MAY include an
// "application/x-www-form-urlencoded" formatted (per Appendix B) query
// component ([RFC3986] Section 3.4), which MUST be retained when adding
// additional query parameters.
func GetRedirectURIFromRequestValues(values url.Values) (string, error) {
// rfc6749 3.1. Authorization Endpoint
// The endpoint URI MAY include an "application/x-www-form-urlencoded" formatted (per Appendix B) query component
redirectURI, err := url.QueryUnescape(values.Get("redirect_uri"))
if err != nil {
return "", errors.WithStack(fosite.ErrInvalidRequest.WithHint(`The "redirect_uri" parameter is malformed or missing.`).WithDebug(err.Error()))
}
return redirectURI, nil
}