db: look up API keys by explicit primary key, not struct condition

GetAPIKeyByID(0) returned the first key instead of not-found.
This commit is contained in:
Kristoffer Dalby
2026-06-05 15:06:10 +00:00
committed by Kristoffer Dalby
parent 84c99023e5
commit 10696fa634
2 changed files with 32 additions and 1 deletions
+4 -1
View File
@@ -109,7 +109,10 @@ func (hsdb *HSDatabase) GetAPIKey(prefix string) (*types.APIKey, error) {
// GetAPIKeyByID returns a [types.APIKey] for a given id.
func (hsdb *HSDatabase) GetAPIKeyByID(id uint64) (*types.APIKey, error) {
key := types.APIKey{}
if result := hsdb.DB.Find(&types.APIKey{ID: id}).First(&key); result.Error != nil {
// Query on an explicit primary-key clause: a struct condition would drop a
// zero-valued ID, making the lookup unconditional and returning the first
// row instead of not-found.
if result := hsdb.DB.First(&key, "id = ?", id); result.Error != nil {
return nil, result.Error
}
+28
View File
@@ -0,0 +1,28 @@
package db
import (
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
// TestGetAPIKeyByIDZeroReturnsError ensures GetAPIKeyByID(0) reports not-found
// rather than returning the lowest-ID key. GORM drops a zero-valued primary key
// from a struct condition, which would otherwise make the lookup unconditional.
func TestGetAPIKeyByIDZeroReturnsError(t *testing.T) {
db, err := newSQLiteTestDB()
require.NoError(t, err)
_, key1, err := db.CreateAPIKey(nil)
require.NoError(t, err)
require.NotNil(t, key1)
_, key2, err := db.CreateAPIKey(nil)
require.NoError(t, err)
require.NotNil(t, key2)
key, err := db.GetAPIKeyByID(0)
require.Error(t, err, "GetAPIKeyByID(0) should be not-found, got key=%+v", key)
assert.Nil(t, key)
}