diff --git a/schema_validation/OPENLINT-OPENAPI-LICENSE b/schema_validation/OPENLINT-OPENAPI-LICENSE new file mode 100644 index 0000000..5722d6b --- /dev/null +++ b/schema_validation/OPENLINT-OPENAPI-LICENSE @@ -0,0 +1,191 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + Copyright 2018 Stoplight, Inc. + Copyright 2026 OpenLint + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/schema_validation/directional_schema.go b/schema_validation/directional_schema.go index c89aeec..a7bbb5b 100644 --- a/schema_validation/directional_schema.go +++ b/schema_validation/directional_schema.go @@ -144,6 +144,10 @@ func pruneDirectionalRequired(schemaNode *yaml.Node, purpose SchemaValidationPur } func pruneRequiredAtSchema(schemaNode *yaml.Node, purpose SchemaValidationPurpose) { + pruneRequiredProperties(schemaNode, purpose, propertySchemaHasDirectionalAnnotation) +} + +func pruneRequiredProperties(schemaNode *yaml.Node, purpose SchemaValidationPurpose, exclude func(*yaml.Node, SchemaValidationPurpose) bool) { if purpose != SchemaValidationPurposeRequestBody && purpose != SchemaValidationPurposeResponseBody { return } @@ -164,7 +168,7 @@ func pruneRequiredAtSchema(schemaNode *yaml.Node, purpose SchemaValidationPurpos continue } propertySchema := mappingValue(propertiesNode, item.Value) - if propertySchemaHasDirectionalAnnotation(propertySchema, purpose) { + if exclude(propertySchema, purpose) { continue } prunedRequired = append(prunedRequired, item) @@ -182,15 +186,8 @@ func propertySchemaHasDirectionalAnnotation(schemaNode *yaml.Node, purpose Schem return false } - switch purpose { - case SchemaValidationPurposeRequestBody: - if boolMappingValue(schemaNode, "readOnly") { - return true - } - case SchemaValidationPurposeResponseBody: - if boolMappingValue(schemaNode, "writeOnly") { - return true - } + if directDirectionalAnnotation(schemaNode, purpose) { + return true } for _, key := range []string{"allOf", "anyOf", "oneOf"} { @@ -206,6 +203,20 @@ func propertySchemaHasDirectionalAnnotation(schemaNode *yaml.Node, purpose Schem return false } +func directDirectionalAnnotation(schemaNode *yaml.Node, purpose SchemaValidationPurpose) bool { + switch purpose { + case SchemaValidationPurposeRequestBody: + if boolMappingValue(schemaNode, "readOnly") { + return true + } + case SchemaValidationPurposeResponseBody: + if boolMappingValue(schemaNode, "writeOnly") { + return true + } + } + return false +} + func mappingPair(node *yaml.Node, key string) (int, *yaml.Node) { if node == nil || node.Kind != yaml.MappingNode { return -1, nil diff --git a/schema_validation/example_schema.go b/schema_validation/example_schema.go new file mode 100644 index 0000000..c2d4751 --- /dev/null +++ b/schema_validation/example_schema.go @@ -0,0 +1,252 @@ +// Copyright 2026 Dave Shanley / Quobix / Princess Beef Heavy Industries, LLC +// SPDX-License-Identifier: MIT AND Apache-2.0 +// Schema preparation includes adaptations from @openlint/ruleset-openapi. +// Copyright 2018 Stoplight, Inc. and 2026 OpenLint. See OPENLINT-OPENAPI-LICENSE. + +package schema_validation + +import ( + "bytes" + "crypto/sha256" + "encoding/json" + "errors" + "fmt" + "slices" + "sync" + + "github.com/pb33f/go-yaml" + "github.com/pb33f/jsonschema/v6" +) + +// ValidateYAMLNode checks a parsed document or value against a compiled schema. +// Validation failures retain their *jsonschema.ValidationError type and instance location. +func ValidateYAMLNode(node *yaml.Node, compiled *jsonschema.Schema) error { + if node == nil || compiled == nil { + return fmt.Errorf("validation requires a YAML node and a compiled schema") + } + value, err := DecodeYAMLValue(node) + if err != nil { + return err + } + return compiled.Validate(value) +} + +// DecodeYAMLValue returns the JSON data represented by a parsed YAML node. +// Scalar object keys and timestamps retain their authored spelling. Aliases and +// merge keys follow the YAML decoder's normal checks. The source is read-only. +func DecodeYAMLValue(node *yaml.Node) (any, error) { + if node == nil { + return nil, errors.New("missing YAML node") + } + normalized, err := jsonInputNode(node, make(map[*yaml.Node]*yaml.Node)) + if err != nil { + return nil, err + } + var value any + err = normalized.Decode(&value) + return value, err +} + +// Copy only paths containing a non-string key or a timestamp. Cache alias +// targets during traversal so repeated references never expand the graph. +func jsonInputNode(n *yaml.Node, aliases map[*yaml.Node]*yaml.Node) (*yaml.Node, error) { + if n.Kind == yaml.AliasNode { + if n.Alias == nil { + return nil, errors.New("missing YAML alias target") + } + target, seen := aliases[n.Alias] + if !seen { + aliases[n.Alias] = nil + var err error + target, err = jsonInputNode(n.Alias, aliases) + if err != nil { + return nil, err + } + aliases[n.Alias] = target + } + if target == nil { + return nil, errors.New("cyclic YAML alias") + } + if target != n.Alias { + copy := *n + copy.Alias = target + return ©, nil + } + return n, nil + } + if n.Kind == yaml.ScalarNode && n.ShortTag() == "!!timestamp" { + copy := *n + copy.Tag = "!!str" + return ©, nil + } + out := n + for i, child := range n.Content { + var next *yaml.Node + if n.Kind == yaml.MappingNode && i%2 == 0 && child.ShortTag() != "!!merge" { + key := child + if key.Kind == yaml.AliasNode { + key = key.Alias + } + if key == nil || key.Kind != yaml.ScalarNode { + return nil, errors.New("JSON object keys must be scalars") + } + next = key + if key.ShortTag() != "!!str" { + copy := *key + copy.Tag = "!!str" + next = © + } + } else { + var err error + next, err = jsonInputNode(child, aliases) + if err != nil { + return nil, err + } + } + if next != child { + if out == n { + copy := *n + copy.Content = slices.Clone(n.Content) + out = © + } + out.Content[i] = next + } + } + return out, nil +} + +type exampleSchemaKey struct { + example, swagger bool + purpose SchemaValidationPurpose + draft *jsonschema.Draft + digest [sha256.Size]byte +} + +type compiledExample func() (*jsonschema.Schema, error) + +// ExampleSchemaCache shares compiled inline example schemas by dialect and prepared content. +// Its zero value is ready for concurrent use. External resources are never loaded. +type ExampleSchemaCache struct { + mu sync.Mutex + schemas map[exampleSchemaKey]compiledExample +} + +// Compile prepares a YAML schema for generic, request, or response examples. +// swagger enables the Swagger 2.0 x-nullable and parameter required conventions. +func (c *ExampleSchemaCache) Compile(node *yaml.Node, draft *jsonschema.Draft, purpose SchemaValidationPurpose, swagger bool) (*jsonschema.Schema, error) { + if node == nil || draft == nil { + return nil, fmt.Errorf("example validation requires a schema and a draft") + } + schema, err := DecodeYAMLValue(node) + if err != nil { + return nil, err + } + return c.compile(schema, exampleSchemaKey{draft: draft, example: true, purpose: purpose, swagger: swagger}) +} + +// CompileSchema compiles a JSON-compatible inline schema under the supplied +// default dialect, sharing the same offline cache as Compile. +func (c *ExampleSchemaCache) CompileSchema(schema any, draft *jsonschema.Draft) (*jsonschema.Schema, error) { + return c.compile(schema, exampleSchemaKey{draft: draft}) +} + +func (c *ExampleSchemaCache) compile(schema any, key exampleSchemaKey) (*jsonschema.Schema, error) { + if key.draft == nil { + return nil, errors.New("missing default dialect") + } + data, err := json.Marshal(schema) + if err != nil { + return nil, err + } + key.digest = sha256.Sum256(data) + c.mu.Lock() + cached := c.schemas[key] + if cached == nil { + const maxSchemas = 1024 + if c.schemas == nil { + c.schemas = make(map[exampleSchemaKey]compiledExample) + } else if len(c.schemas) >= maxSchemas { + clear(c.schemas) + } + cached = sync.OnceValues(func() (*jsonschema.Schema, error) { + return key.compileResource(data, schema) + }) + c.schemas[key] = cached + } + c.mu.Unlock() + return cached() +} + +func (key exampleSchemaKey) compileResource(data []byte, schema any) (*jsonschema.Schema, error) { + resource, err := key.decodeResource(data, schema) + if err != nil { + return nil, err + } + compiler := jsonschema.NewCompiler() + compiler.UseLoader(jsonschema.SchemeURLLoader{}) + compiler.DefaultDraft(key.draft) + const id = "urn:example:schema" + var compiled *jsonschema.Schema + err = compiler.AddResource(id, resource) + if err == nil { + compiled, err = compiler.Compile(id) + } + return compiled, err +} + +func (key exampleSchemaKey) decodeResource(data []byte, schema any) (any, error) { + if !key.example { + // The compiler can retain enum and const values. Give it an owned copy. + return jsonschema.UnmarshalJSON(bytes.NewReader(data)) + } + // Encode the decoded YAML value directly. Parsing JSON text as YAML would fold + // literal U+0085 characters inside strings. + var doc yaml.Node + if err := doc.Encode(schema); err != nil { + return nil, err + } + n := &doc + if key.swagger { + if i, v := mappingPair(n, "required"); v != nil && v.ShortTag() == "!!bool" { + removeMappingPair(n, i) + } + } + prepareExampleSchema(n, key.purpose, key.swagger, false) + return DecodeYAMLValue(n) +} + +// Only schema-bearing keywords are traversed. A property named "not" or an +// example containing "required" must not be interpreted as a schema keyword. +func prepareExampleSchema(node *yaml.Node, purpose SchemaValidationPurpose, swagger, negated bool) { + if node.Kind != yaml.MappingNode { + return + } + if boolMappingValue(node, "nullable") || swagger && boolMappingValue(node, "x-nullable") { + if t := mappingValue(node, "type"); t != nil && t.ShortTag() == "!!str" && t.Value != "null" { + value := *t + *t = yaml.Node{Kind: yaml.SequenceNode, Tag: "!!seq", Content: []*yaml.Node{&value, {Kind: yaml.ScalarNode, Tag: "!!str", Value: "null"}}} + } + } + if !negated { + pruneRequiredProperties(node, purpose, directDirectionalAnnotation) + } + for i := 0; i+1 < len(node.Content); i += 2 { + k, v := node.Content[i].Value, node.Content[i+1] + switch k { + case "properties", "patternProperties", "$defs", "definitions", "dependentSchemas", "dependencies": + if v.Kind == yaml.MappingNode { + for j := 1; j < len(v.Content); j += 2 { + prepareExampleSchema(v.Content[j], purpose, swagger, negated) + } + } + case "not", "if", "then", "else", "additionalProperties", "additionalItems", "propertyNames", "contains", "items", "allOf", "anyOf", "oneOf", "prefixItems", "unevaluatedProperties", "unevaluatedItems": + if v.Kind == yaml.SequenceNode { + for _, child := range v.Content { + prepareExampleSchema(child, purpose, swagger, negated) + } + } else { + prepareExampleSchema(v, purpose, swagger, negated != (k == "not")) + } + } + } +} diff --git a/schema_validation/example_schema_test.go b/schema_validation/example_schema_test.go new file mode 100644 index 0000000..2af0f83 --- /dev/null +++ b/schema_validation/example_schema_test.go @@ -0,0 +1,207 @@ +// Copyright 2026 Dave Shanley / Quobix / Princess Beef Heavy Industries, LLC +// SPDX-License-Identifier: MIT + +package schema_validation + +import ( + "fmt" + "sync" + "testing" + + "github.com/pb33f/go-yaml" + "github.com/pb33f/jsonschema/v6" + "github.com/pb33f/testify/require" +) + +func TestCompiledExampleValidation(t *testing.T) { + parse := func(source string) *yaml.Node { + t.Helper() + var n yaml.Node + require.NoError(t, yaml.Unmarshal([]byte(source), &n)) + return &n + } + schema := parse(`type: object +required: [id, secret] +properties: + id: {type: integer, readOnly: true} + secret: {type: string, writeOnly: true}`) + var c ExampleSchemaCache + request, err := c.Compile(schema, jsonschema.Draft4, SchemaValidationPurposeRequestBody, false) + require.NoError(t, err) + response, err := c.Compile(schema, jsonschema.Draft4, SchemaValidationPurposeResponseBody, false) + require.NoError(t, err) + value := parse("{secret: sample}") + require.NoError(t, ValidateYAMLNode(value, request)) + var failure *jsonschema.ValidationError + require.ErrorAs(t, ValidateYAMLNode(value, response), &failure) + require.NoError(t, ValidateYAMLNode(parse("{id: 2}"), response)) + again, err := c.Compile(schema, jsonschema.Draft4, SchemaValidationPurposeRequestBody, false) + require.NoError(t, err) + require.Same(t, request, again) + newer, err := c.Compile(schema, jsonschema.Draft2020, SchemaValidationPurposeRequestBody, false) + require.NoError(t, err) + require.NotSame(t, request, newer) + // The same input can still be compiled for the opposite direction. + require.Len(t, schema.Content[0].Content[3].Content, 2) +} + +func TestExampleSchemaDialectAndResources(t *testing.T) { + var c ExampleSchemaCache + for _, tc := range []struct { + schema string + draft *jsonschema.Draft + invalid bool + }{ + {`{type: number, minimum: 3, exclusiveMinimum: true}`, jsonschema.Draft4, false}, + {`{type: number, minimum: 3, exclusiveMinimum: true}`, jsonschema.Draft2020, true}, + {`{$ref: 'file:///does-not-exist'}`, jsonschema.Draft7, true}, + {`{$ref: 'https://unavailable.invalid/schema'}`, jsonschema.Draft7, true}, + } { + var n yaml.Node + require.NoError(t, yaml.Unmarshal([]byte(tc.schema), &n)) + compiled, err := c.Compile(&n, tc.draft, SchemaValidationPurposeGeneric, false) + if tc.invalid { + require.Error(t, err) + if tc.schema[1] == '$' { + require.Contains(t, err.Error(), "no URLLoader") + } + continue + } + require.NoError(t, err) + require.Error(t, compiled.Validate(3)) + require.NoError(t, compiled.Validate(4)) + } +} + +func TestDecodeYAMLValuePreservesKeysAndDates(t *testing.T) { + var doc yaml.Node + require.NoError(t, yaml.Unmarshal([]byte("01: &date 2026-11-15\n'1': *date\nnumber: &id 4\nmap: {? *id : text}\n"), &doc)) + got, err := DecodeYAMLValue(&doc) + require.NoError(t, err) + require.Equal(t, map[string]any{"01": "2026-11-15", "1": "2026-11-15", "number": 4, "map": map[string]any{"4": "text"}}, got) + require.Equal(t, "!!timestamp", doc.Content[0].Content[1].ShortTag()) +} + +func TestCompileExamplePreservesNegatedRequiredAndSwaggerNullable(t *testing.T) { + var cache ExampleSchemaCache + var n yaml.Node + require.NoError(t, yaml.Unmarshal([]byte(`type: object +not: + required: [id] + properties: + id: {type: string, readOnly: true} +properties: + value: {type: integer, x-nullable: true}`), &n)) + sch, err := cache.Compile(&n, jsonschema.Draft4, SchemaValidationPurposeRequestBody, true) + require.NoError(t, err) + require.NoError(t, sch.Validate(map[string]any{"value": nil})) + require.Error(t, sch.Validate(map[string]any{"id": "present"})) +} + +func TestCompileSchemaReusesFailures(t *testing.T) { + var c ExampleSchemaCache + invalid := map[string]any{"type": "not-a-type"} + _, a := c.CompileSchema(invalid, jsonschema.Draft7) + _, b := c.CompileSchema(invalid, jsonschema.Draft7) + require.Error(t, a) + require.Same(t, a, b) +} + +func TestCachedInlineSchemaOwnsEnumValues(t *testing.T) { + var c ExampleSchemaCache + v := map[string]any{"v": "original"} + schema := map[string]any{"enum": []any{v}} + compiled, err := c.CompileSchema(schema, jsonschema.Draft7) + require.NoError(t, err) + v["v"] = "changed" + require.NoError(t, compiled.Validate(map[string]any{"v": "original"})) + require.Error(t, compiled.Validate(v)) +} + +func TestYAMLValidationInvalidInputs(t *testing.T) { + var c ExampleSchemaCache + compiled, err := c.CompileSchema(true, jsonschema.Draft7) + require.NoError(t, err) + require.Error(t, ValidateYAMLNode(nil, compiled)) + _, err = DecodeYAMLValue(nil) + require.Error(t, err) + _, err = c.Compile(nil, jsonschema.Draft7, SchemaValidationPurposeGeneric, false) + require.Error(t, err) + _, err = c.CompileSchema(true, nil) + require.Error(t, err) + _, err = c.CompileSchema(make(chan int), jsonschema.Draft7) + require.Error(t, err) + + var cyclic, complexKey yaml.Node + require.NoError(t, yaml.Unmarshal([]byte("cycle: &cycle [*cycle]"), &cyclic)) + require.NoError(t, yaml.Unmarshal([]byte("? [a,b]\n: value"), &complexKey)) + for _, n := range []*yaml.Node{&cyclic, &complexKey, {Kind: yaml.AliasNode}} { + require.Error(t, ValidateYAMLNode(n, compiled)) + _, err := c.Compile(n, jsonschema.Draft7, SchemaValidationPurposeGeneric, false) + require.Error(t, err) + } + for _, example := range []bool{false, true} { + key := exampleSchemaKey{draft: jsonschema.Draft7, example: example} + _, err := key.compileResource([]byte("{"), invalidExampleSchema{}) + require.Error(t, err) + } +} + +func TestMergedExampleAndSwaggerParameter(t *testing.T) { + var node yaml.Node + require.NoError(t, yaml.Unmarshal([]byte("source: &defaults {type: string}\nvalue: {<<: *defaults, required: true, allOf: [{minLength: 2}]}"), &node)) + var c ExampleSchemaCache + schema, err := c.Compile(mappingValue(node.Content[0], "value"), jsonschema.Draft4, SchemaValidationPurposeGeneric, true) + require.NoError(t, err) + require.NoError(t, schema.Validate("ok")) + require.Error(t, schema.Validate("x")) + require.NoError(t, yaml.Unmarshal([]byte("true"), &node)) + boolean, err := c.Compile(&node, jsonschema.Draft7, SchemaValidationPurposeGeneric, false) + require.NoError(t, err) + require.NoError(t, boolean.Validate(nil)) +} + +func TestExampleSchemaCacheConcurrentReuseAndEviction(t *testing.T) { + var c ExampleSchemaCache + const workers = 8 + var wg sync.WaitGroup + var schemas [workers]*jsonschema.Schema + var errs [workers]error + for i := range workers { + wg.Go(func() { + schemas[i], errs[i] = c.CompileSchema(true, jsonschema.Draft7) + }) + } + wg.Wait() + for i := range workers { + require.NoError(t, errs[i]) + require.Same(t, schemas[0], schemas[i]) + } + + for i := range 1024 { + _, err := c.CompileSchema(map[string]any{"title": fmt.Sprint(i)}, jsonschema.Draft7) + require.NoError(t, err) + } + again, err := c.CompileSchema(true, jsonschema.Draft7) + require.NoError(t, err) + require.NotSame(t, schemas[0], again) + require.NoError(t, schemas[0].Validate("still usable")) +} + +// The example compiler must propagate an error from the YAML encoder. +type invalidExampleSchema struct{} + +func (invalidExampleSchema) MarshalYAML() (any, error) { + return nil, fmt.Errorf("cannot encode test schema") +} + +func TestExampleSchemaPreservesUnicodeAndNumbers(t *testing.T) { + var doc yaml.Node + require.NoError(t, yaml.Unmarshal([]byte(`{const: ["\u0085", 9007199254740993]}`), &doc)) + var cache ExampleSchemaCache + compiled, err := cache.Compile(&doc, jsonschema.Draft7, SchemaValidationPurposeGeneric, false) + require.NoError(t, err) + require.NoError(t, compiled.Validate([]any{"\u0085", int64(9007199254740993)})) + require.Error(t, compiled.Validate([]any{" ", int64(9007199254740993)})) + require.Error(t, compiled.Validate([]any{"\u0085", int64(9007199254740992)})) +}