fix(schema): reject redefined attribute group adding attributes via non-self reference

A redefinition of an attributeGroup is a restriction of the original
(src-redefine / cos-ct-restricts), so it may not introduce an attribute the
original lacks unless the original carries an attribute wildcard. The existing
add-attribute check resolved only the redefinition's DIRECT declarations and was
suppressed whenever the redefinition carried any attributeGroup reference, which
conflated a self-reference (re-importing the original's own attributes, valid)
with a non-self reference (injecting foreign attributes, invalid).

Resolve the attribute names a non-self reference contributes and key the
suppression on a genuine self-reference (matched by namespace and local name).
The resolution declines, staying lenient, whenever the contributed set is not
fully knowable: an unresolved group, an attribute-by-ref, an attribute wildcard,
or a further nested reference. This catches W3C XSTS attgC028 (a redefinition
whose ref="car" replaces the original's attributes with foreign ones) while
keeping attgC007/attgC038/groupB018 (added attributes alongside a self-reference)
valid.

XSTS schema invalid-accepted 25 -> 24, valid-rejected held at 0.
This commit is contained in:
Mihaela Mihaljevic 2026-06-22 01:29:57 +02:00
parent 6e7f1b7bfc
commit 81805ad53e
4 changed files with 127 additions and 19 deletions

View File

@ -38,6 +38,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Fixed
- A redefinition of an `attributeGroup` that adds an attribute the original lacks through a NON-self `attributeGroup` reference is now rejected. A redefinition is a restriction of the original (src-redefine / cos-ct-restricts), so it may not introduce an attribute the original does not declare unless the original carries an attribute wildcard. The add-attribute check previously resolved only the redefinition's DIRECT declarations and was suppressed whenever the redefinition carried any `attributeGroup` reference, which conflated a self-reference (re-importing the original's own attributes, valid) with a non-self reference (injecting foreign attributes, invalid). The redefinition's contributed attribute names are now resolved through its non-self references and the suppression keys on a genuine self-reference (matched by namespace and local name); resolution declines, staying lenient, whenever the contributed set is not fully knowable (an unresolved group, an attribute-by-`ref`, an `anyAttribute` wildcard, or a further nested reference). This catches attgC028 (a redefinition whose `ref="car"` replaces the original's attributes with foreign ones) while keeping attgC007/attgC038/groupB018 (added attributes alongside a self-reference) valid. XSTS invalid-schemas-accepted 25 → 24 (attgC028), valid-schemas-rejected held at 0.
- An unprefixed `type`/`base`/`itemType`/`memberTypes` reference to a type declared in a non-empty target namespace is now rejected as undeclared. With no default `xmlns`, an unprefixed QName resolves to the absent namespace, so `type="t"` is `{}t`, not `{urn:x}t` where the type lives; `isUndeclaredReferenceType` matched the type by local name and accepted it. It now mirrors `isUndeclaredReferenceRef`: a no-namespace reference is undeclared when the schema has a non-empty target namespace (a chameleon-included global, and an imported no-namespace type via the foreign pools, remain accepted). XSTS invalid-schemas-accepted 27 → 25 (addB009/test66059 and one more), valid-schemas-rejected held at 0.
- A schema reference (`ref`/`substitutionGroup`) that resolves to the XSD namespace is now rejected as undeclared. The XSD namespace declares no referenceable user component, so `isUndeclaredReferenceType` already rejected a `type`/`base` in it, but `isUndeclaredReferenceRef` fell through to a lenient accept. This is reached when an unprefixed reference picks up a default `xmlns` of the XSD namespace, so it is not in the target namespace where the schema's own components live: e.g. `xmlns="http://www.w3.org/2001/XMLSchema" targetNamespace="foo"` with `<element ref="root"/>` resolves to `{XSD}root`, not `{foo}root`, and is undeclared. A schema that itself targets the XSD namespace, and a genuinely loaded XSD-namespace document, are unaffected. XSTS invalid-schemas-accepted 29 → 27 (xsd013/xsd014), valid-schemas-rejected held at 0.
- Unique Particle Attribution now checks a `complexContent` extension against its EFFECTIVE content model (the base type's content followed by the extension's), not just the extension's own particles. A base whose trailing particle can recur or end optionally competes with the extension's leading particles, so an element could match either across the extension boundary; that cross-boundary non-determinism was missed and the schema wrongly accepted. The base content is resolved and prepended only for a local (target-namespace), non-cyclic base chain; a foreign, built-in (`xs:anyType`), unresolved, or cyclic base leaves the check on the extension's own content, so no valid schema is newly rejected. XSTS invalid-schemas-accepted 31 → 29 (particlesZ022 and one more), valid-schemas-rejected held at 0.

