Skip to content

[pat] Harden retrieval of PATs and check for nil UUIDs #15072

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 our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Nov 30, 2022
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
21 changes: 16 additions & 5 deletions components/gitpod-db/go/personal_access_token.go
Original file line number Diff line number Diff line change
Expand Up @@ -38,14 +38,25 @@ func (d *PersonalAccessToken) TableName() string {
func GetPersonalAccessTokenForUser(ctx context.Context, conn *gorm.DB, tokenID uuid.UUID, userID uuid.UUID) (PersonalAccessToken, error) {
var token PersonalAccessToken

db := conn.WithContext(ctx)
if tokenID == uuid.Nil {
return PersonalAccessToken{}, fmt.Errorf("Token ID is a required argument to get personal access token for user")
}

db = db.Where("id = ?", tokenID).Where("userId = ?", userID).Where("deleted = ?", 0).First(&token)
if db.Error != nil {
if errors.Is(db.Error, gorm.ErrRecordNotFound) {
if userID == uuid.Nil {
return PersonalAccessToken{}, fmt.Errorf("User ID is a required argument to get personal access token for user")
}

tx := conn.
WithContext(ctx).
Where("id = ?", tokenID).
Where("userId = ?", userID).
Where("deleted = ?", 0).
First(&token)
if tx.Error != nil {
if errors.Is(tx.Error, gorm.ErrRecordNotFound) {
return PersonalAccessToken{}, fmt.Errorf("Token with ID %s does not exist: %w", tokenID, ErrorNotFound)
}
return PersonalAccessToken{}, fmt.Errorf("Failed to retrieve token: %v", db.Error)
return PersonalAccessToken{}, fmt.Errorf("Failed to retrieve token: %v", tx.Error)
}

return token, nil
Expand Down
10 changes: 10 additions & 0 deletions components/gitpod-db/go/personal_access_token_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,16 @@ func TestPersonalAccessToken_Get(t *testing.T) {

dbtest.CreatePersonalAccessTokenRecords(t, conn, tokenEntries...)

t.Run("nil token ID is rejected", func(t *testing.T) {
_, err := db.GetPersonalAccessTokenForUser(context.Background(), conn, uuid.Nil, token.UserID)
require.Error(t, err)
})

t.Run("nil user ID is rejected", func(t *testing.T) {
_, err := db.GetPersonalAccessTokenForUser(context.Background(), conn, token.ID, uuid.Nil)
require.Error(t, err)
})

t.Run("not matching user", func(t *testing.T) {
_, err := db.GetPersonalAccessTokenForUser(context.Background(), conn, token.ID, token2.UserID)
require.Error(t, err, db.ErrorNotFound)
Expand Down