Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
114 changes: 85 additions & 29 deletions ARCHITECTURE.md

Large diffs are not rendered by default.

11 changes: 10 additions & 1 deletion Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ fuzz-smoke:
go test -run '^$$' -fuzz='^FuzzValidateNeverPanics$$' -fuzztime=10s ./internal/validate
go test -run '^$$' -fuzz='^FuzzReferencePartsRoundTrip$$' -fuzztime=10s ./internal/uriref
go test -run '^$$' -fuzz='^FuzzResolveKeepsInheritedComponents$$' -fuzztime=10s ./internal/uriref
go test -run '^$$' -fuzz='^FuzzResolveAdmittedFailsOnlyOpaqueBase$$' -fuzztime=10s ./internal/uriref
go test -run '^$$' -fuzz='^FuzzXSDRegexSyntax$$' -fuzztime=10s ./internal/xsdregex

.PHONY: bench
Expand Down Expand Up @@ -108,9 +109,17 @@ lint-config: $(BIN)/golangci-lint
$(BIN)/golangci-lint config verify

.PHONY: lint
lint: lint-config lint-workflows
lint: lint-config lint-workflows lint-test-only-code
$(BIN)/golangci-lint run

# Unexported production code reached only by tests is unused once tests are
# excluded. The host build cannot see cmd/wasmxsd's js/wasm callers, so that
# package is checked by the js/wasm pass.
.PHONY: lint-test-only-code
lint-test-only-code: $(BIN)/golangci-lint
$(BIN)/golangci-lint run --tests=false --enable-only unused $(shell go list -f '{{.Dir}}' ./... | grep -v '/cmd/wasmxsd$$' | sed 's|^$(CURDIR)|.|')
GOOS=js GOARCH=wasm $(BIN)/golangci-lint run --tests=false --enable-only unused ./...

.PHONY: lint-workflows
lint-workflows:
uvx zizmor@$(ZIZMOR_VERSION) --offline .github/workflows
Expand Down
60 changes: 60 additions & 0 deletions attribute_name_diagnostic_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
package xsd_test

import (
"strings"
"testing"

"github.com/jacoelho/xsd"
"github.com/jacoelho/xsd/xsderrors"
)

