diff --git a/CHANGELOG.md b/CHANGELOG.md index 74ddbdd..24c4cc6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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 `.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. diff --git a/README.md b/README.md index 742862b..fe68ee5 100644 --- a/README.md +++ b/README.md @@ -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) diff --git a/Sources/XSLT/XSLTDocumentCache.swift b/Sources/XSLT/XSLTDocumentCache.swift index 7e0516f..13ae173 100644 --- a/Sources/XSLT/XSLTDocumentCache.swift +++ b/Sources/XSLT/XSLTDocumentCache.swift @@ -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]] = [:] + /// 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 diff --git a/Sources/XSLT/XSLTLookups.swift b/Sources/XSLT/XSLTLookups.swift index 744ca55..b808e3e 100644 --- a/Sources/XSLT/XSLTLookups.swift +++ b/Sources/XSLT/XSLTLookups.swift @@ -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], - tokens: Set, - 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) } } diff --git a/Sources/XSLT/XSLTParser.swift b/Sources/XSLT/XSLTParser.swift index 7ca6baa..9909d4c 100644 --- a/Sources/XSLT/XSLTParser.swift +++ b/Sources/XSLT/XSLTParser.swift @@ -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 = []) -> 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"), diff --git a/Sources/XSLT/XSLTUnitCollector.swift b/Sources/XSLT/XSLTUnitCollector.swift index 96a3a0f..cb24175 100644 --- a/Sources/XSLT/XSLTUnitCollector.swift +++ b/Sources/XSLT/XSLTUnitCollector.swift @@ -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 = [] } diff --git a/Tests/XSLTCompositionTests.swift b/Tests/XSLTCompositionTests.swift index 06e7d15..758bfab 100644 --- a/Tests/XSLTCompositionTests.swift +++ b/Tests/XSLTCompositionTests.swift @@ -203,4 +203,53 @@ struct XSLTCompositionTests { #expect(overridden == "supplied-fixed") #expect(try PureXML.XSLT.transform(stylesheet: style, source: "") == "default-fixed") } + + @Test("An include or import cycle terminates instead of recursing forever") + func test_compositionCycle() throws { + let first = """ + + + + + + """ + let second = """ + + """ + let result = try PureXML.XSLT.transform( + stylesheet: first, + source: "", + documentLoader: { ["a.xsl": first, "b.xsl": second][$0] }, + ) + #expect(result == "") + } + + @Test("A diamond import stays legal: both sides load the shared sheet") + func test_diamondImport() throws { + let shared = """ + S + """ + let left = """ + + """ + let right = """ + R + """ + let style = """ + + + + + + + """ + let result = try PureXML.XSLT.transform( + stylesheet: style, + source: "", + 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 == "RS") + } }