//go:build linux package containment import ( "context" "encoding/json" "fmt" "golang.org/x/mod/sumdb/dirhash" "io" "net" "os" "os/exec" "path/filepath" "runtime" "strings" "testing" "time" "amadan.net/oficina/equipo/internal/runner/provider" "amadan.net/oficina/equipo/internal/runner/provider/codex" "amadan.net/oficina/equipo/internal/testci" "crypto/sha256" ) func engineeringGoPolicy(t *testing.T, m *Manager, l provider.Launch, script string, missing ...bool) (provider.Launch, []string, string) { t.Helper() mods := t.TempDir() for name, body := range map[string]string{"go.mod": "module fixture.invalid/app\n\ngo 1.26\n\nrequire fixture.invalid/cached v1.0.0\n", "app_test.go": "package app\nimport (\"testing\"; dep \"fixture.invalid/cached\")\nfunc TestCached(t *testing.T) { if dep.Value != 42 { t.Fatal(dep.Value) } }\n"} { if err := os.WriteFile(filepath.Join(l.Workspace, name), []byte(body), 0600); err != nil { t.Fatal(err) } } for name, body := range map[string]string{"fixture.invalid/cached@v1.0.0/go.mod": "module fixture.invalid/cached\n\ngo 1.26\n", "fixture.invalid/cached@v1.0.0/dep.go": "package cached\nconst Value = 42\n", "cache/download/fixture.invalid/cached/@v/v1.0.0.mod": "module fixture.invalid/cached\n\ngo 1.26\n"} { path := filepath.Join(mods, name) if err := os.MkdirAll(filepath.Dir(path), 0700); err != nil { t.Fatal(err) } if err := os.WriteFile(path, []byte(body), 0600); err != nil { t.Fatal(err) } } sum, err := dirhash.HashDir(filepath.Join(mods, "fixture.invalid/cached@v1.0.0"), "fixture.invalid/cached@v1.0.0", dirhash.Hash1) if err != nil { t.Fatal(err) } if err = os.WriteFile(filepath.Join(mods, "cache/download/fixture.invalid/cached/@v/v1.0.0.ziphash"), []byte(sum), 0600); err != nil { t.Fatal(err) } binary, err := filepath.EvalSymlinks("/usr/bin/python3") if err != nil { t.Fatal(err) } raw, err := exec.Command("go", "env", "GOROOT").Output() if err != nil { t.Fatal(err) } goroot, err := filepath.EvalSymlinks(strings.TrimSpace(string(raw))) if err != nil { t.Fatal(err) } if script == "print('must not run')" { goroot = t.TempDir() if err = os.WriteFile(filepath.Join(goroot, "VERSION"), []byte("fixture"), 0600); err != nil { t.Fatal(err) } } testci.Tools(t, "codex") codexPath, err := exec.LookPath("codex") if err != nil { t.Fatal(err) } codexPath, err = filepath.EvalSymlinks(codexPath) if err != nil { t.Fatal(err) } raw, err = os.ReadFile(codexPath) if err != nil { t.Fatal(err) } pin, _, supported := codex.ReleasePins(runtime.GOARCH) if !supported || fmt.Sprintf("%x", sha256.Sum256(raw)) != pin { t.Fatal("Codex executable pin mismatch") } codexPath = filepath.Join(t.TempDir(), "codex") if err = os.WriteFile(codexPath, raw, 0700); err != nil { t.Fatal(err) } roots := "['/opt/go','/opt/go-mod']" if len(missing) > 0 && missing[0] { roots = "['/opt/go']" } script = "import os\nfor root in " + roots + ": assert os.statvfs(root).f_flag & os.ST_RDONLY,root\n" + script argv := []string{"/opt/harness", "-u", "-c", script} in := provider.PolicyInputs{Action: "implement", RuntimeFiles: []provider.Mount{ {Source: binary, Target: "/opt/harness", ReadOnly: true}, {Source: codexPath, Target: "/opt/codex", ReadOnly: true}, {Source: m.cfg.Binary, Target: "/opt/bwrap", ReadOnly: true}, {Source: goroot, Target: "/opt/go", ReadOnly: true}, {Source: mods, Target: "/opt/go-mod", ReadOnly: true}, }, ProviderVersion: provider.ClaudeVersion, LauncherVersion: "test", BwrapVersion: "0.11.0", EgressHosts: []string{"api.anthropic.com"}, Settings: json.RawMessage(`{}`), MCP: json.RawMessage(`{}`), Workspace: l.Workspace, Scratch: t.TempDir(), Argv: argv} if len(missing) > 0 && missing[0] { in.RuntimeFiles = in.RuntimeFiles[:len(in.RuntimeFiles)-1] } l.Policy, err = provider.BuildPolicy(l.Binding, in) if err != nil { t.Fatal(err) } return l, argv, mods } func TestEngineeringOfflineGo(t *testing.T) { for _, name := range []string{"claude", "codex"} { t.Run(name, func(t *testing.T) { m, l := egressFixture(t) listener, err := net.Listen("tcp", "127.0.0.1:0") if err != nil { t.Fatal(err) } defer listener.Close() script := fmt.Sprintf(`import os,socket,subprocess expected={'GOPROXY':'off','GOSUMDB':'off','GOTOOLCHAIN':'local','MAKEFLAGS':'GOTOOLCHAIN=local','GOFLAGS':'','CGO_ENABLED':'0','GOCACHE':'/tmp/claude-'+str(os.getuid())+'/go-build','GOTMPDIR':'/tmp/claude-'+str(os.getuid())+'/go-tmp','GOROOT':'/opt/go','GOMODCACHE':'/opt/go-mod','GOENV':'off','GOWORK':'off','GOTELEMETRY':'off'} for k,v in expected.items(): assert os.environ.get(k)==v,(k,os.environ.get(k)) assert os.environ['PATH'].endswith('/opt/go/bin:/usr/bin:/bin:/opt') assert 'XDG_CONFIG_HOME' not in os.environ assert os.environ['GIT_CONFIG_GLOBAL']=='/dev/null' and os.environ['GIT_CONFIG_NOSYSTEM']=='1' subprocess.run(['go','version'],check=True) # Opening for write must fail even without changing any source bytes. for path in ['/opt/go/VERSION','/opt/go-mod/fixture.invalid/cached@v1.0.0/dep.go']: try: with open(path,'r+'): pass except OSError: pass else: raise AssertionError('writable: '+path) for root in ['/opt/go','/opt/go-mod']: assert os.statvfs(root).f_flag & os.ST_RDONLY,root try: socket.create_connection(('127.0.0.1',%d),timeout=1) except OSError: pass else: raise AssertionError('host network reachable') r=subprocess.run(['go','test','-mod=mod','-run','^TestCached$','.'],capture_output=True,text=True) assert r.returncode==0,(r.stdout,r.stderr) print(r.stdout,flush=True) os.mkdir('/workspace/missing') open('/workspace/missing/go.mod','w').write('module missing.invalid/app\n\ngo 1.26\n') open('/workspace/missing/app.go','w').write('package app\nimport _ "missing.invalid/uncached"\n') r=subprocess.run(['go','test','-mod=mod','-run','^TestMissing$','.'],cwd='/workspace/missing',capture_output=True,text=True) assert r.returncode!=0 and 'module lookup disabled by GOPROXY=off' in r.stderr,(r.returncode,r.stderr) print('offline-cache-miss',flush=True) # A pinned missing version fails at the read-only cache lock before Go's # proxy lookup. The 'downloading' progress line does not mean a fetch ran. open('/workspace/missing/go.mod','a').write('\nrequire missing.invalid/uncached v1.0.0\n') r=subprocess.run(['go','test','-mod=mod','-run','^TestMissing$','.'],cwd='/workspace/missing',capture_output=True,text=True) assert r.returncode!=0 and 'read-only file system' in r.stderr,(r.returncode,r.stderr) print('pinned-cache-miss-read-only',flush=True) `, listener.Addr().(*net.TCPAddr).Port) script = engineeringShell(t, name, script) l, argv, _ := engineeringGoPolicy(t, m, l, script) ctx, cancel := context.WithTimeout(context.Background(), 90*time.Second) defer cancel() p, err := m.Start(ctx, l, argv) if err != nil { t.Fatal(err) } defer p.Stdin().Close() defer p.Stdout().Close() defer p.Stderr().Close() out, err := io.ReadAll(p.Stdout()) if err != nil { t.Fatal(err) } stderr, _ := io.ReadAll(p.Stderr()) exit, err := p.Wait(ctx) if err != nil || exit.Code != 0 { t.Fatalf("Go probe: %+v %v\n%s\n%s", exit, err, out, stderr) } t.Log(string(out)) }) } } func TestEngineeringGoDigest(t *testing.T) { for _, target := range []string{"/opt/go", "/opt/go-mod"} { t.Run(filepath.Base(target), func(t *testing.T) { m, l := egressFixture(t) l, argv, _ := engineeringGoPolicy(t, m, l, "print('must not run')") var source string for _, mount := range l.Policy.Mounts { if mount.Target == target { source = mount.Source } } // Replace the path after attestation. Containment must bind the original // descriptor, never the replacement. Trusted in-place host edits are allowed. if err := os.WriteFile(filepath.Join(source, "original"), []byte("original"), 0600); err != nil { t.Fatal(err) } if _, err := provider.AttestLaunch(l, argv); err != nil { t.Fatal(err) } if err := os.Rename(source, source+"-old"); err != nil { t.Fatal(err) } t.Cleanup(func() { os.RemoveAll(source + "-old") }) if err := os.Mkdir(source, 0700); err != nil { t.Fatal(err) } dir := t.TempDir() for _, part := range []string{"home", "tmp"} { if err := os.Mkdir(filepath.Join(dir, part), 0700); err != nil { t.Fatal(err) } } plan, err := m.mountPlan(l, dir) if err != nil { t.Fatal(err) } defer plan.close() found := false for i, arg := range plan.args { if arg == target && i >= 2 && plan.args[i-2] == "--ro-bind-fd" { var fd int fmt.Sscanf(plan.args[i-1], "%d", &fd) path := fmt.Sprintf("/proc/self/fd/%d/original", plan.files[fd-6].Fd()) if _, err := os.Stat(path); err != nil { t.Fatal("replacement directory mounted", err) } found = true } } if !found { t.Fatal("read-only retained descriptor missing") } }) } } func TestEngineeringMissingModuleCache(t *testing.T) { for _, project := range []string{"go", "non-go"} { t.Run(project, func(t *testing.T) { m, l := egressFixture(t) script := `import os,subprocess assert not os.path.exists('/opt/go-mod') subprocess.run(['/usr/bin/bash','-c','printf non-go-ok'],check=True) ` if project == "go" { script += `open('/workspace/go.mod','w').write('module fixture.invalid/app\n\ngo 1.26\n') open('/workspace/app_test.go','w').write('package app\nimport "testing"\nfunc TestLocal(t *testing.T) {}\n') subprocess.run(['go','test','-run','^TestLocal$','.'],check=True) ` } l, argv, _ := engineeringGoPolicy(t, m, l, engineeringShell(t, "claude", script), true) ctx, cancel := context.WithTimeout(context.Background(), 45*time.Second) defer cancel() p, err := m.Start(ctx, l, argv) if err != nil { t.Fatal(err) } defer p.Stdin().Close() defer p.Stdout().Close() defer p.Stderr().Close() out, stderr := engineeringOutput(p) exit, err := p.Wait(ctx) if err != nil || exit.Code != 0 { t.Fatalf("missing cache: %+v %v %s %s", exit, err, out, stderr) } }) } }