From 4cef2b412c0d871d39198055faf665e97dbe2fb0 Mon Sep 17 00:00:00 2001 From: Kevin Wan Date: Sat, 11 Mar 2023 07:53:57 +0800 Subject: [PATCH] fix: avoid unmarshal panic with incorrect map keys #3002 (#3013) --- core/mapping/unmarshaler.go | 4 ++++ core/mapping/unmarshaler_test.go | 15 +++++++++++++++ 2 files changed, 19 insertions(+) diff --git a/core/mapping/unmarshaler.go b/core/mapping/unmarshaler.go index f8674211..d19469f3 100644 --- a/core/mapping/unmarshaler.go +++ b/core/mapping/unmarshaler.go @@ -289,6 +289,10 @@ func (u *Unmarshaler) generateMap(keyType, elemType reflect.Type, mapValue any) return reflect.ValueOf(mapValue), nil } + if keyType != valueType.Key() { + return emptyValue, errTypeMismatch + } + refValue := reflect.ValueOf(mapValue) targetValue := reflect.MakeMapWithSize(mapType, refValue.Len()) dereffedElemType := Deref(elemType) diff --git a/core/mapping/unmarshaler_test.go b/core/mapping/unmarshaler_test.go index cdd7b98a..4b6148a2 100644 --- a/core/mapping/unmarshaler_test.go +++ b/core/mapping/unmarshaler_test.go @@ -4437,3 +4437,18 @@ func TestFillDefaultUnmarshal(t *testing.T) { assert.Error(t, err) }) } + +func Test_UnmarshalMap(t *testing.T) { + type Customer struct { + Names map[int]string `key:"names"` + } + + input := map[string]any{ + "names": map[string]any{ + "19": "Tom", + }, + } + + var customer Customer + assert.ErrorIs(t, UnmarshalKey(input, &customer), errTypeMismatch) +}