oficina / equipo Public

fix: prevent detached runner helpers and retain test ancestry

codex agent, operated by paul@keymail.dev pushed by claude agent, operated by paul@keymail.dev 842b9b8be5cecb2569f13f2e79e387837d67b6f0 parent 1f08086
9 files changed, +258 −11
  • internal/equipotest/residual_process_test.go +71 −0
  • internal/equipotest/runner_flow_test.go +2 −0
  • internal/runner/checks/residual_environment_test.go +36 −0
  • internal/runner/checks/sandbox.go +33 −3
  • internal/runner/forge/git.go +3 −3
  • internal/runner/residual_helpers_test.go +93 −0
  • internal/runner/workspace/residual_git_test.go +15 −0
  • internal/runner/workspace/workspace.go +4 −4
  • internal/runner/workspace/workspace_test.go +1 −1
diff --git a/internal/equipotest/residual_process_test.go b/internal/equipotest/residual_process_test.go
new file mode 100644
index 00000000..fea19e7e
--- /dev/null
+++ b/internal/equipotest/residual_process_test.go
@@ -0,0 +1,71 @@
+package equipotest
+
+import (
+ "golang.org/x/sys/unix"
+ "os"
+ "os/exec"
+ "path/filepath"
+ "strconv"
+ "strings"
+ "testing"
+ "time"
+)
+
+func flowSubreaper(t *testing.T) {
+ t.Helper()
+ executionMust(t, unix.Prctl(unix.PR_SET_CHILD_SUBREAPER, 1, 0, 0, 0))
+}
+
+func TestFlowOrphanReparentsToTest(t *testing.T) {
+ if privateProcTest(t) {
+ return
+ }
+ flowSubreaper(t)
+ cmd := exec.Command("/bin/sh", "-c", "sleep 30 >/dev/null 2>&1 & echo $!")
+ raw, err := cmd.Output()
+ executionMust(t, err)
+ pid, err := strconv.Atoi(strings.TrimSpace(string(raw)))
+ executionMust(t, err)
+ fd, err := unix.PidfdOpen(pid, 0)
+ executionMust(t, err)
+ defer unix.Close(fd)
+ defer func() { _ = unix.PidfdSendSignal(fd, unix.SIGKILL, nil, 0); _, _ = unix.Wait4(pid, nil, 0, nil) }()
+ for range 100 {
+ status, err := os.ReadFile(filepath.Join("/proc", strconv.Itoa(pid), "status"))
+ executionMust(t, err)
+ if strings.Contains(string(status), "PPid:\t"+strconv.Itoa(os.Getpid())+"\n") {
+ return
+ }
+ time.Sleep(10 * time.Millisecond)
+ }
+ t.Fatal("detached helper did not reparent to test process")
+}
+
+func dumpFlowProcesses(t *testing.T) {
+ t.Helper()
+ entries, err := os.ReadDir("/proc")
+ if err != nil {
+ t.Log("process inventory:", err)
+ return
+ }
+ for _, entry := range entries {
+ pid, err := strconv.Atoi(entry.Name())
+ if err != nil {
+ continue
+ }
+ root := filepath.Join("/proc", entry.Name())
+ comm, _ := os.ReadFile(filepath.Join(root, "comm"))
+ status, err := os.ReadFile(filepath.Join(root, "status"))
+ if os.IsNotExist(err) {
+ continue
+ }
+ parent := "unknown"
+ for _, line := range strings.Split(string(status), "\n") {
+ if strings.HasPrefix(line, "PPid:") {
+ parent = strings.TrimSpace(strings.TrimPrefix(line, "PPid:"))
+ }
+ }
+ cwd, cwdErr := os.Readlink(filepath.Join(root, "cwd"))
+ t.Logf("process pid=%d comm=%q ppid=%s cwd=%q cwd_error=%v", pid, strings.TrimSpace(string(comm)), parent, cwd, cwdErr)
+ }
+}
diff --git a/internal/equipotest/runner_flow_test.go b/internal/equipotest/runner_flow_test.go
index 62cd2cce..3a2cd24c 100644
--- a/internal/equipotest/runner_flow_test.go
+++ b/internal/equipotest/runner_flow_test.go
@@ -27,6 +27,7 @@ func TestRunnerEndToEnd(t *testing.T) {
if privateProcTest(t) {
return
}
+ flowSubreaper(t)
ctx := context.Background()
root, err := os.MkdirTemp(os.Getenv("TMPDIR"), "e15-")
@@ -201,6 +202,7 @@ func TestRunnerEndToEnd(t *testing.T) {
var phase, detail string
_ = debugDB.QueryRow("SELECT json_extract(body,'$.FailurePhase'),json_extract(body,'$.FailureDetail') FROM journal_supervisor WHERE kind='attempt' ORDER BY rowid DESC LIMIT 1").Scan(&phase, &detail)
t.Log("failure phase", phase, detail)
+ dumpFlowProcesses(t)
diagnostic, _ := os.ReadFile(filepath.Join(root, "failure"))
t.Fatalf("%s: %v bridge=%s", step, err, diagnostic)
}
diff --git a/internal/runner/checks/residual_environment_test.go b/internal/runner/checks/residual_environment_test.go
new file mode 100644
index 00000000..dd51d006
--- /dev/null
+++ b/internal/runner/checks/residual_environment_test.go
@@ -0,0 +1,36 @@
+package checks
+
+import (
+ "amadan.net/oficina/equipo/internal/runner/paseo"
+ "bytes"
+ "context"
+ "os"
+ "os/exec"
+ "path/filepath"
+ "testing"
+)
+
+func TestSandboxDisablesDetachedHelpers(t *testing.T) {
+ root := t.TempDir()
+ work := filepath.Join(root, "work")
+ must(t, os.Mkdir(work, 0700))
+ binary, err := exec.LookPath("codex")
+ must(t, err)
+ s, err := NewCodexSandbox(context.Background(), testSandboxConfig(t, binary, root))
+ must(t, err)
+ policy := paseo.ReadPolicy{ConfigHash: "policy", DeniedPaths: []string{filepath.Join(root, "secret")}}
+ for _, tc := range []struct{ name, script string }{
+ {"telemetry", `test "$GOTELEMETRY" = off && test "$(go env GOTELEMETRY)" = off`},
+ {"maintenance", `test "$(git config --get maintenance.auto)" = false`},
+ {"gc", `test "$(git config --get gc.autoDetach)" = false`},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ var out, stderr bytes.Buffer
+ code, err := s.Run(context.Background(), Command{Argv: []string{"/bin/sh", "-c", tc.script}, Dir: ".", TimeoutSeconds: 10}, work, policy, &out, &stderr)
+ must(t, err)
+ if code != 0 {
+ t.Fatalf("detached helper guard missing: code=%d out=%s err=%s", code, &out, &stderr)
+ }
+ })
+ }
+}
diff --git a/internal/runner/checks/sandbox.go b/internal/runner/checks/sandbox.go
index e1279117..76a82580 100644
--- a/internal/runner/checks/sandbox.go
+++ b/internal/runner/checks/sandbox.go
@@ -76,8 +76,17 @@ func NewCodexSandbox(ctx context.Context, cfg SandboxConfig) (*CodexSandbox, err
if err != nil || goBinary != filepath.Join(goRoot, "bin/go") {
return nil, paseo.ErrContract
}
+ probe, err := os.MkdirTemp(cfg.ScratchRoot, "go-probe-")
+ if err != nil {
+ return nil, err
+ }
+ defer os.RemoveAll(probe)
+ xdg, err := telemetryOffConfig(probe)
+ if err != nil {
+ return nil, err
+ }
cmd = exec.CommandContext(ctx, goBinary, "version")
- cmd.Env = []string{"PATH=/usr/bin:/bin", "GOROOT=" + goRoot, "GOTOOLCHAIN=local", "GOENV=off"}
+ cmd.Env = []string{"PATH=/usr/bin:/bin", "GOROOT=" + goRoot, "GOTOOLCHAIN=local", "GOENV=off", "GOTELEMETRY=off", "XDG_CONFIG_HOME=" + xdg}
b, err = cmd.Output()
if err != nil || strings.TrimSpace(string(b)) != "go version "+GoVersion+" "+runtime.GOOS+"/"+runtime.GOARCH {
return nil, paseo.ErrContract
@@ -135,6 +144,10 @@ func (s *CodexSandbox) Run(ctx context.Context, c Command, work string, policy p
defer os.RemoveAll(control)
// A fresh config home prevents user/project profiles and login state entering the command.
cfgHome := filepath.Join(control, "codex")
+ xdg, err := telemetryOffConfig(control)
+ if err != nil {
+ return -1, err
+ }
temp, err := os.MkdirTemp(work, ".equipo-check-")
if err != nil {
return -1, err
@@ -150,7 +163,7 @@ func (s *CodexSandbox) Run(ctx context.Context, c Command, work string, policy p
if err = os.Mkdir(cfgHome, 0700); err != nil {
return -1, err
}
- roots := map[string]string{":minimal": "read", s.binary: "read", s.goRoot: "read", work: "write", filepath.Join(s.home, ".cache/go-build"): "deny", filepath.Join(s.home, "go/pkg/mod"): "read"}
+ roots := map[string]string{xdg: "read", ":minimal": "read", s.binary: "read", s.goRoot: "read", work: "write", filepath.Join(s.home, ".cache/go-build"): "deny", filepath.Join(s.home, "go/pkg/mod"): "read"}
for _, p := range []string{s.goRoot, filepath.Join(s.home, "go/pkg/mod"), filepath.Join(s.home, ".cache/go-build")} {
r, err := canonicalPath(p)
if err != nil {
@@ -192,7 +205,12 @@ func (s *CodexSandbox) Run(ctx context.Context, c Command, work string, policy p
defer cancel()
cmd := exec.CommandContext(ctx, s.binary, args...)
cmd.Dir = control
- cmd.Env = []string{"PATH=" + filepath.Join(s.goRoot, "bin") + ":/usr/bin:/bin", "HOME=" + s.home, "CODEX_HOME=" + cfgHome, "TMPDIR=" + temp, "GOCACHE=" + cache, "GOTMPDIR=" + goTemp, "GOROOT=" + s.goRoot, "CGO_ENABLED=0", "GOTOOLCHAIN=local", "GOWORK=off", "GOENV=off", "GOFLAGS=", "GOPROXY=off", "GOSUMDB=off", "LANG=C", "LC_ALL=C"}
+ cmd.Env = []string{"PATH=" + filepath.Join(s.goRoot, "bin") + ":/usr/bin:/bin", "HOME=" + s.home, "CODEX_HOME=" + cfgHome, "TMPDIR=" + temp, "GOCACHE=" + cache, "GOTMPDIR=" + goTemp, "GOROOT=" + s.goRoot, "CGO_ENABLED=0", "GOTOOLCHAIN=local", "GOWORK=off", "GOENV=off", "GOFLAGS=", "GOTELEMETRY=off", "XDG_CONFIG_HOME=" + xdg, "GOPROXY=off", "GOSUMDB=off", "LANG=C", "LC_ALL=C"}
+ for key, value := range workspace.GitEnvironment() {
+ if strings.HasPrefix(key, "GIT_") {
+ cmd.Env = append(cmd.Env, key+"="+value)
+ }
+ }
marker, track := runnerproto.ProcessOwnership(ctx)
begin, end := runnerproto.CommandOwnership(ctx)
command := rand.Text()
@@ -251,3 +269,15 @@ func (s *CodexSandbox) Run(ctx context.Context, c Command, work string, policy p
}
return -1, paseo.ErrContract
}
+
+func telemetryOffConfig(root string) (string, error) {
+ xdg := filepath.Join(root, "xdg")
+ dir := filepath.Join(xdg, "go", "telemetry")
+ if err := os.MkdirAll(dir, 0700); err != nil {
+ return "", err
+ }
+ if err := os.WriteFile(filepath.Join(dir, "mode"), []byte("off\n"), 0600); err != nil {
+ return "", err
+ }
+ return xdg, nil
+}
diff --git a/internal/runner/forge/git.go b/internal/runner/forge/git.go
index 572dac9d..9626586c 100644
--- a/internal/runner/forge/git.go
+++ b/internal/runner/forge/git.go
@@ -27,9 +27,9 @@ func (p *Publisher) git(ctx context.Context, dir string, cred *Credential, args
env["HOME"] = "/nonexistent"
env["GIT_CEILING_DIRECTORIES"] = filepath.Dir(dir)
if cred != nil && p.localRemote == nil {
- env["GIT_CONFIG_COUNT"] = "8"
- env["GIT_CONFIG_KEY_7"] = "http.extraHeader"
- env["GIT_CONFIG_VALUE_7"] = "Authorization: Bearer " + cred.Bearer
+ env["GIT_CONFIG_COUNT"] = "10"
+ env["GIT_CONFIG_KEY_9"] = "http.extraHeader"
+ env["GIT_CONFIG_VALUE_9"] = "Authorization: Bearer " + cred.Bearer
}
for k, v := range env {
cmd.Env = append(cmd.Env, k+"="+v)
diff --git a/internal/runner/residual_helpers_test.go b/internal/runner/residual_helpers_test.go
new file mode 100644
index 00000000..0ce41b71
--- /dev/null
+++ b/internal/runner/residual_helpers_test.go
@@ -0,0 +1,93 @@
+package runner
+
+import (
+ "amadan.net/oficina/equipo/internal/runner/checks"
+ "amadan.net/oficina/equipo/internal/runner/paseo"
+ "amadan.net/oficina/equipo/internal/runner/workspace"
+ "amadan.net/oficina/equipo/internal/runnerproto"
+ "bytes"
+ "context"
+ "os"
+ "os/exec"
+ "path/filepath"
+ "strconv"
+ "testing"
+ "time"
+)
+
+func TestRunnerCommandsLeaveNoDetachedHelpers(t *testing.T) {
+ if privateProcTest(t) {
+ return
+ }
+ ctx := context.Background()
+ p, o := realInspector(t)
+ o.LocalOnly = true
+ root := t.TempDir()
+ state := filepath.Join(root, "state")
+ wfMust(t, os.Mkdir(state, 0700))
+ protected := workspace.SecurityPaths{RunnerState: state, RunnerConfig: state + "/config", Journal: state + "/journal", Bearer: state + "/bearer", Cleanup: state + "/cleanup", ForgeCredential: state + "/forge", PaseoHome: state + "/paseo", ProviderHomes: []string{state + "/provider"}, SSH: state + "/ssh"}
+ binary, err := exec.LookPath("codex")
+ wfMust(t, err)
+ goBinary, err := exec.LookPath("go")
+ wfMust(t, err)
+ goBinary, err = filepath.EvalSymlinks(goBinary)
+ wfMust(t, err)
+ sandbox, err := checks.NewCodexSandbox(ctx, checks.SandboxConfig{Binary: binary, ScratchRoot: root, GoRoot: filepath.Dir(filepath.Dir(goBinary)), GoBinary: goBinary, Protected: protected})
+ wfMust(t, err)
+ work := o.Workspace.Path
+ wfMust(t, os.WriteFile(filepath.Join(work, "go.mod"), []byte("module fixture\n\ngo 1.26.0\n"), 0600))
+ wfMust(t, os.WriteFile(filepath.Join(work, "helper_test.go"), []byte("package fixture\nimport \"testing\"\nfunc TestFixture(t *testing.T){}\n"), 0600))
+ baseline := map[int]bool{}
+ entries, err := os.ReadDir("/proc")
+ wfMust(t, err)
+ for _, entry := range entries {
+ pid, _ := strconv.Atoi(entry.Name())
+ baseline[pid] = true
+ }
+ wfMust(t, p.Track(ctx, o))
+ owned := checks.WithProcessOwnership(ctx, o.Marker, func(ctx context.Context, pid int) error { return p.TrackPID(ctx, o, pid) })
+ owned = runnerproto.WithCommandOwnership(owned, func(ctx context.Context, pid int, key string) error { return p.BeginCommand(ctx, o, pid, key) }, func(ctx context.Context, key string) error { return p.EndCommand(ctx, o, key) })
+ policy := paseo.ReadPolicy{ConfigHash: "policy", DeniedPaths: []string{state}}
+ var out, stderr bytes.Buffer
+ code, err := sandbox.Run(owned, checks.Command{Argv: []string{"/bin/sh", "-c", `test "$GOTELEMETRY" = off && test "$(go env GOTELEMETRY)" = off && go test -count=1 ./...`}, Dir: ".", TimeoutSeconds: 90}, work, policy, &out, &stderr)
+ wfMust(t, err)
+ if code != 0 {
+ t.Fatalf("sandboxed go test failed: %d %s %s", code, &out, &stderr)
+ }
+ for _, args := range [][]string{{"init", "--template=", "-b", "main"}, {"add", "."}, {"-c", "user.name=fixture", "-c", "user.email=fixture@example.test", "-c", "gc.auto=1", "commit", "-m", "fixture"}} {
+ cmd := exec.Command("/usr/bin/git", args...)
+ cmd.Dir = work
+ for key, value := range workspace.GitEnvironment() {
+ cmd.Env = append(cmd.Env, key+"="+value)
+ }
+ cmd.Env = append(cmd.Env, "HOME=/nonexistent", "EQUIPO_ATTEMPT_MARKER="+o.Marker)
+ output, err := cmd.CombinedOutput()
+ if err != nil {
+ t.Fatalf("git: %v %s", err, output)
+ }
+ }
+ for range 10 {
+ inv, err := p.Remaining(ctx, o)
+ wfMust(t, err)
+ if !inv.CoverageKnown || len(inv.Processes) != 0 {
+ t.Fatalf("post-Track helper survived: %+v", inv)
+ }
+ entries, err := os.ReadDir("/proc")
+ wfMust(t, err)
+ for _, entry := range entries {
+ pid, err := strconv.Atoi(entry.Name())
+ if err != nil || baseline[pid] {
+ continue
+ }
+ e, err := p.entry(pid)
+ if os.IsNotExist(err) {
+ continue
+ }
+ wfMust(t, err)
+ if !e.dead {
+ t.Fatalf("detached post-Track process: %+v", e)
+ }
+ }
+ time.Sleep(20 * time.Millisecond)
+ }
+}
diff --git a/internal/runner/workspace/residual_git_test.go b/internal/runner/workspace/residual_git_test.go
new file mode 100644
index 00000000..8e6d153c
--- /dev/null
+++ b/internal/runner/workspace/residual_git_test.go
@@ -0,0 +1,15 @@
+package workspace
+
+import "testing"
+
+func TestRunnerGitDisablesDetachedMaintenance(t *testing.T) {
+ f := setup(t)
+ w := f.create(t)
+ for _, key := range []string{"maintenance.auto", "gc.autoDetach"} {
+ git(t, w.Paseo.Path, "config", key, "true")
+ got, err := f.m.run(ctx, w.Paseo.Path, "config", "--get", key)
+ if err != nil || got != "false" {
+ t.Errorf("runner git permits %s: %q %v", key, got, err)
+ }
+ }
+}
diff --git a/internal/runner/workspace/workspace.go b/internal/runner/workspace/workspace.go
index 7e8a5b55..919ae384 100644
--- a/internal/runner/workspace/workspace.go
+++ b/internal/runner/workspace/workspace.go
@@ -158,7 +158,7 @@ func allowed(p string, policy paseo.ReadPolicy) bool {
return true
}
func safeEnv() map[string]string {
- return map[string]string{"PATH": "/usr/bin:/bin", "LANG": "C", "GIT_CONFIG_NOSYSTEM": "1", "GIT_CONFIG_SYSTEM": "/dev/null", "GIT_CONFIG_GLOBAL": "/dev/null", "GIT_TERMINAL_PROMPT": "0", "GIT_NO_REPLACE_OBJECTS": "1", "GIT_ATTR_NOSYSTEM": "1", "GIT_CONFIG_COUNT": "7", "GIT_CONFIG_KEY_0": "core.hooksPath", "GIT_CONFIG_VALUE_0": "/dev/null", "GIT_CONFIG_KEY_1": "credential.helper", "GIT_CONFIG_VALUE_1": "", "GIT_CONFIG_KEY_2": "core.fsmonitor", "GIT_CONFIG_VALUE_2": "false", "GIT_CONFIG_KEY_3": "protocol.allow", "GIT_CONFIG_VALUE_3": "never", "GIT_CONFIG_KEY_4": "core.attributesFile", "GIT_CONFIG_VALUE_4": "/dev/null", "GIT_CONFIG_KEY_5": "core.sshCommand", "GIT_CONFIG_VALUE_5": "/bin/false", "GIT_CONFIG_KEY_6": "commit.gpgSign", "GIT_CONFIG_VALUE_6": "false"}
+ return map[string]string{"PATH": "/usr/bin:/bin", "LANG": "C", "GIT_CONFIG_NOSYSTEM": "1", "GIT_CONFIG_SYSTEM": "/dev/null", "GIT_CONFIG_GLOBAL": "/dev/null", "GIT_TERMINAL_PROMPT": "0", "GIT_NO_REPLACE_OBJECTS": "1", "GIT_ATTR_NOSYSTEM": "1", "GIT_CONFIG_COUNT": "9", "GIT_CONFIG_KEY_0": "core.hooksPath", "GIT_CONFIG_VALUE_0": "/dev/null", "GIT_CONFIG_KEY_1": "credential.helper", "GIT_CONFIG_VALUE_1": "", "GIT_CONFIG_KEY_2": "core.fsmonitor", "GIT_CONFIG_VALUE_2": "false", "GIT_CONFIG_KEY_3": "protocol.allow", "GIT_CONFIG_VALUE_3": "never", "GIT_CONFIG_KEY_4": "core.attributesFile", "GIT_CONFIG_VALUE_4": "/dev/null", "GIT_CONFIG_KEY_5": "core.sshCommand", "GIT_CONFIG_VALUE_5": "/bin/false", "GIT_CONFIG_KEY_6": "commit.gpgSign", "GIT_CONFIG_VALUE_6": "false", "GIT_CONFIG_KEY_7": "maintenance.auto", "GIT_CONFIG_VALUE_7": "false", "GIT_CONFIG_KEY_8": "gc.autoDetach", "GIT_CONFIG_VALUE_8": "false"}
}
func GitEnvironment() map[string]string { return safeEnv() }
func (w Workspace) Environment() map[string]string { return GitEnvironment() }
@@ -258,9 +258,9 @@ func (m *Manager) fetch(ctx context.Context, t team.TargetBinding) (string, stri
}
env := map[string]string{}
if remote.Bearer != "" {
- env["GIT_CONFIG_COUNT"] = "8"
- env["GIT_CONFIG_KEY_7"] = "http.extraHeader"
- env["GIT_CONFIG_VALUE_7"] = "Authorization: Bearer " + remote.Bearer
+ env["GIT_CONFIG_COUNT"] = "10"
+ env["GIT_CONFIG_KEY_9"] = "http.extraHeader"
+ env["GIT_CONFIG_VALUE_9"] = "Authorization: Bearer " + remote.Bearer
}
if _, err := m.git(ctx, repo, nil, env, "-c", "protocol."+protocol+".allow=always", "-c", "http.followRedirects=false", "fetch", "--no-auto-maintenance", "--no-tags", "--no-recurse-submodules", "--", remote.URL, ref); err != nil {
return "", "", err
diff --git a/internal/runner/workspace/workspace_test.go b/internal/runner/workspace/workspace_test.go
index 5c28f3d0..00611641 100644
--- a/internal/runner/workspace/workspace_test.go
+++ b/internal/runner/workspace/workspace_test.go
@@ -496,7 +496,7 @@ os.execve('/usr/bin/git', ['/usr/bin/git'] + args, dict(os.environ))
env, _ := json.Marshal(row.Env)
if strings.Contains(args, " fetch ") {
fetches++
- if row.Env["GIT_CONFIG_VALUE_7"] != "Authorization: Bearer fetch-only-sentinel" {
+ if row.Env["GIT_CONFIG_VALUE_9"] != "Authorization: Bearer fetch-only-sentinel" {
t.Fatal("fetch missing scoped credential")
}
} else if strings.Contains(string(env), "fetch-only-sentinel") {