From b7f957d55233e333be72d1db2e77e5692f93d532 Mon Sep 17 00:00:00 2001 From: Philip Conrad Date: Thu, 29 Sep 2022 22:55:25 -0400 Subject: [PATCH] topdown/json: Fix panic in json.filter on empty JSON paths. (#5200) This commit fixes a panic discovered in the `json.filter` builtin that could be triggered with an empty JSON path parameter, such as `""`. This panic was caused by indexing logic in a helper function always assuming it had at least one path segment to work with, and thus indexing out-of-bounds when no path segment was present. The issue was fixed by adding an extra check to the helper function for the null path case, and adding new unit tests to check for the issue. Fixes: #5199 Signed-off-by: Philip Conrad --- topdown/json.go | 6 ++++++ topdown/json_test.go | 10 ++++++++++ 2 files changed, 16 insertions(+) diff --git a/topdown/json.go b/topdown/json.go index 09a0ea6a93..d1d8897e4d 100644 --- a/topdown/json.go +++ b/topdown/json.go @@ -203,6 +203,12 @@ func pathsToObject(paths []ast.Ref) ast.Object { node := root var done bool + // If the path is an empty JSON path, skip all further processing. + if len(path) == 0 { + done = true + } + + // Otherwise, we should have 1+ path segments to work with. for i := 0; i < len(path)-1 && !done; i++ { k := path[i] diff --git a/topdown/json_test.go b/topdown/json_test.go index 53d114e4ae..f1056f0c98 100644 --- a/topdown/json_test.go +++ b/topdown/json_test.go @@ -16,6 +16,11 @@ func TestFiltersToObject(t *testing.T) { filters []string expected string }{ + { + note: "empty path", + filters: []string{`""`}, + expected: `{}`, + }, { note: "base", filters: []string{`"a/b/c"`}, @@ -81,6 +86,11 @@ func TestFiltersToObject(t *testing.T) { filters: []string{`"a/~0b~1c/d~1~0"`}, expected: `{"a": {"~b/c": {"d/~": null}}}`, }, + { + note: "empty strings mixed with normal paths", + filters: []string{`"a/b/c"`, `""`, `"a/b/d"`, `"a/e/f"`, `""`}, + expected: `{"a": {"b": {"c": null, "d": null}, "e": {"f": null}}}`, + }, } for _, tc := range cases {