Respect rejected API key permissions (#7744)
What changed, and why it matters
This commit fixes a bug in BTCPay Server's API key authorization flow. When a user was asked to approve a set of permissions for an app, unchecking (rejecting) certain permissions was being ignored. As a result, the issued API key could end up with permissions the user explicitly rejected. The fix ensures rejected permissions are not granted and that the system correctly asks again later if an app requests a previously rejected permission.
Review and deploy this patch. Verify that non-strict OAuth-style authorization flows correctly honor user rejections and that re-authorization prompts for newly requested permissions. Audit any API keys issued before this patch to confirm they match the permissions users actually consented to.
Security signals we found
Authorization bypass: user rejection of API key permissions was not honored
Privilege escalation via over-permissive API key issuance
UI consent state not correctly propagated to stored permissions
Null reference risk in existing key matching logic
Regression test added for selective permission rejection
Evidence from the diff
The patch addresses two related issues in UIManageController.APIKeys.cs. First, in AdjustVMForAuthorization, it distinguishes between permissions the user rejected during authorization (non-strict mode) and those genuinely requested. Previously, the code unconditionally set permissionValue.Value = true, overriding the user’s rejection. Now it only sets Value=true when the permission was not rejected. Second, in CheckForMatchingApiKey, it adds a null check (existing == null) to prevent a possible NullReferenceException when matching existing keys. The added Playwright test verifies that rejecting a selective store permission results in an API key without that permission, and that a subsequent authorization request re-prompts the user for the missing permission.
Changed components
BTCPayServer/Controllers/UIManageController.APIKeys.csAPI key authorization/consent flowAPI key repository / permission blob storagePlaywright integration tests (ApiKeysTests.cs)Inspect captured patch +65 / −3
### BTCPayServer.Tests/ApiKeysTests.cs
@@ -208,6 +208,9 @@ await TestApiAgainstAccessToken(accessToken, tester, user,
Assert.Equal(callbackUrl, s.Page.Url);
accessToken = await GetAccessTokenFromCallbackResult(s);
+ // The permission the user rejected isn't granted
+ Assert.Equal(new[] { Permission.Create(Policies.CanModifyStoreSettings, user.StoreId).ToString() },
+ (await apiKeyRepo.GetKey(accessToken)).GetBlob().Permissions);
await TestApiAgainstAccessToken(accessToken, tester, user,
(await apiKeyRepo.GetKey(accessToken)).GetBlob().Permissions);
@@ -273,6 +276,55 @@ await TestApiAgainstAccessToken(accessToken, tester, user,
Assert.Contains("There are no associated permissions to the API key being requested", emptyPageContent);
}
+ [Fact]
+ [Trait("Playwright", "Playwright-2")]
+ public async Task CanRejectSelectiveStoreApiKeyPermission()
+ {
+ await using var s = CreatePlaywrightTester();
+ await s.StartAsync();
+
+ var user = s.Server.NewAccount();
+ await user.GrantAccessAsync();
+ await user.MakeAdmin(false);
+ await s.GoToLogin();
+ await s.LogIn(user.RegisterDetails.Email, user.RegisterDetails.Password);
+
+ const string applicationIdentifier = "selective-permission-test";
+ var callbackUrl = s.ServerUri + "postredirect-callback-test";
+ var requestedPermissions = new[] { Policies.CanModifyStoreSettings, Policies.CanViewProfile };
+ var authUrl = BTCPayServerClient.GenerateAuthorizeUri(s.ServerUri, requestedPermissions,
+ strict: false, selectiveStores: true,
+ applicationDetails: (applicationIdentifier, new Uri(callbackUrl))).ToString();
+
+ await s.GoToUrl(authUrl);
+ await s.Page.SelectOptionAsync("#StoreId", user.StoreId);
+ await s.Page.Locator("#continue").ClickAsync();
+ await s.Page.SetCheckedAsync("#btcpay\\.store\\.canmodifystoresettings", false);
+ await s.Page.Locator("#consent-yes").ClickAsync();
+ await s.Page.WaitForLoadStateAsync(LoadState.DOMContentLoaded);
+
+ var apiKeyRepo = s.Server.PayTester.GetService<APIKeyRepository>();
+ var accessToken = await GetAccessTokenFromCallbackResult(s);
+ var permissions = (await apiKeyRepo.GetKey(accessToken)).GetBlob().Permissions;
+ Assert.Equal(new[] { Policies.CanViewProfile }, permissions);
+
+ // An existing key without every requested permission is not sufficient. Show consent again so the
+ // user can decide whether to grant the newly requested permission.
+ await s.GoToUrl(authUrl);
+ Assert.Equal(1, await s.Page.Locator("select#StoreId").CountAsync());
+ Assert.DoesNotContain("previously generated the API Key", await s.Page.ContentAsync());
+
+ await s.Page.SelectOptionAsync("#StoreId", user.StoreId);
+ await s.Page.Locator("#continue").ClickAsync();
+ await s.Page.Locator("#consent-yes").ClickAsync();
+ await s.Page.WaitForLoadStateAsync(LoadState.DOMContentLoaded);
+
+ accessToken = await GetAccessTokenFromCallbackResult(s);
+ permissions = (await apiKeyRepo.GetKey(accessToken)).GetBlob().Permissions;
+ Assert.Contains(Policies.CanViewProfile, permissions);
+ Assert.Contains(Permission.Create(Policies.CanModifyStoreSettings, user.StoreId).ToString(), permissions);
+ }
+
[Fact]
[Trait("Playwright", "Playwright-2")]
public async Task CannotSubmitCommandForMissingApiKeyPermission()
### BTCPayServer/Controllers/UIManageController.APIKeys.cs
@@ -348,6 +348,12 @@ private async Task<APIKeyData> CheckForMatchingApiKey(IEnumerable<Permission> re
break;
}
+ if (existing == null)
+ {
+ fail = true;
+ break;
+ }
+
if (IsStorePolicy(requested.Key))
{
if ((vm.SelectiveStores && !existing.Any(p => p.Scope == vm.StoreId)) ||
@@ -419,10 +425,14 @@ private void AdjustVMForAuthorization(AuthorizeApiKeysViewModel vm)
continue;
}
- // Set the value to true and adjust the other fields based on the policy type
- permissionValue.Value = true;
+ // Requested permissions are preselected, but unless strict, the user can reject them when authorizing
+ var isRejected = !vm.Strict && !permissionValue.Value &&
+ "authorize".Equals(vm.Command, StringComparison.OrdinalIgnoreCase);
+
+ // Set the value and adjust the other fields based on the policy type
+ permissionValue.Value = !isRejected;
- if (vm.SelectiveStores && permissionValue.IsStorePolicy &&
+ if (!isRejected && vm.SelectiveStores && permissionValue.IsStorePolicy &&
wanted.Any(permission => !string.IsNullOrEmpty(permission.Scope)))
{
permissionValue.StoreMode = AddApiKeyViewModel.ApiKeyStoreMode.Specific;Why this scored 62/100
Community notes
Notes can correct, qualify, or add evidence to the AI analysis. Every note shown here has been validated by a human moderator.
The AI analysis stands alone for now. Submit a note if you can add evidence or important context.