Skip to content

Commit

Permalink
Fix crash in metadata code with empty clause
Browse files Browse the repository at this point in the history
When empty clause is specified in resource, the code needs
to guard against nil value before casting the value to map.
This PR ensures this protection.
Signed-off-by: Anna Khmelnitsky <[email protected]>
  • Loading branch information
annakhm committed Jul 26, 2024
1 parent d7b7a0a commit 700f194
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 0 deletions.
12 changes: 12 additions & 0 deletions nsxt/metadata/metadata.go
Original file line number Diff line number Diff line change
Expand Up @@ -365,6 +365,12 @@ func SchemaToStruct(elem reflect.Value, d *schema.ResourceData, metadata map[str
nestedObj := reflect.New(item.Metadata.ReflectType)
itemList := getItemListForSchemaToStruct(d, item.Metadata.SchemaType, key, parent, parentMap)
if len(itemList) == 0 {
logger.Printf("[TRACE] Item list empty")
continue
}
if itemList[0] == nil {
// empty clause is specified
logger.Printf("[TRACE] Item list contains empty value")
continue
}
nestedSchema := itemList[0].(map[string]interface{})
Expand Down Expand Up @@ -394,6 +400,9 @@ func SchemaToStruct(elem reflect.Value, d *schema.ResourceData, metadata map[str
}

for i, v := range itemList {
if v == nil {
continue
}
if childElem.Metadata.SchemaType == "int" {
sliceElem.Index(i).Set(reflect.ValueOf(v).Convert(reflect.TypeOf(int64(0))))
} else {
Expand All @@ -409,6 +418,9 @@ func SchemaToStruct(elem reflect.Value, d *schema.ResourceData, metadata map[str
sliceElem.Set(
reflect.MakeSlice(reflect.SliceOf(item.Metadata.ReflectType), len(itemList), len(itemList)))
for i, childItem := range itemList {
if childItem == nil {
continue
}
nestedObj := reflect.New(item.Metadata.ReflectType)
nestedSchema := childItem.(map[string]interface{})
if err = SchemaToStruct(nestedObj.Elem(), d, childElem.Schema, key, nestedSchema); err != nil {
Expand Down
16 changes: 16 additions & 0 deletions nsxt/metadata/metadata_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -751,3 +751,19 @@ func TestSchemaToStructEmptySlice(t *testing.T) {
assert.Equal(t, 0, len(obj.StructList))
})
}

func TestSchemaToStructNilStruct(t *testing.T) {
d := schema.TestResourceDataRaw(
t, testSchema, map[string]interface{}{
"struct_field": []interface{}{nil},
})

obj := testStruct{}
elem := reflect.ValueOf(&obj).Elem()
err := SchemaToStruct(elem, d, testExtendedSchema, "", nil)
assert.NoError(t, err, "unexpected error calling SchemaToStruct")

t.Run("Struct field with Nil", func(t *testing.T) {
assert.Nil(t, obj.StructField)
})
}

0 comments on commit 700f194

Please sign in to comment.