Repository navigation
Expand file tree
/
Copy pathengine.go
More file actions
710 lines (634 loc) · 24.4 KB
/
Copy pathengine.go
File metadata and controls
710 lines (634 loc) · 24.4 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
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
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
package keysmith
import (
"context"
"errors"
"fmt"
"slices"
"time"
log "github.com/xraph/go-utils/log"
"github.com/xraph/keysmith/id"
"github.com/xraph/keysmith/key"
"github.com/xraph/keysmith/plugin"
"github.com/xraph/keysmith/policy"
"github.com/xraph/keysmith/rotation"
"github.com/xraph/keysmith/scope"
"github.com/xraph/keysmith/store"
"github.com/xraph/keysmith/usage"
)
// Engine is the central Keysmith engine that coordinates all subsystems.
type Engine struct {
store store.Store
hasher Hasher
generator KeyGenerator
ratelimiter RateLimiter
hooks *plugin.Manager
logger log.Logger
}
// NewEngine creates a new Keysmith engine with the given options.
func NewEngine(opts ...Option) (*Engine, error) {
e := &Engine{
hasher: DefaultHasher(),
generator: DefaultKeyGenerator(),
hooks: plugin.NewManager(),
logger: log.NewNoopLogger(),
}
for _, opt := range opts {
opt(e)
}
if e.store == nil {
return nil, errors.New("keysmith: store is required")
}
return e, nil
}
// Store returns the underlying composite store.
func (e *Engine) Store() store.Store { return e.store }
// RateLimiterConfigured reports whether a RateLimiter was injected. Without
// one, a policy's RateLimit is stored and never enforced.
func (e *Engine) RateLimiterConfigured() bool { return e.ratelimiter != nil }
// Health checks the health of the engine by pinging its store.
func (e *Engine) Health(ctx context.Context) error {
return e.store.Ping(ctx)
}
// Start starts the engine and any background workers.
func (e *Engine) Start(_ context.Context) error { return nil }
// Stop gracefully shuts down the engine.
func (e *Engine) Stop(ctx context.Context) error {
return e.hooks.FireShutdown(ctx)
}
// ──────────────────────────────────────────────────
// Key Management
// ──────────────────────────────────────────────────
// CreateKey generates a new API key, hashes it, stores the hash, and returns
// the raw key exactly once. The raw key is never persisted.
func (e *Engine) CreateKey(ctx context.Context, input *CreateKeyInput) (*key.CreateResult, error) {
sc := scopeFromContext(ctx)
tenantID := sc.tenantID
appID := sc.appID
if tenantID == "" {
tenantID = input.TenantID
}
var pol *policy.Policy
if input.PolicyID != nil {
var polErr error
pol, polErr = e.store.Policies().Get(ctx, *input.PolicyID)
if polErr != nil {
return nil, fmt.Errorf("get policy: %w", polErr)
}
}
// MaxKeyLifetime is a cap. An explicit expiry beyond it is refused
// before anything is written; no expiry defaults to the cap below.
now := time.Now()
if pol != nil && pol.MaxKeyLifetime > 0 && input.ExpiresAt != nil &&
input.ExpiresAt.After(now.Add(pol.MaxKeyLifetime)) {
return nil, ErrKeyLifetimeExceeded
}
rawKey, err := e.generator.Generate(input.Prefix, input.Environment)
if err != nil {
return nil, fmt.Errorf("generate key: %w", err)
}
hash, err := e.hasher.Hash(rawKey)
if err != nil {
return nil, fmt.Errorf("hash key: %w", err)
}
k := &key.Key{
ID: id.NewKeyID(),
TenantID: tenantID,
AppID: appID,
Name: input.Name,
Description: input.Description,
Prefix: input.Prefix,
Hint: rawKey[len(rawKey)-4:],
KeyHash: hash,
Environment: input.Environment,
State: key.StateActive,
PolicyID: input.PolicyID,
Metadata: input.Metadata,
CreatedBy: input.CreatedBy,
ExpiresAt: input.ExpiresAt,
CreatedAt: now,
UpdatedAt: now,
}
// Apply policy constraints if assigned.
if pol != nil && pol.MaxKeyLifetime > 0 && input.ExpiresAt == nil {
expiry := now.Add(pol.MaxKeyLifetime)
k.ExpiresAt = &expiry
}
// Refuse unknown or disallowed scopes before anything is written.
if err := e.checkScopes(ctx, tenantID, pol, input.Scopes); err != nil {
return nil, err
}
if err := e.store.Keys().Create(ctx, k); err != nil {
_ = e.hooks.FireKeyCreateFailed(ctx, k, err)
return nil, fmt.Errorf("store key: %w", err)
}
// Assign scopes.
if len(input.Scopes) > 0 {
if err := e.store.Scopes().AssignToKey(ctx, k.ID, input.Scopes); err != nil {
// The raw key is never returned on this path, so the stored
// key is unreachable. Delete it rather than leave a live key
// that has none of the scopes the caller asked for. The caller
// may have cancelled ctx, which must not stop the cleanup.
assignErr := fmt.Errorf("assign scopes: %w", err)
if delErr := e.store.Keys().Delete(context.WithoutCancel(ctx), k.ID); delErr != nil {
return nil, errors.Join(assignErr, fmt.Errorf("delete key after failed scope assignment: %w", delErr))
}
return nil, assignErr
}
k.Scopes = input.Scopes
}
_ = e.hooks.FireKeyCreated(ctx, k)
return &key.CreateResult{Key: k, RawKey: rawKey}, nil
}
// ValidateKey validates a raw API key and returns the key record if valid.
// This is the hot path — optimized for speed.
func (e *Engine) ValidateKey(ctx context.Context, rawKey string) (*ValidationResult, error) {
hash, err := e.hasher.Hash(rawKey)
if err != nil {
return nil, fmt.Errorf("hash key: %w", err)
}
var viaPrevious bool
var graceEnds *time.Time
k, err := e.store.Keys().GetByHash(ctx, hash)
if err != nil {
// The hash is not any key's current hash. It may still be the hash a
// key had before a rotation whose grace window is open.
rec, recErr := e.store.Rotations().GetInGraceByOldHash(ctx, hash, time.Now())
// A record with no OldHint was written before the grace fix, when
// RotateKey recorded a window on every rotation (compromise ones
// too) but killed the old key at once. That window was never
// honoured, so it must not open now. The close_legacy_grace_windows
// migration closes these rows; this guard covers a store where it
// has not run, such as mongo's index-only Store.Migrate.
if recErr != nil || rec.OldHint == "" {
_ = e.hooks.FireKeyValidationFailed(ctx, rawKey, err)
return nil, ErrInvalidKey
}
k, err = e.store.Keys().Get(ctx, rec.KeyID)
if err != nil {
_ = e.hooks.FireKeyValidationFailed(ctx, rawKey, err)
return nil, ErrInvalidKey
}
viaPrevious = true
ends := rec.GraceEnds
graceEnds = &ends
}
// Check state. Suspended, revoked and expired keys fail here whichever
// hash the caller presented. RevokedAt is final even when State says
// otherwise: a stale full-row write racing a revoke can put State back
// and leave RevokedAt set.
if k.State != key.StateActive || k.RevokedAt != nil {
_ = e.hooks.FireKeyValidationFailed(ctx, rawKey, ErrKeyInactive)
return nil, ErrKeyInactive
}
// Check expiration.
if k.ExpiresAt != nil && time.Now().After(*k.ExpiresAt) {
_ = e.store.Keys().UpdateState(ctx, k.ID, key.StateExpired)
_ = e.hooks.FireKeyExpired(ctx, k)
return nil, ErrKeyExpired
}
// Load the policy. A read failure fails closed: carrying on with a nil
// policy would skip the rate limit and hand the host a result it reads
// as "no restrictions". A policy that no longer exists (a dangling
// PolicyID) is not an outage, so the key validates without one.
var pol *policy.Policy
if k.PolicyID != nil {
var polErr error
pol, polErr = e.store.Policies().Get(ctx, *k.PolicyID)
if polErr != nil {
if !errors.Is(polErr, ErrPolicyNotFound) {
return nil, fmt.Errorf("load policy: %w", polErr)
}
pol = nil
}
}
// Rate-limit check.
if pol != nil && e.ratelimiter != nil && pol.RateLimit > 0 {
allowed, rlErr := e.ratelimiter.Allow(ctx, k.ID.String(), pol.RateLimit, pol.RateLimitWindow)
if rlErr != nil || !allowed {
_ = e.hooks.FireKeyRateLimited(ctx, k)
return nil, ErrRateLimited
}
}
// Load scopes.
scopes, _ := e.store.Scopes().ListByKey(ctx, k.ID)
scopeNames := make([]string, len(scopes))
for i, s := range scopes {
scopeNames[i] = s.Name
}
// Update last-used timestamp asynchronously.
go func() {
now := time.Now()
_ = e.store.Keys().UpdateLastUsed(context.WithoutCancel(ctx), k.ID, now)
}()
_ = e.hooks.FireKeyValidated(ctx, k)
return &ValidationResult{
Key: k,
Scopes: scopeNames,
Policy: pol,
ViaPreviousKey: viaPrevious,
GraceEnds: graceEnds,
}, nil
}
// RotateKey issues a new raw key for the same key record. The previous raw key
// keeps validating until its grace window ends. The window comes from
// WithGrace if given, else the key's policy GracePeriod, else 24 hours. A
// window of zero stops the previous key at once. A revoked or expired key
// cannot be rotated, and a key with RevokedAt set counts as revoked. If
// another write reaches the key between the read and the write (a revoke,
// for example), the rotation is refused with ErrKeyConflict and the key keeps
// the other write.
func (e *Engine) RotateKey(ctx context.Context, keyID id.KeyID, reason rotation.Reason, opts ...RotateOption) (*key.CreateResult, error) {
k, err := e.store.Keys().Get(ctx, keyID)
if err != nil {
return nil, fmt.Errorf("get key: %w", err)
}
if k.State == key.StateRevoked || k.State == key.StateExpired || k.RevokedAt != nil ||
(k.ExpiresAt != nil && time.Now().After(*k.ExpiresAt)) {
return nil, ErrInvalidStateTransition
}
var cfg rotateConfig
for _, opt := range opts {
opt(&cfg)
}
// Grace period: the caller's choice, then the policy's, then 24 hours.
graceTTL := 24 * time.Hour
switch {
case cfg.grace != nil:
graceTTL = *cfg.grace
case k.PolicyID != nil:
// A policy that is gone keeps the 24h default. Any other read
// failure stops the rotation, so the key is left as it was.
pol, polErr := e.store.Policies().Get(ctx, *k.PolicyID)
switch {
case polErr == nil:
if pol.GracePeriod > 0 {
graceTTL = pol.GracePeriod
}
case !errors.Is(polErr, ErrPolicyNotFound):
return nil, fmt.Errorf("get policy: %w", polErr)
}
}
// Generate new key.
rawKey, err := e.generator.Generate(k.Prefix, k.Environment)
if err != nil {
return nil, fmt.Errorf("generate new key: %w", err)
}
newHash, err := e.hasher.Hash(rawKey)
if err != nil {
return nil, fmt.Errorf("hash new key: %w", err)
}
now := time.Now()
newHint := rawKey[len(rawKey)-4:]
// Record the rotation before touching the key. Until the key update
// lands, the old hash is still the key's current hash, so GetByHash
// finds it and callers on the old key never fall into a gap. If the key
// update then fails, the record stays as a history row. When nothing
// else wrote the key, the fallback cannot reach it: it only runs for a
// hash that is no key's current hash, and the old hash still is one.
// When the update lost a race (ErrKeyConflict), another write moved the
// key on, and if that write was a rotation the old hash is no longer
// current. This record would then hold the old key's window open as long
// as this call asked for, past whatever the winner chose, so the
// conflict path below ends this record's window. It ends only this one:
// EndGrace would close the winner's window too.
rec := &rotation.Record{
ID: id.NewRotationID(),
KeyID: k.ID,
TenantID: k.TenantID,
OldKeyHash: k.KeyHash,
NewKeyHash: newHash,
OldHint: k.Hint,
NewHint: newHint,
RotatedBy: cfg.rotatedBy,
Reason: reason,
GraceTTL: graceTTL,
GraceEnds: now.Add(graceTTL),
CreatedAt: now,
}
if err := e.store.Rotations().Create(ctx, rec); err != nil {
return nil, fmt.Errorf("record rotation: %w", err)
}
k.KeyHash = newHash
k.Hint = newHint
k.RotatedAt = &now
k.UpdatedAt = now
if err := e.store.Keys().UpdateIfVersion(ctx, k, k.Version); err != nil {
err = fmt.Errorf("update key: %w", err)
if errors.Is(err, ErrKeyConflict) {
// The caller may have gone, but the window must still close.
if endErr := e.store.Rotations().EndGraceByID(context.WithoutCancel(ctx), rec.ID, time.Now()); endErr != nil {
err = errors.Join(err, fmt.Errorf("end grace of the refused rotation: %w", endErr))
}
}
return nil, err
}
_ = e.hooks.FireKeyRotated(ctx, k, rec)
return &key.CreateResult{Key: k, RawKey: rawKey}, nil
}
// RevokeKey permanently disables a key. Revocation is terminal: no state
// change leads out of it, and revoking twice is refused so hooks fire once.
// If the key changes between the read and the write, the revoke is refused
// with ErrKeyConflict and the caller can read the key again and retry.
func (e *Engine) RevokeKey(ctx context.Context, keyID id.KeyID, reason string) error {
k, err := e.store.Keys().Get(ctx, keyID)
if err != nil {
return fmt.Errorf("get key: %w", err)
}
if k.State == key.StateRevoked {
return ErrInvalidStateTransition
}
now := time.Now()
k.State = key.StateRevoked
k.RevokedAt = &now
k.UpdatedAt = now
if err := e.store.Keys().UpdateIfVersion(ctx, k, k.Version); err != nil {
return fmt.Errorf("update key: %w", err)
}
// A revoked key must not be reachable through a previous key either.
if _, err := e.store.Rotations().EndGrace(ctx, keyID, now); err != nil {
return fmt.Errorf("end grace: %w", err)
}
_ = e.hooks.FireKeyRevoked(ctx, k, reason)
return nil
}
// EndGrace closes every open grace window on a key now, so every previous
// key stops validating. It returns how many windows it closed.
func (e *Engine) EndGrace(ctx context.Context, keyID id.KeyID) (int64, error) {
if _, err := e.store.Keys().Get(ctx, keyID); err != nil {
return 0, fmt.Errorf("get key: %w", err)
}
n, err := e.store.Rotations().EndGrace(ctx, keyID, time.Now())
if err != nil {
return 0, fmt.Errorf("end grace: %w", err)
}
return n, nil
}
// SuspendKey temporarily disables an active key. Only an active key can be
// suspended; anything else, a revoked key above all, is refused. A key with
// RevokedAt set is revoked whatever its State says. The write is
// version-checked like RevokeKey's, so a key that changed after the read is
// refused with ErrKeyConflict.
func (e *Engine) SuspendKey(ctx context.Context, keyID id.KeyID) error {
k, err := e.store.Keys().Get(ctx, keyID)
if err != nil {
return fmt.Errorf("get key: %w", err)
}
if k.State != key.StateActive || k.RevokedAt != nil {
return ErrInvalidStateTransition
}
k.State = key.StateSuspended
k.UpdatedAt = time.Now()
if err := e.store.Keys().UpdateIfVersion(ctx, k, k.Version); err != nil {
return fmt.Errorf("suspend key: %w", err)
}
_ = e.hooks.FireKeySuspended(ctx, k)
return nil
}
// ReactivateKey re-enables a suspended key. A key with RevokedAt set is
// revoked whatever its State says, and stays that way. The write is
// version-checked like RevokeKey's, so a key that changed after the read is
// refused with ErrKeyConflict.
func (e *Engine) ReactivateKey(ctx context.Context, keyID id.KeyID) error {
k, err := e.store.Keys().Get(ctx, keyID)
if err != nil {
return fmt.Errorf("get key: %w", err)
}
if k.State != key.StateSuspended || k.RevokedAt != nil {
return ErrInvalidStateTransition
}
k.State = key.StateActive
k.UpdatedAt = time.Now()
if err := e.store.Keys().UpdateIfVersion(ctx, k, k.Version); err != nil {
return fmt.Errorf("reactivate key: %w", err)
}
_ = e.hooks.FireKeyReactivated(ctx, k)
return nil
}
// GetKey returns a key by ID.
func (e *Engine) GetKey(ctx context.Context, keyID id.KeyID) (*key.Key, error) {
return e.store.Keys().Get(ctx, keyID)
}
// ListKeys returns keys matching the filter.
func (e *Engine) ListKeys(ctx context.Context, filter *key.ListFilter) ([]*key.Key, error) {
return e.store.Keys().List(ctx, filter)
}
// ──────────────────────────────────────────────────
// Policy Management
// ──────────────────────────────────────────────────
// CreatePolicy creates a new key policy.
func (e *Engine) CreatePolicy(ctx context.Context, pol *policy.Policy) error {
sc := scopeFromContext(ctx)
if err := e.checkPolicyName(ctx, sc.tenantID, pol.Name, nil); err != nil {
return err
}
pol.ID = id.NewPolicyID()
pol.TenantID = sc.tenantID
pol.AppID = sc.appID
now := time.Now()
pol.CreatedAt = now
pol.UpdatedAt = now
if err := e.store.Policies().Create(ctx, pol); err != nil {
return fmt.Errorf("create policy: %w", err)
}
_ = e.hooks.FirePolicyCreated(ctx, pol)
return nil
}
// GetPolicy returns a policy by ID.
func (e *Engine) GetPolicy(ctx context.Context, polID id.PolicyID) (*policy.Policy, error) {
return e.store.Policies().Get(ctx, polID)
}
// UpdatePolicy updates an existing policy.
func (e *Engine) UpdatePolicy(ctx context.Context, pol *policy.Policy) error {
if err := e.checkPolicyName(ctx, pol.TenantID, pol.Name, &pol.ID); err != nil {
return err
}
pol.UpdatedAt = time.Now()
if err := e.store.Policies().Update(ctx, pol); err != nil {
return fmt.Errorf("update policy: %w", err)
}
_ = e.hooks.FirePolicyUpdated(ctx, pol)
return nil
}
// checkPolicyName refuses a name another policy in the tenant already has.
// self is the policy being updated, which may keep its own name; it is nil on
// create. The unique (tenant_id, name) index on the SQL and mongo backends
// stays as the backstop for two writes that race past this check.
func (e *Engine) checkPolicyName(ctx context.Context, tenantID, name string, self *id.PolicyID) error {
found, err := e.store.Policies().GetByName(ctx, tenantID, name)
switch {
case errors.Is(err, ErrPolicyNotFound):
return nil
case err != nil:
return fmt.Errorf("check policy name: %w", err)
case self != nil && found.ID.String() == self.String():
return nil
default:
return ErrPolicyNameTaken
}
}
// DeletePolicy deletes a policy by ID. It refuses with ErrPolicyInUse while
// any key that is not revoked uses the policy. A revoked key never validates
// again and cannot be deleted, so it does not hold the policy; it keeps the
// policy's ID after the delete. A key with RevokedAt set counts as revoked
// whatever its State says, as it does everywhere else in the engine.
func (e *Engine) DeletePolicy(ctx context.Context, polID id.PolicyID) error {
keys, err := e.store.Keys().ListByPolicy(ctx, polID)
if err != nil {
return fmt.Errorf("list keys by policy: %w", err)
}
for _, k := range keys {
if k.State != key.StateRevoked && k.RevokedAt == nil {
return ErrPolicyInUse
}
}
if err := e.store.Policies().Delete(ctx, polID); err != nil {
return fmt.Errorf("delete policy: %w", err)
}
_ = e.hooks.FirePolicyDeleted(ctx, polID)
return nil
}
// ListPolicies returns policies matching the filter.
func (e *Engine) ListPolicies(ctx context.Context, filter *policy.ListFilter) ([]*policy.Policy, error) {
return e.store.Policies().List(ctx, filter)
}
// ──────────────────────────────────────────────────
// Scope Management
// ──────────────────────────────────────────────────
// CreateScope creates a permission scope.
func (e *Engine) CreateScope(ctx context.Context, s *scope.Scope) error {
sc := scopeFromContext(ctx)
switch _, err := e.store.Scopes().GetByName(ctx, sc.tenantID, s.Name); {
case err == nil:
return ErrScopeNameTaken
case !errors.Is(err, ErrScopeNotFound):
return fmt.Errorf("check scope name: %w", err)
}
s.ID = id.NewScopeID()
s.TenantID = sc.tenantID
s.AppID = sc.appID
s.CreatedAt = time.Now()
return e.store.Scopes().Create(ctx, s)
}
// ListScopes returns scopes for the tenant.
func (e *Engine) ListScopes(ctx context.Context, filter *scope.ListFilter) ([]*scope.Scope, error) {
return e.store.Scopes().List(ctx, filter)
}
// scopePolicyPage is how many policies DeleteScope reads per call while it
// looks for one that allows the scope.
const scopePolicyPage = 100
// DeleteScope deletes a scope by ID and takes it off every key that holds
// it. It refuses with ErrScopeHasChildren while another scope in the same
// tenant names it as its parent, then with ErrScopeAllowedByPolicy while a
// policy in the tenant lists it in AllowedScopes. It answers
// ErrScopeNotFound for a missing scope.
func (e *Engine) DeleteScope(ctx context.Context, scopeID id.ScopeID) error {
s, err := e.store.Scopes().Get(ctx, scopeID)
if err != nil {
return err
}
children, err := e.store.Scopes().List(ctx, &scope.ListFilter{TenantID: s.TenantID, Parent: s.Name, Limit: 1})
if err != nil {
return fmt.Errorf("list child scopes: %w", err)
}
if len(children) > 0 {
return ErrScopeHasChildren
}
for offset := 0; ; offset += scopePolicyPage {
pols, err := e.store.Policies().List(ctx, &policy.ListFilter{TenantID: s.TenantID, Limit: scopePolicyPage, Offset: offset})
if err != nil {
return fmt.Errorf("list policies: %w", err)
}
for _, p := range pols {
if slices.Contains(p.AllowedScopes, s.Name) {
return ErrScopeAllowedByPolicy
}
}
if len(pols) < scopePolicyPage {
break
}
}
return e.store.Scopes().Delete(ctx, scopeID)
}
// AssignScopes assigns scopes to a key by name.
func (e *Engine) AssignScopes(ctx context.Context, keyID id.KeyID, scopeNames []string) error {
k, err := e.store.Keys().Get(ctx, keyID)
if err != nil {
return fmt.Errorf("get key: %w", err)
}
var pol *policy.Policy
if k.PolicyID != nil {
pol, err = e.store.Policies().Get(ctx, *k.PolicyID)
if err != nil {
return fmt.Errorf("get policy: %w", err)
}
}
if err := e.checkScopes(ctx, k.TenantID, pol, scopeNames); err != nil {
return err
}
return e.store.Scopes().AssignToKey(ctx, keyID, scopeNames)
}
// checkScopes resolves every scope name in the tenant and, when the policy
// lists allowed scopes, checks each against it. It runs before anything is
// written, so a refused create or assignment leaves no trace. An empty
// AllowedScopes means the policy does not restrict scopes.
func (e *Engine) checkScopes(ctx context.Context, tenantID string, pol *policy.Policy, names []string) error {
var allowed map[string]bool
if pol != nil && len(pol.AllowedScopes) > 0 {
allowed = make(map[string]bool, len(pol.AllowedScopes))
for _, s := range pol.AllowedScopes {
allowed[s] = true
}
}
for _, name := range names {
if _, err := e.store.Scopes().GetByName(ctx, tenantID, name); err != nil {
return fmt.Errorf("scope %q: %w", name, err)
}
if allowed != nil && !allowed[name] {
return fmt.Errorf("scope %q: %w", name, ErrScopeNotAllowed)
}
}
return nil
}
// RemoveScopes removes scopes from a key by name.
func (e *Engine) RemoveScopes(ctx context.Context, keyID id.KeyID, scopeNames []string) error {
return e.store.Scopes().RemoveFromKey(ctx, keyID, scopeNames)
}
// ──────────────────────────────────────────────────
// Usage & Analytics
// ──────────────────────────────────────────────────
// RecordUsage records a single usage event for a key.
func (e *Engine) RecordUsage(ctx context.Context, rec *usage.Record) error {
rec.ID = id.NewUsageID()
rec.CreatedAt = time.Now()
return e.store.Usages().Record(ctx, rec)
}
// QueryUsage queries usage records.
func (e *Engine) QueryUsage(ctx context.Context, filter *usage.QueryFilter) ([]*usage.Record, error) {
return e.store.Usages().Query(ctx, filter)
}
// AggregateUsage returns aggregated usage statistics.
func (e *Engine) AggregateUsage(ctx context.Context, filter *usage.QueryFilter) ([]*usage.Aggregation, error) {
return e.store.Usages().Aggregate(ctx, filter)
}
// ListRotations returns rotation records matching the filter.
func (e *Engine) ListRotations(ctx context.Context, filter *rotation.ListFilter) ([]*rotation.Record, error) {
return e.store.Rotations().List(ctx, filter)
}
// ──────────────────────────────────────────────────
// Cleanup
// ──────────────────────────────────────────────────
// CleanupExpiredKeys finds and marks expired keys.
func (e *Engine) CleanupExpiredKeys(ctx context.Context) error {
keys, err := e.store.Keys().ListExpired(ctx, time.Now())
if err != nil {
return fmt.Errorf("list expired keys: %w", err)
}
for _, k := range keys {
if err := e.store.Keys().UpdateState(ctx, k.ID, key.StateExpired); err != nil {
e.logger.Warn("failed to expire key", log.String("key_id", k.ID.String()), log.Any("error", err))
continue
}
_ = e.hooks.FireKeyExpired(ctx, k)
}
return nil
}