Browse Source

fix: avoid unmarshal panic with incorrect map keys #3002 (#3013)

Kevin Wan 2 years ago
parent
commit
4cef2b412c
2 changed files with 19 additions and 0 deletions
  1. 4 0
      core/mapping/unmarshaler.go
  2. 15 0
      core/mapping/unmarshaler_test.go

+ 4 - 0
core/mapping/unmarshaler.go

@@ -289,6 +289,10 @@ func (u *Unmarshaler) generateMap(keyType, elemType reflect.Type, mapValue any)
 		return reflect.ValueOf(mapValue), nil
 		return reflect.ValueOf(mapValue), nil
 	}
 	}
 
 
+	if keyType != valueType.Key() {
+		return emptyValue, errTypeMismatch
+	}
+
 	refValue := reflect.ValueOf(mapValue)
 	refValue := reflect.ValueOf(mapValue)
 	targetValue := reflect.MakeMapWithSize(mapType, refValue.Len())
 	targetValue := reflect.MakeMapWithSize(mapType, refValue.Len())
 	dereffedElemType := Deref(elemType)
 	dereffedElemType := Deref(elemType)

+ 15 - 0
core/mapping/unmarshaler_test.go

@@ -4437,3 +4437,18 @@ func TestFillDefaultUnmarshal(t *testing.T) {
 		assert.Error(t, err)
 		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)
+}