Skip to content

Commit 7779d03

Browse files
committed
test: require path boundary in cmdline dir matching
1 parent 2945399 commit 7779d03

1 file changed

Lines changed: 58 additions & 5 deletions

File tree

lib/instances/manager_test.go

Lines changed: 58 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -306,22 +306,75 @@ func killOrphanedProcessesUnderDir(t *testing.T, dataDir string) {
306306

307307
// cmdlineReferencesDir reports whether any argv token is, or lives under, dir.
308308
func cmdlineReferencesDir(argv []string, dir string) bool {
309+
dir = filepath.Clean(dir)
309310
for _, tok := range argv {
310311
tok = strings.TrimSpace(tok)
311312
if tok == "" {
312313
continue
313314
}
314315
// Tokens may embed the path inside larger strings (e.g. qemu's
315-
// "socket,...,path=/tmp/.../qmp.sock"), so a substring check on the
316-
// cleaned prefix is the robust match. The prefix is a unique per-test
317-
// t.TempDir() root, so substring matching cannot collide across tests.
318-
if strings.Contains(tok, dir) {
319-
return true
316+
// "socket,...,path=/tmp/.../qmp.sock"), so scan for occurrences and
317+
// require a path boundary at the end of the matched directory.
318+
for start := 0; start < len(tok); {
319+
idx := strings.Index(tok[start:], dir)
320+
if idx < 0 {
321+
break
322+
}
323+
idx += start
324+
end := idx + len(dir)
325+
if end == len(tok) || (end < len(tok) && os.IsPathSeparator(tok[end])) {
326+
return true
327+
}
328+
start = idx + 1
320329
}
321330
}
322331
return false
323332
}
324333

334+
func TestCmdlineReferencesDir(t *testing.T) {
335+
t.Parallel()
336+
337+
dir := filepath.Clean(filepath.Join(string(os.PathSeparator), "tmp", "hypeman", "001"))
338+
339+
tests := []struct {
340+
name string
341+
argv []string
342+
want bool
343+
}{
344+
{
345+
name: "exact token",
346+
argv: []string{"qemu-system-x86_64", dir},
347+
want: true,
348+
},
349+
{
350+
name: "embedded under dir",
351+
argv: []string{
352+
"cloud-hypervisor",
353+
"--api-sock",
354+
"socket,id=qmp,path=" + filepath.Join(dir, "instances", "vm-1", "qmp.sock"),
355+
},
356+
want: true,
357+
},
358+
{
359+
name: "sibling dir with prefix is not a match",
360+
argv: []string{
361+
"cloud-hypervisor",
362+
"--api-sock",
363+
"socket,id=qmp,path=" + filepath.Join(string(os.PathSeparator), "tmp", "hypeman", "0010", "instances", "vm-1", "qmp.sock"),
364+
},
365+
want: false,
366+
},
367+
}
368+
369+
for _, tt := range tests {
370+
tt := tt
371+
t.Run(tt.name, func(t *testing.T) {
372+
t.Parallel()
373+
assert.Equal(t, tt.want, cmdlineReferencesDir(tt.argv, dir))
374+
})
375+
}
376+
}
377+
325378
func isGuestProcess(exe string) bool {
326379
switch {
327380
case exe == "firecracker":

0 commit comments

Comments
 (0)