From 0c71f9385d92016e96e1b226f91b3d14282fbd14 Mon Sep 17 00:00:00 2001 From: Christian Haudum Date: Fri, 4 Oct 2024 17:10:50 +0200 Subject: [PATCH] fix(logql): Fix panic in json parsing when using invalid array index This PR fixes a panic that occurs with the following json parser expression: ``` | json keys[""] ``` when the log line is the following: ```json {"keys": ["a", "b", "c"]} ``` Signed-off-by: Christian Haudum --- pkg/logql/log/parser_test.go | 20 +++++++++++++++++++ .../github.com/grafana/jsonparser/parser.go | 6 +----- 2 files changed, 21 insertions(+), 5 deletions(-) diff --git a/pkg/logql/log/parser_test.go b/pkg/logql/log/parser_test.go index 28989b7cb5fe..fd08467af858 100644 --- a/pkg/logql/log/parser_test.go +++ b/pkg/logql/log/parser_test.go @@ -368,6 +368,26 @@ func TestJSONExpressionParser(t *testing.T) { labels.FromStrings("param", "1"), NoParserHints(), }, + { + "object element not present", + testLine, + []LabelExtractionExpr{ + NewLabelExtractionExpr("undefined", `pod[""]`), + }, + labels.EmptyLabels(), + labels.FromStrings("undefined", ""), + NoParserHints(), + }, + { + "accessing invalid array index", + testLine, + []LabelExtractionExpr{ + NewLabelExtractionExpr("param", `pod.deployment.params[""]`), + }, + labels.EmptyLabels(), + labels.FromStrings("param", ""), + NoParserHints(), + }, { "array string element", testLine, diff --git a/vendor/github.com/grafana/jsonparser/parser.go b/vendor/github.com/grafana/jsonparser/parser.go index 5df2a463dcee..df49f2aba0f2 100644 --- a/vendor/github.com/grafana/jsonparser/parser.go +++ b/vendor/github.com/grafana/jsonparser/parser.go @@ -512,7 +512,7 @@ func EachKey(data []byte, cb func(int, []byte, ValueType, error), paths ...[]str } for pi, p := range paths { - if len(p) < level+1 || pathFlags[pi] || p[level][0] != '[' || !sameTree(p, pathsBuf[:level]) { + if len(p) < level+1 || pathFlags[pi] || p[level] == "" || p[level][0] != '[' || !sameTree(p, pathsBuf[:level]) { continue } if len(p[level]) >= 2 { @@ -712,12 +712,10 @@ func WriteToBuffer(buffer []byte, str string) int { } /* - Del - Receives existing data structure, path to delete. Returns: `data` - return modified data - */ func Delete(data []byte, keys ...string) []byte { lk := len(keys) @@ -798,13 +796,11 @@ func Delete(data []byte, keys ...string) []byte { } /* - Set - Receives existing data structure, path to set, and data to set at that key. Returns: `value` - modified byte array `err` - On any parsing error - */ func Set(data []byte, setValue []byte, keys ...string) (value []byte, err error) { // ensure keys are set