//go:build linux package containment import ( "bufio" "context" "encoding/json" "errors" "fmt" "io" "io/fs" "net" "os" "os/exec" "path/filepath" "runtime" "strconv" "strings" "testing" "time" "amadan.net/oficina/equipo/internal/runner/provider" "amadan.net/oficina/equipo/internal/testci" "golang.org/x/sys/unix" ) func fixture(t *testing.T) (*Manager, provider.Launch) { t.Helper() root := t.TempDir() scratch := filepath.Join(root, "state") if err := os.Mkdir(scratch, 0700); err != nil { t.Fatal(err) } workspace := filepath.Join(root, "workspace") if err := os.Mkdir(workspace, 0700); err != nil { t.Fatal(err) } binary, err := os.Executable() if err != nil { t.Fatal(err) } testci.Tools(t, "bwrap", "python3") m, err := New(Config{Binary: "/usr/bin/bwrap", RunnerBinary: binary, ScratchRoot: scratch}) if err != nil { t.Fatalf("namespace capability missing: %v", err) } // An explicit legacy policy permits writes; a missing manifest fails closed. return m, provider.Launch{AttemptKey: "attempt-fixture", Workspace: workspace, Policy: provider.Policy{Hash: "fixture-policy", Manifest: []byte(`{}`)}} } func launch(t *testing.T, m *Manager, l provider.Launch, script string) provider.Process { t.Helper() ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second) t.Cleanup(cancel) argv := []string{"/usr/bin/python3", "-u", "-c", script} if l.Selection.Provider != "" { l, argv = directPolicyFixture(t, m, l, argv) } p, err := m.Start(ctx, l, argv) if err != nil { t.Fatalf("namespace capability/start failed (userns, pidfd required): %v", err) } t.Cleanup(func() { ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() p.(*process).kill() p.Wait(ctx) if _, err := m.Stop(ctx, p.ID()); err != nil { t.Errorf("cleanup: %v", err) } p.Stdin().Close() p.Stdout().Close() p.Stderr().Close() }) return p } func record(t *testing.T, m *Manager, p provider.Process) Record { t.Helper() b, err := os.ReadFile(filepath.Join(m.cfg.ScratchRoot, p.ID()+".json")) if err != nil { t.Fatal(err) } var r Record if err = json.Unmarshal(b, &r); err != nil { t.Fatal(err) } if r.HostPID == 0 || r.StartTicks == 0 || r.NamespaceID == "" || r.ManifestHash == "" { t.Fatalf("incomplete durable identity: %+v", r) } return r } func namespace(t *testing.T, pid int) string { t.Helper() n, e := os.Readlink(fmt.Sprintf("/proc/%d/ns/pid", pid)) if e != nil { t.Fatal(e) } return n } func descriptor(t *testing.T, pid int) int { t.Helper() fd, e := unix.PidfdOpen(pid, 0) if e != nil { t.Fatalf("capability missing: pidfd_open: %v", e) } t.Cleanup(func() { unix.Close(fd) }) return fd } func exited(t *testing.T, fd int) { t.Helper() p := []unix.PollFd{{Fd: int32(fd), Events: unix.POLLIN}} n, e := pollFD(p, 5*time.Second) if e != nil || n != 1 || p[0].Revents&unix.POLLIN == 0 { t.Fatalf("exact process has not exited: poll=%d,%v", n, e) } } func ownedControl(t *testing.T) (*exec.Cmd, int) { t.Helper() c := exec.Command("/usr/bin/sleep", "60") if e := c.Start(); e != nil { t.Fatal(e) } fd := descriptor(t, c.Process.Pid) t.Cleanup(func() { c.Process.Kill(); c.Wait() }) return c, fd } func alive(t *testing.T, fd int) { t.Helper() if e := unix.PidfdSendSignal(fd, 0, nil, 0); e != nil { t.Fatalf("owned unrelated control died: %v", e) } p := []unix.PollFd{{Fd: int32(fd), Events: unix.POLLIN}} n, e := pollFD(p, 0) if e != nil || n != 0 { t.Fatalf("owned unrelated control exited: %d %v", n, e) } } // Resolve only descendants of the exact init we started, never host-wide PIDs. func descendants(t *testing.T, root int) []int { t.Helper() out := []int{root} for i := 0; i < len(out); i++ { tasks, e := filepath.Glob(fmt.Sprintf("/proc/%d/task/*/children", out[i])) if e != nil { t.Fatal(e) } for _, task := range tasks { b, e := os.ReadFile(task) if os.IsNotExist(e) { continue } if e != nil { t.Fatal(e) } for _, s := range strings.Fields(string(b)) { pid, e := strconv.Atoi(s) if e != nil { t.Fatal(e) } out = append(out, pid) } } } return out } const detachedScript = `import os, subprocess, time subprocess.Popen(['/usr/bin/sleep','60'],start_new_session=True) pid=os.fork() if pid==0: if os.fork()==0: time.sleep(60) os._exit(0) os._exit(0) os.waitpid(pid,0) pid=os.fork() if pid==0: try: open('/sys/fs/cgroup/cgroup.procs','w').write(str(os.getpid())) except OSError: pass time.sleep(60) os._exit(0) print('ready',flush=True) time.sleep(60) ` func TestNamespaceKillsDetachedChildren(t *testing.T) { m, l := fixture(t) _, control := ownedControl(t) p := launch(t, m, l, detachedScript) line, e := bufio.NewReader(p.Stdout()).ReadString('\n') if e != nil || line != "ready\n" { t.Fatalf("fixture readiness %q %v", line, e) } r := record(t, m, p) if namespace(t, os.Getpid()) == r.NamespaceID { t.Fatal("shared host PID namespace") } members := descendants(t, r.HostPID) if len(members) < 5 { t.Fatalf("missing detached children: %v", members) } var fds []int for _, pid := range members { if pid != r.HostPID && namespace(t, pid) != r.NamespaceID { t.Fatal("namespace mismatch") } fds = append(fds, descriptor(t, pid)) } proof, e := m.Stop(context.Background(), p.ID()) if e != nil || !proof.Verified || proof.Record != r { t.Fatalf("stop proof: %+v %v", proof, e) } for _, fd := range fds { exited(t, fd) } alive(t, control) } // noSessionReason is why the delegated cgroup test skips where there is no // systemd user session, as inside a MicroVM. const noSessionReason = "no systemd user session; production containment does not use cgroups" // cgroupSkip decides whether the delegated cgroup test runs. stat checks // that base, the user@UID.service cgroup, exists. Without it the test skips, // unless require (EQUIPO_REQUIRE_USER_SESSION=1) demands a session, when it // fails. Any other stat error fails too: something is there but unusable. func cgroupSkip(base string, stat func(string) error, require bool) (skip bool, reason string, fail bool) { e := stat(base) switch { case e == nil: return false, "", false case !errors.Is(e, fs.ErrNotExist): return false, fmt.Sprintf("systemd user session cgroup %s: %v", base, e), true case require: return false, fmt.Sprintf("EQUIPO_REQUIRE_USER_SESSION=1 but no systemd user session at %s: %v", base, e), true } return true, noSessionReason, false } func TestCgroupSessionRule(t *testing.T) { const base = "/sys/fs/cgroup/user.slice/user-1000.slice/user@1000.service" for _, c := range []struct { name string err error require bool skip bool reason string fail bool }{ {name: "session", err: nil}, {name: "session required", err: nil, require: true}, {name: "no session", err: fs.ErrNotExist, skip: true, reason: noSessionReason}, {name: "no session required", err: fs.ErrNotExist, require: true, fail: true, reason: "EQUIPO_REQUIRE_USER_SESSION=1 but no systemd user session at " + base + ": file does not exist"}, {name: "unreadable", err: fs.ErrPermission, fail: true, reason: "systemd user session cgroup " + base + ": permission denied"}, } { var asked []string stat := func(p string) error { asked = append(asked, p); return c.err } skip, reason, fail := cgroupSkip(base, stat, c.require) if skip != c.skip || reason != c.reason || fail != c.fail { t.Errorf("%s: cgroupSkip = (%v, %q, %v), want (%v, %q, %v)", c.name, skip, reason, fail, c.skip, c.reason, c.fail) } if len(asked) != 1 || asked[0] != base { t.Errorf("%s: stat asked %q, want [%q]", c.name, asked, base) } } } func TestNamespaceCgroupMoveKeepsMembership(t *testing.T) { base := fmt.Sprintf("/sys/fs/cgroup/user.slice/user-%d.slice/user@%d.service", os.Getuid(), os.Getuid()) stat := func(p string) error { _, e := os.Stat(p); return e } switch skip, reason, fail := cgroupSkip(base, stat, os.Getenv("EQUIPO_REQUIRE_USER_SESSION") == "1"); { case fail: t.Fatal(reason) case skip: t.Skip(reason) } if _, e := os.ReadFile(filepath.Join(base, "cgroup.subtree_control")); e != nil { t.Fatalf("capability missing: delegated cgroup subtree: %v", e) } a, e := os.MkdirTemp(base, "equipo-task2-") if e != nil { t.Fatalf("capability missing: writable delegated cgroup subtree: %v", e) } t.Cleanup(func() { if e := os.Remove(a); e != nil { t.Errorf("remove test cgroup: %v", e) } }) b := filepath.Join(a, "destination") if e = os.Mkdir(b, 0700); e != nil { t.Fatal(e) } t.Cleanup(func() { if e := os.Remove(b); e != nil { t.Errorf("remove test cgroup: %v", e) } }) // Make two leaf cgroups, keeping the test's parent empty. source := filepath.Join(a, "source") if e = os.Mkdir(source, 0700); e != nil { t.Fatal(e) } t.Cleanup(func() { if e := os.Remove(source); e != nil { t.Errorf("remove test cgroup: %v", e) } }) 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) children := descendants(t, r.HostPID) if len(children) < 2 { t.Fatal("missing harness") } pid := children[1] fd := descriptor(t, pid) before := namespace(t, pid) for _, dir := range []string{source, b} { if e = os.WriteFile(filepath.Join(dir, "cgroup.procs"), []byte(strconv.Itoa(pid)), 0600); e != nil { t.Fatalf("capability missing: authorized cgroup move: %v", e) } actual, e := os.ReadFile(fmt.Sprintf("/proc/%d/cgroup", pid)) if e != nil || !strings.Contains(string(actual), filepath.Base(a)+"/"+filepath.Base(dir)) { t.Fatalf("move not observed: %s %v", actual, e) } } if namespace(t, pid) != before { t.Fatal("cgroup move changed PID namespace") } if _, e = m.Stop(context.Background(), p.ID()); e != nil { t.Fatal(e) } exited(t, fd) } func TestNamespaceHidesHostControl(t *testing.T) { home, e := os.UserHomeDir() if e != nil { t.Fatal(e) } m, l := fixture(t) listener, e := net.Listen("tcp", "127.0.0.1:0") if e != nil { t.Fatal(e) } defer listener.Close() socket, e := net.Listen("unix", filepath.Join(t.TempDir(), "control.sock")) if e != nil { t.Fatal(e) } defer socket.Close() // Deliberately make an owned socket inheritable in the launching process. file, e := socket.(*net.UnixListener).File() if e != nil { t.Fatal(e) } defer file.Close() if _, e = unix.FcntlInt(file.Fd(), unix.F_SETFD, 0); e != nil { t.Fatal(e) } l.Policy.Env = map[string]string{"LANG": "C.UTF-8"} t.Setenv("EQUIPO_TEST_HOST_SECRET", "must-not-inherit") p := launch(t, m, l, fmt.Sprintf(`import os,socket,json paths=['/sys/fs/cgroup','/run/user/%d/bus','/run/user/%d/systemd/private',%s,%s,'/etc/claude-code/managed-settings.json','/etc/codex/config.toml'] assert all(not os.path.exists(p) for p in paths), paths assert os.listdir('/home')==['runner'] assert 'EQUIPO_TEST_HOST_SECRET' not in os.environ assert os.getppid()==1 assert int([l for l in open('/proc/self/status') if l.startswith('CapEff:')][0].split()[1],16)==0 assert open('/proc/1/comm').read().strip()!='python3' assert all(not os.readlink('/proc/self/fd/'+f).startswith('socket:') for f in os.listdir('/proc/self/fd') if os.path.exists('/proc/self/fd/'+f)) s=socket.socket(); assert s.connect_ex(('127.0.0.1',%d))!=0 try: open('/sys/fs/cgroup/cgroup.procs','w').write(str(os.getpid())) raise AssertionError('cgroup exposed') except OSError: pass print('isolated') `, os.Getuid(), os.Getuid(), strconv.Quote(home), strconv.Quote("/proc/1/root"+home), listener.Addr().(*net.TCPAddr).Port)) output, e := io.ReadAll(p.Stdout()) if e != nil { t.Fatal(e) } exit, e := p.Wait(context.Background()) if e != nil || exit.Code != 0 || string(output) != "isolated\n" { errout, _ := io.ReadAll(p.Stderr()) t.Fatalf("isolation: %s %+v %v %s", output, exit, e, errout) } } func TestNamespacePidfdCapability(t *testing.T) { c, fd := ownedControl(t) if e := unix.PidfdSendSignal(fd, unix.SIGKILL, nil, 0); e != nil { t.Fatalf("capability missing: pidfd_send_signal: %v", e) } var info unix.Siginfo if e := unix.Waitid(unix.P_PIDFD, fd, &info, unix.WEXITED|unix.WNOWAIT, nil); e != nil { t.Fatalf("capability missing: waitid(P_PIDFD): %v", e) } exited(t, fd) _ = c } func parentFixture() { runtime.LockOSThread() // os.Executable, not os.Args[0]: the binary may be started by a relative path. binary, e := os.Executable() if e != nil { panic(e) } m, e := New(Config{Binary: "/usr/bin/bwrap", RunnerBinary: binary, ScratchRoot: os.Getenv("EQUIPO_TEST_STATE")}) if e != nil { panic(e) } l := provider.Launch{AttemptKey: "parent-death", Workspace: os.Getenv("EQUIPO_TEST_WORKSPACE"), Policy: provider.Policy{Hash: "parent-policy"}} p, e := m.Start(context.Background(), l, []string{"/usr/bin/python3", "-u", "-c", detachedScript}) if e != nil { panic(e) } if _, e = bufio.NewReader(p.Stdout()).ReadString('\n'); e != nil { panic(e) } b, e := os.ReadFile(filepath.Join(m.cfg.ScratchRoot, p.ID()+".json")) if e != nil { panic(e) } fmt.Println(string(b)) select {} } func TestNamespaceParentDeath(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.Fatalf("launcher fixture: %v", e) } members := descendants(t, r.HostPID) var fds []int for _, pid := range members { fds = append(fds, descriptor(t, pid)) } t.Cleanup(func() { if len(fds) > 0 { unix.PidfdSendSignal(fds[0], unix.SIGKILL, nil, 0) } }) if e = c.Process.Kill(); e != nil { t.Fatal(e) } for _, fd := range fds { exited(t, fd) } } func TestNamespaceStartingThreadExit(t *testing.T) { m, l := fixture(t) done := make(chan provider.Process, 1) go func() { runtime.LockOSThread() p, e := m.Start(context.Background(), l, []string{"/usr/bin/sleep", "60"}) if e != nil { done <- nil return } done <- p }() p := <-done if p == nil { t.Fatal("start failed") } defer m.Stop(context.Background(), p.ID()) r := record(t, m, p) fd := descriptor(t, r.HostPID) time.Sleep(50 * time.Millisecond) alive(t, fd) } func TestNamespaceStartupFailure(t *testing.T) { m, l := fixture(t) // The helper cannot acknowledge PID 1, so no process is returned and no // harness side effect is possible. The incomplete intent remains durable. cfg := m.cfg cfg.RunnerBinary = "/usr/bin/true" m, err := New(cfg) if err != nil { return // An unrelated helper is rejected before startup. } p, e := m.Start(context.Background(), l, []string{"/usr/bin/touch", "/workspace/prompt-sent"}) if e == nil || p != nil { t.Fatal("missing readiness accepted") } if _, e = os.Stat(filepath.Join(l.Workspace, "prompt-sent")); !os.IsNotExist(e) { t.Fatal("harness ran before readiness") } entries, e := os.ReadDir(m.cfg.ScratchRoot) if e != nil { t.Fatal(e) } if len(entries) != 2 { t.Fatalf("startup intent or exit proof missing: %v", entries) } records, e := m.Records(context.Background()) if e != nil || len(records) != 1 { t.Fatalf("startup records: %v %v", records, e) } proof, e := m.Recover(context.Background(), records[0]) if e != nil || !proof.Verified || proof.Exit.ObservedAt.IsZero() { t.Fatalf("failed startup was not proven contained: %+v %v", proof, e) } } func TestNamespaceIntentBeforeFork(t *testing.T) { m, l := fixture(t) marker := filepath.Join(l.Workspace, "intent-observed") shim := filepath.Join(filepath.Dir(l.Workspace), "inspect-intent") script := "#!/usr/bin/python3\nimport glob,json\nrecords=glob.glob(" + strconv.Quote(m.cfg.ScratchRoot+"/*.json") + ")\nassert len(records)==1\nr=json.load(open(records[0]))\nassert r['HostPID']==0 and r['AttemptKey']=='attempt-fixture'\nopen(" + strconv.Quote(marker) + ",'w').write('intent')\n" if e := os.WriteFile(shim, []byte(script), 0700); e != nil { t.Fatal(e) } m.cfg.Binary = shim if p, e := m.Start(context.Background(), l, []string{"/usr/bin/true"}); e == nil { m.Stop(context.Background(), p.ID()) t.Fatal("shim acknowledged readiness") } if b, e := os.ReadFile(marker); e != nil || string(b) != "intent" { t.Fatalf("no durable intent before fork: %q %v", b, e) } } func TestNamespaceStopWaitsForExit(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) proof, e := m.Stop(context.Background(), p.ID()) if e != nil || !proof.Verified { t.Fatalf("stop: %+v %v", proof, e) } polls := []unix.PollFd{{Fd: int32(fd), Events: unix.POLLIN}} n, e := pollFD(polls, 0) if e != nil || n != 1 { t.Fatal("stop acknowledged before exact init exit") } b, e := os.ReadFile(filepath.Join(m.cfg.ScratchRoot, p.ID()+".exit.json")) if e != nil { t.Fatal(e) } var saved Proof if e = json.Unmarshal(b, &saved); e != nil || saved.Record != proof.Record || saved.Exit != proof.Exit || !saved.Verified { t.Fatalf("exit proof not durable: %s %v", b, e) } } func TestNamespaceExitStatus(t *testing.T) { for _, script := range []string{"import sys; sys.exit(137)", "import os,signal; os.kill(os.getpid(),signal.SIGTERM)"} { m, l := fixture(t) p := launch(t, m, l, script) exit, e := p.Wait(context.Background()) if e != nil { t.Fatal(e) } if strings.Contains(script, "137") { if exit.Code != 137 || exit.Signal != 0 { t.Fatalf("numeric exit fabricated signal: %+v", exit) } } else if exit.Code != -1 || exit.Signal != int(unix.SIGTERM) { t.Fatalf("signal outcome: %+v", exit) } } } func TestNamespaceSocketImport(t *testing.T) { m, l := fixture(t) listener, e := net.Listen("unix", filepath.Join(l.Workspace, "service.sock")) if e != nil { t.Fatal(e) } defer listener.Close() p, e := m.Start(context.Background(), l, []string{"/usr/bin/true"}) if e == nil { m.Stop(context.Background(), p.ID()) t.Fatal("host socket imported") } } func TestNamespaceNestedUserNamespace(t *testing.T) { m, l := fixture(t) p := launch(t, m, l, "import subprocess; subprocess.run(['/usr/bin/bwrap','--unshare-user','--ro-bind','/','/','--','/usr/bin/true'],check=True)") exit, e := p.Wait(context.Background()) if e != nil || exit.Code != 0 { b, _ := io.ReadAll(p.Stderr()) t.Fatalf("nested sandbox unavailable: %+v %v %s", exit, e, b) } } func TestNamespaceHelperProtocolPrivate(t *testing.T) { m, l := fixture(t) p := launch(t, m, l, `import os try: fd=os.open('/proc/1/fd/5',os.O_WRONLY) except OSError: print('private') else: os.close(fd) raise AssertionError('harness can forge helper outcome') `) exit, e := p.Wait(context.Background()) if e != nil || exit.Code != 0 { t.Fatalf("helper pipe exposed: %+v %v", exit, e) } } func TestNamespaceHelperBarrier(t *testing.T) { m, l := fixture(t) runtime.LockOSThread() defer runtime.UnlockOSThread() statusR, statusW, e := os.Pipe() if e != nil { t.Fatal(e) } defer statusR.Close() defer statusW.Close() releaseR, releaseW, e := os.Pipe() if e != nil { t.Fatal(e) } defer releaseR.Close() defer releaseW.Close() readyR, readyW, e := os.Pipe() if e != nil { t.Fatal(e) } defer readyR.Close() defer readyW.Close() c := exec.Command(m.cfg.Binary, "--unshare-user", "--unshare-pid", "--as-pid-1", "--die-with-parent", "--unshare-net", "--ro-bind", "/usr", "/usr", "--symlink", "usr/lib", "/lib", "--symlink", "usr/lib64", "/lib64", "--proc", "/proc", "--dev", "/dev", "--bind", l.Workspace, "/workspace", "--ro-bind", m.cfg.RunnerBinary, "/helper", "--json-status-fd", "3", "--", "/helper", "__namespace", "/usr/bin/touch", "/workspace/released") c.ExtraFiles = []*os.File{statusW, releaseR, readyW} c.Stderr = os.Stderr if e = c.Start(); e != nil { t.Fatal(e) } defer func() { c.Process.Kill(); c.Wait() }() statusW.Close() releaseR.Close() readyW.Close() var status struct { PID int `json:"child-pid"` } if e = json.NewDecoder(statusR).Decode(&status); e != nil { t.Fatal(e) } var ready readiness if e = json.NewDecoder(readyR).Decode(&ready); e != nil || ready.PID != 1 { t.Fatalf("helper topology: %+v %v", ready, e) } time.Sleep(30 * time.Millisecond) marker := filepath.Join(l.Workspace, "released") if _, e = os.Stat(marker); !os.IsNotExist(e) { t.Fatal("harness started before release") } if _, e = releaseW.Write([]byte{1}); e != nil { t.Fatal(e) } if e = c.Wait(); e != nil { t.Fatal(e) } if _, e = os.Stat(marker); e != nil { t.Fatal("released harness never ran") } } func TestNamespaceReapsOrphans(t *testing.T) { m, l := fixture(t) p := launch(t, m, l, `import os,time pid=os.fork() if pid==0: if os.fork()==0: open('/workspace/orphan','w').write(str(os.getpid())) time.sleep(.05) os._exit(0) os._exit(0) os.waitpid(pid,0) while not os.path.exists('/workspace/orphan'): time.sleep(.001) orphan=open('/workspace/orphan').read() while not orphan: time.sleep(.001) orphan=open('/workspace/orphan').read() for i in range(1000): if not os.path.exists('/proc/'+orphan): break time.sleep(.001) else: raise AssertionError('orphan remains a zombie') `) exit, e := p.Wait(context.Background()) if e != nil || exit.Code != 0 { t.Fatalf("orphan not reaped: %+v %v", exit, e) } } func TestNamespaceCancellation(t *testing.T) { m, l := fixture(t) ctx, cancel := context.WithCancel(context.Background()) defer cancel() p, e := m.Start(ctx, l, []string{"/usr/bin/sleep", "60"}) if e != nil { t.Fatal(e) } defer p.Stdin().Close() defer p.Stdout().Close() defer p.Stderr().Close() t.Cleanup(func() { p.(*process).kill(); p.Wait(context.Background()) }) r := record(t, m, p) fd := descriptor(t, r.HostPID) cancel() wait, cancelWait := context.WithTimeout(context.Background(), 2*time.Second) defer cancelWait() if _, e = p.Wait(wait); e != nil { t.Fatal(e) } exited(t, fd) } func TestNamespaceConcreteManifestHash(t *testing.T) { m, l := fixture(t) p := launch(t, m, l, "pass") r := record(t, m, p) if r.ManifestHash == l.Policy.Hash { t.Fatal("policy hash substituted for concrete manifest hash") } } func TestNamespaceManifestInputs(t *testing.T) { m, l := fixture(t) plan := &mounts{args: []string{"--bind-fd", "6", "/workspace"}} first, e := m.namespaceManifest(l, []string{"/usr/bin/true"}, "launch", "/scratch/attempt-one", plan) if e != nil { t.Fatal(e) } for _, kind := range []string{"argv", "mount", "scratch", "binary"} { t.Run(kind, func(t *testing.T) { args := []string{"/usr/bin/true"} dir := "/scratch/attempt-one" p := *plan manager := &Manager{cfg: m.cfg, namespaceDigest: m.namespaceDigest} switch kind { case "argv": args = []string{"/usr/bin/false"} case "mount": p.args = []string{"--ro-bind-fd", "6", "/workspace"} case "scratch": dir = "/scratch/attempt-two" case "binary": manager.cfg.RunnerBinary = "/usr/bin/true" } next, e := manager.namespaceManifest(l, args, "launch", dir, &p) if kind == "binary" { if e == nil { t.Fatal("changed namespace executable accepted") } return } if e != nil { t.Fatal(e) } if first == next { t.Fatal("constructed namespace input not hashed") } }) } } func TestNamespaceProviderRequiresManifest(t *testing.T) { m, l := fixture(t) l.Selection.Provider = "claude" p, e := m.Start(context.Background(), l, []string{"/usr/bin/true"}) if e == nil { p.(*process).kill() p.Wait(context.Background()) p.Stdin().Close() p.Stdout().Close() p.Stderr().Close() t.Fatal("provider launch without manifest forked") } if e != errStartup { t.Fatalf("missing manifest passed admission: %v", e) } entries, e := os.ReadDir(m.cfg.ScratchRoot) if e != nil { t.Fatal(e) } if len(entries) != 0 { t.Fatal("unattested provider launch created attempt state") } } func TestNamespaceDirectPolicy(t *testing.T) { m, l := egressFixture(t) p := launch(t, m, l, `import os assert not os.path.exists('/home/runner/equipo-settings.json') try: open('/config/equipo-settings.json','w').write('{}') raise AssertionError('config writable') except OSError: pass print('direct-running',flush=True) `) raw, e := io.ReadAll(p.Stdout()) if e != nil { t.Fatal(e) } exit, e := p.Wait(context.Background()) if e != nil || exit.Code != 0 || string(raw) != "direct-running\n" { errout, _ := io.ReadAll(p.Stderr()) t.Fatalf("direct namespace failed: %s %v %v %s", raw, exit, e, errout) } r := record(t, m, p) if r.ManifestHash == r.PolicyHash { t.Fatal("direct manifest not concrete") } } func TestNamespaceDirectPolicySwapBeforePin(t *testing.T) { m, l := egressFixture(t) l, argv := directPolicyFixture(t, m, l, []string{"/usr/bin/true"}) called := false m.beforePin = func() { called = true for _, mount := range l.Policy.Mounts { if mount.Target == provider.SettingsPath { replacement := mount.Source + "-replacement" if e := os.WriteFile(replacement, []byte(`{"changed":true}`), 0600); e != nil { t.Fatal(e) } if e := os.Rename(replacement, mount.Source); e != nil { t.Fatal(e) } } } } p, e := m.Start(context.Background(), l, argv) if e == nil { p.(*process).kill() p.Wait(context.Background()) p.Stdin().Close() p.Stdout().Close() p.Stderr().Close() t.Fatal("swapped settings reached namespace") } if !called { t.Fatal("did not reach attestation-to-pin boundary") } if e != provider.ErrPolicy { t.Fatalf("unexpected refusal: %v", e) } } func TestNamespaceDirectPolicyAdmission(t *testing.T) { for _, kind := range []string{"runner", "bwrap", "argv", "env", "mount"} { t.Run(kind, func(t *testing.T) { m, l := egressFixture(t) l, argv := directPolicyFixture(t, m, l, []string{"/usr/bin/true"}) switch kind { case "runner": m.cfg.RunnerBinary = "/usr/bin/false" case "bwrap": m.cfg.Binary = "/usr/bin/false" case "argv": argv = append(argv, "unexpected") case "env": l.Policy.Env["LANG"] = "changed" case "mount": l.Policy.Mounts[0].Target = "/opt/other" } reached := false m.beforePin = func() { reached = true } before, err := os.ReadDir(m.cfg.ScratchRoot) if err != nil { t.Fatal(err) } p, e := m.Start(context.Background(), l, argv) if e == nil { p.(*process).kill() p.Wait(context.Background()) p.Stdin().Close() p.Stdout().Close() p.Stderr().Close() t.Fatal("changed direct launch accepted") } if kind == "runner" { if !reached || e != errStartup { t.Fatalf("changed namespace executable bypassed pinned digest check: reached=%v err=%v", reached, e) } } else if reached { t.Fatal("changed direct launch passed attestation") } entries, err := os.ReadDir(m.cfg.ScratchRoot) if err != nil || len(entries) != len(before) { t.Fatalf("changed direct launch created attempt state: %v %v", entries, err) } }) } }