PureXML/Sources/XSLT/XSLTSorting.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

202 lines
8.5 KiB
Swift

/// A node queued for sorting: its original offset and computed keys.
private struct SortEntry {
let offset: Int
let node: PureXML.XPath.Node
let keys: [String]
}
extension PureXML.XSLT.Transformer {
func sorted(_ nodes: [PureXML.XPath.Node], _ sorts: [PureXML.XSLT.Sort], _ context: XSLTContext) -> [PureXML.XPath.Node] {
guard !sorts.isEmpty else { return nodes }
// Keys are computed once per node with the node's own evaluation
// context (its position and size in the selection, the caller's
// variables and bindings), so position()-based keys work.
let keyed = nodes.enumerated().map { offset, xnode -> SortEntry in
guard let owner = Self.ownerNode(xnode) else { return SortEntry(offset: offset, node: xnode, keys: sorts.map { _ in "" }) }
var keyContext = XSLTContext(
node: owner,
current: xnode.treeNode == nil ? xnode : nil,
position: offset + 1,
size: nodes.count,
variables: context.variables,
)
keyContext.namespaces = context.namespaces
keyContext.baseURI = context.baseURI
return SortEntry(offset: offset, node: xnode, keys: sorts.map { string($0.select, keyContext) })
}
// A lang attribute value template evaluates once per sort, in the
// caller's context; a known language selects its tailored alphabet.
let tailorings: [[Character: Int]?] = sorts.map { sort in
sort.lang.flatMap { PureXML.XSLT.Collation.table(for: avt($0, context)) }
}
return keyed.sorted { lhs, rhs in
for (index, sort) in sorts.enumerated() {
let order: Int
if !sort.numeric, sort.caseOrder == nil, let ranks = tailorings[index] {
let tailored = PureXML.XSLT.Collation.compare(lhs.keys[index], rhs.keys[index], ranks)
order = sort.descending ? -tailored : tailored
} else {
order = Self.compareKeys(lhs.keys[index], rhs.keys[index], sort)
}
if order != 0 { return order < 0 }
}
return lhs.offset < rhs.offset
}.map(\.node)
}
static func compareKeys(_ left: String, _ right: String, _ sort: PureXML.XSLT.Sort) -> Int {
var order: Int
if sort.numeric {
let leftNumber = PureXML.XPath.Value.parseNumber(left)
let rightNumber = PureXML.XPath.Value.parseNumber(right)
// NaN keys sort before every number (the Xalan order).
switch (leftNumber.isNaN, rightNumber.isNaN) {
case (true, true): order = 0
case (true, false): order = -1
case (false, true): order = 1
case (false, false): order = leftNumber == rightNumber ? 0 : (leftNumber < rightNumber ? -1 : 1)
}
} else if let caseOrder = sort.caseOrder {
order = caseInsensitiveCompare(left, right, caseOrder)
} else {
order = collate(left, right)
}
return sort.descending ? -order : order
}
/// Text sort order: spaces are ignorable at the primary level (Java
/// Collator semantics, which the conformance golds encode); when the
/// space-stripped strings tie, the string whose first space comes later
/// (or that has none) sorts first.
static func collate(_ left: String, _ right: String) -> Int {
let strippedLeft = left.filter { $0 != " " }
let strippedRight = right.filter { $0 != " " }
if strippedLeft != strippedRight {
return strippedLeft < strippedRight ? -1 : 1
}
let leftSpaces = spacePositions(left)
let rightSpaces = spacePositions(right)
if leftSpaces == rightSpaces { return 0 }
for (leftIndex, rightIndex) in zip(leftSpaces, rightSpaces) where leftIndex != rightIndex {
return leftIndex > rightIndex ? -1 : 1
}
return leftSpaces.count < rightSpaces.count ? -1 : 1
}
private static func spacePositions(_ text: String) -> [Int] {
text.enumerated().compactMap { $1 == " " ? $0 : nil }
}
func forEach(
_ select: String,
_ sorts: [PureXML.XSLT.Sort],
_ body: [PureXML.XSLT.Instruction],
_ context: XSLTContext,
) -> [ResultItem] {
let nodes = sorted(selectXPathNodes(select, context), sorts, context)
var items: [ResultItem] = []
for (offset, xnode) in nodes.enumerated() {
guard let owner = Self.ownerNode(xnode) else { continue }
var itemContext = XSLTContext(
node: owner,
current: xnode.treeNode == nil ? xnode : nil,
position: offset + 1,
size: nodes.count,
variables: context.variables,
)
itemContext.baseURI = context.baseURI
items += instantiate(body, itemContext)
}
return items
}
func chooseInstruction(
_ whens: [PureXML.XSLT.Branch],
_ otherwise: [PureXML.XSLT.Instruction],
_ context: XSLTContext,
) -> [ResultItem] {
for branch in whens where boolean(branch.test, context) {
return instantiate(branch.body, context)
}
return instantiate(otherwise, context)
}
func builtInRule(_ xnode: PureXML.XPath.Node, mode: String?, _ context: XSLTContext) -> [ResultItem] {
recursionGuard.depth += 1
defer { recursionGuard.depth -= 1 }
guard recursionGuard.depth <= maxTemplateDepth else {
recursionGuard.exceeded = true
return []
}
return switch xnode {
case let .tree(node):
switch node.kind {
case .element, .document:
applyTemplates(to: node.children.map { .tree($0) }, mode: mode, parameters: [], context)
case .text, .cdata:
[.node(.text(node.value))]
default:
[]
}
case let .attribute(_, attribute):
[.node(.text(attribute.value))]
case let .namespace(_, _, uri):
[.node(.text(uri))]
}
}
/// Copies the nodes selected by `select` into the result tree (`xsl:copy-of`);
/// a non-node-set result copies as its string value. Whole subtrees are taken
/// as-is, so this does not recurse on their depth.
func copyOf(_ select: String, _ context: XSLTContext) -> [ResultItem] {
guard let nodes = value(select, context)?.nodes else {
// A non-node-set result copies as its string value.
return value(select, context).map { [.node(.text($0.string))] } ?? []
}
return nodes.map { xnode in
switch xnode {
case let .tree(tree): .node(Self.withInScopeNamespaces(tree))
case let .attribute(_, attribute): .attribute(attribute)
case let .namespace(_, prefix, uri):
.attribute(.init(prefix.isEmpty ? "xmlns" : "xmlns:\(prefix)", uri))
}
}
}
func message(_ terminate: Bool, _ body: [PureXML.XSLT.Instruction], _ context: XSLTContext) -> [ResultItem] {
if terminate, termination.message == nil {
termination.message = Self.text(of: instantiate(body, context))
}
return []
}
/// Binds the template's parameters (a passed `with-param` wins over the
/// declared default) and instantiates its body.
func instantiateTemplate(
_ template: PureXML.XSLT.Template,
_ context: XSLTContext,
passing parameters: [PureXML.XSLT.Binding],
from caller: XSLTContext,
) -> [ResultItem] {
recursionGuard.depth += 1
defer { recursionGuard.depth -= 1 }
guard recursionGuard.depth <= maxTemplateDepth else {
recursionGuard.exceeded = true
return []
}
var context = context
context.importPrecedence = template.importPrecedence
context.importRangeLow = template.importRangeLow
context.namespaces = template.namespaces
context.baseURI = template.baseURI
for parameter in template.parameters {
if let passed = parameters.first(where: { $0.name == parameter.name }) {
context.variables[parameter.name] = variableValue(passed.select, passed.body, caller)
} else {
context.variables[parameter.name] = variableValue(parameter.select, parameter.body, context)
}
}
return instantiate(template.body, context)
}
}