fix(schema): enforce element-level block against xsi:type substitution

The block on an element declaration (distinct from block on its type) was
parsed into the derivation tables but never threaded to the instance validator,
so an xsi:type that substitutes a type derived by a blocked method was accepted.
elementBlock now flows through XSDCompiled, SchemaDocument, the validation
context, and both ComplexValidator construction sites to blockedSubstitutionError,
which checks the element's own block alongside the type's. It also resolves the
element-ref type indirection (a ref'd child carries an `element:foo` key that
resolves through `types` to the concrete declared type) so the derivation chain
and block checks fire for referenced children, not only the document root.

XSTS: invalid instances accepted 261 to 240. Baseline updated; regression tests
cover element block rejecting a restriction xsi:type, the no-block control, and
an unrelated block not over-rejecting.

Refs #147, #129.
This commit is contained in:
Mihaela Mihaljevic 2026-06-13 17:35:41 +02:00
parent 2ad15b774f
commit 43456029ac
9 changed files with 90 additions and 7 deletions

View File

@ -9,6 +9,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Fixed
- Element-level `block` is now enforced against `xsi:type` substitution (#147). The `block` on an element declaration (distinct from `block` on its type) was parsed but never threaded to the instance validator, so a document substituting a blocked-derivation type via `xsi:type` was wrongly accepted. The element block is now carried through to `blockedSubstitutionError`, which also resolves the element-ref type indirection (`element:foo` to its concrete type) so the check fires for referenced children, not only the root. XSTS: invalid instances accepted 261 to 240.
- The regex engine now recognizes the full XSD `\p{Is<Block>}` Unicode block set (#147). Only about fifteen blocks were tabulated, so a pattern over any other block (`\p{IsArmenian}`, `\p{IsTamil}`, `\p{IsHangulJamo}`, and so on) failed to compile and rejected valid instances. The table now carries the Unicode 3.1 blocks the XSD regular-expression appendix fixes (surrogate blocks omitted, since surrogates are not scalar values); each range is verified bidirectionally by the XSTS corpus (valid in-block instances pass, invalid out-of-block instances still fail). XSTS: valid instances rejected 502 to 395.
- Length facets on `xs:QName` no longer reject valid values (#147). XSD 1.0 Datatypes 4.3.1 does not define a unit of length for QName (only string, anyURI, binary, and list), so `length`/`minLength`/`maxLength` on QName are implementation-defined; like Xerces and the XSTS NIST set we treat them as non-constraining rather than counting characters. Net XSTS: valid instances rejected 547 to 502 (36+ NIST false rejections fixed); 4 Microsoft cases that read QName length as a character count remain in invalid instances accepted (257 to 261) and are documented as a deliberate spec-ambiguity interpretation in docs/xsts-deviations.md.
- Ordering facets on `xs:duration` are now enforced (#147). `minInclusive`, `maxInclusive`, `minExclusive`, and `maxExclusive` on duration were ignored because duration has no total order in the generic comparator. A `DurationValue` now implements the XSD 1.0 Datatypes 3.2.6.2 partial order (compare by adding to the four reference dateTimes); a value incomparable to the bound (such as `P1M` against `P30D`) is outside the range and rejected. XSTS: invalid instances accepted 355 to 257.

View File

@ -25,6 +25,9 @@ public extension PureXML.Schema {
let abstractTypes: Set<String>
/// Derivation methods each named type forbids through `xsi:type`.
let typeBlock: [String: Set<DerivationMethod>]
/// Derivation methods each element declaration forbids through `xsi:type`
/// (the `block` on the element, distinct from the block on its type).
let elementBlock: [String: Set<DerivationMethod>]
/// Each named complex type's base and derivation method.
let typeDerivation: [String: TypeDerivation]
@ -34,6 +37,7 @@ public extension PureXML.Schema {
elementConstraints: [String: ValueConstraint] = [:],
abstractTypes: Set<String> = [],
typeBlock: [String: Set<DerivationMethod>] = [:],
elementBlock: [String: Set<DerivationMethod>] = [:],
typeDerivation: [String: TypeDerivation] = [:],
) {
self.types = types
@ -41,6 +45,7 @@ public extension PureXML.Schema {
self.elementConstraints = elementConstraints
self.abstractTypes = abstractTypes
self.typeBlock = typeBlock
self.elementBlock = elementBlock
self.typeDerivation = typeDerivation
}

View File

@ -23,16 +23,32 @@ extension PureXML.Schema.ComplexValidator {
child: PureXML.Model.Element,
at path: [PureXML.Validation.PathKey],
) -> PureXML.Validation.ValidationError? {
guard case let .typeReference(declaredName) = declared,
let substitute = Self.xsiTypeName(child), types[substitute] != nil,
let blocked = typeBlock[declaredName],
let methods = PureXML.Schema.XSDParser.derivationMethods(from: substitute, to: declaredName, typeDerivation),
!methods.isDisjoint(with: blocked)
guard case let .typeReference(reference) = declared,
let substitute = Self.xsiTypeName(child), types[substitute] != nil
else {
return nil
}
// A ref'd child carries its type as an element-ref key (`element:foo`)
// that resolves through `types` to the concrete type; follow that chain
// to the declared type name the derivation backbone and `block` use.
var declaredName = reference
var steps = 0
while case let .typeReference(next)? = types[declaredName], next != declaredName, steps <= types.count {
declaredName = next
steps += 1
}
guard let methods = PureXML.Schema.XSDParser.derivationMethods(from: substitute, to: declaredName, typeDerivation) else {
return nil
}
// The substitution is blocked when the derivation method is disallowed by
// either the declared type's `block` or the element declaration's own
// `block` (keyed by the element's name).
let blocked = (typeBlock[declaredName] ?? []).union(elementBlock[child.name.localName] ?? [])
guard !methods.isDisjoint(with: blocked) else {
return nil
}
return PureXML.Validation.ValidationError(
reason: "xsi:type '\(substitute)' is blocked: type '\(declaredName)' disallows substitution by this derivation",
reason: "xsi:type '\(substitute)' is blocked: substitution by this derivation is disallowed",
at: path,
)
}

View File

@ -44,6 +44,7 @@ public extension PureXML.Schema {
private let abstractTypes: Set<String>
private let abstractElements: Set<String>
private let typeBlock: [String: Set<DerivationMethod>]
private let elementBlock: [String: Set<DerivationMethod>]
private let typeDerivation: [String: TypeDerivation]
private let targetNamespace: String?
@ -62,6 +63,7 @@ public extension PureXML.Schema {
abstractTypes = compiled.abstractTypes
abstractElements = compiled.abstractElements
typeBlock = compiled.typeBlock
elementBlock = compiled.elementBlock
typeDerivation = compiled.typeDerivation
targetNamespace = compiled.targetNamespace
// Schema consistency through the validation framework: every named
@ -96,6 +98,7 @@ public extension PureXML.Schema {
elementConstraints: elementConstraints,
abstractTypes: abstractTypes,
typeBlock: typeBlock,
elementBlock: elementBlock,
typeDerivation: typeDerivation,
)
var driver = PureXML.Validation.StreamingXSDValidator(
@ -138,6 +141,7 @@ public extension PureXML.Schema {
elementConstraints: elementConstraints,
abstractTypes: abstractTypes,
typeBlock: typeBlock,
elementBlock: elementBlock,
typeDerivation: typeDerivation,
)
return PureXML.Validation.XSD.validator().errors(for: .element(root), in: context)

View File

@ -113,6 +113,8 @@ extension PureXML.Schema {
var abstractElements: Set<String> = []
/// Derivation methods the named type forbids when used through `xsi:type`.
var typeBlock: [String: Set<DerivationMethod>] = [:]
/// Derivation methods each element declaration forbids through `xsi:type`.
var elementBlock: [String: Set<DerivationMethod>] = [:]
/// Each named complex type's base type and derivation method, the backbone
/// the `block` check walks from an `xsi:type` to its declared type.
var typeDerivation: [String: TypeDerivation] = [:]

View File

@ -60,6 +60,7 @@ extension PureXML.Schema {
abstractTypes: derivation.abstractTypes,
abstractElements: derivation.abstractElements,
typeBlock: derivation.typeBlock,
elementBlock: derivation.elementBlock,
typeDerivation: derivation.typeDerivation,
typeFinal: derivation.typeFinal,
targetNamespace: context.targetNamespace,

View File

@ -10,6 +10,7 @@ public extension PureXML.Validation {
public let elementConstraints: [String: PureXML.Schema.ValueConstraint]
public let abstractTypes: Set<String>
public let typeBlock: [String: Set<PureXML.Schema.DerivationMethod>]
public let elementBlock: [String: Set<PureXML.Schema.DerivationMethod>]
public let typeDerivation: [String: PureXML.Schema.TypeDerivation]
public init(
@ -20,6 +21,7 @@ public extension PureXML.Validation {
elementConstraints: [String: PureXML.Schema.ValueConstraint] = [:],
abstractTypes: Set<String> = [],
typeBlock: [String: Set<PureXML.Schema.DerivationMethod>] = [:],
elementBlock: [String: Set<PureXML.Schema.DerivationMethod>] = [:],
typeDerivation: [String: PureXML.Schema.TypeDerivation] = [:],
) {
self.types = types
@ -29,6 +31,7 @@ public extension PureXML.Validation {
self.elementConstraints = elementConstraints
self.abstractTypes = abstractTypes
self.typeBlock = typeBlock
self.elementBlock = elementBlock
self.typeDerivation = typeDerivation
}
}
@ -66,6 +69,7 @@ public extension PureXML.Validation {
elementConstraints: context.document.elementConstraints,
abstractTypes: context.document.abstractTypes,
typeBlock: context.document.typeBlock,
elementBlock: context.document.elementBlock,
typeDerivation: context.document.typeDerivation,
)
.validate(root, as: declaration, at: [.element(root.name.description)])

View File

@ -0,0 +1,50 @@
@testable import PureXML
import Testing
/// `block` on an element declaration forbids substituting a type derived from
/// the declared type by a listed method via `xsi:type`, distinct from `block`
/// on the type itself (#147, XSTS elemT set). The element-level block was parsed
/// but never enforced, so blocked substitutions were wrongly accepted.
@Suite("Element-level block on xsi:type substitution")
struct SchemaElementBlockTests {
private func schema(block: String) throws -> PureXML.Schema.Document {
let attribute = block.isEmpty ? "" : " block=\"\(block)\""
return try PureXML.Schema.Document("""
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="root">
<xs:complexType><xs:sequence>
<xs:element ref="foo"/>
</xs:sequence></xs:complexType>
</xs:element>
<xs:element name="foo" type="Base"\(attribute)/>
<xs:complexType name="Base">
<xs:sequence><xs:element name="a" type="xs:string"/></xs:sequence>
</xs:complexType>
<xs:complexType name="Restricted">
<xs:complexContent>
<xs:restriction base="Base">
<xs:sequence><xs:element name="a" type="xs:string"/></xs:sequence>
</xs:restriction>
</xs:complexContent>
</xs:complexType>
</xs:schema>
""")
}
private let instance = #"<root><foo xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="Restricted"><a>x</a></foo></root>"#
@Test("block='restriction' on an element rejects a restriction xsi:type")
func test_elementBlockRejectsRestriction() throws {
#expect(try !schema(block: "restriction").validate(instance).isEmpty)
}
@Test("an element without block accepts the same restriction xsi:type")
func test_noBlockAcceptsRestriction() throws {
#expect(try schema(block: "").validate(instance).isEmpty)
}
@Test("block='extension' does not block a restriction substitution")
func test_unrelatedBlockDoesNotReject() throws {
#expect(try schema(block: "extension").validate(instance).isEmpty)
}
}

View File

@ -31,7 +31,7 @@ struct XSTSSuiteTests {
private let knownSchemaValidRejected = 75
private let knownSchemaInvalidAccepted = 2467
private let knownInstanceValidRejected = 395
private let knownInstanceInvalidAccepted = 261
private let knownInstanceInvalidAccepted = 240
@Test("Every XSTS case behaves: compile, reject, validate, invalidate")
func test_suite() throws {