Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

schema.markSchemaErrorKey() disposes of oneOf context #940

Closed
jordan-wu-97 opened this issue Apr 15, 2024 · 0 comments · Fixed by #941
Closed

schema.markSchemaErrorKey() disposes of oneOf context #940

jordan-wu-97 opened this issue Apr 15, 2024 · 0 comments · Fixed by #941

Comments

@jordan-wu-97
Copy link
Contributor

oneOf validation provides a good reason of value doesn't match any schema from "oneOf"

kin-openapi/openapi3/schema.go

Lines 1380 to 1381 in 9dbb4c3

e.Origin = fmt.Errorf("doesn't match schema due to: %w", validationErrors)
e.Reason = `value doesn't match any schema from "oneOf"`

However, the function markSchemaErrorKey unwraps the Origin to err, resulting in the original error containing the oneOf context being lost (line 2125)

kin-openapi/openapi3/schema.go

Lines 2121 to 2139 in 9dbb4c3

func markSchemaErrorKey(err error, key string) error {
var me multiErrorForOneOf
if errors.As(err, &me) {
err = me.Unwrap()
}
if v, ok := err.(*SchemaError); ok {
v.reversePath = append(v.reversePath, key)
return v
}
if v, ok := err.(MultiError); ok {
for _, e := range v {
_ = markSchemaErrorKey(e, key)
}
return v
}
return err
}

Example:

func TestOneOfSchema(t *testing.T) {

	openapi3.SchemaErrorDetailsDisabled = true

	// language=json
	raw := `
{
	"foo": [ "bar" ]
}
`

	// language=json
	schema := `
{
	"type": "object",
	"properties": {
		"foo": {
			"oneOf": [
				{
					"type": "number"
				},
					{
					"type": "string"
				}
			]
		}
	}
}
`

	s := openapi3.NewSchema()
	err := s.UnmarshalJSON([]byte(schema))
	require.NoError(t, err)
	err = s.Validate(context.Background())
	require.NoError(t, err)

	obj := make(map[string]interface{})
	err = json.Unmarshal([]byte(raw), &obj)
	require.NoError(t, err)

	err = s.VisitJSON(obj, openapi3.MultiErrors())
	fmt.Println(err.Error())

}

Output:

Error at "/foo": value must be a number | Error at "/foo": value must be a string

We lost the error message describing that foo must be oneOf the schemas

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

1 participant