From e03b5a87ebc61c77dc93788e369deb771e052793 Mon Sep 17 00:00:00 2001 From: Pierre Fenoll Date: Wed, 21 Sep 2022 15:52:14 +0200 Subject: [PATCH] Validate default values against schema (#610) --- openapi3/issue136_test.go | 53 +++++++++++++++++++++++++++++++++++++++ openapi3/schema.go | 6 +++++ 2 files changed, 59 insertions(+) create mode 100644 openapi3/issue136_test.go diff --git a/openapi3/issue136_test.go b/openapi3/issue136_test.go new file mode 100644 index 000000000..36c8b8588 --- /dev/null +++ b/openapi3/issue136_test.go @@ -0,0 +1,53 @@ +package openapi3 + +import ( + "testing" + + "github.com/stretchr/testify/require" +) + +func TestIssue136(t *testing.T) { + specf := func(dflt string) string { + return ` +openapi: 3.0.2 +info: + title: "Hello World REST APIs" + version: "1.0" +paths: {} +components: + schemas: + SomeSchema: + type: string + default: ` + dflt + ` +` + } + + for _, testcase := range []struct { + dflt, err string + }{ + { + dflt: `"foo"`, + err: "", + }, + { + dflt: `1`, + err: "invalid components: invalid schema default: Field must be set to string or not be present", + }, + } { + t.Run(testcase.dflt, func(t *testing.T) { + spec := specf(testcase.dflt) + + sl := NewLoader() + + doc, err := sl.LoadFromData([]byte(spec)) + require.NoError(t, err) + + err = doc.Validate(sl.Context) + if testcase.err == "" { + require.NoError(t, err) + } else { + require.Error(t, err, testcase.err) + } + }) + } +} diff --git a/openapi3/schema.go b/openapi3/schema.go index ded97f02a..9b36e604a 100644 --- a/openapi3/schema.go +++ b/openapi3/schema.go @@ -753,6 +753,12 @@ func (schema *Schema) validate(ctx context.Context, stack []*Schema) (err error) } } + if v := schema.Default; v != nil { + if err := schema.VisitJSON(v); err != nil { + return fmt.Errorf("invalid schema default: %w", err) + } + } + if x := schema.Example; x != nil && !validationOpts.ExamplesValidationDisabled { if err := validateExampleValue(x, schema); err != nil { return fmt.Errorf("invalid schema example: %w", err)