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 "bufio"
7 "context"
8 "encoding/json"
9 "errors"
10 "fmt"
11 "io"
12 "io/fs"
13 "net"
14 "os"
15 "os/exec"
16 "path/filepath"
17 "runtime"
18 "strconv"
19 "strings"
20 "testing"
21 "time"
22
23 "amadan.net/oficina/equipo/internal/runner/provider"
24 "amadan.net/oficina/equipo/internal/testci"
25 "golang.org/x/sys/unix"
26)
27
28func fixture(t *testing.T) (*Manager, provider.Launch) {
29 t.Helper()
30 root := t.TempDir()
31 scratch := filepath.Join(root, "state")
32 if err := os.Mkdir(scratch, 0700); err != nil {
33 t.Fatal(err)
34 }
35 workspace := filepath.Join(root, "workspace")
36 if err := os.Mkdir(workspace, 0700); err != nil {
37 t.Fatal(err)
38 }
39 binary, err := os.Executable()
40 if err != nil {
41 t.Fatal(err)
42 }
43 testci.Tools(t, "bwrap", "python3")
44 m, err := New(Config{Binary: "/usr/bin/bwrap", RunnerBinary: binary, ScratchRoot: scratch})
45 if err != nil {
46 t.Fatalf("namespace capability missing: %v", err)
47 }
48 // An explicit legacy policy permits writes; a missing manifest fails closed.
49 return m, provider.Launch{AttemptKey: "attempt-fixture", Workspace: workspace, Policy: provider.Policy{Hash: "fixture-policy", Manifest: []byte(`{}`)}}
50}
51func launch(t *testing.T, m *Manager, l provider.Launch, script string) provider.Process {
52 t.Helper()
53 ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
54 t.Cleanup(cancel)
55 argv := []string{"/usr/bin/python3", "-u", "-c", script}
56 if l.Selection.Provider != "" {
57 l, argv = directPolicyFixture(t, m, l, argv)
58 }
59 p, err := m.Start(ctx, l, argv)
60 if err != nil {
61 t.Fatalf("namespace capability/start failed (userns, pidfd required): %v", err)
62 }
63 t.Cleanup(func() {
64 ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
65 defer cancel()
66 p.(*process).kill()
67 p.Wait(ctx)
68 if _, err := m.Stop(ctx, p.ID()); err != nil {
69 t.Errorf("cleanup: %v", err)
70 }
71 p.Stdin().Close()
72 p.Stdout().Close()
73 p.Stderr().Close()
74 })
75 return p
76}
77func record(t *testing.T, m *Manager, p provider.Process) Record {
78 t.Helper()
79 b, err := os.ReadFile(filepath.Join(m.cfg.ScratchRoot, p.ID()+".json"))
80 if err != nil {
81 t.Fatal(err)
82 }
83 var r Record
84 if err = json.Unmarshal(b, &r); err != nil {
85 t.Fatal(err)
86 }
87 if r.HostPID == 0 || r.StartTicks == 0 || r.NamespaceID == "" || r.ManifestHash == "" {
88 t.Fatalf("incomplete durable identity: %+v", r)
89 }
90 return r
91}
92func namespace(t *testing.T, pid int) string {
93 t.Helper()
94 n, e := os.Readlink(fmt.Sprintf("/proc/%d/ns/pid", pid))
95 if e != nil {
96 t.Fatal(e)
97 }
98 return n
99}
100func descriptor(t *testing.T, pid int) int {
101 t.Helper()
102 fd, e := unix.PidfdOpen(pid, 0)
103 if e != nil {
104 t.Fatalf("capability missing: pidfd_open: %v", e)
105 }
106 t.Cleanup(func() { unix.Close(fd) })
107 return fd
108}
109func exited(t *testing.T, fd int) {
110 t.Helper()
111 p := []unix.PollFd{{Fd: int32(fd), Events: unix.POLLIN}}
112 n, e := pollFD(p, 5*time.Second)
113 if e != nil || n != 1 || p[0].Revents&unix.POLLIN == 0 {
114 t.Fatalf("exact process has not exited: poll=%d,%v", n, e)
115 }
116}
117func ownedControl(t *testing.T) (*exec.Cmd, int) {
118 t.Helper()
119 c := exec.Command("/usr/bin/sleep", "60")
120 if e := c.Start(); e != nil {
121 t.Fatal(e)
122 }
123 fd := descriptor(t, c.Process.Pid)
124 t.Cleanup(func() { c.Process.Kill(); c.Wait() })
125 return c, fd
126}
127func alive(t *testing.T, fd int) {
128 t.Helper()
129 if e := unix.PidfdSendSignal(fd, 0, nil, 0); e != nil {
130 t.Fatalf("owned unrelated control died: %v", e)
131 }
132 p := []unix.PollFd{{Fd: int32(fd), Events: unix.POLLIN}}
133 n, e := pollFD(p, 0)
134 if e != nil || n != 0 {
135 t.Fatalf("owned unrelated control exited: %d %v", n, e)
136 }
137}
138
139// Resolve only descendants of the exact init we started, never host-wide PIDs.
140func descendants(t *testing.T, root int) []int {
141 t.Helper()
142 out := []int{root}
143 for i := 0; i < len(out); i++ {
144 tasks, e := filepath.Glob(fmt.Sprintf("/proc/%d/task/*/children", out[i]))
145 if e != nil {
146 t.Fatal(e)
147 }
148 for _, task := range tasks {
149 b, e := os.ReadFile(task)
150 if os.IsNotExist(e) {
151 continue
152 }
153 if e != nil {
154 t.Fatal(e)
155 }
156 for _, s := range strings.Fields(string(b)) {
157 pid, e := strconv.Atoi(s)
158 if e != nil {
159 t.Fatal(e)
160 }
161 out = append(out, pid)
162 }
163 }
164 }
165
166 return out
167}
168
169const detachedScript = `import os, subprocess, time
170subprocess.Popen(['/usr/bin/sleep','60'],start_new_session=True)
171pid=os.fork()
172if pid==0:
173 if os.fork()==0:
174 time.sleep(60)
175 os._exit(0)
176 os._exit(0)
177os.waitpid(pid,0)
178pid=os.fork()
179if pid==0:
180 try:
181 open('/sys/fs/cgroup/cgroup.procs','w').write(str(os.getpid()))
182 except OSError:
183 pass
184 time.sleep(60)
185 os._exit(0)
186print('ready',flush=True)
187time.sleep(60)
188`
189
190func TestNamespaceKillsDetachedChildren(t *testing.T) {
191 m, l := fixture(t)
192 _, control := ownedControl(t)
193 p := launch(t, m, l, detachedScript)
194 line, e := bufio.NewReader(p.Stdout()).ReadString('\n')
195 if e != nil || line != "ready\n" {
196 t.Fatalf("fixture readiness %q %v", line, e)
197 }
198 r := record(t, m, p)
199 if namespace(t, os.Getpid()) == r.NamespaceID {
200 t.Fatal("shared host PID namespace")
201 }
202 members := descendants(t, r.HostPID)
203 if len(members) < 5 {
204 t.Fatalf("missing detached children: %v", members)
205 }
206 var fds []int
207 for _, pid := range members {
208 if pid != r.HostPID && namespace(t, pid) != r.NamespaceID {
209 t.Fatal("namespace mismatch")
210 }
211 fds = append(fds, descriptor(t, pid))
212 }
213 proof, e := m.Stop(context.Background(), p.ID())
214 if e != nil || !proof.Verified || proof.Record != r {
215 t.Fatalf("stop proof: %+v %v", proof, e)
216 }
217 for _, fd := range fds {
218 exited(t, fd)
219 }
220 alive(t, control)
221}
222
223// noSessionReason is why the delegated cgroup test skips where there is no
224// systemd user session, as inside a MicroVM.
225const noSessionReason = "no systemd user session; production containment does not use cgroups"
226
227// cgroupSkip decides whether the delegated cgroup test runs. stat checks
228// that base, the user@UID.service cgroup, exists. Without it the test skips,
229// unless require (EQUIPO_REQUIRE_USER_SESSION=1) demands a session, when it
230// fails. Any other stat error fails too: something is there but unusable.
231func cgroupSkip(base string, stat func(string) error, require bool) (skip bool, reason string, fail bool) {
232 e := stat(base)
233 switch {
234 case e == nil:
235 return false, "", false
236 case !errors.Is(e, fs.ErrNotExist):
237 return false, fmt.Sprintf("systemd user session cgroup %s: %v", base, e), true
238 case require:
239 return false, fmt.Sprintf("EQUIPO_REQUIRE_USER_SESSION=1 but no systemd user session at %s: %v", base, e), true
240 }
241 return true, noSessionReason, false
242}
243
244func TestCgroupSessionRule(t *testing.T) {
245 const base = "/sys/fs/cgroup/user.slice/user-1000.slice/user@1000.service"
246 for _, c := range []struct {
247 name string
248 err error
249 require bool
250 skip bool
251 reason string
252 fail bool
253 }{
254 {name: "session", err: nil},
255 {name: "session required", err: nil, require: true},
256 {name: "no session", err: fs.ErrNotExist, skip: true, reason: noSessionReason},
257 {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"},
258 {name: "unreadable", err: fs.ErrPermission, fail: true, reason: "systemd user session cgroup " + base + ": permission denied"},
259 } {
260 var asked []string
261 stat := func(p string) error { asked = append(asked, p); return c.err }
262 skip, reason, fail := cgroupSkip(base, stat, c.require)
263 if skip != c.skip || reason != c.reason || fail != c.fail {
264 t.Errorf("%s: cgroupSkip = (%v, %q, %v), want (%v, %q, %v)", c.name, skip, reason, fail, c.skip, c.reason, c.fail)
265 }
266 if len(asked) != 1 || asked[0] != base {
267 t.Errorf("%s: stat asked %q, want [%q]", c.name, asked, base)
268 }
269 }
270}
271
272func TestNamespaceCgroupMoveKeepsMembership(t *testing.T) {
273 base := fmt.Sprintf("/sys/fs/cgroup/user.slice/user-%d.slice/user@%d.service", os.Getuid(), os.Getuid())
274 stat := func(p string) error { _, e := os.Stat(p); return e }
275 switch skip, reason, fail := cgroupSkip(base, stat, os.Getenv("EQUIPO_REQUIRE_USER_SESSION") == "1"); {
276 case fail:
277 t.Fatal(reason)
278 case skip:
279 t.Skip(reason)
280 }
281 if _, e := os.ReadFile(filepath.Join(base, "cgroup.subtree_control")); e != nil {
282 t.Fatalf("capability missing: delegated cgroup subtree: %v", e)
283 }
284 a, e := os.MkdirTemp(base, "equipo-task2-")
285 if e != nil {
286 t.Fatalf("capability missing: writable delegated cgroup subtree: %v", e)
287 }
288 t.Cleanup(func() {
289 if e := os.Remove(a); e != nil {
290 t.Errorf("remove test cgroup: %v", e)
291 }
292 })
293 b := filepath.Join(a, "destination")
294 if e = os.Mkdir(b, 0700); e != nil {
295 t.Fatal(e)
296 }
297 t.Cleanup(func() {
298 if e := os.Remove(b); e != nil {
299 t.Errorf("remove test cgroup: %v", e)
300 }
301 })
302 // Make two leaf cgroups, keeping the test's parent empty.
303 source := filepath.Join(a, "source")
304 if e = os.Mkdir(source, 0700); e != nil {
305 t.Fatal(e)
306 }
307 t.Cleanup(func() {
308 if e := os.Remove(source); e != nil {
309 t.Errorf("remove test cgroup: %v", e)
310 }
311 })
312 m, l := fixture(t)
313 p := launch(t, m, l, "import time; print('ready',flush=True); time.sleep(60)")
314 if _, e = bufio.NewReader(p.Stdout()).ReadString('\n'); e != nil {
315 t.Fatal(e)
316 }
317 r := record(t, m, p)
318 children := descendants(t, r.HostPID)
319 if len(children) < 2 {
320 t.Fatal("missing harness")
321 }
322 pid := children[1]
323 fd := descriptor(t, pid)
324 before := namespace(t, pid)
325 for _, dir := range []string{source, b} {
326 if e = os.WriteFile(filepath.Join(dir, "cgroup.procs"), []byte(strconv.Itoa(pid)), 0600); e != nil {
327 t.Fatalf("capability missing: authorized cgroup move: %v", e)
328 }
329 actual, e := os.ReadFile(fmt.Sprintf("/proc/%d/cgroup", pid))
330 if e != nil || !strings.Contains(string(actual), filepath.Base(a)+"/"+filepath.Base(dir)) {
331 t.Fatalf("move not observed: %s %v", actual, e)
332 }
333 }
334 if namespace(t, pid) != before {
335 t.Fatal("cgroup move changed PID namespace")
336 }
337 if _, e = m.Stop(context.Background(), p.ID()); e != nil {
338 t.Fatal(e)
339 }
340 exited(t, fd)
341}
342func TestNamespaceHidesHostControl(t *testing.T) {
343 home, e := os.UserHomeDir()
344 if e != nil {
345 t.Fatal(e)
346 }
347 m, l := fixture(t)
348 listener, e := net.Listen("tcp", "127.0.0.1:0")
349 if e != nil {
350 t.Fatal(e)
351 }
352 defer listener.Close()
353 socket, e := net.Listen("unix", filepath.Join(t.TempDir(), "control.sock"))
354 if e != nil {
355 t.Fatal(e)
356 }
357 defer socket.Close()
358 // Deliberately make an owned socket inheritable in the launching process.
359 file, e := socket.(*net.UnixListener).File()
360 if e != nil {
361 t.Fatal(e)
362 }
363 defer file.Close()
364 if _, e = unix.FcntlInt(file.Fd(), unix.F_SETFD, 0); e != nil {
365 t.Fatal(e)
366 }
367 l.Policy.Env = map[string]string{"LANG": "C.UTF-8"}
368 t.Setenv("EQUIPO_TEST_HOST_SECRET", "must-not-inherit")
369 p := launch(t, m, l, fmt.Sprintf(`import os,socket,json
370paths=['/sys/fs/cgroup','/run/user/%d/bus','/run/user/%d/systemd/private',%s,%s,'/etc/claude-code/managed-settings.json','/etc/codex/config.toml']
371assert all(not os.path.exists(p) for p in paths), paths
372assert os.listdir('/home')==['runner']
373assert 'EQUIPO_TEST_HOST_SECRET' not in os.environ
374assert os.getppid()==1
375assert int([l for l in open('/proc/self/status') if l.startswith('CapEff:')][0].split()[1],16)==0
376assert open('/proc/1/comm').read().strip()!='python3'
377assert 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))
378s=socket.socket(); assert s.connect_ex(('127.0.0.1',%d))!=0
379try:
380 open('/sys/fs/cgroup/cgroup.procs','w').write(str(os.getpid()))
381 raise AssertionError('cgroup exposed')
382except OSError: pass
383print('isolated')
384`, os.Getuid(), os.Getuid(), strconv.Quote(home), strconv.Quote("/proc/1/root"+home), listener.Addr().(*net.TCPAddr).Port))
385 output, e := io.ReadAll(p.Stdout())
386 if e != nil {
387 t.Fatal(e)
388 }
389 exit, e := p.Wait(context.Background())
390 if e != nil || exit.Code != 0 || string(output) != "isolated\n" {
391 errout, _ := io.ReadAll(p.Stderr())
392 t.Fatalf("isolation: %s %+v %v %s", output, exit, e, errout)
393 }
394}
395func TestNamespacePidfdCapability(t *testing.T) {
396 c, fd := ownedControl(t)
397 if e := unix.PidfdSendSignal(fd, unix.SIGKILL, nil, 0); e != nil {
398 t.Fatalf("capability missing: pidfd_send_signal: %v", e)
399 }
400 var info unix.Siginfo
401 if e := unix.Waitid(unix.P_PIDFD, fd, &info, unix.WEXITED|unix.WNOWAIT, nil); e != nil {
402 t.Fatalf("capability missing: waitid(P_PIDFD): %v", e)
403 }
404 exited(t, fd)
405 _ = c
406}
407
408func parentFixture() {
409 runtime.LockOSThread()
410 // os.Executable, not os.Args[0]: the binary may be started by a relative path.
411 binary, e := os.Executable()
412 if e != nil {
413 panic(e)
414 }
415 m, e := New(Config{Binary: "/usr/bin/bwrap", RunnerBinary: binary, ScratchRoot: os.Getenv("EQUIPO_TEST_STATE")})
416 if e != nil {
417 panic(e)
418 }
419 l := provider.Launch{AttemptKey: "parent-death", Workspace: os.Getenv("EQUIPO_TEST_WORKSPACE"), Policy: provider.Policy{Hash: "parent-policy"}}
420 p, e := m.Start(context.Background(), l, []string{"/usr/bin/python3", "-u", "-c", detachedScript})
421 if e != nil {
422 panic(e)
423 }
424 if _, e = bufio.NewReader(p.Stdout()).ReadString('\n'); e != nil {
425 panic(e)
426 }
427 b, e := os.ReadFile(filepath.Join(m.cfg.ScratchRoot, p.ID()+".json"))
428 if e != nil {
429 panic(e)
430 }
431 fmt.Println(string(b))
432 select {}
433}
434func TestNamespaceParentDeath(t *testing.T) {
435 m, l := fixture(t)
436 c := exec.Command(os.Args[0])
437 c.Env = append(os.Environ(), "EQUIPO_NAMESPACE_PARENT_TEST=1", "EQUIPO_TEST_STATE="+m.cfg.ScratchRoot, "EQUIPO_TEST_WORKSPACE="+l.Workspace)
438 stdout, e := c.StdoutPipe()
439 if e != nil {
440 t.Fatal(e)
441 }
442 c.Stderr = os.Stderr
443 if e = c.Start(); e != nil {
444 t.Fatal(e)
445 }
446 t.Cleanup(func() { c.Process.Kill(); c.Wait() })
447 var r Record
448 if e = json.NewDecoder(stdout).Decode(&r); e != nil {
449 t.Fatalf("launcher fixture: %v", e)
450 }
451 members := descendants(t, r.HostPID)
452 var fds []int
453 for _, pid := range members {
454 fds = append(fds, descriptor(t, pid))
455 }
456 t.Cleanup(func() {
457 if len(fds) > 0 {
458 unix.PidfdSendSignal(fds[0], unix.SIGKILL, nil, 0)
459 }
460 })
461 if e = c.Process.Kill(); e != nil {
462 t.Fatal(e)
463 }
464 for _, fd := range fds {
465 exited(t, fd)
466 }
467}
468func TestNamespaceStartingThreadExit(t *testing.T) {
469 m, l := fixture(t)
470 done := make(chan provider.Process, 1)
471 go func() {
472 runtime.LockOSThread()
473 p, e := m.Start(context.Background(), l, []string{"/usr/bin/sleep", "60"})
474 if e != nil {
475 done <- nil
476 return
477 }
478 done <- p
479 }()
480 p := <-done
481 if p == nil {
482 t.Fatal("start failed")
483 }
484 defer m.Stop(context.Background(), p.ID())
485 r := record(t, m, p)
486 fd := descriptor(t, r.HostPID)
487 time.Sleep(50 * time.Millisecond)
488 alive(t, fd)
489}
490
491func TestNamespaceStartupFailure(t *testing.T) {
492 m, l := fixture(t)
493 // The helper cannot acknowledge PID 1, so no process is returned and no
494 // harness side effect is possible. The incomplete intent remains durable.
495 cfg := m.cfg
496 cfg.RunnerBinary = "/usr/bin/true"
497 m, err := New(cfg)
498 if err != nil {
499 return // An unrelated helper is rejected before startup.
500 }
501 p, e := m.Start(context.Background(), l, []string{"/usr/bin/touch", "/workspace/prompt-sent"})
502 if e == nil || p != nil {
503 t.Fatal("missing readiness accepted")
504 }
505 if _, e = os.Stat(filepath.Join(l.Workspace, "prompt-sent")); !os.IsNotExist(e) {
506 t.Fatal("harness ran before readiness")
507 }
508 entries, e := os.ReadDir(m.cfg.ScratchRoot)
509 if e != nil {
510 t.Fatal(e)
511 }
512 if len(entries) != 2 {
513 t.Fatalf("startup intent or exit proof missing: %v", entries)
514 }
515 records, e := m.Records(context.Background())
516 if e != nil || len(records) != 1 {
517 t.Fatalf("startup records: %v %v", records, e)
518 }
519 proof, e := m.Recover(context.Background(), records[0])
520 if e != nil || !proof.Verified || proof.Exit.ObservedAt.IsZero() {
521 t.Fatalf("failed startup was not proven contained: %+v %v", proof, e)
522 }
523}
524func TestNamespaceIntentBeforeFork(t *testing.T) {
525 m, l := fixture(t)
526 marker := filepath.Join(l.Workspace, "intent-observed")
527 shim := filepath.Join(filepath.Dir(l.Workspace), "inspect-intent")
528 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"
529 if e := os.WriteFile(shim, []byte(script), 0700); e != nil {
530 t.Fatal(e)
531 }
532 m.cfg.Binary = shim
533 if p, e := m.Start(context.Background(), l, []string{"/usr/bin/true"}); e == nil {
534 m.Stop(context.Background(), p.ID())
535 t.Fatal("shim acknowledged readiness")
536 }
537 if b, e := os.ReadFile(marker); e != nil || string(b) != "intent" {
538 t.Fatalf("no durable intent before fork: %q %v", b, e)
539 }
540}
541func TestNamespaceStopWaitsForExit(t *testing.T) {
542 m, l := fixture(t)
543 p := launch(t, m, l, "import time; time.sleep(60)")
544 r := record(t, m, p)
545 fd := descriptor(t, r.HostPID)
546 proof, e := m.Stop(context.Background(), p.ID())
547 if e != nil || !proof.Verified {
548 t.Fatalf("stop: %+v %v", proof, e)
549 }
550 polls := []unix.PollFd{{Fd: int32(fd), Events: unix.POLLIN}}
551 n, e := pollFD(polls, 0)
552 if e != nil || n != 1 {
553 t.Fatal("stop acknowledged before exact init exit")
554 }
555 b, e := os.ReadFile(filepath.Join(m.cfg.ScratchRoot, p.ID()+".exit.json"))
556 if e != nil {
557 t.Fatal(e)
558 }
559 var saved Proof
560 if e = json.Unmarshal(b, &saved); e != nil || saved.Record != proof.Record || saved.Exit != proof.Exit || !saved.Verified {
561 t.Fatalf("exit proof not durable: %s %v", b, e)
562 }
563}
564func TestNamespaceExitStatus(t *testing.T) {
565 for _, script := range []string{"import sys; sys.exit(137)", "import os,signal; os.kill(os.getpid(),signal.SIGTERM)"} {
566 m, l := fixture(t)
567 p := launch(t, m, l, script)
568 exit, e := p.Wait(context.Background())
569 if e != nil {
570 t.Fatal(e)
571 }
572 if strings.Contains(script, "137") {
573 if exit.Code != 137 || exit.Signal != 0 {
574 t.Fatalf("numeric exit fabricated signal: %+v", exit)
575 }
576 } else if exit.Code != -1 || exit.Signal != int(unix.SIGTERM) {
577 t.Fatalf("signal outcome: %+v", exit)
578 }
579 }
580}
581func TestNamespaceSocketImport(t *testing.T) {
582 m, l := fixture(t)
583 listener, e := net.Listen("unix", filepath.Join(l.Workspace, "service.sock"))
584 if e != nil {
585 t.Fatal(e)
586 }
587 defer listener.Close()
588 p, e := m.Start(context.Background(), l, []string{"/usr/bin/true"})
589 if e == nil {
590 m.Stop(context.Background(), p.ID())
591 t.Fatal("host socket imported")
592 }
593}
594func TestNamespaceNestedUserNamespace(t *testing.T) {
595 m, l := fixture(t)
596 p := launch(t, m, l, "import subprocess; subprocess.run(['/usr/bin/bwrap','--unshare-user','--ro-bind','/','/','--','/usr/bin/true'],check=True)")
597 exit, e := p.Wait(context.Background())
598 if e != nil || exit.Code != 0 {
599 b, _ := io.ReadAll(p.Stderr())
600 t.Fatalf("nested sandbox unavailable: %+v %v %s", exit, e, b)
601 }
602}
603
604func TestNamespaceHelperProtocolPrivate(t *testing.T) {
605 m, l := fixture(t)
606 p := launch(t, m, l, `import os
607try:
608 fd=os.open('/proc/1/fd/5',os.O_WRONLY)
609except OSError:
610 print('private')
611else:
612 os.close(fd)
613 raise AssertionError('harness can forge helper outcome')
614`)
615 exit, e := p.Wait(context.Background())
616 if e != nil || exit.Code != 0 {
617 t.Fatalf("helper pipe exposed: %+v %v", exit, e)
618 }
619}
620
621func TestNamespaceHelperBarrier(t *testing.T) {
622 m, l := fixture(t)
623 runtime.LockOSThread()
624 defer runtime.UnlockOSThread()
625 statusR, statusW, e := os.Pipe()
626 if e != nil {
627 t.Fatal(e)
628 }
629 defer statusR.Close()
630 defer statusW.Close()
631 releaseR, releaseW, e := os.Pipe()
632 if e != nil {
633 t.Fatal(e)
634 }
635 defer releaseR.Close()
636 defer releaseW.Close()
637 readyR, readyW, e := os.Pipe()
638 if e != nil {
639 t.Fatal(e)
640 }
641 defer readyR.Close()
642 defer readyW.Close()
643 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")
644 c.ExtraFiles = []*os.File{statusW, releaseR, readyW}
645 c.Stderr = os.Stderr
646 if e = c.Start(); e != nil {
647 t.Fatal(e)
648 }
649 defer func() { c.Process.Kill(); c.Wait() }()
650 statusW.Close()
651 releaseR.Close()
652 readyW.Close()
653 var status struct {
654 PID int `json:"child-pid"`
655 }
656 if e = json.NewDecoder(statusR).Decode(&status); e != nil {
657 t.Fatal(e)
658 }
659 var ready readiness
660 if e = json.NewDecoder(readyR).Decode(&ready); e != nil || ready.PID != 1 {
661 t.Fatalf("helper topology: %+v %v", ready, e)
662 }
663 time.Sleep(30 * time.Millisecond)
664 marker := filepath.Join(l.Workspace, "released")
665 if _, e = os.Stat(marker); !os.IsNotExist(e) {
666 t.Fatal("harness started before release")
667 }
668 if _, e = releaseW.Write([]byte{1}); e != nil {
669 t.Fatal(e)
670 }
671 if e = c.Wait(); e != nil {
672 t.Fatal(e)
673 }
674 if _, e = os.Stat(marker); e != nil {
675 t.Fatal("released harness never ran")
676 }
677}
678func TestNamespaceReapsOrphans(t *testing.T) {
679 m, l := fixture(t)
680 p := launch(t, m, l, `import os,time
681pid=os.fork()
682if pid==0:
683 if os.fork()==0:
684 open('/workspace/orphan','w').write(str(os.getpid()))
685 time.sleep(.05)
686 os._exit(0)
687 os._exit(0)
688os.waitpid(pid,0)
689while not os.path.exists('/workspace/orphan'): time.sleep(.001)
690orphan=open('/workspace/orphan').read()
691while not orphan:
692 time.sleep(.001)
693 orphan=open('/workspace/orphan').read()
694for i in range(1000):
695 if not os.path.exists('/proc/'+orphan): break
696 time.sleep(.001)
697else: raise AssertionError('orphan remains a zombie')
698`)
699 exit, e := p.Wait(context.Background())
700 if e != nil || exit.Code != 0 {
701 t.Fatalf("orphan not reaped: %+v %v", exit, e)
702 }
703}
704
705func TestNamespaceCancellation(t *testing.T) {
706 m, l := fixture(t)
707 ctx, cancel := context.WithCancel(context.Background())
708 defer cancel()
709 p, e := m.Start(ctx, l, []string{"/usr/bin/sleep", "60"})
710 if e != nil {
711 t.Fatal(e)
712 }
713 defer p.Stdin().Close()
714 defer p.Stdout().Close()
715 defer p.Stderr().Close()
716 t.Cleanup(func() { p.(*process).kill(); p.Wait(context.Background()) })
717 r := record(t, m, p)
718 fd := descriptor(t, r.HostPID)
719 cancel()
720 wait, cancelWait := context.WithTimeout(context.Background(), 2*time.Second)
721 defer cancelWait()
722 if _, e = p.Wait(wait); e != nil {
723 t.Fatal(e)
724 }
725 exited(t, fd)
726}
727
728func TestNamespaceConcreteManifestHash(t *testing.T) {
729 m, l := fixture(t)
730 p := launch(t, m, l, "pass")
731 r := record(t, m, p)
732 if r.ManifestHash == l.Policy.Hash {
733 t.Fatal("policy hash substituted for concrete manifest hash")
734 }
735}
736
737func TestNamespaceManifestInputs(t *testing.T) {
738 m, l := fixture(t)
739 plan := &mounts{args: []string{"--bind-fd", "6", "/workspace"}}
740 first, e := m.namespaceManifest(l, []string{"/usr/bin/true"}, "launch", "/scratch/attempt-one", plan)
741 if e != nil {
742 t.Fatal(e)
743 }
744 for _, kind := range []string{"argv", "mount", "scratch", "binary"} {
745 t.Run(kind, func(t *testing.T) {
746 args := []string{"/usr/bin/true"}
747 dir := "/scratch/attempt-one"
748 p := *plan
749 manager := &Manager{cfg: m.cfg, namespaceDigest: m.namespaceDigest}
750 switch kind {
751 case "argv":
752 args = []string{"/usr/bin/false"}
753 case "mount":
754 p.args = []string{"--ro-bind-fd", "6", "/workspace"}
755 case "scratch":
756 dir = "/scratch/attempt-two"
757 case "binary":
758 manager.cfg.RunnerBinary = "/usr/bin/true"
759 }
760 next, e := manager.namespaceManifest(l, args, "launch", dir, &p)
761 if kind == "binary" {
762 if e == nil {
763 t.Fatal("changed namespace executable accepted")
764 }
765 return
766 }
767 if e != nil {
768 t.Fatal(e)
769 }
770 if first == next {
771 t.Fatal("constructed namespace input not hashed")
772 }
773 })
774 }
775}
776
777func TestNamespaceProviderRequiresManifest(t *testing.T) {
778 m, l := fixture(t)
779 l.Selection.Provider = "claude"
780 p, e := m.Start(context.Background(), l, []string{"/usr/bin/true"})
781 if e == nil {
782 p.(*process).kill()
783 p.Wait(context.Background())
784 p.Stdin().Close()
785 p.Stdout().Close()
786 p.Stderr().Close()
787 t.Fatal("provider launch without manifest forked")
788 }
789 if e != errStartup {
790 t.Fatalf("missing manifest passed admission: %v", e)
791 }
792 entries, e := os.ReadDir(m.cfg.ScratchRoot)
793 if e != nil {
794 t.Fatal(e)
795 }
796 if len(entries) != 0 {
797 t.Fatal("unattested provider launch created attempt state")
798 }
799}
800
801func TestNamespaceDirectPolicy(t *testing.T) {
802 m, l := egressFixture(t)
803 p := launch(t, m, l, `import os
804assert not os.path.exists('/home/runner/equipo-settings.json')
805try:
806 open('/config/equipo-settings.json','w').write('{}')
807 raise AssertionError('config writable')
808except OSError:
809 pass
810print('direct-running',flush=True)
811`)
812 raw, e := io.ReadAll(p.Stdout())
813 if e != nil {
814 t.Fatal(e)
815 }
816 exit, e := p.Wait(context.Background())
817 if e != nil || exit.Code != 0 || string(raw) != "direct-running\n" {
818 errout, _ := io.ReadAll(p.Stderr())
819 t.Fatalf("direct namespace failed: %s %v %v %s", raw, exit, e, errout)
820 }
821 r := record(t, m, p)
822 if r.ManifestHash == r.PolicyHash {
823 t.Fatal("direct manifest not concrete")
824 }
825}
826func TestNamespaceDirectPolicySwapBeforePin(t *testing.T) {
827 m, l := egressFixture(t)
828 l, argv := directPolicyFixture(t, m, l, []string{"/usr/bin/true"})
829 called := false
830 m.beforePin = func() {
831 called = true
832 for _, mount := range l.Policy.Mounts {
833 if mount.Target == provider.SettingsPath {
834 replacement := mount.Source + "-replacement"
835 if e := os.WriteFile(replacement, []byte(`{"changed":true}`), 0600); e != nil {
836 t.Fatal(e)
837 }
838 if e := os.Rename(replacement, mount.Source); e != nil {
839 t.Fatal(e)
840 }
841 }
842 }
843 }
844 p, e := m.Start(context.Background(), l, argv)
845 if e == nil {
846 p.(*process).kill()
847 p.Wait(context.Background())
848 p.Stdin().Close()
849 p.Stdout().Close()
850 p.Stderr().Close()
851 t.Fatal("swapped settings reached namespace")
852 }
853 if !called {
854 t.Fatal("did not reach attestation-to-pin boundary")
855 }
856 if e != provider.ErrPolicy {
857 t.Fatalf("unexpected refusal: %v", e)
858 }
859}
860
861func TestNamespaceDirectPolicyAdmission(t *testing.T) {
862 for _, kind := range []string{"runner", "bwrap", "argv", "env", "mount"} {
863 t.Run(kind, func(t *testing.T) {
864 m, l := egressFixture(t)
865 l, argv := directPolicyFixture(t, m, l, []string{"/usr/bin/true"})
866 switch kind {
867 case "runner":
868 m.cfg.RunnerBinary = "/usr/bin/false"
869 case "bwrap":
870 m.cfg.Binary = "/usr/bin/false"
871 case "argv":
872 argv = append(argv, "unexpected")
873 case "env":
874 l.Policy.Env["LANG"] = "changed"
875 case "mount":
876 l.Policy.Mounts[0].Target = "/opt/other"
877 }
878 reached := false
879 m.beforePin = func() { reached = true }
880 before, err := os.ReadDir(m.cfg.ScratchRoot)
881 if err != nil {
882 t.Fatal(err)
883 }
884 p, e := m.Start(context.Background(), l, argv)
885 if e == nil {
886 p.(*process).kill()
887 p.Wait(context.Background())
888 p.Stdin().Close()
889 p.Stdout().Close()
890 p.Stderr().Close()
891 t.Fatal("changed direct launch accepted")
892 }
893 if kind == "runner" {
894 if !reached || e != errStartup {
895 t.Fatalf("changed namespace executable bypassed pinned digest check: reached=%v err=%v", reached, e)
896 }
897 } else if reached {
898 t.Fatal("changed direct launch passed attestation")
899 }
900 entries, err := os.ReadDir(m.cfg.ScratchRoot)
901 if err != nil || len(entries) != len(before) {
902 t.Fatalf("changed direct launch created attempt state: %v %v", entries, err)
903 }
904 })
905 }
906}
907