diff --git a/Sources/Canonical/Canonicalizer.swift b/Sources/Canonical/Canonicalizer.swift index d0640b7..ba32f22 100644 --- a/Sources/Canonical/Canonicalizer.swift +++ b/Sources/Canonical/Canonicalizer.swift @@ -19,6 +19,31 @@ public extension PureXML.Canonical { return output } + /// Canonicalizes a subtree that may sit inside a larger document (the C14N + /// node-subset case). The apex element receives the namespace context in + /// scope from its omitted ancestors, and inherits their in-scope `xml:*` + /// attributes (`xml:base`, `xml:lang`, `xml:space`) when it does not set + /// them itself, so signing a fragment yields the same bytes regardless of + /// where the fragment sat in the document. (Inherited `xml:base` follows + /// the C14N 1.0 nearest-ancestor rule, not 1.1 URI joining.) + public func canonicalize(_ subtree: PureXML.Model.TreeNode) -> String { + guard subtree.kind == .element, case let .element(apex) = subtree.node else { + return canonicalize(subtree.node) + } + let ancestorNamespaces = Self.inScopeNamespaces(above: subtree) + let inheritedXML = Self.inheritedXMLAttributes(above: subtree, apex: apex) + var output = "" + switch options.mode { + case .inclusive: + let augmented = Self.augmentedApex(apex, inheritedXML: inheritedXML, mergingNamespaces: ancestorNamespaces) + emit(augmented, inScope: [:], rendered: [:], output: &output) + case .exclusive: + let augmented = Self.augmentedApex(apex, inheritedXML: inheritedXML, mergingNamespaces: nil) + emit(augmented, inScope: ancestorNamespaces, rendered: [:], output: &output) + } + return output + } + private func emit( _ node: PureXML.Model.Node, inScope: [String: String], @@ -144,6 +169,68 @@ public extension PureXML.Canonical { } } + // MARK: Node-subset context + + /// The apex element with its inherited `xml:*` attributes added, and (for + /// inclusive mode) the namespaces in scope from omitted ancestors merged in + /// as declarations so the apex renders its full namespace context. + private static func augmentedApex( + _ apex: PureXML.Model.Element, + inheritedXML: [PureXML.Model.Attribute], + mergingNamespaces ancestorNamespaces: [String: String]?, + ) -> PureXML.Model.Element { + var attributes = apex.attributes + inheritedXML + if let ancestorNamespaces { + let declared = Set(apex.attributes.map(\.name.description)) + for (prefix, uri) in ancestorNamespaces { + let name = prefix.isEmpty ? "xmlns" : "xmlns:\(prefix)" + if !declared.contains(name) { attributes.append(PureXML.Model.Attribute(name, uri)) } + } + } + return PureXML.Model.Element(name: apex.name, attributes: attributes, children: apex.children) + } + + /// The namespace declarations in scope from a node's omitted ancestors, + /// nearest ancestor winning (so an inner redeclaration is preserved). + private static func inScopeNamespaces(above node: PureXML.Model.TreeNode) -> [String: String] { + var result: [String: String] = [:] + var current = node.parent + while let ancestor = current { + for attribute in ancestor.attributes { + guard let prefix = declaredPrefix(of: attribute.name), result[prefix] == nil else { continue } + result[prefix] = attribute.value + } + current = ancestor.parent + } + return result + } + + /// The `xml:*` attributes in scope from a node's omitted ancestors that the + /// apex does not already set, nearest ancestor winning. + private static func inheritedXMLAttributes(above node: PureXML.Model.TreeNode, apex: PureXML.Model.Element) -> [PureXML.Model.Attribute] { + let present = Set(apex.attributes.map(\.name.description)) + var seen: Set = [] + var result: [PureXML.Model.Attribute] = [] + var current = node.parent + while let ancestor = current { + for attribute in ancestor.attributes where attribute.name.prefix == "xml" { + let key = attribute.name.description + guard !present.contains(key), seen.insert(key).inserted else { continue } + result.append(attribute) + } + current = ancestor.parent + } + return result + } + + /// The prefix a namespace declaration binds (empty for the default + /// namespace), or nil when the attribute is not a namespace declaration. + private static func declaredPrefix(of name: PureXML.Model.QualifiedName) -> String? { + if name.prefix == nil, name.localName == "xmlns" { return "" } + if name.prefix == "xmlns" { return name.localName } + return nil + } + // MARK: Escaping private static func escapeText(_ value: String) -> String { diff --git a/Tests/CanonicalSubsetTests.swift b/Tests/CanonicalSubsetTests.swift new file mode 100644 index 0000000..8f4234b --- /dev/null +++ b/Tests/CanonicalSubsetTests.swift @@ -0,0 +1,47 @@ +@testable import PureXML +import Testing + +@Suite("Canonical XML: node-subset canonicalization and xml:* inheritance") +struct CanonicalSubsetTests { + /// The document is held for the duration of each test: a TreeNode's parent + /// link is weak, so the canonicalizer only sees a node's ancestors while the + /// tree that owns them is alive (the standard DOM top-down ownership). + private func canonicalize(_ xml: String, at path: [Int], _ options: PureXML.Canonical.Options) throws -> String { + let document = try PureXML.parseTree(xml) + var node = document + for index in path { + node = node.children[index] + } + return PureXML.Canonical.Canonicalizer(options: options).canonicalize(node) + } + + @Test("An inclusive subtree renders the namespaces in scope from its ancestors") + func test_inheritedNamespace() throws { + let output = try canonicalize("", at: [0, 0], .inclusive) + #expect(output == "") + } + + @Test("A subtree inherits xml:lang and xml:space from omitted ancestors") + func test_inheritedXMLAttributes() throws { + let output = try canonicalize("", at: [0, 0], .inclusive) + #expect(output == "") + } + + @Test("The apex's own xml:* attribute overrides an inherited one") + func test_apexOverridesInherited() throws { + let output = try canonicalize("", at: [0, 0], .inclusive) + #expect(output == "") + } + + @Test("An exclusive subtree renders only the ancestor namespaces it uses") + func test_exclusiveOnlyUsed() throws { + let output = try canonicalize("", at: [0, 0], .exclusive) + #expect(output == "") + } + + @Test("A nearer ancestor's namespace binding wins over a farther one") + func test_nearestNamespaceWins() throws { + let output = try canonicalize("", at: [0, 0, 0], .inclusive) + #expect(output == "") + } +}