-
Notifications
You must be signed in to change notification settings - Fork 3
/
handler.go
551 lines (468 loc) · 15.9 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
package quotacontrol
import (
"context"
"errors"
"fmt"
"log/slog"
"time"
"github.com/0xsequence/quotacontrol/internal/store"
"github.com/0xsequence/quotacontrol/middleware"
"github.com/0xsequence/quotacontrol/proto"
"github.com/go-chi/httprate"
"github.com/goware/logger"
"github.com/goware/validation"
)
type LimitStore interface {
GetAccessLimit(ctx context.Context, projectID uint64, cycle *proto.Cycle) (*proto.Limit, error)
}
type AccessKeyStore interface {
ListAccessKeys(ctx context.Context, projectID uint64, active *bool, service *proto.Service) ([]*proto.AccessKey, error)
FindAccessKey(ctx context.Context, accessKey string) (*proto.AccessKey, error)
InsertAccessKey(ctx context.Context, accessKey *proto.AccessKey) error
UpdateAccessKey(ctx context.Context, accessKey *proto.AccessKey) (*proto.AccessKey, error)
}
type UsageStore interface {
GetAccessKeyUsage(ctx context.Context, projectID uint64, accessKey string, service *proto.Service, min, max time.Time) (proto.AccessUsage, error)
GetAccountUsage(ctx context.Context, projectID uint64, service *proto.Service, min, max time.Time) (proto.AccessUsage, error)
UpdateAccessUsage(ctx context.Context, projectID uint64, accessKey string, service proto.Service, time time.Time, usage proto.AccessUsage) error
}
type CycleStore interface {
GetAccessCycle(ctx context.Context, projectID uint64, now time.Time) (*proto.Cycle, error)
}
// PermissionStore is the interface that wraps the GetUserPermission method.
type PermissionStore interface {
GetUserPermission(ctx context.Context, projectID uint64, userID string) (proto.UserPermission, *proto.ResourceAccess, error)
}
type Cache struct {
QuotaCache
UsageCache
PermissionCache
}
type Store struct {
LimitStore
AccessKeyStore
UsageStore
CycleStore
PermissionStore
}
// NewHandler returns server implementation for proto.QuotaControl.
func NewHandler(log logger.Logger, cache Cache, storage Store, counter httprate.LimitCounter) proto.QuotaControl {
if log == nil {
log = logger.NewLogger(logger.LogLevel_INFO)
}
if storage.CycleStore == nil {
storage.CycleStore = store.Cycle{}
}
return &handler{
log: log.With("service", "quotacontrol"),
cache: cache,
store: storage,
limitCounter: counter,
accessKeyGen: proto.GenerateAccessKey,
}
}
// handler is the quotacontrol handler backend implementation.
type handler struct {
log logger.Logger
cache Cache
store Store
limitCounter httprate.LimitCounter
accessKeyGen func(projectID uint64) string
}
var _ proto.QuotaControl = &handler{}
func (h handler) GetTimeRange(ctx context.Context, projectID uint64, from, to *time.Time) (time.Time, time.Time, error) {
if from != nil && to != nil {
return *from, *to, nil
}
now := middleware.GetTime(ctx)
cycle, err := h.store.CycleStore.GetAccessCycle(ctx, projectID, now)
if err != nil {
return time.Time{}, time.Time{}, err
}
if from == nil && to == nil {
cycle, _ := store.Cycle{}.GetAccessCycle(ctx, projectID, now)
return cycle.GetStart(now), cycle.GetEnd(now), nil
}
duration := cycle.GetDuration(now)
if from == nil {
return to.Add(-duration), *to, nil
}
return *from, from.Add(duration), nil
}
func (h handler) GetAccountUsage(ctx context.Context, projectID uint64, service *proto.Service, from, to *time.Time) (*proto.AccessUsage, error) {
min, max, err := h.GetTimeRange(ctx, projectID, from, to)
if err != nil {
return nil, err
}
usage, err := h.store.UsageStore.GetAccountUsage(ctx, projectID, service, min, max)
if err != nil {
return nil, err
}
return &usage, nil
}
func (h handler) GetAsyncUsage(ctx context.Context, projectID uint64, service *proto.Service, from, to *time.Time) (*proto.AccessUsage, error) {
min, max, err := h.GetTimeRange(ctx, projectID, from, to)
if err != nil {
return nil, err
}
usage, err := h.store.UsageStore.GetAccessKeyUsage(ctx, projectID, "", service, min, max)
if err != nil {
return nil, err
}
return &usage, nil
}
func (h handler) GetAccessKeyUsage(ctx context.Context, accessKey string, service *proto.Service, from, to *time.Time) (*proto.AccessUsage, error) {
projectID, err := proto.GetProjectID(accessKey)
if err != nil {
return nil, err
}
min, max, err := h.GetTimeRange(ctx, projectID, from, to)
if err != nil {
return nil, err
}
usage, err := h.store.UsageStore.GetAccessKeyUsage(ctx, projectID, accessKey, service, min, max)
if err != nil {
return nil, err
}
return &usage, nil
}
func (h handler) PrepareUsage(ctx context.Context, projectID uint64, cycle *proto.Cycle, now time.Time) (bool, error) {
min, max := cycle.GetStart(now), cycle.GetEnd(now)
usage, err := h.GetAccountUsage(ctx, projectID, nil, &min, &max)
if err != nil {
return false, err
}
key := getQuotaKey(projectID, cycle, now)
if err := h.cache.UsageCache.SetUsage(ctx, key, usage.GetTotalUsage()); err != nil {
return false, err
}
return true, nil
}
func (h handler) ClearUsage(ctx context.Context, projectID uint64, now time.Time) (bool, error) {
cycle, err := h.store.CycleStore.GetAccessCycle(ctx, projectID, now)
if err != nil {
return false, err
}
key := getQuotaKey(projectID, cycle, now)
ok, err := h.cache.UsageCache.ClearUsage(ctx, key)
if err != nil {
return false, err
}
return ok, nil
}
func (h handler) GetProjectQuota(ctx context.Context, projectID uint64, now time.Time) (*proto.AccessQuota, error) {
cycle, err := h.store.CycleStore.GetAccessCycle(ctx, projectID, now)
if err != nil {
return nil, err
}
limit, err := h.store.LimitStore.GetAccessLimit(ctx, projectID, cycle)
if err != nil {
return nil, err
}
record := proto.AccessQuota{
Limit: limit,
Cycle: cycle,
AccessKey: &proto.AccessKey{ProjectID: projectID},
}
if err := h.cache.QuotaCache.SetProjectQuota(ctx, &record); err != nil {
h.log.Error("set access quota in cache", slog.Any("error", err))
}
return &record, nil
}
func (h handler) GetAccessQuota(ctx context.Context, accessKey string, now time.Time) (*proto.AccessQuota, error) {
access, err := h.store.AccessKeyStore.FindAccessKey(ctx, accessKey)
if err != nil {
return nil, err
}
cycle, err := h.store.CycleStore.GetAccessCycle(ctx, access.ProjectID, now)
if err != nil {
return nil, err
}
limit, err := h.store.LimitStore.GetAccessLimit(ctx, access.ProjectID, cycle)
if err != nil {
return nil, err
}
record := proto.AccessQuota{
Limit: limit,
Cycle: cycle,
AccessKey: access,
}
if err := h.cache.QuotaCache.SetAccessQuota(ctx, &record); err != nil {
h.log.Error("set access quota in cache", slog.Any("error", err))
}
return &record, nil
}
func (h handler) NotifyEvent(ctx context.Context, projectID uint64, eventType proto.EventType) (bool, error) {
h.log.Info("notify event", slog.Uint64("projectID", projectID), slog.String("eventType", eventType.String()))
return true, nil
}
func (h handler) UpdateProjectUsage(ctx context.Context, service proto.Service, now time.Time, usage map[uint64]*proto.AccessUsage) (map[uint64]bool, error) {
var errs []error
m := make(map[uint64]bool, len(usage))
for projectID, accessUsage := range usage {
err := h.store.UsageStore.UpdateAccessUsage(ctx, projectID, "", service, now, *accessUsage)
if err != nil {
errs = append(errs, fmt.Errorf("%d: %w", projectID, err))
}
m[projectID] = err == nil
}
if len(errs) > 0 {
return m, errors.Join(errs...)
}
return m, nil
}
func (h handler) UpdateKeyUsage(ctx context.Context, service proto.Service, now time.Time, usage map[string]*proto.AccessUsage) (map[string]bool, error) {
var errs []error
m := make(map[string]bool, len(usage))
for key, u := range usage {
projectID, err := proto.GetProjectID(key)
if err != nil {
errs = append(errs, fmt.Errorf("%s: %w", key, err))
continue
}
if err = h.store.UsageStore.UpdateAccessUsage(ctx, projectID, key, service, now, *u); err != nil {
errs = append(errs, fmt.Errorf("%s: %w", key, err))
}
m[key] = err == nil
}
if len(errs) > 0 {
return m, errors.Join(errs...)
}
return m, nil
}
func (h handler) UpdateUsage(ctx context.Context, service proto.Service, now time.Time, usage map[string]*proto.AccessUsage) (map[string]bool, error) {
return h.UpdateKeyUsage(ctx, service, now, usage)
}
func (h handler) ClearAccessQuotaCache(ctx context.Context, projectID uint64) (bool, error) {
accessKeys, err := h.ListAccessKeys(ctx, projectID, proto.Ptr(true), nil)
if err != nil {
h.log.Error("list access keys", slog.Any("error", err))
return true, nil
}
if err := h.cache.QuotaCache.DeleteProjectQuota(ctx, projectID); err != nil {
h.log.Error("delete access quota from cache", slog.Any("error", err))
}
for _, access := range accessKeys {
if err := h.cache.QuotaCache.DeleteAccessQuota(ctx, access.AccessKey); err != nil {
h.log.Error("delete access quota from cache", slog.Any("error", err))
}
}
return true, nil
}
func (h handler) GetAccessKey(ctx context.Context, accessKey string) (*proto.AccessKey, error) {
return h.store.AccessKeyStore.FindAccessKey(ctx, accessKey)
}
func (h handler) GetDefaultAccessKey(ctx context.Context, projectID uint64) (*proto.AccessKey, error) {
list, err := h.store.AccessKeyStore.ListAccessKeys(ctx, projectID, proto.Ptr(true), nil)
if err != nil {
return nil, err
}
for _, accessKey := range list {
if accessKey.Default {
return accessKey, nil
}
}
return nil, proto.ErrNoDefaultKey
}
func (h handler) CreateAccessKey(ctx context.Context, projectID uint64, displayName string, allowedOrigins []string, allowedServices []proto.Service) (*proto.AccessKey, error) {
cycle, err := h.store.CycleStore.GetAccessCycle(ctx, projectID, middleware.GetTime(ctx))
if err != nil {
return nil, err
}
limit, err := h.store.LimitStore.GetAccessLimit(ctx, projectID, cycle)
if err != nil {
return nil, err
}
list, err := h.store.AccessKeyStore.ListAccessKeys(ctx, projectID, proto.Ptr(true), nil)
if err != nil {
return nil, err
}
if limit.MaxKeys > 0 {
if l := len(list); int64(l) >= limit.MaxKeys {
return nil, proto.ErrMaxAccessKeys
}
}
origins, err := validation.NewOrigins(allowedOrigins...)
if err != nil {
return nil, err
}
access := proto.AccessKey{
ProjectID: projectID,
DisplayName: displayName,
AccessKey: h.accessKeyGen(projectID),
Active: true,
Default: len(list) == 0,
AllowedOrigins: origins,
AllowedServices: allowedServices,
}
if err := h.store.AccessKeyStore.InsertAccessKey(ctx, &access); err != nil {
return nil, err
}
return &access, nil
}
func (h handler) RotateAccessKey(ctx context.Context, accessKey string) (*proto.AccessKey, error) {
access, err := h.store.AccessKeyStore.FindAccessKey(ctx, accessKey)
if err != nil {
return nil, err
}
isDefaultKey := access.Default
access.Active = false
access.Default = false
if _, err := h.updateAccessKey(ctx, access); err != nil {
return nil, err
}
newAccess, err := h.CreateAccessKey(ctx, access.ProjectID, access.DisplayName, access.AllowedOrigins.ToStrings(), access.AllowedServices)
if err != nil {
return nil, err
}
if isDefaultKey {
// set new key as default
newAccess.Default = true
return h.updateAccessKey(ctx, newAccess)
}
return newAccess, nil
}
func (h handler) UpdateAccessKey(ctx context.Context, accessKey string, displayName *string, allowedOrigins []string, allowedServices []proto.Service) (*proto.AccessKey, error) {
access, err := h.store.AccessKeyStore.FindAccessKey(ctx, accessKey)
if err != nil {
return nil, err
}
if displayName != nil {
access.DisplayName = *displayName
}
if allowedOrigins != nil {
origins, err := validation.NewOrigins(allowedOrigins...)
if err != nil {
return nil, err
}
access.AllowedOrigins = origins
}
if allowedServices != nil {
access.AllowedServices = allowedServices
}
if access, err = h.updateAccessKey(ctx, access); err != nil {
return nil, err
}
return access, nil
}
func (h handler) UpdateDefaultAccessKey(ctx context.Context, projectID uint64, accessKey string) (bool, error) {
// make sure accessKey exists
access, err := h.store.AccessKeyStore.FindAccessKey(ctx, accessKey)
if err != nil {
return false, err
}
if access.ProjectID != projectID {
return false, fmt.Errorf("project doesn't own the given access key")
}
defaultAccess, err := h.GetDefaultAccessKey(ctx, projectID)
if err != nil {
return false, err
}
// make sure new default access key & old default access key are different
if defaultAccess.AccessKey == access.AccessKey {
return true, nil
}
// update old default access
defaultAccess.Default = false
if _, err := h.updateAccessKey(ctx, defaultAccess); err != nil {
return false, err
}
// set new access key to default
access.Default = true
if _, err = h.updateAccessKey(ctx, access); err != nil {
return false, err
}
return true, nil
}
func (h handler) ListAccessKeys(ctx context.Context, projectID uint64, active *bool, service *proto.Service) ([]*proto.AccessKey, error) {
return h.store.AccessKeyStore.ListAccessKeys(ctx, projectID, active, service)
}
func (h handler) DisableAccessKey(ctx context.Context, accessKey string) (bool, error) {
access, err := h.store.AccessKeyStore.FindAccessKey(ctx, accessKey)
if err != nil {
return false, err
}
list, err := h.store.AccessKeyStore.ListAccessKeys(ctx, access.ProjectID, proto.Ptr(true), nil)
if err != nil {
return false, err
}
if len(list) == 1 {
return false, proto.ErrAtLeastOneKey
}
access.Active = false
access.Default = false
if _, err := h.updateAccessKey(ctx, access); err != nil {
return false, err
}
// set another project accessKey to default
if _, err := h.GetDefaultAccessKey(ctx, access.ProjectID); err == proto.ErrNoDefaultKey {
listUpdated, err := h.store.AccessKeyStore.ListAccessKeys(ctx, access.ProjectID, proto.Ptr(true), nil)
if err != nil {
return false, err
}
newDefaultKey := listUpdated[0]
newDefaultKey.Default = true
if _, err = h.updateAccessKey(ctx, newDefaultKey); err != nil {
return false, err
}
}
return true, nil
}
func (h handler) GetUserPermission(ctx context.Context, projectID uint64, userID string) (proto.UserPermission, *proto.ResourceAccess, error) {
perm, access, err := h.store.PermissionStore.GetUserPermission(ctx, projectID, userID)
if err != nil {
return proto.UserPermission_UNAUTHORIZED, nil, proto.ErrUnauthorizedUser
}
if !perm.Is(proto.UserPermission_UNAUTHORIZED) {
if err := h.cache.PermissionCache.SetUserPermission(ctx, projectID, userID, perm, access); err != nil {
h.log.Error("set user perm in cache", slog.Any("error", err))
}
}
return perm, access, nil
}
func (h handler) updateAccessKey(ctx context.Context, access *proto.AccessKey) (*proto.AccessKey, error) {
access, err := h.store.AccessKeyStore.UpdateAccessKey(ctx, access)
if err != nil {
return nil, err
}
if err := h.cache.QuotaCache.DeleteAccessQuota(ctx, access.AccessKey); err != nil {
h.log.Error("delete access quota from cache", slog.Any("error", err))
}
return access, nil
}
func (h handler) GetProjectStatus(ctx context.Context, projectID uint64) (*proto.ProjectStatus, error) {
status := proto.ProjectStatus{
ProjectID: projectID,
}
now := middleware.GetTime(ctx)
cycle, err := h.store.CycleStore.GetAccessCycle(ctx, projectID, now)
if err != nil {
return nil, err
}
limit, err := h.store.LimitStore.GetAccessLimit(ctx, projectID, cycle)
if err != nil {
return nil, err
}
status.Limit = limit
key := getQuotaKey(projectID, cycle, now)
usage, err := h.cache.UsageCache.PeekUsage(ctx, key)
if err != nil {
if !errors.Is(err, ErrCachePing) {
return nil, err
}
if _, err := h.PrepareUsage(ctx, projectID, cycle, now); err != nil {
return nil, err
}
if usage, err = h.cache.UsageCache.PeekUsage(ctx, key); err != nil {
return nil, err
}
}
status.UsageCounter = usage
limiter := httprate.NewRateLimiter(int(limit.RateLimit), time.Minute, httprate.WithLimitCounter(h.limitCounter))
_, rate, err := limiter.Status(middleware.ProjectRateKey(projectID) + ":")
if err != nil {
return nil, err
}
status.RatelimitCounter = int64(rate)
return &status, nil
}