What changed, and why it matters
This commit adds a length cap and safer string building to a URL template renderer in BTCPay Server. Before the change, an attacker or user who controlled template variables could cause the server to build extremely long strings, potentially wasting memory or CPU. The patch limits URL output to 8,192 characters and returns an empty string if the bound is exceeded. It appears to be a hardening fix rather than a response to a disclosed vulnerability.
Treat as a defensive hardening improvement. Review callers of TextTemplate.CreateUrlTemplate to confirm they handle empty-string returns safely, and consider whether other TextTemplate use cases (non-URL) should also adopt output bounds.
Security signals we found
Unbounded string growth in template rendering is bounded
New MaxOutputLength limit applied to URL templates
Defensive length checks added before every StringBuilder append
Unit test added to verify output bounding behavior
Evidence from the diff
TextTemplate.Render previously used Regex.Replace over the entire template, appending unbounded replacement values. The patch introduces MaxOutputLength (set to 8192 for URL templates), builds output with StringBuilder, and checks length before each append. If any append would exceed the bound, Render returns string.Empty. A unit test verifies the cap works for single large values and for templates with many placeholders. The change is defensive and reduces the risk of unbounded memory consumption or downstream issues from oversized URLs.
Changed components
BTCPayServer.Common/TextTemplate.csBTCPayServer.Tests/UnitTest1.csInspect captured patch +62 / −18
### BTCPayServer.Common/TextTemplate.cs
@@ -9,11 +9,13 @@ namespace BTCPayServer;
public class TextTemplate(string template)
{
+ public const int MaxUrlLength = 8192;
static readonly Regex _interpolationRegex = new Regex(@"\{([^}]+)\}", RegexOptions.Compiled | RegexOptions.CultureInvariant);
public static TextTemplate CreateUrlTemplate(string template) =>
new TextTemplate(template)
{
+ MaxOutputLength = MaxUrlLength,
NotFoundReplacement = path => $"{{{path}}}",
ParsingErrorReplacement = path => $"{{{path}}}",
EncodeFallbackReplacements = false,
@@ -25,31 +27,59 @@ public static TextTemplate CreateUrlTemplate(string template) =>
public Func<(string Path, string Value), string> Encode { get; set; } = v => v.Value;
public bool EncodeFallbackReplacements { get; set; } = true;
+ public int? MaxOutputLength { get; init; }
public string Render(JObject model)
{
model = (JObject)ToLowerCase(model);
- return _interpolationRegex.Replace(template, match =>
+ var result = new StringBuilder(MaxOutputLength is int maxLength
+ ? Math.Min(template.Length, maxLength)
+ : template.Length);
+ var offset = 0;
+ foreach (Match match in _interpolationRegex.Matches(template))
{
- var path = match.Groups[1].Value;
- var initial = path;
- if (!path.StartsWith("$."))
- path = $"$.{path}";
- path = path.ToLowerInvariant();
- try
- {
- var token = model.SelectToken(path);
- return token is null
- ? RenderFallback(initial, NotFoundReplacement)
- : Encode((initial, token.ToString()));
- }
- catch
- {
- return RenderFallback(initial, ParsingErrorReplacement);
- }
- });
+ var literalLength = match.Index - offset;
+ if (ExceedsMaxOutputLength(result.Length, literalLength))
+ return string.Empty;
+ result.Append(template, offset, literalLength);
+
+ var replacement = RenderMatch(model, match);
+ if (ExceedsMaxOutputLength(result.Length, replacement.Length))
+ return string.Empty;
+ result.Append(replacement);
+ offset = match.Index + match.Length;
+ }
+
+ var remainingLength = template.Length - offset;
+ if (ExceedsMaxOutputLength(result.Length, remainingLength))
+ return string.Empty;
+ result.Append(template, offset, remainingLength);
+ return result.ToString();
}
+ private string RenderMatch(JObject model, Match match)
+ {
+ var path = match.Groups[1].Value;
+ var initial = path;
+ if (!path.StartsWith("$."))
+ path = $"$.{path}";
+ path = path.ToLowerInvariant();
+ try
+ {
+ var token = model.SelectToken(path);
+ return token is null
+ ? RenderFallback(initial, NotFoundReplacement)
+ : Encode((initial, token.ToString()));
+ }
+ catch
+ {
+ return RenderFallback(initial, ParsingErrorReplacement);
+ }
+ }
+
+ private bool ExceedsMaxOutputLength(int currentLength, int appendedLength) =>
+ MaxOutputLength is int maxLength && (long)currentLength + appendedLength > maxLength;
+
private string RenderFallback(string path, Func<string, string> replacement)
{
var value = replacement(path);
### BTCPayServer.Tests/UnitTest1.cs
@@ -1257,6 +1257,20 @@ public void TestMailTemplate()
Assert.Equal("hello%20world {Unknown} {Invalid[}", result);
}
+ [Fact]
+ [Trait("Fast", "Fast")]
+ public void UrlTemplateOutputIsBounded()
+ {
+ var template = TextTemplate.CreateUrlTemplate("{Value}");
+ Assert.Equal(TextTemplate.MaxUrlLength, template.MaxOutputLength);
+ Assert.Equal(new string('a', TextTemplate.MaxUrlLength),
+ template.Render(new JObject { ["Value"] = new string('a', TextTemplate.MaxUrlLength) }));
+ Assert.Empty(template.Render(new JObject { ["Value"] = new string('a', TextTemplate.MaxUrlLength + 1) }));
+
+ template = TextTemplate.CreateUrlTemplate(string.Concat(Enumerable.Repeat("{Value}", 100_000)));
+ Assert.Empty(template.Render(new JObject { ["Value"] = new string('%', 500) }));
+ }
+
[Fact]
[Trait("Integration", "Integration")]
public async Task CanUseDefaultCurrency()Why this scored 40/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.