From 31306df2990ecbf6860c6f5f38a8e89d7d4ce8c7 Mon Sep 17 00:00:00 2001 From: quobix Date: Wed, 25 Nov 2026 11:56:59 -0500 Subject: [PATCH 01/27] Load standalone Draft 2020-12 schema resources with authored origins --- datamodel/schema_node.go | 85 +++++++++ datamodel/spec_info.go | 5 +- index/spec_index_build.go | 12 ++ jsonschema/document.go | 393 ++++++++++++++++++++++++++++++++++++++ jsonschema/loader_test.go | 31 +++ jsonschema/reference.go | 163 ++++++++++++++++ 6 files changed, 688 insertions(+), 1 deletion(-) create mode 100644 datamodel/schema_node.go create mode 100644 jsonschema/document.go create mode 100644 jsonschema/loader_test.go create mode 100644 jsonschema/reference.go diff --git a/datamodel/schema_node.go b/datamodel/schema_node.go new file mode 100644 index 00000000..5c934bb4 --- /dev/null +++ b/datamodel/schema_node.go @@ -0,0 +1,85 @@ +// Copyright 2026 Princess B33f Heavy Industries / Dave Shanley +// SPDX-License-Identifier: MIT + +package datamodel + +import ( + "bytes" + "encoding/json" + "errors" + "fmt" + "io" + + "github.com/pb33f/go-yaml" + "github.com/pb33f/libopenapi/internal/jsonnode" +) + +// DecodeSchemaNode reads one JSON or YAML schema and preserves authored positions. +func DecodeSchemaNode(data []byte) (*yaml.Node, error) { + var doc *yaml.Node + if json.Valid(data) { + normalized := normalizeJSONForYAMLParser(data) + var node yaml.Node + if err := jsonnode.Unmarshal(normalized, &node); err != nil { + return nil, err + } + doc = &node + } else { + decoder := yaml.NewDecoder(bytes.NewReader(data)) + doc = new(yaml.Node) + if err := decoder.Decode(doc); err != nil { + return nil, fmt.Errorf("invalid schema document: %w", err) + } + var extra yaml.Node + if err := decoder.Decode(&extra); !errors.Is(err, io.EOF) { + if err != nil { + return nil, err + } + return nil, fmt.Errorf("expected one schema document") + } + } + if len(doc.Content) != 1 { + return nil, fmt.Errorf("missing schema root") + } + if err := checkSchemaKeys(doc); err != nil { + return nil, err + } + return doc, nil +} + +// Check keys in linear time on wide property maps. Every YAML mapping in a JSON +// document, including objects inside examples, has unique string keys. +func checkSchemaKeys(n *yaml.Node) error { + switch n.Kind { + case yaml.MappingNode: + seen := make(map[string]int, len(n.Content)/2) + for i := 0; i < len(n.Content); i += 2 { + key := n.Content[i] + if key.Kind != yaml.ScalarNode || key.Tag != "!!str" { + return fmt.Errorf("line %d: JSON object keys must be strings", key.Line) + } + if line, ok := seen[key.Value]; ok { + return fmt.Errorf("line %d: mapping key %q already defined at line %d", key.Line, key.Value, line) + } + seen[key.Value] = key.Line + if err := checkSchemaKeys(n.Content[i+1]); err != nil { + return err + } + } + case yaml.DocumentNode, yaml.SequenceNode: + for _, child := range n.Content { + if err := checkSchemaKeys(child); err != nil { + return err + } + } + case yaml.ScalarNode: + switch n.Tag { + case "!!str", "!!bool", "!!int", "!!float", "!!null": + default: + return fmt.Errorf("line %d: unsupported JSON scalar %s", n.Line, n.Tag) + } + default: + return fmt.Errorf("line %d: expected JSON-compatible YAML", n.Line) + } + return nil +} diff --git a/datamodel/spec_info.go b/datamodel/spec_info.go index 1a8a569b..0eb6f872 100644 --- a/datamodel/spec_info.go +++ b/datamodel/spec_info.go @@ -24,6 +24,9 @@ const ( YAMLFileType = "yaml" ) +// ErrUnsupportedSpecType indicates a well-formed document with no API version marker. +var ErrUnsupportedSpecType = errors.New("spec type not supported by libopenapi, sorry") + // SpecInfo represents a 'ready-to-process' OpenAPI Document. The RootNode is the most important property // used by the library, this contains the top of the document tree that every single low model is based off. type SpecInfo struct { @@ -382,7 +385,7 @@ func extractSpecInfoInternal(spec []byte, bypass bool, skipJSON bool) (*SpecInfo return nil, err } } - specInfo.Error = errors.New("spec type not supported by libopenapi, sorry") + specInfo.Error = ErrUnsupportedSpecType return specInfo, specInfo.Error } } diff --git a/index/spec_index_build.go b/index/spec_index_build.go index 5ea45afe..f0a94d84 100644 --- a/index/spec_index_build.go +++ b/index/spec_index_build.go @@ -47,6 +47,18 @@ func NewSpecIndexWithConfig(rootNode *yaml.Node, config *SpecIndexConfig) *SpecI return NewSpecIndexWithConfigAndContext(context.Background(), rootNode, config) } +// NewSchemaIndex retains a standalone schema source. Its loader registers only +// schema-bearing positions, since arbitrary instance data can also contain $ref. +func NewSchemaIndex(rootNode *yaml.Node, config *SpecIndexConfig) *SpecIndex { + idx := NewSpecIndexWithConfig(nil, config) + idx.root = rootNode + if rootNode != nil && len(rootNode.Content) > 0 { + idx.nodeMapCompleted = make(chan struct{}) + idx.MapNodes(rootNode) + } + return idx +} + // NewSpecIndex creates a new SpecIndex with default configuration from the given root YAML node. func NewSpecIndex(rootNode *yaml.Node) *SpecIndex { index := new(SpecIndex) diff --git a/jsonschema/document.go b/jsonschema/document.go new file mode 100644 index 00000000..0105bfc7 --- /dev/null +++ b/jsonschema/document.go @@ -0,0 +1,393 @@ +// Copyright 2026 Princess B33f Heavy Industries / Dave Shanley +// SPDX-License-Identifier: MIT + +// Package jsonschema loads and compares authored Draft 2020-12 schema resources. +package jsonschema + +import ( + "crypto/sha256" + "encoding/json" + "errors" + "fmt" + "net/url" + "path" + "path/filepath" + "strconv" + "strings" + + "github.com/pb33f/go-yaml" + "github.com/pb33f/libopenapi/datamodel" + "github.com/pb33f/libopenapi/index" +) + +// Dialect is the supported JSON Schema dialect. +const Dialect = "https://json-schema.org/draft/2020-12/schema" + +// ErrNotSchema identifies an input without a supported standalone schema declaration. +var ErrNotSchema = errors.New("expected a Draft 2020-12 JSON Schema declaration (use --schema for an unmarked schema)") + +// Source holds the physical document once, even when several resources share it. +type Source struct { + relative string + Name string + Data []byte + Node *yaml.Node + Index *index.SpecIndex +} + +// Resource is a root schema or an embedded schema with its own base URI. +type Resource struct { + base *url.URL + ID string + Pointer string + Source *Source + Node *yaml.Node +} + +// Label returns the authored title or a name derived from the resource. +func (r *Resource) Label() string { + if n := member(r.Node, "title"); n != nil && n.Value != "" { + return n.Value + } + if name := path.Base(r.ID); name != "." && name != "/" && name != "" { + return name + } + return "Schema" +} + +// Reference connects an authored reference site to a schema in this snapshot. +type Reference struct { + From, To *yaml.Node + Value string + address string +} + +// Document owns the resources and source locations for a comparison input. +type Document struct { + Root *Resource + Resources []*Resource + Sources map[string]*Source + References []Reference + Rolodex *index.Rolodex + addresses map[string]*yaml.Node + schemas map[*yaml.Node]*Resource + config *datamodel.DocumentConfiguration + base *url.URL +} + +// Load reads one root and all its referenced resources using the supplied source configuration. +// Explicit mode accepts unmarked object and boolean schemas. +func Load(data []byte, source string, config *datamodel.DocumentConfiguration, explicit bool) (*Document, error) { + if config == nil { + config = datamodel.NewDocumentConfiguration() + } + uri, err := retrievalURI(source, config) + if err != nil { + return nil, err + } + doc := newDocument(config, uri.ResolveReference(&url.URL{Path: "."})) + root, err := doc.addSource(data, uri, explicit) + if err == nil { + doc.Root = root + err = doc.resolveReferences() + } + if err != nil { + doc.Release() + return nil, err + } + return doc, nil +} + +func newDocument(config *datamodel.DocumentConfiguration, base *url.URL) *Document { + return &Document{config: config, base: base, Sources: make(map[string]*Source), addresses: make(map[string]*yaml.Node), schemas: make(map[*yaml.Node]*Resource), Rolodex: index.NewRolodex(index.CreateClosedAPIIndexConfig())} +} + +// IsSchema reports whether a node occupies a schema-bearing position in this input. +func (d *Document) IsSchema(node *yaml.Node) bool { return d != nil && d.schemas[node] != nil } + +// Release frees the indexes and drops references to the retained source buffers. +func (d *Document) Release() { + if d == nil { + return + } + for _, source := range d.Sources { + source.Index.Release() + } + if d.Rolodex != nil { + d.Rolodex.Release() + } + *d = Document{} +} + +func retrievalURI(source string, config *datamodel.DocumentConfiguration) (*url.URL, error) { + if config.SpecFilePath != "" { + source = config.SpecFilePath + } + if source == "" { + source = "schema.yaml" + } + original, err := url.Parse(source) + if config.BaseURL != nil { + base := *config.BaseURL + base.Path = strings.TrimSuffix(base.Path, "/") + "/" + filename := filepath.Base(source) + if err == nil && original.IsAbs() { + filename = path.Base(original.Path) + } + return base.ResolveReference(&url.URL{Path: filename}), nil + } + if err == nil && (original.Scheme == "http" || original.Scheme == "https") { + return original, nil + } + if !filepath.IsAbs(source) { + source = filepath.Join(config.BasePath, source) + } + file, err := filepath.Abs(source) + return &url.URL{Scheme: "file", Path: filepath.ToSlash(file)}, err +} + +func (d *Document) resourceID(uri *url.URL) string { + if uri.Scheme == "file" && d.base.Scheme == "file" { + if relative, err := filepath.Rel(d.base.Path, uri.Path); err == nil { + name := filepath.ToSlash(relative) + if uri.RawQuery != "" { + name += "?" + uri.RawQuery + } + return name + } + } + return uri.String() +} + +func (d *Document) sourceName(uri *url.URL) string { + safe := *uri + safe.User = nil + safe.RawQuery = "" + name := d.resourceID(&safe) + if uri.RawQuery != "" || uri.User != nil { + // Signed retrieval URLs must not leak credentials or collide in report source maps. + digest := sha256.Sum256([]byte(uri.String())) + name += fmt.Sprintf(" [%x]", digest[:8]) + } + return name +} + +func (d *Document) addSource(data []byte, uri *url.URL, explicit bool) (*Resource, error) { + doc, err := datamodel.DecodeSchemaNode(data) + if err != nil { + return nil, err + } + root := doc.Content[0] + if !explicit && member(root, "$schema") == nil { + return nil, ErrNotSchema + } + for _, marker := range []string{"openapi", "swagger", "asyncapi"} { + if member(root, marker) != nil { + return nil, fmt.Errorf("conflicting %s version marker in JSON Schema", marker) + } + } + if strings.EqualFold(path.Ext(uri.Path), ".json") && !json.Valid(data) { + return nil, fmt.Errorf("invalid JSON in %s", d.sourceName(uri)) + } + name := d.sourceName(uri) + cfg := index.CreateClosedAPIIndexConfig() + cfg.SpecAbsolutePath, cfg.Rolodex = name, d.Rolodex + idx := index.NewSchemaIndex(doc, cfg) + relative := name + if uri.Scheme != "file" && uri.Scheme == d.base.Scheme && uri.Host == d.base.Host && uri.RawQuery == "" { + if rel, err := filepath.Rel(d.base.Path, uri.Path); err == nil { + relative = filepath.ToSlash(rel) + } + } + source := &Source{Name: name, relative: relative, Data: data, Node: root, Index: idx} + d.Sources[name] = source + if len(d.Resources) == 0 { + d.Rolodex.SetRootNode(doc) + d.Rolodex.SetRootIndex(idx) + } else { + d.Rolodex.AddIndex(idx) + } + if err = d.indexSchema(source, root, uri, "", nil); err != nil { + return nil, err + } + if err = d.register(uri.String(), root, source); err != nil { + return nil, err + } + return d.schemas[root], nil +} + +func member(node *yaml.Node, key string) *yaml.Node { + if node == nil || node.Kind != yaml.MappingNode { + return nil + } + for i := 0; i+1 < len(node.Content); i += 2 { + if node.Content[i].Value == key { + return node.Content[i+1] + } + } + return nil +} + +func (d *Document) lookup(address string) *yaml.Node { + if resource := d.Rolodex.LookupSchemaById(address); resource != nil { + return resource.SchemaNode + } + return d.addresses[address] +} + +func (d *Document) register(address string, node *yaml.Node, source *Source) error { + if prior := d.lookup(address); prior != nil { + if prior == node { + return nil + } + old := d.schemas[prior] + return fmt.Errorf("duplicate schema address %q at %s:%d and %s:%d", address, old.Source.Name, prior.Line, source.Name, node.Line) + } + d.addresses[address] = node + return nil +} + +func (d *Document) indexSchema(source *Source, node *yaml.Node, base *url.URL, pointer string, r *Resource) error { + if node.Kind != yaml.MappingNode && !(node.Kind == yaml.ScalarNode && node.Tag == "!!bool") { + return fmt.Errorf("%s:%d: schema must be an object or boolean", source.Name, node.Line) + } + if dialect := member(node, "$schema"); dialect != nil && strings.TrimSuffix(dialect.Value, "#") != Dialect { + return fmt.Errorf("%s:%d: unsupported JSON Schema dialect %q", source.Name, dialect.Line, dialect.Value) + } + if vocab := member(node, "$vocabulary"); vocab != nil { + if vocab.Kind != yaml.MappingNode { + return fmt.Errorf("%s:%d: $vocabulary must be an object", source.Name, vocab.Line) + } + for i := 0; i < len(vocab.Content); i += 2 { + key, required := vocab.Content[i], vocab.Content[i+1] + if required.Tag != "!!bool" { + return fmt.Errorf("%s:%d: vocabulary requirement must be boolean", source.Name, required.Line) + } + if !strings.EqualFold(required.Value, "true") { + continue + } + switch strings.TrimPrefix(key.Value, "https://json-schema.org/draft/2020-12/vocab/") { + case "core", "applicator", "unevaluated", "validation", "meta-data", "format-annotation", "content": + if strings.HasPrefix(key.Value, "https://json-schema.org/draft/2020-12/vocab/") { + continue + } + } + return fmt.Errorf("%s:%d: unsupported required vocabulary %q", source.Name, key.Line, key.Value) + } + } + id := member(node, "$id") + if id != nil { + resolved, err := base.Parse(id.Value) + if err != nil || id.Tag != "!!str" || resolved.Fragment != "" { + return fmt.Errorf("%s:%d: invalid schema $id %q", source.Name, id.Line, id.Value) + } + base = resolved + } + if r == nil || id != nil { + identity := source.relative + if id != nil { + identity = d.resourceID(base) + } + r = &Resource{base: base, ID: identity, Pointer: pointer, Source: source, Node: node} + d.Resources = append(d.Resources, r) + if err := d.register(base.String(), node, source); err != nil { + return err + } + if id != nil { + entry := &index.SchemaIdEntry{Id: id.Value, ResolvedUri: base.String(), SchemaNode: node, Index: source.Index, DefinitionPath: "#" + pointer, Line: id.Line, Column: id.Column} + if err := source.Index.RegisterSchemaId(entry); err != nil { + return err + } + if err := d.Rolodex.RegisterGlobalSchemaId(entry); err != nil { + return err + } + delete(d.addresses, base.String()) + } + } + d.schemas[node] = r + for _, key := range []string{"$anchor", "$dynamicAnchor"} { + if value := member(node, key); value != nil { + if value.Tag != "!!str" || !anchorName.MatchString(value.Value) { + return fmt.Errorf("%s:%d: invalid %s %q", source.Name, value.Line, key, value.Value) + } + address := *base + address.Fragment = value.Value + if err := d.register(address.String(), node, source); err != nil { + return err + } + } + } + if value := member(node, "$dynamicRef"); value != nil { + return fmt.Errorf("%s:%d: dynamic scope resolution for $dynamicRef %q is unsupported", source.Name, value.Line, value.Value) + } + if value := member(node, "$ref"); value != nil { + target, err := base.Parse(value.Value) + if value.Tag != "!!str" || err != nil { + return fmt.Errorf("%s:%d: invalid $ref %q", source.Name, value.Line, value.Value) + } + d.References = append(d.References, Reference{From: node, Value: value.Value, address: target.String()}) + } + return children(node, func(keyword, key string, child *yaml.Node) error { + childPointer := pointer + "/" + escapePointer(keyword) + if childKind(keyword) != singleSchema { + childPointer += "/" + escapePointer(key) + } + return d.indexSchema(source, child, base, childPointer, r) + }) +} + +func escapePointer(key string) string { + return strings.ReplaceAll(strings.ReplaceAll(key, "~", "~0"), "/", "~1") +} + +const ( + singleSchema = 1 + schemaMap = 2 + schemaList = 3 +) + +func childKind(keyword string) int { + switch keyword { + case "$defs", "properties", "patternProperties", "dependentSchemas": + return schemaMap + case "prefixItems", "allOf", "anyOf", "oneOf": + return schemaList + case "additionalProperties", "unevaluatedProperties", "propertyNames", "contains", "items", "unevaluatedItems", "not", "if", "then", "else", "contentSchema": + return singleSchema + } + return 0 +} + +func children(node *yaml.Node, visit func(keyword, key string, child *yaml.Node) error) error { + for i := 0; i+1 < len(node.Content); i += 2 { + keyword, value := node.Content[i].Value, node.Content[i+1] + switch childKind(keyword) { + case singleSchema: + if err := visit(keyword, "", value); err != nil { + return err + } + case schemaMap: + if value.Kind != yaml.MappingNode { + return fmt.Errorf("line %d: %s requires an object", value.Line, keyword) + } + for j := 0; j < len(value.Content); j += 2 { + if value.Content[j].Tag != "!!str" { + return fmt.Errorf("line %d: schema keys must be strings", value.Content[j].Line) + } + if err := visit(keyword, value.Content[j].Value, value.Content[j+1]); err != nil { + return err + } + } + case schemaList: + if value.Kind != yaml.SequenceNode { + return fmt.Errorf("line %d: %s requires an array", value.Line, keyword) + } + for j, item := range value.Content { + if err := visit(keyword, strconv.Itoa(j), item); err != nil { + return err + } + } + } + } + return nil +} diff --git a/jsonschema/loader_test.go b/jsonschema/loader_test.go new file mode 100644 index 00000000..2709abf6 --- /dev/null +++ b/jsonschema/loader_test.go @@ -0,0 +1,31 @@ +// Copyright 2026 Princess B33f Heavy Industries / Dave Shanley +// SPDX-License-Identifier: MIT + +package jsonschema + +import ( + "github.com/stretchr/testify/require" + "testing" +) + +func TestLoadInputBoundaries(t *testing.T) { + for _, tc := range []struct { + input string + explicit bool + want string + }{ + {`{"$vocabulary":{"urn:unsupported":true}}`, true, "unsupported required vocabulary"}, + {"{}", false, "--schema"}, {`{"$schema":"https://example.org/app"}`, false, "unsupported"}, + {"null", true, "object or boolean"}, {"type: object\ntype: string", true, "already defined"}, + {`{"openapi":"3.1.0","$schema":"https://json-schema.org/draft/2020-12/schema"}`, true, "conflicting"}, + {`{"$defs":{"a":{"$id":"urn:money"},"b":{"$id":"urn:money"}}}`, true, "duplicate"}, + {`{"$dynamicRef":"#scope"}`, true, "dynamic scope"}, {`{"$ref":"#/missing"}`, true, "no schema"}, + {"true\n---\nfalse", true, "one schema"}, + } { + _, err := Load([]byte(tc.input), "schema.yaml", nil, tc.explicit) + require.ErrorContains(t, err, tc.want) + } + d, err := Load([]byte(`{"$schema":"https://json-schema.org/draft/2020-12/schema","examples":[{"$ref":"missing","$id":"urn:x"},{"$id":"urn:x"}]}`), "schema.json", nil, false) + require.NoError(t, err) + d.Release() +} diff --git a/jsonschema/reference.go b/jsonschema/reference.go new file mode 100644 index 00000000..d64da130 --- /dev/null +++ b/jsonschema/reference.go @@ -0,0 +1,163 @@ +// Copyright 2026 Princess B33f Heavy Industries / Dave Shanley +// SPDX-License-Identifier: MIT + +package jsonschema + +import ( + "errors" + "fmt" + + "io" + "io/fs" + "net/http" + "net/url" + "os" + "path/filepath" + "regexp" + "strconv" + "strings" + "time" + + "github.com/pb33f/go-yaml" +) + +var anchorName = regexp.MustCompile(`^[A-Za-z_][-A-Za-z0-9._]*$`) + +func (d *Document) resolveReferences() error { + for i := 0; i < len(d.References); i++ { + ref := d.References[i] + target, err := d.resolve(ref.address) + if err != nil { + return fmt.Errorf("%s:%d: resolve $ref %q: %w", d.schemas[ref.From].Source.Name, ref.From.Line, ref.Value, err) + } + d.References[i].To = target + } + return nil +} + +func (d *Document) resolve(address string) (*yaml.Node, error) { + if target := d.lookup(address); target != nil { + return target, nil + } + uri, err := url.Parse(address) + if err != nil { + return nil, err + } + fragment := uri.Fragment + uri.Fragment, uri.RawFragment = "", "" + root := d.lookup(uri.String()) + if root == nil { + data, err := d.read(uri) + if err != nil { + return nil, err + } + resource, err := d.addSource(data, uri, true) + if err != nil { + return nil, err + } + if target := d.lookup(address); target != nil { + return target, nil + } + root = resource.Node + } + target := root + if fragment != "" { + if !strings.HasPrefix(fragment, "/") { + canonical := *d.schemas[root].base + canonical.Fragment = fragment + if target := d.lookup(canonical.String()); target != nil { + return target, nil + } + return nil, fmt.Errorf("unknown schema anchor %q", fragment) + } + for part := range strings.SplitSeq(fragment[1:], "/") { + key := strings.ReplaceAll(strings.ReplaceAll(part, "~1", "/"), "~0", "~") + if target.Kind == yaml.SequenceNode { + i, err := strconv.Atoi(key) + if err != nil || i < 0 || i >= len(target.Content) || strconv.Itoa(i) != key { + target = nil + } else { + target = target.Content[i] + } + } else { + target = member(target, key) + } + if target == nil { + break + } + } + } + if d.schemas[target] == nil { + return nil, fmt.Errorf("no schema at %q", address) + } + return target, nil +} + +// Read source bytes without attaching a second API-format index to this Rolodex. +// In particular, a revision filesystem controls all local reads for its snapshot. +func (d *Document) read(uri *url.URL) ([]byte, error) { + switch uri.Scheme { + case "file": + if uri.Host != "" && uri.Host != "localhost" { + return nil, fmt.Errorf("unsupported file URI host %q", uri.Host) + } + if !d.config.AllowFileReferences && d.config.BasePath == "" { + return nil, fmt.Errorf("file references are disabled") + } + filename := filepath.FromSlash(uri.Path) + if d.config.LocalFS == nil { + return os.ReadFile(filename) + } + dir := d.config.BasePath + if dir == "" { + dir = filepath.FromSlash(d.base.Path) + } + relative, err := filepath.Rel(dir, filename) + if err != nil { + return nil, err + } + return readSource(d.config.LocalFS, filepath.ToSlash(relative), filename) + case "http", "https": + if !d.config.AllowRemoteReferences { + return nil, fmt.Errorf("remote references are disabled") + } + if d.config.RemoteFS != nil { + return readSource(d.config.RemoteFS, uri.String(), "") + } + get := d.config.RemoteURLHandler + if get == nil { + get = remoteClient.Get + } + res, err := get(uri.String()) + if err != nil { + return nil, err + } + defer res.Body.Close() + if res.StatusCode < 200 || res.StatusCode >= 300 { + return nil, fmt.Errorf("HTTP %d", res.StatusCode) + } + return io.ReadAll(res.Body) + default: + return nil, fmt.Errorf("no registered schema for %q", d.sourceName(uri)) + } +} + +var remoteClient = &http.Client{Timeout: 120 * time.Second} + +func readSource(files fs.FS, name, absolute string) ([]byte, error) { + file, err := files.Open(name) + if err != nil && absolute != "" && (errors.Is(err, fs.ErrInvalid) || !fs.ValidPath(name)) { + file, err = files.Open(absolute) + } + if err != nil { + return nil, err + } + if file == nil { + return nil, fmt.Errorf("missing file %q", name) + } + defer file.Close() + if source, ok := file.(interface{ GetContent() string }); ok { + return []byte(source.GetContent()), nil + } + return io.ReadAll(file) +} From 02596d61698c95bfea056074585ae9be66af12f5 Mon Sep 17 00:00:00 2001 From: quobix Date: Wed, 25 Nov 2026 11:57:01 -0500 Subject: [PATCH 02/27] Compare authored standalone schema constraints with resource-local paths --- jsonschema/compare.go | 482 +++++++++++++++++++++++++++++ jsonschema/document_test.go | 99 ++++++ what-changed/model/change_types.go | 7 + 3 files changed, 588 insertions(+) create mode 100644 jsonschema/compare.go create mode 100644 jsonschema/document_test.go diff --git a/jsonschema/compare.go b/jsonschema/compare.go new file mode 100644 index 00000000..11c1595d --- /dev/null +++ b/jsonschema/compare.go @@ -0,0 +1,482 @@ +// Copyright 2026 Princess B33f Heavy Industries / Dave Shanley +// SPDX-License-Identifier: MIT + +package jsonschema + +import ( + "cmp" + "context" + "encoding/json" + "fmt" + "math/big" + "slices" + "strconv" + "strings" + + "github.com/pb33f/go-yaml" + "github.com/pb33f/libopenapi/datamodel/low" + "github.com/pb33f/libopenapi/datamodel/low/base" + wc "github.com/pb33f/libopenapi/what-changed/model" +) + +// Compare uses the schema comparator on authored constraints. Each referenced +// resource is compared once, independent of the number of references to it. +func Compare(left, right *Document, rules *wc.BreakingRulesConfig) (*wc.SchemaChanges, error) { + if left == nil || right == nil { + return nil, fmt.Errorf("both JSON Schema inputs are required") + } + c := comparison{left: left, right: right, rules: rules} + if err := c.resources(); err != nil { + return nil, err + } + if len(c.changes) == 0 { + return nil, nil + } + slices.SortStableFunc(c.changes, func(a, b *wc.Change) int { + return cmp.Or(strings.Compare(a.SchemaResource, b.SchemaResource), strings.Compare(a.Path, b.Path), strings.Compare(a.Property, b.Property), cmp.Compare(a.ChangeType, b.ChangeType), strings.Compare(a.Original, b.Original), strings.Compare(a.New, b.New)) + }) + return &wc.SchemaChanges{PropertyChanges: wc.NewPropertyChanges(c.changes)}, nil +} + +type comparison struct { + pairs map[*Resource]*Resource + matched map[*Resource]bool + left, right *Document + rules *wc.BreakingRulesConfig + changes []*wc.Change +} + +func (c *comparison) resources() error { + byID := make(map[string]*Resource, len(c.right.Resources)) + type origin struct{ file, pointer string } + byOrigin := make(map[origin]*Resource, len(c.right.Resources)) + used := make(map[*Resource]bool) + pairs := make(map[*Resource]*Resource) + c.pairs, c.matched = pairs, used + for _, r := range c.right.Resources { + byID[r.ID] = r + byOrigin[origin{r.Source.relative, r.Pointer}] = r + } + if c.left.Root != nil && c.right.Root != nil { + pairs[c.left.Root] = c.right.Root + used[c.right.Root] = true + } + for _, l := range c.left.Resources { + if pairs[l] == nil { + if r := byID[l.ID]; r != nil && !used[r] { + pairs[l] = r + used[r] = true + } + } + } + for _, l := range c.left.Resources { + r := pairs[l] + if r == nil { + file := l.Source.relative + if c.left.Root != nil && c.right.Root != nil && l.Source == c.left.Root.Source { + file = c.right.Root.Source.relative + } + r = byOrigin[origin{file, l.Pointer}] + if used[r] { + r = nil + } + if r != nil { + used[r] = true + pairs[l] = r + } + } + } + for _, l := range c.left.Resources { + if err := c.compareResource(l, pairs[l]); err != nil { + return err + } + } + for _, r := range c.right.Resources { + if !used[r] { + if err := c.compareResource(nil, r); err != nil { + return err + } + } + } + return nil +} + +func (c *comparison) compareResource(l, r *Resource) error { + if l == nil || r == nil { + c.membership(l, r, "$", "schema", nil, nil, true) + return nil + } + return c.schema(l, r, l.Node, r.Node, "$", 1) +} + +func (c *comparison) schema(l, r *Resource, left, right *yaml.Node, path string, polarity int) error { + if sameNode(left, right) { + return nil + } + if left.Kind == yaml.ScalarNode || right.Kind == yaml.ScalarNode { + if left.Kind == right.Kind && strings.EqualFold(left.Value, right.Value) { + return nil + } + breaking := !strings.EqualFold(left.Value, "false") && !strings.EqualFold(right.Value, "true") + start := len(c.changes) + wc.CreateChangeWithEncoding(&c.changes, wc.Modified, "schema", left, right, breaking, nil, nil) + c.finish(c.changes[start], l, r, path, "type", polarity, breaking) + return nil + } + // The existing low model owns keyword semantics. Child schemas and references + // carry separate authored locations and must not expand inside this comparison. + lp, err := constraintProxy(left, l) + if err != nil { + return err + } + rp, err := constraintProxy(right, r) + if err != nil { + return err + } + if diff := wc.CompareSchemas(lp, rp); diff != nil { + for _, ch := range diff.GetAllChanges() { + property := ch.Property + if property == "schemaDialect" { + property = "$schema" + } + editPath := PropertyPath(path, property) + for _, dep := range diff.DependentRequiredChanges { + if ch == dep { + editPath = PropertyPath(PropertyPath(path, "dependentRequired"), property) + if a, ok := ch.OriginalObject.([]string); ok { + value, _ := json.Marshal(a) + ch.OriginalEncoded = string(value) + } + if b, ok := ch.NewObject.([]string); ok { + value, _ := json.Marshal(b) + ch.NewEncoded = string(value) + } + property = "dependentRequired" + break + } + } + c.finish(ch, l, r, editPath, property, polarity, compatibility(ch, property)) + c.changes = append(c.changes, ch) + } + } + for _, keyword := range []string{"$anchor", "$ref", "minimum", "maximum", "exclusiveMinimum", "exclusiveMaximum", "multipleOf", "minContains", "maxContains"} { + a, b := member(left, keyword), member(right, keyword) + if a == nil && b == nil || a != nil && b != nil && a.Value == b.Value { + continue + } + kind := wc.Modified + if a == nil { + kind = wc.PropertyAdded + } else if b == nil { + kind = wc.PropertyRemoved + } + start := len(c.changes) + breaking := keyword == "$ref" || a != nil + if exactNumber(keyword) && a != nil && b != nil { + x, ok := new(big.Rat).SetString(a.Value) + y, ok2 := new(big.Rat).SetString(b.Value) + if ok && ok2 && x.Cmp(y) == 0 { + continue + } + } + wc.CreateChange(&c.changes, kind, keyword, a, b, breaking, nil, nil) + if exactNumber(keyword) { + breaking = compatibility(c.changes[start], keyword) + } + c.finish(c.changes[start], l, r, PropertyPath(path, keyword), keyword, polarity, breaking) + } + return c.compareChildren(l, r, left, right, path, polarity) +} + +func constraintProxy(n *yaml.Node, r *Resource) (*base.SchemaProxy, error) { + view := *n + view.Content = make([]*yaml.Node, 0, len(n.Content)) + for i := 0; i < len(n.Content); i += 2 { + k := n.Content[i].Value + if childKind(k) == 0 && k != "$ref" && k != "$anchor" && !exactNumber(k) { + view.Content = append(view.Content, n.Content[i:i+2]...) + } + } + var proxy base.SchemaProxy + if err := proxy.Build(context.Background(), nil, &view, r.Source.Index); err != nil { + return nil, err + } + if proxy.Schema() == nil { + return nil, fmt.Errorf("%s:%d: %w", r.Source.Name, n.Line, proxy.GetBuildError()) + } + return &proxy, nil +} + +type childKey struct{ keyword, key string } + +func childNodes(n *yaml.Node) map[childKey]*yaml.Node { + var nodes map[childKey]*yaml.Node + _ = children(n, func(kw, k string, child *yaml.Node) error { + if nodes == nil { + nodes = make(map[childKey]*yaml.Node) + } + nodes[childKey{kw, k}] = child + return nil + }) + return nodes +} + +func sameNode(a, b *yaml.Node) bool { + if a == b { + return true + } + if a.Kind != b.Kind || a.Tag != b.Tag || a.Value != b.Value || len(a.Content) != len(b.Content) { + return false + } + for i := range a.Content { + if !sameNode(a.Content[i], b.Content[i]) { + return false + } + } + return true +} + +func exactNumber(k string) bool { + switch k { + case "minimum", "maximum", "exclusiveMinimum", "exclusiveMaximum", "multipleOf", "minContains", "maxContains": + return true + } + return false +} + +func (c *comparison) compareChildren(l, r *Resource, left, right *yaml.Node, path string, polarity int) error { + old, newNodes := childNodes(left), childNodes(right) + // allOf, anyOf, and oneOf have unordered operands. Match identical branches + // before comparing the remaining positions. prefixItems is an ordered tuple. + for _, kw := range []string{"allOf", "anyOf", "oneOf"} { + if member(left, kw) == nil || member(right, kw) == nil { + continue + } + byHash := make(map[string][]childKey) + for i := range member(right, kw).Content { + k := childKey{kw, strconv.Itoa(i)} + if n := newNodes[k]; n != nil { + hash := low.HashYAMLNodeSlice([]*yaml.Node{n}) + byHash[hash] = append(byHash[hash], k) + } + } + for i := range member(left, kw).Content { + k := childKey{kw, strconv.Itoa(i)} + if n := old[k]; n != nil { + hash := low.HashYAMLNodeSlice([]*yaml.Node{n}) + if matches := byHash[hash]; len(matches) > 0 { + delete(old, k) + delete(newNodes, matches[0]) + byHash[hash] = matches[1:] + } + } + } + var remainingLeft, remainingRight []childKey + for i := range member(left, kw).Content { + k := childKey{kw, strconv.Itoa(i)} + if old[k] != nil { + remainingLeft = append(remainingLeft, k) + } + } + for i := range member(right, kw).Content { + k := childKey{kw, strconv.Itoa(i)} + if newNodes[k] != nil { + remainingRight = append(remainingRight, k) + } + } + for i := 0; i < min(len(remainingLeft), len(remainingRight)); i++ { + lk, rk := remainingLeft[i], remainingRight[i] + a, b := old[lk], newNodes[rk] + delete(old, lk) + delete(newNodes, rk) + direction := polarity + if kw == "oneOf" { + direction = 0 + } + if c.left.schemas[a] == l && c.right.schemas[b] == r { + if err := c.schema(l, r, a, b, childPath(path, rk), direction); err != nil { + return err + } + } + } + } + for k, a := range old { + b := newNodes[k] + delete(newNodes, k) + p := childPath(path, k) + if b == nil { + if owner := c.left.schemas[a]; owner != l && c.pairs[owner] == nil { + continue + } + c.membership(l, r, p, k.keyword, a, nil, true) + continue + } + direction := polarity + switch k.keyword { + case "not": + direction = -direction + case "oneOf", "if": + direction = 0 + case "$defs": + direction = 1 + } + leftOwner, rightOwner := c.left.schemas[a], c.right.schemas[b] + if leftOwner != l && rightOwner != r { + if c.pairs[leftOwner] != rightOwner && (c.pairs[leftOwner] != nil || c.matched[rightOwner]) { + wc.CreateChange(&c.changes, wc.Modified, k.keyword, member(a, "$id"), member(b, "$id"), true, nil, nil) + c.finish(c.changes[len(c.changes)-1], l, r, p, k.keyword, 1, true) + } + continue + } + if err := c.schema(l, r, a, b, p, direction); err != nil { + return err + } + } + for k, b := range newNodes { + if owner := c.right.schemas[b]; owner != r && !c.matched[owner] { + continue + } + breaking := k.keyword != "$defs" && k.keyword != "anyOf" + c.membership(l, r, childPath(path, k), k.keyword, nil, b, breaking) + } + return nil +} + +// PropertyPath appends an object key to a JSONPath without changing its identity. +func PropertyPath(path, key string) string { + valid := key != "" + for i, c := range key { + if !(c == '_' || c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' || i > 0 && c >= '0' && c <= '9') { + valid = false + break + } + } + if valid { + return path + "." + key + } + return path + "[" + strconv.Quote(key) + "]" +} + +func childPath(path string, k childKey) string { + p := PropertyPath(path, k.keyword) + switch childKind(k.keyword) { + case schemaMap: + return PropertyPath(p, k.key) + case schemaList: + return p + "[" + k.key + "]" + } + return p +} + +func (c *comparison) membership(l, r *Resource, path, kw string, a, b *yaml.Node, breaking bool) { + if l == nil && b == nil { + b = r.Node + breaking = false + } + if r == nil && a == nil { + a = l.Node + } + kind := wc.ObjectAdded + if b == nil { + kind = wc.ObjectRemoved + } + start := len(c.changes) + wc.CreateChangeWithEncoding(&c.changes, kind, kw, a, b, breaking, nil, nil) + c.finish(c.changes[start], l, r, path, kw, 1, breaking) +} + +func compatibility(ch *wc.Change, property string) bool { + switch property { + case "required": + return ch.ChangeType != wc.PropertyRemoved + case "$id", "$dynamicAnchor": + return ch.ChangeType != wc.PropertyAdded + case "minimum", "exclusiveMinimum", "minLength", "minItems", "minProperties", "minContains", "maximum", "exclusiveMaximum", "maxLength", "maxItems", "maxProperties", "maxContains": + if ch.ChangeType == wc.PropertyRemoved { + return false + } + if ch.ChangeType == wc.PropertyAdded { + return true + } + a, ok := new(big.Rat).SetString(ch.Original) + b, ok2 := new(big.Rat).SetString(ch.New) + if ok && ok2 { + sign := b.Cmp(a) + if strings.HasPrefix(property, "max") || property == "exclusiveMaximum" { + return sign < 0 + } + return sign > 0 + } + } + if rule := standaloneDefaults.GetRule(wc.CompSchema, property); rule != nil { + if value := operationRule(rule, ch.ChangeType); value != nil { + return *value + } + } + return true +} + +var standaloneDefaults = wc.GenerateDefaultBreakingRules() + +func operationRule(rule *wc.BreakingChangeRule, kind int) *bool { + switch kind { + case wc.PropertyAdded, wc.ObjectAdded: + return rule.Added + case wc.PropertyRemoved, wc.ObjectRemoved: + return rule.Removed + default: + return rule.Modified + } +} + +func (c *comparison) finish(ch *wc.Change, l, r *Resource, path, property string, polarity int, breaking bool) { + switch property { + case "description", "title", "$comment", "default", "examples", "readOnly", "writeOnly", "deprecated": + breaking = false + case "$id", "$anchor", "$dynamicAnchor": + default: + if polarity < 0 { + switch property { + case "type", "required", "minimum", "maximum", "exclusiveMinimum", "exclusiveMaximum", "minLength", "maxLength", "minContains", "maxContains", "minItems", "maxItems", "minProperties", "maxProperties": + if property == "type" && ch.Property != "schema" { + breaking = true + } else { + breaking = !breaking + } + default: + breaking = true + } + } else if polarity == 0 { + breaking = true + } + } + if c.rules != nil { + if rule := c.rules.GetRule(wc.CompSchema, property); rule != nil { + override := rule.Modified + switch ch.ChangeType { + case wc.PropertyAdded, wc.ObjectAdded: + override = rule.Added + case wc.PropertyRemoved, wc.ObjectRemoved: + override = rule.Removed + } + if override != nil { + breaking = *override + } + } + } + ch.Breaking, ch.Path, ch.Type = breaking, path, "schema" + if l != nil { + ch.SchemaResource = l.ID + if ch.Context.OriginalLine != nil { + ch.Context.OriginalDocument = l.Source.Name + ch.Context.DocumentLocation = l.Source.Name + } + } + if r != nil { + ch.SchemaResource = r.ID + if ch.Context.NewLine != nil { + ch.Context.ModifiedDocument = r.Source.Name + ch.Context.DocumentLocation = r.Source.Name + } + } +} diff --git a/jsonschema/document_test.go b/jsonschema/document_test.go new file mode 100644 index 00000000..7c00fcea --- /dev/null +++ b/jsonschema/document_test.go @@ -0,0 +1,99 @@ +// Copyright 2026 Princess B33f Heavy Industries / Dave Shanley +// SPDX-License-Identifier: MIT + +package jsonschema + +import ( + "fmt" + "testing" + "testing/fstest" + + "github.com/pb33f/libopenapi/datamodel" + wc "github.com/pb33f/libopenapi/what-changed/model" + "github.com/stretchr/testify/require" +) + +func loadTest(t *testing.T, input string) *Document { + t.Helper() + d, err := Load([]byte(input), "customer.yaml", nil, true) + require.NoError(t, err) + t.Cleanup(d.Release) + return d +} + +func TestAuthoredSchemaCompatibility(t *testing.T) { + for _, tc := range []struct { + name, left, right, path string + breaking bool + }{ + {"required", `{"type":"object","properties":{"id":{"type":"string"}}}`, `{"type":"object","properties":{"id":{"type":"string"}},"required":["id"]}`, "$.required", true}, + {"optional constraint", "{}", `{"properties":{"x":{"type":"string"}}}`, "$.properties.x", true}, + {"minContains", `{"contains":{"type":"integer"},"minContains":2}`, `{"contains":{"type":"integer"},"minContains":3}`, "$.minContains", true}, + {"high precision", `{"minimum":1.2345678901234567890}`, `{"minimum":1.2345678901234567891}`, "$.minimum", true}, + {"ambiguous negation", `{"not":{"pattern":"a"}}`, `{"not":{"pattern":"b"}}`, "$.not.pattern", true}, + {"dependent requirements", `{"dependentRequired":{"x":["a"]}}`, `{"dependentRequired":{"x":["a","b"]}}`, "$.dependentRequired.x", true}, + {"reordered conjunction", `{"allOf":[{"type":"boolean"},{"description":"one"}]}`, `{"allOf":[{"description":"two"},{"type":"boolean"}]}`, "$.allOf[0].description", false}, + {"widen boolean", "false", "true", "$", false}, {"narrow boolean", "true", "false", "$", true}, + {"tighten length", `{"minLength":2}`, `{"minLength":3}`, "$.minLength", true}, + {"widen length", `{"minLength":3}`, `{"minLength":2}`, "$.minLength", false}, + {"annotation", `{"description":"old"}`, `{"description":"new"}`, "$.description", false}, + {"static anchor", `{"$anchor":"old"}`, `{"$anchor":"new"}`, `$["$anchor"]`, true}, + {"published definition", `{"$defs":{"a.b":{"minLength":1}}}`, `{"$defs":{"a.b":{"minLength":2}}}`, `$["$defs"]["a.b"].minLength`, true}, + {"reference siblings", `{"$ref":"#","minLength":3}`, `{"$ref":"#","minLength":2}`, "$.minLength", false}, + {"negated widening", `{"not":{"minLength":3}}`, `{"not":{"minLength":2}}`, "$.not.minLength", true}, + } { + t.Run(tc.name, func(t *testing.T) { + left, right := loadTest(t, tc.left), loadTest(t, tc.right) + report, err := Compare(left, right, nil) + require.NoError(t, err) + require.NotNil(t, report) + all := report.GetAllChanges() + require.Len(t, all, 1) + require.Equal(t, tc.path, all[0].Path) + require.Equal(t, tc.breaking, all[0].Breaking) + require.Equal(t, "customer.yaml", all[0].SchemaResource) + }) + } +} + +func TestExplicitPolicyOnWidening(t *testing.T) { + rule := true + diff, err := Compare(loadTest(t, `{"minLength":3}`), loadTest(t, `{"minLength":2}`), &wc.BreakingRulesConfig{Schema: &wc.SchemaRules{MinLength: &wc.BreakingChangeRule{Modified: &rule}}}) + require.NoError(t, err) + require.Equal(t, 1, diff.TotalBreakingChanges()) +} + +func TestLoadReferencesFromEachSnapshot(t *testing.T) { + root := []byte(`{"properties":{"billing":{"$ref":"amount.yaml#amount"},"shipping":{"$ref":"amount.yaml#amount"}}}`) + load := func(limit int) *Document { + cfg := datamodel.NewDocumentConfiguration() + cfg.BasePath = "/snapshot" + cfg.LocalFS = fstest.MapFS{"amount.yaml": {Data: []byte(fmt.Sprintf("$id: urn:amount\n$anchor: amount\nminLength: %d\n", limit))}} + d, err := Load(root, "customer.json", cfg, true) + require.NoError(t, err) + t.Cleanup(d.Release) + return d + } + a, b := load(2), load(3) + require.Len(t, a.References, 2) + require.Same(t, a.References[0].To, a.References[1].To) + diff, err := Compare(a, b, nil) + require.NoError(t, err) + require.Len(t, diff.GetAllChanges(), 1) + ch := diff.GetAllChanges()[0] + require.Equal(t, "urn:amount", ch.SchemaResource) + require.Equal(t, "amount.yaml", ch.Context.OriginalDocument) + require.Equal(t, "amount.yaml", ch.Context.ModifiedDocument) +} + +func TestEmbeddedResourceOccurrence(t *testing.T) { + left := loadTest(t, `{"properties":{"x":{"$id":"urn:field","type":"string"}}}`) + right := loadTest(t, `{"properties":{"y":{"$id":"urn:field","type":"string"}}}`) + changes, err := Compare(left, right, nil) + require.NoError(t, err) + require.Equal(t, 2, changes.TotalChanges()) + require.Equal(t, "$.properties.x", changes.GetAllChanges()[0].Path) + node, ok := left.Root.Source.Index.GetNode(left.Root.Node.Line, left.Root.Node.Column) + require.True(t, ok) + require.Same(t, left.Root.Node, node) +} diff --git a/what-changed/model/change_types.go b/what-changed/model/change_types.go index 361c79da..f7c89fc7 100644 --- a/what-changed/model/change_types.go +++ b/what-changed/model/change_types.go @@ -38,6 +38,8 @@ type WhatChanged struct { // ChangeContext holds a reference to the line and column positions of original and new change. type ChangeContext struct { + OriginalDocument string `json:"originalDocument,omitempty" yaml:"originalDocument,omitempty"` + ModifiedDocument string `json:"modifiedDocument,omitempty" yaml:"modifiedDocument,omitempty"` DocumentLocation string `json:"document,omitempty" yaml:"document,omitempty"` OriginalLine *int `json:"originalLine,omitempty" yaml:"originalLine,omitempty"` OriginalColumn *int `json:"originalColumn,omitempty" yaml:"originalColumn,omitempty"` @@ -72,6 +74,8 @@ func (c *ChangeContext) HasChanged() bool { // Change represents a change between two different elements inside an OpenAPI specification. type Change struct { + // SchemaResource identifies the defining resource for a standalone JSON Schema edit. + SchemaResource string `json:"schemaResource,omitempty" yaml:"schemaResource,omitempty"` // Context represents the lines and column numbers of the original and new values // It's worth noting that these values may frequently be different and are not used to calculate // a change. If the positions change, but values do not, then no change is recorded. @@ -163,6 +167,9 @@ func (c *Change) MarshalJSON() ([]byte, error) { if c.Path != "" { data["path"] = c.Path } + if c.SchemaResource != "" { + data["schemaResource"] = c.SchemaResource + } return json.Marshal(data) } From 23aaeb8ed002745d1cd00f7b6bce385c8d04dfaa Mon Sep 17 00:00:00 2001 From: quobix Date: Wed, 25 Nov 2026 11:59:03 -0500 Subject: [PATCH 03/27] Pre-index schema collections before resolving shared references --- jsonschema/collection.go | 47 ++++++++++++ jsonschema/collection_test.go | 132 ++++++++++++++++++++++++++++++++++ jsonschema/compare.go | 3 + 3 files changed, 182 insertions(+) create mode 100644 jsonschema/collection.go create mode 100644 jsonschema/collection_test.go diff --git a/jsonschema/collection.go b/jsonschema/collection.go new file mode 100644 index 00000000..82e4380c --- /dev/null +++ b/jsonschema/collection.go @@ -0,0 +1,47 @@ +// Copyright 2026 Princess B33f Heavy Industries / Dave Shanley +// SPDX-License-Identifier: MIT + +package jsonschema + +import ( + "fmt" + "io/fs" + "maps" + "net/url" + "path/filepath" + "slices" + "strings" + + "github.com/pb33f/libopenapi/datamodel" +) + +// LoadCollection registers all named schema sources before resolving references. +// Names are slash-separated paths relative to directory. An empty snapshot is valid. +// The returned document has a nil Root and one entry in Sources per physical file. +func LoadCollection(members map[string][]byte, directory string, config *datamodel.DocumentConfiguration) (*Document, error) { + absolute, err := filepath.Abs(directory) + if err != nil { + return nil, err + } + if config == nil { + config = datamodel.NewDocumentConfiguration() + } + base := &url.URL{Scheme: "file", Path: strings.TrimSuffix(filepath.ToSlash(absolute), "/") + "/"} + d := newDocument(config, base) + for _, name := range slices.Sorted(maps.Keys(members)) { + if !fs.ValidPath(name) || name == "." || strings.ContainsRune(name, '\\') { + d.Release() + return nil, fmt.Errorf("invalid schema member path %q", name) + } + uri := base.ResolveReference(&url.URL{Path: name}) + if _, err := d.addSource(members[name], uri, true); err != nil { + d.Release() + return nil, fmt.Errorf("schema member %s: %w", name, err) + } + } + if err := d.resolveReferences(); err != nil { + d.Release() + return nil, err + } + return d, nil +} diff --git a/jsonschema/collection_test.go b/jsonschema/collection_test.go new file mode 100644 index 00000000..7c6e8eba --- /dev/null +++ b/jsonschema/collection_test.go @@ -0,0 +1,132 @@ +// Copyright 2026 Princess B33f Heavy Industries / Dave Shanley +// SPDX-License-Identifier: MIT + +package jsonschema + +import ( + "encoding/json" + "fmt" + "strings" + "testing" + + "github.com/stretchr/testify/require" +) + +func loadMembers(t testing.TB, dir string, files map[string][]byte) *Document { + t.Helper() + d, err := LoadCollection(files, dir, nil) + require.NoError(t, err) + t.Cleanup(d.Release) + return d +} + +func sharedMembers(uses, minimum int) map[string][]byte { + files := map[string][]byte{"money.json": []byte(fmt.Sprintf(`{"$id":"urn:money","properties":{"currency":{"type":"string","minLength":%d}}}`, minimum))} + for i := range uses { + files[fmt.Sprintf("orders/%04d.json", i)] = []byte(fmt.Sprintf(`{"$id":"urn:order:%d","properties":{"value":{"$ref":"urn:money"}}}`, i)) + } + return files +} + +func TestCollectionSharedOwnership(t *testing.T) { + left, right := loadMembers(t, "original", sharedMembers(2, 2)), loadMembers(t, "modified", sharedMembers(2, 3)) + require.Nil(t, right.Root) + require.Len(t, right.Sources, 3) + require.Len(t, right.References, 2) + require.Same(t, right.Sources["money.json"].Node, right.References[0].To) + require.Same(t, right.References[0].To, right.References[1].To) + diff, err := Compare(left, right, nil) + require.NoError(t, err) + require.Len(t, diff.GetAllChanges(), 1) + ch := diff.GetAllChanges()[0] + require.Equal(t, "urn:money", ch.SchemaResource) + require.Equal(t, "$.properties.currency.minLength", ch.Path) + require.True(t, ch.Breaking) + require.Equal(t, "money.json", ch.Context.OriginalDocument) + wire, err := json.Marshal(ch) + require.NoError(t, err) + require.Contains(t, string(wire), `"schemaResource":"urn:money"`) + reverse, err := Compare(right, left, nil) + require.NoError(t, err) + require.Zero(t, reverse.TotalBreakingChanges()) +} + +func TestCollectionIdentityAndMoves(t *testing.T) { + for _, tc := range []struct { + name string + left, right map[string][]byte + changes int + }{ + {"moved", map[string][]byte{"old.json": []byte(`{"$id":"urn:money","type":"string"}`)}, map[string][]byte{"dir/new.json": []byte(`{"$id":"urn:money","type":"string"}`)}, 0}, + {"anonymous", map[string][]byte{"a.yaml": []byte("minLength: 2")}, map[string][]byte{"a.yaml": []byte("minLength: 3")}, 1}, + {"rename id", map[string][]byte{"a.yaml": []byte("$id: urn:first")}, map[string][]byte{"a.yaml": []byte("$id: urn:second")}, 1}, + {"added", nil, map[string][]byte{"a.json": []byte("true")}, 1}, + {"removed", map[string][]byte{"a.json": []byte("false")}, nil, 1}, + {"empty", nil, nil, 0}, + {"distinct", map[string][]byte{"a.yaml": []byte("minLength: 1"), "b.yaml": []byte("minLength: 1")}, map[string][]byte{"a.yaml": []byte("minLength: 2"), "b.yaml": []byte("minLength: 2")}, 2}, + {"nested base", map[string][]byte{"a.json": []byte(`{"$id":"dir/a","$defs":{"field":{"$id":"field","minLength":1}},"$ref":"field"}`)}, map[string][]byte{"a.json": []byte(`{"$id":"dir/a","$defs":{"field":{"$id":"field","minLength":2}},"$ref":"field"}`)}, 1}, + {"retarget", map[string][]byte{"a.yaml": []byte("$ref: urn:one"), "one.yaml": []byte("$id: urn:one"), "two.yaml": []byte("$id: urn:two")}, map[string][]byte{"a.yaml": []byte("$ref: urn:two"), "one.yaml": []byte("$id: urn:one"), "two.yaml": []byte("$id: urn:two")}, 1}, + {"cycle", map[string][]byte{"a.json": []byte(`{"$ref":"b.json"}`), "b.json": []byte(`{"$ref":"a.json","minLength":2}`)}, map[string][]byte{"a.json": []byte(`{"$ref":"b.json"}`), "b.json": []byte(`{"$ref":"a.json","minLength":3}`)}, 1}, + } { + t.Run(tc.name, func(t *testing.T) { + a, b := loadMembers(t, "previous", tc.left), loadMembers(t, "current", tc.right) + diff, err := Compare(a, b, nil) + require.NoError(t, err) + if tc.changes == 0 { + require.Nil(t, diff) + return + } + require.NotNil(t, diff) + require.Equal(t, tc.changes, diff.TotalChanges()) + if tc.name == "distinct" { + cs := diff.GetAllChanges() + require.Equal(t, []string{"a.yaml", "b.yaml"}, []string{cs[0].SchemaResource, cs[1].SchemaResource}) + require.Equal(t, cs[0].Path, cs[1].Path) + } + if tc.name == "nested base" { + require.Equal(t, "dir/field", diff.GetAllChanges()[0].SchemaResource) + } + }) + } +} + +func TestCollectionDuplicateIDAndRetrievalAlias(t *testing.T) { + _, err := LoadCollection(map[string][]byte{"a.json": []byte(`{"$id":"urn:money"}`), "b.json": []byte(`{"$id":"urn:money"}`)}, "root", nil) + require.ErrorContains(t, err, "duplicate") + require.Contains(t, err.Error(), "a.json") + require.Contains(t, err.Error(), "b.json") + d := loadMembers(t, "root", map[string][]byte{"a.json": []byte(`{"$id":"urn:a?x=1"}`), "b.json": []byte(`{"$id":"urn:a?x=2"}`), "refs.json": []byte(`{"properties":{"v":{"$ref":"b.json"}}}`)}) + require.NotEqual(t, d.Resources[0].ID, d.Resources[1].ID) + require.Same(t, d.Sources["b.json"].Node, d.References[0].To) + for _, name := range []string{".", "../a.json", "dir\\a.json", "/outside.json"} { + _, err = LoadCollection(map[string][]byte{name: []byte("true")}, "root", nil) + require.ErrorContains(t, err, "invalid schema member") + } +} + +// BenchmarkSharedReferences measures the complete authored comparison after indexing. +// Every incoming use points at the same target node and source buffer on its side. +func BenchmarkSharedReferences(b *testing.B) { + for _, uses := range []int{2, 100, 1000} { + b.Run(fmt.Sprint(uses), func(b *testing.B) { + left, right := loadMembers(b, "original", sharedMembers(uses, 2)), loadMembers(b, "modified", sharedMembers(uses, 3)) + for _, doc := range []*Document{left, right} { + for _, ref := range doc.References { + if ref.To != doc.Sources["money.json"].Node { + b.Fatal("multiple target nodes") + } + } + } + b.ReportAllocs() + b.ResetTimer() + for b.Loop() { + diff, err := Compare(left, right, nil) + if err != nil || diff == nil || diff.TotalChanges() != 1 || !strings.HasPrefix(diff.GetAllChanges()[0].Path, "$.properties.currency.") { + b.Fatalf("unexpected definition edit: %v", err) + } + } + b.ReportMetric(1, "targetEdits/op") + b.ReportMetric(float64(uses+1), "sources/side") + }) + } +} diff --git a/jsonschema/compare.go b/jsonschema/compare.go index 11c1595d..fe81603f 100644 --- a/jsonschema/compare.go +++ b/jsonschema/compare.go @@ -25,6 +25,9 @@ func Compare(left, right *Document, rules *wc.BreakingRulesConfig) (*wc.SchemaCh if left == nil || right == nil { return nil, fmt.Errorf("both JSON Schema inputs are required") } + if (left.Root == nil) != (right.Root == nil) { + return nil, fmt.Errorf("a schema collection requires a collection on both sides") + } c := comparison{left: left, right: right, rules: rules} if err := c.resources(); err != nil { return nil, err From 360c29c3023120ce07c77b110ac3e6fde0d6fc37 Mon Sep 17 00:00:00 2001 From: quobix Date: Wed, 25 Nov 2026 12:03:26 -0500 Subject: [PATCH 04/27] Preserve resource identity and authored annotations in schema edits --- jsonschema/collection_test.go | 15 ++++ jsonschema/compare.go | 159 +++++++++++++++++++++++++--------- jsonschema/document.go | 16 ++-- jsonschema/document_test.go | 17 ++++ jsonschema/loader_test.go | 10 ++- jsonschema/reference.go | 8 +- 6 files changed, 175 insertions(+), 50 deletions(-) diff --git a/jsonschema/collection_test.go b/jsonschema/collection_test.go index 7c6e8eba..dbb39392 100644 --- a/jsonschema/collection_test.go +++ b/jsonschema/collection_test.go @@ -90,6 +90,21 @@ func TestCollectionIdentityAndMoves(t *testing.T) { } } +func TestMatchResourcesPrefersIDThenOrigin(t *testing.T) { + left := loadMembers(t, "previous", map[string][]byte{ + "a.yml": []byte("$id: urn:move"), "b.yml": []byte("$id: urn:rename"), "gone.yml": []byte("true"), + }) + right := loadMembers(t, "current", map[string][]byte{ + "new.yml": []byte("$id: urn:move"), "b.yml": []byte("$id: urn:renamed"), "fresh.yml": []byte("false"), + }) + pairs := MatchResources(left, right) + require.Len(t, pairs, 2) + for old, current := range pairs { + want := map[string]string{"urn:move": "urn:move", "urn:rename": "urn:renamed"} + require.Equal(t, want[old.ID], current.ID) + } +} + func TestCollectionDuplicateIDAndRetrievalAlias(t *testing.T) { _, err := LoadCollection(map[string][]byte{"a.json": []byte(`{"$id":"urn:money"}`), "b.json": []byte(`{"$id":"urn:money"}`)}, "root", nil) require.ErrorContains(t, err, "duplicate") diff --git a/jsonschema/compare.go b/jsonschema/compare.go index fe81603f..4d9d5c16 100644 --- a/jsonschema/compare.go +++ b/jsonschema/compare.go @@ -42,6 +42,7 @@ func Compare(left, right *Document, rules *wc.BreakingRulesConfig) (*wc.SchemaCh } type comparison struct { + inline map[*Resource]bool pairs map[*Resource]*Resource matched map[*Resource]bool left, right *Document @@ -49,22 +50,32 @@ type comparison struct { changes []*wc.Change } -func (c *comparison) resources() error { - byID := make(map[string]*Resource, len(c.right.Resources)) +// MatchResources pairs the original and modified resources by resolved ID, then +// by source path and embedded pointer. A comparison of two single schemas always +// pairs their roots. Unmatched resources have no entry in the returned map. +func MatchResources(left, right *Document) map[*Resource]*Resource { + pairs, _ := matchResources(left, right) + return pairs +} + +func matchResources(left, right *Document) (map[*Resource]*Resource, map[*Resource]bool) { + if left == nil || right == nil { + return nil, nil + } + byID := make(map[string]*Resource, len(right.Resources)) type origin struct{ file, pointer string } - byOrigin := make(map[origin]*Resource, len(c.right.Resources)) + byOrigin := make(map[origin]*Resource, len(right.Resources)) used := make(map[*Resource]bool) pairs := make(map[*Resource]*Resource) - c.pairs, c.matched = pairs, used - for _, r := range c.right.Resources { + for _, r := range right.Resources { byID[r.ID] = r byOrigin[origin{r.Source.relative, r.Pointer}] = r } - if c.left.Root != nil && c.right.Root != nil { - pairs[c.left.Root] = c.right.Root - used[c.right.Root] = true + if left.Root != nil && right.Root != nil { + pairs[left.Root] = right.Root + used[right.Root] = true } - for _, l := range c.left.Resources { + for _, l := range left.Resources { if pairs[l] == nil { if r := byID[l.ID]; r != nil && !used[r] { pairs[l] = r @@ -72,12 +83,12 @@ func (c *comparison) resources() error { } } } - for _, l := range c.left.Resources { + for _, l := range left.Resources { r := pairs[l] if r == nil { file := l.Source.relative - if c.left.Root != nil && c.right.Root != nil && l.Source == c.left.Root.Source { - file = c.right.Root.Source.relative + if left.Root != nil && right.Root != nil && l.Source == left.Root.Source { + file = right.Root.Source.relative } r = byOrigin[origin{file, l.Pointer}] if used[r] { @@ -89,7 +100,16 @@ func (c *comparison) resources() error { } } } + return pairs, used +} + +func (c *comparison) resources() error { + pairs, used := matchResources(c.left, c.right) + c.pairs, c.matched = pairs, used for _, l := range c.left.Resources { + if c.inline[l] { + continue + } if err := c.compareResource(l, pairs[l]); err != nil { return err } @@ -188,15 +208,61 @@ func (c *comparison) schema(l, r *Resource, left, right *yaml.Node, path string, } c.finish(c.changes[start], l, r, PropertyPath(path, keyword), keyword, polarity, breaking) } + c.compareAnnotations(l, r, left, right, path) return c.compareChildren(l, r, left, right, path, polarity) } +// Keywords outside the supported vocabularies are annotations. Keep them out of +// the API schema model, which also recognizes legacy OpenAPI-only keywords. +func nativeConstraint(keyword string) bool { + switch keyword { + case "$schema", "$id", "$comment", "$dynamicRef", "$dynamicAnchor", "$vocabulary", + "type", "required", "enum", "const", "maxLength", "minLength", "pattern", "format", + "minItems", "maxItems", "uniqueItems", "minProperties", "maxProperties", "dependentRequired", + "title", "description", "default", "examples", "deprecated", "readOnly", "writeOnly", "contentMediaType", "contentEncoding": + return true + } + return false +} + +func annotation(keyword string) bool { + return childKind(keyword) == 0 && !nativeConstraint(keyword) && !exactNumber(keyword) && keyword != "$ref" && keyword != "$anchor" +} + +func (c *comparison) compareAnnotations(l, r *Resource, left, right *yaml.Node, path string) { + record := func(key string, a, b *yaml.Node) { + if a != nil && b != nil && low.HashYAMLNodeSlice([]*yaml.Node{a}) == low.HashYAMLNodeSlice([]*yaml.Node{b}) { + return + } + kind := wc.Modified + if b == nil { + kind = wc.PropertyRemoved + } else if a == nil { + kind = wc.PropertyAdded + } + wc.CreateChangeWithEncoding(&c.changes, kind, key, a, b, false, nil, nil) + c.finish(c.changes[len(c.changes)-1], l, r, PropertyPath(path, key), key, 1, false) + } + for i := 0; i < len(left.Content); i += 2 { + key := left.Content[i].Value + if annotation(key) { + record(key, left.Content[i+1], member(right, key)) + } + } + for i := 0; i < len(right.Content); i += 2 { + key := right.Content[i].Value + if annotation(key) && member(left, key) == nil { + record(key, nil, right.Content[i+1]) + } + } +} + func constraintProxy(n *yaml.Node, r *Resource) (*base.SchemaProxy, error) { view := *n view.Content = make([]*yaml.Node, 0, len(n.Content)) for i := 0; i < len(n.Content); i += 2 { k := n.Content[i].Value - if childKind(k) == 0 && k != "$ref" && k != "$anchor" && !exactNumber(k) { + if nativeConstraint(k) { view.Content = append(view.Content, n.Content[i:i+2]...) } } @@ -292,14 +358,8 @@ func (c *comparison) compareChildren(l, r *Resource, left, right *yaml.Node, pat a, b := old[lk], newNodes[rk] delete(old, lk) delete(newNodes, rk) - direction := polarity - if kw == "oneOf" { - direction = 0 - } - if c.left.schemas[a] == l && c.right.schemas[b] == r { - if err := c.schema(l, r, a, b, childPath(path, rk), direction); err != nil { - return err - } + if err := c.compareChild(l, r, a, b, childPath(path, rk), kw, polarity); err != nil { + return err } } } @@ -314,24 +374,7 @@ func (c *comparison) compareChildren(l, r *Resource, left, right *yaml.Node, pat c.membership(l, r, p, k.keyword, a, nil, true) continue } - direction := polarity - switch k.keyword { - case "not": - direction = -direction - case "oneOf", "if": - direction = 0 - case "$defs": - direction = 1 - } - leftOwner, rightOwner := c.left.schemas[a], c.right.schemas[b] - if leftOwner != l && rightOwner != r { - if c.pairs[leftOwner] != rightOwner && (c.pairs[leftOwner] != nil || c.matched[rightOwner]) { - wc.CreateChange(&c.changes, wc.Modified, k.keyword, member(a, "$id"), member(b, "$id"), true, nil, nil) - c.finish(c.changes[len(c.changes)-1], l, r, p, k.keyword, 1, true) - } - continue - } - if err := c.schema(l, r, a, b, p, direction); err != nil { + if err := c.compareChild(l, r, a, b, p, k.keyword, polarity); err != nil { return err } } @@ -345,6 +388,42 @@ func (c *comparison) compareChildren(l, r *Resource, left, right *yaml.Node, pat return nil } +func (c *comparison) compareChild(l, r *Resource, a, b *yaml.Node, path, keyword string, polarity int) error { + switch keyword { + case "not": + polarity = -polarity + case "oneOf", "if": + polarity = 0 + case "$defs": + polarity = 1 + } + lo, ro := c.left.schemas[a], c.right.schemas[b] + switch { + case lo == l && ro == r: + return c.schema(l, r, a, b, path, polarity) + case lo != l && ro != r: + if c.pairs[lo] != ro && (c.pairs[lo] != nil || c.matched[ro]) { + wc.CreateChange(&c.changes, wc.Modified, keyword, member(a, "$id"), member(b, "$id"), true, nil, nil) + c.finish(c.changes[len(c.changes)-1], l, r, path, keyword, 1, true) + } + case lo == l && !c.matched[ro]: + // An inline schema acquired its first $id. Its constraints now belong to the new resource. + c.matched[ro] = true + return c.schema(l, ro, a, b, "$", polarity) + case ro == r && c.pairs[lo] == nil: + if c.inline == nil { + c.inline = make(map[*Resource]bool) + } + c.inline[lo] = true + return c.schema(lo, r, a, b, path, polarity) + default: + // A matched resource moved to or from an existing inline use. + wc.CreateChangeWithEncoding(&c.changes, wc.Modified, keyword, a, b, true, nil, nil) + c.finish(c.changes[len(c.changes)-1], l, r, path, keyword, 1, true) + } + return nil +} + // PropertyPath appends an object key to a JSONPath without changing its identity. func PropertyPath(path, key string) string { valid := key != "" @@ -434,7 +513,7 @@ func operationRule(rule *wc.BreakingChangeRule, kind int) *bool { func (c *comparison) finish(ch *wc.Change, l, r *Resource, path, property string, polarity int, breaking bool) { switch property { - case "description", "title", "$comment", "default", "examples", "readOnly", "writeOnly", "deprecated": + case "description", "title", "$comment", "default", "examples", "readOnly", "writeOnly", "deprecated", "format", "contentMediaType", "contentEncoding": breaking = false case "$id", "$anchor", "$dynamicAnchor": default: diff --git a/jsonschema/document.go b/jsonschema/document.go index 0105bfc7..b6da9d81 100644 --- a/jsonschema/document.go +++ b/jsonschema/document.go @@ -60,6 +60,7 @@ type Reference struct { From, To *yaml.Node Value string address string + keyword string } // Document owns the resources and source locations for a comparison input. @@ -317,15 +318,14 @@ func (d *Document) indexSchema(source *Source, node *yaml.Node, base *url.URL, p } } } - if value := member(node, "$dynamicRef"); value != nil { - return fmt.Errorf("%s:%d: dynamic scope resolution for $dynamicRef %q is unsupported", source.Name, value.Line, value.Value) - } - if value := member(node, "$ref"); value != nil { - target, err := base.Parse(value.Value) - if value.Tag != "!!str" || err != nil { - return fmt.Errorf("%s:%d: invalid $ref %q", source.Name, value.Line, value.Value) + for _, keyword := range []string{"$ref", "$dynamicRef"} { + if value := member(node, keyword); value != nil { + target, err := base.Parse(value.Value) + if value.Tag != "!!str" || err != nil { + return fmt.Errorf("%s:%d: invalid %s %q", source.Name, value.Line, keyword, value.Value) + } + d.References = append(d.References, Reference{From: node, Value: value.Value, address: target.String(), keyword: keyword}) } - d.References = append(d.References, Reference{From: node, Value: value.Value, address: target.String()}) } return children(node, func(keyword, key string, child *yaml.Node) error { childPointer := pointer + "/" + escapePointer(keyword) diff --git a/jsonschema/document_test.go b/jsonschema/document_test.go index 7c00fcea..f88aeaaf 100644 --- a/jsonschema/document_test.go +++ b/jsonschema/document_test.go @@ -27,6 +27,8 @@ func TestAuthoredSchemaCompatibility(t *testing.T) { breaking bool }{ {"required", `{"type":"object","properties":{"id":{"type":"string"}}}`, `{"type":"object","properties":{"id":{"type":"string"}},"required":["id"]}`, "$.required", true}, + {"custom annotation", `{"source":"old"}`, `{"source":"new"}`, "$.source", false}, + {"format annotation", `{"format":"date"}`, `{"format":"time"}`, "$.format", false}, {"optional constraint", "{}", `{"properties":{"x":{"type":"string"}}}`, "$.properties.x", true}, {"minContains", `{"contains":{"type":"integer"},"minContains":2}`, `{"contains":{"type":"integer"},"minContains":3}`, "$.minContains", true}, {"high precision", `{"minimum":1.2345678901234567890}`, `{"minimum":1.2345678901234567891}`, "$.minimum", true}, @@ -97,3 +99,18 @@ func TestEmbeddedResourceOccurrence(t *testing.T) { require.True(t, ok) require.Same(t, left.Root.Node, node) } + +func TestEmbeddedSchemaAcquiresAddress(t *testing.T) { + before := loadTest(t, `{"properties":{"x":{"type":"string"}}}`) + after := loadTest(t, `{"properties":{"x":{"type":"string","$id":"urn:field"}}}`) + diff, err := Compare(before, after, nil) + require.NoError(t, err) + require.Equal(t, 1, diff.TotalChanges()) + require.Equal(t, "urn:field", diff.GetAllChanges()[0].SchemaResource) + require.Equal(t, `$["$id"]`, diff.GetAllChanges()[0].Path) + rev, err := Compare(after, before, nil) + require.NoError(t, err) + require.Equal(t, 1, rev.TotalChanges()) + require.Equal(t, 1, rev.TotalBreakingChanges()) + require.Equal(t, `$.properties.x["$id"]`, rev.GetAllChanges()[0].Path) +} diff --git a/jsonschema/loader_test.go b/jsonschema/loader_test.go index 2709abf6..20a38480 100644 --- a/jsonschema/loader_test.go +++ b/jsonschema/loader_test.go @@ -19,7 +19,7 @@ func TestLoadInputBoundaries(t *testing.T) { {"null", true, "object or boolean"}, {"type: object\ntype: string", true, "already defined"}, {`{"openapi":"3.1.0","$schema":"https://json-schema.org/draft/2020-12/schema"}`, true, "conflicting"}, {`{"$defs":{"a":{"$id":"urn:money"},"b":{"$id":"urn:money"}}}`, true, "duplicate"}, - {`{"$dynamicRef":"#scope"}`, true, "dynamic scope"}, {`{"$ref":"#/missing"}`, true, "no schema"}, + {`{"$dynamicAnchor":"scope","$dynamicRef":"#scope"}`, true, "dynamic scope"}, {`{"$ref":"#/missing"}`, true, "no schema"}, {"true\n---\nfalse", true, "one schema"}, } { _, err := Load([]byte(tc.input), "schema.yaml", nil, tc.explicit) @@ -29,3 +29,11 @@ func TestLoadInputBoundaries(t *testing.T) { require.NoError(t, err) d.Release() } + +func TestDynamicRefWithStaticTarget(t *testing.T) { + d, err := Load([]byte(`{"$defs":{"a":{"$anchor":"static"}},"$dynamicRef":"#static"}`), "a.json", nil, true) + require.NoError(t, err) + defer d.Release() + require.Len(t, d.References, 1) + require.NotNil(t, d.References[0].To) +} diff --git a/jsonschema/reference.go b/jsonschema/reference.go index d64da130..43e1b1e0 100644 --- a/jsonschema/reference.go +++ b/jsonschema/reference.go @@ -28,7 +28,13 @@ func (d *Document) resolveReferences() error { ref := d.References[i] target, err := d.resolve(ref.address) if err != nil { - return fmt.Errorf("%s:%d: resolve $ref %q: %w", d.schemas[ref.From].Source.Name, ref.From.Line, ref.Value, err) + return fmt.Errorf("%s:%d: resolve %s %q: %w", d.schemas[ref.From].Source.Name, ref.From.Line, ref.keyword, ref.Value, err) + } + if ref.keyword == "$dynamicRef" { + u, _ := url.Parse(ref.address) + if anchor := member(target, "$dynamicAnchor"); anchor != nil && u.Fragment == anchor.Value { + return fmt.Errorf("%s:%d: dynamic scope resolution for $dynamicRef %q is unsupported", d.schemas[ref.From].Source.Name, ref.From.Line, ref.Value) + } } d.References[i].To = target } From 590fd23fcb53319caf066d35e68af6495fdfe120 Mon Sep 17 00:00:00 2001 From: quobix Date: Wed, 25 Nov 2026 12:04:33 -0500 Subject: [PATCH 05/27] Expose authored reference keywords and protect schema source identities --- AGENTS.md | 1 + README.md | 26 ++++++++++++++++++++++++++ jsonschema/document.go | 14 +++++++++----- jsonschema/loader_test.go | 16 ++++++++++++++-- jsonschema/reference.go | 11 +++++++---- 5 files changed, 57 insertions(+), 11 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 003ae474..ff6740d8 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -17,6 +17,7 @@ This repo is a library, not an app. The root package exposes the public entry po | `datamodel/` | Spec parsing/version detection, schemas, and `DocumentConfiguration` | | `bundler/` | Inline and composed bundling, ref rewrite/composition, origin tracking | | `what-changed/` | Unified diff engine for OAS2 and OAS3+, plus breaking-change rule config/report helpers | +| `jsonschema/` | Native Draft 2020-12 documents and collections, resource matching, and authored changes from the shared schema comparator | | `overlay/` | OpenAPI Overlay application engine | | `arazzo/` | Arazzo parsing, resolution, validation, and workflow execution engine | | `renderer/` | Schema/mock sample generation | diff --git a/README.md b/README.md index ae5c0c3a..d9cd08b4 100644 --- a/README.md +++ b/README.md @@ -80,6 +80,32 @@ See all the documentation at https://pb33f.io/libopenapi/ - [About libopenapi](https://pb33f.io/libopenapi/about/) - [Migrating: breaking API changes by version](MIGRATING.md) +### Comparing standalone JSON Schemas + +Use the `jsonschema` package to compare Draft 2020-12 schemas. Pass the source +name so relative references resolve against the correct file. Pass `true` to +`Load` to select this dialect for an unmarked schema or a boolean root. + +```go +before, err := jsonschema.Load(original, "before/customer.json", nil, true) +if err != nil { + return err +} +defer before.Release() +after, err := jsonschema.Load(modified, "after/customer.json", nil, true) +if err != nil { + return err +} +defer after.Release() +changes, err := jsonschema.Compare(before, after, nil) +``` + +`Compare` returns a nil report for equal schemas. For a collection, use +`jsonschema.LoadCollection` with a map of relative filenames to source bytes +and the directory for that snapshot. It registers each member before resolving +references. Each change carries its resource ID, local JSONPath, and source +locations. Releases and breaking-rule overrides work the same for either input. + ### Generating TypeScript models `generator/typescript` renders the component schemas of an OpenAPI document as diff --git a/jsonschema/document.go b/jsonschema/document.go index b6da9d81..94569190 100644 --- a/jsonschema/document.go +++ b/jsonschema/document.go @@ -59,8 +59,9 @@ func (r *Resource) Label() string { type Reference struct { From, To *yaml.Node Value string - address string - keyword string + // Keyword identifies the authored $ref or $dynamicRef. + Keyword string + address string } // Document owns the resources and source locations for a comparison input. @@ -157,7 +158,9 @@ func (d *Document) resourceID(uri *url.URL) string { return name } } - return uri.String() + identity := *uri + identity.User = nil + return identity.String() } func (d *Document) sourceName(uri *url.URL) string { @@ -242,7 +245,8 @@ func (d *Document) register(address string, node *yaml.Node, source *Source) err return nil } old := d.schemas[prior] - return fmt.Errorf("duplicate schema address %q at %s:%d and %s:%d", address, old.Source.Name, prior.Line, source.Name, node.Line) + uri, _ := url.Parse(address) + return fmt.Errorf("duplicate schema address %q at %s:%d and %s:%d", d.sourceName(uri), old.Source.Name, prior.Line, source.Name, node.Line) } d.addresses[address] = node return nil @@ -324,7 +328,7 @@ func (d *Document) indexSchema(source *Source, node *yaml.Node, base *url.URL, p if value.Tag != "!!str" || err != nil { return fmt.Errorf("%s:%d: invalid %s %q", source.Name, value.Line, keyword, value.Value) } - d.References = append(d.References, Reference{From: node, Value: value.Value, address: target.String(), keyword: keyword}) + d.References = append(d.References, Reference{From: node, Value: value.Value, address: target.String(), Keyword: keyword}) } } return children(node, func(keyword, key string, child *yaml.Node) error { diff --git a/jsonschema/loader_test.go b/jsonschema/loader_test.go index 20a38480..0e8e853b 100644 --- a/jsonschema/loader_test.go +++ b/jsonschema/loader_test.go @@ -30,10 +30,22 @@ func TestLoadInputBoundaries(t *testing.T) { d.Release() } +func TestRelativeIDOmitsRetrievalCredentials(t *testing.T) { + d, err := Load([]byte(`{"$id":"customer?version=2","$ref":"#"}`), "https://name:private@schemas.example.test/draft/root.json?token=secret", nil, true) + require.NoError(t, err) + defer d.Release() + require.Equal(t, "https://schemas.example.test/draft/customer?version=2", d.Root.ID) + require.NotContains(t, d.Root.Source.Name, "private") + require.NotContains(t, d.Root.Source.Name, "secret") + require.Same(t, d.Root.Node, d.References[0].To) +} + func TestDynamicRefWithStaticTarget(t *testing.T) { - d, err := Load([]byte(`{"$defs":{"a":{"$anchor":"static"}},"$dynamicRef":"#static"}`), "a.json", nil, true) + d, err := Load([]byte(`{"$defs":{"a":{"$anchor":"static"}},"$dynamicRef":"#static","$ref":"#static"}`), "a.json", nil, true) require.NoError(t, err) defer d.Release() - require.Len(t, d.References, 1) + require.Len(t, d.References, 2) + require.ElementsMatch(t, []string{"$ref", "$dynamicRef"}, []string{d.References[0].Keyword, d.References[1].Keyword}) + require.Same(t, d.References[0].To, d.References[1].To) require.NotNil(t, d.References[0].To) } diff --git a/jsonschema/reference.go b/jsonschema/reference.go index 43e1b1e0..f5c0b86f 100644 --- a/jsonschema/reference.go +++ b/jsonschema/reference.go @@ -6,7 +6,6 @@ package jsonschema import ( "errors" "fmt" - "io" "io/fs" "net/http" @@ -28,9 +27,9 @@ func (d *Document) resolveReferences() error { ref := d.References[i] target, err := d.resolve(ref.address) if err != nil { - return fmt.Errorf("%s:%d: resolve %s %q: %w", d.schemas[ref.From].Source.Name, ref.From.Line, ref.keyword, ref.Value, err) + return fmt.Errorf("%s:%d: resolve %s %q: %w", d.schemas[ref.From].Source.Name, ref.From.Line, ref.Keyword, ref.Value, err) } - if ref.keyword == "$dynamicRef" { + if ref.Keyword == "$dynamicRef" { u, _ := url.Parse(ref.address) if anchor := member(target, "$dynamicAnchor"); anchor != nil && u.Fragment == anchor.Value { return fmt.Errorf("%s:%d: dynamic scope resolution for $dynamicRef %q is unsupported", d.schemas[ref.From].Source.Name, ref.From.Line, ref.Value) @@ -94,7 +93,7 @@ func (d *Document) resolve(address string) (*yaml.Node, error) { } } if d.schemas[target] == nil { - return nil, fmt.Errorf("no schema at %q", address) + return nil, fmt.Errorf("no schema at %q in %s", fragment, d.sourceName(uri)) } return target, nil } @@ -136,6 +135,10 @@ func (d *Document) read(uri *url.URL) ([]byte, error) { } res, err := get(uri.String()) if err != nil { + var requestErr *url.Error + if errors.As(err, &requestErr) { + return nil, fmt.Errorf("%s: %w", d.sourceName(uri), requestErr.Err) + } return nil, err } defer res.Body.Close() From 56ee21725543ccd226c59c4c4d029221518d0b67 Mon Sep 17 00:00:00 2001 From: quobix Date: Wed, 25 Nov 2026 12:06:51 -0500 Subject: [PATCH 06/27] Use the repository assertion module in schema tests --- jsonschema/collection_test.go | 2 +- jsonschema/document_test.go | 2 +- jsonschema/loader_test.go | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/jsonschema/collection_test.go b/jsonschema/collection_test.go index dbb39392..3e1a1793 100644 --- a/jsonschema/collection_test.go +++ b/jsonschema/collection_test.go @@ -9,7 +9,7 @@ import ( "strings" "testing" - "github.com/stretchr/testify/require" + "github.com/pb33f/testify/require" ) func loadMembers(t testing.TB, dir string, files map[string][]byte) *Document { diff --git a/jsonschema/document_test.go b/jsonschema/document_test.go index f88aeaaf..73ba0e95 100644 --- a/jsonschema/document_test.go +++ b/jsonschema/document_test.go @@ -10,7 +10,7 @@ import ( "github.com/pb33f/libopenapi/datamodel" wc "github.com/pb33f/libopenapi/what-changed/model" - "github.com/stretchr/testify/require" + "github.com/pb33f/testify/require" ) func loadTest(t *testing.T, input string) *Document { diff --git a/jsonschema/loader_test.go b/jsonschema/loader_test.go index 0e8e853b..ae24d506 100644 --- a/jsonschema/loader_test.go +++ b/jsonschema/loader_test.go @@ -4,7 +4,7 @@ package jsonschema import ( - "github.com/stretchr/testify/require" + "github.com/pb33f/testify/require" "testing" ) From bebaaa8373208748f548fa95a19dd2fa7a48ba1f Mon Sep 17 00:00:00 2001 From: quobix Date: Wed, 25 Nov 2026 12:10:18 -0500 Subject: [PATCH 07/27] Read JSON Schema coordinates directly from the authored JSON --- datamodel/schema_node.go | 9 ++--- datamodel/spec_info_test.go | 14 +++++++ internal/jsonnode/jsonnode.go | 73 +++++++++++++++++++++++++++-------- 3 files changed, 74 insertions(+), 22 deletions(-) diff --git a/datamodel/schema_node.go b/datamodel/schema_node.go index 5c934bb4..a80625aa 100644 --- a/datamodel/schema_node.go +++ b/datamodel/schema_node.go @@ -18,12 +18,11 @@ import ( func DecodeSchemaNode(data []byte) (*yaml.Node, error) { var doc *yaml.Node if json.Valid(data) { - normalized := normalizeJSONForYAMLParser(data) - var node yaml.Node - if err := jsonnode.Unmarshal(normalized, &node); err != nil { - return nil, err + var ok bool + doc, ok = jsonnode.ParseJSON(data) + if !ok { + return nil, fmt.Errorf("invalid JSON schema document") } - doc = &node } else { decoder := yaml.NewDecoder(bytes.NewReader(data)) doc = new(yaml.Node) diff --git a/datamodel/spec_info_test.go b/datamodel/spec_info_test.go index 0993a1fe..0a072962 100644 --- a/datamodel/spec_info_test.go +++ b/datamodel/spec_info_test.go @@ -11,6 +11,7 @@ import ( "github.com/pb33f/go-yaml" "github.com/pb33f/libopenapi/utils" "github.com/pb33f/testify/assert" + "github.com/pb33f/testify/require" ) const ( @@ -545,6 +546,19 @@ func TestNormalizeJSONForYAMLParser_NoAllocation(t *testing.T) { // TestExtractSpecInfo_JSON_EscapedSlashes tests issue #479 // JSON files containing \/ (escaped forward slash) should parse correctly +func TestDecodeSchemaNodePreservesJSONColumns(t *testing.T) { + for _, value := range []string{`"a\/b"`, `"\uD83D\uDE00"`, `"🙂"`, `"\uD800"`, `"line\nend"`} { + input := `{"description":` + value + `,"minimum":2}` + doc, err := DecodeSchemaNode([]byte(input)) + require.NoError(t, err) + require.Equal(t, len([]rune(input))-1, doc.Content[0].Content[3].Column) + } + for _, input := range []string{"\ttrue", "{\"minimum\"\n:\t1e900}", "{\r\"maximum\":5}"} { + _, err := DecodeSchemaNode([]byte(input)) + require.NoError(t, err) + } +} + func TestExtractSpecInfo_JSON_EscapedSlashes(t *testing.T) { // Exact test case from issue #479 jsonWithEscapedSlash := `{"openapi":"3.0.0","info":{"title":"Escaped Slash Test","description":"This spec contains escaped forward slashes (\\/) that cause parsing issues","version":"1.0.0"},"paths":{"\/test":{"get":{"summary":"Test endpoint with escaped slashes","description":"The path \/test\/ contains escaped forward slashes","responses":{"200":{"description":"OK","content":{"application\/json":{"schema":{"type":"object","properties":{"url":{"type":"string","example":"https:\/\/example.com\/api\/test"},"path":{"type":"string","example":"\/users\/{id}\/profile"}}}}}}}}}}}` diff --git a/internal/jsonnode/jsonnode.go b/internal/jsonnode/jsonnode.go index 8d77d6c1..cfba6841 100644 --- a/internal/jsonnode/jsonnode.go +++ b/internal/jsonnode/jsonnode.go @@ -14,8 +14,10 @@ package jsonnode import ( + "bytes" "regexp" "strconv" + "unicode/utf16" "unicode/utf8" "github.com/pb33f/go-yaml" @@ -37,10 +39,11 @@ const ( var yamlStyleFloat = regexp.MustCompile(`^[-+]?(?:\.[0-9]+|[0-9]+(?:\.[0-9]*)?)(?:[eE][-+]?[0-9]+)?$`) type parser struct { - data []byte - pos int - line int // 1-based line of data[pos] - col int // 1-based column of data[pos], counted in characters as yaml counts them + jsonSyntax bool // accept JSON forms that YAML reads differently + data []byte + pos int + line int // 1-based line of data[pos] + col int // 1-based column of data[pos], counted in characters as yaml counts them depth int nodes []yaml.Node // slab the tree's nodes are allocated from @@ -63,8 +66,18 @@ func Unmarshal(data []byte, out *yaml.Node) error { // Parse returns the yaml document node yaml.Unmarshal produces for the JSON document in data, and true. // It returns false when data is not a JSON object whose yaml parse it reproduces exactly. func Parse(data []byte) (*yaml.Node, bool) { - p := parser{data: data, line: 1, col: 1} - if !p.skipSpace(false) || p.pos >= len(data) || data[p.pos] != '{' { + return parse(data, false) +} + +// ParseJSON builds a tree directly from authored JSON, including boolean roots, +// surrogate pairs, and JSON whitespace. Coordinates refer to the original bytes. +func ParseJSON(data []byte) (*yaml.Node, bool) { + return parse(data, true) +} + +func parse(data []byte, jsonSyntax bool) (*yaml.Node, bool) { + p := parser{data: data, line: 1, col: 1, jsonSyntax: jsonSyntax} + if !p.skipSpace(false) || p.pos >= len(data) || (!jsonSyntax && data[p.pos] != '{') { return nil, false } p.strs = make(map[string]string, 256) @@ -117,7 +130,7 @@ func (p *parser) skipSpace(inCollection bool) bool { p.pos++ p.col++ case '\t': - if !inCollection { + if !inCollection && !p.jsonSyntax { return false } p.pos++ @@ -128,10 +141,14 @@ func (p *parser) skipSpace(inCollection bool) bool { p.col = 1 case '\r': // yaml reads CR LF as one line break; a lone CR is declined. - if p.pos+1 >= len(p.data) || p.data[p.pos+1] != '\n' { + crlf := p.pos+1 < len(p.data) && p.data[p.pos+1] == '\n' + if !crlf && !p.jsonSyntax { return false } - p.pos += 2 + p.pos++ + if crlf { + p.pos++ + } p.line++ p.col = 1 default: @@ -166,7 +183,7 @@ func (p *parser) parseValue() (*yaml.Node, bool) { func (p *parser) parseCollection(kind yaml.Kind, tag string, closer byte) (*yaml.Node, bool) { p.depth++ - if p.depth > maxDepth { + if p.depth > maxDepth && (!p.jsonSyntax || p.depth > 10000) { return nil, false } node := p.newNode(kind, yaml.FlowStyle, tag) @@ -193,7 +210,7 @@ func (p *parser) parseCollection(kind yaml.Kind, tag string, closer byte) (*yaml return nil, false } // yaml only pairs a key with a colon on the same line. - if p.pos >= len(p.data) || p.data[p.pos] != ':' || p.line != keyLine { + if p.pos >= len(p.data) || p.data[p.pos] != ':' || (!p.jsonSyntax && p.line != keyLine) { return nil, false } p.pos++ @@ -272,7 +289,16 @@ func (p *parser) parseNumber() (*yaml.Node, bool) { i = skipDigits(p.data, i) } value := p.intern(p.data[start:i]) - node := p.newNode(yaml.ScalarNode, 0, numberTag(value)) + var tag string + if p.jsonSyntax { + tag = "!!int" + if bytes.IndexAny(p.data[start:i], ".eE") >= 0 { + tag = "!!float" + } + } else { + tag = numberTag(value) + } + node := p.newNode(yaml.ScalarNode, 0, tag) node.Value = value p.col += i - start p.pos = i @@ -337,7 +363,7 @@ func (p *parser) parseString() (*yaml.Node, bool) { if !p.decodeEscape() { return nil, false } - case c >= 0x20 && c < 0x7F: + case c >= 0x20 && (c < 0x7F || p.jsonSyntax && c == 0x7F): if escaped { p.buf = append(p.buf, c) } @@ -348,7 +374,7 @@ func (p *parser) parseString() (*yaml.Node, bool) { return nil, false default: r, size := utf8.DecodeRune(p.data[p.pos:]) - if !plainRune(r, size) { + if !plainRune(r, size) && (!p.jsonSyntax || size == 1) { return nil, false } if escaped { @@ -413,9 +439,22 @@ func (p *parser) decodeEscape() bool { } code = code<<4 | d } - // yaml rejects an escaped surrogate; the caller's yaml parse reports it. - if code >= 0xD800 && code <= 0xDFFF { - return false + if utf16.IsSurrogate(code) { + if !p.jsonSyntax { + return false + } + second := p.pos + 6 + decoded := utf8.RuneError + if second+6 <= len(p.data) && p.data[second] == '\\' && p.data[second+1] == 'u' { + if low, err := strconv.ParseUint(string(p.data[second+2:second+6]), 16, 16); err == nil { + decoded = utf16.DecodeRune(code, rune(low)) + } + } + if decoded != utf8.RuneError { + p.pos += 6 + p.col += 6 + } + code = decoded } p.buf = utf8.AppendRune(p.buf, code) p.pos += 6 From 9edea59bd142bc4d0898ac13e5b037d2ebb1f032 Mon Sep 17 00:00:00 2001 From: quobix Date: Wed, 25 Nov 2026 12:12:31 -0500 Subject: [PATCH 08/27] Round-trip native file paths and Windows drives through schema URIs --- jsonschema/collection.go | 3 ++- jsonschema/document.go | 6 +++--- jsonschema/loader_test.go | 24 +++++++++++++++++++++++- jsonschema/reference.go | 34 +++++++++++++++++++++++++++++++--- 4 files changed, 59 insertions(+), 8 deletions(-) diff --git a/jsonschema/collection.go b/jsonschema/collection.go index 82e4380c..de0f57f5 100644 --- a/jsonschema/collection.go +++ b/jsonschema/collection.go @@ -26,7 +26,8 @@ func LoadCollection(members map[string][]byte, directory string, config *datamod if config == nil { config = datamodel.NewDocumentConfiguration() } - base := &url.URL{Scheme: "file", Path: strings.TrimSuffix(filepath.ToSlash(absolute), "/") + "/"} + base := fileURL(absolute) + base.Path = strings.TrimSuffix(base.Path, "/") + "/" d := newDocument(config, base) for _, name := range slices.Sorted(maps.Keys(members)) { if !fs.ValidPath(name) || name == "." || strings.ContainsRune(name, '\\') { diff --git a/jsonschema/document.go b/jsonschema/document.go index 94569190..525271ec 100644 --- a/jsonschema/document.go +++ b/jsonschema/document.go @@ -145,12 +145,12 @@ func retrievalURI(source string, config *datamodel.DocumentConfiguration) (*url. source = filepath.Join(config.BasePath, source) } file, err := filepath.Abs(source) - return &url.URL{Scheme: "file", Path: filepath.ToSlash(file)}, err + return fileURL(file), err } func (d *Document) resourceID(uri *url.URL) string { - if uri.Scheme == "file" && d.base.Scheme == "file" { - if relative, err := filepath.Rel(d.base.Path, uri.Path); err == nil { + if uri.Scheme == "file" && d.base.Scheme == "file" && uri.Host == d.base.Host { + if relative, err := filepath.Rel(filePath(d.base), filePath(uri)); err == nil { name := filepath.ToSlash(relative) if uri.RawQuery != "" { name += "?" + uri.RawQuery diff --git a/jsonschema/loader_test.go b/jsonschema/loader_test.go index ae24d506..42554416 100644 --- a/jsonschema/loader_test.go +++ b/jsonschema/loader_test.go @@ -4,8 +4,13 @@ package jsonschema import ( - "github.com/pb33f/testify/require" + "net/url" + "os" + "path/filepath" "testing" + + "github.com/pb33f/libopenapi/datamodel" + "github.com/pb33f/testify/require" ) func TestLoadInputBoundaries(t *testing.T) { @@ -30,6 +35,23 @@ func TestLoadInputBoundaries(t *testing.T) { d.Release() } +func TestNativeFilePathsResolveThroughFileURIs(t *testing.T) { + dir := t.TempDir() + name := filepath.Join(dir, "my root.json") + want := filepath.Join(dir, "amount.json") + require.NoError(t, os.WriteFile(want, []byte("true"), 0o600)) + root := fileURL(name) + require.Equal(t, name, filePath(root)) + require.Equal(t, want, filePath(root.ResolveReference(&url.URL{Path: "amount.json"}))) + config := datamodel.NewDocumentConfiguration() + config.AllowFileReferences = true + doc, err := Load([]byte(`{"$ref":"amount.json"}`), name, config, true) + require.NoError(t, err) + defer doc.Release() + require.Len(t, doc.Sources, 2) + require.Same(t, doc.Sources["amount.json"].Node, doc.References[0].To) +} + func TestRelativeIDOmitsRetrievalCredentials(t *testing.T) { d, err := Load([]byte(`{"$id":"customer?version=2","$ref":"#"}`), "https://name:private@schemas.example.test/draft/root.json?token=secret", nil, true) require.NoError(t, err) diff --git a/jsonschema/reference.go b/jsonschema/reference.go index f5c0b86f..a7902383 100644 --- a/jsonschema/reference.go +++ b/jsonschema/reference.go @@ -13,6 +13,7 @@ import ( "os" "path/filepath" "regexp" + "runtime" "strconv" "strings" "time" @@ -22,6 +23,33 @@ import ( var anchorName = regexp.MustCompile(`^[A-Za-z_][-A-Za-z0-9._]*$`) +// File URLs have a leading slash before a Windows drive; native file paths do not. +func fileURL(filename string) *url.URL { + p := filepath.ToSlash(filename) + u := &url.URL{Scheme: "file", Path: p} + if runtime.GOOS == "windows" { + if strings.HasPrefix(p, "//") { + host, rest, _ := strings.Cut(p[2:], "/") + u.Host, u.Path = host, "/"+rest + } else if filepath.VolumeName(filename) != "" { + u.Path = "/" + p + } + } + return u +} + +func filePath(u *url.URL) string { + p := u.Path + if runtime.GOOS == "windows" { + if u.Host != "" && u.Host != "localhost" { + p = "//" + u.Host + p + } else if len(p) >= 3 && p[0] == '/' && p[2] == ':' { + p = p[1:] + } + } + return filepath.FromSlash(p) +} + func (d *Document) resolveReferences() error { for i := 0; i < len(d.References); i++ { ref := d.References[i] @@ -103,19 +131,19 @@ func (d *Document) resolve(address string) (*yaml.Node, error) { func (d *Document) read(uri *url.URL) ([]byte, error) { switch uri.Scheme { case "file": - if uri.Host != "" && uri.Host != "localhost" { + if uri.Host != "" && uri.Host != "localhost" && (runtime.GOOS != "windows" || d.base.Host != uri.Host) { return nil, fmt.Errorf("unsupported file URI host %q", uri.Host) } if !d.config.AllowFileReferences && d.config.BasePath == "" { return nil, fmt.Errorf("file references are disabled") } - filename := filepath.FromSlash(uri.Path) + filename := filePath(uri) if d.config.LocalFS == nil { return os.ReadFile(filename) } dir := d.config.BasePath if dir == "" { - dir = filepath.FromSlash(d.base.Path) + dir = filePath(d.base) } relative, err := filepath.Rel(dir, filename) if err != nil { From 9edd65924c8aaf4ba30cfeedac3f704e26e14863 Mon Sep 17 00:00:00 2001 From: quobix Date: Wed, 25 Nov 2026 12:12:31 -0500 Subject: [PATCH 09/27] Share typed JSON value identity with native schema comparisons --- utils/enum.go | 22 +++++++++++++++++----- utils/enum_test.go | 12 ++++++++++++ 2 files changed, 29 insertions(+), 5 deletions(-) diff --git a/utils/enum.go b/utils/enum.go index 7b9afc0e..b67a92b6 100644 --- a/utils/enum.go +++ b/utils/enum.go @@ -15,6 +15,22 @@ type enumValueIndex struct { active map[*yaml.Node]bool } +func newEnumValueIndex() enumValueIndex { + return enumValueIndex{values: make(map[string]int), nodes: make(map[*yaml.Node]int), active: make(map[*yaml.Node]bool)} +} + +// JSONValueIDs assigns equal IDs to equivalent JSON values within nodes. Object +// key order and equivalent JSON numbers do not affect equality. Zero marks a +// non-JSON value or a number outside the limits described by CheckEnumForDuplicates. +func JSONValueIDs(nodes []*yaml.Node) []int { + index := newEnumValueIndex() + ids := make([]int, len(nodes)) + for i, node := range nodes { + ids[i] = index.valueID(node) + } + return ids +} + // Bound arbitrary-precision parsing and the size of retained numeric keys. const ( maxEnumNumberLength = 1024 @@ -30,11 +46,7 @@ const ( func CheckEnumForDuplicates(seq []*yaml.Node) []*yaml.Node { var duplicates []*yaml.Node seen := make(map[int]bool) - index := enumValueIndex{ - values: make(map[string]int), - nodes: make(map[*yaml.Node]int), - active: make(map[*yaml.Node]bool), - } + index := newEnumValueIndex() for _, node := range seq { id := index.valueID(node) if id == 0 { diff --git a/utils/enum_test.go b/utils/enum_test.go index 916a9a69..ccbb6164 100644 --- a/utils/enum_test.go +++ b/utils/enum_test.go @@ -8,6 +8,18 @@ import ( "github.com/pb33f/testify/require" ) +func TestJSONValueIDs(t *testing.T) { + var doc yaml.Node + require.NoError(t, yaml.Unmarshal([]byte(`[1,"1",1.0,{"a":1,"b":2},{"b":2,"a":1},null]`), &doc)) + values := doc.Content[0].Content + ids := JSONValueIDs(append(values, nil)) + require.Equal(t, ids[0], ids[2]) + require.NotEqual(t, ids[0], ids[1]) + require.Equal(t, ids[3], ids[4]) + require.NotZero(t, ids[5]) + require.Zero(t, ids[6]) +} + func TestCheckEnumForDuplicates_OversizedNumbers(t *testing.T) { for _, tc := range []struct { name string From 6f24017fc1c1b1e065c54a454030548ac441b740 Mon Sep 17 00:00:00 2001 From: quobix Date: Wed, 25 Nov 2026 12:13:56 -0500 Subject: [PATCH 10/27] Recognize Draft 2020-12 keyword overrides in schema rules --- .../model/breaking_rules_config_test.go | 17 +++++++++++++++++ what-changed/model/breaking_rules_model.go | 6 ++++++ 2 files changed, 23 insertions(+) diff --git a/what-changed/model/breaking_rules_config_test.go b/what-changed/model/breaking_rules_config_test.go index 9b22f12a..9f40a4ef 100644 --- a/what-changed/model/breaking_rules_config_test.go +++ b/what-changed/model/breaking_rules_config_test.go @@ -4,12 +4,29 @@ package model import ( + "fmt" "testing" + "github.com/pb33f/go-yaml" "github.com/pb33f/testify/assert" "github.com/pb33f/testify/require" ) +func TestDraft2020SchemaRuleKeysRoundTrip(t *testing.T) { + for _, key := range []string{"$anchor", "$defs", "patternProperties", "dependentSchemas", "minContains", "maxContains"} { + t.Run(key, func(t *testing.T) { + input := []byte(fmt.Sprintf("schema:\n %s:\n modified: false\n", key)) + require.Nil(t, ValidateBreakingRulesConfigYAML(input)) + var config BreakingRulesConfig + require.NoError(t, yaml.Unmarshal(input, &config)) + rule := config.GetRule(CompSchema, key) + require.NotNil(t, rule) + require.NotNil(t, rule.Modified) + require.False(t, *rule.Modified) + }) + } +} + func TestValidateBreakingRulesConfigYAML_ValidConfig(t *testing.T) { yaml := ` schema: diff --git a/what-changed/model/breaking_rules_model.go b/what-changed/model/breaking_rules_model.go index 48d8787c..fdc2e90a 100644 --- a/what-changed/model/breaking_rules_model.go +++ b/what-changed/model/breaking_rules_model.go @@ -150,6 +150,12 @@ type HeaderRules struct { // SchemaRules defines breaking rules for the Schema object properties. type SchemaRules struct { + Anchor *BreakingChangeRule `json:"$anchor,omitempty" yaml:"$anchor,omitempty"` + Defs *BreakingChangeRule `json:"$defs,omitempty" yaml:"$defs,omitempty"` + PatternProperties *BreakingChangeRule `json:"patternProperties,omitempty" yaml:"patternProperties,omitempty"` + DependentSchemas *BreakingChangeRule `json:"dependentSchemas,omitempty" yaml:"dependentSchemas,omitempty"` + MinContains *BreakingChangeRule `json:"minContains,omitempty" yaml:"minContains,omitempty"` + MaxContains *BreakingChangeRule `json:"maxContains,omitempty" yaml:"maxContains,omitempty"` Ref *BreakingChangeRule `json:"$ref,omitempty" yaml:"$ref,omitempty"` Type *BreakingChangeRule `json:"type,omitempty" yaml:"type,omitempty"` Title *BreakingChangeRule `json:"title,omitempty" yaml:"title,omitempty"` From 3950faff57ec21cb59090dcaae241441a9d946be Mon Sep 17 00:00:00 2001 From: quobix Date: Wed, 25 Nov 2026 12:14:22 -0500 Subject: [PATCH 11/27] Validate native schema inputs against the bundled Draft 2020-12 meta-schema --- jsonschema/document.go | 3 +++ jsonschema/loader_test.go | 9 +++++++++ jsonschema/validation.go | 37 +++++++++++++++++++++++++++++++++++++ 3 files changed, 49 insertions(+) create mode 100644 jsonschema/validation.go diff --git a/jsonschema/document.go b/jsonschema/document.go index 525271ec..101b20e1 100644 --- a/jsonschema/document.go +++ b/jsonschema/document.go @@ -214,6 +214,9 @@ func (d *Document) addSource(data []byte, uri *url.URL, explicit bool) (*Resourc if err = d.indexSchema(source, root, uri, "", nil); err != nil { return nil, err } + if err := validateSource(root, data); err != nil { + return nil, fmt.Errorf("%s: %w", name, err) + } if err = d.register(uri.String(), root, source); err != nil { return nil, err } diff --git a/jsonschema/loader_test.go b/jsonschema/loader_test.go index 42554416..c4511821 100644 --- a/jsonschema/loader_test.go +++ b/jsonschema/loader_test.go @@ -35,6 +35,15 @@ func TestLoadInputBoundaries(t *testing.T) { d.Release() } +func TestInvalidConstraintsFailBeforeComparison(t *testing.T) { + for _, input := range []string{`{"type":42}`, `{"required":42}`, "minLength: -2", `{"properties":{"amount":{"multipleOf":0}}}`} { + _, err := Load([]byte(input), "bad.yaml", nil, true) + require.ErrorContains(t, err, "bad.yaml") + } + _, err := LoadCollection(map[string][]byte{"bad.json": []byte(`{"type":"invalid"}`)}, ".", nil) + require.ErrorContains(t, err, "bad.json") +} + func TestNativeFilePathsResolveThroughFileURIs(t *testing.T) { dir := t.TempDir() name := filepath.Join(dir, "my root.json") diff --git a/jsonschema/validation.go b/jsonschema/validation.go new file mode 100644 index 00000000..8fb691a3 --- /dev/null +++ b/jsonschema/validation.go @@ -0,0 +1,37 @@ +// Copyright 2026 Princess B33f Heavy Industries / Dave Shanley +// SPDX-License-Identifier: MIT + +package jsonschema + +import ( + "bytes" + "encoding/json" + "sync" + + "github.com/pb33f/go-yaml" + validator "github.com/pb33f/jsonschema/v6" + modeljson "github.com/pb33f/libopenapi/json" +) + +// The validator ships the draft and its vocabularies. Compiling it needs no network. +var draftMetaSchema = sync.OnceValue(func() *validator.Schema { + return validator.NewCompiler().MustCompile(Dialect) +}) + +func validateSource(root *yaml.Node, data []byte) error { + if root.Kind == yaml.ScalarNode { + return nil // indexSchema has already checked that this is a boolean. + } + var err error + if !json.Valid(data) { + data, err = modeljson.YAMLNodeToJSON(root, "") + if err != nil { + return err + } + } + value, err := validator.UnmarshalJSON(bytes.NewReader(data)) + if err != nil { + return err + } + return draftMetaSchema().Validate(value) +} From f924b1387e40356a1fb9a231eee818e133d70818 Mon Sep 17 00:00:00 2001 From: quobix Date: Wed, 25 Nov 2026 12:14:56 -0500 Subject: [PATCH 12/27] Classify authored schema edits across typed values and resolved uses --- jsonschema/compare.go | 340 +++++++++++++++++++++++---- jsonschema/compare_test.go | 119 ++++++++++ jsonschema/document.go | 34 +-- jsonschema/reference_changes.go | 189 +++++++++++++++ jsonschema/reference_changes_test.go | 145 ++++++++++++ 5 files changed, 770 insertions(+), 57 deletions(-) create mode 100644 jsonschema/compare_test.go create mode 100644 jsonschema/reference_changes.go create mode 100644 jsonschema/reference_changes_test.go diff --git a/jsonschema/compare.go b/jsonschema/compare.go index 4d9d5c16..6e3e7d9a 100644 --- a/jsonschema/compare.go +++ b/jsonschema/compare.go @@ -16,6 +16,7 @@ import ( "github.com/pb33f/go-yaml" "github.com/pb33f/libopenapi/datamodel/low" "github.com/pb33f/libopenapi/datamodel/low/base" + "github.com/pb33f/libopenapi/utils" wc "github.com/pb33f/libopenapi/what-changed/model" ) @@ -42,12 +43,15 @@ func Compare(left, right *Document, rules *wc.BreakingRulesConfig) (*wc.SchemaCh } type comparison struct { - inline map[*Resource]bool - pairs map[*Resource]*Resource - matched map[*Resource]bool - left, right *Document - rules *wc.BreakingRulesConfig - changes []*wc.Change + annotationOnly bool + originalUsage, modifiedUsage map[*yaml.Node]evaluationContext + appliedAdditions map[*Resource]bool + inline map[*Resource]bool + pairs map[*Resource]*Resource + matched map[*Resource]bool + left, right *Document + rules *wc.BreakingRulesConfig + changes []*wc.Change } // MatchResources pairs the original and modified resources by resolved ID, then @@ -106,6 +110,7 @@ func matchResources(left, right *Document) (map[*Resource]*Resource, map[*Resour func (c *comparison) resources() error { pairs, used := matchResources(c.left, c.right) c.pairs, c.matched = pairs, used + c.compareReferences() for _, l := range c.left.Resources { if c.inline[l] { continue @@ -126,24 +131,43 @@ func (c *comparison) resources() error { func (c *comparison) compareResource(l, r *Resource) error { if l == nil || r == nil { - c.membership(l, r, "$", "schema", nil, nil, true) + c.membership(l, r, "$", "schema", nil, nil, l != nil || c.appliedAdditions[r]) return nil } - return c.schema(l, r, l.Node, r.Node, "$", 1) + return c.schema(l, r, l.Node, r.Node, "$", "type", 1) } -func (c *comparison) schema(l, r *Resource, left, right *yaml.Node, path string, polarity int) error { +func (c *comparison) schema(l, r *Resource, left, right *yaml.Node, path, keyword string, polarity int) error { if sameNode(left, right) { return nil } + usage := c.originalUsage[left] | c.modifiedUsage[right] + if keyword == "contentSchema" || c.annotationOnly { + previous := c.annotationOnly + c.annotationOnly = usage == 0 + switch usage { + case positiveContext: + polarity = 1 + case negativeContext: + polarity = -1 + case mixedContext: + polarity = 0 + } + defer func() { c.annotationOnly = previous }() + } + polarity = combinedPolarity(polarity, usage) if left.Kind == yaml.ScalarNode || right.Kind == yaml.ScalarNode { if left.Kind == right.Kind && strings.EqualFold(left.Value, right.Value) { return nil } - breaking := !strings.EqualFold(left.Value, "false") && !strings.EqualFold(right.Value, "true") + a, b := left, right + if polarity < 0 { + a, b = right, left + } + breaking := polarity == 0 || !strings.EqualFold(a.Value, "false") && !strings.EqualFold(b.Value, "true") start := len(c.changes) wc.CreateChangeWithEncoding(&c.changes, wc.Modified, "schema", left, right, breaking, nil, nil) - c.finish(c.changes[start], l, r, path, "type", polarity, breaking) + c.finish(c.changes[start], l, r, path, keyword, 1, breaking) return nil } // The existing low model owns keyword semantics. Child schemas and references @@ -157,28 +181,33 @@ func (c *comparison) schema(l, r *Resource, left, right *yaml.Node, path string, return err } if diff := wc.CompareSchemas(lp, rp); diff != nil { + dependencies := make(map[*wc.Change]bool, len(diff.DependentRequiredChanges)) + for _, change := range diff.DependentRequiredChanges { + dependencies[change] = true + } for _, ch := range diff.GetAllChanges() { property := ch.Property if property == "schemaDialect" { property = "$schema" + ch.Property = property } editPath := PropertyPath(path, property) - for _, dep := range diff.DependentRequiredChanges { - if ch == dep { - editPath = PropertyPath(PropertyPath(path, "dependentRequired"), property) - if a, ok := ch.OriginalObject.([]string); ok { - value, _ := json.Marshal(a) - ch.OriginalEncoded = string(value) - } - if b, ok := ch.NewObject.([]string); ok { - value, _ := json.Marshal(b) - ch.NewEncoded = string(value) - } - property = "dependentRequired" - break + a, b := member(left, property), member(right, property) + if dependencies[ch] { + property = "dependentRequired" + editPath = PropertyPath(PropertyPath(path, property), ch.Property) + a, b = member(member(left, property), ch.Property), member(member(right, property), ch.Property) + ch.OriginalEncoded, ch.NewEncoded = encodedLiteral(a), encodedLiteral(b) + if a != nil && b != nil && equivalentConstraint(property, a, b) { + continue } } - c.finish(ch, l, r, editPath, property, polarity, compatibility(ch, property)) + breaking := compatibility(ch, property) + direction := polarity + if impact, ok := validationChange(property, a, b, polarity); ok { + direction, breaking = 1, impact + } + c.finish(ch, l, r, editPath, property, direction, breaking) c.changes = append(c.changes, ch) } } @@ -206,7 +235,32 @@ func (c *comparison) schema(l, r *Resource, left, right *yaml.Node, path string, if exactNumber(keyword) { breaking = compatibility(c.changes[start], keyword) } - c.finish(c.changes[start], l, r, PropertyPath(path, keyword), keyword, polarity, breaking) + direction := polarity + if impact, ok := validationChange(keyword, a, b, polarity); ok { + direction, breaking = 1, impact + } + c.finish(c.changes[start], l, r, PropertyPath(path, keyword), keyword, direction, breaking) + } + for _, keyword := range literalKeywords { + a, b := member(left, keyword), member(right, keyword) + if a == b { + continue + } + if keyword == "enum" { + c.compareEnum(l, r, path, a, b, polarity) + continue + } + if sameLiteral(a, b) { + continue + } + if keyword == "type" && a != nil && b != nil && equivalentConstraint(keyword, a, b) { + continue + } + breaking, _ := validationChange(keyword, a, b, polarity) + if keyword == "$vocabulary" { + breaking = true + } + c.recordValue(l, r, path, keyword, a, b, breaking) } c.compareAnnotations(l, r, left, right, path) return c.compareChildren(l, r, left, right, path, polarity) @@ -262,7 +316,7 @@ func constraintProxy(n *yaml.Node, r *Resource) (*base.SchemaProxy, error) { view.Content = make([]*yaml.Node, 0, len(n.Content)) for i := 0; i < len(n.Content); i += 2 { k := n.Content[i].Value - if nativeConstraint(k) { + if nativeConstraint(k) && !slices.Contains(literalKeywords[:], k) { view.Content = append(view.Content, n.Content[i:i+2]...) } } @@ -305,6 +359,196 @@ func sameNode(a, b *yaml.Node) bool { return true } +var literalKeywords = [...]string{"type", "enum", "const", "examples", "default", "$vocabulary"} + +// encodedLiteral retains typed values in report records and their hashes. +func encodedLiteral(n *yaml.Node) string { + if n == nil { + return "" + } + switch n.Kind { + case yaml.MappingNode: + fields := make([]string, 0, len(n.Content)/2) + for i := 0; i < len(n.Content); i += 2 { + key, _ := json.Marshal(n.Content[i].Value) + fields = append(fields, string(key)+":"+encodedLiteral(n.Content[i+1])) + } + slices.Sort(fields) + return "{" + strings.Join(fields, ",") + "}" + case yaml.SequenceNode: + values := make([]string, 0, len(n.Content)) + for _, child := range n.Content { + values = append(values, encodedLiteral(child)) + } + return "[" + strings.Join(values, ",") + "]" + } + switch n.ShortTag() { + case "!!int", "!!float": + return n.Value + case "!!null": + return "null" + case "!!bool": + return strings.ToLower(n.Value) + } + quoted, _ := json.Marshal(n.Value) + return string(quoted) +} + +func (c *comparison) recordValue(l, r *Resource, path, keyword string, a, b *yaml.Node, breaking bool) { + kind := wc.Modified + if a == nil { + kind = wc.PropertyAdded + } else if b == nil { + kind = wc.PropertyRemoved + } + wc.CreateChange(&c.changes, kind, keyword, a, b, breaking, nil, nil) + ch := c.changes[len(c.changes)-1] + ch.OriginalEncoded, ch.NewEncoded = encodedLiteral(a), encodedLiteral(b) + c.finish(ch, l, r, PropertyPath(path, keyword), keyword, 1, breaking) +} + +func (c *comparison) compareEnum(l, r *Resource, path string, a, b *yaml.Node, polarity int) { + var values []*yaml.Node + if a != nil { + values = append(values, a.Content...) + } + boundary := len(values) + if b != nil { + values = append(values, b.Content...) + } + if len(values) == 0 { + if (a == nil) != (b == nil) { + c.recordValue(l, r, path, "enum", a, b, polarity == 0 || (polarity > 0) == (a == nil)) + } + return + } + ids := literalIDs(values) + old, current := make(map[int]bool, boundary), make(map[int]bool, len(values)-boundary) + for i, id := range ids { + if i < boundary { + old[id] = true + } else { + current[id] = true + } + } + for i, id := range ids { + if i < boundary && !current[id] { + // Removing an entire enum relaxes its constraint; removing one choice narrows it. + c.recordValue(l, r, path, "enum", values[i], nil, polarity == 0 || (polarity > 0) == (b != nil)) + current[id] = true + } + if i >= boundary && !old[id] { + c.recordValue(l, r, path, "enum", nil, values[i], polarity == 0 || (polarity > 0) == (a == nil)) + old[id] = true + } + } +} + +func sameLiteral(a, b *yaml.Node) bool { + if a == nil || b == nil { + return a == b + } + ids := literalIDs([]*yaml.Node{a, b}) + return ids[0] == ids[1] +} + +func literalIDs(nodes []*yaml.Node) []int { + ids := utils.JSONValueIDs(nodes) + var fallback map[string]int + for i, id := range ids { + if id != 0 { + continue + } + // The shared interner bounds arbitrary-precision arithmetic. Keep distinct + // out-of-range literals distinguishable without expanding their exponents. + if fallback == nil { + fallback = make(map[string]int) + } + wire := encodedLiteral(nodes[i]) + if fallback[wire] == 0 { + fallback[wire] = -len(fallback) - 1 + } + ids[i] = fallback[wire] + } + return ids +} + +func typeAllows(n *yaml.Node, typ string) bool { + if n == nil { + return true + } + if n.Kind == yaml.SequenceNode { + return slices.ContainsFunc(n.Content, func(item *yaml.Node) bool { return typeAllows(item, typ) }) + } + return n.Value == typ || n.Value == "number" && typ == "integer" +} + +func equivalentConstraint(keyword string, a, b *yaml.Node) bool { + forward, _ := validationChange(keyword, a, b, 1) + reverse, _ := validationChange(keyword, b, a, 1) + return !forward && !reverse +} + +// validationChange checks whether b rejects values accepted by a. Reversing the +// operands gives the dual check inside not. Other keywords use their native rule. +func validationChange(keyword string, a, b *yaml.Node, polarity int) (breaking, handled bool) { + if polarity < 0 { + a, b = b, a + } + switch keyword { + case "type": + for _, typ := range []string{"integer", "number", "object", "array", "string", "null", "boolean"} { + if typeAllows(a, typ) && !typeAllows(b, typ) { + return true, true + } + } + case "const", "pattern": + breaking = b != nil + case "uniqueItems": + unique := func(n *yaml.Node) bool { return n != nil && strings.EqualFold(n.Value, "true") } + breaking = unique(b) && !unique(a) + case "dependentRequired": + if b != nil { + for _, req := range b.Content { + if a == nil || !slices.ContainsFunc(a.Content, func(item *yaml.Node) bool { return item.Value == req.Value }) { + return true, true + } + } + } + case "multipleOf": + if a == nil || b == nil { + return polarity == 0 || b != nil, true + } + x, ok1 := new(big.Rat).SetString(a.Value) + y, ok2 := new(big.Rat).SetString(b.Value) + breaking = !ok1 || !ok2 || y.Sign() == 0 || !x.Quo(x, y).IsInt() + default: + return false, false + } + return polarity == 0 || breaking, true +} + +func childMembership(keyword string, whole, added bool, polarity int) bool { + if keyword == "contentSchema" { + return false + } + if keyword == "$defs" { + return !added + } + if polarity == 0 { + return true + } + switch keyword { + case "anyOf": + // Adding the first disjunction restricts the schema. Adding an + // alternative to an existing disjunction widens it. + return (whole == added) == (polarity > 0) + case "allOf", "dependentSchemas": + return added == (polarity > 0) + } + return true +} + func exactNumber(k string) bool { switch k { case "minimum", "maximum", "exclusiveMinimum", "exclusiveMaximum", "multipleOf", "minContains", "maxContains": @@ -371,18 +615,29 @@ func (c *comparison) compareChildren(l, r *Resource, left, right *yaml.Node, pat if owner := c.left.schemas[a]; owner != l && c.pairs[owner] == nil { continue } - c.membership(l, r, p, k.keyword, a, nil, true) + breaking := childMembership(k.keyword, member(right, k.keyword) == nil, false, polarity) + c.membership(l, r, p, k.keyword, a, nil, breaking) continue } - if err := c.compareChild(l, r, a, b, p, k.keyword, polarity); err != nil { + direction := polarity + if k.keyword == "contains" && (member(left, "maxContains") != nil || member(right, "maxContains") != nil) { + direction = 0 + } + if err := c.compareChild(l, r, a, b, p, k.keyword, direction); err != nil { return err } } for k, b := range newNodes { + breaking := childMembership(k.keyword, member(left, k.keyword) == nil, true, polarity) if owner := c.right.schemas[b]; owner != r && !c.matched[owner] { + if breaking && !c.annotationOnly { + if c.appliedAdditions == nil { + c.appliedAdditions = make(map[*Resource]bool) + } + c.appliedAdditions[owner] = true + } continue } - breaking := k.keyword != "$defs" && k.keyword != "anyOf" c.membership(l, r, childPath(path, k), k.keyword, nil, b, breaking) } return nil @@ -400,7 +655,7 @@ func (c *comparison) compareChild(l, r *Resource, a, b *yaml.Node, path, keyword lo, ro := c.left.schemas[a], c.right.schemas[b] switch { case lo == l && ro == r: - return c.schema(l, r, a, b, path, polarity) + return c.schema(l, r, a, b, path, keyword, polarity) case lo != l && ro != r: if c.pairs[lo] != ro && (c.pairs[lo] != nil || c.matched[ro]) { wc.CreateChange(&c.changes, wc.Modified, keyword, member(a, "$id"), member(b, "$id"), true, nil, nil) @@ -409,13 +664,13 @@ func (c *comparison) compareChild(l, r *Resource, a, b *yaml.Node, path, keyword case lo == l && !c.matched[ro]: // An inline schema acquired its first $id. Its constraints now belong to the new resource. c.matched[ro] = true - return c.schema(l, ro, a, b, "$", polarity) + return c.schema(l, ro, a, b, "$", keyword, polarity) case ro == r && c.pairs[lo] == nil: if c.inline == nil { c.inline = make(map[*Resource]bool) } c.inline[lo] = true - return c.schema(lo, r, a, b, path, polarity) + return c.schema(lo, r, a, b, path, keyword, polarity) default: // A matched resource moved to or from an existing inline use. wc.CreateChangeWithEncoding(&c.changes, wc.Modified, keyword, a, b, true, nil, nil) @@ -453,7 +708,6 @@ func childPath(path string, k childKey) string { func (c *comparison) membership(l, r *Resource, path, kw string, a, b *yaml.Node, breaking bool) { if l == nil && b == nil { b = r.Node - breaking = false } if r == nil && a == nil { a = l.Node @@ -532,16 +786,16 @@ func (c *comparison) finish(ch *wc.Change, l, r *Resource, path, property string breaking = true } } + if c.annotationOnly || property == "contentSchema" { + breaking = false + } if c.rules != nil { - if rule := c.rules.GetRule(wc.CompSchema, property); rule != nil { - override := rule.Modified - switch ch.ChangeType { - case wc.PropertyAdded, wc.ObjectAdded: - override = rule.Added - case wc.PropertyRemoved, wc.ObjectRemoved: - override = rule.Removed - } - if override != nil { + ruleKey := property + if property == "$schema" { + ruleKey = wc.PropSchemaDialect + } + if rule := c.rules.GetRule(wc.CompSchema, ruleKey); rule != nil { + if override := operationRule(rule, ch.ChangeType); override != nil { breaking = *override } } diff --git a/jsonschema/compare_test.go b/jsonschema/compare_test.go new file mode 100644 index 00000000..dda0a29a --- /dev/null +++ b/jsonschema/compare_test.go @@ -0,0 +1,119 @@ +// Copyright 2026 Princess B33f Heavy Industries / Dave Shanley +// SPDX-License-Identifier: MIT + +package jsonschema + +import ( + "testing" + + wc "github.com/pb33f/libopenapi/what-changed/model" + "github.com/pb33f/testify/require" +) + +func TestNativeValidationDirections(t *testing.T) { + for _, tc := range []struct { + name, old, current string + forward, reverse int + }{ + {"first type", `{}`, `{"type":"string"}`, 1, 0}, + {"integer to number", `{"type":"integer"}`, `{"type":"number"}`, 0, 1}, + {"disjoint type", `{"type":"string"}`, `{"type":"boolean"}`, 1, 1}, + {"type union", `{"type":["number","object"]}`, `{"type":["integer","object"]}`, 1, 0}, + {"new const", `{}`, `{"const":"blue"}`, 1, 0}, + {"const type", `{"const":1}`, `{"const":"1"}`, 1, 1}, + {"pattern", `{}`, `{"pattern":"^(usd|cad)$"}`, 1, 0}, + {"unique array", `{}`, `{"uniqueItems":true}`, 1, 0}, + {"nonunique default", `{}`, `{"uniqueItems":false}`, 0, 0}, + {"unique switch", `{"uniqueItems":false}`, `{"uniqueItems":true}`, 1, 0}, + {"new multiple", `{}`, `{"multipleOf":0.25}`, 1, 0}, + {"divisible multiple", `{"multipleOf":0.25}`, `{"multipleOf":1.5}`, 1, 0}, + {"incomparable multiple", `{"multipleOf":0.25}`, `{"multipleOf":0.3}`, 1, 1}, + {"new dependency", `{}`, `{"dependentRequired":{"a":["b"]}}`, 1, 0}, + {"added dependency", `{"dependentRequired":{"a":["b"]}}`, `{"dependentRequired":{"a":["b","c"]}}`, 1, 0}, + {"swapped dependency", `{"dependentRequired":{"a":["b"]}}`, `{"dependentRequired":{"a":["c"]}}`, 1, 1}, + {"first anyOf", `{}`, `{"anyOf":[{"type":"number"}]}`, 1, 0}, + {"another anyOf", `{"anyOf":[{"type":"number"}]}`, `{"anyOf":[{"type":"number"},{"type":"string"}]}`, 0, 1}, + {"first negated anyOf", `{"not":{}}`, `{"not":{"anyOf":[{"type":"number"}]}}`, 0, 1}, + {"additional negated anyOf", `{"not":{"anyOf":[{"type":"number"}]}}`, `{"not":{"anyOf":[{"type":"number"},{"type":"string"}]}}`, 1, 0}, + {"negated type", `{"not":{}}`, `{"not":{"type":"string"}}`, 0, 1}, + {"negated dependency", `{"not":{"dependentRequired":{"a":["b"]}}}`, `{"not":{"dependentRequired":{"a":["b","c"]}}}`, 0, 1}, + {"content annotation", `{"contentSchema":{"minLength":4}}`, `{"contentSchema":{"minLength":7}}`, 0, 0}, + {"referenced content schema", `{"contentSchema":{"minLength":4},"$ref":"#/contentSchema"}`, `{"contentSchema":{"minLength":7},"$ref":"#/contentSchema"}`, 1, 0}, + {"negated reference to content schema", `{"contentSchema":{"minLength":4},"not":{"$ref":"#/contentSchema"}}`, `{"contentSchema":{"minLength":7},"not":{"$ref":"#/contentSchema"}}`, 0, 1}, + {"content field addition", `{}`, `{"contentSchema":{"type":"string"}}`, 0, 0}, + {"bounded contains", `{"contains":{"minLength":2},"maxContains":1}`, `{"contains":{"minLength":4},"maxContains":1}`, 1, 1}, + {"new applied resource", `{}`, `{"properties":{"x":{"$id":"urn:field","type":"string"}}}`, 1, 1}, + {"new unused definition", `{}`, `{"$defs":{"x":{"$id":"urn:field","type":"string"}}}`, 0, 1}, + } { + t.Run(tc.name, func(t *testing.T) { + a, b := loadTest(t, tc.old), loadTest(t, tc.current) + for i, sides := range [][2]*Document{{a, b}, {b, a}} { + changes, err := Compare(sides[0], sides[1], nil) + require.NoError(t, err) + require.NotNil(t, changes) + require.Equal(t, 1, changes.TotalChanges()) + want := []int{tc.forward, tc.reverse}[i] + require.Equal(t, want, changes.TotalBreakingChanges(), "direction %d", i) + } + }) + } +} + +func TestNativeLiteralValues(t *testing.T) { + for _, tc := range []struct { + name, key, old, current string + want, breaking int + }{ + {"reordered types", "type", `["array","string"]`, `["string","array"]`, 0, 0}, + {"enum scalar type", "enum", `[1]`, `["1"]`, 2, 1}, + {"enum object", "enum", `[{"id":1}]`, `[{"id":2}]`, 2, 1}, + {"enum array", "enum", `[[1,2]]`, `[[2,1]]`, 2, 1}, + {"enum boolean and string", "enum", `[true,"false"]`, `[true,false]`, 2, 1}, + {"enum canonical equality", "enum", `[{"x":1,"y":true}, 1.00]`, `[1e0,{"y":true,"x":1.0}]`, 0, 0}, + {"object const", "const", `{"id":1}`, `{"id":"1"}`, 1, 1}, + {"structured examples", "examples", `[{"count":1}]`, `[{"count":2}]`, 1, 0}, + {"vocabulary", "$vocabulary", `{"urn:foo":false}`, `{"urn:bar":false}`, 1, 1}, + {"type array", "type", `["object","string"]`, `["array","string"]`, 1, 1}, + } { + t.Run(tc.name, func(t *testing.T) { + left, right := loadTest(t, `{"`+tc.key+`":`+tc.old+`}`), loadTest(t, `{"`+tc.key+`":`+tc.current+`}`) + for _, pair := range [][2]*Document{{left, right}, {right, left}} { + changes, err := Compare(pair[0], pair[1], nil) + require.NoError(t, err) + if tc.want == 0 { + require.Nil(t, changes) + continue + } + require.NotNil(t, changes) + require.Equal(t, tc.want, changes.TotalChanges()) + require.Equal(t, tc.breaking, changes.TotalBreakingChanges()) + for _, ch := range changes.GetAllChanges() { + require.Equal(t, tc.key, ch.Property) + if ch.ChangeType != wc.PropertyAdded { + require.NotEmpty(t, ch.OriginalEncoded) + } + if ch.ChangeType != wc.PropertyRemoved { + require.NotEmpty(t, ch.NewEncoded) + } + } + } + }) + } +} + +func TestNativeKeywordPolicyOverrides(t *testing.T) { + cfg := &wc.BreakingRulesConfig{Schema: &wc.SchemaRules{ + SchemaDialect: &wc.BreakingChangeRule{Added: new(false), Removed: new(false)}, + AdditionalProperties: &wc.BreakingChangeRule{Modified: new(false)}, + }} + for _, tc := range [][2]string{{`{}`, `{"$schema":"` + Dialect + `"}`}, {`{"additionalProperties":true}`, `{"additionalProperties":false}`}} { + a, b := loadTest(t, tc[0]), loadTest(t, tc[1]) + for _, pair := range [][2]*Document{{a, b}, {b, a}} { + changes, err := Compare(pair[0], pair[1], cfg) + require.NoError(t, err) + require.NotNil(t, changes) + require.Equal(t, 1, changes.TotalChanges()) + require.Zero(t, changes.TotalBreakingChanges()) + } + } +} diff --git a/jsonschema/document.go b/jsonschema/document.go index 101b20e1..4a59a644 100644 --- a/jsonschema/document.go +++ b/jsonschema/document.go @@ -62,19 +62,22 @@ type Reference struct { // Keyword identifies the authored $ref or $dynamicRef. Keyword string address string + context evaluationContext } // Document owns the resources and source locations for a comparison input. type Document struct { - Root *Resource - Resources []*Resource - Sources map[string]*Source - References []Reference - Rolodex *index.Rolodex - addresses map[string]*yaml.Node - schemas map[*yaml.Node]*Resource - config *datamodel.DocumentConfiguration - base *url.URL + Root *Resource + Resources []*Resource + Sources map[string]*Source + References []Reference + Rolodex *index.Rolodex + addresses map[string]*yaml.Node + schemas map[*yaml.Node]*Resource + schemaPointers map[*yaml.Node]string + hasAdverseContext bool + config *datamodel.DocumentConfiguration + base *url.URL } // Load reads one root and all its referenced resources using the supplied source configuration. @@ -101,7 +104,7 @@ func Load(data []byte, source string, config *datamodel.DocumentConfiguration, e } func newDocument(config *datamodel.DocumentConfiguration, base *url.URL) *Document { - return &Document{config: config, base: base, Sources: make(map[string]*Source), addresses: make(map[string]*yaml.Node), schemas: make(map[*yaml.Node]*Resource), Rolodex: index.NewRolodex(index.CreateClosedAPIIndexConfig())} + return &Document{config: config, base: base, Sources: make(map[string]*Source), addresses: make(map[string]*yaml.Node), schemas: make(map[*yaml.Node]*Resource), schemaPointers: make(map[*yaml.Node]string), Rolodex: index.NewRolodex(index.CreateClosedAPIIndexConfig())} } // IsSchema reports whether a node occupies a schema-bearing position in this input. @@ -211,7 +214,7 @@ func (d *Document) addSource(data []byte, uri *url.URL, explicit bool) (*Resourc } else { d.Rolodex.AddIndex(idx) } - if err = d.indexSchema(source, root, uri, "", nil); err != nil { + if err = d.indexSchema(source, root, uri, "", nil, positiveContext); err != nil { return nil, err } if err := validateSource(root, data); err != nil { @@ -255,7 +258,7 @@ func (d *Document) register(address string, node *yaml.Node, source *Source) err return nil } -func (d *Document) indexSchema(source *Source, node *yaml.Node, base *url.URL, pointer string, r *Resource) error { +func (d *Document) indexSchema(source *Source, node *yaml.Node, base *url.URL, pointer string, r *Resource, evaluation evaluationContext) error { if node.Kind != yaml.MappingNode && !(node.Kind == yaml.ScalarNode && node.Tag == "!!bool") { return fmt.Errorf("%s:%d: schema must be an object or boolean", source.Name, node.Line) } @@ -292,6 +295,7 @@ func (d *Document) indexSchema(source *Source, node *yaml.Node, base *url.URL, p base = resolved } if r == nil || id != nil { + evaluation |= positiveContext identity := source.relative if id != nil { identity = d.resourceID(base) @@ -313,6 +317,8 @@ func (d *Document) indexSchema(source *Source, node *yaml.Node, base *url.URL, p } } d.schemas[node] = r + d.schemaPointers[node] = pointer[len(r.Pointer):] + d.hasAdverseContext = d.hasAdverseContext || evaluation != positiveContext for _, key := range []string{"$anchor", "$dynamicAnchor"} { if value := member(node, key); value != nil { if value.Tag != "!!str" || !anchorName.MatchString(value.Value) { @@ -331,7 +337,7 @@ func (d *Document) indexSchema(source *Source, node *yaml.Node, base *url.URL, p if value.Tag != "!!str" || err != nil { return fmt.Errorf("%s:%d: invalid %s %q", source.Name, value.Line, keyword, value.Value) } - d.References = append(d.References, Reference{From: node, Value: value.Value, address: target.String(), Keyword: keyword}) + d.References = append(d.References, Reference{From: node, Value: value.Value, address: target.String(), Keyword: keyword, context: evaluation}) } } return children(node, func(keyword, key string, child *yaml.Node) error { @@ -339,7 +345,7 @@ func (d *Document) indexSchema(source *Source, node *yaml.Node, base *url.URL, p if childKind(keyword) != singleSchema { childPointer += "/" + escapePointer(key) } - return d.indexSchema(source, child, base, childPointer, r) + return d.indexSchema(source, child, base, childPointer, r, evaluation.child(node, keyword)) }) } diff --git a/jsonschema/reference_changes.go b/jsonschema/reference_changes.go new file mode 100644 index 00000000..1880656e --- /dev/null +++ b/jsonschema/reference_changes.go @@ -0,0 +1,189 @@ +// Copyright 2026 Princess B33f Heavy Industries / Dave Shanley +// SPDX-License-Identifier: MIT + +package jsonschema + +import ( + "net/url" + "strings" + + "github.com/pb33f/go-yaml" + wc "github.com/pb33f/libopenapi/what-changed/model" +) + +// A target can be evaluated both normally and under negation. Keep both +// possibilities when independent entry points or a reference cycle reach it. +type evaluationContext uint8 + +const ( + positiveContext evaluationContext = 1 << iota + negativeContext + mixedContext = positiveContext | negativeContext +) + +func (ctx evaluationContext) child(parent *yaml.Node, keyword string) evaluationContext { + if ctx == 0 || keyword == "contentSchema" { + return 0 + } + switch keyword { + case "$defs": + return positiveContext + case "not": + return (ctx&positiveContext)<<1 | (ctx&negativeContext)>>1 + case "oneOf", "if": + return mixedContext + case "contains": + if member(parent, "maxContains") != nil { + return mixedContext + } + } + return ctx +} + +func combinedPolarity(polarity int, usage evaluationContext) int { + if polarity > 0 && usage&negativeContext != 0 || polarity < 0 && usage&positiveContext != 0 { + return 0 + } + return polarity +} + +// Trace evaluation contexts, never schema comparisons, through reference +// edges. Each schema enters the work list at most once for each polarity. +func (d *Document) referenceUsage() map[*yaml.Node]evaluationContext { + if !d.hasAdverseContext || len(d.References) == 0 { + return nil + } + uses := make(map[*yaml.Node]evaluationContext) + outgoing := make(map[*yaml.Node][]*yaml.Node, len(d.References)) + type work struct { + node *yaml.Node + context evaluationContext + } + var pending []work + visit := func(node *yaml.Node, ctx evaluationContext) { + delta := ctx &^ uses[node] + if delta != 0 { + uses[node] |= delta + pending = append(pending, work{node, delta}) + } + } + for _, ref := range d.References { + outgoing[ref.From] = append(outgoing[ref.From], ref.To) + visit(ref.To, ref.context) + } + for len(pending) > 0 { + step := pending[len(pending)-1] + pending = pending[:len(pending)-1] + for _, target := range outgoing[step.node] { + visit(target, step.context) + } + _ = children(step.node, func(keyword, _ string, child *yaml.Node) error { + // Declarations and content annotations do not evaluate their children here. + if keyword != "$defs" && keyword != "contentSchema" { + visit(child, step.context.child(step.node, keyword)) + } + return nil + }) + } + return uses +} + +func (c *comparison) compareReferences() { + c.originalUsage, c.modifiedUsage = c.left.referenceUsage(), c.right.referenceUsage() + if len(c.left.References) == 0 || len(c.right.References) == 0 { + return + } + type site struct { + owner *Resource + pointer, keyword string + } + current := make(map[site]*Reference, len(c.right.References)) + for i := range c.right.References { + ref := &c.right.References[i] + current[site{c.right.schemas[ref.From], c.right.schemaPointers[ref.From], ref.Keyword}] = ref + } + var byFile map[site]*Reference + for _, before := range c.left.References { + owner := c.left.schemas[before.From] + key := site{c.pairs[owner], c.left.schemaPointers[before.From], before.Keyword} + after := current[key] + if after == nil && (len(c.pairs) != len(c.left.Resources) || len(c.pairs) != len(c.right.Resources)) { + // Adding or dropping an embedded $id can change the base at an + // otherwise unchanged reference site. + if byFile == nil { + byFile = make(map[site]*Reference, len(c.right.References)) + for i := range c.right.References { + ref := &c.right.References[i] + r := c.right.schemas[ref.From] + byFile[site{c.right.schemas[r.Source.Node], r.Pointer + c.right.schemaPointers[ref.From], ref.Keyword}] = ref + } + } + file := c.pairs[c.left.schemas[owner.Source.Node]] + candidate := byFile[site{file, owner.Pointer + key.pointer, key.keyword}] + if candidate != nil && c.sameTarget(before.From, candidate.From) { + after = candidate + key.owner, key.pointer = c.right.schemas[after.From], c.right.schemaPointers[after.From] + } + } + // The regular keyword comparison reports edits to the authored text. + if after == nil || before.Value != after.Value || c.sameTarget(before.To, after.To) { + continue + } + a, b := member(before.From, before.Keyword), member(after.From, after.Keyword) + wc.CreateChange(&c.changes, wc.Modified, before.Keyword, a, b, true, nil, nil) + change := c.changes[len(c.changes)-1] + change.Reference = before.Value + change.Original = c.left.targetAddress(before.To) + change.New = c.right.targetAddress(after.To) + evaluating := before.context | after.context | c.originalUsage[before.From] | c.modifiedUsage[after.From] + c.finish(change, owner, key.owner, PropertyPath(schemaPointerPath(key.pointer), key.keyword), key.keyword, 1, evaluating != 0) + } +} + +func (c *comparison) sameTarget(a, b *yaml.Node) bool { + old, current := c.left.schemas[a], c.right.schemas[b] + oldPointer, newPointer := c.left.schemaPointers[a], c.right.schemaPointers[b] + if c.pairs[old] == current { + return oldPointer == newPointer + } + // An inline target can acquire or lose its own $id at the same location. + // A matched resource that moved to this slot still has a different identity. + if c.pairs[old] != nil && c.matched[current] { + return false + } + return c.pairs[c.left.schemas[old.Source.Node]] == c.right.schemas[current.Source.Node] && + old.Pointer+oldPointer == current.Pointer+newPointer +} + +func (d *Document) targetAddress(node *yaml.Node) string { + id := d.schemas[node].ID + if pointer := d.schemaPointers[node]; pointer != "" { + return id + "#" + (&url.URL{Fragment: pointer}).EscapedFragment() + } + return id +} + +// Convert a schema-bearing pointer to a JSONPath. A property named "0" is +// an object key, while a prefixItems slot is an array index. +func schemaPointerPath(pointer string) string { + path := "$" + if pointer == "" { + return path + } + var container int + for part := range strings.SplitSeq(strings.TrimPrefix(pointer, "/"), "/") { + key := strings.ReplaceAll(strings.ReplaceAll(part, "~1", "/"), "~0", "~") + switch container { + case schemaList: + path += "[" + key + "]" + container = 0 + case schemaMap: + path = PropertyPath(path, key) + container = 0 + default: + path = PropertyPath(path, key) + container = childKind(key) + } + } + return path +} diff --git a/jsonschema/reference_changes_test.go b/jsonschema/reference_changes_test.go new file mode 100644 index 00000000..fe2c2d38 --- /dev/null +++ b/jsonschema/reference_changes_test.go @@ -0,0 +1,145 @@ +// Copyright 2026 Princess B33f Heavy Industries / Dave Shanley +// SPDX-License-Identifier: MIT + +package jsonschema + +import ( + "fmt" + "strings" + "testing" + + wc "github.com/pb33f/libopenapi/what-changed/model" + "github.com/pb33f/testify/require" +) + +func TestUnchangedReferenceRetargetsAfterResourceMoves(t *testing.T) { + snapshot := func(a, b string) *Document { + return loadMembers(t, t.TempDir(), map[string][]byte{ + "a.yml": []byte("$id: " + a + "\nproperties: {x: true}"), + "b.yml": []byte("$id: " + b + "\nproperties: {x: true}"), + "use.yml": []byte("prefixItems:\n - properties:\n '0':\n $ref: a.yml#/properties/x"), + }) + } + left := snapshot("urn:one", "urn:two") + right := snapshot("urn:two", "urn:one") + changes, err := Compare(left, right, nil) + require.NoError(t, err) + require.NotNil(t, changes) + require.Len(t, changes.GetAllChanges(), 1) + c := changes.GetAllChanges()[0] + require.Equal(t, "use.yml", c.SchemaResource) + require.Equal(t, `$.prefixItems[0].properties["0"]["$ref"]`, c.Path) + require.Equal(t, "$ref", c.Property) + require.Equal(t, "urn:one#/properties/x", c.Original) + require.Equal(t, "urn:two#/properties/x", c.New) + require.Equal(t, "a.yml#/properties/x", c.Reference) + require.True(t, c.Breaking) + require.Equal(t, 4, *c.Context.OriginalLine) + require.Equal(t, "use.yml", c.Context.ModifiedDocument) +} + +func TestReferenceAnchorRetarget(t *testing.T) { + snapshot := func(a, b string) *Document { + return loadMembers(t, t.TempDir(), map[string][]byte{ + "owner.yml": []byte("$id: urn:owner\n$defs:\n 'a/b': {$anchor: " + a + "}\n b: {$anchor: " + b + "}"), + "use.yml": []byte("$dynamicRef: urn:owner#entry"), + }) + } + changes, err := Compare(snapshot("entry", "other"), snapshot("other", "entry"), nil) + require.NoError(t, err) + var ref *wc.Change + for _, change := range changes.GetAllChanges() { + if change.Property == "$dynamicRef" { + require.Nil(t, ref) + ref = change + } + } + require.NotNil(t, ref) + require.Equal(t, "urn:owner#/$defs/a~1b", ref.Original) + require.Equal(t, "urn:owner#/$defs/b", ref.New) + require.True(t, ref.Breaking) +} + +func TestReferenceSurvivesInlineResourceBoundary(t *testing.T) { + before := loadTest(t, `{"$defs":{"v":{"type":"string"}},"$ref":"#/$defs/v"}`) + after := loadTest(t, `{"$defs":{"v":{"$id":"urn:v","type":"string"}},"$ref":"#/$defs/v"}`) + for _, pair := range [][2]*Document{{before, after}, {after, before}} { + changes, err := Compare(pair[0], pair[1], nil) + require.NoError(t, err) + require.Len(t, changes.GetAllChanges(), 1) + require.Equal(t, "$id", changes.GetAllChanges()[0].Property) + } +} + +func TestUnchangedReferenceRetargetsAtNewEmbeddedBase(t *testing.T) { + snapshot := func(id string) *Document { + return loadMembers(t, t.TempDir(), map[string][]byte{ + "source.yml": []byte("properties:\n use:\n $ref: target.yml" + id), + "target.yml": []byte("$id: urn:first"), + "dir/target.yml": []byte("$id: urn:second"), + }) + } + changes, err := Compare(snapshot(""), snapshot("\n $id: dir/use.yml"), nil) + require.NoError(t, err) + require.Len(t, changes.GetAllChanges(), 2) + c := changes.GetAllChanges()[1] + require.Equal(t, "$ref", c.Property) + require.Equal(t, "dir/use.yml", c.SchemaResource) + require.Equal(t, `$["$ref"]`, c.Path) + require.Equal(t, "urn:first", c.Original) + require.Equal(t, "urn:second", c.New) + require.True(t, c.Breaking) +} + +func TestReferenceUseChangesCompatibilityAtDefinition(t *testing.T) { + for _, test := range []struct { + name, use string + breaking bool + }{ + {"ordinary", `{"$ref":"#/$defs/T"}`, false}, + {"negative", `{"not":{"$ref":"#/$defs/T"}}`, true}, + {"exclusive", `{"oneOf":[{"$ref":"#/$defs/T"},{}]}`, true}, + {"condition", `{"if":{"$ref":"#/$defs/T"},"then":false}`, true}, + {"bounded contains", `{"contains":{"$ref":"#/$defs/T"},"maxContains":1}`, true}, + {"transitive", `{"not":{"$ref":"#/$defs/A"}}`, true}, + {"nested positive", `{"not":{"not":{"$ref":"#/$defs/T"}}}`, false}, + } { + t.Run(test.name, func(t *testing.T) { + schema := strings.TrimSuffix(test.use, "}") + `,"$defs": { + "T": {"minimum": %d, "description": "%s"}, + "A": {"$ref": "#/$defs/T", "properties": {"next": {"$ref": "#/$defs/A"}}} + }}` + a := loadTest(t, fmt.Sprintf(schema, 4, "old")) + b := loadTest(t, fmt.Sprintf(schema, 1, "new")) + changes, err := Compare(a, b, nil) + require.NoError(t, err) + require.Len(t, changes.GetAllChanges(), 2) + for _, c := range changes.GetAllChanges() { + require.Equal(t, `$["$defs"].T.`+c.Property, c.Path) + if c.Property == "minimum" { + require.Equal(t, test.breaking, c.Breaking) + } else { + require.Equal(t, "description", c.Property) + require.False(t, c.Breaking) + } + } + }) + } +} + +func TestReferenceUsageCrossesResources(t *testing.T) { + snapshot := func(limit int) *Document { + return loadMembers(t, t.TempDir(), map[string][]byte{ + "use.yml": []byte("not: {$ref: urn:intermediate}"), + "shared.yml": []byte(fmt.Sprintf("$id: urn:target\nproperties: {v: {minimum: %d}}", limit)), + "middle.yml": []byte("$id: urn:intermediate\n$ref: urn:target"), + }) + } + changes, err := Compare(snapshot(5), snapshot(2), nil) + require.NoError(t, err) + require.Len(t, changes.GetAllChanges(), 1) + c := changes.GetAllChanges()[0] + require.Equal(t, "urn:target", c.SchemaResource) + require.Equal(t, "$.properties.v.minimum", c.Path) + require.True(t, c.Breaking) +} From 5039ecc56d709d2ddb205b89917c53b373811101 Mon Sep 17 00:00:00 2001 From: quobix Date: Wed, 25 Nov 2026 12:18:42 -0500 Subject: [PATCH 13/27] Preserve matched schema filenames for one-sided changes --- jsonschema/collection_test.go | 33 +++++++++++++++++++++++++++++++++ jsonschema/compare.go | 4 ++-- 2 files changed, 35 insertions(+), 2 deletions(-) diff --git a/jsonschema/collection_test.go b/jsonschema/collection_test.go index 3e1a1793..692e8f61 100644 --- a/jsonschema/collection_test.go +++ b/jsonschema/collection_test.go @@ -51,6 +51,39 @@ func TestCollectionSharedOwnership(t *testing.T) { require.Zero(t, reverse.TotalBreakingChanges()) } +func TestCollectionSourceFilesAndAuthoredCoordinates(t *testing.T) { + old := loadMembers(t, "before", map[string][]byte{"a/money.yaml": []byte("$id: urn:money\ntype: string\n")}) + newer := loadMembers(t, "after", map[string][]byte{"b/money.yaml": []byte("$id: urn:money\ntype: string\nmaxLength: 12\n")}) + empty := loadMembers(t, "empty", nil) + for _, tt := range []struct { + name string + left, right *Document + original, modified string + authored string + originalLine, newLine *int + }{ + {"added constraint in moved file", old, newer, "a/money.yaml", "b/money.yaml", "b/money.yaml", nil, new(3)}, + {"removed constraint in moved file", newer, old, "b/money.yaml", "a/money.yaml", "b/money.yaml", new(3), nil}, + {"added file", empty, newer, "", "b/money.yaml", "b/money.yaml", nil, new(1)}, + {"removed file", newer, empty, "b/money.yaml", "", "b/money.yaml", new(1), nil}, + } { + t.Run(tt.name, func(t *testing.T) { + diff, err := Compare(tt.left, tt.right, nil) + require.NoError(t, err) + require.NotNil(t, diff) + require.Len(t, diff.GetAllChanges(), 1) + ctx := diff.GetAllChanges()[0].Context + require.Equal(t, tt.original, ctx.OriginalDocument) + require.Equal(t, tt.modified, ctx.ModifiedDocument) + require.Equal(t, tt.authored, ctx.DocumentLocation) + require.Equal(t, tt.originalLine, ctx.OriginalLine) + require.Equal(t, tt.newLine, ctx.NewLine) + require.Equal(t, tt.originalLine == nil, ctx.OriginalColumn == nil) + require.Equal(t, tt.newLine == nil, ctx.NewColumn == nil) + }) + } +} + func TestCollectionIdentityAndMoves(t *testing.T) { for _, tc := range []struct { name string diff --git a/jsonschema/compare.go b/jsonschema/compare.go index 6e3e7d9a..e8649304 100644 --- a/jsonschema/compare.go +++ b/jsonschema/compare.go @@ -803,15 +803,15 @@ func (c *comparison) finish(ch *wc.Change, l, r *Resource, path, property string ch.Breaking, ch.Path, ch.Type = breaking, path, "schema" if l != nil { ch.SchemaResource = l.ID + ch.Context.OriginalDocument = l.Source.Name if ch.Context.OriginalLine != nil { - ch.Context.OriginalDocument = l.Source.Name ch.Context.DocumentLocation = l.Source.Name } } if r != nil { ch.SchemaResource = r.ID + ch.Context.ModifiedDocument = r.Source.Name if ch.Context.NewLine != nil { - ch.Context.ModifiedDocument = r.Source.Name ch.Context.DocumentLocation = r.Source.Name } } From ac02b3aa66bde488e892fc1c339c307b784cdb5b Mon Sep 17 00:00:00 2001 From: quobix Date: Wed, 25 Nov 2026 12:19:02 -0500 Subject: [PATCH 14/27] Resolve external collection dependencies from the configured base --- jsonschema/collection_test.go | 32 +++++++++++++++++++++ jsonschema/reference.go | 53 +++++++++++++++++++++++++++++------ 2 files changed, 76 insertions(+), 9 deletions(-) diff --git a/jsonschema/collection_test.go b/jsonschema/collection_test.go index 692e8f61..246b1102 100644 --- a/jsonschema/collection_test.go +++ b/jsonschema/collection_test.go @@ -6,9 +6,14 @@ package jsonschema import ( "encoding/json" "fmt" + "io" + "net/http" + "net/url" "strings" "testing" + "testing/fstest" + "github.com/pb33f/libopenapi/datamodel" "github.com/pb33f/testify/require" ) @@ -28,6 +33,33 @@ func sharedMembers(uses, minimum int) map[string][]byte { return files } +func TestCollectionExternalBaseAfterMemberLookup(t *testing.T) { + members := map[string][]byte{ + "order.json": []byte(`{"properties":{"price":{"$ref":"money.yaml"},"currency":{"$ref":"types/currency.yaml#code"}}}`), + "money.yaml": []byte("type: integer"), + } + const currency = "$anchor: code\ntype: string" + for _, remote := range []bool{false, true} { + config := datamodel.NewDocumentConfiguration() + config.BasePath = t.TempDir() + config.LocalFS = fstest.MapFS{"types/currency.yaml": {Data: []byte(currency)}} + if remote { + config.BaseURL, _ = url.Parse("https://schemas.example.test/external/") + config.AllowRemoteReferences = true + config.RemoteURLHandler = func(location string) (*http.Response, error) { + require.Equal(t, "https://schemas.example.test/external/types/currency.yaml", location) + return &http.Response{StatusCode: 200, Body: io.NopCloser(strings.NewReader(currency))}, nil + } + } + doc, err := LoadCollection(members, t.TempDir(), config) + require.NoError(t, err) + require.Len(t, doc.References, 2) + require.Same(t, doc.Sources["money.yaml"].Node, doc.References[0].To) + require.Equal(t, "string", member(doc.References[1].To, "type").Value) + doc.Release() + } +} + func TestCollectionSharedOwnership(t *testing.T) { left, right := loadMembers(t, "original", sharedMembers(2, 2)), loadMembers(t, "modified", sharedMembers(2, 3)) require.Nil(t, right.Root) diff --git a/jsonschema/reference.go b/jsonschema/reference.go index a7902383..ab510a3d 100644 --- a/jsonschema/reference.go +++ b/jsonschema/reference.go @@ -53,7 +53,7 @@ func filePath(u *url.URL) string { func (d *Document) resolveReferences() error { for i := 0; i < len(d.References); i++ { ref := d.References[i] - target, err := d.resolve(ref.address) + target, err := d.resolve(ref.address, ref.Value) if err != nil { return fmt.Errorf("%s:%d: resolve %s %q: %w", d.schemas[ref.From].Source.Name, ref.From.Line, ref.Keyword, ref.Value, err) } @@ -68,7 +68,7 @@ func (d *Document) resolveReferences() error { return nil } -func (d *Document) resolve(address string) (*yaml.Node, error) { +func (d *Document) resolve(address, authored string) (*yaml.Node, error) { if target := d.lookup(address); target != nil { return target, nil } @@ -80,18 +80,27 @@ func (d *Document) resolve(address string) (*yaml.Node, error) { uri.Fragment, uri.RawFragment = "", "" root := d.lookup(uri.String()) if root == nil { - data, err := d.read(uri) - if err != nil { - return nil, err + retrieval := d.collectionRetrieval(uri, authored) + root = d.lookup(retrieval.String()) + if root == nil { + data, err := d.read(retrieval) + if err != nil { + return nil, err + } + resource, err := d.addSource(data, retrieval, true) + if err != nil { + return nil, err + } + root = resource.Node } - resource, err := d.addSource(data, uri, true) - if err != nil { - return nil, err + if retrieval != uri { + if err := d.register(uri.String(), root, d.schemas[root].Source); err != nil { + return nil, err + } } if target := d.lookup(address); target != nil { return target, nil } - root = resource.Node } target := root if fragment != "" { @@ -126,6 +135,32 @@ func (d *Document) resolve(address string) (*yaml.Node, error) { return target, nil } +// Collection members are registered under their snapshot paths. An explicit base +// supplies relative dependencies only after those registered locations miss. +func (d *Document) collectionRetrieval(uri *url.URL, authored string) *url.URL { + if d.Root != nil || uri.Scheme != "file" || d.config.BaseURL == nil && d.config.BasePath == "" { + return uri + } + ref, err := url.Parse(authored) + if err != nil || ref.IsAbs() || strings.HasPrefix(ref.Path, "/") { + return uri + } + dir := filePath(d.base) + rel, err := filepath.Rel(dir, filePath(uri)) + if err != nil || !filepath.IsLocal(rel) { + return uri + } + if d.config.BaseURL != nil { + parent := *d.config.BaseURL + parent.Path = strings.TrimSuffix(parent.Path, "/") + "/" + return parent.ResolveReference(&url.URL{Path: filepath.ToSlash(rel), RawQuery: uri.RawQuery}) + } + if filepath.Clean(dir) == filepath.Clean(d.config.BasePath) { + return uri + } + return fileURL(filepath.Join(d.config.BasePath, rel)) +} + // Read source bytes without attaching a second API-format index to this Rolodex. // In particular, a revision filesystem controls all local reads for its snapshot. func (d *Document) read(uri *url.URL) ([]byte, error) { From a7d54e858c1f2bd2c3bdb705431fa5c29e413858 Mon Sep 17 00:00:00 2001 From: quobix Date: Wed, 25 Nov 2026 12:19:29 -0500 Subject: [PATCH 15/27] Keep exact numbers when validating JSON-compatible YAML schemas --- datamodel/schema_node.go | 10 ++++++ jsonschema/document.go | 2 +- jsonschema/loader_test.go | 20 +++++++++++ jsonschema/validation.go | 73 +++++++++++++++++++++++++++++++++------ 4 files changed, 93 insertions(+), 12 deletions(-) diff --git a/datamodel/schema_node.go b/datamodel/schema_node.go index a80625aa..9d057831 100644 --- a/datamodel/schema_node.go +++ b/datamodel/schema_node.go @@ -9,6 +9,7 @@ import ( "errors" "fmt" "io" + "strings" "github.com/pb33f/go-yaml" "github.com/pb33f/libopenapi/internal/jsonnode" @@ -72,6 +73,15 @@ func checkSchemaKeys(n *yaml.Node) error { } } case yaml.ScalarNode: + // YAML's resolver tags a number outside float64 range as a plain string. + // Keep the JSON numeric type when the authored token is a JSON number. + if n.Tag == "!!str" && n.Style == 0 && n.Value != "" && + (n.Value[0] == '-' || n.Value[0] >= '0' && n.Value[0] <= '9') && json.Valid([]byte(n.Value)) { + n.Tag = "!!int" + if strings.ContainsAny(n.Value, ".eE") { + n.Tag = "!!float" + } + } switch n.Tag { case "!!str", "!!bool", "!!int", "!!float", "!!null": default: diff --git a/jsonschema/document.go b/jsonschema/document.go index 4a59a644..ecb3fe06 100644 --- a/jsonschema/document.go +++ b/jsonschema/document.go @@ -217,7 +217,7 @@ func (d *Document) addSource(data []byte, uri *url.URL, explicit bool) (*Resourc if err = d.indexSchema(source, root, uri, "", nil, positiveContext); err != nil { return nil, err } - if err := validateSource(root, data); err != nil { + if err := validateSource(root); err != nil { return nil, fmt.Errorf("%s: %w", name, err) } if err = d.register(uri.String(), root, source); err != nil { diff --git a/jsonschema/loader_test.go b/jsonschema/loader_test.go index c4511821..f6ee7dc2 100644 --- a/jsonschema/loader_test.go +++ b/jsonschema/loader_test.go @@ -44,6 +44,26 @@ func TestInvalidConstraintsFailBeforeComparison(t *testing.T) { require.ErrorContains(t, err, "bad.json") } +func TestSchemaNumberValidationKeepsYAMLPrecision(t *testing.T) { + for _, tc := range []struct { + schema string + valid bool + }{ + {"multipleOf: 1.0e-400", true}, + {"minimum: 1.01e+400", true}, + {"minLength: 0.9999999999999999999", false}, + {"minLength: 1.0000000000000000001", false}, + } { + d, err := Load([]byte(tc.schema), "value.yaml", nil, true) + if tc.valid { + require.NoError(t, err) + d.Release() + } else { + require.Error(t, err) + } + } +} + func TestNativeFilePathsResolveThroughFileURIs(t *testing.T) { dir := t.TempDir() name := filepath.Join(dir, "my root.json") diff --git a/jsonschema/validation.go b/jsonschema/validation.go index 8fb691a3..b91b3c15 100644 --- a/jsonschema/validation.go +++ b/jsonschema/validation.go @@ -4,13 +4,14 @@ package jsonschema import ( - "bytes" "encoding/json" + "fmt" + "math/big" + "strings" "sync" "github.com/pb33f/go-yaml" validator "github.com/pb33f/jsonschema/v6" - modeljson "github.com/pb33f/libopenapi/json" ) // The validator ships the draft and its vocabularies. Compiling it needs no network. @@ -18,20 +19,70 @@ var draftMetaSchema = sync.OnceValue(func() *validator.Schema { return validator.NewCompiler().MustCompile(Dialect) }) -func validateSource(root *yaml.Node, data []byte) error { +func validateSource(root *yaml.Node) error { if root.Kind == yaml.ScalarNode { return nil // indexSchema has already checked that this is a boolean. } - var err error - if !json.Valid(data) { - data, err = modeljson.YAMLNodeToJSON(root, "") - if err != nil { - return err - } - } - value, err := validator.UnmarshalJSON(bytes.NewReader(data)) + value, err := metaValue(root) if err != nil { return err } return draftMetaSchema().Validate(value) } + +// Use authored number strings. A float64 round trip can turn a fractional schema +// limit into an integer or round a small, positive multipleOf to zero. +func metaValue(node *yaml.Node) (any, error) { + switch node.Kind { + case yaml.MappingNode: + value := make(map[string]any, len(node.Content)/2) + for i := 0; i < len(node.Content); i += 2 { + v, err := metaValue(node.Content[i+1]) + if err != nil { + return nil, err + } + value[node.Content[i].Value] = v + } + return value, nil + case yaml.SequenceNode: + value := make([]any, len(node.Content)) + for i, child := range node.Content { + v, err := metaValue(child) + if err != nil { + return nil, err + } + value[i] = v + } + return value, nil + } + switch node.Tag { + case "!!null": + return nil, nil + case "!!bool": + return strings.EqualFold(node.Value, "true"), nil + case "!!int", "!!float": + n := node.Value + if !json.Valid([]byte(n)) { + if node.Tag == "!!int" { + if v, ok := new(big.Int).SetString(n, 0); ok { + return json.Number(v.String()), nil + } + } + n = strings.TrimPrefix(strings.ReplaceAll(n, "_", ""), "+") + if strings.HasPrefix(n, ".") { + n = "0" + n + } else if strings.HasPrefix(n, "-.") { + n = "-0" + n[1:] + } + n = strings.ReplaceAll(strings.ReplaceAll(n, ".e", ".0e"), ".E", ".0E") + if strings.HasSuffix(n, ".") { + n += "0" + } + if !json.Valid([]byte(n)) { + return nil, fmt.Errorf("line %d: invalid JSON number %q", node.Line, node.Value) + } + } + return json.Number(n), nil + } + return node.Value, nil +} From b2b7054a998909654ebbc956ffa3be651f45df92 Mon Sep 17 00:00:00 2001 From: quobix Date: Wed, 25 Nov 2026 12:20:19 -0500 Subject: [PATCH 16/27] Carry schema membership and reference semantics across operand moves --- jsonschema/compare.go | 39 +++++++--- jsonschema/document.go | 10 ++- jsonschema/reference_changes.go | 54 ++++++++++++- jsonschema/reference_changes_test.go | 110 +++++++++++++++++++++++++++ 4 files changed, 198 insertions(+), 15 deletions(-) diff --git a/jsonschema/compare.go b/jsonschema/compare.go index e8649304..aef69069 100644 --- a/jsonschema/compare.go +++ b/jsonschema/compare.go @@ -43,6 +43,7 @@ func Compare(left, right *Document, rules *wc.BreakingRulesConfig) (*wc.SchemaCh } type comparison struct { + operandMoves map[schemaOccurrence]string annotationOnly bool originalUsage, modifiedUsage map[*yaml.Node]evaluationContext appliedAdditions map[*Resource]bool @@ -110,7 +111,7 @@ func matchResources(left, right *Document) (map[*Resource]*Resource, map[*Resour func (c *comparison) resources() error { pairs, used := matchResources(c.left, c.right) c.pairs, c.matched = pairs, used - c.compareReferences() + c.originalUsage, c.modifiedUsage = c.left.referenceUsage(), c.right.referenceUsage() for _, l := range c.left.Resources { if c.inline[l] { continue @@ -120,12 +121,13 @@ func (c *comparison) resources() error { } } for _, r := range c.right.Resources { - if !used[r] { + if !used[r] && !c.inline[r] { if err := c.compareResource(nil, r); err != nil { return err } } } + c.compareReferences() return nil } @@ -134,7 +136,9 @@ func (c *comparison) compareResource(l, r *Resource) error { c.membership(l, r, "$", "schema", nil, nil, l != nil || c.appliedAdditions[r]) return nil } - return c.schema(l, r, l.Node, r.Node, "$", "type", 1) + // Embedded resources have an independent address and also participate + // in their containing applicator, even when neither input has references. + return c.schema(l, r, l.Node, r.Node, "$", "type", combinedPolarity(1, l.context|r.context)) } func (c *comparison) schema(l, r *Resource, left, right *yaml.Node, path, keyword string, polarity int) error { @@ -578,6 +582,7 @@ func (c *comparison) compareChildren(l, r *Resource, left, right *yaml.Node, pat if n := old[k]; n != nil { hash := low.HashYAMLNodeSlice([]*yaml.Node{n}) if matches := byHash[hash]; len(matches) > 0 { + c.recordOperandMove(n, newNodes[matches[0]]) delete(old, k) delete(newNodes, matches[0]) byHash[hash] = matches[1:] @@ -597,15 +602,20 @@ func (c *comparison) compareChildren(l, r *Resource, left, right *yaml.Node, pat remainingRight = append(remainingRight, k) } } - for i := 0; i < min(len(remainingLeft), len(remainingRight)); i++ { + paired := min(len(remainingLeft), len(remainingRight)) + for i := 0; i < paired; i++ { lk, rk := remainingLeft[i], remainingRight[i] a, b := old[lk], newNodes[rk] + c.recordOperandMove(a, b) delete(old, lk) delete(newNodes, rk) if err := c.compareChild(l, r, a, b, childPath(path, rk), kw, polarity); err != nil { return err } } + for _, k := range remainingLeft[paired:] { + c.recordOperandMove(old[k], nil) + } } for k, a := range old { b := newNodes[k] @@ -663,13 +673,10 @@ func (c *comparison) compareChild(l, r *Resource, a, b *yaml.Node, path, keyword } case lo == l && !c.matched[ro]: // An inline schema acquired its first $id. Its constraints now belong to the new resource. - c.matched[ro] = true + c.markInline(ro) return c.schema(l, ro, a, b, "$", keyword, polarity) case ro == r && c.pairs[lo] == nil: - if c.inline == nil { - c.inline = make(map[*Resource]bool) - } - c.inline[lo] = true + c.markInline(lo) return c.schema(lo, r, a, b, path, keyword, polarity) default: // A matched resource moved to or from an existing inline use. @@ -679,6 +686,13 @@ func (c *comparison) compareChild(l, r *Resource, a, b *yaml.Node, path, keyword return nil } +func (c *comparison) markInline(r *Resource) { + if c.inline == nil { + c.inline = make(map[*Resource]bool) + } + c.inline[r] = true +} + // PropertyPath appends an object key to a JSONPath without changing its identity. func PropertyPath(path, key string) string { valid := key != "" @@ -791,6 +805,13 @@ func (c *comparison) finish(ch *wc.Change, l, r *Resource, path, property string } if c.rules != nil { ruleKey := property + if property == "schema" { + if l == nil && r != nil && r.keyword != "" { + ruleKey = r.keyword + } else if r == nil && l != nil && l.keyword != "" { + ruleKey = l.keyword + } + } if property == "$schema" { ruleKey = wc.PropSchemaDialect } diff --git a/jsonschema/document.go b/jsonschema/document.go index ecb3fe06..99eaf26a 100644 --- a/jsonschema/document.go +++ b/jsonschema/document.go @@ -38,6 +38,8 @@ type Source struct { // Resource is a root schema or an embedded schema with its own base URI. type Resource struct { base *url.URL + keyword string + context evaluationContext ID string Pointer string Source *Source @@ -214,7 +216,7 @@ func (d *Document) addSource(data []byte, uri *url.URL, explicit bool) (*Resourc } else { d.Rolodex.AddIndex(idx) } - if err = d.indexSchema(source, root, uri, "", nil, positiveContext); err != nil { + if err = d.indexSchema(source, root, uri, "", "", nil, positiveContext); err != nil { return nil, err } if err := validateSource(root); err != nil { @@ -258,7 +260,7 @@ func (d *Document) register(address string, node *yaml.Node, source *Source) err return nil } -func (d *Document) indexSchema(source *Source, node *yaml.Node, base *url.URL, pointer string, r *Resource, evaluation evaluationContext) error { +func (d *Document) indexSchema(source *Source, node *yaml.Node, base *url.URL, pointer, keyword string, r *Resource, evaluation evaluationContext) error { if node.Kind != yaml.MappingNode && !(node.Kind == yaml.ScalarNode && node.Tag == "!!bool") { return fmt.Errorf("%s:%d: schema must be an object or boolean", source.Name, node.Line) } @@ -300,7 +302,7 @@ func (d *Document) indexSchema(source *Source, node *yaml.Node, base *url.URL, p if id != nil { identity = d.resourceID(base) } - r = &Resource{base: base, ID: identity, Pointer: pointer, Source: source, Node: node} + r = &Resource{base: base, ID: identity, Pointer: pointer, Source: source, Node: node, keyword: keyword, context: evaluation} d.Resources = append(d.Resources, r) if err := d.register(base.String(), node, source); err != nil { return err @@ -345,7 +347,7 @@ func (d *Document) indexSchema(source *Source, node *yaml.Node, base *url.URL, p if childKind(keyword) != singleSchema { childPointer += "/" + escapePointer(key) } - return d.indexSchema(source, child, base, childPointer, r, evaluation.child(node, keyword)) + return d.indexSchema(source, child, base, childPointer, keyword, r, evaluation.child(node, keyword)) }) } diff --git a/jsonschema/reference_changes.go b/jsonschema/reference_changes.go index 1880656e..7a19cb6b 100644 --- a/jsonschema/reference_changes.go +++ b/jsonschema/reference_changes.go @@ -88,8 +88,54 @@ func (d *Document) referenceUsage() map[*yaml.Node]evaluationContext { return uses } +type schemaOccurrence struct { + owner *Resource + pointer string +} + +// Use the comparator's own operand pairing for every reference below a +// reordered allOf, anyOf, or oneOf branch. An empty destination marks a removal. +func (c *comparison) recordOperandMove(a, b *yaml.Node) { + if len(c.left.References) == 0 || len(c.right.References) == 0 { + return + } + old := c.left.schemaPointers[a] + if old == "" { + return // A named resource already has its own stable namespace. + } + owner := c.left.schemas[a] + newPath := "" + if b != nil { + if c.pairs[owner] != c.right.schemas[b] { + return + } + newPath = c.right.schemaPointers[b] + if old == newPath { + return + } + } + if c.operandMoves == nil { + c.operandMoves = make(map[schemaOccurrence]string) + } + c.operandMoves[schemaOccurrence{owner, old}] = newPath +} + +func (c *comparison) matchedPointer(owner *Resource, pointer string) (string, bool) { + if c.operandMoves != nil { + for prefix := pointer; prefix != ""; { + if to, ok := c.operandMoves[schemaOccurrence{owner, prefix}]; ok { + if to == "" { + return "", false + } + return to + pointer[len(prefix):], true + } + prefix = prefix[:strings.LastIndexByte(prefix, '/')] + } + } + return pointer, true +} + func (c *comparison) compareReferences() { - c.originalUsage, c.modifiedUsage = c.left.referenceUsage(), c.right.referenceUsage() if len(c.left.References) == 0 || len(c.right.References) == 0 { return } @@ -105,7 +151,11 @@ func (c *comparison) compareReferences() { var byFile map[site]*Reference for _, before := range c.left.References { owner := c.left.schemas[before.From] - key := site{c.pairs[owner], c.left.schemaPointers[before.From], before.Keyword} + pointer, paired := c.matchedPointer(owner, c.left.schemaPointers[before.From]) + if !paired { + continue + } + key := site{c.pairs[owner], pointer, before.Keyword} after := current[key] if after == nil && (len(c.pairs) != len(c.left.Resources) || len(c.pairs) != len(c.right.Resources)) { // Adding or dropping an embedded $id can change the base at an diff --git a/jsonschema/reference_changes_test.go b/jsonschema/reference_changes_test.go index fe2c2d38..f3e5494b 100644 --- a/jsonschema/reference_changes_test.go +++ b/jsonschema/reference_changes_test.go @@ -38,6 +38,116 @@ func TestUnchangedReferenceRetargetsAfterResourceMoves(t *testing.T) { require.Equal(t, "use.yml", c.Context.ModifiedDocument) } +func TestReferenceFollowsUnorderedOperand(t *testing.T) { + for _, keyword := range []string{"anyOf", "allOf", "oneOf"} { + t.Run(keyword, func(t *testing.T) { + const use = `{"properties":{"field":{"$ref":"a.json"}}}` + const other = `{"type":"boolean"}` + snapshot := func(first, second, a, b string) *Document { + return loadMembers(t, t.TempDir(), map[string][]byte{ + "a.json": []byte(fmt.Sprintf(`{"$id":%q}`, a)), + "b.json": []byte(fmt.Sprintf(`{"$id":%q}`, b)), + "use.json": []byte(fmt.Sprintf(`{%q:[%s,%s]}`, keyword, first, second)), + }) + } + left := snapshot(use, other, "urn:A", "urn:B") + for _, tc := range []struct { + right *Document + retarget bool + }{ + {snapshot(other, use, "urn:A", "urn:B"), false}, + {snapshot(other, use, "urn:B", "urn:A"), true}, + } { + diff, err := Compare(left, tc.right, nil) + require.NoError(t, err) + if !tc.retarget { + require.Nil(t, diff) + continue + } + require.NotNil(t, diff) + require.Len(t, diff.GetAllChanges(), 1) + change := diff.GetAllChanges()[0] + require.Equal(t, "$."+keyword+`[1].properties.field["$ref"]`, change.Path) + require.Equal(t, "use.json", change.SchemaResource) + require.Equal(t, "urn:A", change.Original) + require.Equal(t, "urn:B", change.New) + require.True(t, change.Breaking) + } + }) + } +} + +func TestEmbeddedResourceKeepsContainingContext(t *testing.T) { + for _, tc := range []struct { + name, schema, path string + breaking bool + }{ + {"negated", `{"not":{"$id":"urn:shared","minimum":%d}}`, "$.minimum", true}, + {"negated descendant", `{"not":{"$id":"urn:shared","properties":{"v":{"minimum":%d}}}}`, "$.properties.v.minimum", true}, + {"bounded contains", `{"maxContains":1,"contains":{"$id":"urn:shared","minimum":%d}}`, "$.minimum", true}, + {"conditional", `{"if":{"$id":"urn:shared","minimum":%d},"then":false}`, "$.minimum", true}, + {"positive", `{"properties":{"v":{"$id":"urn:shared","minimum":%d}}}`, "$.minimum", false}, + {"double negative", `{"not":{"not":{"$id":"urn:shared","minimum":%d}}}`, "$.minimum", false}, + } { + t.Run(tc.name, func(t *testing.T) { + a, b := loadTest(t, fmt.Sprintf(tc.schema, 4)), loadTest(t, fmt.Sprintf(tc.schema, 3)) + require.Empty(t, a.References) + diff, err := Compare(a, b, nil) + require.NoError(t, err) + require.Len(t, diff.GetAllChanges(), 1) + ch := diff.GetAllChanges()[0] + require.Equal(t, "urn:shared", ch.SchemaResource) + require.Equal(t, tc.path, ch.Path) + require.Equal(t, tc.breaking, ch.Breaking) + }) + } +} + +func TestRemovedOperandDoesNotInheritSurvivingReference(t *testing.T) { + snapshot := func(branches, a, b string) *Document { + return loadMembers(t, t.TempDir(), map[string][]byte{ + "a.yml": []byte("$id: " + a), "b.yml": []byte("$id: " + b), + "use.yml": []byte("anyOf:\n" + branches), + }) + } + const removed = " - {$ref: a.yml, title: removed}\n" + const kept = " - {$ref: a.yml, title: kept}\n" + diff, err := Compare(snapshot(removed+kept, "urn:A", "urn:B"), snapshot(kept, "urn:B", "urn:A"), nil) + require.NoError(t, err) + require.Len(t, diff.GetAllChanges(), 2) + require.Equal(t, wc.ObjectRemoved, diff.GetAllChanges()[0].ChangeType) + retarget := diff.GetAllChanges()[1] + require.Equal(t, `$.anyOf[0]["$ref"]`, retarget.Path) + require.Equal(t, "urn:B", retarget.New) + require.True(t, retarget.Breaking) +} + +func TestEmbeddedMembershipUsesContainingKeywordOverride(t *testing.T) { + empty := loadTest(t, "{}") + for _, keyword := range []string{"$defs", "properties"} { + for _, override := range []bool{false, true} { + rule := &wc.BreakingChangeRule{Added: &override, Removed: &override} + config := &wc.BreakingRulesConfig{Schema: &wc.SchemaRules{}} + if keyword == "$defs" { + config.Schema.Defs = rule + } else { + config.Schema.Properties = rule + } + member := loadTest(t, fmt.Sprintf(`{%q:{"v":{"$id":"urn:defined","type":"string"}}}`, keyword)) + for _, pair := range [][2]*Document{{empty, member}, {member, empty}} { + diff, err := Compare(pair[0], pair[1], config) + require.NoError(t, err) + require.Len(t, diff.GetAllChanges(), 1) + ch := diff.GetAllChanges()[0] + require.Equal(t, "urn:defined", ch.SchemaResource) + require.Equal(t, "$", ch.Path) + require.Equal(t, "schema", ch.Property) + require.Equal(t, override, ch.Breaking, "%s %v", keyword, ch.ChangeType) + } + } + } +} + func TestReferenceAnchorRetarget(t *testing.T) { snapshot := func(a, b string) *Document { return loadMembers(t, t.TempDir(), map[string][]byte{ From 5dfe0ddea336f775f13caa61dbf344e1bcc9af1a Mon Sep 17 00:00:00 2001 From: quobix Date: Wed, 25 Nov 2026 12:20:38 -0500 Subject: [PATCH 17/27] Resolve virtual schema bases against the host drive --- jsonschema/document_test.go | 10 ++++++++++ jsonschema/reference.go | 11 ++++++++--- 2 files changed, 18 insertions(+), 3 deletions(-) diff --git a/jsonschema/document_test.go b/jsonschema/document_test.go index 73ba0e95..bfbfd96a 100644 --- a/jsonschema/document_test.go +++ b/jsonschema/document_test.go @@ -88,6 +88,16 @@ func TestLoadReferencesFromEachSnapshot(t *testing.T) { require.Equal(t, "amount.yaml", ch.Context.ModifiedDocument) } +func TestRelativeBaseWithVirtualSchemaFiles(t *testing.T) { + config := datamodel.NewDocumentConfiguration() + config.BasePath = "snapshot" + config.LocalFS = fstest.MapFS{"id.yaml": {Data: []byte("type: string")}} + d, err := Load([]byte(`{"$ref":"id.yaml"}`), "customer.json", config, true) + require.NoError(t, err) + defer d.Release() + require.Same(t, d.Sources["id.yaml"].Node, d.References[0].To) +} + func TestEmbeddedResourceOccurrence(t *testing.T) { left := loadTest(t, `{"properties":{"x":{"$id":"urn:field","type":"string"}}}`) right := loadTest(t, `{"properties":{"y":{"$id":"urn:field","type":"string"}}}`) diff --git a/jsonschema/reference.go b/jsonschema/reference.go index ab510a3d..c7506eec 100644 --- a/jsonschema/reference.go +++ b/jsonschema/reference.go @@ -155,10 +155,11 @@ func (d *Document) collectionRetrieval(uri *url.URL, authored string) *url.URL { parent.Path = strings.TrimSuffix(parent.Path, "/") + "/" return parent.ResolveReference(&url.URL{Path: filepath.ToSlash(rel), RawQuery: uri.RawQuery}) } - if filepath.Clean(dir) == filepath.Clean(d.config.BasePath) { + explicit, err := filepath.Abs(d.config.BasePath) + if err != nil || filepath.Clean(dir) == explicit { return uri } - return fileURL(filepath.Join(d.config.BasePath, rel)) + return fileURL(filepath.Join(explicit, rel)) } // Read source bytes without attaching a second API-format index to this Rolodex. @@ -180,7 +181,11 @@ func (d *Document) read(uri *url.URL) ([]byte, error) { if dir == "" { dir = filePath(d.base) } - relative, err := filepath.Rel(dir, filename) + absoluteDir, err := filepath.Abs(dir) + if err != nil { + return nil, err + } + relative, err := filepath.Rel(absoluteDir, filename) if err != nil { return nil, err } From 7a43a44594b47c324e13c744b680054febbe3159 Mon Sep 17 00:00:00 2001 From: quobix Date: Wed, 25 Nov 2026 12:30:44 -0500 Subject: [PATCH 18/27] Validate repeated property schema shapes once per map --- jsonschema/document.go | 2 +- jsonschema/loader_test.go | 39 +++++++++++++++++++++++++++++++++++++++ jsonschema/validation.go | 22 ++++++++++++++++------ 3 files changed, 56 insertions(+), 7 deletions(-) diff --git a/jsonschema/document.go b/jsonschema/document.go index 99eaf26a..103b6435 100644 --- a/jsonschema/document.go +++ b/jsonschema/document.go @@ -219,7 +219,7 @@ func (d *Document) addSource(data []byte, uri *url.URL, explicit bool) (*Resourc if err = d.indexSchema(source, root, uri, "", "", nil, positiveContext); err != nil { return nil, err } - if err := validateSource(root); err != nil { + if err := d.validateSource(root); err != nil { return nil, fmt.Errorf("%s: %w", name, err) } if err = d.register(uri.String(), root, source); err != nil { diff --git a/jsonschema/loader_test.go b/jsonschema/loader_test.go index f6ee7dc2..f1f81a99 100644 --- a/jsonschema/loader_test.go +++ b/jsonschema/loader_test.go @@ -4,9 +4,11 @@ package jsonschema import ( + "fmt" "net/url" "os" "path/filepath" + "strings" "testing" "github.com/pb33f/libopenapi/datamodel" @@ -44,6 +46,43 @@ func TestInvalidConstraintsFailBeforeComparison(t *testing.T) { require.ErrorContains(t, err, "bad.json") } +func TestMetaValidationChecksDistinctPropertySchemasAndPreservesLiterals(t *testing.T) { + for _, kw := range []string{"properties", "$defs", "dependentSchemas"} { + _, err := Load([]byte(`{"`+kw+`":{"a":{"type":"string"},"b":{"type":"string"},"c":{"type":41}}}`), "bad.json", nil, true) + require.ErrorContains(t, err, "/"+kw+"/c/type") + } + doc, err := Load([]byte(`{"const":{"properties":{"a":true,"b":true}},"properties":{"a":true,"b":true}}`), "good.json", nil, true) + require.NoError(t, err) + defer doc.Release() + meta, err := doc.metaValue(doc.Root.Node, false) + require.NoError(t, err) + value := meta.(map[string]any) + require.Len(t, value["properties"], 1) + require.Len(t, value["const"].(map[string]any)["properties"], 2) + require.Len(t, member(doc.Root.Node, "properties").Content, 4) +} + +func BenchmarkLoadRepeatedPropertySchemas(b *testing.B) { + var input strings.Builder + input.WriteString(`{"$schema":"` + Dialect + `","properties":{`) + for i := range 8000 { + if i > 0 { + input.WriteByte(',') + } + fmt.Fprintf(&input, `"field%d":{"type":"string","maxLength":32}`, i) + } + input.WriteString("}}") + data := []byte(input.String()) + b.ReportAllocs() + for b.Loop() { + d, err := Load(data, "wide.json", nil, false) + if err != nil { + b.Fatal(err) + } + d.Release() + } +} + func TestSchemaNumberValidationKeepsYAMLPrecision(t *testing.T) { for _, tc := range []struct { schema string diff --git a/jsonschema/validation.go b/jsonschema/validation.go index b91b3c15..8e4e8dca 100644 --- a/jsonschema/validation.go +++ b/jsonschema/validation.go @@ -19,11 +19,11 @@ var draftMetaSchema = sync.OnceValue(func() *validator.Schema { return validator.NewCompiler().MustCompile(Dialect) }) -func validateSource(root *yaml.Node) error { +func (d *Document) validateSource(root *yaml.Node) error { if root.Kind == yaml.ScalarNode { return nil // indexSchema has already checked that this is a boolean. } - value, err := metaValue(root) + value, err := d.metaValue(root, false) if err != nil { return err } @@ -32,22 +32,32 @@ func validateSource(root *yaml.Node) error { // Use authored number strings. A float64 round trip can turn a fractional schema // limit into an integer or round a small, positive multipleOf to zero. -func metaValue(node *yaml.Node) (any, error) { +func (d *Document) metaValue(node *yaml.Node, repeatedSchemas bool) (any, error) { switch node.Kind { case yaml.MappingNode: value := make(map[string]any, len(node.Content)/2) + _, schema := d.schemas[node] + var previous *yaml.Node for i := 0; i < len(node.Content); i += 2 { - v, err := metaValue(node.Content[i+1]) + name, child := node.Content[i].Value, node.Content[i+1] + // These meta-schema maps apply exactly the same schema to every + // value and impose no constraints on member names or cardinality. + if repeatedSchemas && previous != nil && sameNode(previous, child) { + continue + } + previous = child + repeated := schema && (name == "properties" || name == "$defs" || name == "dependentSchemas") + v, err := d.metaValue(child, repeated) if err != nil { return nil, err } - value[node.Content[i].Value] = v + value[name] = v } return value, nil case yaml.SequenceNode: value := make([]any, len(node.Content)) for i, child := range node.Content { - v, err := metaValue(child) + v, err := d.metaValue(child, false) if err != nil { return nil, err } From c99ee8d9f08e8b1c60ec4a56f87a58c45a651c96 Mon Sep 17 00:00:00 2001 From: quobix Date: Wed, 25 Nov 2026 12:32:39 -0500 Subject: [PATCH 19/27] Retain every diagnostic path for invalid repeated schemas --- jsonschema/loader_test.go | 8 +++++++- jsonschema/validation.go | 26 ++++++++++++++++++-------- 2 files changed, 25 insertions(+), 9 deletions(-) diff --git a/jsonschema/loader_test.go b/jsonschema/loader_test.go index f1f81a99..a598ee03 100644 --- a/jsonschema/loader_test.go +++ b/jsonschema/loader_test.go @@ -50,12 +50,18 @@ func TestMetaValidationChecksDistinctPropertySchemasAndPreservesLiterals(t *test for _, kw := range []string{"properties", "$defs", "dependentSchemas"} { _, err := Load([]byte(`{"`+kw+`":{"a":{"type":"string"},"b":{"type":"string"},"c":{"type":41}}}`), "bad.json", nil, true) require.ErrorContains(t, err, "/"+kw+"/c/type") + _, err = Load([]byte(`{"`+kw+`":{"a":{"type":41},"b":{"type":41},"c":{"type":41}}}`), "bad.json", nil, true) + for _, name := range []string{"a", "b", "c"} { + require.ErrorContains(t, err, "/"+kw+"/"+name+"/type") + } } doc, err := Load([]byte(`{"const":{"properties":{"a":true,"b":true}},"properties":{"a":true,"b":true}}`), "good.json", nil, true) require.NoError(t, err) defer doc.Release() - meta, err := doc.metaValue(doc.Root.Node, false) + var skipped bool + meta, err := doc.metaValue(doc.Root.Node, false, &skipped) require.NoError(t, err) + require.True(t, skipped) value := meta.(map[string]any) require.Len(t, value["properties"], 1) require.Len(t, value["const"].(map[string]any)["properties"], 2) diff --git a/jsonschema/validation.go b/jsonschema/validation.go index 8e4e8dca..8c4b87d8 100644 --- a/jsonschema/validation.go +++ b/jsonschema/validation.go @@ -23,16 +23,25 @@ func (d *Document) validateSource(root *yaml.Node) error { if root.Kind == yaml.ScalarNode { return nil // indexSchema has already checked that this is a boolean. } - value, err := d.metaValue(root, false) - if err != nil { - return err + validate := func(skipped *bool) error { + value, err := d.metaValue(root, false, skipped) + if err != nil { + return err + } + return draftMetaSchema().Validate(value) + } + var skipped bool + err := validate(&skipped) + if err != nil && skipped { + // Include the authored path of every invalid member in the diagnostic. + return validate(nil) } - return draftMetaSchema().Validate(value) + return err } // Use authored number strings. A float64 round trip can turn a fractional schema // limit into an integer or round a small, positive multipleOf to zero. -func (d *Document) metaValue(node *yaml.Node, repeatedSchemas bool) (any, error) { +func (d *Document) metaValue(node *yaml.Node, repeatedSchemas bool, skipped *bool) (any, error) { switch node.Kind { case yaml.MappingNode: value := make(map[string]any, len(node.Content)/2) @@ -42,12 +51,13 @@ func (d *Document) metaValue(node *yaml.Node, repeatedSchemas bool) (any, error) name, child := node.Content[i].Value, node.Content[i+1] // These meta-schema maps apply exactly the same schema to every // value and impose no constraints on member names or cardinality. - if repeatedSchemas && previous != nil && sameNode(previous, child) { + if skipped != nil && repeatedSchemas && previous != nil && sameNode(previous, child) { + *skipped = true continue } previous = child repeated := schema && (name == "properties" || name == "$defs" || name == "dependentSchemas") - v, err := d.metaValue(child, repeated) + v, err := d.metaValue(child, repeated, skipped) if err != nil { return nil, err } @@ -57,7 +67,7 @@ func (d *Document) metaValue(node *yaml.Node, repeatedSchemas bool) (any, error) case yaml.SequenceNode: value := make([]any, len(node.Content)) for i, child := range node.Content { - v, err := d.metaValue(child, false) + v, err := d.metaValue(child, false, skipped) if err != nil { return nil, err } From ced26034318d6acd7a1db6dbe19478f9bab00d8e Mon Sep 17 00:00:00 2001 From: quobix Date: Thu, 26 Nov 2026 10:21:58 -0500 Subject: [PATCH 20/27] Test native schema validation and report source identity --- jsonschema/loader_test.go | 21 +++++++++++++++++++++ what-changed/model/change_types_test.go | 17 +++++++++++++++++ 2 files changed, 38 insertions(+) diff --git a/jsonschema/loader_test.go b/jsonschema/loader_test.go index a598ee03..7b3a4294 100644 --- a/jsonschema/loader_test.go +++ b/jsonschema/loader_test.go @@ -4,6 +4,7 @@ package jsonschema import ( + "encoding/json" "fmt" "net/url" "os" @@ -109,6 +110,26 @@ func TestSchemaNumberValidationKeepsYAMLPrecision(t *testing.T) { } } +func TestYAMLNumbersInSchemaAnnotations(t *testing.T) { + input := []byte("examples: [null, +0x20, 1_024, .25, -.75, 2., 1.e+2]") + doc, err := Load(input, "numbers.yaml", nil, true) + require.NoError(t, err) + defer doc.Release() + + projected, err := doc.metaValue(doc.Root.Node, false, nil) + require.NoError(t, err) + require.Equal(t, []any{ + nil, json.Number("32"), json.Number("1024"), json.Number("0.25"), + json.Number("-0.75"), json.Number("2.0"), json.Number("1.0e+2"), + }, projected.(map[string]any)["examples"]) + require.Equal(t, input, doc.Root.Source.Data) +} + +func TestNonFiniteYAMLNumberReportsAuthoredLine(t *testing.T) { + _, err := Load([]byte("examples:\n - 12\n - .inf\n"), "measurements.yaml", nil, true) + require.ErrorContains(t, err, `measurements.yaml: line 3: invalid JSON number ".inf"`) +} + func TestNativeFilePathsResolveThroughFileURIs(t *testing.T) { dir := t.TempDir() name := filepath.Join(dir, "my root.json") diff --git a/what-changed/model/change_types_test.go b/what-changed/model/change_types_test.go index 9dd111d6..c770ec36 100644 --- a/what-changed/model/change_types_test.go +++ b/what-changed/model/change_types_test.go @@ -27,6 +27,7 @@ func TestChange_MarshalJSON(t *testing.T) { rebuilt := rinseAndRepeat(&change) assert.Equal(t, "modified", rebuilt["changeText"]) assert.Equal(t, float64(1), rebuilt["change"]) + assert.NotContains(t, rebuilt, "schemaResource") change = Change{ ChangeType: ObjectAdded, @@ -89,6 +90,22 @@ func TestChange_MarshalJSON(t *testing.T) { rebuilt = rinseAndRepeat(&change) assert.Equal(t, "difficult", rebuilt["path"]) + change = Change{ + SchemaResource: "urn:example:money", + Path: "$.properties.currency.minLength", + Context: &ChangeContext{ + OriginalDocument: "money.json", + ModifiedDocument: "shared/money.json", + }, + } + rebuilt = rinseAndRepeat(&change) + assert.Equal(t, "urn:example:money", rebuilt["schemaResource"]) + assert.Equal(t, "$.properties.currency.minLength", rebuilt["path"]) + assert.Equal(t, map[string]any{ + "originalDocument": "money.json", + "modifiedDocument": "shared/money.json", + }, rebuilt["context"]) + // Test OriginalEncoded field change = Change{ OriginalEncoded: "key: value\n", From 5b058883c1bb25ce12b6e201695567990e5baa3f Mon Sep 17 00:00:00 2001 From: quobix Date: Thu, 26 Nov 2026 10:23:44 -0500 Subject: [PATCH 21/27] Cover schema comparison boundaries and preserve dependency names --- jsonschema/compare.go | 45 ++-- jsonschema/compare_cases_test.go | 237 +++++++++++++++++++++ jsonschema/reference_compare_cases_test.go | 35 +++ 3 files changed, 291 insertions(+), 26 deletions(-) create mode 100644 jsonschema/compare_cases_test.go create mode 100644 jsonschema/reference_compare_cases_test.go diff --git a/jsonschema/compare.go b/jsonschema/compare.go index aef69069..d55970c3 100644 --- a/jsonschema/compare.go +++ b/jsonschema/compare.go @@ -116,29 +116,29 @@ func (c *comparison) resources() error { if c.inline[l] { continue } - if err := c.compareResource(l, pairs[l]); err != nil { + r := pairs[l] + if r == nil { + c.resourceMembership(l, nil) + continue + } + // An embedded resource participates in its containing applicator, + // even when neither side references its address. + polarity := combinedPolarity(1, l.context|r.context) + if err := c.schema(l, r, l.Node, r.Node, "$", "type", polarity); err != nil { return err } } for _, r := range c.right.Resources { if !used[r] && !c.inline[r] { - if err := c.compareResource(nil, r); err != nil { - return err - } + c.resourceMembership(nil, r) } } c.compareReferences() return nil } -func (c *comparison) compareResource(l, r *Resource) error { - if l == nil || r == nil { - c.membership(l, r, "$", "schema", nil, nil, l != nil || c.appliedAdditions[r]) - return nil - } - // Embedded resources have an independent address and also participate - // in their containing applicator, even when neither input has references. - return c.schema(l, r, l.Node, r.Node, "$", "type", combinedPolarity(1, l.context|r.context)) +func (c *comparison) resourceMembership(l, r *Resource) { + c.membership(l, r, "$", "schema", nil, nil, l != nil || c.appliedAdditions[r]) } func (c *comparison) schema(l, r *Resource, left, right *yaml.Node, path, keyword string, polarity int) error { @@ -191,10 +191,6 @@ func (c *comparison) schema(l, r *Resource, left, right *yaml.Node, path, keywor } for _, ch := range diff.GetAllChanges() { property := ch.Property - if property == "schemaDialect" { - property = "$schema" - ch.Property = property - } editPath := PropertyPath(path, property) a, b := member(left, property), member(right, property) if dependencies[ch] { @@ -325,11 +321,12 @@ func constraintProxy(n *yaml.Node, r *Resource) (*base.SchemaProxy, error) { } } var proxy base.SchemaProxy - if err := proxy.Build(context.Background(), nil, &view, r.Source.Index); err != nil { - return nil, err + err := proxy.Build(context.Background(), nil, &view, r.Source.Index) + if err == nil && proxy.Schema() == nil { + err = proxy.GetBuildError() } - if proxy.Schema() == nil { - return nil, fmt.Errorf("%s:%d: %w", r.Source.Name, n.Line, proxy.GetBuildError()) + if err != nil { + return nil, fmt.Errorf("%s:%d: %w", r.Source.Name, n.Line, err) } return &proxy, nil } @@ -787,12 +784,8 @@ func (c *comparison) finish(ch *wc.Change, l, r *Resource, path, property string default: if polarity < 0 { switch property { - case "type", "required", "minimum", "maximum", "exclusiveMinimum", "exclusiveMaximum", "minLength", "maxLength", "minContains", "maxContains", "minItems", "maxItems", "minProperties", "maxProperties": - if property == "type" && ch.Property != "schema" { - breaking = true - } else { - breaking = !breaking - } + case "required", "minimum", "maximum", "exclusiveMinimum", "exclusiveMaximum", "minLength", "maxLength", "minContains", "maxContains", "minItems", "maxItems", "minProperties", "maxProperties": + breaking = !breaking default: breaking = true } diff --git a/jsonschema/compare_cases_test.go b/jsonschema/compare_cases_test.go new file mode 100644 index 00000000..7311cf4c --- /dev/null +++ b/jsonschema/compare_cases_test.go @@ -0,0 +1,237 @@ +// Copyright 2026 Princess B33f Heavy Industries / Dave Shanley +// SPDX-License-Identifier: MIT + +package jsonschema + +import ( + "fmt" + "testing" + + "github.com/pb33f/go-yaml" + wc "github.com/pb33f/libopenapi/what-changed/model" + "github.com/pb33f/testify/require" +) + +func TestComparisonInputs(t *testing.T) { + single := loadTest(t, "true") + collection := loadMembers(t, "snapshot", map[string][]byte{}) + for _, tc := range []struct { + left, right *Document + message string + }{ + {nil, single, "both JSON Schema inputs are required"}, + {single, nil, "both JSON Schema inputs are required"}, + {single, collection, "collection on both sides"}, + {collection, single, "collection on both sides"}, + } { + diff, err := Compare(tc.left, tc.right, nil) + require.ErrorContains(t, err, tc.message) + require.Nil(t, diff) + } + require.Nil(t, MatchResources(nil, single)) + require.Nil(t, MatchResources(single, nil)) + diff, err := Compare(single, single, nil) + require.NoError(t, err) + require.Nil(t, diff) +} + +func TestResourceMoveCanReplaceRemovedFile(t *testing.T) { + original := loadMembers(t, "before", map[string][]byte{ + "gone.yaml": []byte("$id: urn:gone"), + "moved.yaml": []byte("$id: urn:kept"), + }) + current := loadMembers(t, "after", map[string][]byte{"gone.yaml": []byte("$id: urn:kept")}) + matches := MatchResources(original, current) + require.Len(t, matches, 1) + for old, newResource := range matches { + require.Equal(t, "urn:kept", old.ID) + require.Equal(t, old.ID, newResource.ID) + } + diff, err := Compare(original, current, nil) + require.NoError(t, err) + require.Len(t, diff.GetAllChanges(), 1) + removed := diff.GetAllChanges()[0] + require.Equal(t, "urn:gone", removed.SchemaResource) + require.Equal(t, wc.ObjectRemoved, removed.ChangeType) + require.True(t, removed.Breaking) +} + +func TestEquivalentConstraintSpellings(t *testing.T) { + for _, tc := range []struct{ name, original, modified string }{ + {"boolean case", "FALSE", "false"}, + {"numeric spelling", `{"maximum":1.25}`, `{"maximum":125e-2}`}, + {"dependency order", `{"dependentRequired":{"card":["number","currency"]}}`, `{"dependentRequired":{"card":["currency","number"]}}`}, + } { + t.Run(tc.name, func(t *testing.T) { + diff, err := Compare(loadTest(t, tc.original), loadTest(t, tc.modified), nil) + require.NoError(t, err) + require.Nil(t, diff) + }) + } +} + +func TestDependenciesKeepTheirAuthoredDialectNames(t *testing.T) { + original := loadTest(t, `{"dependentRequired":{"schemaDialect":["oldA"],"$schema":["oldB"]}}`) + modified := loadTest(t, `{"dependentRequired":{"schemaDialect":["newA"],"$schema":["newB"]}}`) + diff, err := Compare(original, modified, nil) + require.NoError(t, err) + changes := diff.GetAllChanges() + require.Len(t, changes, 2) + require.Equal(t, 2, diff.TotalBreakingChanges()) + want := map[string]struct{ path, original, modified string }{ + "schemaDialect": {"$.dependentRequired.schemaDialect", `["oldA"]`, `["newA"]`}, + "$schema": {`$.dependentRequired["$schema"]`, `["oldB"]`, `["newB"]`}, + } + for _, ch := range changes { + expected, exists := want[ch.Property] + require.True(t, exists, "unexpected dependency %q", ch.Property) + require.Equal(t, expected.path, ch.Path) + require.Equal(t, expected.original, ch.OriginalEncoded) + require.Equal(t, expected.modified, ch.NewEncoded) + delete(want, ch.Property) + } + require.Empty(t, want) +} + +func TestAnnotationEditsAlongsideEquivalentDependencies(t *testing.T) { + original := loadTest(t, `{ + "dependentRequired":{"card":["issuer","currency"]}, + "same":{"a":1,"b":2}, + "former-kind":"legacy" + }`) + current := loadTest(t, `{ + "dependentRequired":{"card":["currency","issuer"]}, + "same":{"b":2,"a":1}, + "new-kind":"modern", + "description":"Issued card" + }`) + diff, err := Compare(original, current, nil) + require.NoError(t, err) + changes := diff.GetAllChanges() + require.Len(t, changes, 3) + require.Zero(t, diff.TotalBreakingChanges()) + byKey := map[string]*wc.Change{} + for _, ch := range changes { + byKey[ch.Property] = ch + } + require.Contains(t, byKey, "description") + require.Contains(t, byKey, "former-kind") + require.Contains(t, byKey, "new-kind") + require.Equal(t, `$["former-kind"]`, byKey["former-kind"].Path) + require.Equal(t, wc.PropertyRemoved, byKey["former-kind"].ChangeType) + require.Equal(t, "legacy", byKey["former-kind"].Original) + require.Equal(t, `$["new-kind"]`, byKey["new-kind"].Path) + require.Equal(t, wc.PropertyAdded, byKey["new-kind"].ChangeType) + require.Equal(t, "modern", byKey["new-kind"].New) +} + +func TestCompatibilityOfNestedConstraints(t *testing.T) { + for _, tc := range []struct { + name, original, modified, path string + forward, reverse bool + }{ + {"negated boolean", `{"not":false}`, `{"not":true}`, "$.not", true, false}, + {"negated reference", `{"$defs":{"a":true,"b":false},"not":{"$ref":"#/$defs/a"}}`, `{"$defs":{"a":true,"b":false},"not":{"$ref":"#/$defs/b"}}`, `$.not["$ref"]`, true, true}, + {"maximum size", `{"maxLength":5}`, `{"maxLength":3}`, "$.maxLength", true, false}, + {"new conjunct", `{"allOf":[{"type":"number"}]}`, `{"allOf":[{"type":"number"},{"minimum":0}]}`, "$.allOf[1]", true, false}, + {"new dependency", `{}`, `{"dependentSchemas":{"card":{"required":["issuer"]}}}`, "$.dependentSchemas.card", true, false}, + {"new dependency in condition", `{"if":{},"then":false}`, `{"if":{"dependentSchemas":{"card":{"required":["issuer"]}}},"then":false}`, "$.if.dependentSchemas.card", true, true}, + {"content with both reference polarities", `{"contentSchema":{"minLength":1},"allOf":[{"$ref":"#/contentSchema"},{"not":{"$ref":"#/contentSchema"}}]}`, `{"contentSchema":{"minLength":2},"allOf":[{"$ref":"#/contentSchema"},{"not":{"$ref":"#/contentSchema"}}]}`, "$.contentSchema.minLength", true, true}, + } { + t.Run(tc.name, func(t *testing.T) { + a, b := loadTest(t, tc.original), loadTest(t, tc.modified) + for _, pair := range []struct { + l, r *Document + breaking bool + }{{a, b, tc.forward}, {b, a, tc.reverse}} { + diff, err := Compare(pair.l, pair.r, nil) + require.NoError(t, err) + require.Len(t, diff.GetAllChanges(), 1) + change := diff.GetAllChanges()[0] + require.Equal(t, tc.path, change.Path) + require.Equal(t, pair.breaking, change.Breaking) + } + }) + } +} + +func TestTypedLiteralBoundaryChanges(t *testing.T) { + for _, tc := range []struct { + name, original, modified, property, oldValue, newValue string + breaking bool + }{ + {"empty enum", `{}`, `{"enum":[]}`, "enum", "", "[]", true}, + {"drop empty enum", `{"enum":[]}`, `{}`, "enum", "[]", "", false}, + {"null default", `{"default":null}`, `{"default":"null"}`, "default", "null", `"null"`, false}, + {"large exponent value", `{"const":1.0e-425}`, `{"const":2.0e-425}`, "const", "1.0e-425", "2.0e-425", true}, + } { + t.Run(tc.name, func(t *testing.T) { + result, err := Compare(loadTest(t, tc.original), loadTest(t, tc.modified), nil) + require.NoError(t, err) + require.Len(t, result.GetAllChanges(), 1) + ch := result.GetAllChanges()[0] + require.Equal(t, tc.property, ch.Property) + require.Equal(t, tc.oldValue, ch.OriginalEncoded) + require.Equal(t, tc.newValue, ch.NewEncoded) + require.Equal(t, tc.breaking, ch.Breaking) + }) + } +} + +func TestResourceAtAnExistingPropertyChangesIdentity(t *testing.T) { + const first = `{"$id":"urn:first","type":"string"}` + const second = `{"$id":"urn:second","type":"number"}` + for _, alternative := range []struct{ name, schema string }{ + {"another address", second}, {"inline", `{"type":"number"}`}, + } { + t.Run(alternative.name, func(t *testing.T) { + const shape = `{"properties":{"x":%s,"y":%s}}` + before := loadTest(t, fmt.Sprintf(shape, first, alternative.schema)) + after := loadTest(t, fmt.Sprintf(shape, alternative.schema, first)) + result, err := Compare(before, after, nil) + require.NoError(t, err) + edits := result.GetAllChanges() + require.Len(t, edits, 2) + for i, path := range []string{"$.properties.x", "$.properties.y"} { + ch := edits[i] + require.Equal(t, path, ch.Path) + require.Equal(t, "customer.yaml", ch.SchemaResource) + require.Equal(t, wc.Modified, ch.ChangeType) + require.True(t, ch.Breaking) + } + if alternative.schema == second { + require.Equal(t, "urn:first", edits[0].Original) + require.Equal(t, "urn:second", edits[0].New) + } else { + require.Contains(t, edits[0].OriginalEncoded, "urn:first") + require.Contains(t, edits[0].NewEncoded, "number") + } + }) + } +} + +// An editor can change a source node after Load. An invalid edit must fail the +// whole comparison, including when the edited constraint is nested. +func TestInvalidInMemoryDependencyStopsComparison(t *testing.T) { + for _, tc := range []struct { + name, schema string + locate func(*yaml.Node) *yaml.Node + }{ + {"in property", `{"properties":{"payment":{"dependentRequired":{"card":["issuer"]}}}}`, + func(root *yaml.Node) *yaml.Node { return member(member(root, "properties"), "payment") }}, + {"in conjunct", `{"allOf":[{"dependentRequired":{"card":["issuer"]}}]}`, + func(root *yaml.Node) *yaml.Node { return member(root, "allOf").Content[0] }}, + } { + t.Run(tc.name, func(t *testing.T) { + good, bad := loadTest(t, tc.schema), loadTest(t, tc.schema) + field := member(member(tc.locate(bad.Root.Node), "dependentRequired"), "card") + field.Kind, field.Tag, field.Value, field.Content = yaml.ScalarNode, "!!str", "issuer", nil + for _, pair := range [][2]*Document{{good, bad}, {bad, good}} { + diff, err := Compare(pair[0], pair[1], nil) + require.ErrorContains(t, err, "dependentRequired value must be an array") + require.ErrorContains(t, err, "customer.yaml:1") + require.Nil(t, diff) + } + }) + } +} diff --git a/jsonschema/reference_compare_cases_test.go b/jsonschema/reference_compare_cases_test.go new file mode 100644 index 00000000..6c71e436 --- /dev/null +++ b/jsonschema/reference_compare_cases_test.go @@ -0,0 +1,35 @@ +// Copyright 2026 Princess B33f Heavy Industries / Dave Shanley +// SPDX-License-Identifier: MIT + +package jsonschema + +import ( + "testing" + + "github.com/pb33f/testify/require" +) + +func TestReferenceInNamedOperandKeepsItsAddress(t *testing.T) { + const named = `{"$id":"urn:operand","$ref":"urn:field"}` + const number = `{"type":"number"}` + const definitions = `"$defs":{"field":{"$id":"urn:field"}}` + before := loadTest(t, `{`+definitions+`,"anyOf":[`+named+","+number+`]}`) + after := loadTest(t, `{`+definitions+`,"anyOf":[`+number+","+named+`]}`) + diff, err := Compare(before, after, nil) + require.NoError(t, err) + require.Nil(t, diff) +} + +func TestReferenceInInlineOperandGainsAddress(t *testing.T) { + const input = `{"$defs":{"field":{"$id":"urn:field"}},"anyOf":[` + original := loadTest(t, input+`{"$ref":"urn:field"}]}`) + modified := loadTest(t, input+`{"$id":"urn:operand","$ref":"urn:field"}]}`) + diff, err := Compare(original, modified, nil) + require.NoError(t, err) + require.Len(t, diff.GetAllChanges(), 1) + change := diff.GetAllChanges()[0] + require.Equal(t, "$id", change.Property) + require.Equal(t, "urn:operand", change.SchemaResource) + require.Equal(t, "urn:operand", change.New) + require.False(t, change.Breaking) +} From 8b21b33ace8f8151f347c156987d5e9a72d51586 Mon Sep 17 00:00:00 2001 From: quobix Date: Thu, 26 Nov 2026 10:23:49 -0500 Subject: [PATCH 22/27] Cover authored schema parsing and preserve lookup for scalar roots --- datamodel/schema_node.go | 3 - datamodel/schema_node_test.go | 71 ++++++++++++++++++++ index/schema_index_test.go | 67 +++++++++++++++++++ index/spec_index_build.go | 2 +- internal/jsonnode/parse_json_test.go | 96 ++++++++++++++++++++++++++++ 5 files changed, 235 insertions(+), 4 deletions(-) create mode 100644 datamodel/schema_node_test.go create mode 100644 index/schema_index_test.go create mode 100644 internal/jsonnode/parse_json_test.go diff --git a/datamodel/schema_node.go b/datamodel/schema_node.go index 9d057831..682c79bd 100644 --- a/datamodel/schema_node.go +++ b/datamodel/schema_node.go @@ -38,9 +38,6 @@ func DecodeSchemaNode(data []byte) (*yaml.Node, error) { return nil, fmt.Errorf("expected one schema document") } } - if len(doc.Content) != 1 { - return nil, fmt.Errorf("missing schema root") - } if err := checkSchemaKeys(doc); err != nil { return nil, err } diff --git a/datamodel/schema_node_test.go b/datamodel/schema_node_test.go new file mode 100644 index 00000000..f42c951d --- /dev/null +++ b/datamodel/schema_node_test.go @@ -0,0 +1,71 @@ +// Copyright 2026 Princess B33f Heavy Industries / Dave Shanley +// SPDX-License-Identifier: MIT + +package datamodel + +import ( + "errors" + "io" + "strings" + "testing" + + "github.com/pb33f/go-yaml" + "github.com/pb33f/testify/require" +) + +func TestDecodeSchemaNodeReadsOneDocument(t *testing.T) { + for _, tc := range []struct{ name, source, message string }{ + {"empty", "", "invalid schema document"}, + {"malformed YAML", "properties: [\n", "invalid schema document"}, + {"second document", "type: string\n---\nfalse\n", "expected one schema document"}, + {"malformed second document", "type: string\n---\nenum: [1\n", "yaml:"}, + {"malformed JSON string", "{\"title\":\"\xff\"}", "invalid JSON schema document"}, + {"duplicate escaped JSON key", "{\n \"properties\": {\n \"name\": true,\n \"na\\u006de\": false}}", `line 4: mapping key "name" already defined at line 3`}, + {"duplicate inside YAML example", "examples:\n - name: first\n name: second\n", `line 3: mapping key "name" already defined at line 2`}, + {"numeric YAML key", "properties:\n 42: false\n", "line 2: JSON object keys must be strings"}, + {"complex YAML key", "properties:\n ? [a,b]\n : false\n", "line 2: JSON object keys must be strings"}, + {"YAML timestamp", "const: 2026-11-25\n", "line 1: unsupported JSON scalar !!timestamp"}, + {"YAML alias", "$defs: &shape {}\nproperties:\n x: *shape\n", "line 3: expected JSON-compatible YAML"}, + } { + t.Run(tc.name, func(t *testing.T) { + doc, err := DecodeSchemaNode([]byte(tc.source)) + require.Nil(t, doc) + require.ErrorContains(t, err, tc.message) + if tc.source == "" { + require.ErrorIs(t, err, io.EOF) + } + }) + } +} + +func TestDecodeSchemaNodePreservesYAMLNumberTypes(t *testing.T) { + integer := strings.Repeat("9", 400) + doc, err := DecodeSchemaNode([]byte("examples:\n - " + integer + "\n - -1.5e5000\n - '1e5000'\n - 1GB\n...\n")) + require.NoError(t, err) + require.Equal(t, yaml.DocumentNode, doc.Kind) + require.Len(t, doc.Content, 1) + values := doc.Content[0].Content[1] + require.Equal(t, yaml.SequenceNode, values.Kind) + require.Len(t, values.Content, 4) + for i, want := range []struct{ value, tag string }{ + {integer, "!!int"}, {"-1.5e5000", "!!float"}, {"1e5000", "!!str"}, {"1GB", "!!str"}, + } { + node := values.Content[i] + require.Equal(t, want.value, node.Value) + require.Equal(t, want.tag, node.Tag) + require.Equal(t, i+2, node.Line) + require.Equal(t, 5, node.Column) + } +} + +func TestUnsupportedSpecTypeDistinguishesSchemaFromInvalidAPI(t *testing.T) { + info, err := ExtractSpecInfo([]byte(`{"type":"object","properties":{"id":{"type":"string"}}}`)) + require.ErrorIs(t, err, ErrUnsupportedSpecType) + require.ErrorIs(t, info.Error, ErrUnsupportedSpecType) + require.NotNil(t, info.RootNode) + for _, doc := range []string{"openapi: [", "openapi: '2.0.0'\n"} { + _, err = ExtractSpecInfo([]byte(doc)) + require.Error(t, err) + require.False(t, errors.Is(err, ErrUnsupportedSpecType)) + } +} diff --git a/index/schema_index_test.go b/index/schema_index_test.go new file mode 100644 index 00000000..5567fb9c --- /dev/null +++ b/index/schema_index_test.go @@ -0,0 +1,67 @@ +// Copyright 2026 Princess B33f Heavy Industries / Dave Shanley +// SPDX-License-Identifier: MIT + +package index + +import ( + "testing" + + "github.com/pb33f/go-yaml" + "github.com/pb33f/testify/require" +) + +func TestNewSchemaIndexMapsAuthoredSourceWithoutExtractingReferences(t *testing.T) { + var doc yaml.Node + require.NoError(t, yaml.Unmarshal([]byte("examples:\n - $ref: literal.json\nproperties:\n price:\n $ref: money.json\n $id: urn:price\n"), &doc)) + config := CreateClosedAPIIndexConfig() + config.SpecAbsolutePath = "schemas/order.yaml" + config.Rolodex = NewRolodex(config) + idx := NewSchemaIndex(&doc, config) + require.Same(t, &doc, idx.GetRootNode()) + require.Same(t, config.Rolodex, idx.GetRolodex()) + require.Equal(t, "schemas/order.yaml", idx.GetSpecAbsolutePath()) + require.Empty(t, idx.GetAllReferences()) + require.Empty(t, idx.GetAllSchemaIds()) + example := doc.Content[0].Content[1].Content[0].Content[1] + price := doc.Content[0].Content[3].Content[1] + ref := price.Content[1] + for _, value := range []*yaml.Node{example, ref} { + found, ok := idx.GetNode(value.Line, value.Column) + require.True(t, ok) + require.Same(t, value, found) + } + entry := &SchemaIdEntry{Id: price.Content[3].Value, SchemaNode: price, Index: idx} + require.NoError(t, idx.RegisterSchemaId(entry)) + require.Same(t, price, idx.GetSchemaById("urn:price").SchemaNode) + idx.Release() + require.Nil(t, idx.GetSchemaById("urn:price")) + require.Nil(t, idx.GetRootNode()) + require.Nil(t, idx.GetNodeMap()) + _, ok := idx.GetNode(ref.Line, ref.Column) + require.False(t, ok) + require.Equal(t, "money.json", ref.Value) + idx.Release() +} + +func TestNewSchemaIndexRootForms(t *testing.T) { + for _, source := range []string{"false", "{}"} { + var doc yaml.Node + require.NoError(t, yaml.Unmarshal([]byte("\n"+source), &doc)) + for _, input := range []*yaml.Node{&doc, doc.Content[0]} { + idx := NewSchemaIndex(input, CreateClosedAPIIndexConfig()) + require.Same(t, input, idx.GetRootNode()) + got, ok := idx.GetNode(2, 1) + require.True(t, ok) + require.Same(t, doc.Content[0], got) + idx.Release() + } + } + for _, input := range []*yaml.Node{nil, {Kind: yaml.DocumentNode}} { + idx := NewSchemaIndex(input, CreateClosedAPIIndexConfig()) + require.Same(t, input, idx.GetRootNode()) + got, ok := idx.GetNode(1, 1) + require.Nil(t, got) + require.False(t, ok) + idx.Release() + } +} diff --git a/index/spec_index_build.go b/index/spec_index_build.go index f0a94d84..2c9288d5 100644 --- a/index/spec_index_build.go +++ b/index/spec_index_build.go @@ -52,7 +52,7 @@ func NewSpecIndexWithConfig(rootNode *yaml.Node, config *SpecIndexConfig) *SpecI func NewSchemaIndex(rootNode *yaml.Node, config *SpecIndexConfig) *SpecIndex { idx := NewSpecIndexWithConfig(nil, config) idx.root = rootNode - if rootNode != nil && len(rootNode.Content) > 0 { + if rootNode != nil && (rootNode.Kind != yaml.DocumentNode || len(rootNode.Content) > 0) { idx.nodeMapCompleted = make(chan struct{}) idx.MapNodes(rootNode) } diff --git a/internal/jsonnode/parse_json_test.go b/internal/jsonnode/parse_json_test.go new file mode 100644 index 00000000..6e67ad42 --- /dev/null +++ b/internal/jsonnode/parse_json_test.go @@ -0,0 +1,96 @@ +// Copyright 2026 Princess B33f Heavy Industries / Dave Shanley +// SPDX-License-Identifier: MIT + +package jsonnode + +import ( + "strings" + "testing" + + "github.com/pb33f/go-yaml" + "github.com/pb33f/testify/require" +) + +func TestParseJSONCoordinatesAndTypes(t *testing.T) { + const source = "\t{\r\n\"values\"\r:\t[true, null, -0,\n\t1e9999, 18446744073709551617000]}\t" + doc, ok := ParseJSON([]byte(source)) + require.True(t, ok) + root := doc.Content[0] + require.Equal(t, yaml.MappingNode, root.Kind) + require.Equal(t, 1, root.Line) + require.Equal(t, 2, root.Column) + key, values := root.Content[0], root.Content[1] + require.Equal(t, "values", key.Value) + require.Equal(t, 2, key.Line) + require.Equal(t, 1, key.Column) + require.Equal(t, 3, values.Line) + require.Equal(t, 3, values.Column) + for i, want := range []struct { + value, tag string + line, column int + }{ + {"true", "!!bool", 3, 4}, {"null", "!!null", 3, 10}, {"-0", "!!int", 3, 16}, + {"1e9999", "!!float", 4, 2}, {"18446744073709551617000", "!!int", 4, 10}, + } { + got := values.Content[i] + require.Equal(t, want.tag, got.Tag) + require.Equal(t, want.value, got.Value) + require.Equal(t, want.line, got.Line) + require.Equal(t, want.column, got.Column) + } + doc, ok = ParseJSON([]byte("\tfalse\r")) + require.True(t, ok) + require.Equal(t, "false", doc.Content[0].Value) + require.Equal(t, "!!bool", doc.Content[0].Tag) + _, ok = Parse([]byte(source)) + require.False(t, ok) +} + +func TestParseJSONEscapesPreserveFollowingCoordinates(t *testing.T) { + for _, tc := range []struct{ name, token, decoded string }{ + {"surrogate pair", `"\uD83D\uDE00"`, "😀"}, + {"lone high", `"\uD800"`, "\ufffd"}, + {"lone low", `"\uDC00"`, "\ufffd"}, + {"two high then low", `"\uD800\uD83D\uDE00"`, "\ufffd😀"}, + {"high and BMP", `"\uD800\u0041"`, "\ufffdA"}, + {"escaped backslash", `"\\uD83D\\uDE00"`, `\uD83D\uDE00`}, + {"JSON characters outside YAML repertoire", "\"x\\/\x7f\u0085\u2028😀\"", "x/\x7f\u0085\u2028😀"}, + } { + t.Run(tc.name, func(t *testing.T) { + prefix := "[" + tc.token + "," + doc, ok := ParseJSON([]byte(prefix + "42]")) + require.True(t, ok) + items := doc.Content[0].Content + require.Equal(t, tc.decoded, items[0].Value) + require.Equal(t, 1, items[1].Line) + require.Equal(t, len([]rune(prefix))+1, items[1].Column) + }) + } +} + +func TestParseJSONChecksTheWholeInput(t *testing.T) { + for _, input := range []string{`"\uD800\uZZZZ"`, "\"\xff\"", "\"\x1f\"", "true false", `{"a": true}[]`, `[1,]`} { + doc, ok := ParseJSON([]byte(input)) + require.False(t, ok, "%q", input) + require.Nil(t, doc) + } +} + +func TestParseJSONNestingLimit(t *testing.T) { + nested := func(levels int) []byte { + return []byte(`{"v":` + strings.Repeat("[", levels) + "true" + strings.Repeat("]", levels) + "}") + } + source := nested(9999) // root object + 9,999 arrays + doc, ok := ParseJSON(source) + require.True(t, ok) + node := doc.Content[0].Content[1] + for node.Kind == yaml.SequenceNode { + require.Len(t, node.Content, 1) + node = node.Content[0] + } + require.Equal(t, "true", node.Value) + _, ok = Parse(source) + require.False(t, ok) + _, ok = ParseJSON(nested(10000)) + require.False(t, ok) +} From 2a7bc656d064982f606e6217fcaf663fcf5b5666 Mon Sep 17 00:00:00 2001 From: quobix Date: Thu, 26 Nov 2026 10:25:18 -0500 Subject: [PATCH 23/27] Exercise schema loading, reference resolution and native path contracts --- jsonschema/document.go | 10 +- jsonschema/file_url_test.go | 31 ++++ jsonschema/reference.go | 29 ++-- jsonschema/reference_resolution_test.go | 203 ++++++++++++++++++++++++ jsonschema/resource_loading_test.go | 148 +++++++++++++++++ 5 files changed, 404 insertions(+), 17 deletions(-) create mode 100644 jsonschema/file_url_test.go create mode 100644 jsonschema/reference_resolution_test.go create mode 100644 jsonschema/resource_loading_test.go diff --git a/jsonschema/document.go b/jsonschema/document.go index 103b6435..1187faf5 100644 --- a/jsonschema/document.go +++ b/jsonschema/document.go @@ -309,10 +309,11 @@ func (d *Document) indexSchema(source *Source, node *yaml.Node, base *url.URL, p } if id != nil { entry := &index.SchemaIdEntry{Id: id.Value, ResolvedUri: base.String(), SchemaNode: node, Index: source.Index, DefinitionPath: "#" + pointer, Line: id.Line, Column: id.Column} - if err := source.Index.RegisterSchemaId(entry); err != nil { - return err + err := source.Index.RegisterSchemaId(entry) + if err == nil { + err = d.Rolodex.RegisterGlobalSchemaId(entry) } - if err := d.Rolodex.RegisterGlobalSchemaId(entry); err != nil { + if err != nil { return err } delete(d.addresses, base.String()) @@ -386,9 +387,6 @@ func children(node *yaml.Node, visit func(keyword, key string, child *yaml.Node) return fmt.Errorf("line %d: %s requires an object", value.Line, keyword) } for j := 0; j < len(value.Content); j += 2 { - if value.Content[j].Tag != "!!str" { - return fmt.Errorf("line %d: schema keys must be strings", value.Content[j].Line) - } if err := visit(keyword, value.Content[j].Value, value.Content[j+1]); err != nil { return err } diff --git a/jsonschema/file_url_test.go b/jsonschema/file_url_test.go new file mode 100644 index 00000000..841a1b58 --- /dev/null +++ b/jsonschema/file_url_test.go @@ -0,0 +1,31 @@ +// Copyright 2026 Princess B33f Heavy Industries / Dave Shanley +// SPDX-License-Identifier: MIT + +package jsonschema + +import ( + "net/url" + "testing" + + "github.com/pb33f/testify/require" +) + +func TestFileURIVolumeAndPathSyntax(t *testing.T) { + for _, tc := range []struct { + path, volume, uri, native string + separator byte + }{ + {"/catalog/a b.json", "", "file:///catalog/a%20b.json", "/catalog/a b.json", '/'}, + {"//catalog/share/a.json", "", "file:////catalog/share/a.json", "//catalog/share/a.json", '/'}, + {"/C:/catalog/a.json", "", "file:///C:/catalog/a.json", "/C:/catalog/a.json", '/'}, + {"C:/catalog/a.json", "C:", "file:///C:/catalog/a.json", `C:\catalog\a.json`, '\\'}, + {"//server/share/a.json", "//server/share", "file://server/share/a.json", `\\server\share\a.json`, '\\'}, + } { + u := volumeFileURL(tc.path, tc.volume) + require.Equal(t, tc.uri, u.String()) + require.Equal(t, tc.native, nativeFilePath(u, tc.separator)) + } + localhost, err := url.Parse("file://localhost/D:/catalog/a.json") + require.NoError(t, err) + require.Equal(t, `D:\catalog\a.json`, nativeFilePath(localhost, '\\')) +} diff --git a/jsonschema/reference.go b/jsonschema/reference.go index c7506eec..42304c51 100644 --- a/jsonschema/reference.go +++ b/jsonschema/reference.go @@ -25,29 +25,36 @@ var anchorName = regexp.MustCompile(`^[A-Za-z_][-A-Za-z0-9._]*$`) // File URLs have a leading slash before a Windows drive; native file paths do not. func fileURL(filename string) *url.URL { - p := filepath.ToSlash(filename) - u := &url.URL{Scheme: "file", Path: p} - if runtime.GOOS == "windows" { - if strings.HasPrefix(p, "//") { - host, rest, _ := strings.Cut(p[2:], "/") - u.Host, u.Path = host, "/"+rest - } else if filepath.VolumeName(filename) != "" { - u.Path = "/" + p - } + return volumeFileURL(filepath.ToSlash(filename), filepath.ToSlash(filepath.VolumeName(filename))) +} + +// volumeFileURL converts a slash-normalized native path and volume into a file URI. +func volumeFileURL(filename, volume string) *url.URL { + u := &url.URL{Scheme: "file", Path: filename} + if strings.HasPrefix(volume, "//") { + host, rest, _ := strings.Cut(filename[2:], "/") + u.Host, u.Path = host, "/"+rest + } else if volume != "" { + u.Path = "/" + filename } return u } func filePath(u *url.URL) string { + return nativeFilePath(u, filepath.Separator) +} + +func nativeFilePath(u *url.URL, separator byte) string { p := u.Path - if runtime.GOOS == "windows" { + if separator == '\\' { if u.Host != "" && u.Host != "localhost" { p = "//" + u.Host + p } else if len(p) >= 3 && p[0] == '/' && p[2] == ':' { p = p[1:] } + return strings.ReplaceAll(p, "/", "\\") } - return filepath.FromSlash(p) + return p } func (d *Document) resolveReferences() error { diff --git a/jsonschema/reference_resolution_test.go b/jsonschema/reference_resolution_test.go new file mode 100644 index 00000000..287670d2 --- /dev/null +++ b/jsonschema/reference_resolution_test.go @@ -0,0 +1,203 @@ +// Copyright 2026 Princess B33f Heavy Industries / Dave Shanley +// SPDX-License-Identifier: MIT + +package jsonschema_test + +import ( + "errors" + "fmt" + "io" + "io/fs" + "net/http" + "net/http/httptest" + "net/url" + "path/filepath" + "strings" + "testing" + "testing/fstest" + + "github.com/pb33f/libopenapi/datamodel" + "github.com/pb33f/libopenapi/jsonschema" + "github.com/pb33f/testify/require" +) + +type resourceFS func(string) (fs.File, error) + +func (open resourceFS) Open(name string) (fs.File, error) { return open(name) } + +type cachedResource struct { + fs.File + text string + closed bool +} + +func (f *cachedResource) GetContent() string { return f.text } +func (f *cachedResource) Close() error { f.closed = true; return nil } + +func TestReferencePointersAndSourceDiagnostics(t *testing.T) { + const prefix = "prefixItems: [true, false]\n" + d, err := jsonschema.Load([]byte(prefix+"$ref: '#/prefixItems/1'"), "array.yaml", nil, true) + require.NoError(t, err) + require.Len(t, d.References, 1) + require.Equal(t, "false", d.References[0].To.Value) + d.Release() + for _, tc := range []struct{ ref, want string }{ + {"#/prefixItems/01", "no schema at"}, {"#/prefixItems/3", "no schema at"}, + {"#/prefixItems/-1", "no schema at"}, {"#/prefixItems/not-index", "no schema at"}, + {"#absent", "unknown schema anchor"}, {"file://unrelated/share/a.json", "unsupported file URI host"}, + {"child.json", "file references are disabled"}, {"https://schemas.example.test/dep.json", "remote references are disabled"}, + {"urn:unknown", "no registered schema for"}, + } { + t.Run(tc.ref, func(t *testing.T) { + doc, err := jsonschema.Load([]byte(prefix+"properties:\n value:\n $ref: '"+tc.ref+"'"), "array.yaml", nil, true) + require.Nil(t, doc) + require.ErrorContains(t, err, tc.want) + require.ErrorContains(t, err, "array.yaml:4") + }) + } +} + +func TestVirtualFilesUseTheirSnapshotPaths(t *testing.T) { + snapshot := t.TempDir() + cfg := datamodel.NewDocumentConfiguration() + cfg.AllowFileReferences = true + want := filepath.Join(snapshot, "currency.json") + var opened []string + cached := &cachedResource{text: `{"$anchor":"value","type":"string"}`} + cfg.LocalFS = resourceFS(func(name string) (fs.File, error) { + opened = append(opened, name) + if name == want { + return cached, nil + } + return nil, fs.ErrInvalid + }) + doc, err := jsonschema.Load([]byte(`{"$ref":"currency.json#value"}`), filepath.Join(snapshot, "order.json"), cfg, true) + require.NoError(t, err) + defer doc.Release() + require.Equal(t, []string{"currency.json", want}, opened) + require.True(t, cached.closed) + require.Same(t, doc.Sources["currency.json"].Node, doc.References[0].To) + require.Equal(t, cached.text, string(doc.Sources["currency.json"].Data)) +} + +func TestRemoteVirtualFileErrors(t *testing.T) { + cfg := datamodel.NewDocumentConfiguration() + cfg.AllowRemoteReferences = true + const target = "https://schemas.example.test/types/currency.json" + var location string + load := func(open resourceFS) error { + cfg.RemoteFS = resourceFS(func(name string) (fs.File, error) { location = name; return open(name) }) + doc, err := jsonschema.Load([]byte(`{"$ref":"`+target+`"}`), "order.json", cfg, true) + require.Equal(t, target, location) + if doc != nil { + doc.Release() + } + return err + } + require.ErrorIs(t, load(func(string) (fs.File, error) { return nil, fs.ErrPermission }), fs.ErrPermission) + require.ErrorContains(t, load(func(string) (fs.File, error) { return nil, nil }), "missing file") + require.NoError(t, load(func(string) (fs.File, error) { + return fstest.MapFS{"currency.json": {Data: []byte("true")}}.Open("currency.json") + })) +} + +func TestRemoteResponsesAndTransportErrors(t *testing.T) { + const root = "https://name:password@schemas.example.test/root.json" + const input = `{"$ref":"currency.json"}` + cfg := datamodel.NewDocumentConfiguration() + cfg.AllowRemoteReferences = true + cause := errors.New("upstream unavailable") + for _, tc := range []struct { + name string + get func(string) (*http.Response, error) + want string + wrap bool + }{ + {"status", func(string) (*http.Response, error) { + return &http.Response{StatusCode: 503, Body: io.NopCloser(strings.NewReader(""))}, nil + }, "HTTP 503", false}, + {"plain error", func(string) (*http.Response, error) { return nil, cause }, cause.Error(), true}, + {"credentialed transport", func(location string) (*http.Response, error) { + return nil, &url.Error{Op: "Get", URL: location, Err: cause} + }, cause.Error(), true}, + {"invalid sibling", func(string) (*http.Response, error) { + return &http.Response{StatusCode: 200, Body: io.NopCloser(strings.NewReader("type: not-a-type"))}, nil + }, "currency.json", false}, + } { + t.Run(tc.name, func(t *testing.T) { + cfg.RemoteURLHandler = tc.get + doc, err := jsonschema.Load([]byte(input), root, cfg, true) + require.Nil(t, doc) + require.ErrorContains(t, err, tc.want) + require.NotContains(t, err.Error(), "password") + if tc.wrap { + require.ErrorIs(t, err, cause) + } + }) + } + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path != "/currency.json" { + http.NotFound(w, r) + return + } + _, _ = io.WriteString(w, `{"$anchor":"iso","type":"string"}`) + })) + defer server.Close() + cfg.RemoteURLHandler = nil + doc, err := jsonschema.Load([]byte(`{"$ref":"currency.json#iso"}`), server.URL+"/root.json", cfg, true) + require.NoError(t, err) + defer doc.Release() + require.Same(t, doc.Sources[server.URL+"/currency.json"].Node, doc.References[0].To) +} + +func TestCollectionResolvesExplicitAndOutsideAddresses(t *testing.T) { + dir := t.TempDir() + cfg := datamodel.NewDocumentConfiguration() + cfg.BasePath = dir + cfg.LocalFS = resourceFS(func(name string) (fs.File, error) { + switch name { + case "types/currency.json", "../shared.json": + return fstest.MapFS{"spec.json": {Data: []byte("true")}}.Open("spec.json") + default: + return nil, fs.ErrNotExist + } + }) + members := map[string][]byte{"order.json": []byte(`{"allOf":[{"$ref":"types/currency.json"},{"$ref":"../shared.json"}]}`)} + doc, err := jsonschema.LoadCollection(members, dir, cfg) + require.NoError(t, err) + require.Len(t, doc.Sources, 3) + require.Same(t, doc.Sources["../shared.json"].Node, doc.References[1].To) + doc.Release() + for _, tc := range []struct{ ref, want string }{ + {"file://unrelated/some.json", "unsupported file URI host"}, {"absent.json", "file does not exist"}, + {"file:relative.json", "Rel:"}, + } { + members["order.json"] = []byte(fmt.Sprintf(`{"$ref":%q}`, tc.ref)) + doc, err = jsonschema.LoadCollection(members, dir, cfg) + require.Nil(t, doc) + require.ErrorContains(t, err, tc.want) + } +} + +func TestUnusableRemoteBaseCannotResolveSibling(t *testing.T) { + cfg := datamodel.NewDocumentConfiguration() + cfg.BaseURL = &url.URL{Scheme: "https", Host: "schemas.example.test:invalid"} + cfg.AllowRemoteReferences = true + doc, err := jsonschema.Load([]byte(`{"$ref":"other.json"}`), "root.json", cfg, true) + require.Nil(t, doc) + require.ErrorContains(t, err, "invalid port") +} + +func TestCollectionRetrievalAliasCannotHideAnEmbeddedID(t *testing.T) { + base := t.TempDir() + cfg := datamodel.NewDocumentConfiguration() + cfg.BasePath = filepath.Join(base, "dependencies") + // The dependency claims the missing snapshot address for a nested + // resource. Registering its root at that address would resolve the + // original reference to a different node depending on lookup order. + cfg.LocalFS = fstest.MapFS{"currency.json": {Data: []byte(`{"$defs":{"shadow":{"$id":"../snapshot/currency.json"}}}`)}} + doc, err := jsonschema.LoadCollection(map[string][]byte{"order.json": []byte(`{"$ref":"currency.json"}`)}, filepath.Join(base, "snapshot"), cfg) + require.ErrorContains(t, err, "duplicate schema address") + require.ErrorContains(t, err, "currency.json") + require.Nil(t, doc) +} diff --git a/jsonschema/resource_loading_test.go b/jsonschema/resource_loading_test.go new file mode 100644 index 00000000..ec096982 --- /dev/null +++ b/jsonschema/resource_loading_test.go @@ -0,0 +1,148 @@ +// Copyright 2026 Princess B33f Heavy Industries / Dave Shanley +// SPDX-License-Identifier: MIT + +package jsonschema_test + +import ( + "errors" + "io/fs" + "net/url" + "os" + "path/filepath" + "runtime" + "testing" + "testing/fstest" + + "github.com/pb33f/libopenapi/datamodel" + "github.com/pb33f/libopenapi/jsonschema" + "github.com/pb33f/testify/require" +) + +func TestResourceLabelsOwnershipAndRelease(t *testing.T) { + schema := []byte(`title: Customer +$vocabulary: + https://json-schema.org/draft/2020-12/vocab/validation: true + https://schemas.example.test/optional: false +properties: + kind: false +$defs: + data: {$id: 'types/data?version=2'} +examples: + - {type: string} +`) + doc, err := jsonschema.Load(schema, "", nil, true) + require.NoError(t, err) + require.Len(t, doc.Resources, 2) + require.Equal(t, "schema.yaml", doc.Root.ID) + require.Equal(t, "Customer", doc.Root.Label()) + resource := doc.Resources[1] + require.Equal(t, "types/data?version=2", resource.ID) + require.Equal(t, "data?version=2", resource.Label()) + require.Equal(t, "/$defs/data", resource.Pointer) + require.Same(t, doc.Root.Source, resource.Source) + registered := resource.Source.Index.GetAllSchemaIds() + require.Len(t, registered, 1) + for id, entry := range registered { + require.Same(t, resource.Node, entry.SchemaNode) + require.Same(t, entry, doc.Rolodex.LookupSchemaById(id)) + } + root := doc.Root.Node + require.True(t, doc.IsSchema(root)) + require.True(t, doc.IsSchema(resource.Node)) + require.False(t, doc.IsSchema(root.Content[0])) // the title key + require.False(t, doc.IsSchema(root.Content[len(root.Content)-1].Content[0])) // an example + doc.Release() + require.False(t, doc.IsSchema(root)) + require.Nil(t, doc.Root) + require.Nil(t, doc.Sources) + require.Nil(t, doc.Rolodex) + doc.Release() + var unloaded *jsonschema.Document + require.False(t, unloaded.IsSchema(root)) + unloaded.Release() +} + +func TestSchemaLabelWithoutBasename(t *testing.T) { + doc, err := jsonschema.Load([]byte("$id: ."), "root.yml", nil, true) + require.NoError(t, err) + defer doc.Release() + require.Equal(t, "Schema", doc.Root.Label()) +} + +func TestConfiguredRetrievalBaseAndFilename(t *testing.T) { + base, err := url.Parse("https://schemas.example.test/releases") + require.NoError(t, err) + for _, source := range []string{"local/overridden.json", "https://old.example.test/files/overridden.json?signature=old"} { + cfg := datamodel.NewDocumentConfiguration() + cfg.SpecFilePath, cfg.BaseURL = source, base + doc, err := jsonschema.Load([]byte(`{"type":"string"}`), "order.yml", cfg, true) + require.NoError(t, err) + require.Equal(t, "overridden.json", doc.Root.ID) + require.Equal(t, "https://schemas.example.test/releases/overridden.json", doc.Root.Source.Name) + require.Equal(t, doc.Root.Source.Name, doc.Root.Source.Index.GetSpecAbsolutePath()) + doc.Release() + } +} + +func TestRejectAmbiguousOrInvalidSchemaResources(t *testing.T) { + for _, tc := range []struct{ name, input, want string }{ + {"JSON extension", "type: string", "invalid JSON in invalid.json"}, + {"non-object vocabulary", `{"$vocabulary":true}`, "$vocabulary must be an object"}, + {"vocabulary boolean", `{"$vocabulary":{"https://schemas.example.test/optional":"no"}}`, "vocabulary requirement must be boolean"}, + {"unknown vocabulary shorthand", `{"$vocabulary":{"core":true}}`, "unsupported required vocabulary"}, + {"ID fragment", `{"$id":"urn:example#part"}`, "invalid schema $id"}, + {"empty ID", `{"$id":""}`, "$id cannot be empty"}, + {"anchor syntax", `{"$anchor":"1value"}`, "invalid $anchor"}, + {"ambiguous anchor", `{"$defs":{"a":{"$anchor":"town"},"b":{"$anchor":"town"}}}`, "duplicate schema address"}, + {"invalid pointer URI", `{"$ref":"bad%XY"}`, "invalid $ref"}, + {"single schema", `{"not":17}`, "schema must be an object or boolean"}, + {"schema map", `{"properties":true}`, "properties requires an object"}, + {"non-string map key", "properties: {17: {}}", "JSON object keys must be strings"}, + {"schema list", `{"allOf":{}}`, "allOf requires an array"}, + {"schema list operand", `{"allOf":[false,17]}`, "schema must be an object or boolean"}, + } { + t.Run(tc.name, func(t *testing.T) { + doc, err := jsonschema.Load([]byte(tc.input), "invalid.json", nil, true) + require.ErrorContains(t, err, tc.want) + require.Nil(t, doc) + }) + } + // A declared ID can take a later member's retrieval URI. + doc, err := jsonschema.LoadCollection(map[string][]byte{ + "a.json": []byte(`{"$id":"b.json"}`), "b.json": []byte(`{"$id":"urn:different"}`), + }, t.TempDir(), nil) + require.ErrorContains(t, err, "duplicate schema address") + require.ErrorContains(t, err, "a.json:1") + require.ErrorContains(t, err, "b.json:1") + require.Nil(t, doc) +} + +func TestRelativeLoadingAfterWorkingDirectoryWasRemoved(t *testing.T) { + if runtime.GOOS == "windows" { + t.Skip("Windows retains the current directory while a process uses it") + } + cwd := t.TempDir() + root := filepath.Join(cwd, "root.json") + t.Chdir(cwd) + t.Setenv("PWD", "/") + require.NoError(t, os.Chmod(cwd, 0)) + require.NoError(t, os.Remove(cwd)) + got, cwdErr := os.Getwd() + if cwdErr == nil { + t.Skipf("host can still resolve the removed working directory as %q", got) + } + wantErr := fs.ErrNotExist + if errors.Is(cwdErr, fs.ErrPermission) { + wantErr = fs.ErrPermission + } + _, err := jsonschema.Load([]byte("true"), "root.json", nil, true) + require.ErrorIs(t, err, wantErr) + _, err = jsonschema.LoadCollection(nil, ".", nil) + require.ErrorIs(t, err, wantErr) + + cfg := datamodel.NewDocumentConfiguration() + cfg.BasePath = "schemas" + cfg.LocalFS = fstest.MapFS{"child.json": {Data: []byte("true")}} + _, err = jsonschema.Load([]byte(`{"$ref":"child.json"}`), root, cfg, true) + require.ErrorIs(t, err, wantErr) +} From 18f9f3f85307bca30bb68a519f98085005de21d4 Mon Sep 17 00:00:00 2001 From: quobix Date: Thu, 26 Nov 2026 10:27:37 -0500 Subject: [PATCH 24/27] Keep native schema filenames when resolving an explicit base URL --- jsonschema/document.go | 3 ++- jsonschema/resource_loading_test.go | 17 +++++++++++++---- 2 files changed, 15 insertions(+), 5 deletions(-) diff --git a/jsonschema/document.go b/jsonschema/document.go index 1187faf5..d3dde70b 100644 --- a/jsonschema/document.go +++ b/jsonschema/document.go @@ -138,7 +138,8 @@ func retrievalURI(source string, config *datamodel.DocumentConfiguration) (*url. base := *config.BaseURL base.Path = strings.TrimSuffix(base.Path, "/") + "/" filename := filepath.Base(source) - if err == nil && original.IsAbs() { + // A drive path or a Unix filename with a colon can parse as a URI scheme. + if err == nil && original.IsAbs() && original.Opaque == "" && !filepath.IsAbs(source) { filename = path.Base(original.Path) } return base.ResolveReference(&url.URL{Path: filename}), nil diff --git a/jsonschema/resource_loading_test.go b/jsonschema/resource_loading_test.go index ec096982..6c2528d6 100644 --- a/jsonschema/resource_loading_test.go +++ b/jsonschema/resource_loading_test.go @@ -72,13 +72,22 @@ func TestSchemaLabelWithoutBasename(t *testing.T) { func TestConfiguredRetrievalBaseAndFilename(t *testing.T) { base, err := url.Parse("https://schemas.example.test/releases") require.NoError(t, err) - for _, source := range []string{"local/overridden.json", "https://old.example.test/files/overridden.json?signature=old"} { + type sourceFile struct{ source, filename string } + files := []sourceFile{ + {"local/overridden.json", "overridden.json"}, + {filepath.Join(t.TempDir(), "overridden.json"), "overridden.json"}, + {"https://old.example.test/files/overridden.json?signature=old", "overridden.json"}, + } + if runtime.GOOS != "windows" { + files = append(files, sourceFile{"catalog:v2.json", "catalog:v2.json"}) + } + for _, file := range files { cfg := datamodel.NewDocumentConfiguration() - cfg.SpecFilePath, cfg.BaseURL = source, base + cfg.SpecFilePath, cfg.BaseURL = file.source, base doc, err := jsonschema.Load([]byte(`{"type":"string"}`), "order.yml", cfg, true) require.NoError(t, err) - require.Equal(t, "overridden.json", doc.Root.ID) - require.Equal(t, "https://schemas.example.test/releases/overridden.json", doc.Root.Source.Name) + require.Equal(t, file.filename, doc.Root.ID) + require.Equal(t, "https://schemas.example.test/releases/"+file.filename, doc.Root.Source.Name) require.Equal(t, doc.Root.Source.Name, doc.Root.Source.Index.GetSpecAbsolutePath()) doc.Release() } From e36828c16a54d5704cb47b365326d9b167ac60dc Mon Sep 17 00:00:00 2001 From: quobix Date: Thu, 26 Nov 2026 10:29:02 -0500 Subject: [PATCH 25/27] Report schema child traversal errors during comparison --- jsonschema/compare.go | 15 ++++++--- jsonschema/compare_cases_test.go | 53 ++++++++++++++++++++++++++++++++ 2 files changed, 64 insertions(+), 4 deletions(-) diff --git a/jsonschema/compare.go b/jsonschema/compare.go index d55970c3..a9a6c8c3 100644 --- a/jsonschema/compare.go +++ b/jsonschema/compare.go @@ -333,16 +333,16 @@ func constraintProxy(n *yaml.Node, r *Resource) (*base.SchemaProxy, error) { type childKey struct{ keyword, key string } -func childNodes(n *yaml.Node) map[childKey]*yaml.Node { +func childNodes(n *yaml.Node) (map[childKey]*yaml.Node, error) { var nodes map[childKey]*yaml.Node - _ = children(n, func(kw, k string, child *yaml.Node) error { + err := children(n, func(kw, k string, child *yaml.Node) error { if nodes == nil { nodes = make(map[childKey]*yaml.Node) } nodes[childKey{kw, k}] = child return nil }) - return nodes + return nodes, err } func sameNode(a, b *yaml.Node) bool { @@ -559,7 +559,14 @@ func exactNumber(k string) bool { } func (c *comparison) compareChildren(l, r *Resource, left, right *yaml.Node, path string, polarity int) error { - old, newNodes := childNodes(left), childNodes(right) + old, err := childNodes(left) + if err != nil { + return fmt.Errorf("original %s at %s: %w", l.Source.Name, path, err) + } + newNodes, err := childNodes(right) + if err != nil { + return fmt.Errorf("modified %s at %s: %w", r.Source.Name, path, err) + } // allOf, anyOf, and oneOf have unordered operands. Match identical branches // before comparing the remaining positions. prefixItems is an ordered tuple. for _, kw := range []string{"allOf", "anyOf", "oneOf"} { diff --git a/jsonschema/compare_cases_test.go b/jsonschema/compare_cases_test.go index 7311cf4c..5645e0f4 100644 --- a/jsonschema/compare_cases_test.go +++ b/jsonschema/compare_cases_test.go @@ -235,3 +235,56 @@ func TestInvalidInMemoryDependencyStopsComparison(t *testing.T) { }) } } + +func TestCompareRejectsMalformedSchemaChildrenAfterLoad(t *testing.T) { + for _, tc := range []struct { + name, schema, path, diagnostic string + edit func(*yaml.Node) + }{ + { + name: "property name", + schema: `{ + "properties": { + "1": { "type": "integer" } + } +}`, + path: "$", + diagnostic: "line 3: schema keys must be strings", + edit: func(root *yaml.Node) { + member(root, "properties").Content[0].Tag = "!!int" + }, + }, + { + name: "array applicator below a property", + schema: `{ + "title":"Original", + "properties":{ + "status":{ + "anyOf":[true, false] + } + } +}`, + path: "$.properties.status", + diagnostic: "line 5: anyOf requires an array", + edit: func(root *yaml.Node) { + member(root, "title").Value = "Edited" + choices := member(member(member(root, "properties"), "status"), "anyOf") + choices.Kind, choices.Tag, choices.Content = yaml.MappingNode, "!!map", nil + }, + }, + } { + t.Run(tc.name, func(t *testing.T) { + good, bad := loadTest(t, tc.schema), loadTest(t, tc.schema) + tc.edit(bad.Root.Node) + for _, pair := range []struct { + left, right *Document + side string + }{{bad, good, "original"}, {good, bad, "modified"}} { + diff, err := Compare(pair.left, pair.right, nil) + require.ErrorContains(t, err, pair.side+" customer.yaml at "+tc.path) + require.ErrorContains(t, err, tc.diagnostic) + require.Nil(t, diff) + } + }) + } +} From 3b07cb139b1bc1cf03b5461a84dfcbe06b1adce5 Mon Sep 17 00:00:00 2001 From: quobix Date: Thu, 26 Nov 2026 10:29:05 -0500 Subject: [PATCH 26/27] Redact schema reference diagnostics and validate edited map keys --- jsonschema/document.go | 13 +++++++-- jsonschema/reference.go | 15 +++++++++-- jsonschema/reference_resolution_test.go | 35 +++++++++++++++++++++++++ 3 files changed, 59 insertions(+), 4 deletions(-) diff --git a/jsonschema/document.go b/jsonschema/document.go index d3dde70b..144c3f1d 100644 --- a/jsonschema/document.go +++ b/jsonschema/document.go @@ -169,10 +169,15 @@ func (d *Document) resourceID(uri *url.URL) string { return identity.String() } -func (d *Document) sourceName(uri *url.URL) string { +func withoutRetrievalCredentials(uri *url.URL) url.URL { safe := *uri safe.User = nil safe.RawQuery = "" + return safe +} + +func (d *Document) sourceName(uri *url.URL) string { + safe := withoutRetrievalCredentials(uri) name := d.resourceID(&safe) if uri.RawQuery != "" || uri.User != nil { // Signed retrieval URLs must not leak credentials or collide in report source maps. @@ -388,7 +393,11 @@ func children(node *yaml.Node, visit func(keyword, key string, child *yaml.Node) return fmt.Errorf("line %d: %s requires an object", value.Line, keyword) } for j := 0; j < len(value.Content); j += 2 { - if err := visit(keyword, value.Content[j].Value, value.Content[j+1]); err != nil { + key := value.Content[j] + if key.Kind != yaml.ScalarNode || key.Tag != "!!str" { + return fmt.Errorf("line %d: schema keys must be strings", key.Line) + } + if err := visit(keyword, key.Value, value.Content[j+1]); err != nil { return err } } diff --git a/jsonschema/reference.go b/jsonschema/reference.go index 42304c51..67cc6434 100644 --- a/jsonschema/reference.go +++ b/jsonschema/reference.go @@ -57,17 +57,28 @@ func nativeFilePath(u *url.URL, separator byte) string { return p } +// diagnosticTarget preserves the authored spelling of ordinary references. +// indexSchema has already parsed the reference before resolution starts. +func (ref Reference) diagnosticTarget() string { + uri, _ := url.Parse(ref.Value) + if uri.User == nil && uri.RawQuery == "" { + return ref.Value + } + safe := withoutRetrievalCredentials(uri) + return safe.String() +} + func (d *Document) resolveReferences() error { for i := 0; i < len(d.References); i++ { ref := d.References[i] target, err := d.resolve(ref.address, ref.Value) if err != nil { - return fmt.Errorf("%s:%d: resolve %s %q: %w", d.schemas[ref.From].Source.Name, ref.From.Line, ref.Keyword, ref.Value, err) + return fmt.Errorf("%s:%d: resolve %s %q: %w", d.schemas[ref.From].Source.Name, member(ref.From, ref.Keyword).Line, ref.Keyword, ref.diagnosticTarget(), err) } if ref.Keyword == "$dynamicRef" { u, _ := url.Parse(ref.address) if anchor := member(target, "$dynamicAnchor"); anchor != nil && u.Fragment == anchor.Value { - return fmt.Errorf("%s:%d: dynamic scope resolution for $dynamicRef %q is unsupported", d.schemas[ref.From].Source.Name, ref.From.Line, ref.Value) + return fmt.Errorf("%s:%d: dynamic scope resolution for $dynamicRef %q is unsupported", d.schemas[ref.From].Source.Name, member(ref.From, ref.Keyword).Line, ref.diagnosticTarget()) } } d.References[i].To = target diff --git a/jsonschema/reference_resolution_test.go b/jsonschema/reference_resolution_test.go index 287670d2..5241088c 100644 --- a/jsonschema/reference_resolution_test.go +++ b/jsonschema/reference_resolution_test.go @@ -150,6 +150,41 @@ func TestRemoteResponsesAndTransportErrors(t *testing.T) { require.Same(t, doc.Sources[server.URL+"/currency.json"].Node, doc.References[0].To) } +func TestReferenceDiagnosticsPreserveLocationAndRedactCredentials(t *testing.T) { + const root = "https://schemas.example.test/order.yaml" + cause := errors.New("upstream unavailable") + for _, tc := range []struct{ keyword, ref, label string }{ + {"$ref", "https://reader:private@types.example.test/money.json?signature=secret#currency", "https://types.example.test/money.json#currency"}, + {"$ref", "types/money.json?signature=secret#currency", "types/money.json#currency"}, + {"$ref", "../types/money.json#currency", "../types/money.json#currency"}, + {"$dynamicRef", "https://reader:private@types.example.test/money.json?signature=secret#currency", "https://types.example.test/money.json#currency"}, + } { + t.Run(tc.keyword+tc.label, func(t *testing.T) { + cfg := datamodel.NewDocumentConfiguration() + cfg.AllowRemoteReferences = true + cfg.RemoteURLHandler = func(location string) (*http.Response, error) { + if tc.keyword == "$dynamicRef" { + return &http.Response{StatusCode: 200, Body: io.NopCloser(strings.NewReader(`{"$dynamicAnchor":"currency"}`))}, nil + } + return nil, &url.Error{Op: "Get", URL: location, Err: cause} + } + data := fmt.Sprintf("properties:\n amount:\n title: Amount\n %s: %q\n", tc.keyword, tc.ref) + _, err := jsonschema.Load([]byte(data), root, cfg, true) + require.ErrorContains(t, err, root+":4:") + require.ErrorContains(t, err, fmt.Sprintf("%s %q", tc.keyword, tc.label)) + require.NotContains(t, err.Error(), "reader") + require.NotContains(t, err.Error(), "private") + require.NotContains(t, err.Error(), "signature") + require.NotContains(t, err.Error(), "secret") + if tc.keyword == "$ref" { + require.ErrorIs(t, err, cause) + } else { + require.ErrorContains(t, err, "dynamic scope") + } + }) + } +} + func TestCollectionResolvesExplicitAndOutsideAddresses(t *testing.T) { dir := t.TempDir() cfg := datamodel.NewDocumentConfiguration() From 18eb8107c9d015f0ad6c6d76aa42c0a9c5b28aec Mon Sep 17 00:00:00 2001 From: quobix Date: Thu, 26 Nov 2026 15:07:19 -0500 Subject: [PATCH 27/27] Tighten native schema verdicts, diagnostics and numeric bounds Declaring the dialect and removing a widening applicator no longer report as breaking. Out-of-range numeric bounds are compared without expansion. Load errors name their file, earlier-draft keywords in an unmarked schema are rejected, and a failed collection member is a typed MemberError. Co-Authored-By: Claude Fable 5.2 --- README.md | 12 ++++ datamodel/schema_node.go | 2 +- datamodel/schema_node_test.go | 2 +- jsonschema/collection.go | 13 +++- jsonschema/compare.go | 81 ++++++++++++++----------- jsonschema/compare_test.go | 73 ++++++++++++++++++++++ jsonschema/document.go | 65 +++++++++++++++----- jsonschema/loader_test.go | 8 ++- jsonschema/reference.go | 6 +- jsonschema/reference_resolution_test.go | 24 ++++++++ jsonschema/resource_loading_test.go | 9 ++- utils/enum.go | 14 +++-- utils/enum_test.go | 10 +++ 13 files changed, 254 insertions(+), 65 deletions(-) diff --git a/README.md b/README.md index d9cd08b4..40e82ffa 100644 --- a/README.md +++ b/README.md @@ -106,6 +106,18 @@ and the directory for that snapshot. It registers each member before resolving references. Each change carries its resource ID, local JSONPath, and source locations. Releases and breaking-rule overrides work the same for either input. +The third argument to `Compare` holds explicit overrides only. A rule replaces +the verdict for its keyword in both directions, so pass `nil` for the +direction-aware defaults and never the merged default rules. + +Draft 2020-12 is the only supported dialect. These inputs return an error: + +- a `$schema` that names another dialect +- a `$dynamicRef` that needs dynamic scope resolution +- a schema without `$schema` that uses a keyword from an earlier draft, such as + `definitions` or `dependencies` +- YAML anchors, aliases, and keys that are not strings + ### Generating TypeScript models `generator/typescript` renders the component schemas of an OpenAPI document as diff --git a/datamodel/schema_node.go b/datamodel/schema_node.go index 682c79bd..cc5c99f5 100644 --- a/datamodel/schema_node.go +++ b/datamodel/schema_node.go @@ -53,7 +53,7 @@ func checkSchemaKeys(n *yaml.Node) error { for i := 0; i < len(n.Content); i += 2 { key := n.Content[i] if key.Kind != yaml.ScalarNode || key.Tag != "!!str" { - return fmt.Errorf("line %d: JSON object keys must be strings", key.Line) + return fmt.Errorf("line %d: JSON object keys must be strings (quote the key in YAML)", key.Line) } if line, ok := seen[key.Value]; ok { return fmt.Errorf("line %d: mapping key %q already defined at line %d", key.Line, key.Value, line) diff --git a/datamodel/schema_node_test.go b/datamodel/schema_node_test.go index f42c951d..1633303e 100644 --- a/datamodel/schema_node_test.go +++ b/datamodel/schema_node_test.go @@ -22,7 +22,7 @@ func TestDecodeSchemaNodeReadsOneDocument(t *testing.T) { {"malformed JSON string", "{\"title\":\"\xff\"}", "invalid JSON schema document"}, {"duplicate escaped JSON key", "{\n \"properties\": {\n \"name\": true,\n \"na\\u006de\": false}}", `line 4: mapping key "name" already defined at line 3`}, {"duplicate inside YAML example", "examples:\n - name: first\n name: second\n", `line 3: mapping key "name" already defined at line 2`}, - {"numeric YAML key", "properties:\n 42: false\n", "line 2: JSON object keys must be strings"}, + {"numeric YAML key", "properties:\n 42: false\n", "line 2: JSON object keys must be strings (quote the key in YAML)"}, {"complex YAML key", "properties:\n ? [a,b]\n : false\n", "line 2: JSON object keys must be strings"}, {"YAML timestamp", "const: 2026-11-25\n", "line 1: unsupported JSON scalar !!timestamp"}, {"YAML alias", "$defs: &shape {}\nproperties:\n x: *shape\n", "line 3: expected JSON-compatible YAML"}, diff --git a/jsonschema/collection.go b/jsonschema/collection.go index de0f57f5..cf38221c 100644 --- a/jsonschema/collection.go +++ b/jsonschema/collection.go @@ -15,6 +15,17 @@ import ( "github.com/pb33f/libopenapi/datamodel" ) +// MemberError identifies the collection member that failed to load. Its text is +// the member's own diagnostic, which already names the file. +type MemberError struct { + Name string + Err error +} + +func (e *MemberError) Error() string { return e.Err.Error() } + +func (e *MemberError) Unwrap() error { return e.Err } + // LoadCollection registers all named schema sources before resolving references. // Names are slash-separated paths relative to directory. An empty snapshot is valid. // The returned document has a nil Root and one entry in Sources per physical file. @@ -37,7 +48,7 @@ func LoadCollection(members map[string][]byte, directory string, config *datamod uri := base.ResolveReference(&url.URL{Path: name}) if _, err := d.addSource(members[name], uri, true); err != nil { d.Release() - return nil, fmt.Errorf("schema member %s: %w", name, err) + return nil, &MemberError{Name: name, Err: err} } } if err := d.resolveReferences(); err != nil { diff --git a/jsonschema/compare.go b/jsonschema/compare.go index a9a6c8c3..22d0f1a8 100644 --- a/jsonschema/compare.go +++ b/jsonschema/compare.go @@ -8,7 +8,6 @@ import ( "context" "encoding/json" "fmt" - "math/big" "slices" "strconv" "strings" @@ -22,6 +21,12 @@ import ( // Compare uses the schema comparator on authored constraints. Each referenced // resource is compared once, independent of the number of references to it. +// +// rules holds explicit overrides only. Each rule it contains replaces the +// verdict for that keyword in both directions, so merged defaults such as +// GenerateDefaultBreakingRules would mark a widening edit as breaking. Pass nil +// for the direction-aware defaults. A root replaced by a boolean, or the +// reverse, has no keyword and no override. func Compare(left, right *Document, rules *wc.BreakingRulesConfig) (*wc.SchemaChanges, error) { if left == nil || right == nil { return nil, fmt.Errorf("both JSON Schema inputs are required") @@ -124,7 +129,7 @@ func (c *comparison) resources() error { // An embedded resource participates in its containing applicator, // even when neither side references its address. polarity := combinedPolarity(1, l.context|r.context) - if err := c.schema(l, r, l.Node, r.Node, "$", "type", polarity); err != nil { + if err := c.schema(l, r, l.Node, r.Node, "$", "schema", polarity); err != nil { return err } } @@ -225,16 +230,11 @@ func (c *comparison) schema(l, r *Resource, left, right *yaml.Node, path, keywor start := len(c.changes) breaking := keyword == "$ref" || a != nil if exactNumber(keyword) && a != nil && b != nil { - x, ok := new(big.Rat).SetString(a.Value) - y, ok2 := new(big.Rat).SetString(b.Value) - if ok && ok2 && x.Cmp(y) == 0 { + if order, ok := numericOrder(a.Value, b.Value); ok && order == 0 { continue } } wc.CreateChange(&c.changes, kind, keyword, a, b, breaking, nil, nil) - if exactNumber(keyword) { - breaking = compatibility(c.changes[start], keyword) - } direction := polarity if impact, ok := validationChange(keyword, a, b, polarity); ok { direction, breaking = 1, impact @@ -520,16 +520,38 @@ func validationChange(keyword string, a, b *yaml.Node, polarity int) (breaking, if a == nil || b == nil { return polarity == 0 || b != nil, true } - x, ok1 := new(big.Rat).SetString(a.Value) - y, ok2 := new(big.Rat).SetString(b.Value) + x, ok1 := utils.ParseBoundedRat(a.Value) + y, ok2 := utils.ParseBoundedRat(b.Value) breaking = !ok1 || !ok2 || y.Sign() == 0 || !x.Quo(x, y).IsInt() + case "minimum", "exclusiveMinimum", "minLength", "minItems", "minProperties", "minContains", "maximum", "exclusiveMaximum", "maxLength", "maxItems", "maxProperties", "maxContains": + if a == nil || b == nil { + breaking = b != nil + break + } + // An unknown order is breaking under any polarity. + order, ok := numericOrder(a.Value, b.Value) + if strings.HasPrefix(keyword, "max") || keyword == "exclusiveMaximum" { + order = -order + } + breaking = !ok || order > 0 default: return false, false } return polarity == 0 || breaking, true } -func childMembership(keyword string, whole, added bool, polarity int) bool { +// numericOrder compares two authored numbers exactly and returns the sign of +// b-a. It reports false for a literal beyond the exact-arithmetic limits. +func numericOrder(a, b string) (int, bool) { + x, ok1 := utils.ParseBoundedRat(a) + y, ok2 := utils.ParseBoundedRat(b) + if !ok1 || !ok2 { + return 0, false + } + return y.Cmp(x), true +} + +func (c *comparison) childMembership(keyword string, whole, added bool, polarity int) bool { if keyword == "contentSchema" { return false } @@ -544,8 +566,12 @@ func childMembership(keyword string, whole, added bool, polarity int) bool { // Adding the first disjunction restricts the schema. Adding an // alternative to an existing disjunction widens it. return (whole == added) == (polarity > 0) - case "allOf", "dependentSchemas": + case "not", "propertyNames": return added == (polarity > 0) + case "allOf", "dependentSchemas", "additionalProperties", "unevaluatedProperties", "unevaluatedItems", "items", "contains", "if", "then", "else": + // These also mark locations as evaluated. Changing one can make a + // surviving unevaluated keyword reject what it accepted before. + return c.right.unevaluated || added == (polarity > 0) } return true } @@ -629,7 +655,7 @@ func (c *comparison) compareChildren(l, r *Resource, left, right *yaml.Node, pat if owner := c.left.schemas[a]; owner != l && c.pairs[owner] == nil { continue } - breaking := childMembership(k.keyword, member(right, k.keyword) == nil, false, polarity) + breaking := c.childMembership(k.keyword, member(right, k.keyword) == nil, false, polarity) c.membership(l, r, p, k.keyword, a, nil, breaking) continue } @@ -642,7 +668,7 @@ func (c *comparison) compareChildren(l, r *Resource, left, right *yaml.Node, pat } } for k, b := range newNodes { - breaking := childMembership(k.keyword, member(left, k.keyword) == nil, true, polarity) + breaking := c.childMembership(k.keyword, member(left, k.keyword) == nil, true, polarity) if owner := c.right.schemas[b]; owner != r && !c.matched[owner] { if breaking && !c.annotationOnly { if c.appliedAdditions == nil { @@ -745,22 +771,6 @@ func compatibility(ch *wc.Change, property string) bool { return ch.ChangeType != wc.PropertyRemoved case "$id", "$dynamicAnchor": return ch.ChangeType != wc.PropertyAdded - case "minimum", "exclusiveMinimum", "minLength", "minItems", "minProperties", "minContains", "maximum", "exclusiveMaximum", "maxLength", "maxItems", "maxProperties", "maxContains": - if ch.ChangeType == wc.PropertyRemoved { - return false - } - if ch.ChangeType == wc.PropertyAdded { - return true - } - a, ok := new(big.Rat).SetString(ch.Original) - b, ok2 := new(big.Rat).SetString(ch.New) - if ok && ok2 { - sign := b.Cmp(a) - if strings.HasPrefix(property, "max") || property == "exclusiveMaximum" { - return sign < 0 - } - return sign > 0 - } } if rule := standaloneDefaults.GetRule(wc.CompSchema, property); rule != nil { if value := operationRule(rule, ch.ChangeType); value != nil { @@ -785,17 +795,14 @@ func operationRule(rule *wc.BreakingChangeRule, kind int) *bool { func (c *comparison) finish(ch *wc.Change, l, r *Resource, path, property string, polarity int, breaking bool) { switch property { - case "description", "title", "$comment", "default", "examples", "readOnly", "writeOnly", "deprecated", "format", "contentMediaType", "contentEncoding": + case "$schema", "description", "title", "$comment", "default", "examples", "readOnly", "writeOnly", "deprecated", "format", "contentMediaType", "contentEncoding": + // Annotations never reject data. Neither does declaring the one supported dialect. breaking = false case "$id", "$anchor", "$dynamicAnchor": default: if polarity < 0 { - switch property { - case "required", "minimum", "maximum", "exclusiveMinimum", "exclusiveMaximum", "minLength", "maxLength", "minContains", "maxContains", "minItems", "maxItems", "minProperties", "maxProperties": - breaking = !breaking - default: - breaking = true - } + // Only required inverts here. Bounds settle their direction in validationChange. + breaking = property != "required" || !breaking } else if polarity == 0 { breaking = true } diff --git a/jsonschema/compare_test.go b/jsonschema/compare_test.go index dda0a29a..34731daa 100644 --- a/jsonschema/compare_test.go +++ b/jsonschema/compare_test.go @@ -4,7 +4,10 @@ package jsonschema import ( + "strconv" + "strings" "testing" + "time" wc "github.com/pb33f/libopenapi/what-changed/model" "github.com/pb33f/testify/require" @@ -44,6 +47,32 @@ func TestNativeValidationDirections(t *testing.T) { {"bounded contains", `{"contains":{"minLength":2},"maxContains":1}`, `{"contains":{"minLength":4},"maxContains":1}`, 1, 1}, {"new applied resource", `{}`, `{"properties":{"x":{"$id":"urn:field","type":"string"}}}`, 1, 1}, {"new unused definition", `{}`, `{"$defs":{"x":{"$id":"urn:field","type":"string"}}}`, 0, 1}, + {"dialect declaration", `{}`, `{"$schema":"` + Dialect + `"}`, 0, 0}, + {"dialect spelling", `{"$schema":"` + Dialect + `"}`, `{"$schema":"` + Dialect + `#"}`, 0, 0}, + {"negated dialect declaration", `{"not":{}}`, `{"not":{"$schema":"` + Dialect + `"}}`, 0, 0}, + {"lower bound", `{"minimum":2}`, `{"minimum":3}`, 1, 0}, + {"upper bound", `{"maxLength":5}`, `{"maxLength":4}`, 1, 0}, + {"new upper bound", `{}`, `{"maxItems":5}`, 1, 0}, + {"negated lower bound", `{"not":{"minimum":2}}`, `{"not":{"minimum":3}}`, 0, 1}, + {"negated new upper bound", `{"not":{}}`, `{"not":{"maxItems":5}}`, 0, 1}, + {"bound beyond exact limits", `{"minimum":1e999999}`, `{"minimum":1e999998}`, 1, 1}, + {"negated bound beyond exact limits", `{"not":{"maximum":1e999999}}`, `{"not":{"maximum":1e999998}}`, 1, 1}, + {"multiple beyond exact limits", `{"multipleOf":1e-999999}`, `{"multipleOf":1e-999998}`, 1, 1}, + {"negated requirement", `{"not":{"required":["a"]}}`, `{"not":{"required":["a","b"]}}`, 0, 1}, + {"ambiguous requirement", `{"oneOf":[{"required":["a"]}]}`, `{"oneOf":[{"required":["a","b"]}]}`, 1, 1}, + {"closed object", `{}`, `{"additionalProperties":false}`, 1, 0}, + {"item schema", `{}`, `{"items":{"maxLength":5}}`, 1, 0}, + {"negation", `{}`, `{"not":{"type":"string"}}`, 1, 0}, + {"property names", `{}`, `{"propertyNames":{"maxLength":5}}`, 1, 0}, + {"condition", `{"then":{"minLength":1}}`, `{"if":{"type":"string"},"then":{"minLength":1}}`, 1, 0}, + {"last unevaluated keyword", `{}`, `{"unevaluatedProperties":false}`, 1, 0}, + {"negated item schema", `{"not":{}}`, `{"not":{"items":{"maxLength":5}}}`, 0, 1}, + {"ambiguous item schema", `{"oneOf":[{}]}`, `{"oneOf":[{"items":{"maxLength":5}}]}`, 1, 1}, + {"evaluated items", `{"unevaluatedItems":false}`, `{"unevaluatedItems":false,"items":{"maxLength":5}}`, 1, 1}, + {"composed branch", `{"allOf":[{"minLength":1}]}`, `{"allOf":[{"minLength":1},{"maxLength":5}]}`, 1, 0}, + {"evaluated branch", `{"allOf":[{"properties":{"a":{}}}],"unevaluatedProperties":false}`, `{"allOf":[{"properties":{"a":{}}},{"properties":{"b":{}}}],"unevaluatedProperties":false}`, 1, 1}, + {"property schema", `{"properties":{"a":{}}}`, `{"properties":{"a":{},"b":{}}}`, 1, 1}, + {"tuple slot", `{"prefixItems":[{}]}`, `{"prefixItems":[{},{}]}`, 1, 1}, } { t.Run(tc.name, func(t *testing.T) { a, b := loadTest(t, tc.old), loadTest(t, tc.current) @@ -117,3 +146,47 @@ func TestNativeKeywordPolicyOverrides(t *testing.T) { } } } + +// A rule replaces the verdict in both directions, so merged defaults must not +// stand in for the direction-aware ones. +func TestRulesAreExplicitOverrides(t *testing.T) { + override := func(rule wc.SchemaRules) *wc.BreakingRulesConfig { return &wc.BreakingRulesConfig{Schema: &rule} } + for _, tc := range []struct { + name, old, current string + rules *wc.BreakingRulesConfig + breaking int + }{ + {"widening", `{"minLength":3}`, `{"minLength":2}`, nil, 0}, + {"unrelated override", `{"minLength":3}`, `{"minLength":2}`, override(wc.SchemaRules{MaxLength: &wc.BreakingChangeRule{Modified: new(true)}}), 0}, + {"keyword override", `{"minLength":3}`, `{"minLength":2}`, override(wc.SchemaRules{MinLength: &wc.BreakingChangeRule{Modified: new(true)}}), 1}, + {"merged defaults", `{"minLength":3}`, `{"minLength":2}`, wc.GenerateDefaultBreakingRules(), 1}, + {"dialect override", `{}`, `{"$schema":"` + Dialect + `"}`, override(wc.SchemaRules{SchemaDialect: &wc.BreakingChangeRule{Added: new(true)}}), 1}, + {"root replacement has no keyword", `true`, `false`, override(wc.SchemaRules{Type: &wc.BreakingChangeRule{Modified: new(false)}}), 1}, + {"nested replacement", `{"properties":{"a":true}}`, `{"properties":{"a":false}}`, override(wc.SchemaRules{Properties: &wc.BreakingChangeRule{Modified: new(false)}}), 0}, + } { + t.Run(tc.name, func(t *testing.T) { + changes, err := Compare(loadTest(t, tc.old), loadTest(t, tc.current), tc.rules) + require.NoError(t, err) + require.Equal(t, 1, changes.TotalChanges()) + require.Equal(t, tc.breaking, changes.TotalBreakingChanges()) + }) + } +} + +// Before the limit, each of these exponents cost tens of milliseconds to expand. +func TestNumbersBeyondExactLimitsAreNotExpanded(t *testing.T) { + schema := func(exponent string) *Document { + var properties []string + for i := range 200 { + properties = append(properties, strconv.Quote("p"+strconv.Itoa(i))+`:{"minimum":1e`+exponent+`}`) + } + return loadTest(t, `{"properties":{`+strings.Join(properties, ",")+`}}`) + } + left, right := schema("999999"), schema("999998") + start := time.Now() + changes, err := Compare(left, right, nil) + require.NoError(t, err) + require.Less(t, time.Since(start), 2*time.Second) + require.Equal(t, 200, changes.TotalChanges()) + require.Equal(t, 200, changes.TotalBreakingChanges()) +} diff --git a/jsonschema/document.go b/jsonschema/document.go index 144c3f1d..83d0514b 100644 --- a/jsonschema/document.go +++ b/jsonschema/document.go @@ -2,6 +2,10 @@ // SPDX-License-Identifier: MIT // Package jsonschema loads and compares authored Draft 2020-12 schema resources. +// +// Draft 2020-12 is the only supported dialect. A $dynamicRef that needs dynamic +// scope resolution is an error. YAML input must be JSON-compatible, so anchors, +// aliases and non-string keys are errors too. package jsonschema import ( @@ -24,15 +28,16 @@ import ( const Dialect = "https://json-schema.org/draft/2020-12/schema" // ErrNotSchema identifies an input without a supported standalone schema declaration. -var ErrNotSchema = errors.New("expected a Draft 2020-12 JSON Schema declaration (use --schema for an unmarked schema)") +var ErrNotSchema = errors.New("expected a Draft 2020-12 JSON Schema declaration") // Source holds the physical document once, even when several resources share it. type Source struct { - relative string - Name string - Data []byte - Node *yaml.Node - Index *index.SpecIndex + relative string + undeclared bool // the root has no $schema, so explicit mode chose the dialect + Name string + Data []byte + Node *yaml.Node + Index *index.SpecIndex } // Resource is a root schema or an embedded schema with its own base URI. @@ -78,6 +83,7 @@ type Document struct { schemas map[*yaml.Node]*Resource schemaPointers map[*yaml.Node]string hasAdverseContext bool + unevaluated bool // a schema uses unevaluatedProperties or unevaluatedItems config *datamodel.DocumentConfiguration base *url.URL } @@ -188,23 +194,24 @@ func (d *Document) sourceName(uri *url.URL) string { } func (d *Document) addSource(data []byte, uri *url.URL, explicit bool) (*Resource, error) { + name := d.sourceName(uri) doc, err := datamodel.DecodeSchemaNode(data) if err != nil { - return nil, err + return nil, fmt.Errorf("%s: %w", name, err) } root := doc.Content[0] - if !explicit && member(root, "$schema") == nil { + undeclared := member(root, "$schema") == nil + if undeclared && !explicit { return nil, ErrNotSchema } for _, marker := range []string{"openapi", "swagger", "asyncapi"} { if member(root, marker) != nil { - return nil, fmt.Errorf("conflicting %s version marker in JSON Schema", marker) + return nil, fmt.Errorf("%s: conflicting %s version marker in JSON Schema", name, marker) } } if strings.EqualFold(path.Ext(uri.Path), ".json") && !json.Valid(data) { - return nil, fmt.Errorf("invalid JSON in %s", d.sourceName(uri)) + return nil, fmt.Errorf("invalid JSON in %s", name) } - name := d.sourceName(uri) cfg := index.CreateClosedAPIIndexConfig() cfg.SpecAbsolutePath, cfg.Rolodex = name, d.Rolodex idx := index.NewSchemaIndex(doc, cfg) @@ -214,7 +221,7 @@ func (d *Document) addSource(data []byte, uri *url.URL, explicit bool) (*Resourc relative = filepath.ToSlash(rel) } } - source := &Source{Name: name, relative: relative, Data: data, Node: root, Index: idx} + source := &Source{Name: name, relative: relative, undeclared: undeclared, Data: data, Node: root, Index: idx} d.Sources[name] = source if len(d.Resources) == 0 { d.Rolodex.SetRootNode(doc) @@ -273,6 +280,16 @@ func (d *Document) indexSchema(source *Source, node *yaml.Node, base *url.URL, p if dialect := member(node, "$schema"); dialect != nil && strings.TrimSuffix(dialect.Value, "#") != Dialect { return fmt.Errorf("%s:%d: unsupported JSON Schema dialect %q", source.Name, dialect.Line, dialect.Value) } + if source.undeclared { + // Explicit mode chose the dialect. A keyword from an earlier draft + // would compare as an annotation and hide its edits. + for i := 0; i+1 < len(node.Content); i += 2 { + key := node.Content[i] + if current := supersededKeywords[key.Value]; current != "" { + return fmt.Errorf("%s:%d: %s belongs to an earlier draft; Draft 2020-12 uses %s", source.Name, key.Line, key.Value, current) + } + } + } if vocab := member(node, "$vocabulary"); vocab != nil { if vocab.Kind != yaml.MappingNode { return fmt.Errorf("%s:%d: $vocabulary must be an object", source.Name, vocab.Line) @@ -320,7 +337,7 @@ func (d *Document) indexSchema(source *Source, node *yaml.Node, base *url.URL, p err = d.Rolodex.RegisterGlobalSchemaId(entry) } if err != nil { - return err + return fmt.Errorf("%s:%d: %w", source.Name, id.Line, err) } delete(d.addresses, base.String()) } @@ -349,13 +366,31 @@ func (d *Document) indexSchema(source *Source, node *yaml.Node, base *url.URL, p d.References = append(d.References, Reference{From: node, Value: value.Value, address: target.String(), Keyword: keyword, context: evaluation}) } } - return children(node, func(keyword, key string, child *yaml.Node) error { + nested := false + err := children(node, func(keyword, key string, child *yaml.Node) error { + d.unevaluated = d.unevaluated || keyword == "unevaluatedProperties" || keyword == "unevaluatedItems" childPointer := pointer + "/" + escapePointer(keyword) if childKind(keyword) != singleSchema { childPointer += "/" + escapePointer(key) } - return d.indexSchema(source, child, base, childPointer, keyword, r, evaluation.child(node, keyword)) + err := d.indexSchema(source, child, base, childPointer, keyword, r, evaluation.child(node, keyword)) + nested = nested || err != nil + return err }) + if err != nil && !nested { + // A malformed applicator is reported by line. Name the file it belongs to. + return fmt.Errorf("%s: %w", source.Name, err) + } + return err +} + +// supersededKeywords maps keywords from earlier drafts to their Draft 2020-12 form. +var supersededKeywords = map[string]string{ + "definitions": "$defs", + "dependencies": "dependentRequired or dependentSchemas", + "additionalItems": "items after prefixItems", + "$recursiveRef": "$dynamicRef", + "$recursiveAnchor": "$dynamicAnchor", } func escapePointer(key string) string { diff --git a/jsonschema/loader_test.go b/jsonschema/loader_test.go index 7b3a4294..bb574601 100644 --- a/jsonschema/loader_test.go +++ b/jsonschema/loader_test.go @@ -23,7 +23,7 @@ func TestLoadInputBoundaries(t *testing.T) { want string }{ {`{"$vocabulary":{"urn:unsupported":true}}`, true, "unsupported required vocabulary"}, - {"{}", false, "--schema"}, {`{"$schema":"https://example.org/app"}`, false, "unsupported"}, + {"{}", false, "expected a Draft 2020-12 JSON Schema declaration"}, {`{"$schema":"https://example.org/app"}`, false, "unsupported"}, {"null", true, "object or boolean"}, {"type: object\ntype: string", true, "already defined"}, {`{"openapi":"3.1.0","$schema":"https://json-schema.org/draft/2020-12/schema"}`, true, "conflicting"}, {`{"$defs":{"a":{"$id":"urn:money"},"b":{"$id":"urn:money"}}}`, true, "duplicate"}, @@ -44,7 +44,11 @@ func TestInvalidConstraintsFailBeforeComparison(t *testing.T) { require.ErrorContains(t, err, "bad.yaml") } _, err := LoadCollection(map[string][]byte{"bad.json": []byte(`{"type":"invalid"}`)}, ".", nil) - require.ErrorContains(t, err, "bad.json") + var member *MemberError + require.ErrorAs(t, err, &member) + require.Equal(t, "bad.json", member.Name) + require.ErrorIs(t, err, member.Err) + require.True(t, strings.HasPrefix(err.Error(), "bad.json: "), err.Error()) } func TestMetaValidationChecksDistinctPropertySchemasAndPreservesLiterals(t *testing.T) { diff --git a/jsonschema/reference.go b/jsonschema/reference.go index 67cc6434..306fef46 100644 --- a/jsonschema/reference.go +++ b/jsonschema/reference.go @@ -148,7 +148,11 @@ func (d *Document) resolve(address, authored string) (*yaml.Node, error) { } } if d.schemas[target] == nil { - return nil, fmt.Errorf("no schema at %q in %s", fragment, d.sourceName(uri)) + hint := "" + if strings.HasPrefix(fragment, "/definitions/") { + hint = " (Draft 2020-12 names this keyword $defs)" + } + return nil, fmt.Errorf("no schema at %q in %s%s", fragment, d.sourceName(uri), hint) } return target, nil } diff --git a/jsonschema/reference_resolution_test.go b/jsonschema/reference_resolution_test.go index 5241088c..6468f682 100644 --- a/jsonschema/reference_resolution_test.go +++ b/jsonschema/reference_resolution_test.go @@ -44,6 +44,7 @@ func TestReferencePointersAndSourceDiagnostics(t *testing.T) { for _, tc := range []struct{ ref, want string }{ {"#/prefixItems/01", "no schema at"}, {"#/prefixItems/3", "no schema at"}, {"#/prefixItems/-1", "no schema at"}, {"#/prefixItems/not-index", "no schema at"}, + {"#/definitions/price", "(Draft 2020-12 names this keyword $defs)"}, {"#absent", "unknown schema anchor"}, {"file://unrelated/share/a.json", "unsupported file URI host"}, {"child.json", "file references are disabled"}, {"https://schemas.example.test/dep.json", "remote references are disabled"}, {"urn:unknown", "no registered schema for"}, @@ -236,3 +237,26 @@ func TestCollectionRetrievalAliasCannotHideAnEmbeddedID(t *testing.T) { require.ErrorContains(t, err, "currency.json") require.Nil(t, doc) } + +func TestDependencyDiagnosticsNameTheirOwnFile(t *testing.T) { + cfg := datamodel.NewDocumentConfiguration() + cfg.AllowFileReferences, cfg.BasePath = true, "." + cfg.LocalFS = fstest.MapFS{ + "shape.json": {Data: []byte("{\n\n\n\"properties\":[]}")}, + "keys.yaml": {Data: []byte("properties:\n 200: {}\n")}, + "legacy.json": {Data: []byte("{\n\"definitions\":{}}")}, + } + for file, want := range map[string]string{ + "shape.json": `order.json:1: resolve $ref "shape.json": shape.json: line 4: properties requires an object`, + "keys.yaml": `order.json:1: resolve $ref "keys.yaml": keys.yaml: line 2: JSON object keys must be strings`, + "legacy.json": `order.json:1: resolve $ref "legacy.json": legacy.json:2: definitions belongs to an earlier draft`, + } { + doc, err := jsonschema.Load([]byte(`{"$ref":"`+file+`"}`), "order.json", cfg, true) + require.ErrorContains(t, err, want) + require.Nil(t, doc) + } + // A declared dialect keeps keywords from earlier drafts as annotations. + doc, err := jsonschema.Load([]byte(`{"$schema":"`+jsonschema.Dialect+`","definitions":{"price":{"type":"number"}},"dependencies":{}}`), "declared.json", nil, false) + require.NoError(t, err) + doc.Release() +} diff --git a/jsonschema/resource_loading_test.go b/jsonschema/resource_loading_test.go index 6c2528d6..c3dd2926 100644 --- a/jsonschema/resource_loading_test.go +++ b/jsonschema/resource_loading_test.go @@ -105,9 +105,12 @@ func TestRejectAmbiguousOrInvalidSchemaResources(t *testing.T) { {"ambiguous anchor", `{"$defs":{"a":{"$anchor":"town"},"b":{"$anchor":"town"}}}`, "duplicate schema address"}, {"invalid pointer URI", `{"$ref":"bad%XY"}`, "invalid $ref"}, {"single schema", `{"not":17}`, "schema must be an object or boolean"}, - {"schema map", `{"properties":true}`, "properties requires an object"}, - {"non-string map key", "properties: {17: {}}", "JSON object keys must be strings"}, - {"schema list", `{"allOf":{}}`, "allOf requires an array"}, + {"schema map", `{"properties":true}`, "invalid.json: line 1: properties requires an object"}, + {"non-string map key", "properties: {17: {}}", "invalid.json: line 1: JSON object keys must be strings (quote the key in YAML)"}, + {"schema list", "{\n\"not\":{\n\"allOf\":{}}}", "invalid.json: line 3: allOf requires an array"}, + {"API marker", `{"openapi":"3.1.0"}`, "invalid.json: conflicting openapi version marker"}, + {"earlier draft definitions", `{"definitions":{}}`, "invalid.json:1: definitions belongs to an earlier draft; Draft 2020-12 uses $defs"}, + {"earlier draft keyword below a property", "{\"properties\":{\"list\":{\n\"additionalItems\":false}}}", "invalid.json:2: additionalItems belongs to an earlier draft; Draft 2020-12 uses items after prefixItems"}, {"schema list operand", `{"allOf":[false,17]}`, "schema must be an object or boolean"}, } { t.Run(tc.name, func(t *testing.T) { diff --git a/utils/enum.go b/utils/enum.go index b67a92b6..db795d96 100644 --- a/utils/enum.go +++ b/utils/enum.go @@ -110,10 +110,7 @@ func (index *enumValueIndex) valueKey(node *yaml.Node) (string, bool) { } return "n" + value.String(), true case "!!float": - if !enumFloatWithinLimits(node.Value) { - return "", false - } - value, ok := new(big.Rat).SetString(node.Value) + value, ok := ParseBoundedRat(node.Value) if !ok { return "", false } @@ -156,6 +153,15 @@ func (index *enumValueIndex) valueKey(node *yaml.Node) (string, bool) { return "", false } +// ParseBoundedRat parses a number exactly. It declines a literal outside the +// limits described by CheckEnumForDuplicates, which bound the cost of expansion. +func ParseBoundedRat(value string) (*big.Rat, bool) { + if !enumFloatWithinLimits(value) { + return nil, false + } + return new(big.Rat).SetString(value) +} + func enumFloatWithinLimits(value string) bool { if len(value) > maxEnumNumberLength { return false diff --git a/utils/enum_test.go b/utils/enum_test.go index ccbb6164..07f1e7af 100644 --- a/utils/enum_test.go +++ b/utils/enum_test.go @@ -20,6 +20,16 @@ func TestJSONValueIDs(t *testing.T) { require.Zero(t, ids[6]) } +func TestParseBoundedRat(t *testing.T) { + value, ok := ParseBoundedRat("1.50") + require.True(t, ok) + require.Equal(t, "3/2", value.RatString()) + for _, literal := range []string{"1e401", "1e-401", strings.Repeat("9", 1025), "one"} { + _, ok = ParseBoundedRat(literal) + require.False(t, ok, literal) + } +} + func TestCheckEnumForDuplicates_OversizedNumbers(t *testing.T) { for _, tc := range []struct { name string