diff --git a/pkg/api/apikey.go b/pkg/api/apikey.go index d194429906f..5ad474057c2 100644 --- a/pkg/api/apikey.go +++ b/pkg/api/apikey.go @@ -68,7 +68,10 @@ func (hs *HTTPServer) AddAPIKey(c *models.ReqContext, cmd models.AddApiKeyComman if err == models.ErrInvalidApiKeyExpiration { return Error(400, err.Error(), nil) } - return Error(500, "Failed to add API key", err) + if err == models.ErrDuplicateApiKey { + return Error(409, err.Error(), nil) + } + return Error(500, "Failed to add API Key", err) } result := &dtos.NewApiKeyResult{ diff --git a/pkg/models/apikey.go b/pkg/models/apikey.go index 1edc8379d64..fe96bbd14df 100644 --- a/pkg/models/apikey.go +++ b/pkg/models/apikey.go @@ -7,6 +7,7 @@ import ( var ErrInvalidApiKey = errors.New("Invalid API Key") var ErrInvalidApiKeyExpiration = errors.New("Negative value for SecondsToLive") +var ErrDuplicateApiKey = errors.New("API Key Organization ID And Name Must Be Unique") type ApiKey struct { Id int64 diff --git a/pkg/services/sqlstore/apikey.go b/pkg/services/sqlstore/apikey.go index 13ea1feb7da..65b06ca186d 100644 --- a/pkg/services/sqlstore/apikey.go +++ b/pkg/services/sqlstore/apikey.go @@ -37,6 +37,12 @@ func DeleteApiKeyCtx(ctx context.Context, cmd *models.DeleteApiKeyCommand) error func AddApiKey(cmd *models.AddApiKeyCommand) error { return inTransaction(func(sess *DBSession) error { + key := models.ApiKey{OrgId: cmd.OrgId, Name: cmd.Name} + exists, _ := sess.Get(&key) + if exists { + return models.ErrDuplicateApiKey + } + updated := timeNow() var expires *int64 = nil if cmd.SecondsToLive > 0 { diff --git a/pkg/services/sqlstore/apikey_test.go b/pkg/services/sqlstore/apikey_test.go index a1b06db0f9c..272fcea8aec 100644 --- a/pkg/services/sqlstore/apikey_test.go +++ b/pkg/services/sqlstore/apikey_test.go @@ -115,3 +115,23 @@ func TestApiKeyDataAccess(t *testing.T) { }) }) } + +func TestApiKeyErrors(t *testing.T) { + mockTimeNow() + defer resetTimeNow() + + t.Run("Testing API Duplicate Key Errors", func(t *testing.T) { + InitTestDB(t) + t.Run("Given saved api key", func(t *testing.T) { + cmd := models.AddApiKeyCommand{OrgId: 0, Name: "duplicate", Key: "asd"} + err := AddApiKey(&cmd) + assert.Nil(t, err) + + t.Run("Add API Key with existing Org ID and Name", func(t *testing.T) { + cmd := models.AddApiKeyCommand{OrgId: 0, Name: "duplicate", Key: "asd"} + err = AddApiKey(&cmd) + assert.EqualError(t, err, models.ErrDuplicateApiKey.Error()) + }) + }) + }) +}