Service accounts: Migrate expired API keys (#50883)

This commit is contained in:
Alexander Zobnin 2022-06-16 17:01:50 +03:00 committed by GitHub
parent b09df60464
commit c4f0be7c8d
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 29 additions and 6 deletions

View File

@ -185,6 +185,16 @@ func TestStore_MigrateAllApiKeys(t *testing.T) {
expectedServiceAccouts: 0,
expectedErr: nil,
},
{
desc: "expired api keys should be migrated",
keys: []tests.TestApiKey{
{Name: "test1", Role: models.ROLE_EDITOR, Key: "secret1", OrgId: 1},
{Name: "test2", Role: models.ROLE_EDITOR, Key: "secret2", OrgId: 1, IsExpired: true},
},
orgId: 1,
expectedServiceAccouts: 2,
expectedErr: nil,
},
}
for _, c := range cases {

View File

@ -20,10 +20,11 @@ type TestUser struct {
}
type TestApiKey struct {
Name string
Role models.RoleType
OrgId int64
Key string
Name string
Role models.RoleType
OrgId int64
Key string
IsExpired bool
}
func SetupUserServiceAccount(t *testing.T, sqlStore *sqlstore.SQLStore, testUser TestUser) *models.User {
@ -61,6 +62,19 @@ func SetupApiKey(t *testing.T, sqlStore *sqlstore.SQLStore, testKey TestApiKey)
}
err := sqlStore.AddAPIKey(context.Background(), addKeyCmd)
require.NoError(t, err)
if testKey.IsExpired {
err := sqlStore.WithTransactionalDbSession(context.Background(), func(sess *sqlstore.DBSession) error {
// Force setting expires to time before now to make key expired
var expires int64 = 1
key := models.ApiKey{Expires: &expires}
rowsAffected, err := sess.ID(addKeyCmd.Result.Id).Update(&key)
require.Equal(t, int64(1), rowsAffected)
return err
})
require.NoError(t, err)
}
return addKeyCmd.Result
}

View File

@ -46,8 +46,7 @@ func (ss *SQLStore) GetAPIKeys(ctx context.Context, query *models.GetApiKeysQuer
func (ss *SQLStore) GetAllAPIKeys(ctx context.Context, orgID int64) []*models.ApiKey {
result := make([]*models.ApiKey, 0)
err := ss.WithDbSession(ctx, func(dbSession *DBSession) error {
sess := dbSession.
Where("(expires IS NULL OR expires >= ?) AND service_account_id IS NULL", timeNow().Unix()).Asc("name")
sess := dbSession.Where("service_account_id IS NULL").Asc("name")
if orgID != -1 {
sess = sess.Where("org_id=?", orgID)
}