Enforce API key permission scope (#7684)
What changed, and why it matters
This commit fixes a permission-handling bug in BTCPay Server's Greenfield API. Previously, an API key that was only supposed to manage a single store could be used to create or request broader, server-wide permissions it did not actually have. The change now checks every requested permission against what the current key is allowed to grant, and it also tightens how store-scoped permissions are matched during authorization. In short, it stops a limited key from being upgraded into a more powerful one.
Treat this as a security fix and include it in the next release. Users running affected versions should upgrade promptly, especially if they issue store-scoped or restricted API keys to third parties. Review existing API keys for any that were created with broader permissions than their parent key should have allowed, and rotate them after patching.
Security signals we found
Privilege escalation via API key creation
Missing authorization check on permission grant
Scope confusion between store-scoped and server-wide permissions
Permission hierarchy not enforced before minting new keys
Added defensive integration tests for escalation paths
Evidence from the diff
The patch enforces scope and privilege constraints on API key creation. GreenfieldApiKeysController.CreateUserAPIKey now resolves the calling user’s granted permissions from their claims, compares each requested permission against the permission hierarchy via PermissionService.PermissionNodesByPolicy, and rejects any request that asks for a permission not already held (considering both parent policies and scoped variants). It also changes PermissionAuthorizationHandler so that the anyScope fallback applies only to PolicyType.Store permissions, preventing broader server-level permissions from being satisfied by a scoped store key. New integration tests verify that a store-scoped Unrestricted key cannot call server APIs or delete the user account, and that a CanModifyServerSettings key cannot mint an Unrestricted key.
Changed components
BTCPayServer.Controllers.GreenField.GreenfieldApiKeysControllerBTCPayServer.Security.PermissionAuthorizationHandlerGreenfield API key management endpointsPermission authorization pipelineInspect captured patch +87 / −3
### BTCPayServer.Tests/GreenfieldAPITests.cs
@@ -204,6 +204,64 @@ await AssertHttpError(403, () => scopedClient.CreateAPIKey(new CreateApiKeyReque
}));
}
+ [Fact(Timeout = TestTimeout)]
+ [Trait("Integration", "Integration")]
+ public async Task StoreScopedAdminKeyCannotUseServerPermissions()
+ {
+ using var tester = CreateServerTester();
+ await tester.StartAsync();
+ var admin = tester.NewAccount();
+ await admin.GrantAccessAsync(isAdmin: true);
+
+ var accountClient = await admin.CreateClient();
+ var scopedKey = await accountClient.CreateAPIKey(new CreateApiKeyRequest
+ {
+ Label = "Store-scoped admin key",
+ Permissions = new[] { Permission.Create(Policies.Unrestricted, admin.StoreId) }
+ });
+ var scopedClient = admin.CreateClientFromAPIKey(scopedKey.ApiKey);
+
+ await AssertPermissionError(Policies.CanModifyServerSettings, () => scopedClient.GetServerRoles());
+ }
+
+ [Fact(Timeout = TestTimeout)]
+ [Trait("Integration", "Integration")]
+ public async Task StoreScopedUnrestrictedKeyCannotDeleteUserAccount()
+ {
+ using var tester = CreateServerTester();
+ await tester.StartAsync();
+ var user = tester.NewAccount();
+ await user.GrantAccessAsync();
+
+ var accountClient = await user.CreateClient();
+ var scopedKey = await accountClient.CreateAPIKey(new CreateApiKeyRequest
+ {
+ Label = "Store-scoped key",
+ Permissions = new[] { Permission.Create(Policies.Unrestricted, user.StoreId) }
+ });
+ var scopedClient = user.CreateClientFromAPIKey(scopedKey.ApiKey);
+
+ await AssertHttpError(403, () => scopedClient.DeleteCurrentUser());
+ }
+
+ [Fact(Timeout = TestTimeout)]
+ [Trait("Integration", "Integration")]
+ public async Task ServerSettingsKeyCannotMintUnrestrictedKey()
+ {
+ using var tester = CreateServerTester();
+ await tester.StartAsync();
+ var admin = tester.NewAccount();
+ await admin.GrantAccessAsync(isAdmin: true);
+
+ var restrictedClient = await admin.CreateClient(Policies.CanModifyServerSettings);
+ await AssertPermissionError(Policies.Unrestricted, () => restrictedClient.CreateAPIKey(
+ admin.UserId,
+ new CreateApiKeyRequest
+ {
+ Permissions = new[] { Permission.Create(Policies.Unrestricted) }
+ }));
+ }
+
[Fact(Timeout = TestTimeout)]
[Trait("Integration", "Integration")]
public async Task CanUseMiscAPIs()
### BTCPayServer/Controllers/GreenField/GreenfieldApiKeysController.cs
@@ -6,6 +6,7 @@
using BTCPayServer.Client.Models;
using BTCPayServer.Data;
using BTCPayServer.Security.Greenfield;
+using BTCPayServer.Services;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Identity;
@@ -18,7 +19,10 @@ namespace BTCPayServer.Controllers.Greenfield
[ApiController]
[Authorize(AuthenticationSchemes = AuthenticationSchemes.GreenfieldAPIKeys)]
[EnableCors(CorsPolicies.All)]
- public class GreenfieldApiKeysController(APIKeyRepository apiKeyRepository, UserManager<ApplicationUser> userManager) : ControllerBase
+ public class GreenfieldApiKeysController(
+ APIKeyRepository apiKeyRepository,
+ UserManager<ApplicationUser> userManager,
+ PermissionService permissionService) : ControllerBase
{
[HttpGet("~/api/v1/api-keys/current")]
public async Task<IActionResult> GetKey()
@@ -45,6 +49,27 @@ public async Task<IActionResult> CreateUserAPIKey(string idOrEmail, CreateApiKey
request ??= new CreateApiKeyRequest();
request.Permissions ??= System.Array.Empty<Permission>();
+ var grantedPermissions = Permission.ToPermissions(User.Claims
+ .Where(c => c.Type == GreenfieldConstants.ClaimTypes.Permission)
+ .Select(c => c.Value)
+ .ToArray()).Select(permission => permission.ToString()).ToHashSet();
+ var requestedPermissions = request.Permissions.Distinct().ToArray();
+ var deniedPermission = requestedPermissions.FirstOrDefault(requested =>
+ !IsPermissionGranted(requested));
+ if (deniedPermission is not null)
+ return this.CreateAPIPermissionError(deniedPermission.ToString());
+
+ bool IsPermissionGranted(Permission requested)
+ {
+ if (!permissionService.PermissionNodesByPolicy.TryGetValue(requested.Policy, out var node))
+ return false;
+
+ return node.EnumerateParents().Any(parent =>
+ grantedPermissions.Contains(parent.Definition.Policy) ||
+ requested.Scope is not null &&
+ grantedPermissions.Contains($"{parent.Definition.Policy}:{requested.Scope}"));
+ }
+
var userId = (await userManager.FindByIdOrEmail(idOrEmail))?.Id;
if (userId is null)
return this.UserNotFound();
@@ -54,7 +79,7 @@ public async Task<IActionResult> CreateUserAPIKey(string idOrEmail, CreateApiKey
key.Label = request.Label;
key.SetBlob(new APIKeyBlob()
{
- Permissions = request.Permissions.Select(p => p.ToString()).Distinct().ToArray()
+ Permissions = requestedPermissions.Select(p => p.ToString()).ToArray()
});
await apiKeyRepository.CreateKey(key);
return Ok(FromModel(key));
### BTCPayServer/Security/PermissionAuthorizationHandler.cs
@@ -2,6 +2,7 @@
using System.Collections.Generic;
using System.Threading.Tasks;
using BTCPayServer.Abstractions.Constants;
+using BTCPayServer.Client;
using BTCPayServer.Security.Greenfield;
using BTCPayServer.Services;
using Microsoft.AspNetCore.Authorization;
@@ -60,7 +61,7 @@ private async Task Handle(AuthorizationHandlerContext context, PolicyRequirement
// Now imagine that the api key has "btcpay.store.canviewstoresettings:StoreA"
// The route should still be accessible by the API key.
// However, the action is responsible for only allowing `StoreA` to be shown in the list.
- if (!context.HasPermission(ctx.Permission, permissionService, anyScope: true))
+ if (!context.HasPermission(ctx.Permission, permissionService, anyScope: ctx.Permission.Type is PolicyType.Store))
return;
}
Why this scored 77/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.