Skip to content

Commit ef1143d

Browse files
committed
fix(config): prevent panic on non-struct reflection
Add guard check in findFieldByTagWithMeta to validate input is a struct before calling NumField(). Prevents panic when function is called with non-struct types. Add comprehensive test coverage for string, int, bool, slice, and map types to verify guard behavior.
1 parent b20e98b commit ef1143d

File tree

2 files changed

+30
-0
lines changed

2 files changed

+30
-0
lines changed

pkg/config/setter.go

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -52,6 +52,10 @@ func findFieldByTag(v reflect.Value, name string) (reflect.Value, error) {
5252

5353
// findFieldByTagWithMeta finds a struct field and returns both the value and StructField metadata
5454
func findFieldByTagWithMeta(v reflect.Value, t reflect.Type, name string) (reflect.Value, reflect.StructField, error) {
55+
if v.Kind() != reflect.Struct {
56+
return reflect.Value{}, reflect.StructField{}, fmt.Errorf("expected struct, got %s", v.Kind())
57+
}
58+
5559
for i := 0; i < v.NumField(); i++ {
5660
field := t.Field(i)
5761

pkg/config/setter_test.go

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
package config
22

33
import (
4+
"reflect"
45
"testing"
56

67
"github.com/stretchr/testify/assert"
@@ -276,3 +277,28 @@ func TestSetConfigValue_DomainValidation_Verbosity(t *testing.T) {
276277
})
277278
}
278279
}
280+
281+
func TestFindFieldByTagWithMeta_NonStructValue(t *testing.T) {
282+
// Test that findFieldByTagWithMeta returns an error when given a non-struct value
283+
// This prevents a panic from calling NumField() on non-struct types
284+
tests := []struct {
285+
name string
286+
value interface{}
287+
}{
288+
{"string", "test"},
289+
{"int", 42},
290+
{"bool", true},
291+
{"slice", []string{"a", "b"}},
292+
{"map", map[string]string{"key": "value"}},
293+
}
294+
295+
for _, tt := range tests {
296+
t.Run(tt.name, func(t *testing.T) {
297+
v := reflect.ValueOf(tt.value)
298+
typ := v.Type()
299+
_, _, err := findFieldByTagWithMeta(v, typ, "anyfield")
300+
require.Error(t, err)
301+
assert.Contains(t, err.Error(), "expected struct")
302+
})
303+
}
304+
}

0 commit comments

Comments
 (0)