diff --git a/caddyconfig/caddyfile/importargs.go b/caddyconfig/caddyfile/importargs.go index b2eb3e834..0d7428c40 100644 --- a/caddyconfig/caddyfile/importargs.go +++ b/caddyconfig/caddyfile/importargs.go @@ -112,7 +112,7 @@ func makeArgsReplacer(args []string) *caddy.Replacer { "Placeholder {args." + matches[1] + "} has an invalid index") return nil, false } - if value >= len(args) { + if value < 0 || value >= len(args) { caddy.Log().Named("caddyfile").Warn( "Placeholder {args." + matches[1] + "} index is out of bounds, only " + strconv.Itoa(len(args)) + " argument(s) exist") return nil, false @@ -140,7 +140,7 @@ func makeArgsReplacer(args []string) *caddy.Replacer { "Placeholder {args[" + matches[1] + "]} has an invalid index") return nil, false } - if value >= len(args) { + if value < 0 || value >= len(args) { caddy.Log().Named("caddyfile").Warn( "Placeholder {args[" + matches[1] + "]} index is out of bounds, only " + strconv.Itoa(len(args)) + " argument(s) exist") return nil, false diff --git a/caddyconfig/caddyfile/parse_test.go b/caddyconfig/caddyfile/parse_test.go index 6abfd6b09..d0f0119a8 100644 --- a/caddyconfig/caddyfile/parse_test.go +++ b/caddyconfig/caddyfile/parse_test.go @@ -809,6 +809,46 @@ func TestImportReplacementInJSONWithBrace(t *testing.T) { } } +func TestArgsReplacerOutOfBoundsIndex(t *testing.T) { + for i, test := range []struct { + args []string + input string + expect string + }{ + { + args: []string{"a", "b"}, + input: "{args[1]}", + expect: "b", + }, + { + args: []string{"a", "b"}, + input: "{args[2]}", + expect: "{args[2]}", + }, + { + args: []string{"a", "b"}, + input: "{args[-1]}", + expect: "{args[-1]}", + }, + { + args: []string{"a", "b"}, + input: "{args.-1}", + expect: "{args.-1}", + }, + { + args: nil, + input: "{args[-1]}", + expect: "{args[-1]}", + }, + } { + repl := makeArgsReplacer(test.args) + actual := repl.ReplaceKnown(test.input, "") + if actual != test.expect { + t.Errorf("Test %d: Expected: '%s' but got '%s'", i, test.expect, actual) + } + } +} + func TestSnippets(t *testing.T) { p := testParser(` (common) {