Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

feat: purge expired api keys in dbpurge (#20863)#21040

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to ourterms of service andprivacy statement. We’ll occasionally send you account related emails.

Already on GitHub?Sign in to your account

Merged
Merged
Show file tree
Hide file tree
Changes fromall 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
9 changes: 9 additions & 0 deletionscoderd/database/dbauthz/dbauthz.go
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -1509,6 +1509,15 @@ func (q *querier) DeleteCustomRole(ctx context.Context, arg database.DeleteCusto
returnq.db.DeleteCustomRole(ctx,arg)
}

func (q*querier)DeleteExpiredAPIKeys(ctx context.Context,arg database.DeleteExpiredAPIKeysParams) (int64,error) {
// Requires DELETE across all API keys.
iferr:=q.authorizeContext(ctx,policy.ActionDelete,rbac.ResourceApiKey);err!=nil {
return0,err
}

returnq.db.DeleteExpiredAPIKeys(ctx,arg)
}

func (q*querier)DeleteExternalAuthLink(ctx context.Context,arg database.DeleteExternalAuthLinkParams)error {
returnfetchAndExec(q.log,q.auth,policy.ActionUpdatePersonal,func(ctx context.Context,arg database.DeleteExternalAuthLinkParams) (database.ExternalAuthLink,error) {
//nolint:gosimple
Expand Down
8 changes: 8 additions & 0 deletionscoderd/database/dbauthz/dbauthz_test.go
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -213,6 +213,14 @@ func (s *MethodTestSuite) TestAPIKey() {
dbm.EXPECT().DeleteAPIKeyByID(gomock.Any(),key.ID).Return(nil).AnyTimes()
check.Args(key.ID).Asserts(key,policy.ActionDelete).Returns()
}))
s.Run("DeleteExpiredAPIKeys",s.Mocked(func(dbm*dbmock.MockStore,faker*gofakeit.Faker,check*expects) {
args:= database.DeleteExpiredAPIKeysParams{
Before:time.Date(2025,11,21,0,0,0,0,time.UTC),
LimitCount:1000,
}
dbm.EXPECT().DeleteExpiredAPIKeys(gomock.Any(),args).Return(int64(0),nil).AnyTimes()
check.Args(args).Asserts(rbac.ResourceApiKey,policy.ActionDelete).Returns(int64(0))
}))
s.Run("GetAPIKeyByID",s.Mocked(func(dbm*dbmock.MockStore,faker*gofakeit.Faker,check*expects) {
key:=testutil.Fake(s.T(),faker, database.APIKey{})
dbm.EXPECT().GetAPIKeyByID(gomock.Any(),key.ID).Return(key,nil).AnyTimes()
Expand Down
9 changes: 8 additions & 1 deletioncoderd/database/dbgen/dbgen.go
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -173,6 +173,13 @@ func APIKey(t testing.TB, db database.Store, seed database.APIKey, munge ...func
}
}

// It does not make sense for the created_at to be after the expires_at.
// So if expires is set, change the default created_at to be 24 hours before.
varcreatedAt time.Time
if!seed.ExpiresAt.IsZero()&&seed.CreatedAt.IsZero() {
createdAt=seed.ExpiresAt.Add(-24*time.Hour)
}

params:= database.InsertAPIKeyParams{
ID:takeFirst(seed.ID,id),
// 0 defaults to 86400 at the db layer
Expand All@@ -182,7 +189,7 @@ func APIKey(t testing.TB, db database.Store, seed database.APIKey, munge ...func
UserID:takeFirst(seed.UserID,uuid.New()),
LastUsed:takeFirst(seed.LastUsed,dbtime.Now()),
ExpiresAt:takeFirst(seed.ExpiresAt,dbtime.Now().Add(time.Hour)),
CreatedAt:takeFirst(seed.CreatedAt,dbtime.Now()),
CreatedAt:takeFirst(seed.CreatedAt,createdAt,dbtime.Now()),
UpdatedAt:takeFirst(seed.UpdatedAt,dbtime.Now()),
LoginType:takeFirst(seed.LoginType,database.LoginTypePassword),
Scope:takeFirst(seed.Scope,database.APIKeyScopeAll),
Expand Down
7 changes: 7 additions & 0 deletionscoderd/database/dbmetrics/querymetrics.go
View file
Open in desktop

Some generated files are not rendered by default. Learn more abouthow customized files appear on GitHub.

15 changes: 15 additions & 0 deletionscoderd/database/dbmock/dbmock.go
View file
Open in desktop

Some generated files are not rendered by default. Learn more abouthow customized files appear on GitHub.

15 changes: 14 additions & 1 deletioncoderd/database/dbpurge/dbpurge.go
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -71,6 +71,19 @@ func New(ctx context.Context, logger slog.Logger, db database.Store, clk quartz.
iferr:=tx.ExpirePrebuildsAPIKeys(ctx,dbtime.Time(start));err!=nil {
returnxerrors.Errorf("failed to expire prebuilds user api keys: %w",err)
}
expiredAPIKeys,err:=tx.DeleteExpiredAPIKeys(ctx, database.DeleteExpiredAPIKeysParams{
// Leave expired keys for a week to allow the backend to know the difference
// between a 404 and an expired key. This purge code is just to bound the size of
// the table to something more reasonable.
Before:dbtime.Time(start.Add(time.Hour*24*7*-1)),
// There could be a lot of expired keys here, so set a limit to prevent this
// taking too long.
// This runs every 10 minutes, so it deletes ~1.5m keys per day at most.
LimitCount:10000,
})
iferr!=nil {
returnxerrors.Errorf("failed to delete expired api keys: %w",err)
}

deleteOldAuditLogConnectionEventsBefore:=start.Add(-maxAuditLogConnectionEventAge)
iferr:=tx.DeleteOldAuditLogConnectionEvents(ctx, database.DeleteOldAuditLogConnectionEventsParams{
Expand All@@ -80,7 +93,7 @@ func New(ctx context.Context, logger slog.Logger, db database.Store, clk quartz.
returnxerrors.Errorf("failed to delete old audit log connection events: %w",err)
}

logger.Debug(ctx,"purged old database entries",slog.F("duration",clk.Since(start)))
logger.Debug(ctx,"purged old database entries",slog.F("expired_api_keys",expiredAPIKeys),slog.F("duration",clk.Since(start)))

returnnil
},database.DefaultTXOptions().WithID("db_purge"));err!=nil {
Expand Down
1 change: 1 addition & 0 deletionscoderd/database/querier.go
View file
Open in desktop

Some generated files are not rendered by default. Learn more abouthow customized files appear on GitHub.

32 changes: 32 additions & 0 deletionscoderd/database/queries.sql.go
View file
Open in desktop

Some generated files are not rendered by default. Learn more abouthow customized files appear on GitHub.

20 changes: 20 additions & 0 deletionscoderd/database/queries/apikeys.sql
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -84,6 +84,26 @@ DELETE FROM
WHERE
user_id= $1;

-- name: DeleteExpiredAPIKeys :one
WITH expired_keysAS (
SELECT id
FROM api_keys
-- expired keys only
WHERE expires_at< @before::timestamptz
LIMIT @limit_count
),
deleted_rowsAS (
DELETEFROM
api_keys
USING
expired_keys
WHERE
api_keys.id=expired_keys.id
RETURNINGapi_keys.id
)
SELECTCOUNT(deleted_rows.id)AS deleted_countFROM deleted_rows;
;

-- name: ExpirePrebuildsAPIKeys :exec
-- Firstly, collect api_keys owned by the prebuilds user that correlate
-- to workspaces no longer owned by the prebuilds user.
Expand Down
Loading

[8]ページ先頭

©2009-2025 Movatter.jp