fix(schema): validate notation declarations and enumeration restrictions

This commit is contained in:
Mihaela Mihaljevic 2026-06-15 22:27:04 +02:00
parent 4a7e23186d
commit 20b97d1d62
10 changed files with 216 additions and 4 deletions

View File

@ -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 `<xs:notation>` 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.

View File

@ -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
}
}

View File

@ -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)

View File

@ -76,5 +76,6 @@ extension PureXML.Schema.XSDParser {
+ attributeRestrictionErrors(schema, context, typeMaps.named)
+ simpleTypeBaseNotComplexErrors(schema, in: context)
+ simpleTypeVarietyErrors(schema, context)
+ notationValidityErrors(containers, context)
}
}

View File

@ -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

View File

@ -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<PureXML.Model.QualifiedName> = []
// 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<PureXML.Model.QualifiedName>,
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<PureXML.Model.QualifiedName>,
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
}
}

View File

@ -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)" }

View File

@ -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("""
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
\(body)
</xs:schema>
""")
}
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(#"""
<xs:notation name="note1" public="http://example.com/pub1"/>
"""#)
}
// system only is valid
#expect(throws: Never.self) {
try compile(#"""
<xs:notation name="note2" system="http://example.com/sys1"/>
"""#)
}
// both is valid
#expect(throws: Never.self) {
try compile(#"""
<xs:notation name="note3" public="http://example.com/pub2" system="http://example.com/sys2"/>
"""#)
}
// neither is invalid
#expect(rejects(#"""
<xs:notation name="note4"/>
"""#))
}
@Test("SimpleType notation restriction enumeration check")
func test_notationEnumeration() {
// Valid enumeration referencing declared notation
#expect(throws: Never.self) {
try compile(#"""
<xs:notation name="jpeg" public="image/jpeg"/>
<xs:simpleType name="myNotation">
<xs:restriction base="xs:NOTATION">
<xs:enumeration value="jpeg"/>
</xs:restriction>
</xs:simpleType>
"""#)
}
// Invalid enumeration referencing undeclared notation
#expect(rejects(#"""
<xs:notation name="png" public="image/png"/>
<xs:simpleType name="myNotation">
<xs:restriction base="xs:NOTATION">
<xs:enumeration value="jpeg"/>
</xs:restriction>
</xs:simpleType>
"""#))
// Notation in the XML namespace referenced with xml prefix
#expect(throws: Never.self) {
_ = try PureXML.Schema.Document(#"""
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
targetNamespace="http://www.w3.org/XML/1998/namespace">
<xs:notation name="xmlNotation" public="http://example.com/xml"/>
<xs:simpleType name="myNotation">
<xs:restriction base="xs:NOTATION">
<xs:enumeration value="xml:xmlNotation"/>
</xs:restriction>
</xs:simpleType>
</xs:schema>
"""#)
}
// Notation with xmlns="" default namespace unbinding
#expect(throws: Never.self) {
_ = try PureXML.Schema.Document(#"""
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns="">
<xs:notation name="jpeg" public="image/jpeg"/>
<xs:simpleType name="myNotation">
<xs:restriction base="xs:NOTATION">
<xs:enumeration value="jpeg"/>
</xs:restriction>
</xs:simpleType>
</xs:schema>
"""#)
}
}
}

View File

@ -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

View File

@ -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 `<simpleType>` restriction base, complexContent restriction attributes prohibition) |