//go:build linux package containment import ( "bufio" "context" "encoding/json" "errors" "fmt" "os" "os/exec" "path/filepath" "testing" "time" "amadan.net/oficina/equipo/internal/runner/provider" "golang.org/x/sys/unix" ) func TestNamespaceRecoveryIdentity(t *testing.T) { m, l := fixture(t) p := launch(t, m, l, "import time; print('ready',flush=True); time.sleep(60)") if _, e := bufio.NewReader(p.Stdout()).ReadString('\n'); e != nil { t.Fatal(e) } r := record(t, m, p) fd := descriptor(t, r.HostPID) for _, tc := range []struct { name string edit func(*Record) }{ {"reused pid", func(r *Record) { r.StartTicks++ }}, {"changed manifest", func(r *Record) { r.ManifestHash += "-changed" }}, {"changed namespace", func(r *Record) { r.NamespaceID = "pid:[0]" }}, {"missing handshake", func(r *Record) { r.HostPID = 0; r.StartTicks = 0; r.NamespaceID = "" }}, {"unavailable proof", func(r *Record) { r.ManifestHash = "" }}, } { t.Run(tc.name, func(t *testing.T) { bad := r tc.edit(&bad) proof, e := m.Recover(context.Background(), bad) if e == nil || proof.Verified { t.Fatalf("uncertain identity accepted: %+v %v", proof, e) } alive(t, fd) if _, e := os.Stat(filepath.Join(m.cfg.ScratchRoot, "attempt-"+r.ID)); e != nil { t.Fatalf("unproven recovery removed scratch: %v", e) } }) } changed := r changed.BootID = "different-boot" proof, e := m.Recover(context.Background(), changed) if e != nil || !proof.Verified || proof.Exit.Code != -1 || proof.Exit.Signal != 0 { t.Fatalf("changed boot fabricated outcome: %+v %v", proof, e) } alive(t, fd) // A fresh manager reacquires only the durable, exact namespace init. fresh, e := New(m.cfg) if e != nil { t.Fatal(e) } proof, e = fresh.Recover(context.Background(), r) if e != nil || !proof.Verified || proof.Record != r { t.Fatalf("recover exact identity: %+v %v", proof, e) } exited(t, fd) } func TestNamespaceMountEscape(t *testing.T) { home, e := os.UserHomeDir() if e != nil { t.Fatal(e) } m, l := fixture(t) outsideHome := t.TempDir() if e := os.Chmod(outsideHome, 0700); e != nil { t.Fatal(e) } for _, tc := range []struct { name string edit func(*provider.Launch) }{ {"traversal", func(l *provider.Launch) { l.Workspace += "/../workspace" }}, {"outside private home", func(l *provider.Launch) { l.Binding.Home = outsideHome }}, {"broad home", func(l *provider.Launch) { l.Binding.Home = home }}, {"protected state", func(l *provider.Launch) { l.Workspace = m.cfg.ScratchRoot }}, {"parent of protected state", func(l *provider.Launch) { l.Workspace = filepath.Dir(m.cfg.ScratchRoot) }}, {"host runtime", func(l *provider.Launch) { l.Policy.Mounts = []provider.Mount{{Source: "/run", Target: "/opt/run", ReadOnly: true}} }}, {"host cgroup", func(l *provider.Launch) { l.Policy.Mounts = []provider.Mount{{Source: "/sys/fs/cgroup", Target: "/opt/cgroup", ReadOnly: true}} }}, {"writable runtime", func(l *provider.Launch) { l.Policy.Mounts = []provider.Mount{{Source: "/etc/hostname", Target: "/opt/name"}} }}, {"reserved target", func(l *provider.Launch) { l.Policy.Mounts = []provider.Mount{{Source: "/etc/hostname", Target: "/home/runner/hostname", ReadOnly: true}} }}, {"home environment traversal", func(l *provider.Launch) { l.Policy.Env = map[string]string{"CODEX_HOME": "/home/runner/../../etc"} }}, {"tmp environment traversal", func(l *provider.Launch) { l.Policy.Env = map[string]string{"CLAUDE_TMPDIR": "/tmp/../workspace"} }}, {"environment", func(l *provider.Launch) { l.Policy.Env = map[string]string{"LD_PRELOAD": "/workspace/a.so"} }}, } { t.Run(tc.name, func(t *testing.T) { bad := l tc.edit(&bad) p, e := m.Start(context.Background(), bad, []string{"/usr/bin/true"}) if e == nil { m.Stop(context.Background(), p.ID()) t.Fatal("unsafe mount/environment accepted") } }) } t.Run("symlink swap", func(t *testing.T) { path := filepath.Join(filepath.Dir(l.Workspace), "link") if e := os.Symlink(l.Workspace, path); e != nil { t.Fatal(e) } bad := l bad.Workspace = path if p, e := m.Start(context.Background(), bad, []string{"/usr/bin/true"}); e == nil { m.Stop(context.Background(), p.ID()) t.Fatal("symlink accepted") } }) } func TestNamespaceRecoverySavedExit(t *testing.T) { m, l := fixture(t) p := launch(t, m, l, "pass") r := record(t, m, p) exit, e := p.Wait(context.Background()) if e != nil { t.Fatal(e) } fresh, e := New(m.cfg) if e != nil { t.Fatal(e) } proof, e := fresh.Recover(context.Background(), r) if e != nil || !proof.Verified || proof.Exit != exit { t.Fatalf("durable exit recovery: %+v %v", proof, e) } } func TestNamespaceRecoveryRejectsNonInit(t *testing.T) { m, l := fixture(t) p := launch(t, m, l, "import time; print('ready',flush=True); time.sleep(60)") r := record(t, m, p) // Both candidate PIDs are owned fixtures. Neither is namespace init. control, controlFD := ownedControl(t) bad := r bad.HostPID = control.Process.Pid bad.StartTicks, bad.NamespaceID, _ = identity(bad.HostPID) if e := m.persist(bad); e != nil { t.Fatal(e) } defer m.persist(r) if proof, e := m.Recover(context.Background(), bad); e == nil || proof.Verified { t.Fatal("host process accepted as namespace init") } alive(t, controlFD) } func TestNamespaceRecoveryStaleDurableTicks(t *testing.T) { m, l := fixture(t) p := launch(t, m, l, "import time; time.sleep(60)") r := record(t, m, p) fd := descriptor(t, r.HostPID) bad := r bad.StartTicks++ if e := m.persist(bad); e != nil { t.Fatal(e) } defer m.persist(r) if proof, e := m.Recover(context.Background(), bad); e != nil || !proof.Verified || proof.Exit.Code != -1 || proof.Exit.Signal != 0 { t.Fatalf("absent recorded identity not recovered: %+v %v", proof, e) } alive(t, fd) } func TestNamespaceRecoveryUnavailableProof(t *testing.T) { for _, kind := range []string{"corrupt", "record", "unverified", "timestamp"} { t.Run(kind, func(t *testing.T) { m, l := fixture(t) p := launch(t, m, l, "pass") r := record(t, m, p) if _, e := p.Wait(context.Background()); e != nil { t.Fatal(e) } path := filepath.Join(m.cfg.ScratchRoot, p.ID()+".exit.json") b, e := os.ReadFile(path) if e != nil { t.Fatal(e) } var proof Proof if e = json.Unmarshal(b, &proof); e != nil { t.Fatal(e) } switch kind { case "corrupt": e = os.WriteFile(path, []byte("{"), 0600) case "record": proof.Record.ManifestHash += "-changed" e = durableJSON(m.cfg.ScratchRoot, p.ID()+".exit.json", proof) case "unverified": proof.Verified = false e = durableJSON(m.cfg.ScratchRoot, p.ID()+".exit.json", proof) case "timestamp": proof.Exit.ObservedAt = time.Time{} e = durableJSON(m.cfg.ScratchRoot, p.ID()+".exit.json", proof) } if e != nil { t.Fatal(e) } if recovered, e := m.Recover(context.Background(), r); e == nil || recovered.Verified { t.Fatalf("unavailable proof accepted: %+v %v", recovered, e) } }) } } func TestNamespaceRecoveryCleansScratch(t *testing.T) { for _, kind := range []string{"saved-exit", "new-boot"} { t.Run(kind, func(t *testing.T) { m, l := fixture(t) p := launch(t, m, l, "pass") r := record(t, m, p) if _, e := p.Wait(context.Background()); e != nil { t.Fatal(e) } // Recreate the crash window after proof fsync but before scratch removal. dir := filepath.Join(m.cfg.ScratchRoot, "attempt-"+r.ID) if e := os.Mkdir(dir, 0700); e != nil { t.Fatal(e) } if e := os.WriteFile(filepath.Join(dir, "leftover"), []byte("owned"), 0600); e != nil { t.Fatal(e) } if kind == "new-boot" { r.BootID = "previous-boot" } fresh, e := New(m.cfg) if e != nil { t.Fatal(e) } if proof, e := fresh.Recover(context.Background(), r); e != nil || !proof.Verified { t.Fatalf("recover: %+v %v", proof, e) } if _, e := os.Stat(dir); !os.IsNotExist(e) { t.Fatalf("recovery left owned scratch: %v", e) } }) } } func TestNamespaceScratchIdentity(t *testing.T) { m, l := fixture(t) p := launch(t, m, l, "import time; time.sleep(60)") if _, e := os.Stat(filepath.Join(m.cfg.ScratchRoot, "attempt-"+p.ID(), "tmp")); e != nil { t.Fatalf("scratch not bound to durable ID: %v", e) } } // Restore fixture permissions even when testing the unfixed implementation. func writableFixture(t *testing.T, dir string) { t.Helper() t.Cleanup(func() { _ = filepath.WalkDir(dir, func(path string, d os.DirEntry, err error) error { if err == nil && d.IsDir() { return os.Chmod(path, 0700) } return err }) }) } func TestNamespaceReadOnlyScratch(t *testing.T) { for _, mode := range []int{0555, 0500, 0000} { for _, stop := range []bool{false, true} { t.Run(fmt.Sprintf("%04o/stop=%t", mode, stop), func(t *testing.T) { m, l := fixture(t) script := fmt.Sprintf(`import os,sys for base in ['/tmp', '/home/runner']: os.makedirs(base+'/cache/nested') open(base+'/cache/nested/file','w').write('owned') os.chmod(base+'/cache/nested',%d) os.chmod(base+'/cache',%d) os.chmod(base,%d) print('ready',flush=True) sys.stdin.readline() `, mode, mode, mode) p := launch(t, m, l, script) r := record(t, m, p) dir := filepath.Join(m.cfg.ScratchRoot, "attempt-"+r.ID) writableFixture(t, dir) if _, e := bufio.NewReader(p.Stdout()).ReadString('\n'); e != nil { t.Fatal(e) } if !stop { p.Stdin().Close() _, _ = p.Wait(context.Background()) } proof, e := m.Stop(context.Background(), r.ID) if e != nil || !proof.Verified { t.Fatalf("read-only scratch invalidated exit: %+v %v", proof, e) } if _, e := os.Stat(dir); !os.IsNotExist(e) { t.Fatalf("scratch remains: %v", e) } recovered, e := m.Recover(context.Background(), r) if e != nil || recovered != proof { t.Fatalf("saved proof changed: %+v %v", recovered, e) } }) } } } func TestNamespaceRecoveryReadOnlyScratch(t *testing.T) { m, l := fixture(t) p := launch(t, m, l, "pass") r := record(t, m, p) if _, e := p.Wait(context.Background()); e != nil { t.Fatal(e) } dir := filepath.Join(m.cfg.ScratchRoot, "attempt-"+r.ID) nested := filepath.Join(dir, "cache", "nested") if e := os.MkdirAll(nested, 0700); e != nil { t.Fatal(e) } writableFixture(t, dir) if e := os.WriteFile(filepath.Join(nested, "file"), []byte("owned"), 0400); e != nil { t.Fatal(e) } outside := t.TempDir() marker := filepath.Join(outside, "keep") if e := os.WriteFile(marker, []byte("outside"), 0400); e != nil { t.Fatal(e) } if e := os.Symlink(outside, filepath.Join(nested, "link")); e != nil { t.Fatal(e) } if e := os.Chmod(outside, 0500); e != nil { t.Fatal(e) } defer os.Chmod(outside, 0700) for _, path := range []string{nested, filepath.Dir(nested), dir} { if e := os.Chmod(path, 0500); e != nil { t.Fatal(e) } } proof, e := m.Recover(context.Background(), r) if e != nil || !proof.Verified { t.Fatalf("read-only recovery invalidated exit: %+v %v", proof, e) } if _, e := os.Stat(dir); !os.IsNotExist(e) { t.Fatalf("scratch remains: %v", e) } info, e := os.Stat(outside) if e != nil || info.Mode().Perm() != 0500 { t.Fatalf("symlink target permissions changed: %v %v", info, e) } if b, e := os.ReadFile(marker); e != nil || string(b) != "outside" { t.Fatalf("symlink target changed: %q %v", b, e) } } func TestNamespaceCleanupFailureKeepsProof(t *testing.T) { m, l := fixture(t) p := launch(t, m, l, "pass") r := record(t, m, p) if _, e := p.Wait(context.Background()); e != nil { t.Fatal(e) } want, e := m.Stop(context.Background(), r.ID) if e != nil { t.Fatal(e) } dir := filepath.Join(m.cfg.ScratchRoot, "attempt-"+r.ID) if e := os.Mkdir(dir, 0700); e != nil { t.Fatal(e) } if e := os.Chmod(m.cfg.ScratchRoot, 0500); e != nil { t.Fatal(e) } defer os.Chmod(m.cfg.ScratchRoot, 0700) for range 2 { proof, e := m.Recover(context.Background(), r) if !errors.Is(e, os.ErrPermission) || proof != want { t.Fatalf("cleanup failure changed proof: %+v %v", proof, e) } } if e := os.Chmod(m.cfg.ScratchRoot, 0700); e != nil { t.Fatal(e) } proof, e := m.Recover(context.Background(), r) if e != nil || proof != want { t.Fatalf("cleanup retry: %+v %v", proof, e) } if _, e := os.Stat(dir); !os.IsNotExist(e) { t.Fatalf("scratch remains: %v", e) } } func TestNamespaceRecoveryCrashBeforeExit(t *testing.T) { m, l := fixture(t) c := exec.Command(os.Args[0]) c.Env = append(os.Environ(), "EQUIPO_NAMESPACE_PARENT_TEST=1", "EQUIPO_TEST_STATE="+m.cfg.ScratchRoot, "EQUIPO_TEST_WORKSPACE="+l.Workspace) stdout, e := c.StdoutPipe() if e != nil { t.Fatal(e) } c.Stderr = os.Stderr if e = c.Start(); e != nil { t.Fatal(e) } t.Cleanup(func() { c.Process.Kill(); c.Wait() }) var r Record if e = json.NewDecoder(stdout).Decode(&r); e != nil { t.Fatal(e) } fd := descriptor(t, r.HostPID) t.Cleanup(func() { unix.PidfdSendSignal(fd, unix.SIGKILL, nil, 0) }) if e = c.Process.Kill(); e != nil { t.Fatal(e) } c.Wait() exited(t, fd) deadline := time.Now().Add(5 * time.Second) for { probe, err := unix.PidfdOpen(r.HostPID, 0) if err == unix.ESRCH { break } // EINVAL is the kernel part way through the reap: the process is // unhashed and its number not yet free. Soon it is ESRCH. if err != nil && err != unix.EINVAL { t.Fatal(err) } if err == nil { unix.Close(probe) } if time.Now().After(deadline) { t.Fatalf("namespace init was not reaped: %v", err) } time.Sleep(time.Millisecond) } if _, e := os.Stat(filepath.Join(m.cfg.ScratchRoot, r.ID+".exit.json")); !os.IsNotExist(e) { t.Fatalf("crash fixture has exit proof: %v", e) } assertUnknownRecovery(t, m, r) } func TestNamespaceRecoveryReusedPID(t *testing.T) { for _, kind := range []string{"ticks", "namespace"} { t.Run(kind, func(t *testing.T) { m, l := fixture(t) p := launch(t, m, l, "pass") r := record(t, m, p) if _, e := p.Wait(context.Background()); e != nil { t.Fatal(e) } if e := os.Remove(filepath.Join(m.cfg.ScratchRoot, r.ID+".exit.json")); e != nil { t.Fatal(e) } control, fd := ownedControl(t) r.HostPID = control.Process.Pid ticks, ns, e := identity(r.HostPID) if e != nil { t.Fatal(e) } r.StartTicks, r.NamespaceID = ticks, ns if kind == "ticks" { r.StartTicks++ } else { r.NamespaceID = "pid:[1]" } if e := m.persist(r); e != nil { t.Fatal(e) } assertUnknownRecovery(t, m, r) alive(t, fd) }) } } func assertUnknownRecovery(t *testing.T, m *Manager, r Record) { t.Helper() proof, e := m.Recover(context.Background(), r) if e != nil || !proof.Verified || proof.Record != r || proof.Exit.Code != -1 || proof.Exit.Signal != 0 || proof.Exit.ObservedAt.IsZero() { t.Fatalf("absent init not recovered with unknown outcome: %+v %v", proof, e) } again, e := m.Recover(context.Background(), r) if e != nil || again != proof { t.Fatalf("recovery proof not durable: %+v %v", again, e) } if _, e := os.Stat(filepath.Join(m.cfg.ScratchRoot, "attempt-"+r.ID)); !os.IsNotExist(e) { t.Fatalf("scratch remains: %v", e) } } func TestNamespaceRecoveryMalformedRecord(t *testing.T) { for _, kind := range []string{"namespace", "id"} { t.Run(kind, func(t *testing.T) { m, l := fixture(t) p := launch(t, m, l, "pass") r := record(t, m, p) if _, e := p.Wait(context.Background()); e != nil { t.Fatal(e) } if e := os.Remove(filepath.Join(m.cfg.ScratchRoot, r.ID+".exit.json")); e != nil { t.Fatal(e) } if kind == "namespace" { r.NamespaceID = "invalid" } else { r.ID = "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz" } if e := m.persist(r); e != nil { t.Fatal(e) } if proof, e := m.Recover(context.Background(), r); !errors.Is(e, errIdentity) || proof.Verified { t.Fatalf("malformed record accepted: %+v %v", proof, e) } }) } } func TestDirectInterruptedIntentOnly(t *testing.T) { root := t.TempDir() boot, e := bootID() if e != nil { t.Fatal(e) } m := &Manager{cfg: Config{ScratchRoot: root}, processes: map[string]*process{}} r := Record{ID: "abcdefabcdefabcdefabcdefabcdefab", AttemptKey: "intent", BootID: boot, ManifestHash: "manifest", PolicyHash: "policy"} if e = m.persist(r); e != nil { t.Fatal(e) } dir := filepath.Join(root, "attempt-"+r.ID) if e = os.Mkdir(dir, 0700); e != nil { t.Fatal(e) } proof, e := m.Recover(context.Background(), r) if e != nil || !proof.Verified || proof.Exit.Code != -1 { t.Fatalf("intent-only restart blocked: %+v %v", proof, e) } if _, e = os.Stat(dir); !os.IsNotExist(e) { t.Fatal("intent scratch retained", e) } } func TestDirectInterruptedParentLifecycle(t *testing.T) { root := t.TempDir() boot, e := bootID() if e != nil { t.Fatal(e) } parent := exec.Command("/bin/sleep", "60") if e = parent.Start(); e != nil { t.Fatal(e) } defer parent.Process.Kill() defer parent.Wait() ticks, _, e := identity(parent.Process.Pid) if e != nil { t.Fatal(e) } m := &Manager{cfg: Config{ScratchRoot: root}, processes: map[string]*process{}} r := Record{ID: "abcdefabcdefabcdefabcdefabcdefab", AttemptKey: "intent", BootID: boot, ManifestHash: "manifest", PolicyHash: "policy", ParentPID: parent.Process.Pid, ParentTicks: ticks} if e = m.persist(r); e != nil { t.Fatal(e) } dir := filepath.Join(root, "attempt-"+r.ID) if e = os.Mkdir(dir, 0700); e != nil { t.Fatal(e) } ctx, cancel := context.WithTimeout(context.Background(), 30*time.Millisecond) defer cancel() if proof, e := m.Recover(ctx, r); e == nil || proof.Verified { t.Fatal("cleanup preceded parent death") } if _, e = os.Stat(dir); e != nil { t.Fatal("live lifecycle scratch deleted") } parent.Process.Kill() parent.Wait() if proof, e := m.Recover(context.Background(), r); e != nil || !proof.Verified { t.Fatalf("dead parent blocks recovery: %+v %v", proof, e) } }