package claude import ( "bufio" "bytes" "context" "crypto/sha256" "encoding/hex" "encoding/json" "errors" "fmt" "io" "os" "os/exec" "path/filepath" "reflect" "strings" "sync" "testing" "time" "amadan.net/oficina/equipo/internal/runner/provider" ) const fakeCLI = `import sys,json,os args=sys.argv[1:] with open(os.path.join(os.environ['CLAUDE_CONFIG_DIR'],'history.jsonl'),'w') as config: config.write('{"trust":"fake-cli-write"}') if 'auth' in args: try: with open(os.path.join(os.environ['CLAUDE_CONFIG_DIR'],'.claude.json')) as f: email=json.load(f).get('oauthAccount',{}).get('emailAddress') except FileNotFoundError: email=None if os.environ['FAKE_ACCOUNT']!='account@example.invalid': email=os.environ['FAKE_ACCOUNT'] print(json.dumps({'loggedIn':True,'authMethod':'claude.ai','email':email})) sys.exit(0) if os.environ['FAKE_MODE']=='sandbox': print('Sandbox required but unavailable',file=sys.stderr) print(json.dumps({'type':'result','session_id':'dependency','subtype':'error_during_execution','is_error':True})) sys.exit(1) sid=args[args.index('--resume')+1] if '--resume' in args else args[args.index('--session-id')+1] idx=0 for line in sys.stdin: v=json.loads(line) if v['type']!='user': sys.exit(2) 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':[]} if os.environ.get('FAKE_TOOLS'): init['tools']=[t for t in json.loads(os.environ['FAKE_TOOLS']) if t!='mcp__equipo__permission'] if os.environ['FAKE_MODE']=='identity': init['session_id']='different' if os.environ['FAKE_MODE']=='tools': init['tools'].append('WebFetch') if os.environ['FAKE_MODE']=='plugins': init['plugins']=[{'name':'extra','path':'/untrusted','source':'extra'}] if os.environ['FAKE_MODE']=='skills': init['skills']=['extra'] if os.environ['FAKE_MODE']=='permission': init['permissionMode']='bypassPermissions' if os.environ['FAKE_MODE']=='version': init['claude_code_version']='different' if os.environ['FAKE_MODE']=='model': init['model']='fallback' if os.environ['FAKE_MODE']=='mcp': init['mcp_servers'].append({'name':'extra','status':'connected'}) print(json.dumps(init),flush=True) if os.environ['FAKE_MODE']=='hang': continue if os.environ['FAKE_MODE']=='missing': sys.exit(0) if os.environ['FAKE_MODE']=='partial': print('{broken',flush=True) sys.exit(0) if os.environ['FAKE_MODE']=='oversized': print('x'*1048577,flush=True) sys.exit(0) 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) idx+=1 print('non JSON diagnostic',file=sys.stderr) sys.exit(7 if os.environ['FAKE_MODE']=='exit' and idx else 0) ` type fakeProcess struct { cmd *exec.Cmd in io.WriteCloser out, err io.ReadCloser done chan struct{} exit provider.Exit waitErr error } func (p *fakeProcess) ID() string { return "fake" } func (p *fakeProcess) Stdin() io.WriteCloser { return p.in } func (p *fakeProcess) Stdout() io.ReadCloser { return p.out } func (p *fakeProcess) Stderr() io.ReadCloser { return p.err } func (p *fakeProcess) Wait(ctx context.Context) (provider.Exit, error) { select { case <-ctx.Done(): return provider.Exit{}, ctx.Err() case <-p.done: return p.exit, p.waitErr } } type fakeHost struct { processes []*fakeProcess mu sync.Mutex launches []provider.Launch argv [][]string mode, account, binary string } func (h *fakeHost) Start(ctx context.Context, l provider.Launch, args []string) (provider.Process, error) { if _, e := provider.AttestLaunch(l, args); e != nil { return nil, e } h.mu.Lock() h.launches = append(h.launches, l) h.argv = append(h.argv, append([]string(nil), args...)) mode, account := h.mode, h.account h.mu.Unlock() cmd := exec.CommandContext(ctx, "/usr/bin/python3", append([]string{h.binary}, args[1:]...)...) cmd.Dir = l.Workspace cmd.Env = []string{"PATH=/usr/bin:/bin", "HOME=" + l.Binding.Home, "FAKE_MODE=" + mode, "FAKE_ACCOUNT=" + account} for k, v := range l.Policy.Env { if k == "CLAUDE_CONFIG_DIR" || k == "CLAUDE_SECURESTORAGE_CONFIG_DIR" { v = l.Binding.Home } cmd.Env = append(cmd.Env, k+"="+v) } var manifest struct{ Tools []string } json.Unmarshal(l.Policy.Manifest, &manifest) toolJSON, _ := json.Marshal(manifest.Tools) cmd.Env = append(cmd.Env, "FAKE_TOOLS="+string(toolJSON)) in, _ := cmd.StdinPipe() out, outWrite, _ := os.Pipe() errout, errWrite, _ := os.Pipe() cmd.Stdout = outWrite cmd.Stderr = errWrite if e := cmd.Start(); e != nil { return nil, e } p := &fakeProcess{cmd: cmd, in: in, out: out, err: errout, done: make(chan struct{})} h.mu.Lock() h.processes = append(h.processes, p) h.mu.Unlock() go func() { e := cmd.Wait() outWrite.Close() errWrite.Close() p.exit = provider.Exit{Code: cmd.ProcessState.ExitCode(), ObservedAt: time.Now()} if e != nil { var x *exec.ExitError if !errors.As(e, &x) { p.waitErr = e } } close(p.done) }() return p, nil } type captureFactory struct { block bool blocker *blockedInput malformed, zeroSequence bool opens int mu sync.Mutex inputs int fail bool } type recordedInput struct { io.WriteCloser owner *captureFactory } func (w recordedInput) Write(b []byte) (int, error) { w.owner.mu.Lock() w.owner.inputs++ w.owner.mu.Unlock() return w.WriteCloser.Write(b) } func (f *captureFactory) Open(ctx context.Context, p provider.Process, l provider.Launch) (*provider.Capture, error) { f.mu.Lock() f.opens++ nth := f.opens f.mu.Unlock() if f.fail { return nil, errors.New("capture failed") } if f.malformed && nth == 3 { return &provider.Capture{Input: p.Stdin()}, nil } var diagnostics strings.Builder frames := make(chan provider.Frame) done := make(chan error, 1) go func() { defer p.Stdout().Close() defer p.Stderr().Close() stderrDone := make(chan struct{}) go func() { io.Copy(&diagnostics, p.Stderr()); close(stderrDone) }() scan := bufio.NewScanner(p.Stdout()) scan.Buffer(make([]byte, 4096), MaxFrameBytes+1) var seq int64 for scan.Scan() { seq++ if f.zeroSequence { seq = 0 } b := bytes.Clone(scan.Bytes()) select { case frames <- provider.Frame{Sequence: seq, Bytes: b}: case <-ctx.Done(): close(frames) <-stderrDone done <- ctx.Err() return } } close(frames) <-stderrDone done <- scan.Err() close(done) }() var input io.WriteCloser = recordedInput{p.Stdin(), f} if f.block && nth == 3 { f.blocker = &blockedInput{underlying: input, started: make(chan struct{}), done: make(chan struct{})} input = f.blocker } return &provider.Capture{Input: input, Frames: frames, Done: done, Diagnostics: func() string { return diagnostics.String() }}, nil } type fixture struct { l *Launcher host *fakeHost capture *captureFactory lease *provider.AccountLease launch provider.Launch inputs provider.PolicyInputs interactive string } func fixtureFor(t *testing.T, role string) *fixture { t.Helper() root := t.TempDir() source := filepath.Join(root, "dedicated") os.Mkdir(source, 0700) id := provider.Identity{AccountID: "account@example.invalid", HomeID: "equipo-home", ProviderVersion: Version} b := provider.Binding{ID: "binding", Home: source, AccountID: id.AccountID, Provider: "claude", Expected: id, RuntimeRoot: filepath.Join(root, "homes")} raw, _ := json.Marshal(id) os.WriteFile(filepath.Join(source, provider.IdentityFile), raw, 0600) os.WriteFile(filepath.Join(source, ".credentials.json"), []byte(`{"fake":"login"}`), 0600) os.WriteFile(filepath.Join(source, ".claude.json"), []byte(`{"oauthAccount":{"emailAddress":"account@example.invalid","accountUuid":"fake-account"},"projects":{"untrusted":"trust"},"hooks":{"evil":true}}`), 0600) lease, e := provider.OpenAccount(context.Background(), b) if e != nil { t.Fatal(e) } t.Cleanup(func() { lease.Close() }) binary := filepath.Join(root, "fake-cli") os.WriteFile(binary, []byte(fakeCLI), 0700) helperFile := filepath.Join(root, "helper") os.WriteFile(helperFile, []byte("fake helper"), 0700) work, scratch := filepath.Join(root, "workspace"), filepath.Join(root, "scratch") os.Mkdir(work, 0700) os.Mkdir(scratch, 0700) interactive := filepath.Join(root, "interactive") os.Mkdir(interactive, 0700) os.WriteFile(filepath.Join(interactive, "settings.json"), []byte(`{"trust":"unchanged"}`), 0600) 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"}} in, e = PolicyInputs(lease.Binding(), in, role, "claude-haiku-5-5") if e != nil { t.Fatal(e) } policy, e := provider.BuildPolicy(lease.Binding(), in) if e != nil { t.Fatal(e) } host := &fakeHost{binary: binary, account: id.AccountID} t.Cleanup(func() { host.mu.Lock() defer host.mu.Unlock() for _, p := range host.processes { p.cmd.Process.Kill() <-p.done p.in.Close() p.out.Close() p.err.Close() } }) cap := &captureFactory{} l, e := New(host, cap) if e != nil { t.Fatal(e) } sum := sha256.Sum256([]byte(fakeCLI)) l.digest = hex.EncodeToString(sum[:]) 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} } func openFixture(t *testing.T, f *fixture) (provider.Session, <-chan provider.Event) { t.Helper() ctx, cancel := context.WithTimeout(context.Background(), 8*time.Second) t.Cleanup(cancel) s, e := f.l.Open(ctx, f.launch) if e != nil { t.Fatal(e) } t.Cleanup(func() { ctx, c := context.WithTimeout(context.Background(), time.Second); defer c(); f.l.Close(ctx, s) }) events, e := f.l.Events(ctx, s) if e != nil { t.Fatal(e) } return s, events } func terminal(t *testing.T, events <-chan provider.Event) provider.Event { t.Helper() timer := time.NewTimer(3 * time.Second) defer timer.Stop() for { select { case ev, ok := <-events: if !ok { t.Fatal("events ended without terminal") } if strings.HasPrefix(ev.Kind, "turn.") { return ev } case <-timer.C: t.Fatal("no terminal event") } } } func TestClaudeLaunchPolicy(t *testing.T) { for _, role := range []string{"Engineering", "Review", "Product"} { t.Run(role, func(t *testing.T) { f := fixtureFor(t, role) want := []string{"Bash", "Read", "Write", "Edit", "Glob", "Grep"} if role != "Engineering" { want = []string{"Read", "Glob", "Grep", "Bash"} } if !reflect.DeepEqual(f.inputs.Tools, append(append([]string{}, want...), "mcp__equipo__permission")) { t.Fatalf("tools %v", f.inputs.Tools) } var settings map[string]any json.Unmarshal(f.inputs.Settings, &settings) 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 { t.Fatal("hooks/plugins enabled") } if !sameJSON(f.inputs.MCP, []byte(`{"mcpServers":{"equipo":{"type":"stdio","command":"/opt/equipo-tool-proxy","args":["--socket","/tool/equipo.sock"]}}}`)) { t.Fatal("MCP inventory expanded") } sandbox := settings["sandbox"].(map[string]any) if sandbox["enabled"] != true || sandbox["failIfUnavailable"] != true || sandbox["allowUnsandboxedCommands"] != false { t.Fatal("sandbox weakened") } if sandbox["autoAllowBashIfSandboxed"] != true { t.Fatal("automatic shell approval enabled") } // A Bash command gets its own PID namespace and a fresh /proc, // so it cannot read the CLI's environment (the pasted token). if v, set := sandbox["enableWeakerNestedSandbox"]; set && v != false { t.Fatal("tool sandbox may inherit /proc") } if len(sandbox["excludedCommands"].([]any)) != 0 { t.Fatal("excluded commands") } for _, path := range []string{"/home/runner", "/egress", "/tool", "/tool/equipo.sock", "/config", "/proc", "/dev/fd", "/private/state", "/alias/login"} { for _, key := range []string{"denyRead", "denyWrite"} { found := false for _, value := range sandbox["filesystem"].(map[string]any)[key].([]any) { if value == path { found = true } } if !found { t.Fatalf("missing shell %s denial %s", key, path) } } for _, tool := range []string{"Read", "Write", "Edit", "Glob", "Grep"} { for _, suffix := range []string{")", "/**)"} { if !strings.Contains(string(f.inputs.Settings), tool+"(/"+path+suffix) { t.Fatalf("missing native %s denial %s", tool, path) } } } if !strings.Contains(string(f.inputs.Settings), `"`+path+`"`) || !strings.Contains(string(f.inputs.Settings), "Read(/"+path+"/**)") { t.Fatalf("missing protected path %s", path) } } s, _ := openFixture(t, f) _ = s f.host.mu.Lock() last := len(f.host.argv) - 1 args := f.host.argv[last] launch := f.host.launches[last] f.host.mu.Unlock() if launch.Policy.Hash != f.launch.Policy.Hash { t.Fatal("session ID changed reusable policy hash") } 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} if !reflect.DeepEqual(args, expected) { t.Fatalf("argv %v", args) } for k, v := range map[string]string{"CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC": "1", "DISABLE_AUTOUPDATER": "1", "CLAUDE_CONFIG_DIR": "/home/runner"} { if launch.Policy.Env[k] != v { t.Fatalf("env %s", k) } } if _, ok := launch.Policy.Env["CLAUDE_CODE_DISABLE_AUTO_UPDATE"]; ok { t.Fatal("unsupported updater spelling") } in := f.inputs in.Tools = append(append([]string{}, in.Tools...), "WebFetch") p, e := provider.BuildPolicy(f.lease.Binding(), in) if e != nil { t.Fatal(e) } if p.Hash == f.launch.Policy.Hash { t.Fatal("tool not hashed") } }) } } func TestClaudeNoPromptBeforeAdmission(t *testing.T) { f := fixtureFor(t, "Engineering") t.Setenv("CLAUDE_CONFIG_DIR", f.interactive) s, events := openFixture(t, f) f.capture.mu.Lock() n := f.capture.inputs f.capture.mu.Unlock() if n != 0 { t.Fatal("prompt before admission") } if e := f.l.StartTurn(context.Background(), s, provider.Turn{ID: "t", Prompt: "one"}); e == nil { t.Fatal("missing admission accepted") } for i, id := range []string{"t1", "t2"} { if e := f.l.StartTurn(context.Background(), s, provider.Turn{ID: id, AdmissionID: "admit-" + id, Prompt: "tiny"}); e != nil { t.Fatal(e) } ev := terminal(t, events) if ev.Kind != "turn.completed" || ev.TurnID != id || ev.SessionID != s.ID { t.Fatalf("turn %d: %+v", i, ev) } } if e := f.l.Close(context.Background(), s); e != nil { t.Fatal(e) } runtimeConfig, _ := os.ReadFile(filepath.Join(f.lease.Binding().Home, "history.jsonl")) if string(runtimeConfig) != `{"trust":"fake-cli-write"}` { t.Fatal("fake did not exercise config writes") } got, _ := os.ReadFile(filepath.Join(f.interactive, "settings.json")) if string(got) != `{"trust":"unchanged"}` { t.Fatal("interactive config changed") } } func TestClaudeResumeUsesSameBinding(t *testing.T) { f := fixtureFor(t, "Review") s, events := openFixture(t, f) turn := provider.Turn{ID: "t1", AdmissionID: "a1", Prompt: "tiny"} if e := f.l.StartTurn(context.Background(), s, turn); e != nil { t.Fatal(e) } terminal(t, events) if e := f.l.Close(context.Background(), s); e != nil { t.Fatal(e) } next := f.launch next.AttemptKey = "resume" next.ResumeSessionID = s.ID for _, kind := range []string{"unknown", "account", "connection", "policy"} { t.Run(kind, func(t *testing.T) { bad := next bad.AttemptKey = "bad" switch kind { case "unknown": bad.ResumeSessionID = "00000000-0000-4000-8000-000000000099" case "account": bad.Selection.AccountID = "different" case "connection": bad.Selection.ConnectionID = "different" case "policy": in := f.inputs in.Tools = append(append([]string{}, in.Tools...), "mcp__equipo__other") p, e := provider.BuildPolicy(f.lease.Binding(), in) if e != nil { t.Fatal(e) } bad.Policy = p } if _, e := f.l.Open(context.Background(), bad); e == nil { t.Fatal("invalid resume accepted") } }) } resumed, e := f.l.Open(context.Background(), next) if e != nil { t.Fatal(e) } if resumed.ID != s.ID { t.Fatal("resume identity changed") } f.l.Close(context.Background(), resumed) } func TestClaudeSandboxUnavailable(t *testing.T) { f := fixtureFor(t, "Product") f.host.mode = "sandbox" if _, e := f.l.Open(context.Background(), f.launch); e == nil { t.Fatal("sandbox dependency failure admitted") } if f.capture.inputs != 0 { t.Fatal("dependency control sent prompt") } } func TestClaudeReadiness(t *testing.T) { for _, mode := range []string{"capture", "identity", "digest", "malformed_capture", "config", "no_events", "generation", "refresh", "contained"} { t.Run(mode, func(t *testing.T) { f := fixtureFor(t, "Engineering") switch mode { case "capture": f.capture.fail = true case "identity": f.host.account = "wrong" case "malformed_capture": f.capture.malformed = true case "digest": f.l.digest = strings.Repeat("0", 64) } if mode == "capture" || mode == "identity" || mode == "digest" || mode == "malformed_capture" { if _, e := f.l.Open(context.Background(), f.launch); e == nil { t.Fatal("unready launch accepted") } return } s, events := openFixture(t, f) _ = events switch mode { case "config": os.WriteFile(filepath.Join(filepath.Dir(f.launch.Policy.Mounts[len(f.launch.Policy.Mounts)-1].Source), "equipo-settings.json"), []byte(`{}`), 0600) case "no_events": f.l.mu.Lock() f.l.sessions[s.AttemptKey].attached = false f.l.mu.Unlock() case "generation": os.WriteFile(filepath.Join(f.lease.Binding().CredentialHome, ".credentials.json"), []byte(`{"fake":"new"}`), 0600) f.host.account = "wrong" case "refresh": os.WriteFile(filepath.Join(f.lease.Binding().Home, ".credentials.json"), []byte(`{"fake":"refresh"}`), 0600) f.host.account = "wrong" case "contained": os.Remove(filepath.Join(f.lease.Binding().Home, provider.IdentityFile)) } if e := f.l.StartTurn(context.Background(), s, provider.Turn{ID: "t", AdmissionID: "a", Prompt: "tiny"}); e == nil { t.Fatal("unready turn accepted") } if f.capture.inputs != 0 { t.Fatal("unready prompt written") } }) } } func TestClaudeTerminalErrors(t *testing.T) { for _, mode := range []string{"rate", "identity", "exit", "hang", "missing", "partial", "oversized"} { t.Run(mode, func(t *testing.T) { f := fixtureFor(t, "Review") f.host.mode = mode s, events := openFixture(t, f) if e := f.l.StartTurn(context.Background(), s, provider.Turn{ID: "t", AdmissionID: "a", Prompt: "tiny"}); e != nil { t.Fatal(e) } if mode == "hang" { f.l.Interrupt(context.Background(), s) } else { ev := terminal(t, events) if mode != "exit" && ev.Kind == "turn.completed" { t.Fatal("failure completed") } } f.l.Close(context.Background(), s) next := f.launch next.AttemptKey = "resume" next.ResumeSessionID = s.ID if _, e := f.l.Open(context.Background(), next); e == nil { t.Fatal("uncertain/failed session resumed") } }) } } func TestClaudeObservedIdentity(t *testing.T) { f := fixtureFor(t, "Engineering") observed, e := f.l.Preflight(context.Background(), f.lease.Binding(), f.launch.Policy) if e != nil { t.Fatal(e) } if observed.HomeID != "" || observed.AccountID != "account@example.invalid" || observed.ProviderVersion != Version { t.Fatalf("identity was not CLI observed: %+v", observed) } } func TestClaudePolicyRefusals(t *testing.T) { for _, field := range []string{"settings", "weaker-proc", "autoMemoryEnabled", "autoDreamEnabled", "plugin-authoring@builtin", "mcp", "tools", "argv", "env", "version", "helper", "managed", "managed_instruction", "hash"} { t.Run(field, func(t *testing.T) { f := fixtureFor(t, "Engineering") in := f.inputs switch field { case "autoMemoryEnabled", "autoDreamEnabled", "plugin-authoring@builtin": var v map[string]any json.Unmarshal(in.Settings, &v) if field == "plugin-authoring@builtin" { v["enabledPlugins"].(map[string]any)[field] = true } else { v[field] = true } in.Settings, _ = json.Marshal(v) case "settings": var v map[string]any json.Unmarshal(in.Settings, &v) v["sandbox"].(map[string]any)["enabled"] = false in.Settings, _ = json.Marshal(v) case "weaker-proc": var v map[string]any json.Unmarshal(in.Settings, &v) v["sandbox"].(map[string]any)["enableWeakerNestedSandbox"] = true in.Settings, _ = json.Marshal(v) case "mcp": in.MCP = json.RawMessage(`{"mcpServers":{"other":{"command":"/opt/evil"}}}`) case "tools": in.Tools = append(in.Tools, "WebFetch") case "argv": in.Argv = append(in.Argv, "--dangerously-skip-permissions") case "version": in.ProviderVersion = "2.1.313" case "managed", "managed_instruction": path := filepath.Join(t.TempDir(), "managed.json") os.WriteFile(path, []byte(`{"sandbox":{"enabled":false}}`), 0600) mount := provider.Mount{Source: path, Target: "/etc/claude-code/managed-settings.json", ReadOnly: true} if field == "managed_instruction" { in.InstructionFiles = append(in.InstructionFiles, mount) } else { in.RuntimeFiles = append(in.RuntimeFiles, mount) } case "helper": in.RuntimeFiles = in.RuntimeFiles[:1] } p, e := provider.BuildPolicy(f.lease.Binding(), in) if e != nil { t.Fatal(e) } switch field { case "env": delete(p.Env, "DISABLE_AUTOUPDATER") case "hash": p.Hash = "wrong" } launch := f.launch launch.Policy = p if _, e := f.l.Open(context.Background(), launch); e == nil { t.Fatal("unsafe policy accepted") } }) } } func TestClaudeRefreshBeforeTurn(t *testing.T) { for _, kind := range []string{"source", "runtime"} { t.Run(kind, func(t *testing.T) { f := fixtureFor(t, "Review") s, events := openFixture(t, f) home := f.lease.Binding().CredentialHome if kind == "runtime" { home = f.lease.Binding().Home } os.WriteFile(filepath.Join(home, ".credentials.json"), []byte(`{"fake":"new generation"}`), 0600) e := f.l.StartTurn(context.Background(), s, provider.Turn{ID: "t", AdmissionID: "a", Prompt: "tiny"}) if kind == "runtime" { if !errors.Is(e, provider.ErrAccountMaintenance) { t.Fatal("runtime refresh did not require sign-in", e) } got, _ := os.ReadFile(filepath.Join(f.lease.Binding().CredentialHome, ".credentials.json")) if string(got) == `{"fake":"new generation"}` { t.Fatal("runtime credentials committed") } } else { if e != nil { t.Fatal(e) } terminal(t, events) } }) } } func TestClaudeResumeLatestAttempt(t *testing.T) { f := fixtureFor(t, "Review") s, events := openFixture(t, f) turn := provider.Turn{ID: "t1", AdmissionID: "a1", Prompt: "tiny"} if e := f.l.StartTurn(context.Background(), s, turn); e != nil { t.Fatal(e) } terminal(t, events) if e := f.l.Close(context.Background(), s); e != nil { t.Fatal(e) } next := f.launch next.AttemptKey = "resume-1" next.ResumeSessionID = s.ID s2, e := f.l.Open(context.Background(), next) if e != nil { t.Fatal(e) } f.l.Events(context.Background(), s2) if e = f.l.StartTurn(context.Background(), s2, turn); e == nil { t.Error("resumed admission replayed") } f.l.Interrupt(context.Background(), s2) f.l.Close(context.Background(), s2) next.AttemptKey = "resume-2" if _, e = f.l.Open(context.Background(), next); e == nil { t.Fatal("old completion overrode newer uncertainty") } } func TestClaudeToolHash(t *testing.T) { f := fixtureFor(t, "Engineering") in := f.inputs in.Tools = append(append([]string{}, in.Tools...), "mcp__equipo__new_tool") changed, e := provider.BuildPolicy(f.lease.Binding(), in) if e != nil { t.Fatal(e) } if changed.Hash == f.launch.Policy.Hash { t.Fatal("tool inventory missing from policy hash") } } func TestClaudeActiveLease(t *testing.T) { f := fixtureFor(t, "Review") f.host.mode = "hang" s, _ := openFixture(t, f) if e := f.l.StartTurn(context.Background(), s, provider.Turn{ID: "t", AdmissionID: "a", Prompt: "tiny"}); e != nil { t.Fatal(e) } os.WriteFile(filepath.Join(f.lease.Binding().CredentialHome, ".credentials.json"), []byte(`{"fake":"replacement"}`), 0600) if e := f.lease.Validate(context.Background()); !errors.Is(e, provider.ErrContainment) { t.Fatalf("active interval not checked: %v", e) } } func TestClaudeNativeIdentityMetadata(t *testing.T) { for _, kind := range []string{"staged", "source", "runtime"} { t.Run(kind, func(t *testing.T) { f := fixtureFor(t, "Review") if kind == "staged" { raw, e := os.ReadFile(filepath.Join(f.lease.Binding().Home, ".claude.json")) if e != nil { t.Fatal(e) } if strings.Contains(string(raw), "hooks") || strings.Contains(string(raw), "projects") || !strings.Contains(string(raw), "account@example.invalid") { t.Fatalf("unsafe metadata import: %s", raw) } return } s, _ := openFixture(t, f) home := f.lease.Binding().CredentialHome if kind == "runtime" { home = f.lease.Binding().Home } os.WriteFile(filepath.Join(home, ".claude.json"), []byte(`{"oauthAccount":{"emailAddress":"wrong@example.invalid"}}`), 0600) if e := f.l.StartTurn(context.Background(), s, provider.Turn{ID: "t", AdmissionID: "a", Prompt: "tiny"}); e == nil { t.Fatal("changed native identity metadata admitted") } if f.capture.inputs != 0 { t.Fatal("prompt sent after metadata change") } }) } } func TestClaudeConstructor(t *testing.T) { var host *fakeHost var capture *captureFactory for _, pair := range []struct { host provider.ProcessHost capture provider.CaptureFactory }{{nil, &captureFactory{}}, {&fakeHost{}, nil}, {host, &captureFactory{}}, {&fakeHost{}, capture}} { if _, e := New(pair.host, pair.capture); e == nil { t.Fatal("missing dependency accepted") } } } func TestClaudeConcurrentSession(t *testing.T) { f := fixtureFor(t, "Review") _, _ = openFixture(t, f) next := f.launch next.AttemptKey = "second" if _, e := f.l.Open(context.Background(), next); e == nil { t.Fatal("two processes admitted on one account lease") } } func TestClaudeInitPolicy(t *testing.T) { for _, mode := range []string{"tools", "plugins", "skills", "permission", "version", "model", "mcp"} { t.Run(mode, func(t *testing.T) { f := fixtureFor(t, "Review") f.host.mode = mode s, events := openFixture(t, f) if e := f.l.StartTurn(context.Background(), s, provider.Turn{ID: "t", AdmissionID: "a", Prompt: "tiny"}); e != nil { t.Fatal(e) } if ev := terminal(t, events); ev.Kind != "turn.failed" { t.Fatal("unexpected init policy accepted") } }) } } func TestClaudeCaptureSequence(t *testing.T) { f := fixtureFor(t, "Review") f.capture.zeroSequence = true s, events := openFixture(t, f) if e := f.l.StartTurn(context.Background(), s, provider.Turn{ID: "t", AdmissionID: "a", Prompt: "tiny"}); e != nil { t.Fatal(e) } if ev := terminal(t, events); ev.Kind != "turn.failed" { t.Fatal("unsequenced frame accepted") } } type blockedInput struct { underlying io.WriteCloser started, done chan struct{} once sync.Once } func (b *blockedInput) Write(raw []byte) (int, error) { close(b.started) <-b.done return 0, io.ErrClosedPipe } func (b *blockedInput) Close() error { b.once.Do(func() { close(b.done) }) return b.underlying.Close() } func TestClaudeWriteCancellation(t *testing.T) { f := fixtureFor(t, "Review") f.capture.block = true s, _ := openFixture(t, f) ctx, cancel := context.WithCancel(context.Background()) defer cancel() returned := make(chan error, 1) go func() { returned <- f.l.StartTurn(ctx, s, provider.Turn{ID: "t", AdmissionID: "a", Prompt: "tiny"}) }() <-f.capture.blocker.started cancel() select { case e := <-returned: if e == nil { t.Fatal("cancelled write succeeded") } case <-time.After(200 * time.Millisecond): f.capture.blocker.Close() <-returned t.Fatal("cancelled admission left stdin blocked") } } func TestClaudeRefreshWithConfigTamper(t *testing.T) { f := fixtureFor(t, "Review") s, _ := openFixture(t, f) os.WriteFile(filepath.Join(f.lease.Binding().Home, ".credentials.json"), []byte(`{"fake":"refreshed"}`), 0600) for _, mount := range f.launch.Policy.Mounts { if mount.Target == provider.SettingsPath { os.WriteFile(mount.Source, []byte(`{}`), 0600) } } if e := f.l.StartTurn(context.Background(), s, provider.Turn{ID: "t", AdmissionID: "a", Prompt: "tiny"}); e == nil { t.Fatal("tampered config admitted after refresh") } f.l.mu.Lock() stopped := f.l.sessions[s.AttemptKey].ctx.Err() != nil f.l.mu.Unlock() if !stopped { t.Fatal("tampered refresh left the attempt running") } } type directGuardCapture struct { inner provider.CaptureFactory fail bool bound, turns int } type directGuardInput struct { io.WriteCloser owner *directGuardCapture } func (c *directGuardCapture) Open(ctx context.Context, p provider.Process, l provider.Launch) (*provider.Capture, error) { cap, e := c.inner.Open(ctx, p, l) if e == nil { cap.Input = &directGuardInput{cap.Input, c} } return cap, e } func (w *directGuardInput) BindSession(context.Context, provider.Session) error { w.owner.bound++ return nil } func (w *directGuardInput) BeginTurn(context.Context, provider.Session, provider.Turn) error { w.owner.turns++ if w.owner.fail { return io.ErrClosedPipe } return nil } func TestDirectJournalAdapterBarrier(t *testing.T) { for _, fail := range []bool{false, true} { t.Run(fmt.Sprint(fail), func(t *testing.T) { f := fixtureFor(t, "Engineering") guard := &directGuardCapture{inner: f.l.captures, fail: fail} f.l.captures = guard session, ch := openFixture(t, f) if guard.bound != 1 { t.Fatal("session not durably bound") } err := f.l.StartTurn(context.Background(), session, provider.Turn{ID: "direct-turn", AdmissionID: "direct-admission", Prompt: "hello"}) if fail { if err == nil { t.Fatal("failed journal barrier ignored") } f.capture.mu.Lock() n := f.capture.inputs f.capture.mu.Unlock() if n != 0 { t.Fatal("failed barrier sent input") } } else { if err != nil { t.Fatal(err) } event := terminal(t, ch) if event.Sequence <= 0 { t.Fatal("capture sequence lost before projection") } } if guard.turns != 1 { t.Fatal("journal turn barrier not called") } }) } } func TestRefreshWithoutCertifiedHostFailsClosed(t *testing.T) { f := fixtureFor(t, "Review") in, _, err := policyInputs(f.launch.Policy) if err != nil { t.Fatal(err) } in.AuthHost = "" in.EgressHosts = []string{"api.anthropic.com"} f.launch.Policy, err = provider.BuildPolicy(f.launch.Binding, in) if err != nil { t.Fatal(err) } s, _ := openFixture(t, f) if err = os.WriteFile(filepath.Join(f.launch.Binding.Home, ".credentials.json"), []byte(`{"fake":"refreshed"}`), 0600); err != nil { t.Fatal(err) } t.Setenv("EQUIPO_AUTH_HOST", "auth.claude.example") if err = f.l.StartTurn(context.Background(), s, provider.Turn{ID: "no-refresh", AdmissionID: "no-refresh", Prompt: "never sent"}); !errors.Is(err, provider.ErrAccountMaintenance) { t.Fatalf("uncertified refresh: %v", err) } }