Harden external input handling (#7665)
What changed, and why it matters
This commit adds input validation and safer error handling across BTCPay Server's Greenfield API and web controllers. It prevents negative or nonsensical values for amounts, fees, thresholds, and lightning-address limits; stops malformed JSON error responses from crashing the API client; and makes transaction-label parsing tolerate bad data. Most changes are defensive hardening rather than fixes for known active exploits, but they close paths where an authenticated user or external system could supply dangerous input.
Treat as a routine security hardening patch. Review that all new validation rules are enforced consistently on both server and client, and consider adding additional negative-test coverage for edge cases such as null/empty BIP21 amounts and boundary values for min/max lightning-address settings.
Security signals we found
Input validation added for negative monetary values (amount, fee, threshold, min/max)
API client hardened against malformed JSON error responses
Server-side validation added for lightning address min/max relationship
BIP21 URI negative amount rejected in UriClaimDestination
Unknown transaction patching path now returns synthetic object when forced
Label parsing made tolerant of invalid outpoints
Swagger schemas updated to reflect new minimum value constraints
Evidence from the diff
The patch hardens external input handling in multiple areas: (1) BTCPayServerClient now catches JsonException when deserializing error payloads and falls back to a plain HttpRequestException, avoiding null-reference and deserialization crashes. (2) Lightning payment requests reject negative Amount, MaxFeePercent and MaxFeeFlat values. (3) Pull-payment payouts reject negative/zero amounts and negative BIP21 amounts in URIs. (4) Automated on-chain payout processors reject negative Threshold values and bind the UI validation to the correct field. (5) Lightning address min/max limits are validated (positive, max >= min) in both API and UI controllers. (6) Patching an unknown on-chain wallet transaction can now succeed with a forced flag, returning a synthetic data object instead of requiring an existing transaction. (7) CPFP label tooltips skip invalid outpoints instead of throwing. Swagger schemas are updated to document the new minimums.
Changed components
BTCPayServer.Client (BTCPayServerClient error handling)Greenfield Lightning Node API controllerGreenfield Pull Payment controllerGreenfield Store Automated On-Chain Payout Processors controllerGreenfield Store Lightning Addresses controllerGreenfield Store On-Chain Wallets controllerUILNURLController (lightning address UI)UIOnChainAutomatedPayoutProcessorsControllerUriClaimDestination (BIP21 payout destination parsing)LabelService (CPFP label tooltip generation)Inspect captured patch +182 / −22
### BTCPayServer.Client/BTCPayServerClient.cs
@@ -51,22 +51,31 @@ protected async Task HandleResponse(HttpResponseMessage message)
{
if (!message.IsSuccessStatusCode && message.Content?.Headers?.ContentType?.MediaType?.StartsWith("application/json", StringComparison.OrdinalIgnoreCase) is true)
{
- if (message.StatusCode == System.Net.HttpStatusCode.UnprocessableEntity)
+ try
{
- var aa = await message.Content.ReadAsStringAsync();
- var err = JsonConvert.DeserializeObject<Models.GreenfieldValidationError[]>(aa);
- throw new GreenfieldValidationException(err);
+ if (message.StatusCode == System.Net.HttpStatusCode.UnprocessableEntity)
+ {
+ var aa = await message.Content.ReadAsStringAsync();
+ var err = JsonConvert.DeserializeObject<Models.GreenfieldValidationError[]>(aa);
+ if (err is not null && err.All(e => e is not null))
+ throw new GreenfieldValidationException(err);
+ }
+ else if (message.StatusCode == System.Net.HttpStatusCode.Forbidden)
+ {
+ var err = JsonConvert.DeserializeObject<Models.GreenfieldPermissionAPIError>(await message.Content.ReadAsStringAsync());
+ if (err is not null)
+ throw new GreenfieldAPIException((int)message.StatusCode, err);
+ }
+ else
+ {
+ var err = JsonConvert.DeserializeObject<Models.GreenfieldAPIError>(await message.Content.ReadAsStringAsync());
+ if (err?.Code is not null)
+ throw new GreenfieldAPIException((int)message.StatusCode, err);
+ }
}
- if (message.StatusCode == System.Net.HttpStatusCode.Forbidden)
+ catch (JsonException)
{
- var err = JsonConvert.DeserializeObject<Models.GreenfieldPermissionAPIError>(await message.Content.ReadAsStringAsync());
- throw new GreenfieldAPIException((int)message.StatusCode, err);
- }
- else
- {
- var err = JsonConvert.DeserializeObject<Models.GreenfieldAPIError>(await message.Content.ReadAsStringAsync());
- if (err.Code != null)
- throw new GreenfieldAPIException((int)message.StatusCode, err);
+ // Fall back to the HTTP status when an error response is not valid JSON.
}
}
message.EnsureSuccessStatusCode();
### BTCPayServer.Tests/FastTests.cs
@@ -3,6 +3,7 @@
using System.Globalization;
using System.IO;
using System.Linq;
+using System.Net;
using System.Net.Http;
using System.Runtime.CompilerServices;
using System.Security;
@@ -27,11 +28,13 @@
using BTCPayServer.Services.Apps;
using BTCPayServer.Services.Fees;
using BTCPayServer.Services.Invoices;
+using BTCPayServer.Services.Labels;
using BTCPayServer.Services.Rates;
using BTCPayServer.Services.Wallets;
using BTCPayServer.Services.Wallets.Import;
using BTCPayServer.Services.WalletFileParsing;
using BTCPayServer.Validation;
+using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Configuration.Memory;
using Microsoft.Extensions.DependencyInjection;
@@ -64,6 +67,43 @@ public void BTCPayServerClientEscapesPathIdentifiers()
Assert.Equal("https://example.com/root/api/v1/stores/..%2Fusers%2Fme/webhooks/delivery%2F..%2Fx?email=a%2Bb%40example.com", request.RequestUri!.AbsoluteUri);
}
+ [Theory]
+ [InlineData(HttpStatusCode.BadRequest, "{")]
+ [InlineData(HttpStatusCode.Forbidden, "{")]
+ [InlineData(HttpStatusCode.UnprocessableEntity, "{")]
+ [InlineData(HttpStatusCode.UnprocessableEntity, "[null]")]
+ public async Task BTCPayServerClientFallsBackToHttpExceptionForMalformedJsonErrors(HttpStatusCode statusCode, string content)
+ {
+ using var httpClient = new HttpClient(new TestHttpMessageHandler(_ => new HttpResponseMessage(statusCode)
+ {
+ Content = new StringContent(content, Encoding.UTF8, "application/json")
+ }));
+ var client = new BTCPayServerClient(new Uri("https://example.com/"), httpClient);
+
+ var exception = await Assert.ThrowsAsync<HttpRequestException>(() =>
+ client.SendHttpRequest($"api/v1/test", queryPayload: null, method: HttpMethod.Get));
+
+ Assert.Equal(statusCode, exception.StatusCode);
+ }
+
+ [Fact]
+ public void CreateTransactionTagModelsIgnoresInvalidCpfpOutpoints()
+ {
+ const string txId = "aecb52b892f5e12454b3ee1ad554ffe28c1cca35ffdfaa441c74a30cf7a279f0";
+ var transactionInfo = new WalletTransactionInfo(new WalletId("store", "BTC"));
+ transactionInfo.LabelColors.Add(WalletObjectData.Types.CPFP, "#000000");
+ transactionInfo.Attachments.Add(new Attachment(WalletObjectData.Types.CPFP, linkData: new JObject
+ {
+ ["outpoints"] = new JArray($"{txId}-1", "invalid")
+ }));
+
+ var model = Assert.Single(new LabelService(null!).CreateTransactionTagModels(
+ transactionInfo, new DefaultHttpContext().Request));
+
+ Assert.Contains(txId, model.Tooltip);
+ Assert.DoesNotContain("invalid", model.Tooltip);
+ }
+
private class RequestInspectingClient : BTCPayServerClient
{
public RequestInspectingClient(Uri btcpayHost) : base(btcpayHost)
### BTCPayServer.Tests/GreenfieldAPITests.cs
@@ -3166,6 +3166,21 @@ await AssertHttpError(403, async () =>
Assert.Equal(new Dictionary<string, LabelData>(), transaction.Labels);
// transaction patch tests
+ var unknownTransactionHash = RandomUtils.GetUInt256();
+ await AssertEx.AssertApiError("transaction-not-found", () =>
+ client.PatchOnChainWalletTransaction(walletId.StoreId, walletId.CryptoCode,
+ unknownTransactionHash.ToString(), new PatchOnChainTransactionRequest()));
+ var forcedTransaction = await client.PatchOnChainWalletTransaction(
+ walletId.StoreId, walletId.CryptoCode, unknownTransactionHash.ToString(),
+ new PatchOnChainTransactionRequest
+ {
+ Comment = "pending transaction",
+ Labels = ["pending"]
+ }, true);
+ Assert.Equal(unknownTransactionHash, forcedTransaction.TransactionHash);
+ Assert.Equal("pending transaction", forcedTransaction.Comment);
+ Assert.Contains("pending", forcedTransaction.Labels);
+
var patchedTransaction = await client.PatchOnChainWalletTransaction(
walletId.StoreId, walletId.CryptoCode, txdata.TransactionHash.ToString(),
new PatchOnChainTransactionRequest()
@@ -4053,6 +4068,13 @@ await adminClient.ApprovePayout(notApprovedPayoutWithoutPullPayment.Id,
Assert.Empty(await adminClient.GetStoreOnChainAutomatedPayoutProcessors(admin.StoreId, "BTC"));
Assert.Empty(await adminClient.GetPayoutProcessors(admin.StoreId));
+ await AssertValidationError([nameof(OnChainAutomatedPayoutSettings.Threshold)], () =>
+ adminClient.UpdateStoreOnChainAutomatedPayoutProcessors(admin.StoreId, "BTC",
+ new OnChainAutomatedPayoutSettings
+ {
+ IntervalSeconds = TimeSpan.FromSeconds(3600),
+ Threshold = -1m
+ }));
await adminClient.UpdateStoreOnChainAutomatedPayoutProcessors(admin.StoreId, "BTC",
new OnChainAutomatedPayoutSettings() { IntervalSeconds = TimeSpan.FromSeconds(3600) });
Assert.Equal(3600, Assert.Single(await adminClient.GetStoreOnChainAutomatedPayoutProcessors(admin.StoreId, "BTC")).IntervalSeconds.TotalSeconds);
### BTCPayServer.Tests/LightningTests.cs
@@ -169,6 +169,15 @@ public async Task CanUseLightningAPI()
Amount = LightMoney.Satoshis(-1)
}));
Assert.Contains(validationErr.ValidationErrors, error => error.Path == "Amount");
+ validationErr = await Assert.ThrowsAsync<GreenfieldValidationException>(() =>
+ client.PayLightningInvoice(user.StoreId, "BTC", new PayLightningInvoiceRequest
+ {
+ BOLT11 = merchantInvoice.BOLT11,
+ MaxFeePercent = -1,
+ MaxFeeFlat = Money.Satoshis(-1)
+ }));
+ Assert.Contains(validationErr.ValidationErrors, error => error.Path == "MaxFeePercent");
+ Assert.Contains(validationErr.ValidationErrors, error => error.Path == "MaxFeeFlat");
var payResponse = await client.PayLightningInvoice(user.StoreId, "BTC", new PayLightningInvoiceRequest
{
@@ -539,6 +548,16 @@ public async Task StoreLightningAddressesAPITests()
Assert.Empty(await adminClient.GetStoreLightningAddresses(store.Id));
Assert.Empty(await adminClient.GetStoreLightningAddresses(store2));
+ await AssertEx.AssertValidationError(["Min"], () =>
+ adminClient.AddOrUpdateStoreLightningAddress(store.Id, address1,
+ new LightningAddressData { Min = 0 }));
+ await AssertEx.AssertValidationError(["Max"], () =>
+ adminClient.AddOrUpdateStoreLightningAddress(store.Id, address1,
+ new LightningAddressData { Max = 0 }));
+ await AssertEx.AssertValidationError(["Max"], () =>
+ adminClient.AddOrUpdateStoreLightningAddress(store.Id, address1,
+ new LightningAddressData { Min = 2, Max = 1 }));
+ Assert.Empty(await adminClient.GetStoreLightningAddresses(store.Id));
await adminClient.AddOrUpdateStoreLightningAddress(store.Id, address1, new LightningAddressData());
await adminClient.AddOrUpdateStoreLightningAddress(store.Id, address1, new LightningAddressData()
### BTCPayServer.Tests/PullPaymentsTests.cs
@@ -1036,6 +1036,20 @@ void VerifyResult()
//permission test around auto approved pps and payouts
var nonApproved = await acc.CreateClient(Policies.CanCreateNonApprovedPullPayments);
var approved = await acc.CreateClient(Policies.CanCreatePullPayments);
+ var payoutAddress = new Key().GetAddress(ScriptPubKeyType.TaprootBIP86, Network.RegTest).ToString();
+ await AssertEx.AssertValidationError(["Amount"], () =>
+ nonApproved.CreatePayout(acc.StoreId, new CreatePayoutThroughStoreRequest
+ {
+ Amount = -1,
+ PayoutMethodId = "BTC",
+ Destination = payoutAddress
+ }));
+ await AssertEx.AssertValidationError(["Destination"], () =>
+ nonApproved.CreatePayout(acc.StoreId, new CreatePayoutThroughStoreRequest
+ {
+ PayoutMethodId = "BTC",
+ Destination = $"bitcoin:{payoutAddress}?amount=-1"
+ }));
await AssertEx.AssertPermissionError(Policies.CanCreatePullPayments, async () =>
{
await nonApproved.CreatePullPayment(acc.StoreId, new CreatePullPaymentRequest()
@@ -1054,7 +1068,7 @@ await AssertEx.AssertPermissionError(Policies.CanCreatePullPayments, async () =>
Amount = 100,
PayoutMethodId = "BTC",
Approved = true,
- Destination = new Key().GetAddress(ScriptPubKeyType.TaprootBIP86, Network.RegTest).ToString()
+ Destination = payoutAddress
});
});
@@ -1072,7 +1086,7 @@ await AssertEx.AssertPermissionError(Policies.CanCreatePullPayments, async () =>
Amount = 100,
PayoutMethodId = "BTC",
Approved = true,
- Destination = new Key().GetAddress(ScriptPubKeyType.TaprootBIP86, Network.RegTest).ToString()
+ Destination = payoutAddress
});
}
### BTCPayServer/Controllers/GreenField/GreenfieldLightningNodeApiController.cs
@@ -14,6 +14,7 @@
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
+using NBitcoin;
using Newtonsoft.Json.Linq;
namespace BTCPayServer.Controllers.Greenfield
@@ -243,6 +244,14 @@ public virtual async Task<IActionResult> PayInvoice(string cryptoCode, PayLightn
{
ModelState.AddModelError(nameof(lightningInvoice.Amount), "Amount must be greater than or equal to 0");
}
+ if (lightningInvoice.MaxFeePercent is < 0)
+ {
+ ModelState.AddModelError(nameof(lightningInvoice.MaxFeePercent), "Maximum fee percentage must be greater than or equal to 0");
+ }
+ if (lightningInvoice.MaxFeeFlat is not null && lightningInvoice.MaxFeeFlat < Money.Zero)
+ {
+ ModelState.AddModelError(nameof(lightningInvoice.MaxFeeFlat), "Maximum flat fee must be greater than or equal to 0");
+ }
if (!ModelState.IsValid)
{
### BTCPayServer/Controllers/GreenField/GreenfieldPullPaymentController.cs
@@ -534,10 +534,13 @@ public async Task<IActionResult> CreatePayoutThroughStore(string storeId, Create
else if (amt is ClaimRequest.ClaimedAmountResult.Success succ)
{
request.Amount = succ.Amount;
- if (request.Amount is { } v && (v < ppBlob?.MinimumClaim || v == 0.0m))
+ if (request.Amount is { } v &&
+ (v <= 0.0m || ppBlob?.MinimumClaim is { } minimum && v < minimum))
{
var minimumClaim = ppBlob?.MinimumClaim is decimal val ? val : 0.0m;
- ModelState.AddModelError(nameof(request.Amount), $"Amount too small (should be at least {minimumClaim})");
+ ModelState.AddModelError(nameof(request.Amount), minimumClaim > 0
+ ? $"Amount too small (should be at least {minimumClaim})"
+ : "Amount must be greater than 0");
return this.CreateValidationError(ModelState);
}
var result = await _pullPaymentService.Claim(new ClaimRequest()
### BTCPayServer/Controllers/GreenField/GreenfieldStoreAutomatedOnChainPayoutProcessorsController.cs
@@ -80,6 +80,8 @@ public async Task<IActionResult> UpdateStoreOnchainAutomatedPayoutProcessor(
string storeId, string paymentMethod, OnChainAutomatedPayoutSettings request)
{
AutomatedPayoutConstants.ValidateInterval(ModelState, request.IntervalSeconds, nameof(request.IntervalSeconds));
+ if (request.Threshold < 0)
+ ModelState.AddModelError(nameof(request.Threshold), "The threshold should be greater than or equal to 0");
if (request.FeeBlockTarget is int t && (t < 1 || t > 1000))
ModelState.AddModelError(nameof(request.FeeBlockTarget), "The feeBlockTarget should be between 1 and 1000");
if (!ModelState.IsValid)
### BTCPayServer/Controllers/GreenField/GreenfieldStoreLightningAddressesController.cs
@@ -80,10 +80,16 @@ public async Task<IActionResult> AddOrUpdateStoreLightningAddress(
string storeId, string username, LightningAddressData data)
{
if (data.Min <= 0)
- {
ModelState.AddModelError(nameof(data.Min), "Minimum must be greater than 0 if provided.");
+
+ if (data.Max <= 0)
+ ModelState.AddModelError(nameof(data.Max), "Maximum must be greater than 0 if provided.");
+
+ if (data.Min is { } min && data.Max is { } max && min > max)
+ ModelState.AddModelError(nameof(data.Max), "Maximum must be greater than or equal to minimum.");
+
+ if (!ModelState.IsValid)
return this.CreateValidationError(ModelState);
- }
if (await _lightningAddressService.Set(new Data.LightningAddressData
{
### BTCPayServer/Controllers/UILNURLController.cs
@@ -956,6 +956,12 @@ public async Task<IActionResult> EditLightningAddress(string storeId, [FromForm]
vm.AddModelError(addressVm => addressVm.Add.CurrencyCode, StringLocalizer["Currency is invalid"], this);
}
+ if (vm.Add.Min is { } min && vm.Add.Max is { } max && min > max)
+ {
+ vm.AddModelError(addressVm => addressVm.Add.Max,
+ StringLocalizer["Maximum must be greater than or equal to minimum"], this);
+ }
+
JObject metadata = null;
if (!string.IsNullOrEmpty(vm.Add.InvoiceMetadata))
{
### BTCPayServer/Data/Payouts/BitcoinLike/UriClaimDestination.cs
@@ -14,6 +14,8 @@ public UriClaimDestination(BitcoinUrlBuilder bitcoinUrl)
ArgumentNullException.ThrowIfNull(bitcoinUrl);
if (bitcoinUrl.Address is null)
throw new ArgumentException(nameof(bitcoinUrl));
+ if (bitcoinUrl.Amount is { } amount && amount < Money.Zero)
+ throw new ArgumentOutOfRangeException(nameof(bitcoinUrl), "The BIP21 amount cannot be negative");
_bitcoinUrl = bitcoinUrl;
Address = bitcoinUrl.Address ?? throw new FormatException("the bip21 doesn't contain an address");
}
### BTCPayServer/PayoutProcessors/OnChain/UIOnChainAutomatedPayoutProcessorsController.cs
@@ -148,6 +148,7 @@ public OnChainTransferViewModel(OnChainAutomatedPayoutBlob blob)
[Range(1, 1000)]
public int FeeTargetBlock { get; set; }
+ [Range(0, double.MaxValue)]
public decimal Threshold { get; set; }
[Range(AutomatedPayoutConstants.MinIntervalMinutes, AutomatedPayoutConstants.MaxIntervalMinutes)]
### BTCPayServer/Plugins/Wallets/Controllers/GreenfieldStoreOnChainWalletsController.cs
@@ -261,7 +261,8 @@ public async Task<IActionResult> PatchOnChainWalletTransaction(
return actionResult;
var wallet = btcPayWalletProvider.GetWallet(network);
- var tx = await wallet.FetchTransaction(derivationScheme.AccountDerivation, uint256.Parse(transactionId));
+ var transactionHash = uint256.Parse(transactionId);
+ var tx = await wallet.FetchTransaction(derivationScheme.AccountDerivation, transactionHash);
if (!force && tx is null)
{
return this.CreateAPIError(404, "transaction-not-found", "The transaction was not found.");
@@ -285,6 +286,18 @@ public async Task<IActionResult> PatchOnChainWalletTransaction(
.Values
.FirstOrDefault();
+ if (tx is null)
+ {
+ return Ok(new OnChainWalletTransactionData
+ {
+ TransactionHash = transactionHash,
+ Comment = walletTransactionsInfo?.Comment ?? string.Empty,
+#pragma warning disable CS0612 // Type or member is obsolete
+ Labels = walletTransactionsInfo?.LegacyLabels ?? new Dictionary<string, LabelData>()
+#pragma warning restore CS0612 // Type or member is obsolete
+ });
+ }
+
return Ok(ToModel(walletTransactionsInfo, tx, wallet));
}
### BTCPayServer/Services/Labels/LabelService.cs
@@ -102,7 +102,12 @@ string PayoutTooltip(IGrouping<string, string>? payoutsByPullPaymentId = null)
}
else if (tag.Type == WalletObjectData.Types.CPFP)
{
- var txs = ((tag.LinkData?["outpoints"] as JArray)?.Select(e => OutPoint.Parse(e.ToString()).Hash) ?? []).ToHashSet();
+ var txs = new HashSet<uint256>();
+ foreach (var value in (tag.LinkData?["outpoints"] as JArray) ?? [])
+ {
+ if (OutPoint.TryParse(value.ToString(), out var outpoint) && outpoint is not null)
+ txs.Add(outpoint.Hash);
+ }
var txsStr = string.Join(", ", txs);
model.Tooltip = $"This is transaction is paying for fee for the following transactions: {txsStr}";
model.Link = "#";
### BTCPayServer/Views/UIOnChainAutomatedPayoutProcessors/Configure.cshtml
@@ -48,7 +48,7 @@
<div class="input-group">
<input asp-for="Threshold" class="form-control" min="0" inputmode="numeric" style="max-width:12ch;">
<span class="input-group-text">@cryptoCode</span>
- <span asp-validation-for="FeeTargetBlock" class="text-danger"></span>
+ <span asp-validation-for="Threshold" class="text-danger"></span>
</div>
<div class="form-text" text-translate="true">Only process payouts when this payout sum is reached.</div>
</div>
### BTCPayServer/wwwroot/swagger/v1/swagger.template.lightning.common.json
@@ -355,18 +355,21 @@
},
"amount": {
"type": "string",
+ "minimum": 0,
"description": "Optional explicit payment amount in millisatoshi (if specified, it overrides the BOLT11 amount)",
"nullable": true
},
"maxFeePercent": {
"type": "string",
"format": "float",
+ "minimum": 0,
"nullable": true,
"description": "The fee limit expressed as a percentage of the payment amount",
"example": "6.15"
},
"maxFeeFlat": {
"type": "string",
+ "minimum": 0,
"nullable": true,
"description": "The fee limit expressed as a fixed amount in satoshi",
"example": "21"
### BTCPayServer/wwwroot/swagger/v1/swagger.template.pull-payments.json
@@ -928,6 +928,8 @@
"amount": {
"type": "string",
"format": "decimal",
+ "minimum": 0,
+ "exclusiveMinimum": true,
"example": "10399.18",
"description": "The amount of the payout in the currency of the pull payment (eg. USD)."
},
### BTCPayServer/wwwroot/swagger/v1/swagger.template.stores-lightning-addresses.json
@@ -213,11 +213,15 @@
},
"min": {
"type": "string",
+ "format": "decimal",
+ "minimum": 1,
"nullable": true,
"description": "The minimum amount in sats this ln address allows"
},
"max": {
"type": "string",
+ "format": "decimal",
+ "minimum": 1,
"nullable": true,
"description": "The maximum amount in sats this ln address allows"
},Why this scored 51/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.