diff --git a/pkg/engine/jmespath/functions.go b/pkg/engine/jmespath/functions.go index fe992f5d3b..801280e18d 100644 --- a/pkg/engine/jmespath/functions.go +++ b/pkg/engine/jmespath/functions.go @@ -612,6 +612,7 @@ func jpPathCanonicalize(arguments []interface{}) (interface{}, error) { func jpTruncate(arguments []interface{}) (interface{}, error) { var err error + var normalizedLength float64 str, err := validateArg(truncate, arguments, 0, reflect.String) if err != nil { return nil, err @@ -621,7 +622,13 @@ func jpTruncate(arguments []interface{}) (interface{}, error) { return nil, err } - return trunc.Truncator(str.String(), int(length.Float()), trunc.CutStrategy{}), nil + if length.Float() < 0 { + normalizedLength = float64(0) + } else { + normalizedLength = length.Float() + } + + return trunc.Truncator(str.String(), int(normalizedLength), trunc.CutStrategy{}), nil } // InterfaceToString casts an interface to a string type diff --git a/pkg/engine/jmespath/functions_test.go b/pkg/engine/jmespath/functions_test.go index d74ea16534..b431595afe 100644 --- a/pkg/engine/jmespath/functions_test.go +++ b/pkg/engine/jmespath/functions_test.go @@ -995,6 +995,18 @@ func Test_Truncate(t *testing.T) { jmesPath: "truncate('Lorem ipsum ipsum ipsum dolor sit amet', `40`)", expectedResult: "Lorem ipsum ipsum ipsum dolor sit amet", }, + { + jmesPath: "truncate('Lorem ipsum', `2.6`)", + expectedResult: "Lo", + }, + { + jmesPath: "truncate('Lorem ipsum', `0`)", + expectedResult: "", + }, + { + jmesPath: "truncate('Lorem ipsum', `-1`)", + expectedResult: "", + }, } for _, tc := range testCases {