Skip to content

Commit 27e53e2

Browse files
Fix potential panic on bare ${var} reference and add early exit in closestMatch
Guard against out-of-bounds access when the suggest function receives a single-segment path like "var" (without a variable name). Also short-circuit closestMatch on exact match (distance 0) to skip unnecessary iterations. Co-authored-by: Isaac
1 parent 9360685 commit 27e53e2

2 files changed

Lines changed: 21 additions & 1 deletion

File tree

bundle/config/mutator/suggest.go

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,9 @@ func closestMatch(key string, candidates []string) (string, int) {
3030
if d < bestDist {
3131
bestDist = d
3232
best = c
33+
if d == 0 {
34+
break
35+
}
3336
}
3437
}
3538
if bestDist > threshold {
@@ -144,7 +147,8 @@ func (m *resolveVariableReferences) suggest(
144147

145148
// Handle var.X → variables.X.value rewriting for internal lookup.
146149
// Also detect typos in the "var" prefix itself (e.g., "vr", "va").
147-
isVar := path.HasPrefix(varPath)
150+
// Require at least 2 segments (e.g., "var.X") to avoid a panic on bare "var".
151+
isVar := len(path) >= 2 && path.HasPrefix(varPath)
148152
varPrefixCorrected := false
149153
if !isVar && len(path) >= 2 {
150154
if c, _ := closestMatch(path[0].Key(), []string{"var"}); c != "" {

bundle/config/mutator/suggest_test.go

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -238,6 +238,22 @@ func TestSuggestVarPrefixTypo(t *testing.T) {
238238
assert.Equal(t, "", m.suggest("vr.nonexistent", normalized))
239239
}
240240

241+
func TestSuggestBareVarDoesNotPanic(t *testing.T) {
242+
normalized := dyn.V(map[string]dyn.Value{
243+
"variables": dyn.V(map[string]dyn.Value{
244+
"my_cluster_id": dyn.V(map[string]dyn.Value{
245+
"value": dyn.V("abc-123"),
246+
}),
247+
}),
248+
})
249+
250+
m := &resolveVariableReferences{
251+
prefixes: defaultPrefixes,
252+
}
253+
254+
assert.Equal(t, "", m.suggest("var", normalized))
255+
}
256+
241257
func TestSuggestNoSuggestionForCorrectPath(t *testing.T) {
242258
normalized := dyn.V(map[string]dyn.Value{
243259
"variables": dyn.V(map[string]dyn.Value{

0 commit comments

Comments
 (0)