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

fix: prevent panic on examples for pointer field types #148

Merged
merged 2 commits into from
Oct 22, 2023
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
26 changes: 17 additions & 9 deletions schema.go
Original file line number Diff line number Diff line change
Expand Up @@ -198,7 +198,7 @@
} else if v == "false" {
return false
} else {
panic("invalid bool tag '" + tag + "' for field '" + f.Name + "': " + v)
panic(fmt.Errorf("invalid bool tag '%s' for field '%s': %v", tag, f.Name, v))
}
}
return false
Expand All @@ -209,7 +209,7 @@
if i, err := strconv.Atoi(v); err == nil {
return &i
} else {
panic("invalid int tag '" + tag + "' for field '" + f.Name + "': " + v + " (" + err.Error() + ")")
panic(fmt.Errorf("invalid int tag '%s' for field '%s': %v (%w)", tag, f.Name, v, err))
}
}
return nil
Expand All @@ -220,15 +220,15 @@
if i, err := strconv.ParseFloat(v, 64); err == nil {
return &i
} else {
panic("invalid float tag '" + tag + "' for field '" + f.Name + "': " + v + " (" + err.Error() + ")")
panic(fmt.Errorf("invalid float tag '%s' for field '%s': %v (%w)", tag, f.Name, v, err))
}
}
return nil
}

func jsonTagValue(f reflect.StructField, t reflect.Type, value string) any {
// Special case: strings don't need quotes.
if t.Kind() == reflect.String {
if t.Kind() == reflect.String || (t.Kind() == reflect.Pointer && t.Elem().Kind() == reflect.String) {
return value
}

Expand All @@ -243,7 +243,7 @@

var v any
if err := json.Unmarshal([]byte(value), &v); err != nil {
panic("invalid tag for field '" + f.Name + "': " + err.Error())
panic(fmt.Errorf("invalid tag for field '%s': %w", f.Name, err))
}

vv := reflect.ValueOf(v)
Expand All @@ -256,17 +256,25 @@
tmp := reflect.MakeSlice(t, 0, vv.Len())
for i := 0; i < vv.Len(); i++ {
if !vv.Index(i).Elem().Type().ConvertibleTo(t.Elem()) {
panic(fmt.Errorf("unable to convert %v to %v: %w", vv.Index(i).Interface(), t.Elem(), ErrSchemaInvalid))
panic(fmt.Errorf("unable to convert %v to %v for field '%s': %w", vv.Index(i).Interface(), t.Elem(), f.Name, ErrSchemaInvalid))

Check warning on line 259 in schema.go

View check run for this annotation

Codecov / codecov/patch

schema.go#L259

Added line #L259 was not covered by tests
}

tmp = reflect.Append(tmp, vv.Index(i).Elem().Convert(t.Elem()))
}
v = tmp.Interface()
} else if !tv.ConvertibleTo(t) {
panic(fmt.Errorf("unable to convert %v to %v: %w", tv, t, ErrSchemaInvalid))
} else if !tv.ConvertibleTo(deref(t)) {
panic(fmt.Errorf("unable to convert %v to %v for field '%s': %w", tv, t, f.Name, ErrSchemaInvalid))
}

v = reflect.ValueOf(v).Convert(t).Interface()
converted := reflect.ValueOf(v).Convert(deref(t))
if t.Kind() == reflect.Ptr {
// Special case: if the field is a pointer, we need to get a pointer
// to the converted value.
tmp := reflect.New(t.Elem())
tmp.Elem().Set(converted)
converted = tmp
}
v = converted.Interface()
}

return v
Expand Down
32 changes: 31 additions & 1 deletion schema_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -369,6 +369,29 @@ func TestSchema(t *testing.T) {
}
}`,
},
{
name: "field-pointer-example",
input: struct {
Int *int64 `json:"int" example:"123"`
Str *string `json:"str" example:"foo"`
}{},
expected: `{
"type": "object",
"additionalProperties": false,
"required": ["int", "str"],
"properties": {
"int": {
"type": "integer",
"format": "int64",
"examples": [123]
},
"str": {
"type": "string",
"examples": ["foo"]
}
}
}`,
},
{
name: "panic-bool",
input: struct {
Expand Down Expand Up @@ -397,14 +420,21 @@ func TestSchema(t *testing.T) {
}{},
panics: `invalid tag for field 'Value': invalid character 'b' looking for beginning of value`,
},
{
name: "panic-json-type",
input: struct {
Value int `json:"value" example:"true"`
}{},
panics: `unable to convert bool to int for field 'Value': schema is invalid`,
},
}

for _, c := range cases {
t.Run(c.name, func(t *testing.T) {
r := NewMapRegistry("#/components/schemas/", DefaultSchemaNamer)

if c.panics != "" {
assert.PanicsWithValue(t, c.panics, func() {
assert.PanicsWithError(t, c.panics, func() {
r.Schema(reflect.TypeOf(c.input), false, "")
})
} else {
Expand Down
Loading