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 "encoding/json"
8 "fmt"
9 "golang.org/x/mod/sumdb/dirhash"
10 "io"
11 "net"
12 "os"
13 "os/exec"
14 "path/filepath"
15 "runtime"
16 "strings"
17 "testing"
18 "time"
19
20 "amadan.net/oficina/equipo/internal/runner/provider"
21 "amadan.net/oficina/equipo/internal/runner/provider/codex"
22 "amadan.net/oficina/equipo/internal/testci"
23 "crypto/sha256"
24)
25
26func engineeringGoPolicy(t *testing.T, m *Manager, l provider.Launch, script string, missing ...bool) (provider.Launch, []string, string) {
27 t.Helper()
28 mods := t.TempDir()
29 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"} {
30 if err := os.WriteFile(filepath.Join(l.Workspace, name), []byte(body), 0600); err != nil {
31 t.Fatal(err)
32 }
33 }
34 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"} {
35 path := filepath.Join(mods, name)
36 if err := os.MkdirAll(filepath.Dir(path), 0700); err != nil {
37 t.Fatal(err)
38 }
39 if err := os.WriteFile(path, []byte(body), 0600); err != nil {
40 t.Fatal(err)
41 }
42 }
43 sum, err := dirhash.HashDir(filepath.Join(mods, "fixture.invalid/cached@v1.0.0"), "fixture.invalid/cached@v1.0.0", dirhash.Hash1)
44 if err != nil {
45 t.Fatal(err)
46 }
47 if err = os.WriteFile(filepath.Join(mods, "cache/download/fixture.invalid/cached/@v/v1.0.0.ziphash"), []byte(sum), 0600); err != nil {
48 t.Fatal(err)
49 }
50 binary, err := filepath.EvalSymlinks("/usr/bin/python3")
51 if err != nil {
52 t.Fatal(err)
53 }
54 raw, err := exec.Command("go", "env", "GOROOT").Output()
55 if err != nil {
56 t.Fatal(err)
57 }
58 goroot, err := filepath.EvalSymlinks(strings.TrimSpace(string(raw)))
59 if err != nil {
60 t.Fatal(err)
61 }
62 if script == "print('must not run')" {
63 goroot = t.TempDir()
64 if err = os.WriteFile(filepath.Join(goroot, "VERSION"), []byte("fixture"), 0600); err != nil {
65 t.Fatal(err)
66 }
67 }
68 testci.Tools(t, "codex")
69 codexPath, err := exec.LookPath("codex")
70 if err != nil {
71 t.Fatal(err)
72 }
73 codexPath, err = filepath.EvalSymlinks(codexPath)
74 if err != nil {
75 t.Fatal(err)
76 }
77 raw, err = os.ReadFile(codexPath)
78 if err != nil {
79 t.Fatal(err)
80 }
81 pin, _, supported := codex.ReleasePins(runtime.GOARCH)
82 if !supported || fmt.Sprintf("%x", sha256.Sum256(raw)) != pin {
83 t.Fatal("Codex executable pin mismatch")
84 }
85 codexPath = filepath.Join(t.TempDir(), "codex")
86 if err = os.WriteFile(codexPath, raw, 0700); err != nil {
87 t.Fatal(err)
88 }
89 roots := "['/opt/go','/opt/go-mod']"
90 if len(missing) > 0 && missing[0] {
91 roots = "['/opt/go']"
92 }
93 script = "import os\nfor root in " + roots + ": assert os.statvfs(root).f_flag & os.ST_RDONLY,root\n" + script
94 argv := []string{"/opt/harness", "-u", "-c", script}
95 in := provider.PolicyInputs{Action: "implement", RuntimeFiles: []provider.Mount{
96 {Source: binary, Target: "/opt/harness", ReadOnly: true},
97 {Source: codexPath, Target: "/opt/codex", ReadOnly: true},
98 {Source: m.cfg.Binary, Target: "/opt/bwrap", ReadOnly: true},
99 {Source: goroot, Target: "/opt/go", ReadOnly: true},
100 {Source: mods, Target: "/opt/go-mod", ReadOnly: true},
101 }, 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}
102 if len(missing) > 0 && missing[0] {
103 in.RuntimeFiles = in.RuntimeFiles[:len(in.RuntimeFiles)-1]
104 }
105 l.Policy, err = provider.BuildPolicy(l.Binding, in)
106 if err != nil {
107 t.Fatal(err)
108 }
109 return l, argv, mods
110}
111
112func TestEngineeringOfflineGo(t *testing.T) {
113 for _, name := range []string{"claude", "codex"} {
114 t.Run(name, func(t *testing.T) {
115 m, l := egressFixture(t)
116 listener, err := net.Listen("tcp", "127.0.0.1:0")
117 if err != nil {
118 t.Fatal(err)
119 }
120 defer listener.Close()
121 script := fmt.Sprintf(`import os,socket,subprocess
122expected={'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'}
123for k,v in expected.items(): assert os.environ.get(k)==v,(k,os.environ.get(k))
124assert os.environ['PATH'].endswith('/opt/go/bin:/usr/bin:/bin:/opt')
125assert 'XDG_CONFIG_HOME' not in os.environ
126assert os.environ['GIT_CONFIG_GLOBAL']=='/dev/null' and os.environ['GIT_CONFIG_NOSYSTEM']=='1'
127subprocess.run(['go','version'],check=True)
128# Opening for write must fail even without changing any source bytes.
129for path in ['/opt/go/VERSION','/opt/go-mod/fixture.invalid/cached@v1.0.0/dep.go']:
130 try:
131 with open(path,'r+'): pass
132 except OSError: pass
133 else: raise AssertionError('writable: '+path)
134for root in ['/opt/go','/opt/go-mod']: assert os.statvfs(root).f_flag & os.ST_RDONLY,root
135try: socket.create_connection(('127.0.0.1',%d),timeout=1)
136except OSError: pass
137else: raise AssertionError('host network reachable')
138r=subprocess.run(['go','test','-mod=mod','-run','^TestCached$','.'],capture_output=True,text=True)
139assert r.returncode==0,(r.stdout,r.stderr)
140print(r.stdout,flush=True)
141os.mkdir('/workspace/missing')
142open('/workspace/missing/go.mod','w').write('module missing.invalid/app\n\ngo 1.26\n')
143open('/workspace/missing/app.go','w').write('package app\nimport _ "missing.invalid/uncached"\n')
144r=subprocess.run(['go','test','-mod=mod','-run','^TestMissing$','.'],cwd='/workspace/missing',capture_output=True,text=True)
145assert r.returncode!=0 and 'module lookup disabled by GOPROXY=off' in r.stderr,(r.returncode,r.stderr)
146print('offline-cache-miss',flush=True)
147# A pinned missing version fails at the read-only cache lock before Go's
148# proxy lookup. The 'downloading' progress line does not mean a fetch ran.
149open('/workspace/missing/go.mod','a').write('\nrequire missing.invalid/uncached v1.0.0\n')
150r=subprocess.run(['go','test','-mod=mod','-run','^TestMissing$','.'],cwd='/workspace/missing',capture_output=True,text=True)
151assert r.returncode!=0 and 'read-only file system' in r.stderr,(r.returncode,r.stderr)
152print('pinned-cache-miss-read-only',flush=True)
153`, listener.Addr().(*net.TCPAddr).Port)
154 script = engineeringShell(t, name, script)
155 l, argv, _ := engineeringGoPolicy(t, m, l, script)
156 ctx, cancel := context.WithTimeout(context.Background(), 90*time.Second)
157 defer cancel()
158 p, err := m.Start(ctx, l, argv)
159 if err != nil {
160 t.Fatal(err)
161 }
162 defer p.Stdin().Close()
163 defer p.Stdout().Close()
164 defer p.Stderr().Close()
165 out, err := io.ReadAll(p.Stdout())
166 if err != nil {
167 t.Fatal(err)
168 }
169 stderr, _ := io.ReadAll(p.Stderr())
170 exit, err := p.Wait(ctx)
171 if err != nil || exit.Code != 0 {
172 t.Fatalf("Go probe: %+v %v\n%s\n%s", exit, err, out, stderr)
173 }
174 t.Log(string(out))
175 })
176 }
177}
178
179func TestEngineeringGoDigest(t *testing.T) {
180 for _, target := range []string{"/opt/go", "/opt/go-mod"} {
181 t.Run(filepath.Base(target), func(t *testing.T) {
182 m, l := egressFixture(t)
183 l, argv, _ := engineeringGoPolicy(t, m, l, "print('must not run')")
184 var source string
185 for _, mount := range l.Policy.Mounts {
186 if mount.Target == target {
187 source = mount.Source
188 }
189 }
190 // Replace the path after attestation. Containment must bind the original
191 // descriptor, never the replacement. Trusted in-place host edits are allowed.
192 if err := os.WriteFile(filepath.Join(source, "original"), []byte("original"), 0600); err != nil {
193 t.Fatal(err)
194 }
195 if _, err := provider.AttestLaunch(l, argv); err != nil {
196 t.Fatal(err)
197 }
198 if err := os.Rename(source, source+"-old"); err != nil {
199 t.Fatal(err)
200 }
201 t.Cleanup(func() { os.RemoveAll(source + "-old") })
202 if err := os.Mkdir(source, 0700); err != nil {
203 t.Fatal(err)
204 }
205 dir := t.TempDir()
206 for _, part := range []string{"home", "tmp"} {
207 if err := os.Mkdir(filepath.Join(dir, part), 0700); err != nil {
208 t.Fatal(err)
209 }
210 }
211 plan, err := m.mountPlan(l, dir)
212 if err != nil {
213 t.Fatal(err)
214 }
215 defer plan.close()
216 found := false
217 for i, arg := range plan.args {
218 if arg == target && i >= 2 && plan.args[i-2] == "--ro-bind-fd" {
219 var fd int
220 fmt.Sscanf(plan.args[i-1], "%d", &fd)
221 path := fmt.Sprintf("/proc/self/fd/%d/original", plan.files[fd-6].Fd())
222 if _, err := os.Stat(path); err != nil {
223 t.Fatal("replacement directory mounted", err)
224 }
225 found = true
226 }
227 }
228 if !found {
229 t.Fatal("read-only retained descriptor missing")
230 }
231 })
232 }
233}
234
235func TestEngineeringMissingModuleCache(t *testing.T) {
236 for _, project := range []string{"go", "non-go"} {
237 t.Run(project, func(t *testing.T) {
238 m, l := egressFixture(t)
239 script := `import os,subprocess
240assert not os.path.exists('/opt/go-mod')
241subprocess.run(['/usr/bin/bash','-c','printf non-go-ok'],check=True)
242`
243 if project == "go" {
244 script += `open('/workspace/go.mod','w').write('module fixture.invalid/app\n\ngo 1.26\n')
245open('/workspace/app_test.go','w').write('package app\nimport "testing"\nfunc TestLocal(t *testing.T) {}\n')
246subprocess.run(['go','test','-run','^TestLocal$','.'],check=True)
247`
248 }
249 l, argv, _ := engineeringGoPolicy(t, m, l, engineeringShell(t, "claude", script), true)
250 ctx, cancel := context.WithTimeout(context.Background(), 45*time.Second)
251 defer cancel()
252 p, err := m.Start(ctx, l, argv)
253 if err != nil {
254 t.Fatal(err)
255 }
256 defer p.Stdin().Close()
257 defer p.Stdout().Close()
258 defer p.Stderr().Close()
259 out, stderr := engineeringOutput(p)
260 exit, err := p.Wait(ctx)
261 if err != nil || exit.Code != 0 {
262 t.Fatalf("missing cache: %+v %v %s %s", exit, err, out, stderr)
263 }
264 })
265 }
266}
267