View File

@ -69,9 +69,10 @@ extension PureXML.Schema.XSDParser {
guard let name = RedefineNode.attribute(redefinition, "name"),
let baseGroup = resolveBaseComponent(base, name: name, owner: redefinition)
else { continue }
let referenced = referencedAttributeNames(of: redefinition, ownName: name, base: base)
// Each restriction violation is a property of this redefinition's
// attribute group, so it locates on the redefinition declaration.
findings += attributeGroupRestrictionErrors(name: name, base: baseGroup, redefinition: redefinition)
findings += attributeGroupRestrictionErrors(name: name, base: baseGroup, redefinition: redefinition, referenced: referenced)
.map { PureXML.Schema.SchemaLocatedFinding(reason: $0, node: redefinition) }
}
}
@ -111,7 +112,53 @@ extension PureXML.Schema.XSDParser {
base[namespacedKey(name, owner: owner)] ?? base["{}\(name)"]
}
private static func attributeGroupRestrictionErrors(name: String, base: XSDTree, redefinition: XSDTree) -> [String] {
/// The non-prohibited attribute names a redefinition pulls in through its
/// `attributeGroup` references, with whether any of them is a SELF-reference
/// (resolving by NAMESPACE and local name to the redefinition's own name+target).
/// A self-reference re-imports the original and is reported via `hasSelfReference`
/// rather than counted. Returns nil (decline, stay lenient) when a referenced
/// group does not resolve from the base pool, carries an attribute wildcard, nests
/// a further `attributeGroup` reference, or names an attribute by `ref` (not
/// `name`): in each case the contributed set is not fully known, so the add-check
/// must not fire. A redefinition with no `attributeGroup` reference yields an empty
/// set and no self-reference, preserving the direct-declaration-only behavior.
private static func referencedAttributeNames(
of redefinition: XSDTree, ownName: String, base: [String: XSDTree],
) -> (names: Set<String>, hasSelfReference: Bool)? {
let schema = RedefineNode.schemaOwner(redefinition)
let target = RedefineNode.attribute(schema, "targetNamespace") ?? ""
let bindings = RedefineNode.namespaceBindings(of: schema)
var names: Set<String> = []
var hasSelfReference = false
for child in RedefineNode.elementChildren(redefinition) where RedefineNode.localName(child) == "attributeGroup" {
guard let ref = RedefineNode.attribute(child, "ref") else { return nil }
let refNamespace = RedefineNode.referenceNamespace(ref, bindings) ?? ""
if RedefineNode.stripPrefix(ref) == ownName, refNamespace == target {
hasSelfReference = true
continue
}
guard let group = base["{\(refNamespace)}\(RedefineNode.stripPrefix(ref))"] else { return nil }
for member in RedefineNode.elementChildren(group) {
switch RedefineNode.localName(member) {
case "attribute":
guard let attrName = RedefineNode.attribute(member, "name") else { return nil }
if RedefineNode.attribute(member, "use") != "prohibited" { names.insert(attrName) }
case "anyAttribute", "attributeGroup":
return nil
default:
break
}
}
}
return (names, hasSelfReference)
}
private static func attributeGroupRestrictionErrors(
name: String,
base: XSDTree,
redefinition: XSDTree,
referenced: (names: Set<String>, hasSelfReference: Bool)?,
) -> [String] {
var errors: [String] = []
let children = RedefineNode.elementChildren(redefinition)
// The redefinition's attributes by name, so a check can read the `use` (a
@ -124,23 +171,20 @@ extension PureXML.Schema.XSDParser {
let use: (String) -> String? = { redefined[$0].map { RedefineNode.attribute($0, "use") ?? "optional" } }
let hasReference = children.contains { RedefineNode.localName($0) == "attributeGroup" }
let baseHasWildcard = RedefineNode.elementChildren(base).contains { RedefineNode.localName($0) == "anyAttribute" }
// A restriction may not ADD an attribute the original does not have (a superset).
// Checked only when the original's attribute set is fully known from its direct
// declarations (no nested attributeGroup reference could supply the name), and
// only when the redefinition itself carries no attributeGroup reference: a
// self-reference brings in the original's attributes, so declaring further ones
// alongside it is a valid redefine (W3C attgC007/attgC038/groupB018), not an
// addition. Both guards keep the check from mistaking an inherited attribute for
// a newly added one.
// A restriction may not ADD an attribute the original lacks (and the original
// has no wildcard to admit it). The redefinition's full attribute set is its
// direct declarations PLUS those pulled in by a NON-self attributeGroup
// reference (`referenced.names`); a self-reference re-imports the original's own
// attributes, so declaring further ones alongside it is a valid redefine (W3C
// attgC007/attgC038/groupB018), not an addition. The check runs only when that
// set is fully known (`referenced` resolved, no self-reference) and the
// original's set is fully known (no nested reference, no wildcard), so an
// inherited attribute is never mistaken for an added one (catches attgC028,
// whose `ref="car"` injects foreign attributes with no self-reference).
let baseNames = Set(RedefineNode.children(base, named: "attribute").compactMap { RedefineNode.attribute($0, "name") })
let baseHasReference = RedefineNode.elementChildren(base).contains { RedefineNode.localName($0) == "attributeGroup" }
if !baseHasReference, !hasReference {
// A `use="prohibited"` attribute forbids the name rather than permitting it,
// so declaring one the base lacks does not widen the usable set; like the
// re-introduce and fixed-value checks, it is left alone.
for attrName in redefined.keys.sorted() where !baseNames.contains(attrName) && use(attrName) != "prohibited" {
errors.append("a redefined attribute group '\(name)' may not add the attribute '\(attrName)'")
}
if !baseHasReference, !baseHasWildcard {
errors += addedAttributeErrors(name: name, redefined: redefined, baseNames: baseNames, referenced: referenced, use: use)
}
for attribute in RedefineNode.children(base, named: "attribute") {
guard let attrName = RedefineNode.attribute(attribute, "name") else { continue }
@ -162,6 +206,30 @@ extension PureXML.Schema.XSDParser {
return errors
}
/// The "may not ADD an attribute the original lacks" errors. The redefinition's
/// full attribute set is its direct (non-prohibited) declarations plus the names a
/// non-self reference contributes (`referenced.names`, already non-prohibited). A
/// `use="prohibited"` direct attribute forbids rather than widens, so it is left
/// alone. The check fires only when both sets are fully known and admit no wildcard:
/// the original has no nested reference and no wildcard, and the redefinition has a
/// resolved reference set with no self-reference (a self-reference re-imports the
/// original and is governed by the restriction rules, not counted as an addition).
private static func addedAttributeErrors(
name: String,
redefined: [String: XSDTree],
baseNames: Set<String>,
referenced: (names: Set<String>, hasSelfReference: Bool)?,
use: (String) -> String?,
) -> [String] {
guard let referenced, !referenced.hasSelfReference else { return [] }
var effective = referenced.names
for attrName in redefined.keys where use(attrName) != "prohibited" {
effective.insert(attrName)
}
return effective.sorted().filter { !baseNames.contains($0) }
.map { "a redefined attribute group '\(name)' may not add the attribute '\($0)'" }
}
/// A base attribute with a `fixed` value is relaxed when the redefinition declares
/// a matching, non-prohibited attribute whose `fixed` value differs (or is absent).
/// Prohibiting or omitting the attribute is not relaxation, so it is left alone.

View File

@ -88,6 +88,45 @@ struct SchemaRedefineAttributeGroupTests {
)
}
@Test("a non-self reference injecting a foreign attribute is rejected (attgC028)")
func test_nonSelfReferenceAddRejected() throws {
let main = "<xs:schema xmlns:xs='http://www.w3.org/2001/XMLSchema'>"
+ "<xs:redefine schemaLocation='b.xsd'><xs:attributeGroup name='g'>"
+ "<xs:attributeGroup ref='car'/></xs:attributeGroup></xs:redefine>"
+ "<xs:attributeGroup name='car'><xs:attribute name='foo1' type='xs:int'/>"
+ "<xs:attribute name='foo2' type='xs:string'/></xs:attributeGroup>"
+ "<xs:element name='e'/></xs:schema>"
let baseDoc = "<xs:schema xmlns:xs='http://www.w3.org/2001/XMLSchema'>"
+ "<xs:attributeGroup name='g'><xs:attribute name='att' type='xs:int'/></xs:attributeGroup></xs:schema>"
#expect(throws: (any Error).self) { try PureXML.Schema.Document(main, schemaLoader: { _ in baseDoc }) }
}
@Test("a non-self reference whose attributes are all in the original is valid")
func test_nonSelfReferenceSubsetAccepted() throws {
let main = "<xs:schema xmlns:xs='http://www.w3.org/2001/XMLSchema'>"
+ "<xs:redefine schemaLocation='b.xsd'><xs:attributeGroup name='g'>"
+ "<xs:attributeGroup ref='sub'/></xs:attributeGroup></xs:redefine>"
+ "<xs:attributeGroup name='sub'><xs:attribute name='att' type='xs:int'/></xs:attributeGroup>"
+ "<xs:element name='e'/></xs:schema>"
let baseDoc = "<xs:schema xmlns:xs='http://www.w3.org/2001/XMLSchema'>"
+ "<xs:attributeGroup name='g'><xs:attribute name='att' type='xs:int'/>"
+ "<xs:attribute name='att2' type='xs:string'/></xs:attributeGroup></xs:schema>"
_ = try PureXML.Schema.Document(main, schemaLoader: { _ in baseDoc })
}
@Test("a referenced group with an attribute wildcard is not judged (lenient, no false positive)")
func test_nonSelfReferenceWildcardLenient() throws {
let main = "<xs:schema xmlns:xs='http://www.w3.org/2001/XMLSchema'>"
+ "<xs:redefine schemaLocation='b.xsd'><xs:attributeGroup name='g'>"
+ "<xs:attributeGroup ref='car'/></xs:attributeGroup></xs:redefine>"
+ "<xs:attributeGroup name='car'><xs:attribute name='foo1' type='xs:int'/>"
+ "<xs:anyAttribute/></xs:attributeGroup>"
+ "<xs:element name='e'/></xs:schema>"
let baseDoc = "<xs:schema xmlns:xs='http://www.w3.org/2001/XMLSchema'>"
+ "<xs:attributeGroup name='g'><xs:attribute name='att' type='xs:int'/></xs:attributeGroup></xs:schema>"
_ = try PureXML.Schema.Document(main, schemaLoader: { _ in baseDoc })
}
@Test("re-declaring an attribute the base inherits via a reference is valid")
func test_redeclareInheritedAccepted() throws {
let main = "<xs:schema xmlns:xs='http://www.w3.org/2001/XMLSchema'>"

View File

@ -146,9 +146,9 @@ struct XSTSSuiteTests {
/// model-group occurrence, identity-constraint content, derivation base kind, attribute/simple-type,
/// composition, simpleContent inline-type, complexContent mixedness, and substitution-group anySimpleType checks.
/// src-resolve (#185) 43->39; xsi:Not-Allowed (#183) 39->37; NameAndTypeOK restriction-only + cos-all-limited group-ref (#158) 37->35.
/// UPA `##other` 35->31; UPA effective-extension model 31->29; ref to XSD ns undeclared 29->27; unprefixed type-ref to target ns undeclared 27->25; valid-rejected 0.
/// UPA `##other` 35->31; UPA ext-model 31->29; ref-to-XSD-ns 29->27; unprefixed type-ref 27->25; redefine attrGroup non-self-ref add (attgC028) 25->24; valid-rejected 0.
private let knownSchemaValidRejected = 0
private let knownSchemaInvalidAccepted = 25
private let knownSchemaInvalidAccepted = 24
private let knownInstanceValidRejected = 0
/// Instance bucket (133 -> 26), per-step deltas in CHANGELOG.md: xsi:type must derive from the
/// declared type (complex/atomic/list/union via the element-ref chain); anyType cannot stand in