Fix LNURL authentication, rate expansion and subscription credit rounding (#7762)
What changed, and why it matters
This commit fixes several unrelated bugs in BTCPay Server. The most security-relevant changes are: (1) LNURL authentication now uses expiring challenges tied to a user's security stamp, preventing old or stale login challenges from being reused; (2) notifications are now filtered by store permission policy, so users without the right role no longer receive sensitive payout/invoice notifications; (3) subscription credit rounding is changed so customers cannot be credited more than they actually paid; and (4) a memory-cache fix prevents lightning address lookups from returning stale null results. The rate-rule change adds a length limit to prevent very large nested rate expressions from being processed.
Review and deploy this patch promptly. Validate LNURL auth flows, confirm notification recipients match expected store roles, and verify subscription credit calculations do not exceed paid amounts. Consider adding regression tests for stale LNURL challenge reuse and notification policy filtering.
Security signals we found
LNURL auth challenge reuse / stale-k1 issue mitigated by expiration and security-stamp binding
Store notifications now scoped by permission policy, reducing information disclosure to under-privileged users
Subscription credit rounding changed to prevent over-crediting customers
Rate expression flattening bounded by maximum length to limit CPU/memory consumption
Memory-cache no longer caches missing lightning-address lookups, preventing stale negative cache hits
Evidence from the diff
The patch bundles four distinct fixes. LNURL auth replaces raw 32-byte k1 values with a Challenge record containing k1, the user’s SecurityStamp, and a 5-minute expiration; CompleteCreation, CompleteLogin, and the final login check now validate the challenge against the current user. Notification scopes gain a Policy property and NotificationSender filters store users by whether their role’s permission set includes the required policy (CanViewPayouts/CanViewInvoices), restricting event-driven notifications to authorized users. Subscriptions change credit rounding to MidpointRounding.ToZero and round plan price and top-up values before arithmetic, ensuring credited amounts never exceed paid amounts. LightningAddressService avoids caching null results by only setting the cache when a result is found. RateRules.cs adds a MaxFlattenedLength cap to limit expansion of nested rate expressions.
Changed components
BTCPayServer/Controllers/LnurlAuthService.csBTCPayServer/Controllers/UIAccountController.csBTCPayServer/Services/Notifications/NotificationScopes.csBTCPayServer/Services/Notifications/NotificationSender.csBTCPayServer/HostedServices/InvoiceWatcher.csBTCPayServer/HostedServices/PullPaymentHostedService.csBTCPayServer/Data/Payouts/BitcoinLike/BitcoinLikePayoutHandler.csBTCPayServer/Plugins/Subscriptions/SubscriptionContext.csBTCPayServer/Plugins/Subscriptions/SubscriptionHostedService.csBTCPayServer/Controllers/LightningAddressService.csBTCPayServer.Rating/RateRules.csInspect captured patch +108 / −33
### BTCPayServer.Rating/RateRules.cs
@@ -544,6 +544,8 @@ public FlattenExpressionRewriter(RateRules parent, CurrencyPair pair)
public List<RateRulesErrors> Errors = new List<RateRulesErrors>();
const int MaxNestedCount = 8;
+ const int MaxFlattenedLength = 20_000;
+ int flattenedLength;
public override SyntaxNode? VisitIdentifierName(IdentifierNameSyntax node)
{
if (
@@ -560,13 +562,15 @@ public FlattenExpressionRewriter(RateRules parent, CurrencyPair pair)
else // eg. replace BTC_X to BTC_USD, then replace by the expression for BTC_USD
{
var bestCandidate = parent.FindBestCandidate(replacedPair);
- if (nested > MaxNestedCount)
+ flattenedLength += bestCandidate.FullSpan.Length;
+ if (nested > MaxNestedCount || flattenedLength > MaxFlattenedLength || Errors.Contains(RateRulesErrors.TooMuchNestedCalls))
{
Errors.Add(RateRulesErrors.TooMuchNestedCalls);
return RateRules.CreateExpression($"ERR_TOO_MUCH_NESTED_CALLS({replacedPair})");
}
var innerFlatten = CreateNewContext(replacedPair);
var replaced = innerFlatten.Visit(bestCandidate);
+ flattenedLength = innerFlatten.flattenedLength;
if (replaced is ExpressionSyntax expression)
{
var hasBinaryOps = new HasBinaryOperations();
@@ -592,6 +596,7 @@ private FlattenExpressionRewriter CreateNewContext(CurrencyPair pair)
{
Errors = Errors,
nested = nested + 1,
+ flattenedLength = flattenedLength,
ExchangeRates = ExchangeRates,
};
}
### BTCPayServer.Tests/SubscriptionSecurityTests.cs
@@ -1,5 +1,11 @@
using System;
+using BTCPayServer.Client.Models;
+using BTCPayServer.Data;
using BTCPayServer.Data.Subscriptions;
+using BTCPayServer.Plugins.Subscriptions;
+using BTCPayServer.Services.Invoices;
+using BTCPayServer.Services.Rates;
+using Microsoft.Extensions.Logging.Abstractions;
using Xunit;
namespace BTCPayServer.Tests;
@@ -23,4 +29,33 @@ public void UnusedPeriodAmountCannotExceedPaidAmount()
Assert.NotNull(unused);
Assert.InRange(unused.Value, 0m, subscriber.PaidAmount!.Value);
}
+
+ [Theory]
+ [InlineData(0.0051, 0.0)]
+ [InlineData(0.01, 0.01)]
+ [InlineData(0.0151, 0.01)]
+ [InlineData(10.00000002, 10.0)]
+ public void InvoiceCreditCannotExceedPaidAmount(decimal paid, decimal expectedCredit)
+ {
+ var subCtx = new SubscriptionContext(null!, null!, new CurrencyNameTable([], NullLogger<CurrencyNameTable>.Instance), default);
+ foreach (var status in new[] { InvoiceStatus.Processing, InvoiceStatus.Settled })
+ {
+ var invoice = new InvoiceEntity { Currency = "USD", Price = paid, Status = status };
+ invoice.AddRate(new("BTC", "USD"), 100_000m);
+#pragma warning disable CS0618
+ invoice.Payments = [new PaymentEntity
+ {
+ Currency = "BTC",
+ Value = paid / 100_000m,
+ Status = status == InvoiceStatus.Processing ? PaymentStatus.Processing : PaymentStatus.Settled
+ }];
+#pragma warning restore CS0618
+ invoice.UpdateTotals();
+
+ var credit = subCtx.GetAmountToCredit(invoice);
+ Assert.Equal(paid, invoice.PaidAmount.Net);
+ Assert.Equal(expectedCredit, credit);
+ Assert.True(credit <= paid);
+ }
+ }
}
### BTCPayServer/Controllers/LightningAddressService.cs
@@ -46,11 +46,14 @@ private async Task<List<LightningAddressData>> GetCore(ApplicationDbContext cont
public async Task<LightningAddressData?> ResolveByAddress(string username)
{
- return await _memoryCache.GetOrCreateAsync(GetKey(username), async entry =>
- {
- var result = await Get(new LightningAddressQuery { Usernames = new[] { NormalizeUsername(username) } });
- return result.FirstOrDefault();
- });
+ var key = GetKey(username);
+ if (_memoryCache.TryGetValue(key, out LightningAddressData? cached))
+ return cached;
+ var result = (await Get(new LightningAddressQuery { Usernames = new[] { NormalizeUsername(username) } }))
+ .FirstOrDefault();
+ if (result is not null)
+ _memoryCache.Set(key, result);
+ return result;
}
public async Task<bool> Set(LightningAddressData data)
### BTCPayServer/Controllers/LnurlAuthService.cs
@@ -18,12 +18,21 @@ public class LoginWithLNURLAuthViewModel
public class LnurlAuthService
{
- public readonly ConcurrentDictionary<string, byte[]> CreationStore =
- new ConcurrentDictionary<string, byte[]>();
- public readonly ConcurrentDictionary<string, byte[]> LoginStore =
- new ConcurrentDictionary<string, byte[]>();
- public readonly ConcurrentDictionary<string, byte[]> FinalLoginStore =
- new ConcurrentDictionary<string, byte[]>();
+ public record Challenge(byte[] K1, string SecurityStamp, DateTimeOffset Expiration)
+ {
+ public Challenge(ApplicationUser user) : this(RandomUtils.GetBytes(32), user.SecurityStamp, DateTimeOffset.UtcNow.AddMinutes(5))
+ {
+ }
+
+ public bool IsValid(ApplicationUser user) => DateTimeOffset.UtcNow < Expiration && SecurityStamp == user.SecurityStamp;
+ }
+
+ public readonly ConcurrentDictionary<string, Challenge> CreationStore =
+ new ConcurrentDictionary<string, Challenge>();
+ public readonly ConcurrentDictionary<string, Challenge> LoginStore =
+ new ConcurrentDictionary<string, Challenge>();
+ public readonly ConcurrentDictionary<string, Challenge> FinalLoginStore =
+ new ConcurrentDictionary<string, Challenge>();
private readonly ApplicationDbContextFactory _contextFactory;
private readonly ILogger<LnurlAuthService> _logger;
@@ -42,9 +51,9 @@ public async Task<byte[]> RequestCreation(string userId)
{
return null;
}
- var k1 = RandomUtils.GetBytes(32);
- CreationStore.AddOrReplace(userId, k1);
- return k1;
+ var challenge = new Challenge(user);
+ CreationStore.AddOrReplace(userId, challenge);
+ return challenge.K1;
}
public async Task<bool> CompleteCreation(string name, string userId, ECDSASignature sig, PubKey pubKey)
@@ -55,12 +64,12 @@ public async Task<bool> CompleteCreation(string name, string userId, ECDSASignat
var user = await dbContext.Users.Include(applicationUser => applicationUser.Fido2Credentials)
.FirstOrDefaultAsync(applicationUser => applicationUser.Id == userId);
var pubkeyBytes = pubKey.ToBytes();
- if (!CreationStore.TryGetValue(userId.ToLowerInvariant(), out var k1) || user == null || await dbContext.Fido2Credentials.AnyAsync(credential => credential.Type == Fido2Credential.CredentialType.LNURLAuth && credential.Blob == pubkeyBytes))
+ if (!CreationStore.TryGetValue(userId.ToLowerInvariant(), out var challenge) || user == null || !challenge.IsValid(user) || await dbContext.Fido2Credentials.AnyAsync(credential => credential.Type == Fido2Credential.CredentialType.LNURLAuth && credential.Blob == pubkeyBytes))
{
return false;
}
- if (!LNURL.LNAuthRequest.VerifyChallenge(sig, pubKey, k1))
+ if (!LNURL.LNAuthRequest.VerifyChallenge(sig, pubKey, challenge.K1))
{
return false;
}
@@ -102,11 +111,11 @@ public async Task<byte[]> RequestLogin(string userId)
return null;
}
- var k1 = RandomUtils.GetBytes(32);
+ var challenge = new Challenge(user);
FinalLoginStore.TryRemove(userId, out _);
- LoginStore.AddOrReplace(userId, k1);
- return k1;
+ LoginStore.AddOrReplace(userId, challenge);
+ return challenge.K1;
}
public async Task<bool> CompleteLogin(string userId, ECDSASignature sig, PubKey pubKey)
@@ -115,7 +124,7 @@ public async Task<bool> CompleteLogin(string userId, ECDSASignature sig, PubKey
userId = userId.ToLowerInvariant();
var user = await dbContext.Users.Include(applicationUser => applicationUser.Fido2Credentials)
.FirstOrDefaultAsync(applicationUser => applicationUser.Id == userId);
- if (user == null || !LoginStore.TryGetValue(userId, out var k1))
+ if (user == null || !LoginStore.TryGetValue(userId, out var challenge) || !challenge.IsValid(user))
{
return false;
}
@@ -128,7 +137,7 @@ public async Task<bool> CompleteLogin(string userId, ECDSASignature sig, PubKey
{
return false;
}
- if (!LNURL.LNAuthRequest.VerifyChallenge(sig, pubKey, k1))
+ if (!LNURL.LNAuthRequest.VerifyChallenge(sig, pubKey, challenge.K1))
{
return false;
}
@@ -137,7 +146,7 @@ public async Task<bool> CompleteLogin(string userId, ECDSASignature sig, PubKey
await dbContext.SaveChangesAsync();
LoginStore.Remove(userId, out _);
- FinalLoginStore.AddOrReplace(userId, k1);
+ FinalLoginStore.AddOrReplace(userId, challenge);
// 7. return OK to client
return true;
}
### BTCPayServer/Controllers/UIAccountController.cs
@@ -344,8 +344,8 @@ public async Task<IActionResult> LoginWithLNURLAuth(LoginWithLNURLAuthViewModel
try
{
var k1 = Encoders.Hex.DecodeData(viewModel.LNURLEndpoint.ParseQueryString().Get("k1"));
- if (lnurlAuthService.FinalLoginStore.TryRemove(user.Id, out var storedk1) &&
- storedk1.SequenceEqual(k1))
+ if (lnurlAuthService.FinalLoginStore.TryRemove(user.Id, out var challenge) &&
+ challenge.IsValid(user) && challenge.K1.SequenceEqual(k1))
{
lnurlAuthService.FinalLoginStore.TryRemove(user.Id, out _);
return await RedirectLoginSuccess(user, session);
### BTCPayServer/Data/Payouts/BitcoinLike/BitcoinLikePayoutHandler.cs
@@ -5,6 +5,7 @@
using System.Threading.Tasks;
using BTCPayServer;
using BTCPayServer.Abstractions.Models;
+using BTCPayServer.Client;
using BTCPayServer.Client.Models;
using BTCPayServer.Data;
using BTCPayServer.Events;
@@ -425,7 +426,7 @@ await WalletRepository.AddWalletTransactionAttachment(
}
else
{
- await _notificationSender.SendNotification(new StoreScope(payout.StoreDataId),
+ await _notificationSender.SendNotification(new StoreScope(payout.StoreDataId) { Policy = Policies.CanViewPayouts },
new ExternalPayoutTransactionNotification()
{
PaymentMethod = payout.PayoutMethodId,
### BTCPayServer/HostedServices/InvoiceWatcher.cs
@@ -4,6 +4,7 @@
using System.Threading;
using System.Threading.Channels;
using System.Threading.Tasks;
+using BTCPayServer.Client;
using BTCPayServer.Client.Models;
using BTCPayServer.Data;
using BTCPayServer.Events;
@@ -240,7 +241,7 @@ public Task StartAsync(CancellationToken cancellationToken)
{
if (InvoiceEventNotification.HandlesEvent(b.Name))
{
- await _notificationSender.SendNotification(new StoreScope(b.Invoice.StoreId),
+ await _notificationSender.SendNotification(new StoreScope(b.Invoice.StoreId) { Policy = Policies.CanViewInvoices },
new InvoiceEventNotification(b.Invoice.Id, b.Name, b.Invoice.StoreId));
}
if (b.Name == InvoiceEvent.Created)
### BTCPayServer/HostedServices/PullPaymentHostedService.cs
@@ -5,6 +5,7 @@
using System.Threading.Channels;
using System.Threading.Tasks;
using BTCPayServer.Abstractions.Extensions;
+using BTCPayServer.Client;
using BTCPayServer.Client.Models;
using BTCPayServer.Data;
using BTCPayServer.Data.Payouts.LightningLike;
@@ -782,7 +783,7 @@ await HandleApproval(new PayoutApproval()
}
req.Completion.TrySetResult(response);
- await _notificationSender.SendNotification(new StoreScope(payout.StoreDataId),
+ await _notificationSender.SendNotification(new StoreScope(payout.StoreDataId) { Policy = Policies.CanViewPayouts },
new PayoutNotification()
{
StoreId = payout.StoreDataId,
### BTCPayServer/Plugins/Subscriptions/SubscriptionContext.cs
@@ -26,12 +26,15 @@ public class SubscriptionContext(ApplicationDbContext ctx, EventAggregator aggre
public IReadOnlyList<object> Events => _evts;
public decimal RoundAmount(decimal amount, string currency)
- => Math.Round(amount, currencyNameTable.GetNumberFormatInfo(currency)?.CurrencyDecimalDigits ?? 2);
+ => RoundAmount(amount, currency, MidpointRounding.ToEven);
+
+ public decimal RoundAmount(decimal amount, string currency, MidpointRounding mode)
+ => Math.Round(amount, currencyNameTable.GetNumberFormatInfo(currency)?.CurrencyDecimalDigits ?? 2, mode);
public decimal GetAmountToCredit(InvoiceEntity invoice)
// If the subscriber settled more than expected, we credit the subscriber with the difference.
- => RoundAmount(invoice.Status is InvoiceStatus.Processing ? invoice.PaidAmount.Net : invoice.NetSettled, invoice.Currency);
+ => RoundAmount(invoice.Status is InvoiceStatus.Processing ? invoice.PaidAmount.Net : invoice.NetSettled, invoice.Currency, MidpointRounding.ToZero);
public async Task<decimal> CreditSubscriber(SubscriberData sub, string description, decimal credit)
=> (await TryCreditDebitSubscriber(sub, description, credit, 0m, true))!.Value;
### BTCPayServer/Plugins/Subscriptions/SubscriptionHostedService.cs
@@ -194,7 +194,7 @@ private async Task CreateInvoiceForCheckout(SubscriptionContext subCtx, PlanChec
var plan = checkout.Plan;
var existingCredit = checkout.Subscriber?.GetCredit() ?? 0m;
- var amount = checkout.CreditPurchase ?? (plan.Price - existingCredit);
+ var amount = checkout.CreditPurchase ?? (subCtx.RoundAmount(plan.Price, plan.Currency) - existingCredit);
if (checkout.OnPay == PlanCheckoutData.OnPayBehavior.HardMigration &&
checkout.Subscriber?.GetUnusedPeriodAmount(subCtx.Now) is decimal unusedAmount)
amount -= subCtx.RoundAmount(unusedAmount, plan.Currency);
@@ -699,6 +699,11 @@ public class UpdateCreditParameters
if (portal is null)
return null;
+ if (value is not null)
+ value = subCtx.RoundAmount(value.Value, portal.Subscriber.Plan.Currency);
+ if (value is <= 0.0m)
+ return null;
+
var checkout = new PlanCheckoutData(portal.Subscriber)
{
SuccessRedirectUrl = linkGenerator.SubscriberPortalLink(portalSessionId, portal.BaseUrl),
### BTCPayServer/Services/Notifications/NotificationScopes.cs
@@ -15,6 +15,7 @@ public StoreScope(string storeId, IEnumerable<StoreRoleId> roles = null)
}
public string StoreId { get; }
public IEnumerable<StoreRoleId> Roles { get; set; }
+ public string Policy { get; set; }
}
public class UserScope : INotificationScope
### BTCPayServer/Services/Notifications/NotificationSender.cs
@@ -3,7 +3,9 @@
using System.Linq;
using System.Threading.Tasks;
using BTCPayServer.Abstractions.Contracts;
+using BTCPayServer.Client;
using BTCPayServer.Data;
+using BTCPayServer.Services.Stores;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
@@ -14,7 +16,7 @@ public class UserNotificationsUpdatedEvent
{
public string UserId { get; set; }
}
- public class NotificationSender(ApplicationDbContextFactory contextFactory, IServiceScopeFactory scopeFactory, NotificationManager notificationManager)
+ public class NotificationSender(ApplicationDbContextFactory contextFactory, IServiceScopeFactory scopeFactory, NotificationManager notificationManager, StoreRepository storeRepository, PermissionService permissionService)
{
public async Task SendNotification(INotificationScope scope, BaseNotification notification)
@@ -68,6 +70,15 @@ private async Task<string[]> GetUsers(INotificationScope scope, string notificat
}
case StoreScope s:
var roles = s.Roles?.Select(role => role.Id);
+ if (s.Policy is not null)
+ {
+ var permission = Permission.Create(s.Policy, s.StoreId);
+ var allowedRoles = (await storeRepository.GetStoreRoles(s.StoreId))
+ .Where(role => role.ToPermissionSet(s.StoreId).HasPermission(permission, permissionService))
+ .Select(role => role.Id)
+ .ToArray();
+ roles = roles is null ? allowedRoles : roles.Intersect(allowedRoles).ToArray();
+ }
query = ctx.UserStore
.Include(store => store.ApplicationUser)
.Where(u => u.StoreDataId == s.StoreId && (roles == null || roles.Contains(u.StoreRoleId)))
### BTCPayServer/wwwroot/swagger/v1/swagger.template.subscriptions.json
@@ -1026,7 +1026,7 @@
},
"creditedByInvoice": {
"type": "string",
- "description": "Amount credited due to invoice settlement.",
+ "description": "Amount credited from invoice payments.",
"example": "12.00"
},
"onPayBehavior": {Why this scored 63/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.