PureXML/Tests/XSLTRecursionLimitTests.swift
Mihaela Mihaljevic 7b7adef016
fix(xslt): bound template recursion so it fails gracefully, not with a crash (#357)
* fix(xslt): bound template recursion so it fails gracefully, not with a crash

A recursive named template whose depth is driven by source data (e.g.
`<xsl:with-param name="n" select="count(//x)"/>`) could recurse without bound
and overflow the native stack (SIGBUS) on attacker-controllable input. Every
XSLT processor guards this (libxslt's xsltMaxDepth); PureXML did not.

Measurement first: source *nesting* depth is not the exposure. `transform`
parses the source at the default maxDepth (256) and there is no XSLT API that
accepts a pre-built tree, so the engine never sees a source deeper than ~255;
an identity transform of a 254-deep source completes normally on a normal
stack. The reachable crash is data-driven template recursion, which overflows
an 8 MB stack between ~400 and 600 levels.

Template-instantiation nesting (instantiateTemplate and builtInRule) is now
counted and capped at maxTemplateDepth; past it the guard latches, the
instantiation loops unwind, and `transform` throws
XSLTError.recursionLimitExceeded instead of crashing. The default (300, exposed
as PureXML.XSLT.defaultMaxTemplateDepth, overridable via a new maxTemplateDepth
parameter on transform) clears the parser's max source depth so a deep-source
identity transform still runs, while staying within an 8 MB main-thread stack
with margin. A stylesheet with deeper legitimate recursion raises the limit on
a correspondingly larger stack.

copyOf moved to XSLTSorting.swift to keep XSLTTransformer.swift within the file
length limit; it is unchanged (a whole-subtree copy that does not recurse on
depth). Guarded by XSLTRecursionLimitTests (run on a large-stack thread, since
the limit is above what swift-testing's Task stack holds). Full suite 1802 pass.
Part of #356; making the engine fully iterative (deep recursion succeeds, and
is safe on a small Task stack) remains tracked there.

* test(xslt): exclude the large-stack recursion tests on WASI

WASI is single-threaded and has no Foundation Thread/DispatchSemaphore, which
the recursion-limit tests need to exercise the guard on a stack large enough for
the limit (300) to fire before the stack overflows. Guard the file with
#if !os(WASI); the recursion guard itself is platform-independent pure Swift,
covered by the macOS and Linux runs.
2026-06-27 18:30:19 +02:00

97 lines
4.9 KiB
Swift

// The recursion guard must be exercised on a large stack (the limit is above
// what a small stack holds), which needs Foundation's Thread. WASI is
// single-threaded and has no Thread/Dispatch, so these tests are excluded
// there; the guard itself is platform-independent pure Swift, covered by the
// macOS and Linux runs.
#if !os(WASI)
import Foundation
import Testing
@testable import PureXML
/// XSLT template recursion is bounded so an unbounded recursive template (whose
/// depth can be driven by source data) fails gracefully instead of overflowing
/// the stack (#356). Source *nesting* depth is already bounded by the parser's
/// `maxDepth`, so it is not the exposure; a recursive named template is.
///
/// These run on a dedicated large-stack thread: the recursion limit (300) is
/// above what swift-testing's small Task stack holds, so the guard must be given
/// a production-sized stack to fire on rather than the test harness overflowing
/// first. That is exactly the gap the limit closes on a normal 8 MB main thread.
@Suite("XSLT template recursion limit")
struct XSLTRecursionLimitTests {
private let xsl = "xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\""
/// Runs `body` on a thread with a large stack and returns its result, so the
/// recursion guard is exercised on a production-sized stack.
private func onLargeStack<T: Sendable>(_ body: @escaping @Sendable () -> T) -> T {
let box = Box<T>()
let done = DispatchSemaphore(value: 0)
let thread = Thread {
box.value = body()
done.signal()
}
thread.stackSize = 64 * 1024 * 1024
thread.start()
done.wait()
guard let value = box.value else { preconditionFailure("the worker thread produced no result") }
return value
}
private final class Box<T>: @unchecked Sendable { var value: T? }
/// A stylesheet whose named template recurses `count` times, driving the
/// recursion from the passed parameter (a stand-in for `count(//x)`).
private func recursiveStylesheet(_ count: Int) -> String {
"<xsl:stylesheet version=\"1.0\" \(xsl)>"
+ "<xsl:template match=\"/\"><xsl:call-template name=\"d\">"
+ "<xsl:with-param name=\"n\" select=\"\(count)\"/></xsl:call-template></xsl:template>"
+ "<xsl:template name=\"d\"><xsl:param name=\"n\"/>"
+ "<xsl:if test=\"$n &gt; 0\"><x><xsl:call-template name=\"d\">"
+ "<xsl:with-param name=\"n\" select=\"$n - 1\"/></xsl:call-template></x></xsl:if></xsl:template>"
+ "</xsl:stylesheet>"
}
@Test("recursion past the default limit throws rather than crashing")
func test_deepRecursionFailsGracefully() {
let error: (any Error)? = onLargeStack {
do {
_ = try PureXML.XSLT.transform(stylesheet: recursiveStylesheet(5000), source: "<r/>")
return nil
} catch {
return error
}
}
#expect(error as? PureXML.XSLT.XSLTError == .recursionLimitExceeded(PureXML.XSLT.defaultMaxTemplateDepth))
}
@Test("recursion within the limit transforms normally")
func test_shallowRecursionSucceeds() {
let out = onLargeStack { (try? PureXML.XSLT.transform(stylesheet: recursiveStylesheet(100), source: "<r/>")) ?? "" }
#expect(out.contains("<x>"))
}
@Test("a raised maxTemplateDepth allows deeper legitimate recursion")
func test_configurableLimit() {
let out = onLargeStack {
(try? PureXML.XSLT.transform(stylesheet: recursiveStylesheet(1000), source: "<r/>", maxTemplateDepth: 4000)) ?? ""
}
// Recursion went far past the default limit of 300 (it would otherwise have
// thrown), producing ~1000 nested <x> elements.
#expect(out.components(separatedBy: "<x>").count - 1 > 900)
}
@Test("an identity transform of the deepest permitted source still runs")
func test_identityOfMaxDepthSource() {
let depth = 254 // the parser permits up to maxDepth (256) nesting.
let src = String(repeating: "<a>", count: depth) + "leaf" + String(repeating: "</a>", count: depth)
let sheet = "<xsl:stylesheet version=\"1.0\" \(xsl)>"
+ "<xsl:template match=\"@*|node()\"><xsl:copy><xsl:apply-templates select=\"@*|node()\"/></xsl:copy></xsl:template>"
+ "</xsl:stylesheet>"
let out = onLargeStack { (try? PureXML.XSLT.transform(stylesheet: sheet, source: src)) ?? "" }
#expect(out.contains("leaf"))
#expect(out.contains(String(repeating: "<a>", count: depth)))
}
}
#endif