From 1375813e8aebb7a18ab9e068741168311b094070 Mon Sep 17 00:00:00 2001 From: Masaaki Goshima Date: Wed, 18 Dec 2024 10:45:26 +0900 Subject: [PATCH] fix invalid path (#598) --- path.go | 11 +++++++++++ path_test.go | 27 +++++++++++++++++++++++++++ 2 files changed, 38 insertions(+) diff --git a/path.go b/path.go index fcb56815..aaa3477a 100644 --- a/path.go +++ b/path.go @@ -83,6 +83,9 @@ end: } func parsePathDot(b *PathBuilder, buf []rune, cursor int) (*PathBuilder, []rune, int, error) { + if b.root == nil || b.node == nil { + return nil, nil, 0, fmt.Errorf("required '$' character at first: %w", ErrInvalidPathString) + } length := len(buf) if cursor+1 < length && buf[cursor+1] == '.' { b, buf, c, err := parsePathRecursive(b, buf, cursor) @@ -119,6 +122,10 @@ end: } func parseQuotedKey(b *PathBuilder, buf []rune, cursor int) (*PathBuilder, []rune, int, error) { + if b.root == nil || b.node == nil { + return nil, nil, 0, fmt.Errorf("required '$' character at first: %w", ErrInvalidPathString) + } + cursor++ // skip single quote start := cursor length := len(buf) @@ -156,6 +163,10 @@ end: } func parsePathIndex(b *PathBuilder, buf []rune, cursor int) (*PathBuilder, []rune, int, error) { + if b.root == nil || b.node == nil { + return nil, nil, 0, fmt.Errorf("required '$' character at first: %w", ErrInvalidPathString) + } + length := len(buf) cursor++ // skip '[' character if length <= cursor { diff --git a/path_test.go b/path_test.go index 84e6cc0d..5b62d26f 100644 --- a/path_test.go +++ b/path_test.go @@ -603,6 +603,33 @@ building: } } +func TestInvalidPath(t *testing.T) { + tests := []struct { + name string + path string + }{ + { + name: "missing root with dot", + path: ".foo", + }, + { + name: "missing root with index", + path: "foo[0]", + }, + { + name: "missing root with recursive", + path: "..foo", + }, + } + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + if _, err := yaml.PathString(test.path); err == nil { + t.Fatal("expected error") + } + }) + } +} + func ExamplePath_AnnotateSource() { yml := ` a: 1