/
persister_consent.go
575 lines (488 loc) · 17.6 KB
/
persister_consent.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
package sql
import (
"context"
"database/sql"
"fmt"
"strings"
"time"
"github.com/gobuffalo/pop/v6"
"github.com/ory/x/sqlxx"
"github.com/ory/x/errorsx"
"github.com/pkg/errors"
"github.com/ory/fosite"
"github.com/ory/hydra/client"
"github.com/ory/hydra/consent"
"github.com/ory/hydra/flow"
"github.com/ory/hydra/x"
"github.com/ory/x/sqlcon"
)
var _ consent.Manager = &Persister{}
func (p *Persister) RevokeSubjectConsentSession(ctx context.Context, user string) error {
return p.transaction(ctx, p.revokeConsentSession("consent_challenge_id IS NOT NULL AND subject = ?", user))
}
func (p *Persister) RevokeSubjectClientConsentSession(ctx context.Context, user, client string) error {
return p.transaction(ctx, p.revokeConsentSession("consent_challenge_id IS NOT NULL AND subject = ? AND client_id = ?", user, client))
}
func (p *Persister) revokeConsentSession(whereStmt string, whereArgs ...interface{}) func(context.Context, *pop.Connection) error {
return func(ctx context.Context, c *pop.Connection) error {
fs := make([]*flow.Flow, 0)
if err := p.QueryWithNetwork(ctx).
Where(whereStmt, whereArgs...).
Select("consent_challenge_id").
All(&fs); err != nil {
if errors.Is(err, sql.ErrNoRows) {
return errorsx.WithStack(x.ErrNotFound)
}
return sqlcon.HandleError(err)
}
var count int
for _, f := range fs {
if err := p.RevokeAccessToken(ctx, f.ConsentChallengeID.String()); errors.Is(err, fosite.ErrNotFound) {
// do nothing
} else if err != nil {
return err
}
if err := p.RevokeRefreshToken(ctx, f.ConsentChallengeID.String()); errors.Is(err, fosite.ErrNotFound) {
// do nothing
} else if err != nil {
return err
}
localCount, err := c.RawQuery("DELETE FROM hydra_oauth2_flow WHERE consent_challenge_id = ? AND nid = ?", f.ConsentChallengeID, p.NetworkID(ctx)).ExecWithCount()
if err != nil {
if errors.Is(err, sql.ErrNoRows) {
return errorsx.WithStack(x.ErrNotFound)
}
return sqlcon.HandleError(err)
}
// If there are no sessions to revoke we should return an error to indicate to the caller
// that the request failed.
count += localCount
}
if count == 0 {
return errorsx.WithStack(x.ErrNotFound)
}
return nil
}
}
func (p *Persister) RevokeSubjectLoginSession(ctx context.Context, subject string) error {
err := p.QueryWithNetwork(ctx).Where("subject = ?", subject).Delete(&consent.LoginSession{})
if err != nil {
return sqlcon.HandleError(err)
}
// This confuses people, see https://github.com/ory/hydra/issues/1168
//
// count, _ := rows.RowsAffected()
// if count == 0 {
// return errorsx.WithStack(x.ErrNotFound)
// }
return nil
}
func (p *Persister) CreateForcedObfuscatedLoginSession(ctx context.Context, session *consent.ForcedObfuscatedLoginSession) error {
return p.transaction(ctx, func(ctx context.Context, c *pop.Connection) error {
nid := p.NetworkID(ctx)
if err := c.RawQuery(
"DELETE FROM hydra_oauth2_obfuscated_authentication_session WHERE nid = ? AND client_id = ? AND subject = ?",
nid,
session.ClientID,
session.Subject,
).Exec(); err != nil {
return sqlcon.HandleError(err)
}
return sqlcon.HandleError(c.RawQuery(
"INSERT INTO hydra_oauth2_obfuscated_authentication_session (nid, subject, client_id, subject_obfuscated) VALUES (?, ?, ?, ?)",
nid,
session.Subject,
session.ClientID,
session.SubjectObfuscated,
).Exec())
})
}
func (p *Persister) GetForcedObfuscatedLoginSession(ctx context.Context, client, obfuscated string) (*consent.ForcedObfuscatedLoginSession, error) {
var s consent.ForcedObfuscatedLoginSession
if err := p.Connection(ctx).Where(
"client_id = ? AND subject_obfuscated = ? AND nid = ?",
client,
obfuscated,
p.NetworkID(ctx),
).First(&s); errors.Is(err, sql.ErrNoRows) {
return nil, errorsx.WithStack(x.ErrNotFound)
} else if err != nil {
return nil, sqlcon.HandleError(err)
}
return &s, nil
}
// CreateConsentRequest configures fields that are introduced or changed in the
// consent request. It doesn't touch fields that would be copied from the login
// request.
func (p *Persister) CreateConsentRequest(ctx context.Context, req *consent.ConsentRequest) error {
c, err := p.Connection(ctx).RawQuery(`
UPDATE hydra_oauth2_flow
SET
state = ?,
consent_challenge_id = ?,
consent_skip = ?,
consent_verifier = ?,
consent_csrf = ?
WHERE login_challenge = ? AND nid = ?;
`,
flow.FlowStateConsentInitialized,
sqlxx.NullString(req.ID),
req.Skip,
req.Verifier,
req.CSRF,
req.LoginChallenge.String(),
p.NetworkID(ctx),
).ExecWithCount()
if err != nil {
return sqlcon.HandleError(err)
}
if c != 1 {
return errorsx.WithStack(x.ErrNotFound)
}
return nil
}
func (p *Persister) GetFlowByConsentChallenge(ctx context.Context, challenge string) (*flow.Flow, error) {
f := &flow.Flow{}
if err := sqlcon.HandleError(p.QueryWithNetwork(ctx).Where("consent_challenge_id = ?", challenge).First(f)); err != nil {
return nil, err
}
return f, nil
}
func (p *Persister) GetConsentRequest(ctx context.Context, challenge string) (*consent.ConsentRequest, error) {
f, err := p.GetFlowByConsentChallenge(ctx, challenge)
if err != nil {
if errors.Is(err, sqlcon.ErrNoRows) {
return nil, errorsx.WithStack(x.ErrNotFound)
}
return nil, err
}
return f.GetConsentRequest(), nil
}
func (p *Persister) CreateLoginRequest(ctx context.Context, req *consent.LoginRequest) error {
f := flow.NewFlow(req)
return sqlcon.HandleError(p.CreateWithNetwork(ctx, f))
}
func (p *Persister) GetFlow(ctx context.Context, login_challenge string) (*flow.Flow, error) {
var f flow.Flow
return &f, p.transaction(ctx, func(ctx context.Context, c *pop.Connection) error {
if err := p.QueryWithNetwork(ctx).Where("login_challenge = ?", login_challenge).First(&f); err != nil {
if errors.Is(err, sql.ErrNoRows) {
return errorsx.WithStack(x.ErrNotFound)
}
return sqlcon.HandleError(err)
}
return nil
})
}
func (p *Persister) GetLoginRequest(ctx context.Context, login_challenge string) (*consent.LoginRequest, error) {
var lr *consent.LoginRequest
return lr, p.transaction(ctx, func(ctx context.Context, c *pop.Connection) error {
var f flow.Flow
if err := p.QueryWithNetwork(ctx).Where("login_challenge = ?", login_challenge).First(&f); err != nil {
if errors.Is(err, sql.ErrNoRows) {
return errorsx.WithStack(x.ErrNotFound)
}
return sqlcon.HandleError(err)
}
lr = f.GetLoginRequest()
return nil
})
}
func (p *Persister) HandleConsentRequest(ctx context.Context, r *consent.HandledConsentRequest) (*consent.ConsentRequest, error) {
f := &flow.Flow{}
if err := sqlcon.HandleError(p.QueryWithNetwork(ctx).Where("consent_challenge_id = ?", r.ID).First(f)); errors.Is(err, sqlcon.ErrNoRows) {
return nil, err
}
if err := f.HandleConsentRequest(r); err != nil {
return nil, errorsx.WithStack(err)
}
if err := p.UpdateWithNetwork(ctx, f); err != nil {
return nil, sqlcon.HandleError(err)
}
return p.GetConsentRequest(ctx, r.ID)
}
func (p *Persister) VerifyAndInvalidateConsentRequest(ctx context.Context, verifier string) (*consent.HandledConsentRequest, error) {
var r consent.HandledConsentRequest
return &r, p.transaction(ctx, func(ctx context.Context, c *pop.Connection) error {
var f flow.Flow
if err := p.QueryWithNetwork(ctx).Where("consent_verifier = ?", verifier).First(&f); err != nil {
return sqlcon.HandleError(err)
}
if err := f.InvalidateConsentRequest(); err != nil {
return errorsx.WithStack(fosite.ErrInvalidRequest.WithDebug(err.Error()))
}
r = *f.GetHandledConsentRequest()
return p.UpdateWithNetwork(ctx, &f)
})
}
func (p *Persister) HandleLoginRequest(ctx context.Context, challenge string, r *consent.HandledLoginRequest) (lr *consent.LoginRequest, err error) {
return lr, p.transaction(ctx, func(ctx context.Context, c *pop.Connection) error {
f, err := p.GetFlow(ctx, challenge)
if err != nil {
return sqlcon.HandleError(err)
}
err = f.HandleLoginRequest(r)
if err != nil {
return err
}
err = p.UpdateWithNetwork(ctx, f)
if err != nil {
return sqlcon.HandleError(err)
}
lr, err = p.GetLoginRequest(ctx, challenge)
return sqlcon.HandleError(err)
})
}
func (p *Persister) VerifyAndInvalidateLoginRequest(ctx context.Context, verifier string) (*consent.HandledLoginRequest, error) {
var d consent.HandledLoginRequest
return &d, p.transaction(ctx, func(ctx context.Context, c *pop.Connection) error {
var f flow.Flow
if err := p.QueryWithNetwork(ctx).Where("login_verifier = ?", verifier).First(&f); err != nil {
return sqlcon.HandleError(err)
}
if err := f.InvalidateLoginRequest(); err != nil {
return errorsx.WithStack(fosite.ErrInvalidRequest.WithDebug(err.Error()))
}
d = f.GetHandledLoginRequest()
return sqlcon.HandleError(p.UpdateWithNetwork(ctx, &f))
})
}
func (p *Persister) GetRememberedLoginSession(ctx context.Context, id string) (*consent.LoginSession, error) {
var s consent.LoginSession
if err := p.QueryWithNetwork(ctx).Where("remember = TRUE").Find(&s, id); errors.Is(err, sql.ErrNoRows) {
return nil, errorsx.WithStack(x.ErrNotFound)
} else if err != nil {
return nil, sqlcon.HandleError(err)
}
return &s, nil
}
func (p *Persister) ConfirmLoginSession(ctx context.Context, id string, authenticatedAt time.Time, subject string, remember bool) error {
return sqlcon.HandleError(
p.UpdateWithNetwork(ctx, &consent.LoginSession{
ID: id,
NID: p.NetworkID(ctx),
AuthenticatedAt: sqlxx.NullTime(authenticatedAt),
Subject: subject,
Remember: remember,
}))
}
func (p *Persister) CreateLoginSession(ctx context.Context, session *consent.LoginSession) error {
return sqlcon.HandleError(p.CreateWithNetwork(ctx, session))
}
func (p *Persister) DeleteLoginSession(ctx context.Context, id string) error {
count, err := p.Connection(ctx).RawQuery("DELETE FROM hydra_oauth2_authentication_session WHERE id=? AND nid = ?", id, p.NetworkID(ctx)).ExecWithCount()
if count == 0 {
return errorsx.WithStack(x.ErrNotFound)
} else {
return sqlcon.HandleError(err)
}
}
func (p *Persister) FindGrantedAndRememberedConsentRequests(ctx context.Context, client, subject string) ([]consent.HandledConsentRequest, error) {
rs := make([]consent.HandledConsentRequest, 0)
return rs, p.transaction(ctx, func(ctx context.Context, c *pop.Connection) error {
f := &flow.Flow{}
if err := c.
Where(
strings.TrimSpace(fmt.Sprintf(`
(state = %d OR state = %d) AND
subject = ? AND
client_id = ? AND
consent_skip=FALSE AND
consent_error='{}' AND
consent_remember=TRUE AND
nid = ?`, flow.FlowStateConsentUsed, flow.FlowStateConsentUnused,
)),
subject, client, p.NetworkID(ctx)).
Order("requested_at DESC").
Limit(1).
First(f); err != nil {
if errors.Is(err, sql.ErrNoRows) {
return errorsx.WithStack(consent.ErrNoPreviousConsentFound)
}
return sqlcon.HandleError(err)
}
var err error
rs, err = p.filterExpiredConsentRequests(ctx, []consent.HandledConsentRequest{*f.GetHandledConsentRequest()})
return err
})
}
func (p *Persister) FindSubjectsGrantedConsentRequests(ctx context.Context, subject string, limit, offset int) ([]consent.HandledConsentRequest, error) {
var fs []flow.Flow
c := p.Connection(ctx)
if err := c.
Where(
strings.TrimSpace(fmt.Sprintf(`
(state = %d OR state = %d) AND
subject = ? AND
consent_skip=FALSE AND
consent_error='{}' AND
nid = ?`, flow.FlowStateConsentUsed, flow.FlowStateConsentUnused,
)),
subject, p.NetworkID(ctx)).
Order("requested_at DESC").
Paginate(offset/limit+1, limit).
All(&fs); err != nil {
if errors.Is(err, sql.ErrNoRows) {
return nil, errorsx.WithStack(consent.ErrNoPreviousConsentFound)
}
return nil, sqlcon.HandleError(err)
}
var rs []consent.HandledConsentRequest
for _, f := range fs {
rs = append(rs, *f.GetHandledConsentRequest())
}
return p.filterExpiredConsentRequests(ctx, rs)
}
func (p *Persister) CountSubjectsGrantedConsentRequests(ctx context.Context, subject string) (int, error) {
n, err := p.Connection(ctx).
Where(
strings.TrimSpace(fmt.Sprintf(`
(state = %d OR state = %d) AND
subject = ? AND
consent_skip=FALSE AND
consent_error='{}' AND
nid = ?`, flow.FlowStateConsentUsed, flow.FlowStateConsentUnused,
)),
subject, p.NetworkID(ctx)).
Count(&flow.Flow{})
return n, sqlcon.HandleError(err)
}
func (p *Persister) filterExpiredConsentRequests(ctx context.Context, requests []consent.HandledConsentRequest) ([]consent.HandledConsentRequest, error) {
var result []consent.HandledConsentRequest
for _, v := range requests {
if v.RememberFor > 0 && v.RequestedAt.Add(time.Duration(v.RememberFor)*time.Second).Before(time.Now().UTC()) {
continue
}
result = append(result, v)
}
if len(result) == 0 {
return nil, errorsx.WithStack(consent.ErrNoPreviousConsentFound)
}
return result, nil
}
func (p *Persister) ListUserAuthenticatedClientsWithFrontChannelLogout(ctx context.Context, subject, sid string) ([]client.Client, error) {
return p.listUserAuthenticatedClients(ctx, subject, sid, "front")
}
func (p *Persister) ListUserAuthenticatedClientsWithBackChannelLogout(ctx context.Context, subject, sid string) ([]client.Client, error) {
return p.listUserAuthenticatedClients(ctx, subject, sid, "back")
}
func (p *Persister) listUserAuthenticatedClients(ctx context.Context, subject, sid, channel string) ([]client.Client, error) {
var cs []client.Client
return cs, p.transaction(ctx, func(ctx context.Context, c *pop.Connection) error {
if err := c.RawQuery(
/* #nosec G201 - channel can either be "front" or "back" */
fmt.Sprintf(`
SELECT DISTINCT c.* FROM hydra_client as c
JOIN hydra_oauth2_flow as f ON (c.id = f.client_id)
WHERE
f.subject=? AND
c.%schannel_logout_uri!='' AND
c.%schannel_logout_uri IS NOT NULL AND
f.login_session_id = ? AND
f.nid = ? AND
c.nid = ?`,
channel,
channel,
),
subject,
sid,
p.NetworkID(ctx),
p.NetworkID(ctx),
).All(&cs); err != nil {
return sqlcon.HandleError(err)
}
return nil
})
}
func (p *Persister) CreateLogoutRequest(ctx context.Context, request *consent.LogoutRequest) error {
return errorsx.WithStack(p.CreateWithNetwork(ctx, request))
}
func (p *Persister) AcceptLogoutRequest(ctx context.Context, challenge string) (*consent.LogoutRequest, error) {
if err := p.Connection(ctx).RawQuery("UPDATE hydra_oauth2_logout_request SET accepted=true, rejected=false WHERE challenge=? AND nid = ?", challenge, p.NetworkID(ctx)).Exec(); err != nil {
return nil, sqlcon.HandleError(err)
}
return p.GetLogoutRequest(ctx, challenge)
}
func (p *Persister) RejectLogoutRequest(ctx context.Context, challenge string) error {
count, err := p.Connection(ctx).
RawQuery("UPDATE hydra_oauth2_logout_request SET rejected=true, accepted=false WHERE challenge=? AND nid = ?", challenge, p.NetworkID(ctx)).
ExecWithCount()
if count == 0 {
return errorsx.WithStack(x.ErrNotFound)
} else {
return errorsx.WithStack(err)
}
}
func (p *Persister) GetLogoutRequest(ctx context.Context, challenge string) (*consent.LogoutRequest, error) {
var lr consent.LogoutRequest
return &lr, sqlcon.HandleError(p.QueryWithNetwork(ctx).Where("challenge = ? AND rejected = FALSE", challenge).First(&lr))
}
func (p *Persister) VerifyAndInvalidateLogoutRequest(ctx context.Context, verifier string) (*consent.LogoutRequest, error) {
var lr consent.LogoutRequest
return &lr, p.transaction(ctx, func(ctx context.Context, c *pop.Connection) error {
if count, err := c.RawQuery(
"UPDATE hydra_oauth2_logout_request SET was_used=TRUE WHERE nid = ? AND verifier=? AND was_used=FALSE AND accepted=TRUE AND rejected=FALSE",
p.NetworkID(ctx),
verifier,
).ExecWithCount(); count == 0 && err == nil {
return errorsx.WithStack(x.ErrNotFound)
} else if err != nil {
return sqlcon.HandleError(err)
}
err := sqlcon.HandleError(p.QueryWithNetwork(ctx).Where("verifier=?", verifier).First(&lr))
if err != nil {
return err
}
return nil
})
}
func (p *Persister) FlushInactiveLoginConsentRequests(ctx context.Context, notAfter time.Time, limit int, batchSize int) error {
/* #nosec G201 table is static */
var f flow.Flow
// The value of notAfter should be the minimum between input parameter and request max expire based on its configured age
requestMaxExpire := time.Now().Add(-p.config.ConsentRequestMaxAge())
if requestMaxExpire.Before(notAfter) {
notAfter = requestMaxExpire
}
challenges := []string{}
queryFormat := `
SELECT login_challenge
FROM hydra_oauth2_flow
WHERE (
(state != ?)
OR (login_error IS NOT NULL AND login_error <> '{}' AND login_error <> '')
OR (consent_error IS NOT NULL AND consent_error <> '{}' AND consent_error <> '')
)
AND requested_at < ?
AND nid = ?
ORDER BY login_challenge
LIMIT %[1]d
`
// Select up to [limit] flows that can be safely deleted, i.e. flows that meet
// the following criteria:
// - flow.state is anything between FlowStateLoginInitialized and FlowStateConsentUnused (unhandled)
// - flow.login_error has valid error (login rejected)
// - flow.consent_error has valid error (consent rejected)
// AND timed-out
// - flow.requested_at < minimum of ttl.login_consent_request and notAfter
q := p.Connection(ctx).RawQuery(fmt.Sprintf(queryFormat, limit), flow.FlowStateConsentUsed, notAfter, p.NetworkID(ctx))
if err := q.All(&challenges); err == sql.ErrNoRows {
return errors.Wrap(fosite.ErrNotFound, "")
}
// Delete in batch consent requests and their references in cascade
for i := 0; i < len(challenges); i += batchSize {
j := i + batchSize
if j > len(challenges) {
j = len(challenges)
}
q := p.Connection(ctx).RawQuery(
fmt.Sprintf("DELETE FROM %s WHERE login_challenge in (?) AND nid = ?", (&f).TableName()),
challenges[i:j],
p.NetworkID(ctx),
)
if err := q.Exec(); err != nil {
return sqlcon.HandleError(err)
}
}
return nil
}