Skip to content
Snippets Groups Projects
Commit d62b8803 authored by Jano Hendriks's avatar Jano Hendriks
Browse files

Fix potential nil pointer in audit event code and recover from panic

parent 206e4e45
No related branches found
No related tags found
No related merge requests found
......@@ -232,6 +232,20 @@ func CheckToFormatForAuditEvent(changes map[string]any, original any, new any, f
if !found {
return false
}
defer func() {
if err := recover(); err != nil {
logs.ErrorWithFields(map[string]any{
"error": err,
"field": field,
"index": index,
"original": fmt.Sprintf("%#v", originalFieldValue),
"new": fmt.Sprintf("%#v", newFieldValue),
}, errors.Error("Failed to format for audit event"))
}
didInsert = false
}()
doGroupSlice := doGroupSliceForAuditEvent(originalStructField)
originalFormattedObject := checkToFormatForAuditEvent(originalFieldValue, index)
......@@ -355,7 +369,7 @@ func checkToFormatForAuditEvent(fieldValue reflect.Value, index int) *string {
} else if fieldValue.Kind() == reflect.Slice &&
fieldValue.Len() > 0 {
if index == -1 ||
index > fieldValue.Len() {
index >= fieldValue.Len() {
return nil
}
......
......@@ -3,37 +3,43 @@ package audit
import (
"encoding/json"
"fmt"
"gitlab.bob.co.za/bob-public-utils/bobgroup-go-utils/utils"
"testing"
"time"
)
type StringType *string
type Tag struct {
Name string
Value *string
StrType *StringType
}
type MockObject struct {
Object interface{}
Name *string `json:"name"`
Strings []*string `json:"strings"`
Tags []Tag `json:"tag"`
TimeCreated *time.Time `json:"time_created"`
SingleTagPtr *Tag `json:"single_tag_ptr"`
SingleTag Tag `json:"single_tag"`
StrType *StringType `json:"str_type"`
}
func TestGetChanges(t *testing.T) {
object1 := MockObject{
Object: MockObject{
Object: MockObject{
Object: MockObject{
Object: MockObject{
Object: "done",
},
},
},
},
Strings: []*string{nil},
}
object2 := MockObject{
Object: MockObject{
Object: MockObject{
Object: MockObject{
Object: MockObject{
Object: "done1",
},
},
},
},
Name: utils.ValueToPointer("NewName"),
Strings: []*string{utils.ValueToPointer("NewStr1"), utils.ValueToPointer("NewStr2")},
Tags: []Tag{{"NewTag", utils.ValueToPointer("NewValue"), utils.ValueToPointer(StringType(utils.ValueToPointer("NewStrType")))}},
TimeCreated: utils.ValueToPointer(time.Now()),
SingleTagPtr: &Tag{"NewSingleTagPtr", utils.ValueToPointer("NewSingleValuePtr"), nil},
SingleTag: Tag{"NewSingleTag", utils.ValueToPointer("NewSingleValue"), nil},
StrType: utils.ValueToPointer(StringType(utils.ValueToPointer("NewStrType"))),
}
changes, err := GetChanges(object1, object2)
......@@ -41,6 +47,6 @@ func TestGetChanges(t *testing.T) {
panic(err)
}
result, _ := json.Marshal(changes)
fmt.Println(result)
result, _ := json.MarshalIndent(changes, "", " ")
fmt.Println(string(result))
}
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment