oficina / equipo Public

Clone
git clone https://amadan.net/oficina/equipo

Plain git — no account needed to clone.

Download

Download this file

1//go:build linux
2
3package containment
4
5import (
6 "context"
7 "crypto/sha256"
8 "encoding/hex"
9 "errors"
10 "fmt"
11 "io"
12 "net"
13 "os"
14 "path/filepath"
15 "slices"
16 "strings"
17 "syscall"
18 "testing"
19
20 "amadan.net/oficina/equipo/internal/runner/provider"
21)
22
23// withAction gives the fixture launch a hand-built manifest for action,
24// certifying bubblewrap as the real launches do.
25func withAction(t *testing.T, m *Manager, l provider.Launch, action string) provider.Launch {
26 t.Helper()
27 raw, err := os.ReadFile(m.cfg.Binary)
28 if err != nil {
29 t.Fatal(err)
30 }
31 bwrap := sha256.Sum256(raw)
32 l.Policy.Manifest = []byte(fmt.Sprintf(`{"Action":%q,"Files":[{"Mount":{"Source":%q},"SHA256":%q}]}`, action, m.cfg.Binary, hex.EncodeToString(bwrap[:])))
33 l.Policy.ManifestHash = provider.ManifestDigest(l.Policy.Manifest)
34 return l
35}
36
37func attemptDir(t *testing.T, m *Manager) string {
38 t.Helper()
39 dir, err := os.MkdirTemp(m.cfg.ScratchRoot, "attempt-")
40 if err != nil {
41 t.Fatal(err)
42 }
43 t.Cleanup(func() { os.RemoveAll(dir) })
44 for _, name := range []string{"tmp", "home"} {
45 if err = os.Mkdir(filepath.Join(dir, name), 0700); err != nil {
46 t.Fatal(err)
47 }
48 }
49 return dir
50}
51
52// toolSocket makes a runner-style per-attempt tool socket.
53func toolSocket(t *testing.T) string {
54 t.Helper()
55 dir := t.TempDir()
56 if err := os.Chmod(dir, 0700); err != nil {
57 t.Fatal(err)
58 }
59 fd, err := os.Open(dir)
60 if err != nil {
61 t.Fatal(err)
62 }
63 t.Cleanup(func() { fd.Close() })
64 ln, err := net.ListenUnix("unix", &net.UnixAddr{Name: fmt.Sprintf("/proc/self/fd/%d/equipo.sock", fd.Fd()), Net: "unix"})
65 if err != nil {
66 t.Fatal(err)
67 }
68 t.Cleanup(func() { ln.Close() })
69 path := filepath.Join(dir, "equipo.sock")
70 if err = os.Chmod(path, 0600); err != nil {
71 t.Fatal(err)
72 }
73 return path
74}
75
76// runPlanned runs argv in the namespace mountPlan gives l, and returns
77// its standard output.
78func runPlanned(t *testing.T, m *Manager, l provider.Launch, argv []string, id string) string {
79 t.Helper()
80 dir := attemptDir(t, m)
81 plan, err := m.mountPlan(l, dir)
82 if err != nil {
83 t.Fatal(err)
84 }
85 if _, err = m.namespaceManifest(l, argv, l.Policy.Hash, dir, plan); err != nil {
86 plan.close()
87 t.Fatal(err)
88 }
89 boot, err := bootID()
90 if err != nil {
91 t.Fatal(err)
92 }
93 r := Record{ID: id, BootID: boot, AttemptKey: l.AttemptKey, ManifestHash: l.Policy.Hash}
94 if err = m.persist(r); err != nil {
95 t.Fatal(err)
96 }
97 result := make(chan startResult, 1)
98 go m.lifecycle(context.Background(), r, argv, plan, dir, result, nil, false)
99 started := <-result
100 if started.err != nil {
101 t.Fatal(started.err)
102 }
103 p := started.p
104 p.Stdin().Close()
105 errOut := make(chan []byte, 1)
106 go func() { b, _ := io.ReadAll(p.Stderr()); errOut <- b }()
107 out, err := io.ReadAll(p.Stdout())
108 if err != nil {
109 t.Fatal(err)
110 }
111 if _, err := p.Wait(context.Background()); err != nil {
112 t.Fatal(err)
113 }
114 if stderr := <-errOut; len(stderr) > 0 {
115 t.Logf("stderr: %s", stderr)
116 }
117 p.Stdout().Close()
118 p.Stderr().Close()
119 return string(out)
120}
121
122// A Research step's namespace (spec §4): /etc is a fresh tmpfs holding
123// only the host CA bundle, passwd and group stubs and the masked
124// provider directories, never the host /etc; /workspace is the runner's
125// empty scratch directory, writable; nothing else of the runner's
126// state but its tool socket.
127func TestNamespaceResearchMinimalEtc(t *testing.T) {
128 m, l := fixture(t)
129 l = withAction(t, m, l, provider.ResearchStepAction)
130 l.ToolSocket = toolSocket(t)
131 host, err := filepath.EvalSymlinks(hostCABundle)
132 if err != nil {
133 t.Skip("no host CA bundle")
134 }
135 raw, err := os.ReadFile(host)
136 if err != nil {
137 t.Fatal(err)
138 }
139 ca := sha256.Sum256(raw)
140 script := `import os, pwd, grp, hashlib
141seen = []
142for root, dirs, files in os.walk("/"):
143 if root == "/":
144 dirs[:] = [d for d in dirs if d not in ("proc", "sys", "dev", "usr")]
145 seen += [os.path.join(root, n) for n in dirs + files]
146print(sorted(seen))
147print(pwd.getpwuid(os.getuid()).pw_name, grp.getgrgid(os.getgid()).gr_name)
148print(hashlib.sha256(open("/etc/ssl/certs/ca-certificates.crt", "rb").read()).hexdigest())
149print(os.listdir("/workspace"))
150open("/workspace/notes.txt", "w").write("x")
151print(os.listdir("/workspace"))
152for path in ("/etc/hosts", "/etc/passwd"):
153 try:
154 open(path, "a").write("x")
155 print("wrote", path)
156 except OSError as e:
157 print("refused", e.errno)
158`
159 out := runPlanned(t, m, l, []string{"/usr/bin/python3", "-u", "-c", script}, "01234567890123456789012345678911")
160 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"}
161 quoted := make([]string, len(tree))
162 for i, p := range tree {
163 quoted[i] = "'" + p + "'"
164 }
165 want := "[" + strings.Join(quoted, ", ") + "]\n" +
166 "runner runner\n" +
167 hex.EncodeToString(ca[:]) + "\n" +
168 "[]\n['notes.txt']\n" +
169 "refused 30\nrefused 30\n"
170 if out != want {
171 t.Fatalf("research namespace:\n%s\nwant\n%s", out, want)
172 }
173 if entries, _ := os.ReadDir(l.Workspace); len(entries) != 1 || entries[0].Name() != "notes.txt" {
174 t.Fatalf("scratch workspace after the step: %v", entries)
175 }
176}
177
178// The plan itself: no host /etc overlay, a tmpfs /etc, the masked
179// directories kept; a workspace that is not empty is refused.
180func TestResearchMountPlan(t *testing.T) {
181 m, l := fixture(t)
182 l = withAction(t, m, l, provider.ResearchStepAction)
183 dir := attemptDir(t, m)
184 plan, err := m.mountPlan(l, dir)
185 if err != nil {
186 t.Fatal(err)
187 }
188 defer plan.close()
189 args := strings.Join(plan.args, " ")
190 if slices.Contains(plan.args, "--overlay-src") || slices.Contains(plan.args, "--tmp-overlay") || strings.Contains(args, "--ro-bind /etc") {
191 t.Fatalf("host /etc reaches a research step: %s", args)
192 }
193 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 "} {
194 if !strings.Contains(args+" ", want) {
195 t.Fatalf("plan lacks %q: %s", want, args)
196 }
197 }
198 if strings.Index(args, "--tmpfs /etc ") > strings.Index(args, "/etc/ssl/certs/ca-certificates.crt") {
199 t.Fatal("CA bundle bound before the /etc tmpfs")
200 }
201 // A clone or a desk is never a research workspace.
202 if err := os.WriteFile(filepath.Join(l.Workspace, "README.md"), []byte("repository"), 0600); err != nil {
203 t.Fatal(err)
204 }
205 if plan, err := m.mountPlan(l, attemptDir(t, m)); err == nil {
206 plan.close()
207 t.Fatal("research step over a non-empty workspace accepted")
208 }
209 // Every other launch keeps the host /etc overlay.
210 _, other := fixture(t)
211 other = withAction(t, m, other, "implement")
212 plan2, err := m.mountPlan(other, attemptDir(t, m))
213 if err != nil {
214 t.Fatal(err)
215 }
216 defer plan2.close()
217 if !slices.Contains(plan2.args, "--overlay-src") {
218 t.Fatal("engineering lost the host /etc")
219 }
220}
221
222// The host CA bundle is resolved on the host first and the regular file
223// it names is pinned, so a symlinked bundle (the common layout) works
224// and the namespace sees a file, not a link.
225func TestResearchCABundleResolved(t *testing.T) {
226 m, l := fixture(t)
227 l = withAction(t, m, l, provider.ResearchStepAction)
228 real := filepath.Join(t.TempDir(), "bundle.pem")
229 if err := os.WriteFile(real, []byte("-----BEGIN CERTIFICATE-----\n"), 0644); err != nil {
230 t.Fatal(err)
231 }
232 link := filepath.Join(t.TempDir(), "ca-certificates.crt")
233 if err := os.Symlink(real, link); err != nil {
234 t.Fatal(err)
235 }
236 old := hostCABundle
237 hostCABundle = link
238 defer func() { hostCABundle = old }()
239 plan, err := m.mountPlan(l, attemptDir(t, m))
240 if err != nil {
241 t.Fatalf("symlinked CA bundle refused: %v", err)
242 }
243 defer plan.close()
244 found := false
245 for i, arg := range plan.args {
246 if arg == "/etc/ssl/certs/ca-certificates.crt" {
247 var fd int
248 fmt.Sscan(plan.args[i-1], &fd)
249 found = plan.files[fd-6].Name() == real
250 }
251 }
252 if !found {
253 t.Fatal("CA bundle not pinned at its resolved file")
254 }
255}
256
257// researchDir makes a runner-style kept-image directory: 0700, the
258// runner's, regular files only.
259func researchDir(t *testing.T) string {
260 t.Helper()
261 dir := filepath.Join(t.TempDir(), "research")
262 if err := os.Mkdir(dir, 0700); err != nil {
263 t.Fatal(err)
264 }
265 for name, body := range map[string]string{"img-1.png": "png bytes", "img-2.png": "more png"} {
266 if err := os.WriteFile(filepath.Join(dir, name), []byte(body), 0600); err != nil {
267 t.Fatal(err)
268 }
269 }
270 return dir
271}
272
273// Engineering and Review see kept images read-only at /research.
274func TestNamespaceResearchDirReadOnly(t *testing.T) {
275 m, l := fixture(t)
276 l = withAction(t, m, l, "implement")
277 l.ResearchDir = researchDir(t)
278 script := `import os
279print(sorted(os.listdir("/research")), open("/research/img-1.png").read())
280for path in ("/research/img-1.png", "/research/planted.png"):
281 try:
282 open(path, "a").write("x")
283 print("wrote", path)
284 except OSError as e:
285 print("refused", e.errno)
286`
287 out := runPlanned(t, m, l, []string{"/usr/bin/python3", "-u", "-c", script}, "01234567890123456789012345678912")
288 want := "['img-1.png', 'img-2.png'] png bytes\nrefused 30\nrefused 30\n"
289 if out != want {
290 t.Fatalf("/research inside the namespace:\n%s\nwant\n%s", out, want)
291 }
292 inspect := withAction(t, m, l, "inspect")
293 plan, err := m.mountPlan(inspect, attemptDir(t, m))
294 if err != nil {
295 t.Fatalf("review's /research refused: %v", err)
296 }
297 plan.close()
298}
299
300// The /research bind is refused for any launch but Engineering and
301// Review (a research step above all), and for a directory that is not
302// the runner's own flat directory of regular files.
303func TestResearchDirRefusals(t *testing.T) {
304 m, base := fixture(t)
305 type refusal struct {
306 name, reason string
307 setup func(t *testing.T, l *provider.Launch)
308 }
309 for _, c := range []refusal{
310 {"research step", "launch", func(t *testing.T, l *provider.Launch) { *l = withAction(t, m, *l, provider.ResearchStepAction) }},
311 {"coordinator", "launch", func(t *testing.T, l *provider.Launch) { *l = withAction(t, m, *l, "converse") }},
312 {"answer", "launch", func(t *testing.T, l *provider.Launch) { *l = withAction(t, m, *l, "answer") }},
313 {"no action", "launch", func(t *testing.T, l *provider.Launch) { l.Policy.Manifest, l.Policy.ManifestHash = []byte(`{}`), "" }},
314 {"tampered manifest", "launch", func(t *testing.T, l *provider.Launch) { l.Policy.ManifestHash = provider.ManifestDigest([]byte(`{}`)) }},
315 {"symlinked directory", "", func(t *testing.T, l *provider.Launch) {
316 link := filepath.Join(t.TempDir(), "research")
317 os.Symlink(l.ResearchDir, link)
318 l.ResearchDir = link
319 }},
320 {"relative path", "", func(t *testing.T, l *provider.Launch) { l.ResearchDir = "research" }},
321 {"group readable", "mode", func(t *testing.T, l *provider.Launch) { os.Chmod(l.ResearchDir, 0750) }},
322 {"world readable", "mode", func(t *testing.T, l *provider.Launch) { os.Chmod(l.ResearchDir, 0755) }},
323 {"not the runner's", "owner", func(t *testing.T, l *provider.Launch) {
324 if os.Getuid() == 0 {
325 t.Skip("the runner owns everything as root")
326 }
327 l.ResearchDir = "/var"
328 }},
329 {"subdirectory", "entry", func(t *testing.T, l *provider.Launch) { os.Mkdir(filepath.Join(l.ResearchDir, "nested"), 0700) }},
330 {"symlink entry", "entry", func(t *testing.T, l *provider.Launch) {
331 os.Symlink("/etc/hostname", filepath.Join(l.ResearchDir, "img-3.png"))
332 }},
333 {"fifo entry", "entry", func(t *testing.T, l *provider.Launch) {
334 syscall.Mkfifo(filepath.Join(l.ResearchDir, "img-3.png"), 0600)
335 }},
336 {"hard link", "entry", func(t *testing.T, l *provider.Launch) {
337 os.Link(filepath.Join(l.ResearchDir, "img-1.png"), filepath.Join(t.TempDir(), "elsewhere"))
338 }},
339 {"inside the workspace", "overlap", func(t *testing.T, l *provider.Launch) {
340 dir := filepath.Join(l.Workspace, "research")
341 os.Mkdir(dir, 0700)
342 l.ResearchDir = dir
343 }},
344 {"is the workspace", "overlap", func(t *testing.T, l *provider.Launch) { l.ResearchDir = l.Workspace }},
345 {"inside the scratch root", "overlap", func(t *testing.T, l *provider.Launch) {
346 dir := filepath.Join(m.cfg.ScratchRoot, "research")
347 os.Mkdir(dir, 0700)
348 l.ResearchDir = dir
349 }},
350 } {
351 t.Run(c.name, func(t *testing.T) {
352 l := withAction(t, m, base, "implement")
353 ws := filepath.Join(t.TempDir(), "workspace")
354 os.Mkdir(ws, 0700)
355 l.Workspace = ws
356 l.ResearchDir = researchDir(t)
357 c.setup(t, &l)
358 plan, err := m.mountPlan(l, attemptDir(t, m))
359 if err == nil {
360 plan.close()
361 t.Fatal("research directory accepted")
362 }
363 if !errors.Is(err, errMount) || !strings.Contains(err.Error(), c.reason) {
364 t.Fatalf("refused for the wrong reason: %v (want %q)", err, c.reason)
365 }
366 })
367 }
368}
369