From 10696fa6343a1c96de038b3d032e3663bc83aeb0 Mon Sep 17 00:00:00 2001 From: Kristoffer Dalby Date: Fri, 5 Jun 2026 15:06:10 +0000 Subject: [PATCH] db: look up API keys by explicit primary key, not struct condition GetAPIKeyByID(0) returned the first key instead of not-found. --- hscontrol/db/api_key.go | 5 ++++- hscontrol/db/api_key_byid_test.go | 28 ++++++++++++++++++++++++++++ 2 files changed, 32 insertions(+), 1 deletion(-) create mode 100644 hscontrol/db/api_key_byid_test.go diff --git a/hscontrol/db/api_key.go b/hscontrol/db/api_key.go index f53ad6f1..e64648c9 100644 --- a/hscontrol/db/api_key.go +++ b/hscontrol/db/api_key.go @@ -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 } diff --git a/hscontrol/db/api_key_byid_test.go b/hscontrol/db/api_key_byid_test.go new file mode 100644 index 00000000..05822c0b --- /dev/null +++ b/hscontrol/db/api_key_byid_test.go @@ -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) +}