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

discriminator value should verify the type is string to avoid panic #509

Merged
merged 3 commits into from
Mar 14, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 6 additions & 1 deletion openapi3/schema.go
Original file line number Diff line number Diff line change
Expand Up @@ -871,7 +871,12 @@ func (schema *Schema) visitSetOperations(settings *schemaValidationSettings, val
return errors.New("input does not contain the discriminator property")
}

if discriminatorRef, okcheck = schema.Discriminator.Mapping[discriminatorVal.(string)]; len(schema.Discriminator.Mapping) > 0 && !okcheck {
discriminatorValString, okcheck := discriminatorVal.(string)
if !okcheck {
return errors.New("descriminator value is not a string")
}

if discriminatorRef, okcheck = schema.Discriminator.Mapping[discriminatorValString]; len(schema.Discriminator.Mapping) > 0 && !okcheck {
return errors.New("input does not contain a valid discriminator value")
}
}
Expand Down
18 changes: 18 additions & 0 deletions openapi3/schema_oneOf_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -116,3 +116,21 @@ func TestVisitJSON_OneOf_NoDiscriptor_MissingField(t *testing.T) {
})
require.EqualError(t, err, "doesn't match schema due to: Error at \"/scratches\": property \"scratches\" is missing\nSchema:\n {\n \"properties\": {\n \"name\": {\n \"type\": \"string\"\n },\n \"scratches\": {\n \"type\": \"boolean\"\n }\n },\n \"required\": [\n \"name\",\n \"scratches\"\n ],\n \"type\": \"object\"\n }\n\nValue:\n {\n \"name\": \"snoopy\"\n }\n Or Error at \"/barks\": property \"barks\" is missing\nSchema:\n {\n \"properties\": {\n \"barks\": {\n \"type\": \"boolean\"\n },\n \"name\": {\n \"type\": \"string\"\n }\n },\n \"required\": [\n \"name\",\n \"barks\"\n ],\n \"type\": \"object\"\n }\n\nValue:\n {\n \"name\": \"snoopy\"\n }\n")
}

func TestVisitJSON_OneOf_BadDescriminatorType(t *testing.T) {
s, err := NewLoader().LoadFromData(oneofSpec)
require.NoError(t, err)
err = s.Components.Schemas["Animal"].Value.VisitJSON(map[string]interface{}{
"name": "snoopy",
"scratches": true,
"$type": 1,
})
require.EqualError(t, err, "descriminator value is not a string")

err = s.Components.Schemas["Animal"].Value.VisitJSON(map[string]interface{}{
"name": "snoopy",
"barks": true,
"$type": nil,
})
require.EqualError(t, err, "descriminator value is not a string")
}