From f91dc0bce7176cbcca8e6c6c9069f66afbc45986 Mon Sep 17 00:00:00 2001 From: Erik Jankovic Date: Fri, 28 Feb 2025 17:33:45 +0100 Subject: [PATCH] fix: make sure Fields map is not nil --- api/types/events/events.go | 5 +++ api/types/events/struct_test.go | 69 +++++++++++++++++++++++++++++++++ 2 files changed, 74 insertions(+) create mode 100644 api/types/events/struct_test.go diff --git a/api/types/events/events.go b/api/types/events/events.go index 7938c5a6c66e4..bfbd38c26a755 100644 --- a/api/types/events/events.go +++ b/api/types/events/events.go @@ -192,6 +192,11 @@ func (m *Struct) trimToMaxSize(maxSize int) *Struct { if v != nil { if strVal := v.GetStringValue(); strVal != "" { trimmedVal := trimStr(strVal, maxSize) + + if out.Fields == nil { + out.Fields = make(map[string]*types.Value) + } + out.Fields[trimmedKey] = &types.Value{ Kind: &types.Value_StringValue{ StringValue: trimmedVal, diff --git a/api/types/events/struct_test.go b/api/types/events/struct_test.go new file mode 100644 index 0000000000000..337170b69ec31 --- /dev/null +++ b/api/types/events/struct_test.go @@ -0,0 +1,69 @@ +/* +Copyright 2025 Gravitational, Inc. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package events + +import ( + "reflect" + "strings" + "testing" + + "github.com/gogo/protobuf/types" + "github.com/stretchr/testify/require" +) + +func TestStructTrimToMaxSize(t *testing.T) { + testCases := []struct { + name string + maxSize int + in *Struct + want *Struct + }{ + { + name: "Field key exceeds max limit size", + maxSize: 10, + in: &Struct{ + Struct: types.Struct{ + Fields: map[string]*types.Value{ + strings.Repeat("A", 100): { + Kind: &types.Value_StringValue{ + StringValue: "A", + }, + }, + }, + }, + }, + want: &Struct{ + Struct: types.Struct{ + Fields: map[string]*types.Value{ + strings.Repeat("A", 8): { + Kind: &types.Value_StringValue{ + StringValue: "A", + }, + }, + }, + }, + }, + }, + } + + for _, tc := range testCases { + t.Run(tc.name, func(t *testing.T) { + got := tc.in.trimToMaxSize(tc.maxSize) + require.True(t, reflect.DeepEqual(got, tc.want)) + }) + } +}