//go:build linux package server import ( "fmt" "os" "os/exec" "path/filepath" "slices" "strconv" "syscall" "testing" "time" "github.com/Autumn-27/artex/agent" ) // TestSelectTaskProcsKeepsOtherTasks checks the task scoping of the local kill // switch on a fixed process table: every task runs as the executor uid, and // pausing task 1 must select task 1's processes only, never task 10's, a // process the server did not start, or a shared process such as the browser. func TestSelectTaskProcsKeepsOtherTasks(t *testing.T) { exe := []int{10001, 10001, 10001, 10001} root := []int{0, 0, 0, 0} procs := []procEntry{ {pid: 100, ppid: 1, pgrp: 100, stat: "S", uids: root, cwd: "/data"}, // the server {pid: 200, ppid: 100, pgrp: 200, stat: "S", uids: exe, cwd: "/data/tasks/1/main"}, {pid: 201, ppid: 200, pgrp: 200, stat: "S", uids: exe, cwd: "/tmp"}, // task 1 child that left the directory {pid: 202, ppid: 100, pgrp: 202, stat: "S", uids: exe, cwd: "/", task: "1"}, // task 1 daemon: setsid, reparented, cd / {pid: 203, ppid: 200, pgrp: 200, stat: "Z", uids: exe, cwd: "/data/tasks/1/main"}, // zombie {pid: 204, ppid: 100, pgrp: 204, stat: "S", uids: root, cwd: "/data/tasks/1/main"}, // server identity {pid: 300, ppid: 100, pgrp: 300, stat: "S", uids: exe, cwd: "/data/tasks/10/main"}, {pid: 301, ppid: 300, pgrp: 300, stat: "S", uids: exe, cwd: "/data/tasks/1/i4"}, // task 10 child inside task 1's directory {pid: 302, ppid: 100, pgrp: 200, stat: "S", uids: exe, cwd: "/data/tasks/10/i2", task: "10"}, // task 10 process in task 1's group {pid: 303, ppid: 100, pgrp: 303, stat: "S", uids: exe, cwd: "/data/tasks/1/main", task: "10"}, // task 10 daemon inside task 1's directory {pid: 400, ppid: 1, pgrp: 400, stat: "S", uids: exe, cwd: "/data/tasks/1/main"}, // not started by the server {pid: 401, ppid: 1, pgrp: 401, stat: "S", uids: exe, cwd: "/tmp"}, {pid: 500, ppid: 100, pgrp: 500, stat: "S", uids: exe, cwd: "/data"}, // shared browser } priv := ExecPrivilege{Enabled: true, UID: 10001, GID: 10001} cases := []struct { name string taskDir string priv ExecPrivilege pids, grps []int }{ {"task1_executor", "/data/tasks/1", priv, []int{200, 201, 202}, []int{202}}, {"task1_server_identity", "/data/tasks/1", ExecPrivilege{}, []int{200, 201, 202, 204}, []int{202, 204}}, {"task10_executor", "/data/tasks/10", priv, []int{300, 301, 302, 303}, []int{300, 303}}, {"no_task_dir", "", priv, nil, nil}, } for _, tc := range cases { t.Run(tc.name, func(t *testing.T) { pids, grps := selectTaskProcs(procs, 100, 100, tc.taskDir, tc.priv) slices.Sort(pids) slices.Sort(grps) if !slices.Equal(pids, tc.pids) || !slices.Equal(grps, tc.grps) { t.Fatalf("selectTaskProcs(%q) = pids %v groups %v, want pids %v groups %v", tc.taskDir, pids, grps, tc.pids, tc.grps) } }) } } // scopeFixture runs real processes for two tasks (1 and 10) and a neutral one // under a data directory, as the engine's agent runs would. type scopeFixture struct { dataDir string own []int // task 1 others []int // task 10 and the neutral process } func startScopeFixture(t *testing.T) *scopeFixture { t.Helper() enableLocalKillSubreaper() // as NewEngine does: escaped daemons stay our descendants f := &scopeFixture{dataDir: t.TempDir()} dirA := filepath.Join(f.dataDir, "tasks", "1", "main") dirB := filepath.Join(f.dataDir, "tasks", "10", "main") neutral := t.TempDir() for _, d := range []string{dirA, dirB} { if err := os.MkdirAll(d, 0o755); err != nil { t.Fatal(err) } } var all []int t.Cleanup(func() { for _, pid := range all { _ = syscall.Kill(pid, syscall.SIGKILL) } }) start := func(dir, task, script string) int { cmd := exec.Command("sh", "-c", script) cmd.Dir = dir cmd.Env = os.Environ() if task != "" { cmd.Env = append(cmd.Env, agent.ExecTaskEnv+"="+task) } cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true} if err := cmd.Start(); err != nil { t.Fatal(err) } all = append(all, cmd.Process.Pid) go func() { _ = cmd.Wait() }() return cmd.Process.Pid } // startDaemon runs script, which writes the pid of a background process to a // file and exits, and returns that pid. startDaemon := func(dir, task, script string) int { pidFile := filepath.Join(t.TempDir(), "pid") start(dir, task, fmt.Sprintf(script, pidFile)) pid := waitForPIDs(t, pidFile, 1, 5*time.Second)[0] all = append(all, pid) return pid } // Task 1: a command in its run directory, a shell that left it with its child, // and a setsid daemon that left it after its parent exited. f.own = append(f.own, start(dirA, "", "exec sleep 300")) pidFile := filepath.Join(t.TempDir(), "pid") f.own = append(f.own, start(dirA, "1", fmt.Sprintf("cd /; sleep 300 & echo $! > %q; wait", pidFile))) f.own = append(f.own, waitForPIDs(t, pidFile, 1, 5*time.Second)[0]) f.own = append(f.own, startDaemon(dirA, "1", "cd /; setsid sleep 300 /dev/null 2>&1 & echo $! > %q")) // Task 10: a command in its run directory, one that moved into task 1's run // directory, and a daemon there. The neutral process stands for a process of // the server that belongs to no task (the shared browser, a chat session). f.others = append(f.others, start(dirB, "10", "exec sleep 300")) f.others = append(f.others, start(dirB, "10", fmt.Sprintf("cd %q; exec sleep 300", dirA))) f.others = append(f.others, startDaemon(dirB, "10", "cd "+strconv.Quote(dirA)+"; setsid sleep 300 /dev/null 2>&1 & echo $! > %q")) f.others = append(f.others, start(neutral, "", "exec sleep 300")) time.Sleep(100 * time.Millisecond) // let the shells reach their cd and exec return f } // TestFindLocalTaskPIDsSelectsOnlyItsTask runs real processes for two tasks and // a neutral process and checks that the scan for task 1 finds all of task 1's // processes and none of the others, with the privilege drop off and on. func TestFindLocalTaskPIDsSelectsOnlyItsTask(t *testing.T) { for _, tc := range []struct { name string priv func(t *testing.T) ExecPrivilege }{ {"server_identity", func(*testing.T) ExecPrivilege { return ExecPrivilege{} }}, {"executor_uid", func(t *testing.T) ExecPrivilege { if os.Getuid() == 0 { t.Skip("needs a non-root uid to stand for the executor uid; TestSelectTaskProcsKeepsOtherTasks covers the uid filter") } return ExecPrivilege{Enabled: true, UID: uint32(os.Getuid()), GID: uint32(os.Getgid())} }}, } { t.Run(tc.name, func(t *testing.T) { priv := tc.priv(t) f := startScopeFixture(t) got := findLocalTaskPIDs(filepath.Join(f.dataDir, "tasks", "1"), priv) for _, pid := range f.own { if !slices.Contains(got, pid) { t.Errorf("task 1 process %d not selected (selected %v)", pid, got) } } for _, pid := range f.others { if slices.Contains(got, pid) { t.Errorf("process %d of another task or of no task selected for task 1 (selected %v)", pid, got) } } }) } } // TestEnginePauseAndDeleteKillOnlyTheirTask pauses (and, separately, starts the // deletion of) task 1 through the engine and checks that task 1's processes die // while task 10's processes and the neutral process keep running. func TestEnginePauseAndDeleteKillOnlyTheirTask(t *testing.T) { for _, tc := range []struct { name string stop func(e *Engine) }{ {"pause", func(e *Engine) { e.Pause("1", agent.AbortPausedByUser) }}, {"delete", func(e *Engine) { e.BeginDelete("1") }}, } { t.Run(tc.name, func(t *testing.T) { f := startScopeFixture(t) e := NewEngine(nil) e.SetKillSwitchConfig(f.dataDir, ExecPrivilege{}) tc.stop(e) assertAllPIDsDeadWithin(t, f.own, 5*time.Second) for _, pid := range f.others { if !pidAlive(pid) { t.Errorf("process %d of another task or of no task was killed by the %s of task 1", pid, tc.name) } } }) } }