diff --git a/datamodel/low/base/schema_build.go b/datamodel/low/base/schema_build.go index b2016773..dab25056 100644 --- a/datamodel/low/base/schema_build.go +++ b/datamodel/low/base/schema_build.go @@ -138,9 +138,11 @@ func (s *Schema) Build(ctx context.Context, root *yaml.Node, idx *index.SpecInde if utils.IsNodeArray(typeValue) { refs := make([]low.ValueReference[string], 0, len(typeValue.Content)) for r := range typeValue.Content { + // An alias keeps the anchor name as its value, so read the node it points to. + item := utils.NodeAlias(typeValue.Content[r]) refs = append(refs, low.ValueReference[string]{ - Value: typeValue.Content[r].Value, - ValueNode: typeValue.Content[r], + Value: item.Value, + ValueNode: item, }) } s.Type = low.NodeReference[SchemaDynamicValue[string, []low.ValueReference[string]]]{ diff --git a/datamodel/low/base/schema_test.go b/datamodel/low/base/schema_test.go index 2614a407..7eaa6911 100644 --- a/datamodel/low/base/schema_test.go +++ b/datamodel/low/base/schema_test.go @@ -506,6 +506,26 @@ const: tasty` assert.Equal(t, "tasty", schConst) } +func TestSchema_Build_TypeListWithAlias(t *testing.T) { + build := func(spec string) *Schema { + var rootNode yaml.Node + assert.NoError(t, yaml.Unmarshal([]byte(spec), &rootNode)) + sch := Schema{} + assert.NoError(t, low.BuildModel(rootNode.Content[0].Content[3], &sch)) + assert.NoError(t, sch.Build(context.Background(), rootNode.Content[0].Content[3], nil)) + return &sch + } + // An alias in a list of types reads the value it points to, not the name of its anchor. + aliased := build("name: &object string\nschema: {type: [*object, 'null']}") + plain := build("name: string\nschema: {type: [string, 'null']}") + assert.True(t, aliased.Type.Value.IsB()) + if assert.Len(t, aliased.Type.Value.B, 2) { + assert.Equal(t, "string", aliased.Type.Value.B[0].Value) + assert.Equal(t, "null", aliased.Type.Value.B[1].Value) + } + assert.Equal(t, plain.Hash(), aliased.Hash()) +} + func TestSchema_Build_PropsLookup(t *testing.T) { yml := `components: schemas: diff --git a/what-changed/model/schema_usage.go b/what-changed/model/schema_usage.go index 1d48e6b1..10c08b55 100644 --- a/what-changed/model/schema_usage.go +++ b/what-changed/model/schema_usage.go @@ -6,6 +6,8 @@ package model import ( "context" "iter" + "slices" + "strconv" "strings" "sync" @@ -106,6 +108,18 @@ type usageWalker struct { visited [schemaObject + 1]schemaUsage targets map[string]*yaml.Node unknown bool + // nullable adds null to the types of a schema. Only OpenAPI 3.0 defines it, so it is kept when the version is unknown. + nullable bool + // siblings applies the keywords next to $ref as well. OpenAPI 3.1 does, and the schema model only reads them that + // way with TransformSiblingRefs, so without both only the referenced schema counts. + siblings bool + // dropped counts the keywords being walked that the model drops next to a $ref. + dropped int + // throughDropped is set once the walk reaches a schema through keywords the model drops next to a $ref, or through + // a $ref the model does not resolve, and madeExclusive once it keeps the direction of the branches of a oneOf. + throughDropped, madeExclusive bool + // sharedUnions shares the branches of every oneOf, as before. + sharedUnions bool } func buildSchemaUsage(idx *index.SpecIndex) schemaUsage { @@ -116,21 +130,38 @@ func buildSchemaUsage(idx *index.SpecIndex) schemaUsage { if root.Kind == yaml.DocumentNode && len(root.Content) > 0 { root = root.Content[0] } - w := usageWalker{index: idx, targets: make(map[string]*yaml.Node)} - for i := range w.visited { - w.visited[i] = make(schemaUsage) - } - for key, value := range usageFields(root) { - switch key { - case v3.JSONSchemaDialectLabel: - if !knownUsageDialect(value) { - return nil + version, known := idx.ResolveDocumentVersion() + walk := func(sharedUnions bool) *usageWalker { + w := &usageWalker{ + index: idx, + targets: make(map[string]*yaml.Node), + nullable: !known || version < 3.1, + siblings: known && version >= 3.1 && idx.GetConfig() != nil && idx.GetConfig().TransformSiblingRefs, + sharedUnions: sharedUnions, + } + for i := range w.visited { + w.visited[i] = make(schemaUsage) + } + for key, value := range usageFields(root) { + switch key { + case v3.JSONSchemaDialectLabel: + if !knownUsageDialect(value) { + w.unknown = true + return w + } + case v3.PathsLabel: + w.openAPIEntries(value, pathItemObject, 0) + case v3.WebhooksLabel: + w.each(value, pathItemObject, sharedSchema) } - case v3.PathsLabel: - w.openAPIEntries(value, pathItemObject, 0) - case v3.WebhooksLabel: - w.each(value, pathItemObject, sharedSchema) } + return w + } + w := walk(false) + // The walk follows the keywords the model drops next to a $ref, as it did before. That did not matter while every + // oneOf was shared, so the document is walked again that way when both happen. + if !w.unknown && w.madeExclusive && w.throughDropped { + w = walk(true) } if w.unknown { return nil @@ -176,10 +207,19 @@ func (w *usageWalker) each(node *yaml.Node, object usageObject, dir schemaDirect } func (w *usageWalker) walk(node *yaml.Node, object usageObject, dir schemaDirection) { + w.walkReached(node, object, dir, false) +} + +// walkReached walks node, which referenced tells is reached through a reference rather than written in place. +func (w *usageWalker) walkReached(node *yaml.Node, object usageObject, dir schemaDirection, referenced bool) { + aliased := node != nil && node.Kind == yaml.AliasNode node = utils.NodeAlias(node) if w.unknown || node == nil || node.Kind != yaml.MappingNode { return } + if object == schemaObject && w.dropped > 0 { + w.throughDropped = true + } visited := w.visited[object] if prior, seen := visited[node]; seen && prior&dir == dir { return @@ -200,16 +240,28 @@ func (w *usageWalker) walk(node *yaml.Node, object usageObject, dir schemaDirect } } } + // The schema model drops the keywords next to a $ref without TransformSiblingRefs, when it reaches the schema through + // a $ref, and for an alias in a list. Next to the $ref of anything other than a schema, such as a response or a path + // item, it always drops them. The walk still follows them, as before, and records that it did. In OpenAPI 3.0 the + // model still reads them where the schema is written, so treating them as dropped there only shares more unions. + dropped := (object != schemaObject || !w.siblings || referenced || aliased) && usageField(node, v3.RefLabel) != nil for key, value := range usageFields(node) { if key == v3.RefLabel { ref := utils.NodeAlias(value).Value + // The model does not resolve a $ref whose value is an alias, so the walk reaches what the model does not. + if value.Kind == yaml.AliasNode { + w.throughDropped = true + } if target := w.localTarget(ref); target != nil { - w.walk(target, object, sameInstance) + w.walkReached(target, object, sameInstance, true) continue } w.unknown = true return } + if dropped { + w.dropped++ + } switch object { case pathItemObject, operationObject: w.operationField(key, value, dir) @@ -229,6 +281,9 @@ func (w *usageWalker) walk(node *yaml.Node, object usageObject, dir schemaDirect case schemaObject: w.schemaField(key, value, dir, sameInstance) } + if dropped { + w.dropped-- + } } } @@ -264,7 +319,17 @@ func (w *usageWalker) schemaField(key string, value *yaml.Node, dir, sameInstanc case v3.NotLabel, v3.IfLabel, v3.ContainsLabel: w.walk(value, schemaObject, sharedSchema) case v3.OneOfLabel: - w.each(value, schemaObject, sharedSchema) + // A oneOf rejects an instance that matches more than one branch, so changing one branch can change what the + // union accepts in the opposite direction: widening a branch can make an instance match a second one, and + // narrowing it can leave an instance that matched two branches with only one. Branches that no instance can + // match at the same time cannot interfere with each other, so they keep the direction, as with anyOf. + // A shared direction is the same either way, so the branches are only checked when it is not. + if !w.sharedUnions && sameInstance != sharedSchema && w.exclusiveBranches(value) { + w.madeExclusive = true + w.each(value, schemaObject, sameInstance) + } else { + w.each(value, schemaObject, sharedSchema) + } case v3.SchemaDialectLabel: if !knownUsageDialect(value) { w.unknown = true @@ -275,6 +340,152 @@ func (w *usageWalker) schemaField(key string, value *yaml.Node, dir, sameInstanc } } +// exclusiveBranches reports whether no instance can match two of the branches, so that exclusivity does not depend +// on what a branch contains. That holds for a single branch and for branches that accept different types. +func (w *usageWalker) exclusiveBranches(branches *yaml.Node) bool { + branches = utils.NodeAlias(branches) + if branches.Kind != yaml.SequenceNode { + return false + } + if len(branches.Content) == 1 { + return true + } + seen := make(map[string]bool) + for _, branch := range branches.Content { + types, ok := w.instanceTypes(branch) + if !ok { + return false + } + for t := range types { + if seen[t] { + return false + } + seen[t] = true + } + } + return true +} + +// jsonTypes are the instance types of JSON Schema. A type name outside this list cannot be compared with another one. +var jsonTypes = map[string]bool{ + "null": true, "boolean": true, "object": true, "array": true, "number": true, "string": true, "integer": true, +} + +// instanceTypes returns an upper bound of the JSON types a schema accepts. OpenAPI 3.0 ignores the siblings of $ref, so +// only the referenced schema counts there. In 3.1 they apply as well, so a type next to a reference narrows the bound. +// That only holds for the schema itself, written in place: the schema model reads a schema it reaches through a $ref +// as the target of its own $ref, without the type next to it, and does the same with an alias in a list. +// It reports false when it cannot tell: no type along the references, a type that cannot be read, a reference that +// cannot be resolved, a cycle of references, or types along the references that have nothing in common, which is more +// likely a mistake than a schema that accepts nothing. The same goes for the boolean schema false. +func (w *usageWalker) instanceTypes(node *yaml.Node) (map[string]bool, bool) { + var bound map[string]bool + followed := make([]*yaml.Node, 0, 8) + aliased := node != nil && node.Kind == yaml.AliasNode + for { + node = utils.NodeAlias(node) + // The boolean schema true accepts every instance, like {}, so it narrows nothing. + if utils.IsNodeBoolValue(node) { + if accepts, _ := strconv.ParseBool(node.Value); accepts { + return bound, len(bound) > 0 + } + } + if node.Kind != yaml.MappingNode || slices.Contains(followed, node) { + return nil, false + } + followed = append(followed, node) + var declared *yaml.Node + ref := "" + nullable := false + for key, value := range usageFields(node) { + switch key { + case v3.TypeLabel: + declared = utils.NodeAlias(value) + case v3.RefLabel: + // The model does not resolve a $ref whose value is an alias. + if value.Kind == yaml.AliasNode { + return nil, false + } + ref = utils.NodeAlias(value).Value + case v3.NullableLabel: + // Read it as the schema model does: a YAML boolean, in any spelling that YAML accepts. + if utils.IsNodeBoolValue(value) { + nullable, _ = strconv.ParseBool(utils.NodeAlias(value).Value) + } + } + } + if declared != nil && (ref == "" || (w.siblings && len(followed) == 1 && !aliased)) { + types, ok := w.declaredTypes(declared, nullable) + if !ok { + return nil, false + } + bound = intersectTypes(bound, types) + } + if ref == "" { + return bound, len(bound) > 0 + } + if node = w.localTarget(ref); node == nil { + return nil, false + } + } +} + +// declaredTypes returns the JSON types of a type declaration, or false when it cannot be read. +func (w *usageWalker) declaredTypes(declared *yaml.Node, nullable bool) (map[string]bool, bool) { + var names []string + switch { + // The schema model only reads a single type from a YAML string, so `type: null` declares no type at all. + case utils.IsNodeStringValue(declared): + names = []string{declared.Value} + case declared.Kind == yaml.SequenceNode: + for _, item := range declared.Content { + names = append(names, utils.NodeAlias(item).Value) + } + } + if len(names) == 0 { + return nil, false + } + // OpenAPI 3.0 adds null with nullable. In 3.1 nullable means nothing. + if nullable && w.nullable { + names = append(names, "null") + } + types := make(map[string]bool) + for _, name := range names { + if !jsonTypes[name] { + return nil, false + } + types[name] = true + // Every integer is a number, so the two overlap. + if name == "number" { + types["integer"] = true + } + } + return types, true +} + +// intersectTypes narrows bound to the types it shares with types. A nil bound does not restrict anything yet. +func intersectTypes(bound, types map[string]bool) map[string]bool { + if bound == nil { + return types + } + for t := range bound { + if !types[t] { + delete(bound, t) + } + } + return bound +} + +// usageField returns the value of one field of a mapping, or nil when the mapping does not have it. +func usageField(node *yaml.Node, name string) *yaml.Node { + for key, value := range usageFields(node) { + if key == name { + return value + } + } + return nil +} + // Other dialects may introduce applicators that the OpenAPI schema walk cannot follow. func knownUsageDialect(value *yaml.Node) bool { switch strings.TrimSuffix(utils.NodeAlias(value).Value, "#") { diff --git a/what-changed/model/schema_usage_oneof_test.go b/what-changed/model/schema_usage_oneof_test.go new file mode 100644 index 00000000..cff5b470 --- /dev/null +++ b/what-changed/model/schema_usage_oneof_test.go @@ -0,0 +1,453 @@ +// Copyright 2026 Princess B33f Heavy Industries / Dave Shanley +// SPDX-License-Identifier: MIT + +package model + +import ( + "context" + "fmt" + "strings" + "testing" + + "github.com/pb33f/go-yaml" + "github.com/pb33f/libopenapi/datamodel" + highv3 "github.com/pb33f/libopenapi/datamodel/high/v3" + v3 "github.com/pb33f/libopenapi/datamodel/low/v3" + "github.com/pb33f/libopenapi/index" + "github.com/pb33f/testify/assert" + "github.com/pb33f/testify/require" +) + +func TestRequiredOneOfBranches(t *testing.T) { + const widget = "{$ref: '#/components/schemas/Widget'}" + const extra = ` + List: {type: array, items: {$ref: '#/components/schemas/Widget'}} + Page: {type: object, properties: {item: {$ref: '#/components/schemas/Widget'}}} + Alias1: {$ref: '#/components/schemas/Alias2'} + Alias2: {$ref: '#/components/schemas/Alias3'} + Alias3: {$ref: '#/components/schemas/Alias4'} + Alias4: {$ref: '#/components/schemas/Alias5'} + Alias5: {$ref: '#/components/schemas/Alias6'} + Alias6: {$ref: '#/components/schemas/Alias7'} + Alias7: {$ref: '#/components/schemas/Alias8'} + Alias8: {type: string} + StringOrObject: {type: [string, object]} + Narrowed: {$ref: '#/components/schemas/StringOrObject', type: string} + Mismatched: {$ref: '#/components/schemas/Alias8', type: object} + Untyped: {minLength: 1} + Anything: {} + Everything: true + Nothing: false + Named: {type: &object string} + AliasedType: {type: [*object]}` + for _, tc := range []struct { + name, schema string + breaking bool + }{ + {"single branch", "oneOf: [" + widget + "]", false}, + {"array or object", "oneOf: [{type: array, items: " + widget + "}, {type: object, properties: {widgets: {type: array, items: " + widget + "}}}]", false}, + {"branches by reference", "oneOf: [{$ref: '#/components/schemas/List'}, {$ref: '#/components/schemas/Page'}]", false}, + {"null or object", "oneOf: [{type: 'null'}, " + widget + "]", false}, + {"list of types", "oneOf: [{type: [string, number]}, {type: [array, 'null'], items: " + widget + "}]", false}, + {"two objects", "oneOf: [" + widget + ", {type: object, required: [other], properties: {other: {type: string}}}]", true}, + {"two arrays", "oneOf: [{type: array, items: " + widget + "}, {type: array, items: {type: string}}]", true}, + {"integer and number", "oneOf: [{type: integer}, {type: number}, " + widget + "]", true}, + {"branch without a type", "oneOf: [" + widget + ", {properties: {other: {type: string}}}]", true}, + {"boolean branch", "oneOf: [" + widget + ", true]", true}, + {"type that is not a JSON type", "oneOf: [" + widget + ", {type: Object}]", true}, + {"integer and number in one branch", "oneOf: [{type: [integer, number]}, " + widget + "]", false}, + // The type next to the reference and the type behind it have nothing in common, which is more likely a mistake + // than a schema that accepts nothing. + {"reference next to a type", "oneOf: [" + widget + ", {$ref: '#/components/schemas/Page', type: string}]", true}, + // In OpenAPI 3.1 the siblings of $ref apply as well, so a type next to a reference narrows it. + {"reference next to a narrower type", "oneOf: [{type: object, properties: {item: " + widget + "}}, {$ref: '#/components/schemas/StringOrObject', type: string}]", false}, + {"reference narrowed to the type of another branch", "oneOf: [{type: object, properties: {item: " + widget + "}}, {$ref: '#/components/schemas/StringOrObject', type: object}]", true}, + {"reference without a type next to a type", "oneOf: [{type: object, properties: {item: " + widget + "}}, {$ref: '#/components/schemas/Untyped', type: string}]", false}, + // The schema model reads a schema it reaches through a $ref as the target of its own $ref, without the type next + // to it, so only the type next to the $ref of the branch itself counts. + {"type next to a reference along the chain", "oneOf: [{type: object, properties: {item: " + widget + "}}, {$ref: '#/components/schemas/Narrowed'}]", true}, + {"type next to a reference along the chain that has nothing in common with it", "oneOf: [{type: object, properties: {item: " + widget + "}}, {$ref: '#/components/schemas/Mismatched'}]", false}, + {"reference next to a type that is not a JSON type", "oneOf: [{type: object, properties: {item: " + widget + "}}, {$ref: '#/components/schemas/Alias8', type: Object}]", true}, + // The boolean schema true accepts every instance like {}, so the type next to either reference is what counts. + {"reference to an empty schema next to a type", "oneOf: [{type: object, properties: {item: " + widget + "}}, {$ref: '#/components/schemas/Anything', type: string}]", false}, + {"reference to true next to a type", "oneOf: [{type: object, properties: {item: " + widget + "}}, {$ref: '#/components/schemas/Everything', type: string}]", false}, + // The boolean schema false accepts nothing, which is more likely a mistake than a branch that no instance matches. + {"reference to false next to a type", "oneOf: [{type: object, properties: {item: " + widget + "}}, {$ref: '#/components/schemas/Nothing', type: string}]", true}, + // An alias in a list of types reads the value it points to, not the name of its anchor. + {"alias in a list of types", "oneOf: [" + widget + ", {$ref: '#/components/schemas/AliasedType'}]", false}, + // An unquoted null is not a type name: the schema model leaves the type unset, so the branch accepts anything. + {"type that is a YAML null", "oneOf: [" + widget + ", {type: null}]", true}, + // In OpenAPI 3.1 nullable has no effect, so the object branch does not accept null. + {"nullable in OpenAPI 3.1", "oneOf: [{type: object, nullable: true, properties: {item: " + widget + "}}, {type: 'null'}]", false}, + // The length of a chain of references does not change the types its end accepts. + {"chain of eight references", "oneOf: [{type: object, properties: {item: " + widget + "}}, {$ref: '#/components/schemas/Alias1'}]", false}, + } { + t.Run(tc.name, func(t *testing.T) { + op := strings.Replace(usageResponseOnly, widget, "{"+tc.schema+"}", 1) + schemas := func(required string) string { + return usageWidget(required) + extra + } + requireEntryBreaking(t, usageSpec(op, schemas("name")), usageSpec(op, schemas("name, id")), tc.breaking) + }) + } +} + +func TestRequiredOneOfBranchThatIsAnAlias(t *testing.T) { + // The schema model does not apply TransformSiblingRefs to an alias in a list, so it reads an aliased branch as the + // target of its $ref, without the type next to it. The branch then accepts objects, like the other one. + const widget = "{$ref: '#/components/schemas/Widget'}" + op := strings.Replace(usageResponseOnly, widget, "{oneOf: [{type: object, properties: {item: "+widget+"}}, *narrowed]}", 1) + build := func(required string) string { + spec := usageSpec(op, usageWidget(required)+"\n StringOrObject: {type: [string, object]}") + return strings.Replace(spec, "\npaths:", "\nx-narrowed: &narrowed {$ref: '#/components/schemas/StringOrObject', type: string}\npaths:", 1) + } + requireEntryBreaking(t, build("name"), build("name, id"), true) +} + +// Rendering a document and reading it back must not change whether the branches are exclusive. +func TestRequiredOneOfBranchesAfterRendering(t *testing.T) { + const widget = "{$ref: '#/components/schemas/Widget'}" + for _, tc := range []struct{ name, schema, extra string }{ + {"alias in a list of types", "oneOf: [" + widget + ", {$ref: '#/components/schemas/Other'}]", "\n x-type: &object string\n Other: {type: [*object]}"}, + {"reference to true next to a type", "oneOf: [{type: object, properties: {item: " + widget + "}}, {$ref: '#/components/schemas/Other', type: string}]", "\n Other: true"}, + } { + t.Run(tc.name, func(t *testing.T) { + op := strings.Replace(usageResponseOnly, widget, "{"+tc.schema+"}", 1) + left, right := usageSpec(op, usageWidget("name")+tc.extra), usageSpec(op, usageWidget("name, id")+tc.extra) + requireEntryBreaking(t, left, right, false) + render := func(spec string) string { + rendered, err := highv3.NewDocument(buildUsageDocument(t, spec)).Render() + require.NoError(t, err) + return string(rendered) + } + requireEntryBreaking(t, render(left), render(right), false) + }) + } +} + +func TestRequiredOneOfBranchesKeepTheirDirection(t *testing.T) { + const widget = "{$ref: '#/components/schemas/Widget'}" + union := "oneOf: [{type: array, items: " + widget + "}, {type: object, properties: {widgets: {type: array, items: " + widget + "}}}]" + // The same union in a request makes the schema shared with the response, so it must stay breaking. + op := strings.Replace(usageShared, widget, "{"+union+"}", 1) + requireEntryBreaking(t, usageSpec(op, usageWidget("name")), usageSpec(op, usageWidget("name, id")), true) + // A removed requirement is only safe for a request, so a union used by a response alone must stay breaking. + op = strings.Replace(usageResponseOnly, widget, "{"+union+"}", 1) + requireEntryBreaking(t, usageSpec(op, usageWidget("name, id")), usageSpec(op, usageWidget("name")), true) +} + +func TestRequiredOneOfBranchesOpenAPI30(t *testing.T) { + const widget = "{$ref: '#/components/schemas/Widget'}" + const other = "\n Other: {type: object, properties: {other: {type: string}}}\n Untyped: {minLength: 1}" + for _, tc := range []struct { + name, schema string + breaking bool + }{ + // OpenAPI 3.0 ignores the siblings of $ref, so the second branch is an object like Widget. + {"reference next to a type", "oneOf: [" + widget + ", {$ref: '#/components/schemas/Other', type: string}]", true}, + {"reference without a type next to a type", "oneOf: [{type: object, properties: {item: " + widget + "}}, {$ref: '#/components/schemas/Untyped', type: string}]", true}, + {"nullable object or string", "oneOf: [{type: object, nullable: true, properties: {item: " + widget + "}}, {type: string}]", false}, + {"nullable branches", "oneOf: [{type: object, nullable: true, properties: {item: " + widget + "}}, {type: string, nullable: true}]", true}, + // YAML resolves True and TRUE to the same boolean as true, and the schema model reads them as nullable. + {"nullable branches spelled True", "oneOf: [{type: object, nullable: true, properties: {item: " + widget + "}}, {type: string, nullable: True}]", true}, + {"nullable branches spelled TRUE", "oneOf: [{type: object, nullable: true, properties: {item: " + widget + "}}, {type: string, nullable: TRUE}]", true}, + // A quoted 'true' is a string, which the schema model does not read as nullable. + {"nullable that is a string", "oneOf: [{type: object, nullable: true, properties: {item: " + widget + "}}, {type: string, nullable: 'true'}]", false}, + // An empty list of types cannot be compared, and nullable does not change that. + {"nullable empty list of types", "oneOf: [" + widget + ", {type: [], nullable: true}]", true}, + } { + t.Run(tc.name, func(t *testing.T) { + op := strings.Replace(usageResponseOnly, widget, "{"+tc.schema+"}", 1) + build := func(required string) string { + return strings.Replace(usageSpec(op, usageWidget(required)+other), "openapi: 3.1.0", "openapi: 3.0.3", 1) + } + requireEntryBreaking(t, build("name"), build("name, id"), tc.breaking) + }) + } +} + +// Without TransformSiblingRefs the schema model reads only the reference, so a type next to it narrows nothing. +func TestRequiredOneOfBranchesWithoutSiblingTransform(t *testing.T) { + const widget = "{$ref: '#/components/schemas/Widget'}" + union := "oneOf: [{type: object, properties: {item: " + widget + "}}, {$ref: '#/components/schemas/StringOrObject', type: string}]" + op := strings.Replace(usageResponseOnly, widget, "{"+union+"}", 1) + build := func(required string) *v3.Document { + info, err := datamodel.ExtractSpecInfo([]byte(usageSpec(op, usageWidget(required)+"\n StringOrObject: {type: [string, object]}"))) + require.NoError(t, err) + config := datamodel.NewDocumentConfiguration() + config.TransformSiblingRefs = false + doc, err := v3.CreateDocumentFromConfig(info, config) + require.NoError(t, err) + return doc + } + changes := CompareDocuments(build("name"), build("name, id")) + require.NotNil(t, changes) + for _, ch := range changes.GetAllChanges() { + if ch.Property == v3.RequiredLabel { + assert.True(t, ch.Breaking) + return + } + } + t.Fatal("missing required change") +} + +func TestRequiredOneOfBranchesInKeywordsTheModelDrops(t *testing.T) { + // The union only reaches Widget through the keywords next to a $ref. The schema model reads them only with + // TransformSiblingRefs, and only where the schema is written: when it reaches a schema through a $ref, or an alias + // in a list, it follows the $ref of that schema and drops the rest. There the branches stay shared, as before. + const widget = "{$ref: '#/components/schemas/Widget'}" + const union = "oneOf: [{type: object, properties: {item: " + widget + "}}, {type: string}]" + const other = "\n Other: {type: object}" + holder := strings.Replace(usageResponseOnly, "Widget", "Holder", 1) + for _, tc := range []struct { + name, operation, schemas string + // breaking is the result with the transform on and then off. + breaking [2]bool + }{ + {"oneOf written next to a reference", + strings.Replace(usageResponseOnly, widget, "{$ref: '#/components/schemas/Other', "+union+"}", 1), + other, [2]bool{false, true}}, + {"oneOf next to a reference, reached through a reference", holder, + other + "\n Holder: {$ref: '#/components/schemas/Other', " + union + "}", [2]bool{true, true}}, + {"oneOf in the properties next to a reference, reached through a reference", holder, + other + "\n Holder: {$ref: '#/components/schemas/Other', properties: {p: {" + union + "}}}", [2]bool{true, true}}, + {"oneOf next to a reference in an alias", + " x-holder: &holder {$ref: '#/components/schemas/Other', " + union + "}\n" + + strings.Replace(usageResponseOnly, widget, "{anyOf: [*holder]}", 1), + other, [2]bool{true, true}}, + // The keywords the model drops inside an exclusive branch are shared as well. + {"keywords next to a reference in an exclusive branch, reached through a reference", + strings.Replace(usageResponseOnly, widget, "{oneOf: [{type: object, properties: {item: {$ref: '#/components/schemas/Holder'}}}, {type: string}]}", 1), + other + "\n Holder: {$ref: '#/components/schemas/Other', properties: {w: " + widget + "}}", [2]bool{true, true}}, + {"keywords next to a reference written in an exclusive branch", + strings.Replace(usageResponseOnly, widget, "{oneOf: [{$ref: '#/components/schemas/Other', type: object, properties: {item: "+widget+"}}, {type: string}]}", 1), + other, [2]bool{false, true}}, + } { + for i, transform := range []bool{true, false} { + t.Run(fmt.Sprintf("%s, TransformSiblingRefs %v", tc.name, transform), func(t *testing.T) { + build := func(required string) *v3.Document { + info, err := datamodel.ExtractSpecInfo([]byte(usageSpec(tc.operation, usageWidget(required)+tc.schemas))) + require.NoError(t, err) + config := datamodel.NewDocumentConfiguration() + config.TransformSiblingRefs = transform + doc, err := v3.CreateDocumentFromConfig(info, config) + require.NoError(t, err) + return doc + } + changes := CompareDocuments(build("name"), build("name, id")) + require.NotNil(t, changes) + for _, ch := range changes.GetAllChanges() { + if ch.Property == v3.RequiredLabel { + assert.Equal(t, tc.breaking[i], ch.Breaking) + return + } + } + t.Fatal("missing required change") + }) + } + } +} + +func TestRequiredOneOfBranchesElsewhereWithKeywordsTheModelDrops(t *testing.T) { + // Widget is only reached through the properties next to the $ref of Holder, which the model drops. One response + // refers to Holder directly and another through an exclusive union, in either order. Before this PR every oneOf was + // shared, so following keywords the model drops did not matter there. When both happen, every oneOf is shared again. + const union = "{oneOf: [{type: object, properties: {item: {$ref: '#/components/schemas/Holder'}}}, {type: string}]}" + const others = ` + /others: + get: + responses: + '200': + description: ok + content: + application/json: + schema: %s` + holder := strings.Replace(usageResponseOnly, "Widget", "Holder", 1) + const dropped = "\n Other: {type: object}\n Holder: {$ref: '#/components/schemas/Other', properties: {w: {$ref: '#/components/schemas/Widget'}}}" + for _, tc := range []struct { + name, first, second, schemas string + breaking bool + }{ + {"reference before the union", holder, fmt.Sprintf(others, union), dropped, true}, + {"union before the reference", strings.Replace(holder, "{$ref: '#/components/schemas/Holder'}", union, 1), fmt.Sprintf(others, "{$ref: '#/components/schemas/Holder'}"), dropped, true}, + {"no keywords next to a reference", holder, fmt.Sprintf(others, union), "\n Holder: {type: object, properties: {w: {$ref: '#/components/schemas/Widget'}}}", false}, + } { + for _, transform := range []bool{true, false} { + t.Run(fmt.Sprintf("%s, TransformSiblingRefs %v", tc.name, transform), func(t *testing.T) { + build := func(required string) *v3.Document { + spec := usageSpec(tc.first, usageWidget(required)+tc.schemas) + spec = strings.Replace(spec, "\ncomponents:", tc.second+"\ncomponents:", 1) + info, err := datamodel.ExtractSpecInfo([]byte(spec)) + require.NoError(t, err) + config := datamodel.NewDocumentConfiguration() + config.TransformSiblingRefs = transform + doc, err := v3.CreateDocumentFromConfig(info, config) + require.NoError(t, err) + return doc + } + changes := CompareDocuments(build("name"), build("name, id")) + require.NotNil(t, changes) + for _, ch := range changes.GetAllChanges() { + if ch.Property == v3.RequiredLabel { + assert.Equal(t, tc.breaking, ch.Breaking) + return + } + } + t.Fatal("missing required change") + }) + } + } +} + +func TestRequiredOneOfBranchesNextToTheReferenceOfAResponseOrPathItem(t *testing.T) { + // The model reads a response or path item with a $ref as the one it refers to, and drops the rest. The union next + // to that $ref is the only one that reaches Widget, so its branches stay shared, as before. + const union = "{oneOf: [{type: object, properties: {item: {$ref: '#/components/schemas/Widget'}}}, {type: string}]}" + const content = "content: {application/json: {schema: " + union + "}}" + for _, tc := range []struct { + name, path string + breaking bool + }{ + {"response", " get:\n responses:\n '200': {$ref: '#/components/responses/Empty', " + content + "}", true}, + {"path item", " $ref: '#/components/pathItems/Empty'\n get:\n responses:\n '200': {description: ok, " + content + "}", true}, + {"no reference", " get:\n responses:\n '200': {description: ok, " + content + "}", false}, + } { + for _, transform := range []bool{true, false} { + t.Run(fmt.Sprintf("%s, TransformSiblingRefs %v", tc.name, transform), func(t *testing.T) { + build := func(required string) *v3.Document { + spec := "openapi: 3.1.0\ninfo: {title: Direction, version: 1.0.0}\npaths:\n /widgets:\n" + tc.path + + "\ncomponents:\n responses:\n Empty: {description: ok}\n pathItems:\n Empty: {}\n schemas:\n" + usageWidget(required) + info, err := datamodel.ExtractSpecInfo([]byte(spec)) + require.NoError(t, err) + config := datamodel.NewDocumentConfiguration() + config.TransformSiblingRefs = transform + doc, err := v3.CreateDocumentFromConfig(info, config) + require.NoError(t, err) + return doc + } + changes := CompareDocuments(build("name"), build("name, id")) + require.NotNil(t, changes) + for _, ch := range changes.GetAllChanges() { + if ch.Property == v3.RequiredLabel { + assert.Equal(t, tc.breaking, ch.Breaking) + return + } + } + t.Fatal("missing required change") + }) + } + } +} + +func TestRequiredOneOfBranchesInARequest(t *testing.T) { + const widget = "{$ref: '#/components/schemas/Widget'}" + for _, tc := range []struct { + name, schema string + breaking bool + }{ + // A request may now leave out the property, and no instance can match the other branch as well. + {"branches that accept different types", "oneOf: [" + widget + ", {type: array}]", false}, + {"two objects", "oneOf: [" + widget + ", {type: object, required: [other], properties: {other: {type: string}}}]", true}, + } { + t.Run(tc.name, func(t *testing.T) { + op := strings.Replace(usageRequestOnly, widget, "{"+tc.schema+"}", 1) + requireEntryBreaking(t, usageSpec(op, usageWidget("name, id")), usageSpec(op, usageWidget("name")), tc.breaking) + }) + } +} + +// widgetUsage returns the direction of Widget in a document whose only response schema is the given YAML. The second +// result is false when the usage of the document is unknown. +func TestSchemaUsageOneOfBranchesWithAReferenceThatIsAnAlias(t *testing.T) { + // The model does not resolve a $ref whose value is an alias, so it cannot tell what such a branch accepts, and + // the walk following such a $ref elsewhere reaches what the model does not. Both keep the union shared, as before. + const widget = "{$ref: '#/components/schemas/Widget'}" + const others = "\n /others: {get: {responses: {'200': {description: ok, content: {application/json: {schema: {$ref: *other}}}}}}}" + for _, tc := range []struct { + name, schema, paths string + direction schemaDirection + }{ + {"branch that is such a reference", "{oneOf: [" + widget + ", {$ref: *text}]}", "", sharedSchema}, + {"such a reference elsewhere", "{oneOf: [" + widget + ", {type: string}]}", others, sharedSchema}, + {"no such reference", "{oneOf: [" + widget + ", {type: string}]}", "", responseSchema}, + } { + t.Run(tc.name, func(t *testing.T) { + var root yaml.Node + require.NoError(t, yaml.Unmarshal([]byte(`openapi: 3.1.0 +x-refs: {text: &text '#/components/schemas/Text', other: &other '#/components/schemas/Other'} +paths: + /widgets: {get: {responses: {'200': {description: ok, content: {application/json: {schema: `+tc.schema+`}}}}}}`+tc.paths+` +components: + schemas: + Widget: {type: object} + Text: {type: string} + Other: {type: object}`), &root)) + idx := index.NewSpecIndexWithConfig(&root, index.CreateClosedAPIIndexConfig()) + usage := buildSchemaUsage(idx) + require.NotNil(t, usage) + widget := idx.FindComponentInRoot(context.Background(), "#/components/schemas/Widget") + require.NotNil(t, widget) + assert.Equal(t, tc.direction, usage[widget.Node]) + }) + } +} + +func widgetUsage(t *testing.T, schema string) (schemaDirection, bool) { + t.Helper() + spec := `openapi: 3.1.0 +info: {title: Direction, version: 1.0.0} +paths: + /widgets: + get: + responses: + '200': + description: ok + content: + application/json: + schema: ` + schema + ` +components: + schemas: + Widget: {type: object} + Loop: {$ref: '#/components/schemas/Loop'} + LoopA: {$ref: '#/components/schemas/LoopB'} + LoopB: {$ref: '#/components/schemas/LoopA'} + Untyped: {minLength: 1}` + var root yaml.Node + require.NoError(t, yaml.Unmarshal([]byte(spec), &root)) + idx := index.NewSpecIndexWithConfig(&root, index.CreateClosedAPIIndexConfig()) + usage := buildSchemaUsage(idx) + if usage == nil { + return 0, false + } + widget := idx.FindComponentInRoot(context.Background(), "#/components/schemas/Widget") + require.NotNil(t, widget) + return usage[widget.Node], true +} + +func TestSchemaUsageOneOfBranches(t *testing.T) { + const widget = "{$ref: '#/components/schemas/Widget'}" + for _, tc := range []struct { + name, schema string + direction schemaDirection + known bool + }{ + {"branches that accept different types", "{oneOf: [" + widget + ", {type: array}]}", responseSchema, true}, + {"oneOf that is not a list", "{oneOf: {first: " + widget + "}}", sharedSchema, true}, + {"type that is not a name", "{oneOf: [" + widget + ", {type: [string, {a: b}]}]}", sharedSchema, true}, + {"type that is not a name or a list", "{oneOf: [" + widget + ", {type: {a: b}}]}", sharedSchema, true}, + {"reference that cannot be resolved next to a type", "{oneOf: [" + widget + ", {$ref: '#/components/schemas/Missing', type: string}]}", 0, false}, + {"empty list of types", "{oneOf: [" + widget + ", {type: []}]}", sharedSchema, true}, + {"reference cycle", "{oneOf: [" + widget + ", {$ref: '#/components/schemas/Loop'}]}", sharedSchema, true}, + {"reference cycle through two schemas", "{oneOf: [" + widget + ", {$ref: '#/components/schemas/LoopA'}]}", sharedSchema, true}, + {"empty list of types that is nullable", "{oneOf: [" + widget + ", {type: [], nullable: true}]}", sharedSchema, true}, + // Without a known version, the siblings of $ref may be ignored, so only the reference counts. + {"reference without a type next to a type in an unknown version", "{oneOf: [" + widget + ", {$ref: '#/components/schemas/Untyped', type: string}]}", sharedSchema, true}, + {"reference to nothing", "{oneOf: [" + widget + ", {$ref: '#/components/schemas/Missing'}]}", 0, false}, + } { + t.Run(tc.name, func(t *testing.T) { + direction, known := widgetUsage(t, tc.schema) + assert.Equal(t, tc.known, known) + assert.Equal(t, tc.direction, direction) + }) + } +} diff --git a/what-changed/model/schema_usage_test.go b/what-changed/model/schema_usage_test.go index c20977e1..04476b07 100644 --- a/what-changed/model/schema_usage_test.go +++ b/what-changed/model/schema_usage_test.go @@ -196,7 +196,7 @@ func TestRequiredConservativeSchemaContexts(t *testing.T) { }{ {"negated", "not: " + ref, true}, {"conditional predicate", "if: " + ref, true}, - {"exclusive union", "oneOf: [" + ref + "]", true}, + {"exclusive union of one branch", "oneOf: [" + ref + "]", false}, {"array items", "type: array, items: " + ref, false}, {"allOf reference", "allOf: [" + ref + "]", false}, {"property named not", "properties: {not: " + ref + "}", false},