Skip to content
This repository has been archived by the owner on Jul 12, 2023. It is now read-only.

Clean up deleted API keys after 1 week #909

Merged
merged 2 commits into from
Oct 27, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 3 additions & 2 deletions pkg/config/cleanup_server_config.go
Original file line number Diff line number Diff line change
Expand Up @@ -40,11 +40,12 @@ type CleanupConfig struct {
RateLimit uint64 `env:"RATE_LIMIT,default=60"`

// Cleanup config
AuditEntryMaxAge time.Duration `env:"AUDIT_ENTRY_MAX_AGE,default=720h"`
AuthorizedAppMaxAge time.Duration `env:"AUTHORIZED_APP_MAX_AGE,default=336h"`
CleanupPeriod time.Duration `env:"CLEANUP_PERIOD,default=15m"`
MobileAppMaxAge time.Duration `env:"MOBILE_APP_MAX_AGE,default=168h"`
VerificationCodeMaxAge time.Duration `env:"VERIFICATION_CODE_MAX_AGE,default=24h"`
VerificationTokenMaxAge time.Duration `env:"VERIFICATION_TOKEN_MAX_AGE,default=24h"`
MobileAppMaxAge time.Duration `env:"MOBILE_APP_MAX_AGE,default=168h"`
AuditEntryMaxAge time.Duration `env:"AUDIT_ENTRY_MAX_AGE,default=720h"`
}

// NewCleanupConfig returns the environment config for the cleanup server.
Expand Down
11 changes: 11 additions & 0 deletions pkg/controller/cleanup/cleanup.go
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,17 @@ func (c *Controller) HandleCleanup() http.Handler {
// attempt the other purges.
var merr *multierror.Error

// API keys
item = tag.Upsert(itemTagKey, "API_KEYS")
if count, err := c.db.PurgeAuthorizedApps(c.config.AuthorizedAppMaxAge); err != nil {
merr = multierror.Append(merr, fmt.Errorf("failed to purge authorized apps: %w", err))
result = observability.ResultError("FAILED")
} else {
c.logger.Infow("purged authorized apps", "count", count)
result = observability.ResultOK()
}
stats.RecordWithTags(ctx, []tag.Mutator{result, item}, mRequests.M(1))

// Verification codes
item = tag.Upsert(itemTagKey, "VERIFICATION_CODE")
if count, err := c.db.PurgeVerificationCodes(c.config.VerificationCodeMaxAge); err != nil {
Expand Down
15 changes: 15 additions & 0 deletions pkg/database/authorized_app.go
Original file line number Diff line number Diff line change
Expand Up @@ -418,3 +418,18 @@ func (a *AuthorizedApp) AuditID() string {
func (a *AuthorizedApp) AuditDisplay() string {
return a.Name
}

// PurgeAuthorizedApps will delete authorized apps that have been deleted for
// more than the specified time.
func (db *Database) PurgeAuthorizedApps(maxAge time.Duration) (int64, error) {
if maxAge > 0 {
maxAge = -1 * maxAge
}
deleteBefore := time.Now().UTC().Add(maxAge)

result := db.db.
Unscoped().
Where("deleted_at IS NOT NULL AND deleted_at < ?", deleteBefore).
Delete(&AuthorizedApp{})
return result.RowsAffected, result.Error
}