-
Notifications
You must be signed in to change notification settings - Fork 1.5k
/
Copy pathmanager_sql.go
462 lines (385 loc) · 13.2 KB
/
manager_sql.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
/*
* Copyright © 2015-2018 Aeneas Rekkas <aeneas+oss@aeneas.io>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @author Aeneas Rekkas <aeneas+oss@aeneas.io>
* @Copyright 2017-2018 Aeneas Rekkas <aeneas+oss@aeneas.io>
* @license Apache-2.0
*/
package consent
import (
"database/sql"
"fmt"
"strings"
"time"
"github.com/jmoiron/sqlx"
"github.com/ory/fosite"
"github.com/ory/hydra/client"
"github.com/ory/hydra/pkg"
"github.com/ory/sqlcon"
"github.com/pkg/errors"
"github.com/rubenv/sql-migrate"
)
type SQLManager struct {
db *sqlx.DB
c client.Manager
store pkg.FositeStorer
}
func NewSQLManager(db *sqlx.DB, c client.Manager, store pkg.FositeStorer) *SQLManager {
return &SQLManager{
db: db,
c: c,
store: store,
}
}
func (m *SQLManager) CreateSchemas() (int, error) {
migrate.SetTable("hydra_oauth2_authentication_consent_migration")
n, err := migrate.Exec(m.db.DB, m.db.DriverName(), migrations, migrate.Up)
if err != nil {
return 0, errors.Wrapf(err, "Could not migrate sql schema, applied %d migrations", n)
}
return n, nil
}
func (m *SQLManager) RevokeUserConsentSession(user string) error {
return m.revokeConsentSession(user, "")
}
func (m *SQLManager) RevokeUserClientConsentSession(user, client string) error {
return m.revokeConsentSession(user, client)
}
func (m *SQLManager) revokeConsentSession(user, client string) error {
args := []interface{}{user}
part := "r.subject=?"
if client != "" {
part += " AND r.client_id=?"
args = append(args, client)
}
var challenges = make([]string, 0)
if err := m.db.Select(&challenges, m.db.Rebind(fmt.Sprintf(
`SELECT r.challenge FROM hydra_oauth2_consent_request_handled as h
JOIN hydra_oauth2_consent_request as r ON r.challenge = h.challenge WHERE %s`,
part,
)), args...); err != nil {
if err == sql.ErrNoRows {
return errors.WithStack(pkg.ErrNotFound)
}
return sqlcon.HandleError(err)
}
for _, challenge := range challenges {
if err := m.store.RevokeAccessToken(nil, challenge); errors.Cause(err) == fosite.ErrNotFound {
// do nothing
} else if err != nil {
return err
}
if err := m.store.RevokeRefreshToken(nil, challenge); errors.Cause(err) == fosite.ErrNotFound {
// do nothing
} else if err != nil {
return err
}
}
var queries []string
switch m.db.DriverName() {
case "mysql":
queries = append(queries,
fmt.Sprintf(`DELETE h, r FROM hydra_oauth2_consent_request_handled as h
JOIN hydra_oauth2_consent_request as r ON r.challenge = h.challenge
WHERE %s`, part),
)
default:
queries = append(queries,
fmt.Sprintf(`DELETE FROM hydra_oauth2_consent_request_handled
WHERE challenge IN (SELECT r.challenge FROM hydra_oauth2_consent_request as r WHERE %s)`, part),
fmt.Sprintf(`DELETE FROM hydra_oauth2_consent_request as r WHERE %s`, part),
)
}
for _, q := range queries {
rows, err := m.db.Exec(m.db.Rebind(q), args...)
if err != nil {
if err == sql.ErrNoRows {
return errors.WithStack(pkg.ErrNotFound)
}
return sqlcon.HandleError(err)
}
if count, _ := rows.RowsAffected(); count == 0 {
return errors.WithStack(pkg.ErrNotFound)
}
}
return nil
}
func (m *SQLManager) RevokeUserAuthenticationSession(user string) error {
rows, err := m.db.Exec(
m.db.Rebind("DELETE FROM hydra_oauth2_authentication_session WHERE subject=?"),
user,
)
if err != nil {
if err == sql.ErrNoRows {
return errors.WithStack(pkg.ErrNotFound)
}
return sqlcon.HandleError(err)
}
count, _ := rows.RowsAffected()
if count == 0 {
return errors.WithStack(pkg.ErrNotFound)
}
return nil
}
func (m *SQLManager) CreateForcedObfuscatedAuthenticationSession(s *ForcedObfuscatedAuthenticationSession) error {
tx, err := m.db.Beginx()
if err != nil {
return sqlcon.HandleError(err)
}
if _, err := m.db.Exec(
m.db.Rebind("DELETE FROM hydra_oauth2_obfuscated_authentication_session WHERE client_id=? AND subject=?"),
s.ClientID,
s.Subject,
); err != nil {
if err := tx.Rollback(); err != nil {
return sqlcon.HandleError(err)
}
return sqlcon.HandleError(err)
}
if _, err := m.db.NamedExec(
"INSERT INTO hydra_oauth2_obfuscated_authentication_session (subject, client_id, subject_obfuscated) VALUES (:subject, :client_id, :subject_obfuscated)",
s,
); err != nil {
if err := tx.Rollback(); err != nil {
return sqlcon.HandleError(err)
}
return sqlcon.HandleError(err)
}
if err := tx.Commit(); err != nil {
return sqlcon.HandleError(err)
}
return nil
}
func (m *SQLManager) GetForcedObfuscatedAuthenticationSession(client, obfuscated string) (*ForcedObfuscatedAuthenticationSession, error) {
var d ForcedObfuscatedAuthenticationSession
if err := m.db.Get(&d, m.db.Rebind("SELECT * FROM hydra_oauth2_obfuscated_authentication_session WHERE client_id=? AND subject_obfuscated=?"), client, obfuscated); err != nil {
if err == sql.ErrNoRows {
return nil, errors.WithStack(pkg.ErrNotFound)
}
return nil, sqlcon.HandleError(err)
}
return &d, nil
}
func (m *SQLManager) CreateConsentRequest(c *ConsentRequest) error {
d, err := newSQLConsentRequest(c)
if err != nil {
return err
}
if _, err := m.db.NamedExec(fmt.Sprintf(
"INSERT INTO hydra_oauth2_consent_request (%s) VALUES (%s)",
strings.Join(sqlParamsConsentRequest, ", "),
":"+strings.Join(sqlParamsConsentRequest, ", :"),
), d); err != nil {
return sqlcon.HandleError(err)
}
return nil
}
func (m *SQLManager) GetConsentRequest(challenge string) (*ConsentRequest, error) {
var d sqlConsentRequest
if err := m.db.Get(&d, m.db.Rebind("SELECT * FROM hydra_oauth2_consent_request WHERE challenge=?"), challenge); err != nil {
if err == sql.ErrNoRows {
return nil, errors.WithStack(pkg.ErrNotFound)
}
return nil, sqlcon.HandleError(err)
}
c, err := m.c.GetConcreteClient(d.Client)
if err != nil {
return nil, err
}
return d.toConsentRequest(c)
}
func (m *SQLManager) CreateAuthenticationRequest(c *AuthenticationRequest) error {
d, err := newSQLAuthenticationRequest(c)
if err != nil {
return err
}
if _, err := m.db.NamedExec(fmt.Sprintf(
"INSERT INTO hydra_oauth2_authentication_request (%s) VALUES (%s)",
strings.Join(sqlParamsAuthenticationRequest, ", "),
":"+strings.Join(sqlParamsAuthenticationRequest, ", :"),
), d); err != nil {
return sqlcon.HandleError(err)
}
return nil
}
func (m *SQLManager) GetAuthenticationRequest(challenge string) (*AuthenticationRequest, error) {
var d sqlConsentRequest
if err := m.db.Get(&d, m.db.Rebind("SELECT * FROM hydra_oauth2_authentication_request WHERE challenge=?"), challenge); err != nil {
if err == sql.ErrNoRows {
return nil, errors.WithStack(pkg.ErrNotFound)
}
return nil, sqlcon.HandleError(err)
}
c, err := m.c.GetConcreteClient(d.Client)
if err != nil {
return nil, err
}
return d.toAuthenticationRequest(c)
}
func (m *SQLManager) HandleConsentRequest(challenge string, r *HandledConsentRequest) (*ConsentRequest, error) {
d, err := newSQLHandledConsentRequest(r)
if err != nil {
return nil, err
}
if _, err := m.db.NamedExec(fmt.Sprintf(
"INSERT INTO hydra_oauth2_consent_request_handled (%s) VALUES (%s)",
strings.Join(sqlParamsConsentRequestHandled, ", "),
":"+strings.Join(sqlParamsConsentRequestHandled, ", :"),
), d); err != nil {
return nil, sqlcon.HandleError(err)
}
return m.GetConsentRequest(challenge)
}
func (m *SQLManager) VerifyAndInvalidateConsentRequest(verifier string) (*HandledConsentRequest, error) {
var d sqlHandledConsentRequest
var challenge string
// This can be solved more elegantly with a join statement, but it works for now
if err := m.db.Get(&challenge, m.db.Rebind("SELECT challenge FROM hydra_oauth2_consent_request WHERE verifier=?"), verifier); err != nil {
return nil, sqlcon.HandleError(err)
}
if err := m.db.Get(&d, m.db.Rebind("SELECT * FROM hydra_oauth2_consent_request_handled WHERE challenge=?"), challenge); err != nil {
return nil, sqlcon.HandleError(err)
}
if d.WasUsed {
return nil, errors.WithStack(fosite.ErrInvalidRequest.WithDebug("Consent verifier has been used already"))
}
r, err := m.GetConsentRequest(challenge)
if err != nil {
return nil, err
}
if _, err := m.db.Exec(m.db.Rebind("UPDATE hydra_oauth2_consent_request_handled SET was_used=true WHERE challenge=?"), challenge); err != nil {
return nil, sqlcon.HandleError(err)
}
return d.toHandledConsentRequest(r)
}
func (m *SQLManager) HandleAuthenticationRequest(challenge string, r *HandledAuthenticationRequest) (*AuthenticationRequest, error) {
d, err := newSQLHandledAuthenticationRequest(r)
if err != nil {
return nil, err
}
if _, err := m.db.NamedExec(fmt.Sprintf(
"INSERT INTO hydra_oauth2_authentication_request_handled (%s) VALUES (%s)",
strings.Join(sqlParamsAuthenticationRequestHandled, ", "),
":"+strings.Join(sqlParamsAuthenticationRequestHandled, ", :"),
), d); err != nil {
return nil, sqlcon.HandleError(err)
}
return m.GetAuthenticationRequest(challenge)
}
func (m *SQLManager) VerifyAndInvalidateAuthenticationRequest(verifier string) (*HandledAuthenticationRequest, error) {
var d sqlHandledAuthenticationRequest
var challenge string
// This can be solved more elegantly with a join statement, but it works for now
if err := m.db.Get(&challenge, m.db.Rebind("SELECT challenge FROM hydra_oauth2_authentication_request WHERE verifier=?"), verifier); err != nil {
return nil, sqlcon.HandleError(err)
}
if err := m.db.Get(&d, m.db.Rebind("SELECT * FROM hydra_oauth2_authentication_request_handled WHERE challenge=?"), challenge); err != nil {
return nil, sqlcon.HandleError(err)
}
if d.WasUsed {
return nil, errors.WithStack(fosite.ErrInvalidRequest.WithDebug("Consent verifier has been used already"))
}
if _, err := m.db.Exec(m.db.Rebind("UPDATE hydra_oauth2_authentication_request_handled SET was_used=true WHERE challenge=?"), challenge); err != nil {
return nil, sqlcon.HandleError(err)
}
r, err := m.GetAuthenticationRequest(challenge)
if err != nil {
return nil, err
}
return d.toHandledAuthenticationRequest(r)
}
func (m *SQLManager) GetAuthenticationSession(id string) (*AuthenticationSession, error) {
var a AuthenticationSession
if err := m.db.Get(&a, m.db.Rebind("SELECT * FROM hydra_oauth2_authentication_session WHERE id=?"), id); err != nil {
if err == sql.ErrNoRows {
return nil, errors.WithStack(pkg.ErrNotFound)
}
return nil, sqlcon.HandleError(err)
}
return &a, nil
}
func (m *SQLManager) CreateAuthenticationSession(a *AuthenticationSession) error {
if _, err := m.db.NamedExec(fmt.Sprintf(
"INSERT INTO hydra_oauth2_authentication_session (%s) VALUES (%s)",
strings.Join(sqlParamsAuthSession, ", "),
":"+strings.Join(sqlParamsAuthSession, ", :"),
), a); err != nil {
return sqlcon.HandleError(err)
}
return nil
}
func (m *SQLManager) DeleteAuthenticationSession(id string) error {
if _, err := m.db.Exec(m.db.Rebind("DELETE FROM hydra_oauth2_authentication_session WHERE id=?"), id); err != nil {
return sqlcon.HandleError(err)
}
return nil
}
func (m *SQLManager) FindPreviouslyGrantedConsentRequests(client string, subject string) ([]HandledConsentRequest, error) {
var a []sqlHandledConsentRequest
if err := m.db.Select(&a, m.db.Rebind(`SELECT h.* FROM
hydra_oauth2_consent_request_handled as h
JOIN
hydra_oauth2_consent_request as r ON (h.challenge = r.challenge)
WHERE
r.subject=? AND r.client_id=? AND r.skip=FALSE
AND
(h.error='{}' AND h.remember=TRUE)
`), subject, client); err != nil {
if err == sql.ErrNoRows {
return nil, errors.WithStack(ErrNoPreviousConsentFound)
}
return nil, sqlcon.HandleError(err)
}
return m.resolveHandledConsentRequests(a)
}
func (m *SQLManager) FindPreviouslyGrantedConsentRequestsByUser(subject string, limit, offset int) ([]HandledConsentRequest, error) {
var a []sqlHandledConsentRequest
if err := m.db.Select(&a, m.db.Rebind(`SELECT h.* FROM
hydra_oauth2_consent_request_handled as h
JOIN
hydra_oauth2_consent_request as r ON (h.challenge = r.challenge)
WHERE
r.subject=? AND r.skip=FALSE
AND
(h.error='{}' AND h.remember=TRUE)
LIMIT ? OFFSET ?
`), subject, limit, offset); err != nil {
return nil, sqlcon.HandleError(err)
}
return m.resolveHandledConsentRequests(a)
}
func (m *SQLManager) resolveHandledConsentRequests(requests []sqlHandledConsentRequest) ([]HandledConsentRequest, error) {
var aa []HandledConsentRequest
for _, v := range requests {
r, err := m.GetConsentRequest(v.Challenge)
if err != nil {
return nil, err
} else if errors.Cause(err) == sqlcon.ErrNoRows {
return nil, errors.WithStack(ErrNoPreviousConsentFound)
}
if v.RememberFor > 0 && v.RequestedAt.Add(time.Duration(v.RememberFor)*time.Second).Before(time.Now().UTC()) {
continue
}
va, err := v.toHandledConsentRequest(r)
if err != nil {
return nil, err
}
aa = append(aa, *va)
}
if len(aa) == 0 {
return nil, errors.WithStack(ErrNoPreviousConsentFound)
}
return aa, nil
}