fix(xslt): composition cycles terminate; id() gains a per-document index

An include or import cycle recursed without bound and crashed the
host with a stack overflow, reachable from stylesheet data. The
compile chain tracks the active load chain by resolved href and drops
re-entry, while diamond composition keeps loading both copies with
their own import precedences per 2.6.2. id() builds a per-document
index on first use instead of re-walking the document per call,
matching key(). Cycle and diamond regression tests added.
This commit is contained in:
Mihaela Mihaljevic 2026-06-10 18:06:13 +02:00
parent 3ea4e6f37d
commit 6c0afa3749
7 changed files with 99 additions and 23 deletions

View File

@ -11,6 +11,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- Scanner-side validity findings are now located structured values (validation-framework audit follow-up): `DocumentType.validityFindings` carries `ValidityFinding` values (reason plus the declared name they are about) instead of strings, `DTDSchema.declarationErrors` holds ready `ValidationError`s, and every declaration-level finding renders at its declaration's coding path (`x`, `r/@a`) instead of "at root of document", matching the XSD consistency-errors precedent. Finding texts are unchanged.
### Fixed
- Stylesheet composition cycles no longer crash (#130 critic loop): an include or import cycle (a.xsl includes b.xsl includes a.xsl) recursed without bound and killed the host with a stack overflow, a denial of service reachable from stylesheet data. The compile chain now tracks the active load chain by resolved href and drops re-entry, while diamond composition (two units legitimately loading the same sheet) keeps loading both copies with their own import precedences, per 2.6.2. id() also gains a per-document index built on first use instead of re-walking the whole document per call, matching key(). Cycle and diamond regression tests added.
### Added
- Top-level stylesheet parameters (#141), nineteenth xalan burn-down (#130): `PureXML.XSLT.transform` accepts `parameters: [String: String]`, overriding `xsl:param` globals by name (xsl:variable globals are never overridable; the stylesheet records which names are parameters across imports and includes). The conformance runner honors the xalan harness contract, reading `<case>.param` files; en alphabet sorting passes, and the CRLF param files exposed a Swift grapheme gotcha (CRLF is one Character, so splitting on "\n" never splits; the runner splits on newline graphemes). Baseline 128 to 127; Polish/Russian alphabet tailoring stays baselined as the locale class.

View File

@ -125,7 +125,7 @@ flowchart TB
PureXML is a working, dependency-free XML library today: parse, emit, validate,
query, and stream documents on macOS, Linux, Windows, and WASM. The test suite
currently runs **978 tests in 167 suites** (`swift test`).
currently runs **980 tests in 167 suites** (`swift test`).
### Shipped (libxml2-aligned surface)

View File

@ -33,6 +33,9 @@ extension PureXML.XSLT {
/// name to the names of its ID-typed attributes. A document with no
/// entry has no IDs (the XPath id() definition needs the DTD).
var idAttributes: [ObjectIdentifier: [String: Set<String>]] = [:]
/// The id() index per document root, built on first use: ID value to
/// its element (the first in document order wins, per ID semantics).
var idIndexes: [ObjectIdentifier: [String: PureXML.Model.TreeNode]] = [:]
}
/// The ID-typed attributes a document type declares, element name to

View File

@ -21,28 +21,40 @@ extension PureXML.XSLT.Library {
while let parent = documentRoot.parent {
documentRoot = parent
}
guard let declared = documents.idAttributes[ObjectIdentifier(documentRoot)], !declared.isEmpty else {
let rootIdentity = ObjectIdentifier(documentRoot)
guard let declared = documents.idAttributes[rootIdentity], !declared.isEmpty else {
return .nodeSet([])
}
var matched: [PureXML.XPath.Node] = []
collectIdentified(documentRoot, declared: declared, tokens: tokens, into: &matched)
// The index is built once per document, not re-walked per call.
let index: [String: PureXML.Model.TreeNode]
if let cached = documents.idIndexes[rootIdentity] {
index = cached
} else {
var built: [String: PureXML.Model.TreeNode] = [:]
buildIDIndex(documentRoot, declared: declared, into: &built)
documents.idIndexes[rootIdentity] = built
index = built
}
let matched = index.filter { tokens.contains($0.key) }.values
.map { PureXML.XPath.Node.tree($0) }
.sorted(by: PureXML.XPath.Node.precedes)
return .nodeSet(matched)
}
private static func collectIdentified(
/// Walks the document once, indexing every DTD-identified element by
/// its ID value; the first occurrence in document order wins.
private static func buildIDIndex(
_ node: PureXML.Model.TreeNode,
declared: [String: Set<String>],
tokens: Set<String>,
into matched: inout [PureXML.XPath.Node],
into index: inout [String: PureXML.Model.TreeNode],
) {
let idNames = node.name.flatMap { declared[$0.description] } ?? []
let identified = node.kind == .element && !idNames.isEmpty
&& node.attributes.contains { idNames.contains($0.name.description) && tokens.contains($0.value) }
if identified {
matched.append(.tree(node))
if node.kind == .element, let name = node.name?.description, let idNames = declared[name] {
for attribute in node.attributes where idNames.contains(attribute.name.description) {
if index[attribute.value] == nil { index[attribute.value] = node }
}
}
for child in node.children {
collectIdentified(child, declared: declared, tokens: tokens, into: &matched)
buildIDIndex(child, declared: declared, into: &index)
}
}

View File

@ -59,10 +59,10 @@ extension PureXML.XSLT {
/// import subtree, the set apply-imports searches. An included
/// stylesheet's declarations join the including unit at its
/// precedence; its imports join the including unit's import list.
static func compile(_ top: XSLTTree, loader: (String) -> String?, counter: inout Int, base: String = "") -> Stylesheet {
static func compile(_ top: XSLTTree, loader: (String) -> String?, counter: inout Int, base: String = "", chain: Set<String> = []) -> Stylesheet {
var parts = Parts()
let low = counter
var collector = XSLTUnitCollector(counter: counter)
var collector = XSLTUnitCollector(counter: counter, chain: chain)
collectUnit(top, loader: loader, base: base, into: &collector, imports: &parts)
counter = collector.counter
let precedence = counter
@ -88,11 +88,20 @@ extension PureXML.XSLT {
for child in XSLTNode.elementChildren(top) where XSLTNode.isXSL(child) {
switch XSLTNode.localName(child) {
case "import":
parts.fold(load(child, loader: loader, counter: &collector.counter, base: base), isImport: true)
case "include":
if let (tree, resolved) = loadTree(child, loader: loader, base: base) {
let loadedImport = loadTree(child, loader: loader, base: base)
if let (tree, resolved) = loadedImport, !collector.chain.contains(resolved) {
collector.retainedRoots.append(tree)
parts.fold(compile(tree, loader: loader, counter: &collector.counter, base: resolved, chain: collector.chain.union([resolved])), isImport: true)
}
case "include":
let loadedInclude = loadTree(child, loader: loader, base: base)
if let (tree, resolved) = loadedInclude, !collector.chain.contains(resolved) {
collector.retainedRoots.append(tree)
// The include flattens into this unit: its href joins
// the chain for the nested walk and leaves with it.
collector.chain.insert(resolved)
collectUnit(tree, loader: loader, base: resolved, into: &collector, imports: &parts)
collector.chain.remove(resolved)
}
default:
collector.declarations.append((child, base))
@ -147,11 +156,6 @@ extension PureXML.XSLT {
return (top, resolved)
}
private static func load(_ node: XSLTTree, loader: (String) -> String?, counter: inout Int, base: String) -> Stylesheet? {
guard let (top, resolved) = loadTree(node, loader: loader, base: base) else { return nil }
return compile(top, loader: loader, counter: &counter, base: resolved)
}
private static func parseOutput(_ node: XSLTTree) -> Output {
Output(
method: XSLTNode.attribute(node, "method"),

View File

@ -8,4 +8,8 @@ struct XSLTUnitCollector {
var counter: Int
var declarations: [(XSLTTree, String)] = []
var retainedRoots: [XSLTTree] = []
/// The resolved hrefs on the active load chain (ancestors only, not
/// siblings): re-entry means an include or import cycle, which is
/// dropped; a diamond (two units loading the same sheet) stays legal.
var chain: Set<String> = []
}

View File

@ -203,4 +203,53 @@ struct XSLTCompositionTests {
#expect(overridden == "<out>supplied-fixed</out>")
#expect(try PureXML.XSLT.transform(stylesheet: style, source: "<x/>") == "<out>default-fixed</out>")
}
@Test("An include or import cycle terminates instead of recursing forever")
func test_compositionCycle() throws {
let first = """
<xsl:stylesheet version="1.0" \(xsl)>
<xsl:include href="b.xsl"/>
<xsl:output omit-xml-declaration="yes"/>
<xsl:template match="/"><out/></xsl:template>
</xsl:stylesheet>
"""
let second = """
<xsl:stylesheet version="1.0" \(xsl)><xsl:include href="a.xsl"/></xsl:stylesheet>
"""
let result = try PureXML.XSLT.transform(
stylesheet: first,
source: "<x/>",
documentLoader: { ["a.xsl": first, "b.xsl": second][$0] },
)
#expect(result == "<out/>")
}
@Test("A diamond import stays legal: both sides load the shared sheet")
func test_diamondImport() throws {
let shared = """
<xsl:stylesheet version="1.0" \(xsl)><xsl:template match="item">S</xsl:template></xsl:stylesheet>
"""
let left = """
<xsl:stylesheet version="1.0" \(xsl)><xsl:import href="shared.xsl"/></xsl:stylesheet>
"""
let right = """
<xsl:stylesheet version="1.0" \(xsl)><xsl:import href="shared.xsl"/><xsl:template match="item">R<xsl:apply-imports/></xsl:template></xsl:stylesheet>
"""
let style = """
<xsl:stylesheet version="1.0" \(xsl)>
<xsl:import href="left.xsl"/>
<xsl:import href="right.xsl"/>
<xsl:output omit-xml-declaration="yes"/>
<xsl:template match="/"><out><xsl:apply-templates select="//item"/></out></xsl:template>
</xsl:stylesheet>
"""
let result = try PureXML.XSLT.transform(
stylesheet: style,
source: "<r><item/></r>",
documentLoader: { ["shared.xsl": shared, "left.xsl": left, "right.xsl": right][$0] },
)
// right.xsl wins (later import); its apply-imports reaches its own
// imported copy of shared.xsl.
#expect(result == "<out>RS</out>")
}
}