diff --git a/BTCPayServer.Tests/GreenfieldAPITests.cs b/BTCPayServer.Tests/GreenfieldAPITests.cs index 108b054b1..034ee9bed 100644 --- a/BTCPayServer.Tests/GreenfieldAPITests.cs +++ b/BTCPayServer.Tests/GreenfieldAPITests.cs @@ -218,6 +218,8 @@ namespace BTCPayServer.Tests Permissions = new Permission[] { Permission.Create(Policies.CanViewInvoices, store.Id) }, }); + await AssertAPIError("user-not-found", () => unrestricted.CreateAPIKey("fewiofwuefo", new CreateApiKeyRequest())); + // Despite the grant, the user shouldn't be able to get the invoices! newUserClient = acc.CreateClientFromAPIKey(newUserAPIKey.ApiKey); await Assert.ThrowsAsync(() => newUserClient.GetInvoices(store.Id)); diff --git a/BTCPayServer/Controllers/GreenField/GreenfieldApiKeysController.cs b/BTCPayServer/Controllers/GreenField/GreenfieldApiKeysController.cs index 836c19d7f..f0c7e8651 100644 --- a/BTCPayServer/Controllers/GreenField/GreenfieldApiKeysController.cs +++ b/BTCPayServer/Controllers/GreenField/GreenfieldApiKeysController.cs @@ -11,6 +11,7 @@ using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Cors; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Mvc; +using Microsoft.EntityFrameworkCore; using NBitcoin; using NBitcoin.DataEncoders; @@ -66,7 +67,14 @@ namespace BTCPayServer.Controllers.Greenfield { Permissions = request.Permissions.Select(p => p.ToString()).Distinct().ToArray() }); - await _apiKeyRepository.CreateKey(key); + try + { + await _apiKeyRepository.CreateKey(key); + } + catch (DbUpdateException) + { + return this.CreateAPIError("user-not-found", "This user does not exists"); + } return Ok(FromModel(key)); } diff --git a/Changelog.md b/Changelog.md index 6f3ab483c..3da06c502 100644 --- a/Changelog.md +++ b/Changelog.md @@ -9,6 +9,7 @@ ### Bug fix * Avoid crash when some plugins are installed (#4725) +* Greenfield: Do not create if create API key is called on a non-existant user (Fix #4731) ### Improvements