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 "fmt"
10 "io"
11 "net"
12 "os"
13 "path/filepath"
14 "strings"
15 "testing"
16 "time"
17
18 "amadan.net/oficina/equipo/internal/runner/egress"
19 "amadan.net/oficina/equipo/internal/runner/provider"
20 "amadan.net/oficina/equipo/internal/testci"
21)
22
23func egressFixture(t *testing.T, deep ...bool) (*Manager, provider.Launch) {
24 t.Helper()
25 root, e := os.MkdirTemp(os.Getenv("TMPDIR"), "e3-")
26 if e != nil {
27 t.Fatal(e)
28 }
29 t.Cleanup(func() { os.RemoveAll(root) })
30 state := filepath.Join(root, "s")
31 if len(deep) > 0 && deep[0] {
32 state = filepath.Join(state, strings.Repeat("deep", 20), "state")
33 }
34 workspace := filepath.Join(root, "w")
35 if e = os.MkdirAll(state, 0700); e != nil {
36 t.Fatal(e)
37 }
38 if e = os.Mkdir(workspace, 0700); e != nil {
39 t.Fatal(e)
40 }
41 binary, e := os.Executable()
42 if e != nil {
43 t.Fatal(e)
44 }
45 testci.Tools(t, "bwrap", "python3")
46 m, e := New(Config{Binary: "/usr/bin/bwrap", RunnerBinary: binary, ScratchRoot: state})
47 if e != nil {
48 t.Fatal(e)
49 }
50 home := filepath.Join(root, "fake-login")
51 if e = os.Mkdir(home, 0700); e != nil {
52 t.Fatal(e)
53 }
54 id := provider.Identity{AccountID: "fake-account", HomeID: "fake-home", ProviderVersion: "2.1.312"}
55 metadata, _ := json.Marshal(id)
56 for name, raw := range map[string][]byte{provider.IdentityFile: metadata, ".credentials.json": []byte(`{"token":"fake-only"}`)} {
57 if e = os.WriteFile(filepath.Join(home, name), raw, 0600); e != nil {
58 t.Fatal(e)
59 }
60 }
61 lease, e := provider.OpenAccount(context.Background(), provider.Binding{ID: "fake-binding", Provider: "claude", AccountID: id.AccountID, Expected: id, Home: home, RuntimeRoot: filepath.Join(state, "homes")})
62 if e != nil {
63 t.Fatal(e)
64 }
65 t.Cleanup(func() {
66 if e := lease.Close(); e != nil {
67 t.Error(e)
68 }
69 })
70 if e = lease.Preflight(context.Background(), func(context.Context, provider.Binding) (provider.Identity, error) { return id, nil }); e != nil {
71 t.Fatal(e)
72 }
73 l := provider.Launch{AttemptKey: "egress", Workspace: workspace, Binding: lease.Binding(), Selection: provider.Selection{Provider: "claude", AccountID: id.AccountID}}
74 l, _ = directPolicyFixture(t, m, l, []string{"/usr/bin/true"})
75 return m, l
76}
77
78func TestEgressRejectsHostServices(t *testing.T) {
79 tcp, e := net.Listen("tcp", "127.0.0.1:0")
80 if e != nil {
81 t.Fatal(e)
82 }
83 defer tcp.Close()
84 abstract, e := net.Listen("unix", fmt.Sprintf("@equipo-egress-%d-%d", os.Getpid(), time.Now().UnixNano()))
85 if e != nil {
86 t.Fatal(e)
87 }
88 defer abstract.Close()
89 // Shared-network controls prove both services exist before private launch.
90 for _, ln := range []net.Listener{tcp, abstract} {
91 c, e := net.Dial(ln.Addr().Network(), ln.Addr().String())
92 if e != nil {
93 t.Fatal(e)
94 }
95 c.Close()
96 }
97 m, l := egressFixture(t)
98 script := fmt.Sprintf(`import socket, os
99for family, address in [(socket.AF_INET, ('127.0.0.1', %d)), (socket.AF_UNIX, '\0%s')]:
100 s=socket.socket(family); s.settimeout(1)
101 try:
102 s.connect(address)
103 print('HOST REACHABLE')
104 except OSError:
105 print('blocked')
106 s.close()
107s=socket.create_connection(('127.0.0.1',18080),1)
108s.sendall(b'CONNECT localhost:443 HTTP/1.1\r\nHost: localhost:443\r\n\r\n')
109print(s.recv(1024).decode().strip())
110print(os.environ['HTTPS_PROXY'], os.environ['https_proxy'], os.environ['HTTP_PROXY'], os.environ['http_proxy'])
111print('socket', os.path.exists('/egress/proxy.sock'))
112print('only-socket', os.listdir('/egress') == ['proxy.sock'])
113try:
114 os.chmod('/egress/proxy.sock', 0o666)
115 print('SOCKET WRITABLE')
116except OSError:
117 print('socket-readonly')
118`, tcp.Addr().(*net.TCPAddr).Port, strings.TrimPrefix(abstract.Addr().String(), "@"))
119 p := launch(t, m, l, script)
120 b, _ := io.ReadAll(p.Stdout())
121 exit, e := p.Wait(context.Background())
122 if e != nil || exit.Code != 0 || strings.Count(string(b), "blocked") != 2 || !strings.Contains(string(b), "403") || !strings.Contains(string(b), "socket True") || strings.Count(string(b), "http://127.0.0.1:18080") != 4 || !strings.Contains(string(b), "only-socket True") || !strings.Contains(string(b), "socket-readonly") {
123 errout, _ := io.ReadAll(p.Stderr())
124 t.Fatalf("isolation/relay: %q exit=%+v err=%v stderr=%s", b, exit, e, errout)
125 }
126 if p.(*process).EgressDenials() != 1 {
127 t.Fatal("relay denial absent from process diagnostics")
128 }
129}
130
131func TestEgressLongScratchRoot(t *testing.T) {
132 m, l := egressFixture(t, true)
133 cfg := m.cfg
134 if len(cfg.ScratchRoot) < 70 {
135 t.Fatal("fixture scratch root is too short")
136 }
137 p := launch(t, m, l, `import socket, sys
138s=socket.create_connection(('127.0.0.1',18080),2)
139s.sendall(b'CONNECT localhost:443 HTTP/1.1\r\nHost: localhost:443\r\n\r\n')
140with s.makefile('rb') as response:
141 assert response.read() == b'HTTP/1.1 403 Forbidden\r\n\r\n'
142s.close()
143print('relay-ready', flush=True)
144sys.stdin.read(1)
145`)
146 line, e := bufio.NewReader(p.Stdout()).ReadString('\n')
147 if e != nil || line != "relay-ready\n" {
148 t.Fatalf("long-root relay: %q %v", line, e)
149 }
150 path := p.(*process).egress.SocketPath()
151 if !strings.HasPrefix(path, cfg.ScratchRoot+"/") || len(path) <= 107 {
152 t.Fatalf("SocketPath must retain the real long path: %q", path)
153 }
154 info, e := os.Stat(path)
155 if e != nil || info.Mode()&os.ModeSocket == 0 || info.Mode().Perm() != 0600 {
156 t.Fatalf("real socket path: %v %v", info, e)
157 }
158 if _, e = p.Stdin().Write([]byte{'x'}); e != nil {
159 t.Fatal(e)
160 }
161 exit, e := p.Wait(context.Background())
162 if e != nil || exit.Code != 0 {
163 t.Fatalf("long-root launch: %+v %v", exit, e)
164 }
165 if _, e = os.Stat(path); !os.IsNotExist(e) {
166 t.Fatalf("long-root socket survived exit: %v", e)
167 }
168}
169
170func TestEgressDiesWithAttempt(t *testing.T) {
171 for _, mode := range []string{"stop", "context", "proxy_failure", "exit"} {
172 t.Run(mode, func(t *testing.T) {
173 m, l := egressFixture(t)
174 ctx, cancel := context.WithCancel(context.Background())
175 defer cancel()
176 l, argv := directPolicyFixture(t, m, l, []string{"/usr/bin/python3", "-u", "-c", `import socket,sys,time
177s=socket.create_connection(('127.0.0.1',18080),1)
178s.sendall(b'CONNECT localhost:443 HTTP/1.1\r\n\r\n')
179assert b'403' in s.recv(1024)
180s.close()
181print('ready',flush=True)
182sys.stdin.read(1)
183`})
184 p, e := m.Start(ctx, l, argv)
185 if e != nil {
186 t.Fatal(e)
187 }
188 defer p.Stdin().Close()
189 defer p.Stdout().Close()
190 defer p.Stderr().Close()
191 t.Cleanup(func() { m.Stop(context.Background(), p.ID()) })
192 line, e := bufio.NewReader(p.Stdout()).ReadString('\n')
193 if e != nil || line != "ready\n" {
194 t.Fatalf("relay readiness: %q %v", line, e)
195 }
196 impl := p.(*process)
197 if impl.egress == nil {
198 t.Fatal("attempt lacks proxy")
199 }
200 path := impl.egress.SocketPath()
201 fd := descriptor(t, record(t, m, p).HostPID)
202 switch mode {
203 case "stop":
204 _, e = m.Stop(context.Background(), p.ID())
205 case "context":
206 cancel()
207 case "proxy_failure":
208 e = impl.egress.Close()
209 case "exit":
210 _, e = p.Stdin().Write([]byte{'x'})
211 }
212 if e != nil {
213 t.Fatal(e)
214 }
215 wait, c := context.WithTimeout(context.Background(), 3*time.Second)
216 defer c()
217 if _, e = p.Wait(wait); e != nil {
218 t.Fatal(e)
219 }
220 exited(t, fd)
221 if _, e = os.Stat(path); !os.IsNotExist(e) {
222 t.Fatalf("socket outlived attempt: %v", e)
223 }
224 select {
225 case <-impl.egress.Done():
226 default:
227 t.Fatal("proxy outlived attempt")
228 }
229 if c, e := net.Dial("unix", path); e == nil {
230 c.Close()
231 t.Fatal("listener outlived attempt")
232 }
233 })
234 }
235}
236
237func TestEgressMountPolicy(t *testing.T) {
238 m, l := egressFixture(t)
239 for _, key := range []string{"HTTPS_PROXY", "HTTP_PROXY", "https_proxy", "http_proxy", "ALL_PROXY", "NO_PROXY", "EQUIPO_EGRESS"} {
240 t.Run(key, func(t *testing.T) {
241 bad := l
242 bad.Policy.Env = map[string]string{key: "http://127.0.0.1:1"}
243 if p, e := m.Start(context.Background(), bad, []string{"/usr/bin/true"}); e == nil {
244 m.Stop(context.Background(), p.ID())
245 t.Fatal("caller replaced fixed relay environment")
246 }
247 })
248 }
249 l.Selection.Provider = "unknown"
250 if p, e := m.Start(context.Background(), l, []string{"/usr/bin/true"}); e == nil {
251 m.Stop(context.Background(), p.ID())
252 t.Fatal("unknown provider accepted")
253 }
254 l.Selection.Provider = "claude"
255 p := launch(t, m, l, "pass")
256 r := record(t, m, p)
257 policy, e := egress.ProviderPolicy(provider.NetworkContract{Provider: "claude"}, false)
258 if e != nil {
259 t.Fatal(e)
260 }
261 hash, e := policy.Hash()
262 if e != nil {
263 t.Fatal(e)
264 }
265 if r.EgressHash != hash {
266 t.Fatalf("missing exact host-policy hash: %q want %q", r.EgressHash, hash)
267 }
268}
269
270func TestEgressInstalledContract(t *testing.T) {
271 m, _ := egressFixture(t)
272 for _, contracts := range [][]provider.NetworkContract{
273 {{Provider: "other"}},
274 {{Provider: "claude", AuthHost: "*.example"}},
275 {{Provider: "claude", AuthHost: "refresh.example"}},
276 {{Provider: "claude"}, {Provider: "claude", AuthHost: "refresh.example"}},
277 } {
278 cfg := m.cfg
279 cfg.ProviderNetworks = contracts
280 if _, e := New(cfg); e == nil {
281 t.Fatalf("invalid installed contracts accepted: %+v", contracts)
282 }
283 }
284 cfg := m.cfg
285 contracts := []provider.NetworkContract{{Provider: "claude"}}
286 cfg.ProviderNetworks = contracts
287 manager, e := New(cfg)
288 if e != nil {
289 t.Fatal(e)
290 }
291 contracts[0].AuthHost = "changed.example"
292 if manager.cfg.ProviderNetworks[0].AuthHost != "" {
293 t.Fatal("installed contract changed after New")
294 }
295}
296
297func TestEgressRefreshRequiresStagedHome(t *testing.T) {
298 m, l := egressFixture(t)
299 l.Binding = provider.Binding{Home: l.Binding.Home, DedicatedHome: true}
300 if p, e := m.Start(context.Background(), l, []string{"/usr/bin/true"}); e == nil {
301 m.Stop(context.Background(), p.ID())
302 t.Fatal("unstaged home qualified for refresh")
303 }
304}
305
306func TestEgressStartupFailureClosesProxy(t *testing.T) {
307 m, l := egressFixture(t)
308 m.cfg.RunnerBinary = "/usr/bin/true"
309 l, argv := directPolicyFixture(t, m, l, []string{"/usr/bin/true"})
310 sockets := func() int {
311 entries, e := os.ReadDir("/proc/self/fd")
312 if e != nil {
313 t.Fatal(e)
314 }
315 count := 0
316 for _, entry := range entries {
317 target, _ := os.Readlink("/proc/self/fd/" + entry.Name())
318 if strings.HasPrefix(target, "socket:[") {
319 count++
320 }
321 }
322 return count
323 }
324 before := sockets()
325 if p, e := m.Start(context.Background(), l, argv); e == nil {
326 m.Stop(context.Background(), p.ID())
327 t.Fatal("invalid helper started")
328 }
329 if after := sockets(); after != before {
330 t.Fatalf("startup failure leaked sockets: before=%d after=%d", before, after)
331 }
332 entries, e := os.ReadDir(m.cfg.ScratchRoot)
333 if e != nil {
334 t.Fatal(e)
335 }
336 for _, entry := range entries {
337 if entry.IsDir() && entry.Name() != "homes" {
338 t.Fatalf("startup scratch survived: %s", entry.Name())
339 }
340 }
341}
342
343func TestEgressRejectsForgedDedicatedHome(t *testing.T) {
344 m, l := egressFixture(t)
345 home := filepath.Join(m.cfg.ScratchRoot, "homes", "forged")
346 if e := os.MkdirAll(home, 0700); e != nil {
347 t.Fatal(e)
348 }
349 l.Binding = provider.Binding{Home: home, DedicatedHome: true}
350 if p, e := m.Start(context.Background(), l, []string{"/usr/bin/true"}); e == nil {
351 m.Stop(context.Background(), p.ID())
352 t.Fatal("caller boolean granted dedicated-home authority")
353 }
354 plan := &mounts{}
355 if _, e := m.openEgress(context.Background(), l, t.TempDir(), plan); e == nil {
356 if plan.proxy != nil {
357 plan.proxy.Close()
358 }
359 plan.close()
360 t.Fatal("egress accepted forged provenance")
361 }
362}
363
364func directPolicyFixture(t *testing.T, m *Manager, l provider.Launch, argv []string) (provider.Launch, []string) {
365 t.Helper()
366 binary, e := filepath.EvalSymlinks(argv[0])
367 if e != nil {
368 t.Fatal(e)
369 }
370 argv = append([]string(nil), argv...)
371 argv[0] = "/opt/harness"
372 scratch := t.TempDir()
373 network, e := egress.ProviderPolicy(provider.NetworkContract{Provider: l.Selection.Provider}, true)
374 if e != nil {
375 t.Fatal(e)
376 }
377 l.Policy, e = provider.BuildPolicy(l.Binding, provider.PolicyInputs{
378 RuntimeFiles: []provider.Mount{{Source: binary, Target: argv[0], ReadOnly: true}, {Source: m.cfg.Binary, Target: "/opt/bwrap", ReadOnly: true}, {Source: m.cfg.RunnerBinary, Target: "/opt/runner", ReadOnly: true}},
379 ProviderVersion: "2.1.312", LauncherVersion: "test", BwrapVersion: "0.11.0", EgressHosts: network.Hosts,
380 Settings: json.RawMessage(`{"sandbox":true}`), MCP: json.RawMessage(`{}`), Workspace: l.Workspace, Scratch: scratch, Argv: argv,
381 })
382 if e != nil {
383 t.Fatal(e)
384 }
385 return l, argv
386}
387