feat(schema): validate built-in-typed default/fixed values

An element/attribute default/fixed value must be a valid value of its type
(Attribute/Element Locally Valid, XSD 1.0). A fixed="abc" on an xs:integer or a
default="1 2" on an xs:int was accepted because the value constraint was never
checked at compile time.

The value is now validated against its type when the type resolves to a
built-in datatype (namespace-aware: only a type in the XSD namespace),
normalising whitespace per the type so a default=" 5 " on an integer stays
valid. A named or inline user type is left to its own rules, so no valid value
constraint is rejected.

XSTS: invalid schemas accepted 638 to 621, valid schemas rejected held at 72,
instance buckets unchanged.
This commit is contained in:
Mihaela Mihaljevic 2026-06-14 11:55:55 +02:00
parent 0143381f67
commit 3e3b937e89
6 changed files with 84 additions and 2 deletions

View File

@ -9,6 +9,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Fixed
- An element/attribute `default`/`fixed` value must be a valid value of its `type` (Attribute/Element Locally Valid, XSD 1.0, #158). A `fixed="abc"` on an `xs:integer` or a `default="1 2"` on an `xs:int` was accepted because the value constraint was never checked at compile time. The value is now validated against its type when the type resolves to a built-in datatype (namespace-aware: only a `type` in the XSD namespace), normalising whitespace per the type as XSD requires (so `default=" 5 "` on an integer is valid); a named or inline user type is left to its own rules, so no valid value constraint is rejected. XSTS: invalid schemas accepted 638 to 621, no other bucket raised (valid schemas rejected held at 72).
- A constraining facet must apply to its simple type's variety (XSD 1.0 Part 2, #158). A `list` may be constrained only by `length`/`minLength`/`maxLength`, `pattern`, `enumeration`, and `whiteSpace`; a `union` only by `pattern` and `enumeration`. A value-bound facet (`maxInclusive`, `totalDigits`, ...) constrains an atomic value space, so restricting a list (`list of integer`) by `maxInclusive` was wrongly accepted. The base's variety is resolved from the raw tree (the check runs before the types are compiled), namespace-aware so a user type that shares a built-in's local name does not flip the variety: a base in the XSD namespace is a built-in (only the list datatypes are list-variety), a base in the schema's own target namespace resolves to a declared global, and an external or unresolvable base is skipped, so no valid restriction is rejected. XSTS: invalid schemas accepted 664 to 638, no other bucket raised (valid schemas rejected held at 72).
- A complexType's shorthand content (without `simpleContent`/`complexContent`) is now checked for order, not just cardinality (#158). Its model is `(annotation?, (group | all | choice | sequence)?, (attribute | attributeGroup)*, anyAttribute?)`: an optional model group, then attributes, then an optional `anyAttribute`. The existing content-shape check caught the wrong number of model groups and the exclusivity of a content spec, but not the order, so a model group after an attribute, an attribute after `anyAttribute`, or a second `anyAttribute` (the ctB family) was accepted. The complexType's direct children, excluding `annotation` and the content specs, are matched against the same ordered slot model used for a `complexContent` derivation. XSTS: invalid schemas accepted 687 to 664, no other bucket raised (valid schemas rejected held at 72).
- An `any`/`anyAttribute` wildcard's `namespace` constraint is now validated at compile time (#158). Its value space is `('##any' | '##other')` standing alone, or a list of namespace URIs and the `##targetNamespace`/`##local` tokens; the wildcard parser mapped any unrecognised token to a literal URI, so a misspelled token (`##all`, `##target`), an `##any`/`##other` placed inside a list (`##any ##other`), or any other `##`-prefixed token was accepted. The unprefixed `namespace` value is now tokenised and checked against that grammar, while `##any`/`##other` are admitted only as the whole value; a prefixed (foreign) attribute that merely shares the local name is the author's own and is not checked, so no valid schema is rejected. XSTS: invalid schemas accepted 736 to 687, no other bucket raised (valid schemas rejected held at 72).

View File

@ -28,6 +28,38 @@ extension PureXML.Schema.XSDParser {
return errors
}
/// A `default`/`fixed` value on an `element` or `attribute` must be a valid value
/// of its `type` (Attribute/Element Locally Valid, XSD 1.0). Only a type that
/// resolves to a built-in datatype is checked, since the check runs before the
/// types are compiled; a `fixed="abc"` on an `xs:integer` was wrongly accepted.
/// A named or inline user type, or a type in another namespace, is left alone, so
/// no valid value constraint is rejected.
static func valueConstraintErrors(_ schema: XSDTree) -> [String] {
let bindings = namespaceBindings(schema)
var errors: [String] = []
forEachValueConstrained(schema) { node in
guard let typeName = PureXML.Schema.XSDNode.attribute(node, "type") else { return }
let fixed = PureXML.Schema.XSDNode.attribute(node, "fixed")
guard let value = fixed ?? PureXML.Schema.XSDNode.attribute(node, "default") else { return }
let (prefix, local) = splitQName(typeName)
let uri = prefix.map { bindings[$0] } ?? bindings[""]
guard uri == xsdNamespace, let builtin = PureXML.Schema.BuiltinType(rawValue: local),
!PureXML.Schema.SimpleType(base: builtin).isValid(value)
else { return }
errors.append("the \(fixed != nil ? "fixed" : "default") value '\(value)' is not valid for type '\(typeName)'")
}
return errors
}
private static func forEachValueConstrained(_ node: XSDTree, _ visit: (XSDTree) -> Void) {
let local = PureXML.Schema.XSDNode.localName(node)
if local == "appinfo" || local == "documentation" { return }
if local == "element" || local == "attribute" { visit(node) }
for child in PureXML.Schema.XSDNode.elementChildren(node) {
forEachValueConstrained(child, visit)
}
}
private static let facetNames: Set<String> = [
"minExclusive", "minInclusive", "maxExclusive", "maxInclusive", "totalDigits",
"fractionDigits", "length", "minLength", "maxLength", "enumeration", "whiteSpace", "pattern",

View File

@ -57,6 +57,7 @@ extension PureXML.Schema.XSDParser {
var errors: [String] = []
collectStructure(schema, into: &errors)
errors += simpleTypeVarietyFacetErrors(schema)
errors += valueConstraintErrors(schema)
return errors
}

View File

@ -0,0 +1,48 @@
@testable import PureXML
import Testing
/// An element/attribute `default`/`fixed` value must be a valid value of its
/// `type` (Attribute/Element Locally Valid, XSD 1.0), checked at compile time.
/// Only a built-in type is checked (a named/inline user type is left to its own
/// rules), covering the attO family (`fixed="abc"` on `xs:integer`).
@Suite("Default/fixed value validity (compile time)")
struct SchemaValueConstraintValidityTests {
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("a built-in-typed default/fixed value outside the type's value space is rejected")
func test_invalidValues() {
#expect(rejects(#"<xs:attribute name="a" type="xs:integer" fixed="abc"/>"#))
#expect(rejects(#"<xs:attribute name="a" type="xs:int" default="abc"/>"#))
#expect(rejects(#"<xs:element name="e" type="xs:int" default="1 2"/>"#))
#expect(rejects(#"<xs:element name="e" type="xs:boolean" fixed="maybe"/>"#))
#expect(rejects(#"<xs:attribute name="a" type="xs:date" default="not-a-date"/>"#))
}
@Test("a valid built-in-typed default/fixed value compiles, with whitespace normalized")
func test_validValues() throws {
try compile(#"<xs:attribute name="a" type="xs:integer" fixed="42"/>"#)
try compile(#"<xs:element name="e" type="xs:int" default=" 5 "/>"#)
try compile(#"<xs:attribute name="a" type="xs:boolean" default="true"/>"#)
try compile(#"<xs:element name="e" type="xs:string" fixed="anything goes"/>"#)
}
@Test("a default/fixed value on a non-built-in type is left alone")
func test_userTypeUnchecked() throws {
try compile(#"""
<xs:simpleType name="t"><xs:restriction base="xs:string"/></xs:simpleType>
<xs:attribute name="a" type="t" fixed="anything"/>
"""#)
}
}

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 = 72
private let knownSchemaInvalidAccepted = 638
private let knownSchemaInvalidAccepted = 621
private let knownInstanceValidRejected = 214
private let knownInstanceInvalidAccepted = 165

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 | we rarely reject a good schema |
| **invalid-schemas-accepted** | **2461 -> 638** | we rarely catch a bad one (facet definition + applicability, id, structural content-model, UPA determinism, complexContent + complexType content order, identity-constraint XPath-subset, and wildcard-namespace validity landed) |
| **invalid-schemas-accepted** | **2461 -> 621** | we rarely catch a bad one (facet definition + applicability, default/fixed value validity, id, structural content-model, UPA determinism, complexContent + complexType content order, identity-constraint XPath-subset, and wildcard-namespace validity landed) |
| valid-instances-rejected | 233 | (instance side, separately tracked) |
| invalid-instances-accepted | 165 | |