Skip to content

Commit

Permalink
discriminator value should verify the type is string to avoid panic (#…
Browse files Browse the repository at this point in the history
  • Loading branch information
kandaaaaa authored Mar 14, 2022
1 parent 590c85c commit 943ee05
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 1 deletion.
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")
}

0 comments on commit 943ee05

Please sign in to comment.