Add dedicated permission and CSRF protection for invoice status changes (#7643)
What changed, and why it matters
This commit hardens BTCPay Server's invoice status changes. Previously, marking an invoice as settled or invalid required the broad 'modify invoices' permission and the web UI action ignored CSRF protection. The patch adds a dedicated, narrower permission for status changes and requires anti-forgery validation on the web UI endpoint, reducing the risk that a malicious web page or overly permissioned API key can flip invoice states.
Treat this as a security hardening patch and include it in the next release. Review existing API keys and user roles to ensure the new `CanManageInvoiceStatus` permission is granted only where needed, since `CanModifyInvoices` now implicitly includes it. No immediate incident response is indicated by the commit alone.
Security signals we found
Removal of [IgnoreAntiforgeryToken] from state-changing UI action
Addition of dedicated fine-grained permission for invoice status mutation
Authorization policy narrowed from CanModifyInvoices to CanManageInvoiceStatus
Anti-forgery token included in UI component and sent by JavaScript fetch
New unit tests asserting required policy and antiforgery validation
Evidence from the diff
The change introduces a new policy constant Policies.CanManageInvoiceStatus and applies it to both the UI ChangeInvoiceState action and the Greenfield API MarkInvoiceStatus action, replacing the previous CanModifyInvoices requirement. The UI action’s [IgnoreAntiforgeryToken] attribute is removed, an anti-forgery token is emitted in the invoice status component, and the accompanying JavaScript now sends the token in the RequestVerificationToken header. Tests verify the new authorization policy and the absence of antiforgery bypass. Swagger documentation is updated to reflect the new permission.
Changed components
BTCPayServer.Client/Permissions.csBTCPayServer/Controllers/UIInvoiceController.UI.csBTCPayServer/Controllers/GreenField/GreenfieldInvoiceController.csBTCPayServer/Components/InvoiceStatus/Default.cshtmlBTCPayServer/wwwroot/main/site.jsBTCPayServer/Hosting/BTCPayServerServices.csBTCPayServer.Tests/AuthorizationPolicyTests.csBTCPayServer.Tests/GreenfieldAPITests.csInspect captured patch +76 / −11
### BTCPayServer.Client/Permissions.cs
@@ -21,6 +21,7 @@ public class Policies
public const string CanViewReports = "btcpay.store.canviewreports";
public const string CanViewInvoices = "btcpay.store.canviewinvoices";
public const string CanCreateInvoice = "btcpay.store.cancreateinvoice";
+ public const string CanManageInvoiceStatus = "btcpay.store.canmanageinvoicestatus";
public const string CanModifyInvoices = "btcpay.store.canmodifyinvoices";
public const string CanViewPaymentRequests = "btcpay.store.canviewpaymentrequests";
public const string CanModifyPaymentRequests = "btcpay.store.canmodifypaymentrequests";
### BTCPayServer.Tests/AuthorizationPolicyTests.cs
@@ -0,0 +1,51 @@
+using System;
+using System.Linq;
+using System.Reflection;
+using BTCPayServer.Client;
+using BTCPayServer.Controllers;
+using BTCPayServer.Controllers.Greenfield;
+using Microsoft.AspNetCore.Authorization;
+using Microsoft.AspNetCore.Mvc;
+using Xunit;
+
+namespace BTCPayServer.Tests;
+
+public class AuthorizationPolicyTests(ITestOutputHelper helper) : UnitTestBase(helper)
+{
+ private static void AssertPolicy(Type controller, string action, string expectedPolicy)
+ {
+ var methods = controller.GetMethods(BindingFlags.Instance | BindingFlags.Public)
+ .Where(m => m.Name == action)
+ .ToArray();
+ Assert.NotEmpty(methods);
+ foreach (var method in methods)
+ {
+ var policies = method.GetCustomAttributes<AuthorizeAttribute>(true)
+ .Select(a => a.Policy)
+ .Where(p => p is not null)
+ .ToArray();
+ Assert.Contains(expectedPolicy, policies);
+ }
+ }
+
+ [Fact]
+ [Trait("Fast", "Fast")]
+ public void InvoiceStatusMutationsRequireManageStatusPermission()
+ {
+ AssertPolicy(typeof(UIInvoiceController), nameof(UIInvoiceController.ChangeInvoiceState), Policies.CanManageInvoiceStatus);
+ AssertPolicy(typeof(GreenfieldInvoiceController), nameof(GreenfieldInvoiceController.MarkInvoiceStatus), Policies.CanManageInvoiceStatus);
+ }
+
+ [Fact]
+ [Trait("Fast", "Fast")]
+ public void ChangeInvoiceStateRequiresAntiforgeryValidation()
+ {
+ var methods = typeof(UIInvoiceController)
+ .GetMethods(BindingFlags.Instance | BindingFlags.Public)
+ .Where(m => m.Name == nameof(UIInvoiceController.ChangeInvoiceState))
+ .ToArray();
+ Assert.NotEmpty(methods);
+ foreach (var method in methods)
+ Assert.Empty(method.GetCustomAttributes<IgnoreAntiforgeryTokenAttribute>(true));
+ }
+}
### BTCPayServer.Tests/GreenfieldAPITests.cs
@@ -2234,6 +2234,7 @@ public async Task InvoiceTests()
await user.SetupWebhook();
var client = await user.CreateClient(Policies.Unrestricted);
var viewOnly = await user.CreateClient(Policies.CanViewInvoices);
+ var statusOnly = await user.CreateClient(Policies.CanManageInvoiceStatus);
//create
@@ -2368,17 +2369,21 @@ await AssertValidationError(new[] { "startDate" },
new CreateInvoiceRequest { Currency = "USD", Amount = 1 });
Assert.Contains(InvoiceStatus.Settled, newInvoice.AvailableStatusesForManualMarking);
Assert.Contains(InvoiceStatus.Invalid, newInvoice.AvailableStatusesForManualMarking);
- await client.MarkInvoiceStatus(newInvoice.Id, new MarkInvoiceStatusRequest()
+ await AssertHttpError(403, () => viewOnly.MarkInvoiceStatus(newInvoice.Id, new MarkInvoiceStatusRequest
+ {
+ Status = InvoiceStatus.Settled
+ }));
+ await statusOnly.MarkInvoiceStatus(newInvoice.Id, new MarkInvoiceStatusRequest()
{
Status = InvoiceStatus.Settled
});
- newInvoice = await client.GetInvoice(newInvoice.Id);
+ newInvoice = await statusOnly.GetInvoice(newInvoice.Id);
Assert.DoesNotContain(InvoiceStatus.Settled, newInvoice.AvailableStatusesForManualMarking);
Assert.Contains(InvoiceStatus.Invalid, newInvoice.AvailableStatusesForManualMarking);
newInvoice = await client.CreateInvoice(user.StoreId,
new CreateInvoiceRequest { Currency = "USD", Amount = 1 });
- await client.MarkInvoiceStatus(newInvoice.Id, new MarkInvoiceStatusRequest()
+ await statusOnly.MarkInvoiceStatus(newInvoice.Id, new MarkInvoiceStatusRequest()
{
Status = InvoiceStatus.Invalid
});
@@ -2391,7 +2396,7 @@ await AssertValidationError(new[] { "startDate" },
Assert.DoesNotContain(InvoiceStatus.Invalid, newInvoice.AvailableStatusesForManualMarking);
await AssertHttpError(403, async () =>
{
- await viewOnly.UpdateInvoice(invoice.Id,
+ await statusOnly.UpdateInvoice(invoice.Id,
new UpdateInvoiceRequest
{
Metadata = metadataForUpdate
### BTCPayServer/Components/InvoiceStatus/Default.cshtml
@@ -15,6 +15,7 @@
<div class="badge badge-@badgeClass" data-invoice-state-badge="@Model.InvoiceId">
@if (canMark)
{
+ @Html.AntiForgeryToken()
<span class="dropdown-toggle" data-bs-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
@state
</span>
### BTCPayServer/Controllers/GreenField/GreenfieldInvoiceController.cs
@@ -239,7 +239,7 @@ request.Checkout.PaymentMethods[i] is not { } pm ||
}
}
- [Authorize(Policy = Policies.CanModifyInvoices,
+ [Authorize(Policy = Policies.CanManageInvoiceStatus,
AuthenticationSchemes = AuthenticationSchemes.Greenfield)]
[HttpPost("~/api/v1/stores/{storeId}/invoices/{invoiceId}/status")]
[HttpPost("~/api/v1/invoices/{invoiceId}/status")]
### BTCPayServer/Controllers/UIInvoiceController.UI.cs
@@ -1283,8 +1283,7 @@ public async Task<IActionResult> CreateInvoice(CreateInvoiceModel model, Cancell
[HttpPost]
[Route("invoices/{invoiceId}/changestate/{newState}")]
[Route("stores/{storeId}/invoices/{invoiceId}/changestate/{newState}")]
- [Authorize(AuthenticationSchemes = AuthenticationSchemes.Cookie, Policy = Policies.CanModifyInvoices)]
- [IgnoreAntiforgeryToken]
+ [Authorize(AuthenticationSchemes = AuthenticationSchemes.Cookie, Policy = Policies.CanManageInvoiceStatus)]
public async Task<IActionResult> ChangeInvoiceState(string invoiceId, string newState)
{
var invoice = (await _InvoiceRepository.GetInvoices(new InvoiceQuery
### BTCPayServer/Hosting/BTCPayServerServices.cs
@@ -562,11 +562,16 @@ CREATE INDEX IF NOT EXISTS idx_invoices_expired_cleanup
Policies.CanCreateInvoice,
new PermissionDisplay("Create an invoice", "Allows creating new invoices."),
new PermissionDisplay("Create an invoice", "Allows creating new invoices on the selected stores.")),
+ new PolicyDefinition(
+ Policies.CanManageInvoiceStatus,
+ new PermissionDisplay("Manage invoice status", "Allows viewing invoices and marking them as settled or invalid."),
+ new PermissionDisplay("Manage invoice status", "Allows viewing invoices and marking them as settled or invalid on the selected stores."),
+ new[] { Policies.CanViewInvoices }),
new PolicyDefinition(
Policies.CanModifyInvoices,
new PermissionDisplay("Modify invoices", "Allows viewing and modifying invoices."),
new PermissionDisplay("Modify invoices", "Allows viewing and modifying invoices on the selected stores."),
- new[] { Policies.CanViewInvoices, Policies.CanCreateInvoice, Policies.CanCreateLightningInvoiceInStore }),
+ new[] { Policies.CanViewInvoices, Policies.CanCreateInvoice, Policies.CanManageInvoiceStatus, Policies.CanCreateLightningInvoiceInStore }),
new PolicyDefinition(
Policies.CanModifyWebhooks,
new PermissionDisplay("Modify stores webhooks", "Allows modifying the webhooks of all your stores."),
### BTCPayServer/wwwroot/main/site.js
@@ -475,7 +475,10 @@ document.addEventListener("DOMContentLoaded", () => {
const { invoiceId, newState } = $button.dataset
$badge.classList.add('pe-none'); // disable further interaction
- const response = await fetch(`${baseUrl}/invoices/${invoiceId}/changestate/${newState}`, { method: 'POST' })
+ const tokenInput = $badge.querySelector('input[name="__RequestVerificationToken"]')
+ const headers = {}
+ if (tokenInput?.value) headers.RequestVerificationToken = tokenInput.value
+ const response = await fetch(`${baseUrl}/invoices/${invoiceId}/changestate/${newState}`, { method: 'POST', headers })
if (response.ok) {
const { statusString } = await response.json()
$badge.outerHTML = `<div class="badge badge-${newState}" data-invoice-state-badge="${invoiceId}">${statusString}</div>`
### BTCPayServer/wwwroot/swagger/v1/swagger.template.invoices.json
@@ -458,7 +458,7 @@
"security": [
{
"API_Key": [
- "btcpay.store.canmodifyinvoices"
+ "btcpay.store.canmanageinvoicestatus"
],
"Basic": []
}
### BTCPayServer/wwwroot/swagger/v1/swagger.template.json
@@ -216,7 +216,7 @@
"securitySchemes": {
"API_Key": {
"type": "apiKey",
- "description": "BTCPay Server supports authenticating and authorizing users through an API Key that is generated by them. Send the API Key as a header value to Authorization with the format: `token {token}`. For a smoother experience, you can generate a url that redirects users to an API key creation screen.\n\n The following permissions are available to the context of the user creating the API Key:\n\n* `btcpay.impersonation.canimpersonate`: Can impersonate users\n* `btcpay.user.candeleteuser`: Delete user\n* `btcpay.user.canmanagenotificationsforuser`: Manage your notifications\n* `btcpay.user.canmodifyprofile`: Manage your profile\n* `btcpay.user.canviewnotificationsforuser`: View your notifications\n* `btcpay.user.canviewprofile`: View your profile\n* `unrestricted`: Unrestricted access\n\nThe following permissions are available if the user is an administrator:\n\n* `btcpay.server.cancreatelightninginvoiceinternalnode`: Create invoices with internal lightning node\n* `btcpay.server.cancreateuser`: Create new users\n* `btcpay.server.canmanageusers`: Manage users\n* `btcpay.server.canmodifyserversettings`: Manage your server\n* `btcpay.server.canuseinternallightningnode`: Use the internal lightning node\n* `btcpay.server.canviewlightninginvoiceinternalnode`: View invoices from internal lightning node\n* `btcpay.server.canviewusers`: View users\n\nThe following permissions applies to all stores of the user, you can limit to a specific store with the following format: `btcpay.store.cancreateinvoice:6HSHAEU4iYWtjxtyRs9KyPjM9GAQp8kw2T9VWbGG1FnZ`:\n\n* `btcpay.store.canarchivepullpayments`: Archive your pull payments\n* `btcpay.store.canbroadcasttransactions`: Broadcast wallet transactions\n* `btcpay.store.cancanceltransactions`: Cancel wallet transactions\n* `btcpay.store.cancreateinvoice`: Create an invoice\n* `btcpay.store.cancreatelightninginvoice`: Create invoices from the lightning nodes associated with your stores\n* `btcpay.store.cancreatenonapprovedpullpayments`: Create non-approved pull payments\n* `btcpay.store.cancreatepullpayments`: Create pull payments\n* `btcpay.store.cancreatetransactions`: Create wallet transactions\n* `btcpay.store.cancreditsubscribers`: Credit your subscribers\n* `btcpay.store.canmanagelegacyaccesstokens`: Manage legacy access tokens\n* `btcpay.store.canmanagepayouts`: Manage payouts\n* `btcpay.store.canmanagepullpayments`: Manage your pull payments\n* `btcpay.store.canmanagesubscribers`: Manage your subscribers\n* `btcpay.store.canmanagewallets`: Manage wallets\n* `btcpay.store.canmanagewalletsettings`: Manage wallet settings\n* `btcpay.store.canmanagewallettransactions`: Manage wallet transactions\n* `btcpay.store.canmodifyinvoices`: Modify invoices\n* `btcpay.store.canmodifyofferings`: Modify your offerings\n* `btcpay.store.canmodifypaymentrequests`: Modify your payment requests\n* `btcpay.store.canmodifystoresettings`: Modify your stores\n* `btcpay.store.cansendstoreemails`: Send store emails\n* `btcpay.store.cansigntransactions`: Sign wallet transactions\n* `btcpay.store.canuselightningnode`: Use the lightning nodes associated with your stores\n* `btcpay.store.canviewinvoices`: View invoices\n* `btcpay.store.canviewlightninginvoice`: View the lightning invoices associated with your stores\n* `btcpay.store.canviewofferings`: View your offerings\n* `btcpay.store.canviewpaymentrequests`: View your payment requests\n* `btcpay.store.canviewpayouts`: View payouts\n* `btcpay.store.canviewpullpayments`: View your pull payments\n* `btcpay.store.canviewreports`: View your reports\n* `btcpay.store.canviewstoresettings`: View your stores\n* `btcpay.store.canviewwallet`: View wallets\n* `btcpay.store.webhooks.canmodifywebhooks`: Modify stores webhooks\n\nNote that API Keys only limits permission of a user and can never expand it. If an API Key has the permission `btcpay.server.canmodifyserversettings` but that the user account creating this API Key is not administrator, the API Key will not be able to modify the server settings.\nSome permissions may include other permissions, see [this operation](#operation/permissionsMetadata).\n",
+ "description": "BTCPay Server supports authenticating and authorizing users through an API Key that is generated by them. Send the API Key as a header value to Authorization with the format: `token {token}`. For a smoother experience, you can generate a url that redirects users to an API key creation screen.\n\n The following permissions are available to the context of the user creating the API Key:\n\n* `btcpay.impersonation.canimpersonate`: Can impersonate users\n* `btcpay.user.candeleteuser`: Delete user\n* `btcpay.user.canmanagenotificationsforuser`: Manage your notifications\n* `btcpay.user.canmodifyprofile`: Manage your profile\n* `btcpay.user.canviewnotificationsforuser`: View your notifications\n* `btcpay.user.canviewprofile`: View your profile\n* `unrestricted`: Unrestricted access\n\nThe following permissions are available if the user is an administrator:\n\n* `btcpay.server.cancreatelightninginvoiceinternalnode`: Create invoices with internal lightning node\n* `btcpay.server.cancreateuser`: Create new users\n* `btcpay.server.canmanageusers`: Manage users\n* `btcpay.server.canmodifyserversettings`: Manage your server\n* `btcpay.server.canuseinternallightningnode`: Use the internal lightning node\n* `btcpay.server.canviewlightninginvoiceinternalnode`: View invoices from internal lightning node\n* `btcpay.server.canviewusers`: View users\n\nThe following permissions applies to all stores of the user, you can limit to a specific store with the following format: `btcpay.store.cancreateinvoice:6HSHAEU4iYWtjxtyRs9KyPjM9GAQp8kw2T9VWbGG1FnZ`:\n\n* `btcpay.store.canarchivepullpayments`: Archive your pull payments\n* `btcpay.store.canbroadcasttransactions`: Broadcast wallet transactions\n* `btcpay.store.cancanceltransactions`: Cancel wallet transactions\n* `btcpay.store.cancreateinvoice`: Create an invoice\n* `btcpay.store.cancreatelightninginvoice`: Create invoices from the lightning nodes associated with your stores\n* `btcpay.store.cancreatenonapprovedpullpayments`: Create non-approved pull payments\n* `btcpay.store.cancreatepullpayments`: Create pull payments\n* `btcpay.store.cancreatetransactions`: Create wallet transactions\n* `btcpay.store.cancreditsubscribers`: Credit your subscribers\n* `btcpay.store.canmanageinvoicestatus`: Manage invoice status\n* `btcpay.store.canmanagelegacyaccesstokens`: Manage legacy access tokens\n* `btcpay.store.canmanagepayouts`: Manage payouts\n* `btcpay.store.canmanagepullpayments`: Manage your pull payments\n* `btcpay.store.canmanagesubscribers`: Manage your subscribers\n* `btcpay.store.canmanagewallets`: Manage wallets\n* `btcpay.store.canmanagewalletsettings`: Manage wallet settings\n* `btcpay.store.canmanagewallettransactions`: Manage wallet transactions\n* `btcpay.store.canmodifyinvoices`: Modify invoices\n* `btcpay.store.canmodifyofferings`: Modify your offerings\n* `btcpay.store.canmodifypaymentrequests`: Modify your payment requests\n* `btcpay.store.canmodifystoresettings`: Modify your stores\n* `btcpay.store.cansendstoreemails`: Send store emails\n* `btcpay.store.cansigntransactions`: Sign wallet transactions\n* `btcpay.store.canuselightningnode`: Use the lightning nodes associated with your stores\n* `btcpay.store.canviewinvoices`: View invoices\n* `btcpay.store.canviewlightninginvoice`: View the lightning invoices associated with your stores\n* `btcpay.store.canviewofferings`: View your offerings\n* `btcpay.store.canviewpaymentrequests`: View your payment requests\n* `btcpay.store.canviewpayouts`: View payouts\n* `btcpay.store.canviewpullpayments`: View your pull payments\n* `btcpay.store.canviewreports`: View your reports\n* `btcpay.store.canviewstoresettings`: View your stores\n* `btcpay.store.canviewwallet`: View wallets\n* `btcpay.store.webhooks.canmodifywebhooks`: Modify stores webhooks\n\nNote that API Keys only limits permission of a user and can never expand it. If an API Key has the permission `btcpay.server.canmodifyserversettings` but that the user account creating this API Key is not administrator, the API Key will not be able to modify the server settings.\nSome permissions may include other permissions, see [this operation](#operation/permissionsMetadata).\n",
"name": "Authorization",
"in": "header"
},Why this scored 74/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.