-
Notifications
You must be signed in to change notification settings - Fork 402
/
apikeys.go
469 lines (390 loc) · 14.3 KB
/
apikeys.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
// Copyright (C) 2019 Storj Labs, Inc.
// See LICENSE for copying information.
package satellitedb
import (
"context"
"database/sql"
"errors"
"strings"
"time"
"github.com/zeebo/errs"
"storj.io/common/macaroon"
"storj.io/common/uuid"
"storj.io/storj/satellite/console"
"storj.io/storj/satellite/satellitedb/dbx"
"storj.io/storj/shared/dbutil/pgutil"
"storj.io/storj/shared/lrucache"
)
// ensures that apikeys implements console.APIKeys.
var _ console.APIKeys = (*apikeys)(nil)
type projectApiKeyRow = dbx.ApiKey_Project_PublicId_Project_RateLimit_Project_BurstLimit_Project_RateLimitHead_Project_BurstLimitHead_Project_RateLimitGet_Project_BurstLimitGet_Project_RateLimitPut_Project_BurstLimitPut_Project_RateLimitList_Project_BurstLimitList_Project_RateLimitDel_Project_BurstLimitDel_Project_SegmentLimit_Project_UsageLimit_Project_BandwidthLimit_Project_UserSpecifiedUsageLimit_Project_UserSpecifiedBandwidthLimit_Row
// apikeys is an implementation of satellite.APIKeys.
type apikeys struct {
db dbx.DriverMethods
lru *lrucache.ExpiringLRUOf[*projectApiKeyRow]
}
func (keys *apikeys) GetPagedByProjectID(ctx context.Context, projectID uuid.UUID, cursor console.APIKeyCursor, ignoredNamePrefix string) (page *console.APIKeyPage, err error) {
defer mon.Task()(&ctx)(&err)
search := "%" + strings.ReplaceAll(cursor.Search, " ", "%") + "%"
if cursor.Limit == 0 {
return nil, console.ErrAPIKeyRequest.New("limit cannot be 0")
}
if cursor.Page == 0 {
return nil, console.ErrAPIKeyRequest.New("page cannot be 0")
}
page = &console.APIKeyPage{
Search: cursor.Search,
Limit: cursor.Limit,
Offset: uint64((cursor.Page - 1) * cursor.Limit),
Order: cursor.Order,
OrderDirection: cursor.OrderDirection,
}
countQuery := keys.db.Rebind(`
SELECT COUNT(*)
FROM api_keys ak
WHERE ak.project_id = ?
AND lower(ak.name) LIKE ?
`)
ignorePrefixClause := ""
if ignoredNamePrefix != "" {
ignorePrefixClause = "AND ak.name NOT LIKE '" + ignoredNamePrefix + "%' "
countQuery += ignorePrefixClause
}
countRow := keys.db.QueryRowContext(ctx,
countQuery,
projectID[:],
strings.ToLower(search),
)
err = countRow.Scan(&page.TotalCount)
if err != nil {
return nil, err
}
if page.TotalCount == 0 {
return page, nil
}
if page.Offset > page.TotalCount-1 {
return nil, console.ErrAPIKeyRequest.New("page is out of range")
}
repoundQuery := keys.db.Rebind(`
SELECT ak.id, ak.project_id, ak.name, ak.user_agent, ak.created_at, ak.version, p.public_id
FROM api_keys ak, projects p
WHERE ak.project_id = ?
AND ak.project_id = p.id
AND lower(ak.name) LIKE ?
` + ignorePrefixClause + apikeySortClause(cursor.Order, page.OrderDirection) + `
LIMIT ? OFFSET ?`)
rows, err := keys.db.QueryContext(ctx,
repoundQuery,
projectID[:],
strings.ToLower(search),
page.Limit,
page.Offset)
if err != nil {
return nil, err
}
defer func() { err = errs.Combine(err, rows.Close()) }()
var apiKeys []console.APIKeyInfo
for rows.Next() {
ak := console.APIKeyInfo{}
err = rows.Scan(&ak.ID, &ak.ProjectID, &ak.Name, &ak.UserAgent, &ak.CreatedAt, &ak.Version, &ak.ProjectPublicID)
if err != nil {
return nil, err
}
apiKeys = append(apiKeys, ak)
}
page.APIKeys = apiKeys
page.Order = cursor.Order
page.PageCount = uint(page.TotalCount / uint64(cursor.Limit))
if page.TotalCount%uint64(cursor.Limit) != 0 {
page.PageCount++
}
page.CurrentPage = cursor.Page
err = rows.Err()
if err != nil {
return nil, err
}
return page, err
}
// Get implements satellite.APIKeys.
func (keys *apikeys) Get(ctx context.Context, id uuid.UUID) (_ *console.APIKeyInfo, err error) {
defer mon.Task()(&ctx)(&err)
dbKey, err := keys.db.Get_ApiKey_Project_PublicId_By_ApiKey_Id(ctx, dbx.ApiKey_Id(id[:]))
if err != nil {
return nil, err
}
return fromDBXApiKeyProjectPublicIdRow(ctx, dbKey)
}
// GetByHead implements satellite.APIKeys.
func (keys *apikeys) GetByHead(ctx context.Context, head []byte) (_ *console.APIKeyInfo, err error) {
defer mon.Task()(&ctx)(&err)
dbKey, err := keys.lru.Get(ctx, string(head), func() (*dbx.ApiKey_Project_PublicId_Project_RateLimit_Project_BurstLimit_Project_RateLimitHead_Project_BurstLimitHead_Project_RateLimitGet_Project_BurstLimitGet_Project_RateLimitPut_Project_BurstLimitPut_Project_RateLimitList_Project_BurstLimitList_Project_RateLimitDel_Project_BurstLimitDel_Project_SegmentLimit_Project_UsageLimit_Project_BandwidthLimit_Project_UserSpecifiedUsageLimit_Project_UserSpecifiedBandwidthLimit_Row, error) {
return keys.db.Get_ApiKey_Project_PublicId_Project_RateLimit_Project_BurstLimit_Project_RateLimitHead_Project_BurstLimitHead_Project_RateLimitGet_Project_BurstLimitGet_Project_RateLimitPut_Project_BurstLimitPut_Project_RateLimitList_Project_BurstLimitList_Project_RateLimitDel_Project_BurstLimitDel_Project_SegmentLimit_Project_UsageLimit_Project_BandwidthLimit_Project_UserSpecifiedUsageLimit_Project_UserSpecifiedBandwidthLimit_By_ApiKey_Head(ctx, dbx.ApiKey_Head(head))
})
if err != nil {
return nil, err
}
return fromDBXApiKey_ApiKey_Project_PublicId_Project_RateLimit_Project_BurstLimit_Project_RateLimitHead_Project_BurstLimitHead_Project_RateLimitGet_Project_BurstLimitGet_Project_RateLimitPut_Project_BurstLimitPut_Project_RateLimitList_Project_BurstLimitList_Project_RateLimitDel_Project_BurstLimitDel_Project_SegmentLimit_Project_UsageLimit_Project_BandwidthLimit_Project_UserSpecifiedUsageLimit_Project_UserSpecifiedBandwidthLimit_Row(ctx, dbKey)
}
// GetByNameAndProjectID implements satellite.APIKeys.
func (keys *apikeys) GetByNameAndProjectID(ctx context.Context, name string, projectID uuid.UUID) (_ *console.APIKeyInfo, err error) {
defer mon.Task()(&ctx)(&err)
dbKey, err := keys.db.Get_ApiKey_Project_PublicId_By_ApiKey_Name_And_ApiKey_ProjectId(ctx,
dbx.ApiKey_Name(name),
dbx.ApiKey_ProjectId(projectID[:]))
if err != nil {
return nil, err
}
return fromDBXApiKeyProjectPublicIdRow(ctx, dbKey)
}
// GetAllNamesByProjectID implements satellite.APIKeys.
func (keys *apikeys) GetAllNamesByProjectID(ctx context.Context, projectID uuid.UUID) ([]string, error) {
var err error
defer mon.Task()(&ctx)(&err)
query := keys.db.Rebind(`
SELECT ak.name
FROM api_keys ak
WHERE ak.project_id = ?
` + apikeySortClause(console.KeyName, console.Ascending),
)
rows, err := keys.db.QueryContext(ctx, query, projectID[:])
if err != nil {
return nil, err
}
defer func() { err = errs.Combine(err, rows.Close()) }()
names := []string{}
for rows.Next() {
var name string
err = rows.Scan(&name)
if err != nil {
return nil, err
}
names = append(names, name)
}
err = rows.Err()
if err != nil {
return nil, err
}
return names, nil
}
// Create implements satellite.APIKeys.
func (keys *apikeys) Create(ctx context.Context, head []byte, info console.APIKeyInfo) (_ *console.APIKeyInfo, err error) {
defer mon.Task()(&ctx)(&err)
id, err := uuid.New()
if err != nil {
return nil, err
}
optional := dbx.ApiKey_Create_Fields{
Version: dbx.ApiKey_Version(uint(info.Version)),
}
if info.UserAgent != nil {
optional.UserAgent = dbx.ApiKey_UserAgent(info.UserAgent)
}
if !info.CreatedBy.IsZero() {
optional.CreatedBy = dbx.ApiKey_CreatedBy(info.CreatedBy[:])
}
_, err = keys.db.Create_ApiKey(
ctx,
dbx.ApiKey_Id(id[:]),
dbx.ApiKey_ProjectId(info.ProjectID[:]),
dbx.ApiKey_Head(head),
dbx.ApiKey_Name(info.Name),
dbx.ApiKey_Secret(info.Secret),
optional,
)
if err != nil {
return nil, err
}
return keys.Get(ctx, id)
}
// Update implements satellite.APIKeys.
func (keys *apikeys) Update(ctx context.Context, key console.APIKeyInfo) (err error) {
defer mon.Task()(&ctx)(&err)
return keys.db.UpdateNoReturn_ApiKey_By_Id(
ctx,
dbx.ApiKey_Id(key.ID[:]),
dbx.ApiKey_Update_Fields{
Name: dbx.ApiKey_Name(key.Name),
},
)
}
// Delete implements satellite.APIKeys.
func (keys *apikeys) Delete(ctx context.Context, id uuid.UUID) (err error) {
defer mon.Task()(&ctx)(&err)
_, err = keys.db.Delete_ApiKey_By_Id(ctx, dbx.ApiKey_Id(id[:]))
return err
}
// DeleteMultiple implements satellite.APIKeys.
func (keys *apikeys) DeleteMultiple(ctx context.Context, ids []uuid.UUID) (err error) {
defer mon.Task()(&ctx)(&err)
_, err = keys.db.ExecContext(ctx, `DELETE FROM api_keys WHERE id = ANY($1)`, pgutil.UUIDArray(ids))
if errors.Is(err, sql.ErrNoRows) {
err = nil
}
return err
}
// DeleteAllByProjectID deletes all APIKeyInfos from store by given projectID.
func (keys *apikeys) DeleteAllByProjectID(ctx context.Context, id uuid.UUID) (err error) {
defer mon.Task()(&ctx)(&err)
_, err = keys.db.Delete_ApiKey_By_ProjectId(ctx, dbx.ApiKey_ProjectId(id[:]))
return err
}
// DeleteExpiredByNamePrefix deletes expired APIKeyInfo from store by key name prefix.
func (keys *apikeys) DeleteExpiredByNamePrefix(ctx context.Context, lifetime time.Duration, prefix string, asOfSystemTimeInterval time.Duration, pageSize int) (err error) {
defer mon.Task()(&ctx)(&err)
if pageSize <= 0 {
return Error.New("expected page size to be positive; got %d", pageSize)
}
type keyInfo struct {
id uuid.UUID
createdAt time.Time
}
var pageCursor uuid.UUID
var toBeDeleted []uuid.UUID
found := make([]keyInfo, pageSize)
aost := keys.db.AsOfSystemInterval(asOfSystemTimeInterval)
now := time.Now()
cursorQuery := `
SELECT id FROM api_keys
` + aost + `
WHERE id > $1 AND api_keys.name LIKE
'` + prefix + `%'
ORDER BY id LIMIT 1
`
selectQuery := `
SELECT id, created_at FROM api_keys
` + aost + `
WHERE id >= $1 AND api_keys.name LIKE
'` + prefix + `%'
ORDER BY id LIMIT $2
`
for {
// Select the ID beginning this page of records
err = keys.db.QueryRowContext(ctx, cursorQuery, pageCursor).Scan(&pageCursor)
if err != nil {
if errors.Is(err, sql.ErrNoRows) {
return nil
}
return Error.Wrap(err)
}
// Select page of records
rows, err := keys.db.QueryContext(ctx, selectQuery, pageCursor, pageSize)
if err != nil {
return Error.Wrap(err)
}
var i int
for i = 0; rows.Next(); i++ {
key := keyInfo{}
err = rows.Scan(&key.id, &key.createdAt)
if err != nil {
return Error.Wrap(err)
}
found[i] = key
if now.After(key.createdAt.Add(lifetime)) {
toBeDeleted = append(toBeDeleted, key.id)
}
}
if err = errs.Combine(rows.Err(), rows.Close()); err != nil {
return Error.Wrap(err)
}
// Delete all expired keys in the page
if len(toBeDeleted) != 0 {
_, err = keys.db.ExecContext(ctx, `DELETE FROM api_keys WHERE id = ANY($1)`, pgutil.UUIDArray(toBeDeleted))
if err != nil {
return Error.Wrap(err)
}
}
if i < pageSize {
return nil
}
// Advance the cursor to the next page
pageCursor = found[i-1].id
}
}
func apiKeyToAPIKeyInfo(ctx context.Context, key *dbx.ApiKey) (_ *console.APIKeyInfo, err error) {
defer mon.Task()(&ctx)(&err)
id, err := uuid.FromBytes(key.Id)
if err != nil {
return nil, err
}
projectID, err := uuid.FromBytes(key.ProjectId)
if err != nil {
return nil, err
}
var createdBy uuid.UUID
if key.CreatedBy != nil {
createdBy, err = uuid.FromBytes(key.CreatedBy)
if err != nil {
return nil, err
}
}
result := &console.APIKeyInfo{
ID: id,
ProjectID: projectID,
CreatedBy: createdBy,
Name: key.Name,
CreatedAt: key.CreatedAt,
Head: key.Head,
Secret: key.Secret,
Version: macaroon.APIKeyVersion(key.Version),
}
if key.UserAgent != nil {
result.UserAgent = key.UserAgent
}
return result, nil
}
func fromDBXApiKeyProjectPublicIdRow(ctx context.Context, row *dbx.ApiKey_Project_PublicId_Row) (_ *console.APIKeyInfo, err error) {
defer mon.Task()(&ctx)(&err)
result, err := apiKeyToAPIKeyInfo(ctx, &row.ApiKey)
if err != nil {
return nil, err
}
result.ProjectPublicID, err = uuid.FromBytes(row.Project_PublicId)
if err != nil {
return nil, err
}
return result, nil
}
func fromDBXApiKey_ApiKey_Project_PublicId_Project_RateLimit_Project_BurstLimit_Project_RateLimitHead_Project_BurstLimitHead_Project_RateLimitGet_Project_BurstLimitGet_Project_RateLimitPut_Project_BurstLimitPut_Project_RateLimitList_Project_BurstLimitList_Project_RateLimitDel_Project_BurstLimitDel_Project_SegmentLimit_Project_UsageLimit_Project_BandwidthLimit_Project_UserSpecifiedUsageLimit_Project_UserSpecifiedBandwidthLimit_Row(ctx context.Context, row *dbx.ApiKey_Project_PublicId_Project_RateLimit_Project_BurstLimit_Project_RateLimitHead_Project_BurstLimitHead_Project_RateLimitGet_Project_BurstLimitGet_Project_RateLimitPut_Project_BurstLimitPut_Project_RateLimitList_Project_BurstLimitList_Project_RateLimitDel_Project_BurstLimitDel_Project_SegmentLimit_Project_UsageLimit_Project_BandwidthLimit_Project_UserSpecifiedUsageLimit_Project_UserSpecifiedBandwidthLimit_Row) (_ *console.APIKeyInfo, err error) {
defer mon.Task()(&ctx)(&err)
result, err := apiKeyToAPIKeyInfo(ctx, &row.ApiKey)
if err != nil {
return nil, err
}
result.ProjectPublicID, err = uuid.FromBytes(row.Project_PublicId)
if err != nil {
return nil, err
}
result.ProjectRateLimit = row.Project_RateLimit
result.ProjectBurstLimit = row.Project_BurstLimit
result.ProjectRateLimitHead = row.Project_RateLimitHead
result.ProjectBurstLimitHead = row.Project_BurstLimitHead
result.ProjectRateLimitGet = row.Project_RateLimitGet
result.ProjectBurstLimitGet = row.Project_BurstLimitGet
result.ProjectRateLimitPut = row.Project_RateLimitPut
result.ProjectBurstLimitPut = row.Project_BurstLimitPut
result.ProjectRateLimitList = row.Project_RateLimitList
result.ProjectBurstLimitList = row.Project_BurstLimitList
result.ProjectRateLimitDelete = row.Project_RateLimitDel
result.ProjectBurstLimitDelete = row.Project_BurstLimitDel
result.ProjectBandwidthLimit = row.Project_BandwidthLimit
if row.Project_UserSpecifiedBandwidthLimit != nil {
result.ProjectBandwidthLimit = row.Project_UserSpecifiedBandwidthLimit
}
result.ProjectStorageLimit = row.Project_UsageLimit
if row.Project_UserSpecifiedUsageLimit != nil {
result.ProjectStorageLimit = row.Project_UserSpecifiedUsageLimit
}
result.ProjectSegmentsLimit = row.Project_SegmentLimit
return result, nil
}
// apikeySortClause returns what ORDER BY clause should be used when sorting API key results.
func apikeySortClause(order console.APIKeyOrder, direction console.OrderDirection) string {
dirStr := "ASC"
if direction == console.Descending {
dirStr = "DESC"
}
if order == console.CreationDate {
return "ORDER BY ak.created_at " + dirStr + ", ak.name, ak.project_id"
}
return "ORDER BY LOWER(ak.name) " + dirStr + ", ak.name, ak.project_id"
}