oficina / equipo Public

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

Plain git — no account needed to clone.

Download

Download this file

1package claude
2
3import (
4 "bufio"
5 "bytes"
6 "context"
7 "crypto/sha256"
8 "encoding/hex"
9 "encoding/json"
10 "errors"
11 "fmt"
12 "io"
13 "os"
14 "os/exec"
15 "path/filepath"
16 "reflect"
17 "strings"
18 "sync"
19 "testing"
20 "time"
21
22 "amadan.net/oficina/equipo/internal/runner/provider"
23)
24
25const fakeCLI = `import sys,json,os
26args=sys.argv[1:]
27with open(os.path.join(os.environ['CLAUDE_CONFIG_DIR'],'history.jsonl'),'w') as config: config.write('{"trust":"fake-cli-write"}')
28if 'auth' in args:
29 try:
30 with open(os.path.join(os.environ['CLAUDE_CONFIG_DIR'],'.claude.json')) as f: email=json.load(f).get('oauthAccount',{}).get('emailAddress')
31 except FileNotFoundError: email=None
32 if os.environ['FAKE_ACCOUNT']!='account@example.invalid': email=os.environ['FAKE_ACCOUNT']
33 print(json.dumps({'loggedIn':True,'authMethod':'claude.ai','email':email}))
34 sys.exit(0)
35if os.environ['FAKE_MODE']=='sandbox':
36 print('Sandbox required but unavailable',file=sys.stderr)
37 print(json.dumps({'type':'result','session_id':'dependency','subtype':'error_during_execution','is_error':True}))
38 sys.exit(1)
39sid=args[args.index('--resume')+1] if '--resume' in args else args[args.index('--session-id')+1]
40idx=0
41for line in sys.stdin:
42 v=json.loads(line)
43 if v['type']!='user': sys.exit(2)
44 init={'type':'system','subtype':'init','session_id':sid,'claude_code_version':'2.1.312','model':args[args.index('--model')+1],'permissionMode':'default','tools':args[args.index('--tools')+1].split(',')+['mcp__equipo__permission'],'mcp_servers':[{'name':'equipo','status':'connected'}],'skills':[],'plugins':[]}
45 if os.environ.get('FAKE_TOOLS'): init['tools']=[t for t in json.loads(os.environ['FAKE_TOOLS']) if t!='mcp__equipo__permission']
46 if os.environ['FAKE_MODE']=='identity': init['session_id']='different'
47 if os.environ['FAKE_MODE']=='tools': init['tools'].append('WebFetch')
48 if os.environ['FAKE_MODE']=='plugins': init['plugins']=[{'name':'extra','path':'/untrusted','source':'extra'}]
49 if os.environ['FAKE_MODE']=='skills': init['skills']=['extra']
50 if os.environ['FAKE_MODE']=='permission': init['permissionMode']='bypassPermissions'
51 if os.environ['FAKE_MODE']=='version': init['claude_code_version']='different'
52 if os.environ['FAKE_MODE']=='model': init['model']='fallback'
53 if os.environ['FAKE_MODE']=='mcp': init['mcp_servers'].append({'name':'extra','status':'connected'})
54 print(json.dumps(init),flush=True)
55 if os.environ['FAKE_MODE']=='hang': continue
56 if os.environ['FAKE_MODE']=='missing': sys.exit(0)
57 if os.environ['FAKE_MODE']=='partial':
58 print('{broken',flush=True)
59 sys.exit(0)
60 if os.environ['FAKE_MODE']=='oversized':
61 print('x'*1048577,flush=True)
62 sys.exit(0)
63 print(json.dumps({'type':'result','subtype':'success','is_error':os.environ['FAKE_MODE']=='rate','session_id':sid,'result':'ok','usage':{'input_tokens':idx+2,'output_tokens':3},'result_index':idx}),flush=True)
64 idx+=1
65print('non JSON diagnostic',file=sys.stderr)
66sys.exit(7 if os.environ['FAKE_MODE']=='exit' and idx else 0)
67`
68
69type fakeProcess struct {
70 cmd *exec.Cmd
71 in io.WriteCloser
72 out, err io.ReadCloser
73 done chan struct{}
74 exit provider.Exit
75 waitErr error
76}
77
78func (p *fakeProcess) ID() string { return "fake" }
79func (p *fakeProcess) Stdin() io.WriteCloser { return p.in }
80func (p *fakeProcess) Stdout() io.ReadCloser { return p.out }
81func (p *fakeProcess) Stderr() io.ReadCloser { return p.err }
82func (p *fakeProcess) Wait(ctx context.Context) (provider.Exit, error) {
83 select {
84 case <-ctx.Done():
85 return provider.Exit{}, ctx.Err()
86 case <-p.done:
87 return p.exit, p.waitErr
88 }
89}
90
91type fakeHost struct {
92 processes []*fakeProcess
93 mu sync.Mutex
94 launches []provider.Launch
95 argv [][]string
96 mode, account, binary string
97}
98
99func (h *fakeHost) Start(ctx context.Context, l provider.Launch, args []string) (provider.Process, error) {
100 if _, e := provider.AttestLaunch(l, args); e != nil {
101 return nil, e
102 }
103 h.mu.Lock()
104 h.launches = append(h.launches, l)
105 h.argv = append(h.argv, append([]string(nil), args...))
106 mode, account := h.mode, h.account
107 h.mu.Unlock()
108 cmd := exec.CommandContext(ctx, "/usr/bin/python3", append([]string{h.binary}, args[1:]...)...)
109 cmd.Dir = l.Workspace
110 cmd.Env = []string{"PATH=/usr/bin:/bin", "HOME=" + l.Binding.Home, "FAKE_MODE=" + mode, "FAKE_ACCOUNT=" + account}
111 for k, v := range l.Policy.Env {
112 if k == "CLAUDE_CONFIG_DIR" || k == "CLAUDE_SECURESTORAGE_CONFIG_DIR" {
113 v = l.Binding.Home
114 }
115 cmd.Env = append(cmd.Env, k+"="+v)
116 }
117 var manifest struct{ Tools []string }
118 json.Unmarshal(l.Policy.Manifest, &manifest)
119 toolJSON, _ := json.Marshal(manifest.Tools)
120 cmd.Env = append(cmd.Env, "FAKE_TOOLS="+string(toolJSON))
121 in, _ := cmd.StdinPipe()
122 out, outWrite, _ := os.Pipe()
123 errout, errWrite, _ := os.Pipe()
124 cmd.Stdout = outWrite
125 cmd.Stderr = errWrite
126 if e := cmd.Start(); e != nil {
127 return nil, e
128 }
129 p := &fakeProcess{cmd: cmd, in: in, out: out, err: errout, done: make(chan struct{})}
130 h.mu.Lock()
131 h.processes = append(h.processes, p)
132 h.mu.Unlock()
133 go func() {
134 e := cmd.Wait()
135 outWrite.Close()
136 errWrite.Close()
137 p.exit = provider.Exit{Code: cmd.ProcessState.ExitCode(), ObservedAt: time.Now()}
138 if e != nil {
139 var x *exec.ExitError
140 if !errors.As(e, &x) {
141 p.waitErr = e
142 }
143 }
144 close(p.done)
145 }()
146 return p, nil
147}
148
149type captureFactory struct {
150 block bool
151 blocker *blockedInput
152 malformed, zeroSequence bool
153 opens int
154 mu sync.Mutex
155 inputs int
156 fail bool
157}
158type recordedInput struct {
159 io.WriteCloser
160 owner *captureFactory
161}
162
163func (w recordedInput) Write(b []byte) (int, error) {
164 w.owner.mu.Lock()
165 w.owner.inputs++
166 w.owner.mu.Unlock()
167 return w.WriteCloser.Write(b)
168}
169func (f *captureFactory) Open(ctx context.Context, p provider.Process, l provider.Launch) (*provider.Capture, error) {
170 f.mu.Lock()
171 f.opens++
172 nth := f.opens
173 f.mu.Unlock()
174 if f.fail {
175 return nil, errors.New("capture failed")
176 }
177 if f.malformed && nth == 3 {
178 return &provider.Capture{Input: p.Stdin()}, nil
179 }
180 var diagnostics strings.Builder
181 frames := make(chan provider.Frame)
182 done := make(chan error, 1)
183 go func() {
184 defer p.Stdout().Close()
185 defer p.Stderr().Close()
186 stderrDone := make(chan struct{})
187 go func() { io.Copy(&diagnostics, p.Stderr()); close(stderrDone) }()
188 scan := bufio.NewScanner(p.Stdout())
189 scan.Buffer(make([]byte, 4096), MaxFrameBytes+1)
190 var seq int64
191 for scan.Scan() {
192 seq++
193 if f.zeroSequence {
194 seq = 0
195 }
196 b := bytes.Clone(scan.Bytes())
197 select {
198 case frames <- provider.Frame{Sequence: seq, Bytes: b}:
199 case <-ctx.Done():
200 close(frames)
201 <-stderrDone
202 done <- ctx.Err()
203 return
204 }
205 }
206 close(frames)
207 <-stderrDone
208 done <- scan.Err()
209 close(done)
210 }()
211 var input io.WriteCloser = recordedInput{p.Stdin(), f}
212 if f.block && nth == 3 {
213 f.blocker = &blockedInput{underlying: input, started: make(chan struct{}), done: make(chan struct{})}
214 input = f.blocker
215 }
216 return &provider.Capture{Input: input, Frames: frames, Done: done, Diagnostics: func() string { return diagnostics.String() }}, nil
217}
218
219type fixture struct {
220 l *Launcher
221 host *fakeHost
222 capture *captureFactory
223 lease *provider.AccountLease
224 launch provider.Launch
225 inputs provider.PolicyInputs
226 interactive string
227}
228
229func fixtureFor(t *testing.T, role string) *fixture {
230 t.Helper()
231 root := t.TempDir()
232 source := filepath.Join(root, "dedicated")
233 os.Mkdir(source, 0700)
234 id := provider.Identity{AccountID: "account@example.invalid", HomeID: "equipo-home", ProviderVersion: Version}
235 b := provider.Binding{ID: "binding", Home: source, AccountID: id.AccountID, Provider: "claude", Expected: id, RuntimeRoot: filepath.Join(root, "homes")}
236 raw, _ := json.Marshal(id)
237 os.WriteFile(filepath.Join(source, provider.IdentityFile), raw, 0600)
238 os.WriteFile(filepath.Join(source, ".credentials.json"), []byte(`{"fake":"login"}`), 0600)
239 os.WriteFile(filepath.Join(source, ".claude.json"), []byte(`{"oauthAccount":{"emailAddress":"account@example.invalid","accountUuid":"fake-account"},"projects":{"untrusted":"trust"},"hooks":{"evil":true}}`), 0600)
240 lease, e := provider.OpenAccount(context.Background(), b)
241 if e != nil {
242 t.Fatal(e)
243 }
244 t.Cleanup(func() { lease.Close() })
245 binary := filepath.Join(root, "fake-cli")
246 os.WriteFile(binary, []byte(fakeCLI), 0700)
247 helperFile := filepath.Join(root, "helper")
248 os.WriteFile(helperFile, []byte("fake helper"), 0700)
249 work, scratch := filepath.Join(root, "workspace"), filepath.Join(root, "scratch")
250 os.Mkdir(work, 0700)
251 os.Mkdir(scratch, 0700)
252 interactive := filepath.Join(root, "interactive")
253 os.Mkdir(interactive, 0700)
254 os.WriteFile(filepath.Join(interactive, "settings.json"), []byte(`{"trust":"unchanged"}`), 0600)
255 in := provider.PolicyInputs{RuntimeFiles: []provider.Mount{{Source: binary, Target: "/opt/claude", ReadOnly: true}, {Source: helperFile, Target: helper, ReadOnly: true}}, Workspace: work, Scratch: scratch, AuthHost: "auth.claude.example", EgressHosts: []string{"api.anthropic.com", "auth.claude.example"}, LauncherVersion: "2", BwrapVersion: "0.11.0", DeniedPaths: []string{"/private/state", "/alias/login"}}
256 in, e = PolicyInputs(lease.Binding(), in, role, "claude-haiku-5-5")
257 if e != nil {
258 t.Fatal(e)
259 }
260 policy, e := provider.BuildPolicy(lease.Binding(), in)
261 if e != nil {
262 t.Fatal(e)
263 }
264 host := &fakeHost{binary: binary, account: id.AccountID}
265 t.Cleanup(func() {
266 host.mu.Lock()
267 defer host.mu.Unlock()
268 for _, p := range host.processes {
269 p.cmd.Process.Kill()
270 <-p.done
271 p.in.Close()
272 p.out.Close()
273 p.err.Close()
274 }
275 })
276 cap := &captureFactory{}
277 l, e := New(host, cap)
278 if e != nil {
279 t.Fatal(e)
280 }
281 sum := sha256.Sum256([]byte(fakeCLI))
282 l.digest = hex.EncodeToString(sum[:])
283 return &fixture{l: l, host: host, capture: cap, lease: lease, launch: provider.Launch{AttemptKey: "attempt", Workspace: work, Binding: lease.Binding(), Policy: policy, Selection: provider.Selection{ConnectionID: "connection", Provider: "claude", Family: "claude", Model: "claude-haiku-5-5", AccountID: id.AccountID}}, inputs: in, interactive: interactive}
284}
285func openFixture(t *testing.T, f *fixture) (provider.Session, <-chan provider.Event) {
286 t.Helper()
287 ctx, cancel := context.WithTimeout(context.Background(), 8*time.Second)
288 t.Cleanup(cancel)
289 s, e := f.l.Open(ctx, f.launch)
290 if e != nil {
291 t.Fatal(e)
292 }
293 t.Cleanup(func() { ctx, c := context.WithTimeout(context.Background(), time.Second); defer c(); f.l.Close(ctx, s) })
294 events, e := f.l.Events(ctx, s)
295 if e != nil {
296 t.Fatal(e)
297 }
298 return s, events
299}
300func terminal(t *testing.T, events <-chan provider.Event) provider.Event {
301 t.Helper()
302 timer := time.NewTimer(3 * time.Second)
303 defer timer.Stop()
304 for {
305 select {
306 case ev, ok := <-events:
307 if !ok {
308 t.Fatal("events ended without terminal")
309 }
310 if strings.HasPrefix(ev.Kind, "turn.") {
311 return ev
312 }
313 case <-timer.C:
314 t.Fatal("no terminal event")
315 }
316 }
317}
318func TestClaudeLaunchPolicy(t *testing.T) {
319 for _, role := range []string{"Engineering", "Review", "Product"} {
320 t.Run(role, func(t *testing.T) {
321 f := fixtureFor(t, role)
322 want := []string{"Bash", "Read", "Write", "Edit", "Glob", "Grep"}
323 if role != "Engineering" {
324 want = []string{"Read", "Glob", "Grep", "Bash"}
325 }
326 if !reflect.DeepEqual(f.inputs.Tools, append(append([]string{}, want...), "mcp__equipo__permission")) {
327 t.Fatalf("tools %v", f.inputs.Tools)
328 }
329 var settings map[string]any
330 json.Unmarshal(f.inputs.Settings, &settings)
331 if settings["disableAllHooks"] != true || !reflect.DeepEqual(settings["enabledPlugins"], map[string]any{"agents-md@builtin": false, "plugin-authoring@builtin": false}) || settings["autoMemoryEnabled"] != false || settings["autoDreamEnabled"] != false {
332 t.Fatal("hooks/plugins enabled")
333 }
334 if !sameJSON(f.inputs.MCP, []byte(`{"mcpServers":{"equipo":{"type":"stdio","command":"/opt/equipo-tool-proxy","args":["--socket","/tool/equipo.sock"]}}}`)) {
335 t.Fatal("MCP inventory expanded")
336 }
337 sandbox := settings["sandbox"].(map[string]any)
338 if sandbox["enabled"] != true || sandbox["failIfUnavailable"] != true || sandbox["allowUnsandboxedCommands"] != false {
339 t.Fatal("sandbox weakened")
340 }
341 if sandbox["autoAllowBashIfSandboxed"] != true {
342 t.Fatal("automatic shell approval enabled")
343 }
344 // A Bash command gets its own PID namespace and a fresh /proc,
345 // so it cannot read the CLI's environment (the pasted token).
346 if v, set := sandbox["enableWeakerNestedSandbox"]; set && v != false {
347 t.Fatal("tool sandbox may inherit /proc")
348 }
349 if len(sandbox["excludedCommands"].([]any)) != 0 {
350 t.Fatal("excluded commands")
351 }
352 for _, path := range []string{"/home/runner", "/egress", "/tool", "/tool/equipo.sock", "/config", "/proc", "/dev/fd", "/private/state", "/alias/login"} {
353 for _, key := range []string{"denyRead", "denyWrite"} {
354 found := false
355 for _, value := range sandbox["filesystem"].(map[string]any)[key].([]any) {
356 if value == path {
357 found = true
358 }
359 }
360 if !found {
361 t.Fatalf("missing shell %s denial %s", key, path)
362 }
363 }
364 for _, tool := range []string{"Read", "Write", "Edit", "Glob", "Grep"} {
365 for _, suffix := range []string{")", "/**)"} {
366 if !strings.Contains(string(f.inputs.Settings), tool+"(/"+path+suffix) {
367 t.Fatalf("missing native %s denial %s", tool, path)
368 }
369 }
370 }
371 if !strings.Contains(string(f.inputs.Settings), `"`+path+`"`) || !strings.Contains(string(f.inputs.Settings), "Read(/"+path+"/**)") {
372 t.Fatalf("missing protected path %s", path)
373 }
374 }
375 s, _ := openFixture(t, f)
376 _ = s
377 f.host.mu.Lock()
378 last := len(f.host.argv) - 1
379 args := f.host.argv[last]
380 launch := f.host.launches[last]
381 f.host.mu.Unlock()
382 if launch.Policy.Hash != f.launch.Policy.Hash {
383 t.Fatal("session ID changed reusable policy hash")
384 }
385 expected := []string{"/opt/claude", "-p", "--verbose", "--include-hook-events", "--input-format", "stream-json", "--output-format", "stream-json", "--model", "claude-haiku-5-5", "--setting-sources", "", "--disable-slash-commands", "--strict-mcp-config", "--mcp-config", provider.MCPPath, "--settings", provider.SettingsPath, "--permission-mode", "manual", "--permission-prompt-tool", "mcp__equipo__permission", "--tools", strings.Join(want, ","), "--session-id", s.ID}
386 if !reflect.DeepEqual(args, expected) {
387 t.Fatalf("argv %v", args)
388 }
389 for k, v := range map[string]string{"CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC": "1", "DISABLE_AUTOUPDATER": "1", "CLAUDE_CONFIG_DIR": "/home/runner"} {
390 if launch.Policy.Env[k] != v {
391 t.Fatalf("env %s", k)
392 }
393 }
394 if _, ok := launch.Policy.Env["CLAUDE_CODE_DISABLE_AUTO_UPDATE"]; ok {
395 t.Fatal("unsupported updater spelling")
396 }
397 in := f.inputs
398 in.Tools = append(append([]string{}, in.Tools...), "WebFetch")
399 p, e := provider.BuildPolicy(f.lease.Binding(), in)
400 if e != nil {
401 t.Fatal(e)
402 }
403 if p.Hash == f.launch.Policy.Hash {
404 t.Fatal("tool not hashed")
405 }
406 })
407 }
408}
409func TestClaudeNoPromptBeforeAdmission(t *testing.T) {
410 f := fixtureFor(t, "Engineering")
411 t.Setenv("CLAUDE_CONFIG_DIR", f.interactive)
412 s, events := openFixture(t, f)
413 f.capture.mu.Lock()
414 n := f.capture.inputs
415 f.capture.mu.Unlock()
416 if n != 0 {
417 t.Fatal("prompt before admission")
418 }
419 if e := f.l.StartTurn(context.Background(), s, provider.Turn{ID: "t", Prompt: "one"}); e == nil {
420 t.Fatal("missing admission accepted")
421 }
422 for i, id := range []string{"t1", "t2"} {
423 if e := f.l.StartTurn(context.Background(), s, provider.Turn{ID: id, AdmissionID: "admit-" + id, Prompt: "tiny"}); e != nil {
424 t.Fatal(e)
425 }
426 ev := terminal(t, events)
427 if ev.Kind != "turn.completed" || ev.TurnID != id || ev.SessionID != s.ID {
428 t.Fatalf("turn %d: %+v", i, ev)
429 }
430 }
431 if e := f.l.Close(context.Background(), s); e != nil {
432 t.Fatal(e)
433 }
434 runtimeConfig, _ := os.ReadFile(filepath.Join(f.lease.Binding().Home, "history.jsonl"))
435 if string(runtimeConfig) != `{"trust":"fake-cli-write"}` {
436 t.Fatal("fake did not exercise config writes")
437 }
438 got, _ := os.ReadFile(filepath.Join(f.interactive, "settings.json"))
439 if string(got) != `{"trust":"unchanged"}` {
440 t.Fatal("interactive config changed")
441 }
442}
443func TestClaudeResumeUsesSameBinding(t *testing.T) {
444 f := fixtureFor(t, "Review")
445 s, events := openFixture(t, f)
446 turn := provider.Turn{ID: "t1", AdmissionID: "a1", Prompt: "tiny"}
447 if e := f.l.StartTurn(context.Background(), s, turn); e != nil {
448 t.Fatal(e)
449 }
450 terminal(t, events)
451 if e := f.l.Close(context.Background(), s); e != nil {
452 t.Fatal(e)
453 }
454 next := f.launch
455 next.AttemptKey = "resume"
456 next.ResumeSessionID = s.ID
457 for _, kind := range []string{"unknown", "account", "connection", "policy"} {
458 t.Run(kind, func(t *testing.T) {
459 bad := next
460 bad.AttemptKey = "bad"
461 switch kind {
462 case "unknown":
463 bad.ResumeSessionID = "00000000-0000-4000-8000-000000000099"
464 case "account":
465 bad.Selection.AccountID = "different"
466 case "connection":
467 bad.Selection.ConnectionID = "different"
468 case "policy":
469 in := f.inputs
470 in.Tools = append(append([]string{}, in.Tools...), "mcp__equipo__other")
471 p, e := provider.BuildPolicy(f.lease.Binding(), in)
472 if e != nil {
473 t.Fatal(e)
474 }
475 bad.Policy = p
476 }
477 if _, e := f.l.Open(context.Background(), bad); e == nil {
478 t.Fatal("invalid resume accepted")
479 }
480 })
481 }
482 resumed, e := f.l.Open(context.Background(), next)
483 if e != nil {
484 t.Fatal(e)
485 }
486 if resumed.ID != s.ID {
487 t.Fatal("resume identity changed")
488 }
489 f.l.Close(context.Background(), resumed)
490
491}
492func TestClaudeSandboxUnavailable(t *testing.T) {
493 f := fixtureFor(t, "Product")
494 f.host.mode = "sandbox"
495 if _, e := f.l.Open(context.Background(), f.launch); e == nil {
496 t.Fatal("sandbox dependency failure admitted")
497 }
498 if f.capture.inputs != 0 {
499 t.Fatal("dependency control sent prompt")
500 }
501}
502func TestClaudeReadiness(t *testing.T) {
503 for _, mode := range []string{"capture", "identity", "digest", "malformed_capture", "config", "no_events", "generation", "refresh", "contained"} {
504 t.Run(mode, func(t *testing.T) {
505 f := fixtureFor(t, "Engineering")
506 switch mode {
507 case "capture":
508 f.capture.fail = true
509 case "identity":
510 f.host.account = "wrong"
511 case "malformed_capture":
512 f.capture.malformed = true
513 case "digest":
514 f.l.digest = strings.Repeat("0", 64)
515 }
516 if mode == "capture" || mode == "identity" || mode == "digest" || mode == "malformed_capture" {
517 if _, e := f.l.Open(context.Background(), f.launch); e == nil {
518 t.Fatal("unready launch accepted")
519 }
520 return
521 }
522 s, events := openFixture(t, f)
523 _ = events
524 switch mode {
525 case "config":
526 os.WriteFile(filepath.Join(filepath.Dir(f.launch.Policy.Mounts[len(f.launch.Policy.Mounts)-1].Source), "equipo-settings.json"), []byte(`{}`), 0600)
527 case "no_events":
528 f.l.mu.Lock()
529 f.l.sessions[s.AttemptKey].attached = false
530 f.l.mu.Unlock()
531 case "generation":
532 os.WriteFile(filepath.Join(f.lease.Binding().CredentialHome, ".credentials.json"), []byte(`{"fake":"new"}`), 0600)
533 f.host.account = "wrong"
534 case "refresh":
535 os.WriteFile(filepath.Join(f.lease.Binding().Home, ".credentials.json"), []byte(`{"fake":"refresh"}`), 0600)
536 f.host.account = "wrong"
537 case "contained":
538 os.Remove(filepath.Join(f.lease.Binding().Home, provider.IdentityFile))
539 }
540 if e := f.l.StartTurn(context.Background(), s, provider.Turn{ID: "t", AdmissionID: "a", Prompt: "tiny"}); e == nil {
541 t.Fatal("unready turn accepted")
542 }
543 if f.capture.inputs != 0 {
544 t.Fatal("unready prompt written")
545 }
546 })
547 }
548}
549func TestClaudeTerminalErrors(t *testing.T) {
550 for _, mode := range []string{"rate", "identity", "exit", "hang", "missing", "partial", "oversized"} {
551 t.Run(mode, func(t *testing.T) {
552 f := fixtureFor(t, "Review")
553 f.host.mode = mode
554 s, events := openFixture(t, f)
555 if e := f.l.StartTurn(context.Background(), s, provider.Turn{ID: "t", AdmissionID: "a", Prompt: "tiny"}); e != nil {
556 t.Fatal(e)
557 }
558 if mode == "hang" {
559 f.l.Interrupt(context.Background(), s)
560 } else {
561 ev := terminal(t, events)
562 if mode != "exit" && ev.Kind == "turn.completed" {
563 t.Fatal("failure completed")
564 }
565 }
566 f.l.Close(context.Background(), s)
567 next := f.launch
568 next.AttemptKey = "resume"
569 next.ResumeSessionID = s.ID
570 if _, e := f.l.Open(context.Background(), next); e == nil {
571 t.Fatal("uncertain/failed session resumed")
572 }
573 })
574 }
575}
576
577func TestClaudeObservedIdentity(t *testing.T) {
578 f := fixtureFor(t, "Engineering")
579 observed, e := f.l.Preflight(context.Background(), f.lease.Binding(), f.launch.Policy)
580 if e != nil {
581 t.Fatal(e)
582 }
583 if observed.HomeID != "" || observed.AccountID != "account@example.invalid" || observed.ProviderVersion != Version {
584 t.Fatalf("identity was not CLI observed: %+v", observed)
585 }
586}
587func TestClaudePolicyRefusals(t *testing.T) {
588 for _, field := range []string{"settings", "weaker-proc", "autoMemoryEnabled", "autoDreamEnabled", "plugin-authoring@builtin", "mcp", "tools", "argv", "env", "version", "helper", "managed", "managed_instruction", "hash"} {
589 t.Run(field, func(t *testing.T) {
590 f := fixtureFor(t, "Engineering")
591 in := f.inputs
592 switch field {
593 case "autoMemoryEnabled", "autoDreamEnabled", "plugin-authoring@builtin":
594 var v map[string]any
595 json.Unmarshal(in.Settings, &v)
596 if field == "plugin-authoring@builtin" {
597 v["enabledPlugins"].(map[string]any)[field] = true
598 } else {
599 v[field] = true
600 }
601 in.Settings, _ = json.Marshal(v)
602 case "settings":
603 var v map[string]any
604 json.Unmarshal(in.Settings, &v)
605 v["sandbox"].(map[string]any)["enabled"] = false
606 in.Settings, _ = json.Marshal(v)
607 case "weaker-proc":
608 var v map[string]any
609 json.Unmarshal(in.Settings, &v)
610 v["sandbox"].(map[string]any)["enableWeakerNestedSandbox"] = true
611 in.Settings, _ = json.Marshal(v)
612 case "mcp":
613 in.MCP = json.RawMessage(`{"mcpServers":{"other":{"command":"/opt/evil"}}}`)
614 case "tools":
615 in.Tools = append(in.Tools, "WebFetch")
616 case "argv":
617 in.Argv = append(in.Argv, "--dangerously-skip-permissions")
618 case "version":
619 in.ProviderVersion = "2.1.313"
620 case "managed", "managed_instruction":
621 path := filepath.Join(t.TempDir(), "managed.json")
622 os.WriteFile(path, []byte(`{"sandbox":{"enabled":false}}`), 0600)
623 mount := provider.Mount{Source: path, Target: "/etc/claude-code/managed-settings.json", ReadOnly: true}
624 if field == "managed_instruction" {
625 in.InstructionFiles = append(in.InstructionFiles, mount)
626 } else {
627 in.RuntimeFiles = append(in.RuntimeFiles, mount)
628 }
629 case "helper":
630 in.RuntimeFiles = in.RuntimeFiles[:1]
631 }
632 p, e := provider.BuildPolicy(f.lease.Binding(), in)
633 if e != nil {
634 t.Fatal(e)
635 }
636 switch field {
637 case "env":
638 delete(p.Env, "DISABLE_AUTOUPDATER")
639 case "hash":
640 p.Hash = "wrong"
641 }
642 launch := f.launch
643 launch.Policy = p
644 if _, e := f.l.Open(context.Background(), launch); e == nil {
645 t.Fatal("unsafe policy accepted")
646 }
647 })
648 }
649}
650func TestClaudeRefreshBeforeTurn(t *testing.T) {
651 for _, kind := range []string{"source", "runtime"} {
652 t.Run(kind, func(t *testing.T) {
653 f := fixtureFor(t, "Review")
654 s, events := openFixture(t, f)
655 home := f.lease.Binding().CredentialHome
656 if kind == "runtime" {
657 home = f.lease.Binding().Home
658 }
659 os.WriteFile(filepath.Join(home, ".credentials.json"), []byte(`{"fake":"new generation"}`), 0600)
660 e := f.l.StartTurn(context.Background(), s, provider.Turn{ID: "t", AdmissionID: "a", Prompt: "tiny"})
661 if kind == "runtime" {
662 if !errors.Is(e, provider.ErrAccountMaintenance) {
663 t.Fatal("runtime refresh did not require sign-in", e)
664 }
665 got, _ := os.ReadFile(filepath.Join(f.lease.Binding().CredentialHome, ".credentials.json"))
666 if string(got) == `{"fake":"new generation"}` {
667 t.Fatal("runtime credentials committed")
668 }
669 } else {
670 if e != nil {
671 t.Fatal(e)
672 }
673 terminal(t, events)
674 }
675 })
676 }
677}
678
679func TestClaudeResumeLatestAttempt(t *testing.T) {
680 f := fixtureFor(t, "Review")
681 s, events := openFixture(t, f)
682 turn := provider.Turn{ID: "t1", AdmissionID: "a1", Prompt: "tiny"}
683 if e := f.l.StartTurn(context.Background(), s, turn); e != nil {
684 t.Fatal(e)
685 }
686 terminal(t, events)
687 if e := f.l.Close(context.Background(), s); e != nil {
688 t.Fatal(e)
689 }
690 next := f.launch
691 next.AttemptKey = "resume-1"
692 next.ResumeSessionID = s.ID
693 s2, e := f.l.Open(context.Background(), next)
694 if e != nil {
695 t.Fatal(e)
696 }
697 f.l.Events(context.Background(), s2)
698 if e = f.l.StartTurn(context.Background(), s2, turn); e == nil {
699 t.Error("resumed admission replayed")
700 }
701 f.l.Interrupt(context.Background(), s2)
702 f.l.Close(context.Background(), s2)
703 next.AttemptKey = "resume-2"
704 if _, e = f.l.Open(context.Background(), next); e == nil {
705 t.Fatal("old completion overrode newer uncertainty")
706 }
707}
708
709func TestClaudeToolHash(t *testing.T) {
710 f := fixtureFor(t, "Engineering")
711 in := f.inputs
712 in.Tools = append(append([]string{}, in.Tools...), "mcp__equipo__new_tool")
713 changed, e := provider.BuildPolicy(f.lease.Binding(), in)
714 if e != nil {
715 t.Fatal(e)
716 }
717 if changed.Hash == f.launch.Policy.Hash {
718 t.Fatal("tool inventory missing from policy hash")
719 }
720}
721func TestClaudeActiveLease(t *testing.T) {
722 f := fixtureFor(t, "Review")
723 f.host.mode = "hang"
724 s, _ := openFixture(t, f)
725 if e := f.l.StartTurn(context.Background(), s, provider.Turn{ID: "t", AdmissionID: "a", Prompt: "tiny"}); e != nil {
726 t.Fatal(e)
727 }
728 os.WriteFile(filepath.Join(f.lease.Binding().CredentialHome, ".credentials.json"), []byte(`{"fake":"replacement"}`), 0600)
729 if e := f.lease.Validate(context.Background()); !errors.Is(e, provider.ErrContainment) {
730 t.Fatalf("active interval not checked: %v", e)
731 }
732}
733
734func TestClaudeNativeIdentityMetadata(t *testing.T) {
735 for _, kind := range []string{"staged", "source", "runtime"} {
736 t.Run(kind, func(t *testing.T) {
737 f := fixtureFor(t, "Review")
738 if kind == "staged" {
739 raw, e := os.ReadFile(filepath.Join(f.lease.Binding().Home, ".claude.json"))
740 if e != nil {
741 t.Fatal(e)
742 }
743 if strings.Contains(string(raw), "hooks") || strings.Contains(string(raw), "projects") || !strings.Contains(string(raw), "account@example.invalid") {
744 t.Fatalf("unsafe metadata import: %s", raw)
745 }
746 return
747 }
748 s, _ := openFixture(t, f)
749 home := f.lease.Binding().CredentialHome
750 if kind == "runtime" {
751 home = f.lease.Binding().Home
752 }
753 os.WriteFile(filepath.Join(home, ".claude.json"), []byte(`{"oauthAccount":{"emailAddress":"wrong@example.invalid"}}`), 0600)
754 if e := f.l.StartTurn(context.Background(), s, provider.Turn{ID: "t", AdmissionID: "a", Prompt: "tiny"}); e == nil {
755 t.Fatal("changed native identity metadata admitted")
756 }
757 if f.capture.inputs != 0 {
758 t.Fatal("prompt sent after metadata change")
759 }
760 })
761 }
762}
763
764func TestClaudeConstructor(t *testing.T) {
765 var host *fakeHost
766 var capture *captureFactory
767 for _, pair := range []struct {
768 host provider.ProcessHost
769 capture provider.CaptureFactory
770 }{{nil, &captureFactory{}}, {&fakeHost{}, nil}, {host, &captureFactory{}}, {&fakeHost{}, capture}} {
771 if _, e := New(pair.host, pair.capture); e == nil {
772 t.Fatal("missing dependency accepted")
773 }
774 }
775}
776func TestClaudeConcurrentSession(t *testing.T) {
777 f := fixtureFor(t, "Review")
778 _, _ = openFixture(t, f)
779 next := f.launch
780 next.AttemptKey = "second"
781 if _, e := f.l.Open(context.Background(), next); e == nil {
782 t.Fatal("two processes admitted on one account lease")
783 }
784}
785
786func TestClaudeInitPolicy(t *testing.T) {
787 for _, mode := range []string{"tools", "plugins", "skills", "permission", "version", "model", "mcp"} {
788 t.Run(mode, func(t *testing.T) {
789 f := fixtureFor(t, "Review")
790 f.host.mode = mode
791 s, events := openFixture(t, f)
792 if e := f.l.StartTurn(context.Background(), s, provider.Turn{ID: "t", AdmissionID: "a", Prompt: "tiny"}); e != nil {
793 t.Fatal(e)
794 }
795 if ev := terminal(t, events); ev.Kind != "turn.failed" {
796 t.Fatal("unexpected init policy accepted")
797 }
798 })
799 }
800}
801func TestClaudeCaptureSequence(t *testing.T) {
802 f := fixtureFor(t, "Review")
803 f.capture.zeroSequence = true
804 s, events := openFixture(t, f)
805 if e := f.l.StartTurn(context.Background(), s, provider.Turn{ID: "t", AdmissionID: "a", Prompt: "tiny"}); e != nil {
806 t.Fatal(e)
807 }
808 if ev := terminal(t, events); ev.Kind != "turn.failed" {
809 t.Fatal("unsequenced frame accepted")
810 }
811}
812
813type blockedInput struct {
814 underlying io.WriteCloser
815 started, done chan struct{}
816 once sync.Once
817}
818
819func (b *blockedInput) Write(raw []byte) (int, error) {
820 close(b.started)
821 <-b.done
822 return 0, io.ErrClosedPipe
823}
824func (b *blockedInput) Close() error {
825 b.once.Do(func() { close(b.done) })
826 return b.underlying.Close()
827}
828func TestClaudeWriteCancellation(t *testing.T) {
829 f := fixtureFor(t, "Review")
830 f.capture.block = true
831 s, _ := openFixture(t, f)
832 ctx, cancel := context.WithCancel(context.Background())
833 defer cancel()
834 returned := make(chan error, 1)
835 go func() { returned <- f.l.StartTurn(ctx, s, provider.Turn{ID: "t", AdmissionID: "a", Prompt: "tiny"}) }()
836 <-f.capture.blocker.started
837 cancel()
838 select {
839 case e := <-returned:
840 if e == nil {
841 t.Fatal("cancelled write succeeded")
842 }
843 case <-time.After(200 * time.Millisecond):
844 f.capture.blocker.Close()
845 <-returned
846 t.Fatal("cancelled admission left stdin blocked")
847 }
848}
849
850func TestClaudeRefreshWithConfigTamper(t *testing.T) {
851 f := fixtureFor(t, "Review")
852 s, _ := openFixture(t, f)
853 os.WriteFile(filepath.Join(f.lease.Binding().Home, ".credentials.json"), []byte(`{"fake":"refreshed"}`), 0600)
854 for _, mount := range f.launch.Policy.Mounts {
855 if mount.Target == provider.SettingsPath {
856 os.WriteFile(mount.Source, []byte(`{}`), 0600)
857 }
858 }
859 if e := f.l.StartTurn(context.Background(), s, provider.Turn{ID: "t", AdmissionID: "a", Prompt: "tiny"}); e == nil {
860 t.Fatal("tampered config admitted after refresh")
861 }
862 f.l.mu.Lock()
863 stopped := f.l.sessions[s.AttemptKey].ctx.Err() != nil
864 f.l.mu.Unlock()
865 if !stopped {
866 t.Fatal("tampered refresh left the attempt running")
867 }
868}
869
870type directGuardCapture struct {
871 inner provider.CaptureFactory
872 fail bool
873 bound, turns int
874}
875type directGuardInput struct {
876 io.WriteCloser
877 owner *directGuardCapture
878}
879
880func (c *directGuardCapture) Open(ctx context.Context, p provider.Process, l provider.Launch) (*provider.Capture, error) {
881 cap, e := c.inner.Open(ctx, p, l)
882 if e == nil {
883 cap.Input = &directGuardInput{cap.Input, c}
884 }
885 return cap, e
886}
887func (w *directGuardInput) BindSession(context.Context, provider.Session) error {
888 w.owner.bound++
889 return nil
890}
891func (w *directGuardInput) BeginTurn(context.Context, provider.Session, provider.Turn) error {
892 w.owner.turns++
893 if w.owner.fail {
894 return io.ErrClosedPipe
895 }
896 return nil
897}
898
899func TestDirectJournalAdapterBarrier(t *testing.T) {
900 for _, fail := range []bool{false, true} {
901 t.Run(fmt.Sprint(fail), func(t *testing.T) {
902 f := fixtureFor(t, "Engineering")
903 guard := &directGuardCapture{inner: f.l.captures, fail: fail}
904 f.l.captures = guard
905 session, ch := openFixture(t, f)
906 if guard.bound != 1 {
907 t.Fatal("session not durably bound")
908 }
909 err := f.l.StartTurn(context.Background(), session, provider.Turn{ID: "direct-turn", AdmissionID: "direct-admission", Prompt: "hello"})
910 if fail {
911 if err == nil {
912 t.Fatal("failed journal barrier ignored")
913 }
914 f.capture.mu.Lock()
915 n := f.capture.inputs
916 f.capture.mu.Unlock()
917 if n != 0 {
918 t.Fatal("failed barrier sent input")
919 }
920 } else {
921 if err != nil {
922 t.Fatal(err)
923 }
924 event := terminal(t, ch)
925 if event.Sequence <= 0 {
926 t.Fatal("capture sequence lost before projection")
927 }
928 }
929 if guard.turns != 1 {
930 t.Fatal("journal turn barrier not called")
931 }
932 })
933 }
934}
935
936func TestRefreshWithoutCertifiedHostFailsClosed(t *testing.T) {
937 f := fixtureFor(t, "Review")
938 in, _, err := policyInputs(f.launch.Policy)
939 if err != nil {
940 t.Fatal(err)
941 }
942 in.AuthHost = ""
943 in.EgressHosts = []string{"api.anthropic.com"}
944 f.launch.Policy, err = provider.BuildPolicy(f.launch.Binding, in)
945 if err != nil {
946 t.Fatal(err)
947 }
948 s, _ := openFixture(t, f)
949 if err = os.WriteFile(filepath.Join(f.launch.Binding.Home, ".credentials.json"), []byte(`{"fake":"refreshed"}`), 0600); err != nil {
950 t.Fatal(err)
951 }
952 t.Setenv("EQUIPO_AUTH_HOST", "auth.claude.example")
953 if err = f.l.StartTurn(context.Background(), s, provider.Turn{ID: "no-refresh", AdmissionID: "no-refresh", Prompt: "never sent"}); !errors.Is(err, provider.ErrAccountMaintenance) {
954 t.Fatalf("uncertified refresh: %v", err)
955 }
956}
957