-
Notifications
You must be signed in to change notification settings - Fork 22
Expand file tree
/
Copy pathsql.go
More file actions
395 lines (331 loc) · 11.3 KB
/
sql.go
File metadata and controls
395 lines (331 loc) · 11.3 KB
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
package repository
import (
"context"
"encoding/json"
"errors"
"fmt"
"strings"
"time"
"github.com/ory/fosite"
"github.com/sigbit/mcp-auth-proxy/v2/pkg/models"
"gorm.io/driver/mysql"
"gorm.io/driver/postgres"
"gorm.io/driver/sqlite"
"gorm.io/gorm"
"gorm.io/gorm/clause"
)
type sqlRepository struct {
db *gorm.DB
}
type authorizeCodeSession struct {
Code string `gorm:"primaryKey;size:512"`
Request []byte `gorm:"not null"`
CreatedAt time.Time
UpdatedAt time.Time
}
type accessTokenSession struct {
Signature string `gorm:"primaryKey;size:512"`
Request []byte `gorm:"not null"`
CreatedAt time.Time
UpdatedAt time.Time
}
type refreshTokenSession struct {
Signature string `gorm:"primaryKey;size:512"`
AccessSignature string `gorm:"size:512"`
Request []byte `gorm:"not null"`
CreatedAt time.Time
UpdatedAt time.Time
}
type clientRecord struct {
ID string `gorm:"primaryKey;size:512"`
Client []byte `gorm:"not null"`
CreatedAt time.Time
UpdatedAt time.Time
}
type pkceRequestSession struct {
Signature string `gorm:"primaryKey;size:512"`
Request []byte `gorm:"not null"`
CreatedAt time.Time
UpdatedAt time.Time
}
type authorizeRequestRecord struct {
RequestID string `gorm:"primaryKey;size:512"`
Request []byte `gorm:"not null"`
CreatedAt time.Time
UpdatedAt time.Time
}
func NewSQLRepository(driver string, dsn string) (Repository, error) {
if driver == "" {
return nil, fmt.Errorf("driver must not be empty")
}
if dsn == "" {
return nil, fmt.Errorf("dsn must not be empty")
}
var dialector gorm.Dialector
switch strings.ToLower(driver) {
case "sqlite":
dialector = sqlite.Open(dsn)
case "postgres", "postgresql":
dialector = postgres.Open(dsn)
case "mysql":
dialector = mysql.Open(dsn)
default:
return nil, fmt.Errorf("unsupported driver: %s", driver)
}
db, err := gorm.Open(dialector, &gorm.Config{})
if err != nil {
return nil, fmt.Errorf("failed to connect database: %w", err)
}
if err := db.AutoMigrate(
&authorizeCodeSession{},
&accessTokenSession{},
&refreshTokenSession{},
&clientRecord{},
&pkceRequestSession{},
&authorizeRequestRecord{},
); err != nil {
return nil, fmt.Errorf("failed to migrate schema: %w", err)
}
return &sqlRepository{db: db}, nil
}
func (r *sqlRepository) CreateAuthorizeCodeSession(ctx context.Context, code string, fositeReq fosite.Requester) error {
data, err := marshalRequest(fositeReq)
if err != nil {
return err
}
session := authorizeCodeSession{
Code: code,
Request: data,
}
return r.db.WithContext(ctx).
Clauses(clause.OnConflict{UpdateAll: true}).
Create(&session).Error
}
func (r *sqlRepository) GetAuthorizeCodeSession(ctx context.Context, code string, sess fosite.Session) (fosite.Requester, error) {
var session authorizeCodeSession
if err := r.db.WithContext(ctx).First(&session, "code = ?", code).Error; err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
return nil, fosite.ErrNotFound
}
return nil, fmt.Errorf("failed to load authorize code session: %w", err)
}
return unmarshalRequest(session.Request, sess)
}
func (r *sqlRepository) InvalidateAuthorizeCodeSession(ctx context.Context, code string) error {
return r.db.WithContext(ctx).Delete(&authorizeCodeSession{}, "code = ?", code).Error
}
func (r *sqlRepository) CreateAccessTokenSession(ctx context.Context, signature string, fositeReq fosite.Requester) error {
data, err := marshalRequest(fositeReq)
if err != nil {
return err
}
session := accessTokenSession{
Signature: signature,
Request: data,
}
return r.db.WithContext(ctx).
Clauses(clause.OnConflict{UpdateAll: true}).
Create(&session).Error
}
func (r *sqlRepository) GetAccessTokenSession(ctx context.Context, signature string, sess fosite.Session) (fosite.Requester, error) {
var session accessTokenSession
if err := r.db.WithContext(ctx).First(&session, "signature = ?", signature).Error; err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
return nil, fosite.ErrNotFound
}
return nil, fmt.Errorf("failed to load access token session: %w", err)
}
return unmarshalRequest(session.Request, sess)
}
func (r *sqlRepository) DeleteAccessTokenSession(ctx context.Context, signature string) error {
return r.db.WithContext(ctx).Delete(&accessTokenSession{}, "signature = ?", signature).Error
}
func (r *sqlRepository) CreateRefreshTokenSession(ctx context.Context, signature string, accessSignature string, req fosite.Requester) error {
data, err := marshalRequest(req)
if err != nil {
return err
}
session := refreshTokenSession{
Signature: signature,
AccessSignature: accessSignature,
Request: data,
}
return r.db.WithContext(ctx).
Clauses(clause.OnConflict{UpdateAll: true}).
Create(&session).Error
}
func (r *sqlRepository) GetRefreshTokenSession(ctx context.Context, signature string, sess fosite.Session) (fosite.Requester, error) {
var session refreshTokenSession
if err := r.db.WithContext(ctx).First(&session, "signature = ?", signature).Error; err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
return nil, fosite.ErrNotFound
}
return nil, fmt.Errorf("failed to load refresh token session: %w", err)
}
return unmarshalRequest(session.Request, sess)
}
func (r *sqlRepository) DeleteRefreshTokenSession(ctx context.Context, signature string) error {
return r.db.WithContext(ctx).Delete(&refreshTokenSession{}, "signature = ?", signature).Error
}
func (r *sqlRepository) RotateRefreshToken(ctx context.Context, requestID string, signature string) error {
var session refreshTokenSession
if err := r.db.WithContext(ctx).First(&session, "signature = ?", signature).Error; err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
return fosite.ErrNotFound
}
return fmt.Errorf("failed to load refresh token session: %w", err)
}
var req models.Request
if err := json.Unmarshal(session.Request, &req); err != nil {
return fmt.Errorf("failed to decode refresh token session: %w", err)
}
req.RotatedAt = time.Now().UTC()
data, err := json.Marshal(req)
if err != nil {
return fmt.Errorf("failed to encode refresh token session: %w", err)
}
return r.db.WithContext(ctx).
Model(&refreshTokenSession{}).
Where("signature = ?", signature).
Update("request", data).Error
}
func (r *sqlRepository) RevokeRefreshToken(ctx context.Context, requestID string) error {
return r.db.WithContext(ctx).Delete(&refreshTokenSession{}, "signature = ?", requestID).Error
}
func (r *sqlRepository) RevokeAccessToken(ctx context.Context, requestID string) error {
return r.db.WithContext(ctx).Delete(&accessTokenSession{}, "signature = ?", requestID).Error
}
func (r *sqlRepository) RegisterClient(ctx context.Context, fositeClient fosite.Client) error {
data, err := marshalClient(fositeClient)
if err != nil {
return err
}
record := clientRecord{
ID: fositeClient.GetID(),
Client: data,
}
return r.db.WithContext(ctx).
Clauses(clause.OnConflict{UpdateAll: true}).
Create(&record).Error
}
func (r *sqlRepository) GetClient(ctx context.Context, id string) (fosite.Client, error) {
var record clientRecord
if err := r.db.WithContext(ctx).First(&record, "id = ?", id).Error; err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
return nil, fosite.ErrNotFound
}
return nil, fmt.Errorf("failed to load client: %w", err)
}
return unmarshalClient(record.Client)
}
func (r *sqlRepository) ClientAssertionJWTValid(ctx context.Context, jti string) error {
return errors.New("not implemented")
}
func (r *sqlRepository) SetClientAssertionJWT(ctx context.Context, jti string, exp time.Time) error {
return errors.New("not implemented")
}
func (r *sqlRepository) CreatePKCERequestSession(ctx context.Context, signature string, req fosite.Requester) error {
data, err := marshalRequest(req)
if err != nil {
return err
}
session := pkceRequestSession{
Signature: signature,
Request: data,
}
return r.db.WithContext(ctx).
Clauses(clause.OnConflict{UpdateAll: true}).
Create(&session).Error
}
func (r *sqlRepository) GetPKCERequestSession(ctx context.Context, signature string, sess fosite.Session) (fosite.Requester, error) {
var session pkceRequestSession
if err := r.db.WithContext(ctx).First(&session, "signature = ?", signature).Error; err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
return nil, fosite.ErrNotFound
}
return nil, fmt.Errorf("failed to load pkce request session: %w", err)
}
return unmarshalRequest(session.Request, sess)
}
func (r *sqlRepository) DeletePKCERequestSession(ctx context.Context, signature string) error {
return r.db.WithContext(ctx).Delete(&pkceRequestSession{}, "signature = ?", signature).Error
}
func (r *sqlRepository) CreateAuthorizeRequest(ctx context.Context, fositeAR fosite.AuthorizeRequester) error {
data, err := marshalAuthorizeRequest(fositeAR)
if err != nil {
return err
}
record := authorizeRequestRecord{
RequestID: fositeAR.GetID(),
Request: data,
}
return r.db.WithContext(ctx).
Clauses(clause.OnConflict{UpdateAll: true}).
Create(&record).Error
}
func (r *sqlRepository) GetAuthorizeRequest(ctx context.Context, requestID string) (fosite.AuthorizeRequester, error) {
var record authorizeRequestRecord
if err := r.db.WithContext(ctx).First(&record, "request_id = ?", requestID).Error; err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
return nil, fosite.ErrNotFound
}
return nil, fmt.Errorf("failed to load authorize request: %w", err)
}
return unmarshalAuthorizeRequest(record.Request)
}
func (r *sqlRepository) DeleteAuthorizeRequest(ctx context.Context, requestID string) error {
return r.db.WithContext(ctx).Delete(&authorizeRequestRecord{}, "request_id = ?", requestID).Error
}
func (r *sqlRepository) Close() error {
sqlDB, err := r.db.DB()
if err != nil {
return fmt.Errorf("failed to get sql db: %w", err)
}
return sqlDB.Close()
}
func marshalRequest(req fosite.Requester) ([]byte, error) {
data, err := json.Marshal(models.FromFositeReq(req))
if err != nil {
return nil, fmt.Errorf("failed to marshal request: %w", err)
}
return data, nil
}
func unmarshalRequest(data []byte, sess fosite.Session) (fosite.Requester, error) {
var req models.Request
if err := json.Unmarshal(data, &req); err != nil {
return nil, fmt.Errorf("failed to unmarshal request: %w", err)
}
fositeReq := req.ToFositeReq()
if err := restoreSession(fositeReq, req.SessionData, sess); err != nil {
return nil, err
}
return fositeReq, nil
}
func marshalClient(client fosite.Client) ([]byte, error) {
data, err := json.Marshal(models.FromFositeClient(client))
if err != nil {
return nil, fmt.Errorf("failed to marshal client: %w", err)
}
return data, nil
}
func unmarshalClient(data []byte) (fosite.Client, error) {
var client models.Client
if err := json.Unmarshal(data, &client); err != nil {
return nil, fmt.Errorf("failed to unmarshal client: %w", err)
}
return client.ToFositeClient(), nil
}
func marshalAuthorizeRequest(req fosite.AuthorizeRequester) ([]byte, error) {
data, err := json.Marshal(models.FromFositeAuthorizeRequest(req))
if err != nil {
return nil, fmt.Errorf("failed to marshal authorize request: %w", err)
}
return data, nil
}
func unmarshalAuthorizeRequest(data []byte) (fosite.AuthorizeRequester, error) {
var req models.AuthorizeRequest
if err := json.Unmarshal(data, &req); err != nil {
return nil, fmt.Errorf("failed to unmarshal authorize request: %w", err)
}
return req.ToFositeAuthorizeRequest(), nil
}