//go:build linux package containment import ( "context" "crypto/sha256" "encoding/hex" "errors" "fmt" "io" "net" "os" "path/filepath" "slices" "strings" "syscall" "testing" "amadan.net/oficina/equipo/internal/runner/provider" ) // withAction gives the fixture launch a hand-built manifest for action, // certifying bubblewrap as the real launches do. func withAction(t *testing.T, m *Manager, l provider.Launch, action string) provider.Launch { t.Helper() raw, err := os.ReadFile(m.cfg.Binary) if err != nil { t.Fatal(err) } bwrap := sha256.Sum256(raw) l.Policy.Manifest = []byte(fmt.Sprintf(`{"Action":%q,"Files":[{"Mount":{"Source":%q},"SHA256":%q}]}`, action, m.cfg.Binary, hex.EncodeToString(bwrap[:]))) l.Policy.ManifestHash = provider.ManifestDigest(l.Policy.Manifest) return l } func attemptDir(t *testing.T, m *Manager) string { t.Helper() dir, err := os.MkdirTemp(m.cfg.ScratchRoot, "attempt-") if err != nil { t.Fatal(err) } t.Cleanup(func() { os.RemoveAll(dir) }) for _, name := range []string{"tmp", "home"} { if err = os.Mkdir(filepath.Join(dir, name), 0700); err != nil { t.Fatal(err) } } return dir } // toolSocket makes a runner-style per-attempt tool socket. func toolSocket(t *testing.T) string { t.Helper() dir := t.TempDir() if err := os.Chmod(dir, 0700); err != nil { t.Fatal(err) } fd, err := os.Open(dir) if err != nil { t.Fatal(err) } t.Cleanup(func() { fd.Close() }) ln, err := net.ListenUnix("unix", &net.UnixAddr{Name: fmt.Sprintf("/proc/self/fd/%d/equipo.sock", fd.Fd()), Net: "unix"}) if err != nil { t.Fatal(err) } t.Cleanup(func() { ln.Close() }) path := filepath.Join(dir, "equipo.sock") if err = os.Chmod(path, 0600); err != nil { t.Fatal(err) } return path } // runPlanned runs argv in the namespace mountPlan gives l, and returns // its standard output. func runPlanned(t *testing.T, m *Manager, l provider.Launch, argv []string, id string) string { t.Helper() dir := attemptDir(t, m) plan, err := m.mountPlan(l, dir) if err != nil { t.Fatal(err) } if _, err = m.namespaceManifest(l, argv, l.Policy.Hash, dir, plan); err != nil { plan.close() t.Fatal(err) } boot, err := bootID() if err != nil { t.Fatal(err) } r := Record{ID: id, BootID: boot, AttemptKey: l.AttemptKey, ManifestHash: l.Policy.Hash} if err = m.persist(r); err != nil { t.Fatal(err) } result := make(chan startResult, 1) go m.lifecycle(context.Background(), r, argv, plan, dir, result, nil, false) started := <-result if started.err != nil { t.Fatal(started.err) } p := started.p p.Stdin().Close() errOut := make(chan []byte, 1) go func() { b, _ := io.ReadAll(p.Stderr()); errOut <- b }() out, err := io.ReadAll(p.Stdout()) if err != nil { t.Fatal(err) } if _, err := p.Wait(context.Background()); err != nil { t.Fatal(err) } if stderr := <-errOut; len(stderr) > 0 { t.Logf("stderr: %s", stderr) } p.Stdout().Close() p.Stderr().Close() return string(out) } // A Research step's namespace (spec ยง4): /etc is a fresh tmpfs holding // only the host CA bundle, passwd and group stubs and the masked // provider directories, never the host /etc; /workspace is the runner's // empty scratch directory, writable; nothing else of the runner's // state but its tool socket. func TestNamespaceResearchMinimalEtc(t *testing.T) { m, l := fixture(t) l = withAction(t, m, l, provider.ResearchStepAction) l.ToolSocket = toolSocket(t) host, err := filepath.EvalSymlinks(hostCABundle) if err != nil { t.Skip("no host CA bundle") } raw, err := os.ReadFile(host) if err != nil { t.Fatal(err) } ca := sha256.Sum256(raw) script := `import os, pwd, grp, hashlib seen = [] for root, dirs, files in os.walk("/"): if root == "/": dirs[:] = [d for d in dirs if d not in ("proc", "sys", "dev", "usr")] seen += [os.path.join(root, n) for n in dirs + files] print(sorted(seen)) print(pwd.getpwuid(os.getuid()).pw_name, grp.getgrgid(os.getgid()).gr_name) print(hashlib.sha256(open("/etc/ssl/certs/ca-certificates.crt", "rb").read()).hexdigest()) print(os.listdir("/workspace")) open("/workspace/notes.txt", "w").write("x") print(os.listdir("/workspace")) for path in ("/etc/hosts", "/etc/passwd"): try: open(path, "a").write("x") print("wrote", path) except OSError as e: print("refused", e.errno) ` out := runPlanned(t, m, l, []string{"/usr/bin/python3", "-u", "-c", script}, "01234567890123456789012345678911") tree := []string{"/bin", "/equipo-namespace", "/etc", "/etc/claude-code", "/etc/codex", "/etc/group", "/etc/passwd", "/etc/ssl", "/etc/ssl/certs", "/etc/ssl/certs/ca-certificates.crt", "/home", "/home/runner", "/lib", "/lib64", "/run", "/tmp", "/tool", "/tool/equipo.sock", "/workspace"} quoted := make([]string, len(tree)) for i, p := range tree { quoted[i] = "'" + p + "'" } want := "[" + strings.Join(quoted, ", ") + "]\n" + "runner runner\n" + hex.EncodeToString(ca[:]) + "\n" + "[]\n['notes.txt']\n" + "refused 30\nrefused 30\n" if out != want { t.Fatalf("research namespace:\n%s\nwant\n%s", out, want) } if entries, _ := os.ReadDir(l.Workspace); len(entries) != 1 || entries[0].Name() != "notes.txt" { t.Fatalf("scratch workspace after the step: %v", entries) } } // The plan itself: no host /etc overlay, a tmpfs /etc, the masked // directories kept; a workspace that is not empty is refused. func TestResearchMountPlan(t *testing.T) { m, l := fixture(t) l = withAction(t, m, l, provider.ResearchStepAction) dir := attemptDir(t, m) plan, err := m.mountPlan(l, dir) if err != nil { t.Fatal(err) } defer plan.close() args := strings.Join(plan.args, " ") if slices.Contains(plan.args, "--overlay-src") || slices.Contains(plan.args, "--tmp-overlay") || strings.Contains(args, "--ro-bind /etc") { t.Fatalf("host /etc reaches a research step: %s", args) } for _, want := range []string{"--tmpfs /etc ", "--tmpfs /etc/claude-code", "--tmpfs /etc/codex", "/etc/ssl/certs/ca-certificates.crt", "/etc/passwd", "/etc/group", "--remount-ro /etc "} { if !strings.Contains(args+" ", want) { t.Fatalf("plan lacks %q: %s", want, args) } } if strings.Index(args, "--tmpfs /etc ") > strings.Index(args, "/etc/ssl/certs/ca-certificates.crt") { t.Fatal("CA bundle bound before the /etc tmpfs") } // A clone or a desk is never a research workspace. if err := os.WriteFile(filepath.Join(l.Workspace, "README.md"), []byte("repository"), 0600); err != nil { t.Fatal(err) } if plan, err := m.mountPlan(l, attemptDir(t, m)); err == nil { plan.close() t.Fatal("research step over a non-empty workspace accepted") } // Every other launch keeps the host /etc overlay. _, other := fixture(t) other = withAction(t, m, other, "implement") plan2, err := m.mountPlan(other, attemptDir(t, m)) if err != nil { t.Fatal(err) } defer plan2.close() if !slices.Contains(plan2.args, "--overlay-src") { t.Fatal("engineering lost the host /etc") } } // The host CA bundle is resolved on the host first and the regular file // it names is pinned, so a symlinked bundle (the common layout) works // and the namespace sees a file, not a link. func TestResearchCABundleResolved(t *testing.T) { m, l := fixture(t) l = withAction(t, m, l, provider.ResearchStepAction) real := filepath.Join(t.TempDir(), "bundle.pem") if err := os.WriteFile(real, []byte("-----BEGIN CERTIFICATE-----\n"), 0644); err != nil { t.Fatal(err) } link := filepath.Join(t.TempDir(), "ca-certificates.crt") if err := os.Symlink(real, link); err != nil { t.Fatal(err) } old := hostCABundle hostCABundle = link defer func() { hostCABundle = old }() plan, err := m.mountPlan(l, attemptDir(t, m)) if err != nil { t.Fatalf("symlinked CA bundle refused: %v", err) } defer plan.close() found := false for i, arg := range plan.args { if arg == "/etc/ssl/certs/ca-certificates.crt" { var fd int fmt.Sscan(plan.args[i-1], &fd) found = plan.files[fd-6].Name() == real } } if !found { t.Fatal("CA bundle not pinned at its resolved file") } } // researchDir makes a runner-style kept-image directory: 0700, the // runner's, regular files only. func researchDir(t *testing.T) string { t.Helper() dir := filepath.Join(t.TempDir(), "research") if err := os.Mkdir(dir, 0700); err != nil { t.Fatal(err) } for name, body := range map[string]string{"img-1.png": "png bytes", "img-2.png": "more png"} { if err := os.WriteFile(filepath.Join(dir, name), []byte(body), 0600); err != nil { t.Fatal(err) } } return dir } // Engineering and Review see kept images read-only at /research. func TestNamespaceResearchDirReadOnly(t *testing.T) { m, l := fixture(t) l = withAction(t, m, l, "implement") l.ResearchDir = researchDir(t) script := `import os print(sorted(os.listdir("/research")), open("/research/img-1.png").read()) for path in ("/research/img-1.png", "/research/planted.png"): try: open(path, "a").write("x") print("wrote", path) except OSError as e: print("refused", e.errno) ` out := runPlanned(t, m, l, []string{"/usr/bin/python3", "-u", "-c", script}, "01234567890123456789012345678912") want := "['img-1.png', 'img-2.png'] png bytes\nrefused 30\nrefused 30\n" if out != want { t.Fatalf("/research inside the namespace:\n%s\nwant\n%s", out, want) } inspect := withAction(t, m, l, "inspect") plan, err := m.mountPlan(inspect, attemptDir(t, m)) if err != nil { t.Fatalf("review's /research refused: %v", err) } plan.close() } // The /research bind is refused for any launch but Engineering and // Review (a research step above all), and for a directory that is not // the runner's own flat directory of regular files. func TestResearchDirRefusals(t *testing.T) { m, base := fixture(t) type refusal struct { name, reason string setup func(t *testing.T, l *provider.Launch) } for _, c := range []refusal{ {"research step", "launch", func(t *testing.T, l *provider.Launch) { *l = withAction(t, m, *l, provider.ResearchStepAction) }}, {"coordinator", "launch", func(t *testing.T, l *provider.Launch) { *l = withAction(t, m, *l, "converse") }}, {"answer", "launch", func(t *testing.T, l *provider.Launch) { *l = withAction(t, m, *l, "answer") }}, {"no action", "launch", func(t *testing.T, l *provider.Launch) { l.Policy.Manifest, l.Policy.ManifestHash = []byte(`{}`), "" }}, {"tampered manifest", "launch", func(t *testing.T, l *provider.Launch) { l.Policy.ManifestHash = provider.ManifestDigest([]byte(`{}`)) }}, {"symlinked directory", "", func(t *testing.T, l *provider.Launch) { link := filepath.Join(t.TempDir(), "research") os.Symlink(l.ResearchDir, link) l.ResearchDir = link }}, {"relative path", "", func(t *testing.T, l *provider.Launch) { l.ResearchDir = "research" }}, {"group readable", "mode", func(t *testing.T, l *provider.Launch) { os.Chmod(l.ResearchDir, 0750) }}, {"world readable", "mode", func(t *testing.T, l *provider.Launch) { os.Chmod(l.ResearchDir, 0755) }}, {"not the runner's", "owner", func(t *testing.T, l *provider.Launch) { if os.Getuid() == 0 { t.Skip("the runner owns everything as root") } l.ResearchDir = "/var" }}, {"subdirectory", "entry", func(t *testing.T, l *provider.Launch) { os.Mkdir(filepath.Join(l.ResearchDir, "nested"), 0700) }}, {"symlink entry", "entry", func(t *testing.T, l *provider.Launch) { os.Symlink("/etc/hostname", filepath.Join(l.ResearchDir, "img-3.png")) }}, {"fifo entry", "entry", func(t *testing.T, l *provider.Launch) { syscall.Mkfifo(filepath.Join(l.ResearchDir, "img-3.png"), 0600) }}, {"hard link", "entry", func(t *testing.T, l *provider.Launch) { os.Link(filepath.Join(l.ResearchDir, "img-1.png"), filepath.Join(t.TempDir(), "elsewhere")) }}, {"inside the workspace", "overlap", func(t *testing.T, l *provider.Launch) { dir := filepath.Join(l.Workspace, "research") os.Mkdir(dir, 0700) l.ResearchDir = dir }}, {"is the workspace", "overlap", func(t *testing.T, l *provider.Launch) { l.ResearchDir = l.Workspace }}, {"inside the scratch root", "overlap", func(t *testing.T, l *provider.Launch) { dir := filepath.Join(m.cfg.ScratchRoot, "research") os.Mkdir(dir, 0700) l.ResearchDir = dir }}, } { t.Run(c.name, func(t *testing.T) { l := withAction(t, m, base, "implement") ws := filepath.Join(t.TempDir(), "workspace") os.Mkdir(ws, 0700) l.Workspace = ws l.ResearchDir = researchDir(t) c.setup(t, &l) plan, err := m.mountPlan(l, attemptDir(t, m)) if err == nil { plan.close() t.Fatal("research directory accepted") } if !errors.Is(err, errMount) || !strings.Contains(err.Error(), c.reason) { t.Fatalf("refused for the wrong reason: %v (want %q)", err, c.reason) } }) } }