feat(schema): validate identity constraint keyref field arity mismatch

This commit is contained in:
Mihaela Mihaljevic 2026-06-15 18:23:45 +02:00
parent 31fe3e7c22
commit 80064be6b8
5 changed files with 70 additions and 13 deletions

View File

@ -13,6 +13,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- Enforce top-level declaration naming, block xs:anySimpleType derivation, and restrict simpleType facets. Top-level definitions must specify a `name` attribute. Derivation by restriction or extension of `xs:anySimpleType` is disallowed. Restriction facets (`length`, `minLength`, `maxLength`, `totalDigits`, `fractionDigits`) must be tighter than or equal to the base type's facets. XSTS: invalid schemas accepted 387 to 383, no other bucket raised.
- Enforce simpleType derivation constraints on restricted complexType attributes (XSD 1.0 `cos-ct-derived-ok` / `derivation-ok-restriction.1`). The type of a restricted attribute must be validly derived by restriction from its base counterpart, checking atomic built-in derivation, list item type restriction, and union membership or member-to-member restriction recursively. XSTS: invalid schemas accepted 367 to 365, no other bucket raised.
- Enforce element type restriction constraints on restricted complexType particles (XSD 1.0 `NameAndTypeOK` / `elementTypeRestrictionOK`). Verify that the restricted particle's type validly derives by restriction from the base particle's type, checking union variety members structurally, prohibiting complex-restricting-simple and simple-restricting-complex (except where base is `anyType`), and falling back to name-based derivation. Prohibited attributes are exempted from type and value constraint checks. XSTS: invalid schemas accepted 365 to 357, no other bucket raised.
- Enforce identity constraint keyref arity validation at schema compile time (XSD 1.0 `c-identity-constraint`). Verify that the number of fields in a keyref matches the arity of its referenced key or unique constraint. XSTS: invalid schemas accepted 357 to 354, no other bucket raised.
## [0.1.0] - 2026-06-15

View File

@ -23,31 +23,61 @@ extension PureXML.Schema.XSDParser {
return errors
}
private struct KeyrefInfo {
let name: String
let refer: String
let arity: Int
}
/// Findings for a `keyref` whose `refer` does not name a `key` or `unique` in
/// the document. Skipped when the document pulls in external definitions
/// the document, or whose field arity does not match the referenced key/unique's.
/// Skipped when the document pulls in external definitions
/// (`import`/`include`/`redefine`), which the default compile does not load,
/// so a `refer` into them is never flagged.
private static func keyrefReferErrors(_ schema: XSDTree) -> [String] {
if hasExternalReference(schema) { return [] }
var names: Set<String> = []
var refers: [String] = []
collectKeysAndRefers(schema, names: &names, refers: &refers)
return refers.filter { !names.contains($0) }
.map { "keyref refers to undeclared key or unique '\($0)'" }
var keyArities: [String: Int] = [:]
var keyrefs: [KeyrefInfo] = []
collectKeysAndRefers(schema, keyArities: &keyArities, keyrefs: &keyrefs)
var errors: [String] = []
for keyref in keyrefs {
if let keyArity = keyArities[keyref.refer] {
if keyArity != keyref.arity {
errors.append("keyref '\(keyref.name)' and its referenced key/unique '\(keyref.refer)' must have the same number of fields")
}
} else {
errors.append("keyref refers to undeclared key or unique '\(keyref.refer)'")
}
}
return errors
}
private static func collectKeysAndRefers(_ node: XSDTree, names: inout Set<String>, refers: inout [String]) {
private static func collectKeysAndRefers(
_ node: XSDTree,
keyArities: inout [String: Int],
keyrefs: inout [KeyrefInfo],
) {
if let local = PureXML.Schema.XSDNode.localName(node), local == "appinfo" || local == "documentation" { return }
if node.name?.namespaceURI == xsdNamespace, let local = PureXML.Schema.XSDNode.localName(node) {
if local == "key" || local == "unique", let name = PureXML.Schema.XSDNode.attribute(node, "name")?.trimmingXMLWhitespace() {
names.insert(name)
let arity = PureXML.Schema.XSDNode.elementChildren(node)
.count(where: { $0.name?.namespaceURI == xsdNamespace && PureXML.Schema.XSDNode.localName($0) == "field" })
keyArities[name] = arity
}
if local == "keyref", let refer = PureXML.Schema.XSDNode.attribute(node, "refer")?.trimmingXMLWhitespace() {
refers.append(PureXML.Schema.XSDNode.stripPrefix(refer))
if local == "keyref" {
let name = PureXML.Schema.XSDNode.attribute(node, "name")?.trimmingXMLWhitespace()
let refer = PureXML.Schema.XSDNode.attribute(node, "refer")?.trimmingXMLWhitespace()
if let name, let refer {
let arity = PureXML.Schema.XSDNode.elementChildren(node)
.count(where: { $0.name?.namespaceURI == xsdNamespace && PureXML.Schema.XSDNode.localName($0) == "field" })
keyrefs.append(KeyrefInfo(name: name, refer: PureXML.Schema.XSDNode.stripPrefix(refer), arity: arity))
}
}
}
for child in PureXML.Schema.XSDNode.elementChildren(node) {
collectKeysAndRefers(child, names: &names, refers: &refers)
collectKeysAndRefers(child, keyArities: &keyArities, keyrefs: &keyrefs)
}
}

View File

@ -72,6 +72,32 @@ struct SchemaNameUniquenessTests {
"""#))
}
@Test("a keyref arity must match its referenced key or unique")
func test_keyrefArityMismatch() {
// keyref and key have different arities (1 vs 2): must be rejected.
#expect(rejects(#"""
<xs:element name="root">
<xs:complexType><xs:sequence><xs:element ref="a"/></xs:sequence></xs:complexType>
<xs:key name="k">
<xs:selector xpath="a"/>
<xs:field xpath="@id1"/>
<xs:field xpath="@id2"/>
</xs:key>
<xs:keyref name="r" refer="k">
<xs:selector xpath="a"/>
<xs:field xpath="@ref"/>
</xs:keyref>
</xs:element>
<xs:element name="a">
<xs:complexType>
<xs:attribute name="id1" type="xs:string"/>
<xs:attribute name="id2" type="xs:string"/>
<xs:attribute name="ref" type="xs:string"/>
</xs:complexType>
</xs:element>
"""#))
}
@Test("a duplicate identity-constraint name is rejected")
func test_duplicateIdentityConstraint() {
#expect(rejects(#"""

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 = 357
private let knownSchemaInvalidAccepted = 354
private let knownInstanceValidRejected = 180
private let knownInstanceInvalidAccepted = 158

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 -> 357** | 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 landed). |
| **invalid-schemas-accepted** | **2461 -> 354** | 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 landed). |
| valid-instances-rejected | **233 -> 180** | (instance side; #164's element-ref namespace fix is shared with instance validation, -34) |
| invalid-instances-accepted | **160 -> 158** | (instance side; resolving an inline `<simpleType>` restriction base preserves list/union variety, so a `length` facet counts items and two more invalid instances are caught) |