Use TextTemplate for placeholder rendering
What changed, and why it matters
This commit replaces several hand-written string-replacement routines with a shared TextTemplate engine for rendering placeholders in URLs, emails, Lightning payment descriptions, and point-of-sale button text. The change is a defensive refactoring: it centralizes how user-supplied values are substituted into templates, making it easier to ensure values are encoded consistently. The new test shows that URL placeholders are now URL-encoded, which reduces the risk of malicious values breaking or manipulating generated links. There is no direct evidence in the commit of an exploitable vulnerability being fixed, but the change removes a common source of injection and encoding mistakes.
Review the TextTemplate implementation (not shown in this commit) to confirm it encodes by default, does not double-encode, and cannot evaluate arbitrary code or access object graph properties beyond intended placeholders. Ensure all remaining manual string.Replace placeholder logic is migrated and that tests cover edge cases such as null values, special characters, and HTML contexts.
Security signals we found
Refactoring of string.Replace placeholder substitution to a centralized template engine
URL encoding applied to substituted values in redirect/support URLs
Reduction of manual StringComparison.OrdinalIgnoreCase replacement chains
New unit test verifying URL-encoded placeholder rendering
Potential mitigation of URL injection / open-redirect-adjacent issues via encoding
Evidence from the diff
The patch refactors placeholder substitution across BTCPay Server to use a TextTemplate helper. Affected flows include invoice redirect URLs (InvoiceEntity.FillPlaceholdersUri), store support URLs (UIInvoiceController.UI), LNURL/Lightning invoice descriptions (UILNURLController, LightningLikePaymentHandler), email call-to-action buttons (EmailsPlugin), and point-of-sale button text (UIPointOfSaleController). The new TextTemplate class appears to support an Encode callback, which FillPlaceholdersUri and UIInvoiceController use to apply HttpUtility.UrlEncode / Uri.EscapeDataString to substituted values. A new unit test asserts that a redirect URL template containing order id, invoice id, and status produces a correctly URL-encoded absolute URI. The commit does not include the TextTemplate implementation itself, so the full security properties of the engine cannot be verified from this diff alone.
Changed components
BTCPayServer.Services.Invoices.InvoiceEntityBTCPayServer.Controllers.UIInvoiceController.UIBTCPayServer.Controllers.UILNURLControllerBTCPayServer.Payments.Lightning.LightningLikePaymentHandlerBTCPayServer.Plugins.Emails.EmailsPluginBTCPayServer.Plugins.PointOfSale.Controllers.UIPointOfSaleControllerInspect captured patch +65 / −18
### BTCPayServer.Tests/FastTests.cs
@@ -727,6 +727,20 @@ public void CanParseBadSpaceVersionCondition(string parsed, string formatted)
}.ToString());
}
+ [Fact]
+ public void CanRenderInvoiceUriTemplates()
+ {
+ var entity = new InvoiceEntity
+ {
+ Id = "invoice/id",
+ Metadata = new InvoiceMetadata { OrderId = "order id" },
+ Status = InvoiceStatus.Settled,
+ RedirectURLTemplate = "https://example.com/{orderid}/{InvoiceId}?status={STATUS}"
+ };
+
+ Assert.Equal("https://example.com/order+id/invoice%2fid?status=Settled", entity.RedirectURL.OriginalString);
+ }
+
[Fact]
public void CanCalculateDust()
{
### BTCPayServer.Tests/UnitTest1.cs
@@ -1239,6 +1239,14 @@ public void TestMailTemplate()
template = new TextTemplate("Hello mister {Name.NameInner.Ogg} {Name.NameInner.Ogg2} !");
result = template.Render(model);
Assert.Equal("Hello mister 2 3 !", result);
+
+ template = new TextTemplate("{0} or {Price}");
+ result = template.Render(new JObject
+ {
+ ["0"] = "$10",
+ ["Price"] = "$10"
+ });
+ Assert.Equal("$10 or $10", result);
}
[Fact]
### BTCPayServer/Controllers/UIInvoiceController.UI.cs
@@ -883,9 +883,15 @@ public async Task<IActionResult> Checkout(string? invoiceId, string? id = null,
var orderId = invoice.Metadata.OrderId;
var supportUrl = !string.IsNullOrEmpty(storeBlob.StoreSupportUrl)
- ? storeBlob.StoreSupportUrl
- .Replace("{OrderId}", string.IsNullOrEmpty(orderId) ? string.Empty : Uri.EscapeDataString(orderId))
- .Replace("{InvoiceId}", Uri.EscapeDataString(invoice.Id))
+ ? new TextTemplate(storeBlob.StoreSupportUrl)
+ {
+ Encode = value => Uri.EscapeDataString(value.Value)
+ }
+ .Render(new JObject
+ {
+ ["OrderId"] = orderId,
+ ["InvoiceId"] = invoice.Id
+ })
: null;
string GetPaymentMethodImage(PaymentMethodId paymentMethodId2)
### BTCPayServer/Controllers/UILNURLController.cs
@@ -696,10 +696,12 @@ private async Task<LNURLPayRequest> CreateLNUrlRequestFromInvoice(
private void SetLNUrlDescriptionMetadata(Dictionary<string, string> lnUrlMetadata, Data.StoreData store, StoreBlob blob, InvoiceMetadata invoiceMetadata)
{
- var invoiceDescription = blob.LightningDescriptionTemplate
- .Replace("{StoreName}", store.StoreName ?? "", StringComparison.OrdinalIgnoreCase)
- .Replace("{ItemDescription}", invoiceMetadata?.ItemDesc ?? "", StringComparison.OrdinalIgnoreCase)
- .Replace("{OrderId}", invoiceMetadata?.OrderId ?? "", StringComparison.OrdinalIgnoreCase);
+ var invoiceDescription = new TextTemplate(blob.LightningDescriptionTemplate).Render(new JObject
+ {
+ ["StoreName"] = store.StoreName,
+ ["ItemDescription"] = invoiceMetadata?.ItemDesc,
+ ["OrderId"] = invoiceMetadata?.OrderId
+ });
lnUrlMetadata.Add("text/plain", invoiceDescription);
}
### BTCPayServer/Payments/Lightning/LightningLikePaymentHandler.cs
@@ -93,10 +93,12 @@ public async Task ConfigurePrompt(PaymentMethodContext context)
LightningInvoice? lightningInvoice;
- string description = storeBlob.LightningDescriptionTemplate;
- description = description.Replace("{StoreName}", store.StoreName ?? "", StringComparison.OrdinalIgnoreCase)
- .Replace("{ItemDescription}", invoice.Metadata.ItemDesc ?? "", StringComparison.OrdinalIgnoreCase)
- .Replace("{OrderId}", invoice.Metadata.OrderId ?? "", StringComparison.OrdinalIgnoreCase);
+ var description = new TextTemplate(storeBlob.LightningDescriptionTemplate).Render(new JObject
+ {
+ ["StoreName"] = store.StoreName,
+ ["ItemDescription"] = invoice.Metadata.ItemDesc,
+ ["OrderId"] = invoice.Metadata.OrderId
+ });
using (var cts = new CancellationTokenSource(LightningTimeout))
{
try
### BTCPayServer/Plugins/Emails/EmailsPlugin.cs
@@ -9,6 +9,7 @@
using BTCPayServer.Services;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
+using Newtonsoft.Json.Linq;
namespace BTCPayServer.Plugins.Emails;
@@ -108,8 +109,11 @@ private static void ConfigureEmailSearch(IServiceCollection services)
public static string CallToAction(string actionName, string actionLink)
{
- var button = $"{BUTTON_HTML}".Replace("{button_description}", actionName, System.StringComparison.InvariantCulture);
- return button.Replace("{button_link}", actionLink, System.StringComparison.InvariantCulture);
+ return new TextTemplate(BUTTON_HTML).Render(new JObject
+ {
+ ["button_description"] = actionName,
+ ["button_link"] = actionLink
+ });
}
public static string CreateEmailBody(string body) => $"<html><body style='{BODY_STYLE}'>{HEADER_HTML}{body}</body></html>";
### BTCPayServer/Plugins/PointOfSale/Controllers/UIPointOfSaleController.cs
@@ -170,7 +170,11 @@ private ViewPointOfSaleViewModel.AppItemViewModel FillItemViewModel(ViewPointOfS
vm.ButtonText = string.IsNullOrEmpty(vm.BuyButtonText)
? vm.PriceType == AppItemPriceType.Topup ? settings.CustomButtonText : settings.ButtonText
: vm.BuyButtonText;
- vm.ButtonText = vm.ButtonText.Replace("{0}", vm.PriceFormatted).Replace("{Price}", vm.PriceFormatted);
+ vm.ButtonText = new TextTemplate(vm.ButtonText).Render(new JObject
+ {
+ ["0"] = vm.PriceFormatted,
+ ["Price"] = vm.PriceFormatted
+ });
vm.InStock = vm.Inventory is null or > 0;
return vm;
}
### BTCPayServer/Services/Invoices/InvoiceEntity.cs
@@ -495,10 +495,17 @@ public List<PaymentEntity> GetPayments(string currency, bool accountedOnly)
private Uri FillPlaceholdersUri(string v)
{
- var uriStr = (v ?? string.Empty).Replace("{OrderId}", System.Web.HttpUtility.UrlEncode(Metadata.OrderId) ?? "", StringComparison.OrdinalIgnoreCase)
- .Replace("{InvoiceId}", System.Web.HttpUtility.UrlEncode(Id) ?? "", StringComparison.OrdinalIgnoreCase)
- // NOTE: Not recommended to depend on the status on client side, rather fetch invoice status via API instead
- .Replace("{Status}", System.Web.HttpUtility.UrlEncode(Status.ToString()) ?? "", StringComparison.OrdinalIgnoreCase);
+ var template = new TextTemplate(v ?? string.Empty)
+ {
+ Encode = value => System.Web.HttpUtility.UrlEncode(value.Value) ?? string.Empty
+ };
+ var uriStr = template.Render(new JObject
+ {
+ ["OrderId"] = Metadata.OrderId,
+ ["InvoiceId"] = Id,
+ // NOTE: Not recommended to depend on the status on client side, rather fetch invoice status via API instead
+ ["Status"] = Status.ToString()
+ });
if (Uri.TryCreate(uriStr, UriKind.Absolute, out var uri) && (uri.Scheme == "http" || uri.Scheme == "https"))
return uri;
return null;Why this scored 45/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.