forked from pydio/cells
-
Notifications
You must be signed in to change notification settings - Fork 0
/
handler.go
613 lines (498 loc) · 18 KB
/
handler.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
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
/*
* 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 grpc
import (
"context"
"fmt"
"net/http"
"net/url"
"strings"
"time"
json "github.com/pydio/cells/x/jsonx"
"github.com/ory/fosite"
"github.com/ory/fosite/handler/openid"
"github.com/ory/fosite/token/jwt"
"github.com/ory/hydra/consent"
"github.com/ory/hydra/oauth2"
"github.com/ory/x/sqlcon"
"github.com/ory/x/urlx"
"github.com/pborman/uuid"
"github.com/pkg/errors"
"go.uber.org/zap"
"github.com/pydio/cells/common/auth"
"github.com/pydio/cells/common/config"
"github.com/pydio/cells/common/log"
pauth "github.com/pydio/cells/common/proto/auth"
servicecontext "github.com/pydio/cells/common/service/context"
"github.com/pydio/cells/common/sql"
)
// Handler for the plugin
type Handler struct{}
var (
_ pauth.LoginProviderHandler = (*Handler)(nil)
_ pauth.ConsentProviderHandler = (*Handler)(nil)
_ pauth.AuthCodeProviderHandler = (*Handler)(nil)
_ pauth.AuthCodeExchangerHandler = (*Handler)(nil)
_ pauth.AuthTokenVerifierHandler = (*Handler)(nil)
_ pauth.AuthTokenRefresherHandler = (*Handler)(nil)
_ pauth.AuthTokenRevokerHandler = (*Handler)(nil)
)
func (h *Handler) GetLogin(ctx context.Context, in *pauth.GetLoginRequest, out *pauth.GetLoginResponse) error {
req, err := auth.GetRegistry().ConsentManager().GetLoginRequest(ctx, in.Challenge)
if err != nil {
return err
}
out.Challenge = req.Challenge
out.SessionID = req.SessionID
out.RequestURL = req.RequestURL
out.Subject = req.Subject
out.RequestedScope = req.RequestedScope
out.RequestedAudience = req.RequestedAudience
out.ClientID = req.Client.GetID()
return nil
}
func (h *Handler) CreateLogin(ctx context.Context, in *pauth.CreateLoginRequest, out *pauth.CreateLoginResponse) error {
// Set up csrf/challenge/verifier values
verifier := strings.Replace(uuid.New(), "-", "", -1)
challenge := strings.Replace(uuid.New(), "-", "", -1)
csrf := strings.Replace(uuid.New(), "-", "", -1)
// Generate the request URL
host, _ := servicecontext.HttpMetaFromGrpcContext(ctx, servicecontext.HttpMetaHost)
provider := auth.GetConfigurationProvider(host)
iu := urlx.AppendPaths(provider.IssuerURL(), provider.OAuth2AuthURL())
sessionID := uuid.New()
if err := auth.GetRegistry().ConsentManager().CreateLoginSession(ctx, &consent.LoginSession{
ID: sessionID,
Subject: "",
AuthenticatedAt: time.Now().UTC(),
Remember: false,
}); err != nil {
return err
}
client, err := auth.GetRegistry().ClientManager().GetConcreteClient(ctx, in.GetClientID())
if err != nil {
return err
}
// Set the session
if err := auth.GetRegistry().ConsentManager().CreateLoginRequest(
ctx,
&consent.LoginRequest{
Challenge: challenge,
Verifier: verifier,
CSRF: csrf,
Skip: false,
RequestedScope: in.GetScopes(),
RequestedAudience: in.GetAudiences(),
Subject: "",
Client: client,
RequestURL: iu.String(),
AuthenticatedAt: time.Time{},
RequestedAt: time.Now().UTC(),
SessionID: sessionID,
},
); err != nil {
return errors.WithStack(err)
}
out.Login = &pauth.ID{
Challenge: challenge,
Verifier: verifier,
CSRF: csrf,
}
return nil
}
func (h *Handler) AcceptLogin(ctx context.Context, in *pauth.AcceptLoginRequest, out *pauth.AcceptLoginResponse) error {
var p consent.HandledLoginRequest
p.Subject = in.Subject
p.Challenge = in.Challenge
p.RequestedAt = time.Now().UTC()
p.AuthenticatedAt = p.RequestedAt
_, err := auth.GetRegistry().ConsentManager().HandleLoginRequest(ctx, in.Challenge, &p)
if err != nil {
return err
}
return nil
}
func (h *Handler) GetConsent(ctx context.Context, in *pauth.GetConsentRequest, out *pauth.GetConsentResponse) error {
req, err := auth.GetRegistry().ConsentManager().GetConsentRequest(ctx, in.Challenge)
if err != nil {
return err
}
out.Challenge = req.Challenge
out.LoginSessionID = req.LoginSessionID
out.Subject = req.Subject
out.SubjectIdentifier = req.Subject
out.ClientID = req.Client.ClientID
return nil
}
func (h *Handler) CreateConsent(ctx context.Context, in *pauth.CreateConsentRequest, out *pauth.CreateConsentResponse) error {
// Set up csrf/challenge/verifier values
verifier := strings.Replace(uuid.New(), "-", "", -1)
challenge := strings.Replace(uuid.New(), "-", "", -1)
csrf := strings.Replace(uuid.New(), "-", "", -1)
login, err := auth.GetRegistry().ConsentManager().GetLoginRequest(ctx, in.LoginChallenge)
if err != nil {
return err
}
client, err := auth.GetRegistry().ClientManager().GetConcreteClient(ctx, login.Client.ClientID)
if err != nil {
return err
}
session, err := auth.GetRegistry().ConsentManager().VerifyAndInvalidateLoginRequest(ctx, login.Verifier)
if err != nil {
return err
}
if session.Error != nil {
return fmt.Errorf(session.Error.Name)
}
host, _ := servicecontext.HttpMetaFromGrpcContext(ctx, servicecontext.HttpMetaHost)
if session.RequestedAt.Add(auth.GetConfigurationProvider(host).ConsentRequestMaxAge()).Before(time.Now()) {
return errors.WithStack(fosite.ErrRequestUnauthorized.WithDebug("The login request has expired, please try again."))
}
if err := auth.GetRegistry().ConsentManager().ConfirmLoginSession(ctx, session.LoginRequest.SessionID, session.Subject, session.Remember); err != nil {
return err
}
// Set the session
if err := auth.GetRegistry().ConsentManager().CreateConsentRequest(
ctx,
&consent.ConsentRequest{
Challenge: challenge,
Verifier: verifier,
CSRF: csrf,
Skip: false,
RequestedScope: login.RequestedScope,
RequestedAudience: login.RequestedAudience,
Subject: session.Subject,
Client: client,
RequestURL: login.RequestURL,
LoginChallenge: login.Challenge,
LoginSessionID: login.SessionID,
AuthenticatedAt: time.Now().UTC(),
RequestedAt: time.Now().UTC(),
},
); err != nil {
return errors.WithStack(err)
}
out.Consent = &pauth.ID{
Challenge: challenge,
Verifier: verifier,
CSRF: csrf,
}
return nil
}
func (h *Handler) AcceptConsent(ctx context.Context, in *pauth.AcceptConsentRequest, out *pauth.AcceptConsentResponse) error {
var p consent.HandledConsentRequest
accessToken := make(map[string]interface{})
idToken := make(map[string]interface{})
for k, v := range in.GetAccessToken() {
accessToken[k] = v
}
for k, v := range in.GetIDToken() {
idToken[k] = v
}
p.Challenge = in.Challenge
p.RequestedAt = time.Now().UTC()
p.AuthenticatedAt = p.RequestedAt
p.Session = consent.NewConsentRequestSessionData()
p.Session.AccessToken = accessToken
p.Session.IDToken = idToken
p.GrantedScope = in.GetScopes()
p.GrantedAudience = in.GetAudiences()
_, err := auth.GetRegistry().ConsentManager().HandleConsentRequest(ctx, in.Challenge, &p)
if err != nil {
return err
}
return nil
}
func (h *Handler) CreateAuthCode(ctx context.Context, in *pauth.CreateAuthCodeRequest, out *pauth.CreateAuthCodeResponse) error {
values := url.Values{}
values.Set("client_id", in.GetClientID())
values.Set("redirect_uri", in.GetRedirectURI())
values.Set("response_type", "code")
values.Set("consent_verifier", in.GetConsent().GetVerifier())
values.Set("state", uuid.New())
req, err := http.NewRequest("POST", "", strings.NewReader(values.Encode()))
if err != nil {
return err
}
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
cookieSession, err := auth.GetRegistry().CookieStore().Get(req, "oauth2_consent_csrf")
if err != nil {
return err
}
cookieSession.Values["csrf"] = in.GetConsent().GetCSRF()
ar, err := auth.GetRegistry().OAuth2Provider().NewAuthorizeRequest(ctx, req)
if err != nil {
e := fosite.ErrorToRFC6749Error(err)
log.Logger(ctx).Error("Could not create authorize request", zap.Error(e))
return err
}
session, err := auth.GetRegistry().ConsentStrategy().HandleOAuth2AuthorizationRequest(http.ResponseWriter(nil), req, ar)
if errors.Cause(err) == consent.ErrAbortOAuth2Request {
// do nothing
return nil
} else if err != nil {
e := fosite.ErrorToRFC6749Error(err)
log.Logger(ctx).Error("Could not handle authorize request", zap.Error(e))
return err
}
for _, scope := range session.GrantedScope {
ar.GrantScope(scope)
}
for _, audience := range session.GrantedAudience {
ar.GrantAudience(audience)
}
openIDKeyID, err := auth.GetRegistry().OpenIDJWTStrategy().GetPublicKeyID(ctx)
if err != nil {
return err
}
var accessTokenKeyID string
host, _ := servicecontext.HttpMetaFromGrpcContext(ctx, servicecontext.HttpMetaHost)
configProvider := auth.GetConfigurationProvider(host)
if configProvider.AccessTokenStrategy() == "jwt" {
accessTokenKeyID, err = auth.GetRegistry().AccessTokenJWTStrategy().GetPublicKeyID(ctx)
if err != nil {
return err
}
}
ar.SetID(session.Challenge)
claims := &jwt.IDTokenClaims{
Subject: session.ConsentRequest.SubjectIdentifier,
Issuer: strings.TrimRight(configProvider.IssuerURL().String(), "/") + "/",
IssuedAt: time.Now().UTC(),
AuthTime: time.Now().UTC(),
RequestedAt: time.Now().UTC(),
Extra: session.Session.IDToken,
}
claims.Add("sid", session.ConsentRequest.LoginSessionID)
// done
response, err := auth.GetRegistry().OAuth2Provider().NewAuthorizeResponse(ctx, ar, &oauth2.Session{
DefaultSession: &openid.DefaultSession{
Claims: claims,
Headers: &jwt.Headers{Extra: map[string]interface{}{
"kid": openIDKeyID,
}},
Subject: session.ConsentRequest.Subject,
},
Extra: session.Session.AccessToken,
KID: accessTokenKeyID,
ClientID: ar.GetClient().GetID(),
ConsentChallenge: session.Challenge,
})
if err != nil {
e := fosite.ErrorToRFC6749Error(err)
log.Logger(ctx).Error("Could not create authorize response", zap.Error(e), zap.String("debug", e.Debug))
return err
}
out.Code = response.GetCode()
return nil
}
func (h *Handler) CreateLogout(ctx context.Context, in *pauth.CreateLogoutRequest, out *pauth.CreateLogoutResponse) error {
challenge := strings.Replace(uuid.New(), "-", "", -1)
host, _ := servicecontext.HttpMetaFromGrpcContext(ctx, servicecontext.HttpMetaHost)
// Set the session
if err := auth.GetRegistry().ConsentManager().CreateLogoutRequest(
ctx,
&consent.LogoutRequest{
RequestURL: in.RequestURL,
Challenge: challenge,
Subject: in.Subject,
SessionID: in.SessionID,
Verifier: uuid.New(),
RPInitiated: false,
PostLogoutRedirectURI: auth.GetConfigurationProvider(host).LogoutRedirectURL().String(),
},
); err != nil {
return errors.WithStack(err)
}
out.Logout = &pauth.ID{
Challenge: challenge,
}
return nil
}
func (h *Handler) AcceptLogout(ctx context.Context, in *pauth.AcceptLogoutRequest, out *pauth.AcceptLogoutResponse) error {
// Accept the logout
logout, err := auth.GetRegistry().ConsentManager().AcceptLogoutRequest(ctx, in.GetChallenge())
if err != nil {
return errors.WithStack(err)
}
// Validating directly the logout
if _, err := auth.GetRegistry().ConsentManager().VerifyAndInvalidateLogoutRequest(ctx, logout.Verifier); err != nil {
return errors.WithStack(err)
}
if err := auth.GetRegistry().ConsentManager().DeleteLoginSession(ctx, logout.SessionID); err != nil {
return errors.WithStack(err)
}
accessSignature := auth.GetRegistrySQL().OAuth2HMACStrategy().AccessTokenSignature(in.GetAccessToken())
refreshSignature := auth.GetRegistrySQL().OAuth2HMACStrategy().RefreshTokenSignature(in.GetRefreshToken())
if err := auth.GetRegistry().OAuth2Storage().DeleteAccessTokenSession(ctx, accessSignature); err != nil {
return errors.WithStack(err)
}
if err := auth.GetRegistry().OAuth2Storage().DeleteRefreshTokenSession(ctx, refreshSignature); err != nil {
return errors.WithStack(err)
}
if err := auth.GetRegistry().OAuth2Storage().DeleteOpenIDConnectSession(ctx, refreshSignature); err != nil {
return errors.WithStack(err)
}
return nil
}
// Verify checks if the token is valid for hydra
func (h *Handler) Verify(ctx context.Context, in *pauth.VerifyTokenRequest, out *pauth.VerifyTokenResponse) error {
session := oauth2.NewSession("")
tokenType, ar, err := auth.GetRegistry().OAuth2Provider().IntrospectToken(ctx, in.GetToken(), fosite.AccessToken, session)
if err != nil {
return err
}
if tokenType != fosite.AccessToken {
return errors.New("Only access tokens are allowed in the authorization header")
}
claims := ar.GetSession().(*oauth2.Session).IDTokenClaims()
b, err := json.Marshal(claims)
if err != nil {
return err
}
out.Success = true
out.Data = b
return nil
}
// PasswordCredentialsToken validates the login information and generates a token
func (h *Handler) PasswordCredentialsToken(ctx context.Context, in *pauth.PasswordCredentialsTokenRequest, out *pauth.PasswordCredentialsTokenResponse) error {
token, err := auth.LocalJWTVerifier().PasswordCredentialsToken(ctx, in.Username, in.Password)
if err != nil {
return err
}
out.AccessToken = token.AccessToken
out.IDToken = token.Extra("id_token").(string)
out.RefreshToken = token.RefreshToken
out.Expiry = token.Expiry.Unix()
return nil
}
// Exchange code for a proper token
func (h *Handler) Exchange(ctx context.Context, in *pauth.ExchangeRequest, out *pauth.ExchangeResponse) error {
session := oauth2.NewSession("")
values := url.Values{}
values.Set("client_id", config.DefaultOAuthClientID)
values.Set("grant_type", "authorization_code")
values.Set("code", in.Code)
values.Set("redirect_uri", config.GetDefaultSiteURL()+"/auth/callback")
req, err := http.NewRequest("POST", "", strings.NewReader(values.Encode()))
if err != nil {
return err
}
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
ar, err := auth.GetRegistry().OAuth2Provider().NewAccessRequest(ctx, req, session)
if err != nil {
return err
}
resp, err := auth.GetRegistry().OAuth2Provider().NewAccessResponse(ctx, ar)
if err != nil {
return err
}
out.AccessToken = resp.GetAccessToken()
out.IDToken = resp.GetExtra("id_token").(string)
out.RefreshToken = resp.GetExtra("refresh_token").(string)
out.Expiry = resp.GetExtra("expires_in").(int64)
return nil
}
// Refresh token
func (h *Handler) Refresh(ctx context.Context, in *pauth.RefreshTokenRequest, out *pauth.RefreshTokenResponse) error {
session := oauth2.NewSession("")
values := url.Values{}
values.Set("client_id", config.DefaultOAuthClientID)
values.Set("grant_type", "refresh_token")
values.Set("refresh_token", in.RefreshToken)
values.Set("response_type", "id_token token")
values.Set("redirect_uri", config.GetDefaultSiteURL()+"/auth/callback")
req, err := http.NewRequest("POST", "", strings.NewReader(values.Encode()))
if err != nil {
return err
}
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
ar, err := auth.GetRegistry().OAuth2Provider().NewAccessRequest(ctx, req, session)
if err != nil {
return err
}
resp, err := auth.GetRegistry().OAuth2Provider().NewAccessResponse(ctx, ar)
if err != nil {
return err
}
out.AccessToken = resp.GetAccessToken()
out.IDToken = resp.GetExtra("id_token").(string)
out.RefreshToken = resp.GetExtra("refresh_token").(string)
out.Expiry = resp.GetExtra("expires_in").(int64)
return nil
}
// Revoke adds token to revocation list and eventually clear RefreshToken as well (directly inside Dex)
func (h *Handler) Revoke(ctx context.Context, in *pauth.RevokeTokenRequest, out *pauth.RevokeTokenResponse) error {
accessSignature := auth.GetRegistrySQL().OAuth2HMACStrategy().AccessTokenSignature(in.GetToken().GetAccessToken())
refreshSignature := auth.GetRegistrySQL().OAuth2HMACStrategy().RefreshTokenSignature(in.GetToken().GetRefreshToken())
accessTokenSession, err := auth.GetRegistry().OAuth2Storage().GetAccessTokenSession(ctx, accessSignature, nil)
if err != nil {
return err
}
refreshTokenSession, err := auth.GetRegistry().OAuth2Storage().GetRefreshTokenSession(ctx, refreshSignature, nil)
if err != nil {
return err
}
if err := auth.GetRegistry().OAuth2Storage().RevokeAccessToken(ctx, accessTokenSession.GetID()); err != nil {
return err
}
if err := auth.GetRegistry().OAuth2Storage().RevokeRefreshToken(ctx, refreshTokenSession.GetID()); err != nil {
return err
}
return nil
}
// PruneTokens garbage collect expired IdTokens and Tokens
func (h *Handler) PruneTokens(ctx context.Context, in *pauth.PruneTokensRequest, out *pauth.PruneTokensResponse) error {
storage := auth.GetRegistry().OAuth2Storage()
err := storage.FlushInactiveAccessTokens(ctx, time.Now())
if err != nil {
return err
}
type client struct {
ID string `json:"client_id"`
MaxInactivity string `json:"revokeRefreshTokenAfterInactivity"`
}
var clients []client
if err := auth.GetConfigurationProvider().Clients().Scan(&clients); err != nil {
return err
}
for _, c := range clients {
if c.MaxInactivity == "" {
continue
}
duration, err := time.ParseDuration(c.MaxInactivity)
if err != nil {
return err
}
store, ok := auth.GetRegistry().OAuth2Storage().(*oauth2.FositeSQLStore)
if !ok {
continue
}
if res, err := store.DB.ExecContext(ctx, store.DB.Rebind("DELETE FROM hydra_oauth2_refresh WHERE client_id = ? AND requested_at < ?"), c.ID, time.Now().Add(-duration)); err == sql.ErrNoRows {
return nil
} else if err != nil {
return sqlcon.HandleError(err)
} else {
i, _ := res.RowsAffected()
out.Count = int32(i)
}
}
return nil
}