From 20b97d1d62639ef6e0bb728272b1ba0f439a0528 Mon Sep 17 00:00:00 2001 From: Mihaela Mihaljevic Date: Mon, 15 Jun 2026 22:27:04 +0200 Subject: [PATCH] fix(schema): validate notation declarations and enumeration restrictions --- CHANGELOG.md | 1 + Sources/Schema/BuiltinType.swift | 2 + Sources/Schema/Primitive.swift | 3 +- Sources/Schema/SchemaIDAttribute.swift | 1 + Sources/Schema/SchemaNameUniqueness.swift | 2 +- Sources/Schema/SchemaNotationValidity.swift | 101 +++++++++++++++++++ Sources/Schema/SimpleType.swift | 1 + Tests/SchemaNotationValidityTests.swift | 105 ++++++++++++++++++++ Tests/XSTSSuiteTests.swift | 2 +- docs/schema-validity-burndown.md | 2 +- 10 files changed, 216 insertions(+), 4 deletions(-) create mode 100644 Sources/Schema/SchemaNotationValidity.swift create mode 100644 Tests/SchemaNotationValidityTests.swift diff --git a/CHANGELOG.md b/CHANGELOG.md index 5e40aa9..454533c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Fixed +- Validate notation declarations and notation enumeration constraints on simpleTypes (XSD 1.0 Structures §3.12 / §3.14). Every `` declaration must specify at least one of `public` or `system` attributes. For any simpleType restricting `xs:NOTATION`, all `enumeration` values must name a declared notation in the schema. Resolved prefix bindings are traversed recursively up the ancestor path to handle default namespaces and local namespace declarations. XSTS: invalid schemas accepted 309 to 306, no other bucket raised. - Enforce cross-container global component-name and identity-constraint uniqueness constraints (XSD 1.0 Structures §3.14). Within a schema (including all included and imported schemas), global type names (simpleType and complexType sharing one symbol space), global element names, global attribute names, named model groups, and named attribute groups must be unique within their respective symbol spaces and target namespaces. Identity constraints (unique, key, keyref) must have unique names across all target namespaces in the entire schema document. Circular and duplicate imports/includes are handled namespace-aware without causing false-positive validations on valid schemas. XSTS: invalid schemas accepted 316 to 309, no other bucket raised. - Enforce substitution group exclusions based on element final and schema finalDefault attributes (XSD 1.0 Structures §3.3.6 / Schema Component Constraint: Substitution Group OK (Transitive)), including support for element declarations with inline anonymous types. The entire derivation path from the member type to the head type is checked; if any step contains a derivation method prohibited by the head element's final or the schema's finalDefault, the substitution is rejected. XSTS: invalid schemas accepted 323 to 316, no other bucket raised. - Enforce targetNamespace scope matching on local schema references (XSD 1.0 Structures §3.14). If a schema has a targetNamespace declared, any local type, element, attribute, group, or attributeGroup reference without a namespace prefix (resolving to no namespace) is rejected as undeclared unless a default namespace matching the targetNamespace is declared on the element, since all global components defined in the document belong to the targetNamespace. XSTS: invalid schemas accepted 325 to 323, no other bucket raised. diff --git a/Sources/Schema/BuiltinType.swift b/Sources/Schema/BuiltinType.swift index 86221f1..da60e4b 100644 --- a/Sources/Schema/BuiltinType.swift +++ b/Sources/Schema/BuiltinType.swift @@ -50,6 +50,7 @@ public extension PureXML.Schema { case base64Binary case anyURI case qName = "QName" + case notation = "NOTATION" var whiteSpace: WhiteSpace { switch self { @@ -122,6 +123,7 @@ public extension PureXML.Schema { case .base64Binary: .base64Binary case .anyURI: .anyURI case .qName: .qName + case .notation: .notation default: .string } } diff --git a/Sources/Schema/Primitive.swift b/Sources/Schema/Primitive.swift index 30fa09a..dcd54fc 100644 --- a/Sources/Schema/Primitive.swift +++ b/Sources/Schema/Primitive.swift @@ -34,6 +34,7 @@ extension PureXML.Schema { case ncName case nmtoken case language + case notation func isValid(_ value: String) -> Bool { stringValidity(value) ?? numericValidity(value) @@ -45,7 +46,7 @@ extension PureXML.Schema { switch self { case .string, .anyURI: true case .boolean: Lexical.isBoolean(value) - case .qName: Lexical.isQName(value) + case .qName, .notation: Lexical.isQName(value) case .name: Lexical.isName(value) case .ncName: Lexical.isNCName(value) case .nmtoken: Lexical.isNMToken(value) diff --git a/Sources/Schema/SchemaIDAttribute.swift b/Sources/Schema/SchemaIDAttribute.swift index 27fdd4c..2ccd20b 100644 --- a/Sources/Schema/SchemaIDAttribute.swift +++ b/Sources/Schema/SchemaIDAttribute.swift @@ -76,5 +76,6 @@ extension PureXML.Schema.XSDParser { + attributeRestrictionErrors(schema, context, typeMaps.named) + simpleTypeBaseNotComplexErrors(schema, in: context) + simpleTypeVarietyErrors(schema, context) + + notationValidityErrors(containers, context) } } diff --git a/Sources/Schema/SchemaNameUniqueness.swift b/Sources/Schema/SchemaNameUniqueness.swift index 387f0d7..95b003f 100644 --- a/Sources/Schema/SchemaNameUniqueness.swift +++ b/Sources/Schema/SchemaNameUniqueness.swift @@ -217,7 +217,7 @@ extension PureXML.Schema.XSDParser { return true } - private static func resolveContainerNamespaces(_ containers: [XSDTree], mainTargetNamespace: String?) -> [Int: String?] { + static func resolveContainerNamespaces(_ containers: [XSDTree], mainTargetNamespace: String?) -> [Int: String?] { var resolved: [Int: String?] = [:] guard !containers.isEmpty else { return resolved } let mainIndex = containers.count - 1 diff --git a/Sources/Schema/SchemaNotationValidity.swift b/Sources/Schema/SchemaNotationValidity.swift new file mode 100644 index 0000000..f151ff9 --- /dev/null +++ b/Sources/Schema/SchemaNotationValidity.swift @@ -0,0 +1,101 @@ +extension PureXML.Schema.XSDParser { + static func notationValidityErrors( + _ containers: [XSDTree], + _ context: PureXML.Schema.XSDContext, + ) -> [String] { + let namespaceMap = resolveContainerNamespaces(containers, mainTargetNamespace: context.targetNamespace) + var errors: [String] = [] + var declaredNotations: Set = [] + + // 1. Collect all declared notations and validate notation declarations + for index in containers.indices { + let container = containers[index] + let containerNamespace = namespaceMap[index] ?? context.targetNamespace + for child in PureXML.Schema.XSDNode.elementChildren(container) { + guard child.name?.namespaceURI == xsdNamespace, + PureXML.Schema.XSDNode.localName(child) == "notation" + else { + continue + } + let name = PureXML.Schema.XSDNode.attribute(child, "name") ?? "" + if PureXML.Schema.XSDNode.attribute(child, "public") == nil, PureXML.Schema.XSDNode.attribute(child, "system") == nil { + errors.append("notation '\(name)' must specify at least one of public or system attributes") + } + let qName = PureXML.Model.QualifiedName(localName: name, namespaceURI: containerNamespace) + declaredNotations.insert(qName) + } + } + + // 2. Validate notation enumeration constraints on simpleTypes + for index in containers.indices { + let container = containers[index] + walkSimpleTypes(container, context: context, declaredNotations: declaredNotations, into: &errors) + } + + return errors + } + + private static func walkSimpleTypes( + _ node: XSDTree, + context: PureXML.Schema.XSDContext, + declaredNotations: Set, + into errors: inout [String], + ) { + let local = PureXML.Schema.XSDNode.localName(node) + if local == "appinfo" || local == "documentation" { return } + + if node.name?.namespaceURI == xsdNamespace, local == "restriction" { + validateNotationRestriction(node, context: context, declaredNotations: declaredNotations, into: &errors) + } + + for child in PureXML.Schema.XSDNode.elementChildren(node) { + walkSimpleTypes(child, context: context, declaredNotations: declaredNotations, into: &errors) + } + } + + private static func validateNotationRestriction( + _ node: XSDTree, + context: PureXML.Schema.XSDContext, + declaredNotations: Set, + into errors: inout [String], + ) { + guard let parent = node.parent, + parent.name?.namespaceURI == xsdNamespace, + PureXML.Schema.XSDNode.localName(parent) == "simpleType", + let baseAttr = PureXML.Schema.XSDNode.attribute(node, "base") + else { + return + } + let baseType = PureXML.Schema.XSDSimpleParser.simpleTypeReference(baseAttr, context) + guard baseType.base == .notation else { return } + + let bindings = collectBindings(from: node) + for child in PureXML.Schema.XSDNode.elementChildren(node) where child.name?.namespaceURI == xsdNamespace && PureXML.Schema.XSDNode.localName(child) == "enumeration" { + guard let value = PureXML.Schema.XSDNode.attribute(child, "value") else { continue } + let prefix = PureXML.Schema.XSDNode.prefix(value) + let resolvedNamespace = prefix == "xml" ? "http://www.w3.org/XML/1998/namespace" : PureXML.Schema.XSDNode.referenceNamespace(value, bindings) + let localVal = PureXML.Schema.XSDNode.stripPrefix(value) + let valQName = PureXML.Model.QualifiedName(prefix: prefix, localName: localVal, namespaceURI: resolvedNamespace) + let isDeclared = declaredNotations.contains { dec in + let decNS = (dec.namespaceURI == "") ? nil : dec.namespaceURI + let valNS = (valQName.namespaceURI == "") ? nil : valQName.namespaceURI + return dec.localName == valQName.localName && decNS == valNS + } + if !isDeclared { + errors.append("notation enumeration value '\(value)' does not name a declared notation") + } + } + } + + private static func collectBindings(from node: XSDTree) -> [String: String] { + var bindings: [String: String] = [:] + var current: XSDTree? = node + while let element = current { + for (prefix, uri) in PureXML.Schema.XSDNode.namespaceBindings(of: element) where bindings[prefix] == nil { + bindings[prefix] = uri + } + current = element.parent + } + return bindings + } +} diff --git a/Sources/Schema/SimpleType.swift b/Sources/Schema/SimpleType.swift index 197b2d2..011bed2 100644 --- a/Sources/Schema/SimpleType.swift +++ b/Sources/Schema/SimpleType.swift @@ -241,6 +241,7 @@ public extension PureXML.Schema { // unspecified (XSD 1.0 Datatypes 4.3.1), so like Xerces and the XSTS // NIST oracle we do not constrain QName values by length. if case .qName = primitive { return nil } + if case .notation = primitive { return nil } let length = primitive.measuredLength(value) if let exact = facets.length, length != exact { return "length \(length) is not \(exact)" } if let minimum = facets.minLength, length < minimum { return "length \(length) is below \(minimum)" } diff --git a/Tests/SchemaNotationValidityTests.swift b/Tests/SchemaNotationValidityTests.swift new file mode 100644 index 0000000..f016e2c --- /dev/null +++ b/Tests/SchemaNotationValidityTests.swift @@ -0,0 +1,105 @@ +@testable import PureXML +import Testing + +@Suite("Schema notation validity tests") +struct SchemaNotationValidityTests { + private func compile(_ body: String) throws { + _ = try PureXML.Schema.Document(""" + + \(body) + + """) + } + + private func rejects(_ body: String) -> Bool { + do { + try compile(body) + return false + } catch { + return true + } + } + + @Test("Notation must specify public or system attribute") + func test_notationAttributes() { + // public only is valid + #expect(throws: Never.self) { + try compile(#""" + + """#) + } + + // system only is valid + #expect(throws: Never.self) { + try compile(#""" + + """#) + } + + // both is valid + #expect(throws: Never.self) { + try compile(#""" + + """#) + } + + // neither is invalid + #expect(rejects(#""" + + """#)) + } + + @Test("SimpleType notation restriction enumeration check") + func test_notationEnumeration() { + // Valid enumeration referencing declared notation + #expect(throws: Never.self) { + try compile(#""" + + + + + + + """#) + } + + // Invalid enumeration referencing undeclared notation + #expect(rejects(#""" + + + + + + + """#)) + + // Notation in the XML namespace referenced with xml prefix + #expect(throws: Never.self) { + _ = try PureXML.Schema.Document(#""" + + + + + + + + + """#) + } + + // Notation with xmlns="" default namespace unbinding + #expect(throws: Never.self) { + _ = try PureXML.Schema.Document(#""" + + + + + + + + + """#) + } + } +} diff --git a/Tests/XSTSSuiteTests.swift b/Tests/XSTSSuiteTests.swift index e745999..0cadfb3 100644 --- a/Tests/XSTSSuiteTests.swift +++ b/Tests/XSTSSuiteTests.swift @@ -29,7 +29,7 @@ struct XSTSSuiteTests { /// XSTS` (debug is far slower and the corpus is large). Per-case deviations /// are written to /tmp/xsts-failures.txt for the burn-down. private let knownSchemaValidRejected = 1 - private let knownSchemaInvalidAccepted = 309 + private let knownSchemaInvalidAccepted = 306 private let knownInstanceValidRejected = 171 private let knownInstanceInvalidAccepted = 155 diff --git a/docs/schema-validity-burndown.md b/docs/schema-validity-burndown.md index 674be10..6696861 100644 --- a/docs/schema-validity-burndown.md +++ b/docs/schema-validity-burndown.md @@ -10,7 +10,7 @@ irreducible tail. Do not deviate to new features while this is open. | Bucket | Count | Reading | |---|---|---| | valid-schemas-rejected | **72 -> 4** | production target is 0: rejecting a correct schema is the most user-hostile defect (#148). Particle-restriction over-rejection fixed: pointless `maxOccurs=0` particles removed, content-free restriction of an EMPTY base, empty-derived emptiable-base, and (#163) the pairwise check over the normalized content model with occurrence subsumption applied only to same-kind pairings (cross-kind element/group, group/element, group/wildcard match occurrence inside, by effective total range / member). #164 resolved element-ref namespaces by prefix binding (the `particlesJj/Jk/Jm/Jn/Js`, `particlesQ/R` cluster, -28). Content-free (`maxOccurs=0`) derived groups and substitution-group declaration order closed `particlesW006`/`elemZ027_a`; the W3C MapAndSum rule (Sequence:Choice, #165) closed `particlesV003`. Remaining 1 (`particlesZ001`): a documented spec ambiguity (RecurseAsIfGroup; the reference rejects it), not a defect. | -| **invalid-schemas-accepted** | **2461 -> 309** | we rarely catch a bad one (facet, default/fixed value, particle-restriction name+type, id, structural content-model, UPA determinism, content order, identity-constraint XPath-subset, wildcard-namespace, final/block, simpleType content, group/wildcard and group/element cardinality, element-ref namespace, sequence/choice MapAndSum, circular type derivation, circular group/attributeGroup/substitution references, attribute-use uniqueness and single-ID, type-excludes-inline-type, ID-typed value-constraint exclusion, all-group reference placement, substitution-member type derivation, default/fixed mutual exclusion, elementTypeRestrictionOK NameAndTypeOK union checks, prohibited attribute type-check bypass, keyref arity verification, top-level group/attributeGroup local-attribute checks, simpleType restriction structure and prefix binding checks, namespace-aware reference resolution checks, simpleType variety constraints on list itemType and union memberTypes, targetNamespace scope matching on local schema references, substitution group exclusions based on element final and schema finalDefault attributes, cross-container component-name and identity-constraint uniqueness checks landed). | +| **invalid-schemas-accepted** | **2461 -> 306** | we rarely catch a bad one (facet, default/fixed value, particle-restriction name+type, id, structural content-model, UPA determinism, content order, identity-constraint XPath-subset, wildcard-namespace, final/block, simpleType content, group/wildcard and group/element cardinality, element-ref namespace, sequence/choice MapAndSum, circular type derivation, circular group/attributeGroup/substitution references, attribute-use uniqueness and single-ID, type-excludes-inline-type, ID-typed value-constraint exclusion, all-group reference placement, substitution-member type derivation, default/fixed mutual exclusion, elementTypeRestrictionOK NameAndTypeOK union checks, prohibited attribute type-check bypass, keyref arity verification, top-level group/attributeGroup local-attribute checks, simpleType restriction structure and prefix binding checks, namespace-aware reference resolution checks, simpleType variety constraints on list itemType and union memberTypes, targetNamespace scope matching on local schema references, substitution group exclusions based on element final and schema finalDefault attributes, cross-container component-name and identity-constraint uniqueness checks, notation declarations and notation enumeration restrictions landed). | | valid-instances-rejected | **233 -> 171** | (instance side; #164's element-ref namespace fix is shared with instance validation, complexContent restriction attributes inheritance and namespace fixes) | | invalid-instances-accepted | **160 -> 155** | (instance side; resolving inline `` restriction base, complexContent restriction attributes prohibition) |