func TestQualifiedAttributeDiagnosticsNameExpandedName(t *testing.T) {
t.Parallel()
const body = `<xs:element name="r"><xs:complexType>
<xs:attribute name="x" type="xs:string" fixed="F"/>
<xs:attribute name="y" type="xs:int"/>
<xs:attribute name="z" type="xs:string" use="required"/>
<xs:attribute name="w" type="xs:int"/>
</xs:complexType></xs:element>`
for _, tt := range []struct {
name string
schema string
doc string
want [3]string
}{
{
name: "qualified",
schema: `<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" targetNamespace="urn:a" elementFormDefault="qualified" attributeFormDefault="qualified">` + body + `</xs:schema>`,
doc: `<a:r xmlns:a="urn:a" a:x="G" a:y="notint" a:w="1"/>`,
want: [3]string{`"{urn:a}x"`, `"{urn:a}y"`, `"{urn:a}z"`},
},
{
name: "unqualified",
schema: `<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">` + body + `</xs:schema>`,
doc: `<r x="G" y="notint" w="1"/>`,
want: [3]string{`"x"`, `"y"`, `"z"`},
},
} {
t.Run(tt.name, func(t *testing.T) {
t.Parallel()
engine, err := xsd.Compile(xsd.Bytes("names.xsd", []byte(tt.schema)))
if err != nil {
t.Fatal(err)
}
err = engine.ValidateWithOptions(strings.NewReader(tt.doc), xsd.ValidateOptions{MaxErrors: 10})
leaves := xsderrors.Flatten(err)
if len(leaves) != 3 {
t.Fatalf("got %d diagnostics, want 3: %v", len(leaves), err)
}
for i, marker := range []string{"expected fixed value", "invalid attribute", "missing required attribute"} {
msg := leaves[i].Error()
if !strings.Contains(msg, marker) || !strings.Contains(msg, tt.want[i]) {
t.Errorf("diagnostic %d = %q, want %q naming %s", i, msg, marker, tt.want[i])
}
if tt.name == "qualified" && strings.Contains(msg, `"`+"xyz"[i:i+1]+`"`) {
t.Errorf("diagnostic %d names a bare local name: %q", i, msg)
}
}
})
}
}
63 changes: 29 additions & 34 deletions compile.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,66 +17,61 @@ type Engine struct {
// CompileOptions controls schema compilation resource limits.
type CompileOptions struct {
// MaxSchemaDepth caps nested schema XML elements. Zero uses the default.
// See docs/RESOURCE_LIMITS.md#compilation.
MaxSchemaDepth int
// MaxSchemaAttributes caps attributes on one schema XML element. Zero uses the default.
// See docs/RESOURCE_LIMITS.md#compilation.
MaxSchemaAttributes int
// MaxSchemaTokenBytes caps the bytes the schema XML reader holds for one
// token (names, attribute values, PI and text payload, construction
// scratch), measured lexically, and the character data accumulated in
// one element across text tokens. It also scales literal evaluation
// work. Zero uses the default.
// MaxSchemaTokenBytes caps the bytes held for one schema token and the text accumulated in one element. Zero uses the default.
// See docs/RESOURCE_LIMITS.md#compilation.
MaxSchemaTokenBytes int64
// MaxSchemaSourceBytes caps bytes read from each schema source. Zero uses the default.
// See docs/RESOURCE_LIMITS.md#compilation.
MaxSchemaSourceBytes int64
// MaxSchemaSources caps the explicit sources passed to one compilation and,
// separately, the distinct schema documents it loads, explicit and
// resolver-loaded together. An unavailable include/import target loads
// nothing and is not counted. Zero uses the default.
// MaxSchemaSources caps the explicit sources and the distinct schema documents of one compilation. Zero uses the default.
// See docs/RESOURCE_LIMITS.md#compilation.
MaxSchemaSources int
// MaxSchemaTotalBytes caps aggregate bytes read from schema sources. An opener
// source reached again is read and charged again; a file source is read
// once; an in-memory source is compared by digest without charge. Zero uses the default.
// MaxSchemaTotalBytes caps aggregate bytes read from schema sources. Zero uses the default.
// See docs/RESOURCE_LIMITS.md#compilation.
MaxSchemaTotalBytes int64
// MaxSchemaReferences caps include/import references processed during compilation. Zero uses the default.
// See docs/RESOURCE_LIMITS.md#compilation.
MaxSchemaReferences int
// MaxSchemaDependencySteps caps aggregate schema-graph expansion, target-context
// propagation, component-dependency resolution and retained derived records
// (content-model particles and models, compiled content-model tables,
// attribute uses, wildcard namespaces). Zero uses the default.
// MaxSchemaDependencySteps caps aggregate schema-graph expansion and dependency-resolution work. Zero uses the default.
// See docs/RESOURCE_LIMITS.md#compilation.
MaxSchemaDependencySteps int
// MaxSchemaTargetContexts caps distinct source/effective-target-namespace contexts,
// including primary and chameleon-derived contexts. Zero uses the default.
// MaxSchemaTargetContexts caps distinct source/effective-target-namespace contexts. Zero uses the default.
// See docs/RESOURCE_LIMITS.md#compilation.
MaxSchemaTargetContexts int
// MaxSchemaInstantiatedNodes caps aggregate schema node occurrences across effective target contexts. Zero uses the default.
// See docs/RESOURCE_LIMITS.md#compilation.
MaxSchemaInstantiatedNodes int
// MaxSchemaNames caps interned schema names, including built-ins. Zero means no explicit limit.
// MaxSchemaNames caps interned schema names. Zero means no explicit limit.
// See docs/RESOURCE_LIMITS.md#compilation.
MaxSchemaNames int
// MaxFiniteOccurs caps finite maxOccurs values. Zero uses the uint32 runtime cap.
// See docs/RESOURCE_LIMITS.md#compilation.
MaxFiniteOccurs uint64
// MaxContentModelStates caps compiled content-model DFA states. Zero uses the default.
// See docs/RESOURCE_LIMITS.md#compilation.
MaxContentModelStates int
// MaxContentModelAnalysisSteps caps content-model traversal, determinization, and ambiguity-analysis work. Zero uses the default.
// MaxContentModelAnalysisSteps caps content-model traversal, determinization and ambiguity-analysis work. Zero uses the default.
// See docs/RESOURCE_LIMITS.md#compilation.
MaxContentModelAnalysisSteps int
// MaxSubstitutionClosureEntries caps aggregate transitive substitution-group relationships. Zero uses the default.
// See docs/RESOURCE_LIMITS.md#compilation.
MaxSubstitutionClosureEntries int
// MaxSimpleUnionMemberEntries caps aggregate flattened simple-union members. Zero uses the default.
// See docs/RESOURCE_LIMITS.md#compilation.
MaxSimpleUnionMemberEntries int
// MaxSchemaPatternWork caps regular-expression matching work for one schema
// literal (enumeration, bound, fixed or default value), across all pattern
// facets, list items and union members. Units are defined in
// docs/RESOURCE_LIMITS.md (Pattern matching cost). Zero uses the finite
// default.
// MaxSchemaPatternWork caps regular-expression matching work for one schema literal. Zero uses the finite default.
// See docs/RESOURCE_LIMITS.md#compilation.
MaxSchemaPatternWork uint64
// MaxSchemaTotalPatternWork caps regular-expression matching work summed
// over every schema-literal evaluation of one compilation; a facet literal
// may be charged for both its base-type check and facet compilation; units are in
// docs/RESOURCE_LIMITS.md (Pattern matching cost). Zero uses the default.
// MaxSchemaTotalPatternWork caps regular-expression matching work summed over one compilation. Zero uses the default.
// See docs/RESOURCE_LIMITS.md#compilation.
MaxSchemaTotalPatternWork uint64
// MaxSchemaPatternRetainedBytes caps the estimated memory retained by
// compiled regular expressions, summed over the distinct pattern facets of
// one compilation; identical pattern text is compiled and charged once.
// The estimate is defined in docs/RESOURCE_LIMITS.md. Each pattern is
// separately limited by fixed per-pattern bounds. Zero uses the default.
// MaxSchemaPatternRetainedBytes caps the estimated memory retained by compiled regular expressions. Zero uses the default.
// See docs/RESOURCE_LIMITS.md#compilation.
MaxSchemaPatternRetainedBytes int64
}

Expand Down
24 changes: 18 additions & 6 deletions docs/RESOURCE_LIMITS.md
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ func compileWithLimits(schema []byte) (*xsd.Engine, error) {
| `MaxContentModelAnalysisSteps` | `16_777_216` | Max content-model traversal, determinization, and ambiguity-analysis work. Comparing two wildcard namespace lists, for ambiguity or for a wildcard restriction, costs one step per namespace looked up. |
| `MaxSubstitutionClosureEntries` | `1_000_000` | Max aggregate transitive substitution-group relationships. |
| `MaxSimpleUnionMemberEntries` | `1_000_000` | Max aggregate flattened simple-union members. |
| `MaxSchemaPatternWork` | `536_870_912` | Max regular-expression matching work for one schema literal (enumeration, bound, fixed or default value). Same unit as `MaxInstancePatternWork`. Unsigned. |
| `MaxSchemaPatternWork` | `536_870_912` | Max regular-expression matching work for one schema literal (enumeration, bound, fixed or default value), across all pattern facets, list items and union members. Same unit as `MaxInstancePatternWork`. Unsigned. |
| `MaxSchemaTotalPatternWork` | `8_589_934_592` | Max regular-expression matching work summed over every schema-literal evaluation of one compilation. A facet literal can be charged for its base-type check and again for facet compilation; a fixed/default value is charged once. Same unit. |
| `MaxSchemaPatternRetainedBytes` | `64 MiB` | Max estimated memory retained by compiled regular expressions, summed over the distinct pattern facets of one compilation. Identical pattern text is compiled and charged once. |

Expand Down Expand Up @@ -225,6 +225,14 @@ same whatever facets it has. Both are still compiled and
checked first, so their patterns and facet literals charge the pattern,
storage, type-count and work limits as a reached type's do.

A restriction that declares a bound, enumeration or pattern retains a copy of
its base's entries on that side, and the copy is charged to the value storage
budget derived from `MaxSchemaTotalBytes` and `MaxSchemaInstantiatedNodes`. A
restriction that adds nothing on a side shares its base's entries. A long
restriction chain in which each step adds a bound therefore retains memory
quadratic in its depth; exceeding the budget reports `schema.limit` naming
both options.

Each pattern is compiled under fixed structural bounds that are not options:
source 1 MiB, 100,000 AST nodes, 100,000 NFA states (counted repeats expand
into states), 1,000,000 retained character ranges, and nesting depth 1,024.
Expand All @@ -235,9 +243,13 @@ aggregate over a compilation.
The retained-bytes estimate of one pattern is 256 bytes of fixed overhead plus
the source length, plus 8 bytes per character range (each distinct range array
counted once, by capacity), plus, for a run-length pattern, 48 bytes per atom
and the literal text, or, for an NFA pattern, 48 bytes per state, 24 bytes per
precomputed closure, 8 bytes per closure element and 8 bytes per closure
bitset word. The default is a byte target, not a multiple of the per-pattern
and the literal text, or, for an NFA pattern, 48 bytes per state plus, for the
mode that retains them, 8 bytes per scalar successor (deterministic patterns of
at most 64 states) or 8 bytes per closure bitset word (other patterns of at
most 64 states); larger NFAs retain neither. Every retained array is charged by
capacity, not length, which raises the estimate by the arrays' append slack:
about 22% for a large NFA, and up to about 70% for a small one. A pattern set near the `MaxSchemaPatternRetainedBytes` default that
compiles today can fail with `schema.limit`. The default is a byte target, not a multiple of the per-pattern
caps: 64 MiB admits about 5 patterns at the per-pattern caps (about 13 MB each)
and about 10,000 Unicode-category patterns of the `[\p{L}\p{N} ]` class. The
largest aggregate observed across the W3C and project corpora under default
Expand All @@ -259,10 +271,10 @@ func validateWithLimits(engine *xsd.Engine, doc io.Reader) error {

| Option | Default | Meaning |
| --- | ---: | --- |
| `MaxErrors` | `100` | Max collected recoverable validation errors. |
| `MaxErrors` | `100` | Max collected recoverable validation errors. Once reached, validation stops semantic assessment but continues reading XML until a fatal error or the document end; a later fatal error takes precedence. |
| `MaxIdentityScopes` | `10_000` | Max active identity-constraint scopes. |
| `MaxIdentityEntries` | `100_000` | Independent max for stored ID, IDREF, key, unique, and keyref entries, pending identity-selector matches, and pending identity-field values. |
| `MaxIdentityTupleBytes` | `4 KiB` | Max byte length of one stored identity key. |
| `MaxIdentityTupleBytes` | `4 KiB` | Max canonical text bytes of one ID or IDREF value or one key/unique/keyref tuple: the sum of each field's canonical value length plus one byte between fields. This measures values, not stored bytes; stored keys add per-field framing. |
| `MaxInstanceDepth` | `256` | Max nested XML elements. |
| `MaxInstanceAttributes` | `4_096` | Max attributes on one XML element. |
| `MaxInstanceTextBytes` | `4 MiB` | Max retained character data bytes. |
Expand Down
41 changes: 37 additions & 4 deletions docs/spec/INTERPRETATIONS.md
Original file line number Diff line number Diff line change
Expand Up @@ -434,9 +434,12 @@ pattern, and a substitution-group member whose type is a member of the head's
restricted union; Xerces-J and libxml2 do the same for a restricted union
nested in another union. xmlschema loses the constraint under a facet-free restriction of
a restricted union. .NET rejects a union whose member is a restricted union.
Cases: `project/corrections-restricted-union-nested`,
`project/corrections-restricted-union-xsi` and
`project/corrections-union-substitution-bad-member`.
libxml2 also rejects an `xsi:type` member of a facet-free union on an element
typed by a facet-free restriction of that union. Cases:
`project/corrections-restricted-union-nested`,
`project/corrections-restricted-union-xsi`,
`project/corrections-union-substitution-bad-member` and
`project/datatypes/unions/restricted-union-xsi-type-member`.

## I-011 — regex metacharacter grammar

Expand Down Expand Up @@ -1960,8 +1963,13 @@ Observed: Xerces-J 2.12.2 evaluates selector `.//.` as the context element
alone, missing every descendant row, and counts a node reached through several
field branches as several matches. libxml2 2.9.13 omits the context element
from `.//.`. .NET 10.0.14 and xmlschema 4.3.2 follow the XPath meaning.
Xerces-J also accepts a field `@a|@b` that selects two attributes of one
element, whether or not either attribute has a fixed value, although clause 3
asks for exactly one member; the other three reject it.

Cases: `project/identity/field-union-nodes/overlap`,
Cases: `project/identity/fixed-value-field/declared-attribute`,
`project/identity/fixed-value-field/wildcard-attribute`,
`project/identity/field-union-nodes/overlap`,
`project/identity/selector-self-descendant-scopes` and
`project/identity/selector-self-descendant-union-single-selection`.

Expand Down Expand Up @@ -3078,3 +3086,28 @@ xmlschema differ. The controls `required-empty-choice-after-overlap`,
`optional-empty-choice-before-overlap`, `zero-occurrence-before-overlap`
(libxml2 differs) and `reachable-overlap` are invalid, and
`required-empty-choice-before-element` is valid.

## I-053 — a reference the built-in backend cannot represent is an unavailable hint

**Status:** decided by the specification text, the first rank of the
[processor tie-break](#processor-tie-break).

A `schemaLocation` or `xml:base` that is a valid anyURI after XLink escaping,
but names no document the built-in backend can identify, makes the referenced
document unavailable, and the schema compiles without it. The
[import](https://www.w3.org/TR/2004/REC-xmlschema-1-20041028/structures.html#src-import)
and include `schemaLocation` is only a hint, so a location that names no
reachable document is not a schema error. `http://h:abc/x.xsd` and
`http://a%41b/x.xsd` are not rejected by the anyURI lexical space, which
`uriref` implements, so the built-in backend adds no URI error class of its
own. A custom resolver still receives the raw reference.

Xerces-J 2.12.2 and xmlschema 4.3.2 report these references as blocked
acquisitions, as the oracle image has no network. .NET 10.0.14 rejects
`http://h:abc/x.xsd` and `http://a%41b/x.xsd` as invalid URIs, and libxml2
2.9.13 rejects `http://h:abc/x.xsd` as not a valid value of the `anyURI`
type.

Cases: `project/composition/import-location-invalid-port`,
`project/composition/import-location-escaped-host` and
`project/composition/import-xml-base-invalid-port` (schemas valid).
41 changes: 41 additions & 0 deletions doctype_position_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
package xsd_test

import (
"errors"
"strings"
"testing"

"github.com/jacoelho/xsd"
"github.com/jacoelho/xsd/xsderrors"
)

func TestDOCTYPERejectedAtDeclarationStart(t *testing.T) {
const schema = `<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"><xs:element name="r" type="xs:string"/></xs:schema>`
engine, err := xsd.Compile(xsd.Bytes("s.xsd", []byte(schema)))
if err != nil {
t.Fatal(err)
}
for _, test := range []struct {
name string
doc string
line, column int
}{
{"before the root", "\n<?p x?><!DOCTYPE r><r/>", 2, 8},
{"after the root", "<r/><!DOCTYPE r>", 1, 5},
{"inside content", "<r>\n <!DOCTYPE r></r>", 2, 3},
} {
t.Run(test.name, func(t *testing.T) {
err := engine.Validate(strings.NewReader(test.doc))
diagnostic, ok := errors.AsType[*xsderrors.Error](err)
if !ok {
t.Fatalf("error = %T %v, want structured error", err, err)
}
if diagnostic.Code() != xsderrors.CodeUnsupportedDTD {
t.Fatalf("code = %v, want unsupported.dtd", diagnostic.Code())
}
if diagnostic.Line() != test.line || diagnostic.Column() != test.column {
t.Errorf("location = %d:%d, want %d:%d", diagnostic.Line(), diagnostic.Column(), test.line, test.column)
}
})
}
}
Loading