Preserve unresolved template expressions
What changed, and why it matters
This commit changes how BTCPay Server fills in template placeholders (like {OrderId} or {InvoiceId}) in URLs, payment descriptions, and point-of-sale button text. Previously, if a placeholder could not be resolved or had a syntax error, it was replaced with a visible error string such as [NotFound(...)] and could also be URL-encoded, making it unreadable. The new behavior preserves the original placeholder expression unchanged when it cannot be resolved, and adds a dedicated URL template helper that properly encodes resolved values while leaving unresolved placeholders intact. The change is described as a fix/polish rather than a security patch, but it reduces the risk of broken or misleading URLs and user-facing strings.
Treat as a hardening/usability fix rather than an urgent security patch. Review whether user-supplied template strings are validated or escaped to prevent injection of unexpected placeholders or malformed expressions. Continue monitoring for related security advisories from the BTCPay Server project.
Security signals we found
Template engine fallback behavior changed from error-string substitution to literal placeholder preservation
URL template helper introduced to encode resolved values while not encoding unresolved placeholders
Multiple user-controlled template inputs rendered into URLs and payment metadata
No explicit security advisory, CVE, or exploit description in commit or supplied references
No input sanitization or allowlist added for template expressions
Evidence from the diff
The TextTemplate class is extended with CreateUrlTemplate, EncodeFallbackReplacements, and configurable fallback replacement functions. Call sites for URL generation (InvoiceEntity.FillPlaceholdersUri, UIInvoiceController.UI Checkout support URL) now use CreateUrlTemplate, which URL-encodes resolved values but does not encode unresolved fallback placeholders. Other call sites (LNURL/lightning description, POS button text) preserve unresolved template expressions literally instead of emitting [NotFound(…)]/[ParsingError(…)]. Tests are updated to assert that unknown or invalid placeholders remain as {path} in output. The commit does not add input validation, output encoding beyond URL escaping, or authentication/authorization changes.
Changed components
BTCPayServer.Common/TextTemplate.csBTCPayServer/Controllers/UIInvoiceController.UI.csBTCPayServer/Controllers/UILNURLController.csBTCPayServer/Payments/Lightning/LightningLikePaymentHandler.csBTCPayServer/Plugins/PointOfSale/Controllers/UIPointOfSaleController.csBTCPayServer/Services/Invoices/InvoiceEntity.csInspect captured patch +59 / −19
### BTCPayServer.Common/TextTemplate.cs
@@ -10,10 +10,21 @@ namespace BTCPayServer;
public class TextTemplate(string template)
{
static readonly Regex _interpolationRegex = new Regex(@"\{([^}]+)\}", RegexOptions.Compiled | RegexOptions.CultureInvariant);
+
+ public static TextTemplate CreateUrlTemplate(string template) =>
+ new TextTemplate(template)
+ {
+ NotFoundReplacement = path => $"{{{path}}}",
+ ParsingErrorReplacement = path => $"{{{path}}}",
+ EncodeFallbackReplacements = false,
+ Encode = value => Uri.EscapeDataString(value.Value)
+ };
+
public Func<string, string> NotFoundReplacement { get; set; } = path => $"[NotFound({path})]";
public Func<string, string> ParsingErrorReplacement { get; set; } = path => $"[ParsingError({path})]";
public Func<(string Path, string Value), string> Encode { get; set; } = v => v.Value;
+ public bool EncodeFallbackReplacements { get; set; } = true;
public string Render(JObject model)
{
@@ -28,15 +39,23 @@ public string Render(JObject model)
try
{
var token = model.SelectToken(path);
- return Encode((initial, token?.ToString() ?? NotFoundReplacement(initial)));
+ return token is null
+ ? RenderFallback(initial, NotFoundReplacement)
+ : Encode((initial, token.ToString()));
}
catch
{
- return Encode((initial, ParsingErrorReplacement(initial)));
+ return RenderFallback(initial, ParsingErrorReplacement);
}
});
}
+ private string RenderFallback(string path, Func<string, string> replacement)
+ {
+ var value = replacement(path);
+ return EncodeFallbackReplacements ? Encode((path, value)) : value;
+ }
+
public List<string> GetPaths(JObject model)
{
var paths = new List<List<string>>();
### BTCPayServer.Tests/FastTests.cs
@@ -735,10 +735,14 @@ public void CanRenderInvoiceUriTemplates()
Id = "invoice/id",
Metadata = new InvoiceMetadata { OrderId = "order id" },
Status = InvoiceStatus.Settled,
- RedirectURLTemplate = "https://example.com/{orderid}/{InvoiceId}?status={STATUS}"
+ RedirectURLTemplate = "https://example.com/{unknown}/{orderid}/{InvoiceId}?status={STATUS}",
+ NotificationURLTemplate = "https://example.com/{invalid[}?orderId={OrderId}"
};
- Assert.Equal("https://example.com/order+id/invoice%2fid?status=Settled", entity.RedirectURL.OriginalString);
+ Assert.Equal("https://example.com/{unknown}/order%20id/invoice%2Fid?status=Settled", entity.RedirectURL.OriginalString);
+
+ entity.Metadata.OrderId = null;
+ Assert.Equal("https://example.com/{invalid[}?orderId=", entity.NotificationURL.OriginalString);
}
[Fact]
### BTCPayServer.Tests/UnitTest1.cs
@@ -1240,13 +1240,21 @@ public void TestMailTemplate()
result = template.Render(model);
Assert.Equal("Hello mister 2 3 !", result);
- template = new TextTemplate("{0} or {Price}");
+ template = new TextTemplate("{0} or {Price} in {Currency} {Currency[}")
+ {
+ NotFoundReplacement = path => $"{{{path}}}",
+ ParsingErrorReplacement = path => $"{{{path}}}"
+ };
result = template.Render(new JObject
{
["0"] = "$10",
["Price"] = "$10"
});
- Assert.Equal("$10 or $10", result);
+ Assert.Equal("$10 or $10 in {Currency} {Currency[}", result);
+
+ template = TextTemplate.CreateUrlTemplate("{Known} {Unknown} {Invalid[}");
+ result = template.Render(new JObject { ["Known"] = "hello world" });
+ Assert.Equal("hello%20world {Unknown} {Invalid[}", result);
}
[Fact]
### BTCPayServer/Controllers/UIInvoiceController.UI.cs
@@ -883,13 +883,10 @@ public async Task<IActionResult> Checkout(string? invoiceId, string? id = null,
var orderId = invoice.Metadata.OrderId;
var supportUrl = !string.IsNullOrEmpty(storeBlob.StoreSupportUrl)
- ? new TextTemplate(storeBlob.StoreSupportUrl)
- {
- Encode = value => Uri.EscapeDataString(value.Value)
- }
+ ? TextTemplate.CreateUrlTemplate(storeBlob.StoreSupportUrl)
.Render(new JObject
{
- ["OrderId"] = orderId,
+ ["OrderId"] = orderId ?? string.Empty,
["InvoiceId"] = invoice.Id
})
: null;
### BTCPayServer/Controllers/UILNURLController.cs
@@ -696,7 +696,12 @@ private async Task<LNURLPayRequest> CreateLNUrlRequestFromInvoice(
private void SetLNUrlDescriptionMetadata(Dictionary<string, string> lnUrlMetadata, Data.StoreData store, StoreBlob blob, InvoiceMetadata invoiceMetadata)
{
- var invoiceDescription = new TextTemplate(blob.LightningDescriptionTemplate).Render(new JObject
+ var template = new TextTemplate(blob.LightningDescriptionTemplate)
+ {
+ NotFoundReplacement = path => $"{{{path}}}",
+ ParsingErrorReplacement = path => $"{{{path}}}"
+ };
+ var invoiceDescription = template.Render(new JObject
{
["StoreName"] = store.StoreName,
["ItemDescription"] = invoiceMetadata?.ItemDesc,
### BTCPayServer/Payments/Lightning/LightningLikePaymentHandler.cs
@@ -93,7 +93,12 @@ public async Task ConfigurePrompt(PaymentMethodContext context)
LightningInvoice? lightningInvoice;
- var description = new TextTemplate(storeBlob.LightningDescriptionTemplate).Render(new JObject
+ var template = new TextTemplate(storeBlob.LightningDescriptionTemplate)
+ {
+ NotFoundReplacement = path => $"{{{path}}}",
+ ParsingErrorReplacement = path => $"{{{path}}}"
+ };
+ var description = template.Render(new JObject
{
["StoreName"] = store.StoreName,
["ItemDescription"] = invoice.Metadata.ItemDesc,
### BTCPayServer/Plugins/PointOfSale/Controllers/UIPointOfSaleController.cs
@@ -170,7 +170,12 @@ private ViewPointOfSaleViewModel.AppItemViewModel FillItemViewModel(ViewPointOfS
vm.ButtonText = string.IsNullOrEmpty(vm.BuyButtonText)
? vm.PriceType == AppItemPriceType.Topup ? settings.CustomButtonText : settings.ButtonText
: vm.BuyButtonText;
- vm.ButtonText = new TextTemplate(vm.ButtonText).Render(new JObject
+ var buttonTextTemplate = new TextTemplate(vm.ButtonText)
+ {
+ NotFoundReplacement = path => $"{{{path}}}",
+ ParsingErrorReplacement = path => $"{{{path}}}"
+ };
+ vm.ButtonText = buttonTextTemplate.Render(new JObject
{
["0"] = vm.PriceFormatted,
["Price"] = vm.PriceFormatted
### BTCPayServer/Services/Invoices/InvoiceEntity.cs
@@ -495,13 +495,10 @@ public List<PaymentEntity> GetPayments(string currency, bool accountedOnly)
private Uri FillPlaceholdersUri(string v)
{
- var template = new TextTemplate(v ?? string.Empty)
- {
- Encode = value => System.Web.HttpUtility.UrlEncode(value.Value) ?? string.Empty
- };
+ var template = TextTemplate.CreateUrlTemplate(v ?? string.Empty);
var uriStr = template.Render(new JObject
{
- ["OrderId"] = Metadata.OrderId,
+ ["OrderId"] = Metadata.OrderId ?? string.Empty,
["InvoiceId"] = Id,
// NOTE: Not recommended to depend on the status on client side, rather fetch invoice status via API instead
["Status"] = Status.ToString()Why this scored 35/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.