// Package realcli runs the pinned Claude CLI itself, in bubblewrap, // against a fake Messages API on loopback. package realcli import ( "bufio" "crypto/sha256" "encoding/hex" "encoding/json" "fmt" "io" "net" "net/http" "net/http/httptest" "os" "os/exec" "path/filepath" "runtime" "slices" "strconv" "strings" "sync" "testing" "time" "amadan.net/oficina/equipo/internal/runner/provider" "amadan.net/oficina/equipo/internal/runner/provider/claude" "amadan.net/oficina/equipo/internal/testci" ) const canary = "sk-ant-oat01-equipo-canary-0f3a9c" // TestStepApprovalInThePinnedCLI: production 2026-11-22. A token // connection sets CLAUDE_CODE_SUBPROCESS_ENV_SCRUB, which turns the // pinned CLI's sandbox auto-approval off, so Engineering's ordinary shell // commands reached the step's permission callback and were refused. This // runs the real CLI under Equipo's Engineering settings, answers every // permission request with claude.StepPermission (over the CLI's stdio // control channel; production carries the same request over MCP), and // holds the approved commands to the sandbox: they run, but read no // protected file, see no credential, reach no network, write nothing // outside the workspace, and leave no process behind. func TestStepApprovalInThePinnedCLI(t *testing.T) { testci.Tools(t, "try-bin", "bwrap") binary := pinnedCLI(t) for _, mode := range []string{"token", "subscription"} { t.Run(mode, func(t *testing.T) { approvalRun(t, binary, mode) }) } } func pinnedCLI(t *testing.T) string { home, err := os.UserHomeDir() if err != nil { t.Fatal(err) } binary := filepath.Join(home, ".local/share/equipo/try/bin/claude") f, err := os.Open(binary) if os.IsNotExist(err) { testci.Absent(t, "pinned Claude 2.1.312 binary absent; the approval regression runs the local pinned installation") } if err != nil { t.Fatal(err) } sum := sha256.New() _, err = io.Copy(sum, f) f.Close() pin, ok := claude.ReleasePin(runtime.GOARCH) if err != nil || !ok || hex.EncodeToString(sum.Sum(nil)) != pin { t.Fatal("pinned Claude digest differs") } return binary } func approvalRun(t *testing.T, binary, mode string) { root := t.TempDir() work, runnerHome, cred, cfg := filepath.Join(root, "workspace"), filepath.Join(root, "home"), filepath.Join(root, "cred"), filepath.Join(root, "config") for _, d := range []string{filepath.Join(work, "internal"), runnerHome, cred, cfg} { if err := os.MkdirAll(d, 0o700); err != nil { t.Fatal(err) } } os.WriteFile(filepath.Join(work, "internal", "door.go"), []byte("package internal\n"), 0o600) os.WriteFile(filepath.Join(cred, ".credentials.json"), []byte(`{"canary":"`+canary+`"}`), 0o600) env := []string{} if mode == "token" { env = append(env, provider.OAuthTokenEnv+"="+canary, provider.ScrubEnv+"=1") } else { os.MkdirAll(filepath.Join(runnerHome, ".claude"), 0o700) os.WriteFile(filepath.Join(runnerHome, ".claude", ".credentials.json"), []byte(`{"claudeAiOauth":{"accessToken":"`+canary+`","refreshToken":"`+canary+`-refresh","expiresAt":4102444800000,"scopes":["user:inference","user:profile"],"subscriptionType":"max"}}`), 0o600) } b := provider.Binding{ID: "binding", Provider: "claude", Home: runnerHome, CredentialHome: cred, RuntimeRoot: filepath.Join(root, "runtime")} profile, _ := provider.Profile("implement") in, err := claude.PolicyInputs(b, provider.PolicyInputs{Action: "implement", Tools: profile.MCPTools()}, profile.Specialist, "claude-opus-5-5") if err != nil { t.Fatal(err) } // StepPermission reads the policy's manifest: its settings and tools. manifest, _ := json.Marshal(map[string]any{"Settings": in.Settings, "Tools": in.Tools, "DeniedPaths": in.DeniedPaths}) policy := provider.Policy{Manifest: manifest} os.WriteFile(filepath.Join(cfg, "equipo-settings.json"), in.Settings, 0o600) os.WriteFile(filepath.Join(cfg, "equipo-mcp.json"), []byte(`{"mcpServers":{}}`), 0o600) marker := "3" + strconv.Itoa(1000+os.Getpid()%8000) api := fakeAPI(t) port := api.URL[strings.LastIndex(api.URL, ":")+1:] // The protected paths come from command substitution, so the CLI // cannot check them itself: only the sandbox stands between the // command and the file. hidden := []string{ `c=$(printf /config); cat $c/equipo-settings.json 2>&1; echo read-rc=$?`, `h=$(printf /home/runner); ls -A $h $h/.claude 2>&1; cat $h/.claude/.credentials.json 2>&1; echo listed`, `k=$(printf ` + cred + `); cat $k/.credentials.json 2>&1; echo cred-rc=$?`, `p=$(printf /proc); env; tr '\0' '\n' < $p/self/environ 2>&1; tr '\0' '\n' < $p/1/environ 2>&1; echo env-done`, `for d in $(printf '/config ` + cred + ` /home/runner'); do echo probe > $d/written 2>&1; done; echo wrote`, `timeout 3 bash -c 'echo > /dev/tcp/127.0.0.1/` + port + `' 2>&1 && echo connected || echo refused`, } script := []tool{bash(`cd internal && ls`), bash(`echo ok > /workspace/written && echo ws-ok`)} for _, c := range hidden { script = append(script, bash(c)) } api.script(append(script, tool{"Bash", map[string]any{"command": "sleep " + marker, "run_in_background": true}})) // The argv Equipo launches, with the permission callback on the CLI's // stdio channel and no MCP servers (this test answers in-process). argv := slices.Clone(in.Argv) for i := range argv { switch argv[i] { case "mcp__equipo__permission": argv[i] = "stdio" } } args := []string{"--unshare-user", "--unshare-pid", "--unshare-ipc", "--unshare-uts", "--die-with-parent", "--new-session", "--ro-bind", "/usr", "/usr", "--symlink", "usr/bin", "/bin", "--symlink", "usr/lib", "/lib", "--symlink", "usr/lib64", "/lib64", "--ro-bind", "/etc", "/etc", "--proc", "/proc", "--dev", "/dev", "--tmpfs", "/tmp", "--bind", runnerHome, "/home/runner", "--bind", work, "/workspace", "--bind", cred, cred, "--bind", cfg, "/config", "--ro-bind", binary, "/opt/claude", "--chdir", "/workspace", "--clearenv", "--setenv", "HOME", "/home/runner", "--setenv", "TMPDIR", "/tmp", "--setenv", "PATH", "/usr/bin:/bin:/opt", "--setenv", "CLAUDE_CODE_TMPDIR", "/tmp", "--setenv", "ANTHROPIC_BASE_URL", api.URL, "--setenv", "CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC", "1", "--setenv", "DISABLE_AUTOUPDATER", "1"} for _, kv := range env { k, v, _ := strings.Cut(kv, "=") args = append(args, "--setenv", k, v) } cmd := exec.Command("bwrap", append(args, argv...)...) stdin, _ := cmd.StdinPipe() stdout, _ := cmd.StdoutPipe() var stderr strings.Builder cmd.Stderr = &stderr if err := cmd.Start(); err != nil { t.Fatal(err) } done := make(chan struct{}) t.Cleanup(func() { _ = cmd.Process.Kill(); <-done }) go func() { _ = cmd.Wait(); close(done) }() send := func(v any) { raw, _ := json.Marshal(v); stdin.Write(append(raw, '\n')) } send(map[string]any{"type": "user", "message": map[string]any{"role": "user", "content": "go"}}) results, asked := map[string]string{}, map[string]string{} uses := map[string]string{} lines := make(chan []byte) go func() { sc := bufio.NewScanner(stdout) sc.Buffer(make([]byte, 1<<20), 16<<20) for sc.Scan() { lines <- slices.Clone(sc.Bytes()) } close(lines) }() deadline := time.After(150 * time.Second) read: for { select { case <-deadline: t.Fatalf("no result in time; stderr: %s", stderr.String()) case line, ok := <-lines: if !ok { break read } var m struct { RequestID string `json:"request_id"` Kind string `json:"type"` Request struct { Subtype string ToolName string `json:"tool_name"` Input json.RawMessage `json:"input"` ToolUseID string `json:"tool_use_id"` } Message struct{ Content []json.RawMessage } } if json.Unmarshal(line, &m) != nil { continue } switch m.Kind { case "control_request": if m.Request.Subtype != "can_use_tool" { continue } raw, _ := json.Marshal(map[string]any{"tool_name": m.Request.ToolName, "tool_use_id": m.Request.ToolUseID, "input": m.Request.Input}) answer := claude.StepPermission(raw, policy) var in struct{ Command string } _ = json.Unmarshal(m.Request.Input, &in) asked[in.Command] = string(answer) send(map[string]any{"type": "control_response", "response": map[string]any{"subtype": "success", "request_id": m.RequestID, "response": json.RawMessage(answer)}}) case "assistant", "user": for _, c := range m.Message.Content { var b struct { Type, ID, Name string ToolUseID string `json:"tool_use_id"` Input map[string]any Content json.RawMessage IsError bool `json:"is_error"` } if json.Unmarshal(c, &b) != nil { continue } if b.Type == "tool_use" { uses[b.ID], _ = b.Input["command"].(string) } if b.Type == "tool_result" { var text string if json.Unmarshal(b.Content, &text) != nil { text = string(b.Content) } results[uses[b.ToolUseID]] = fmt.Sprintf("error=%v %s", b.IsError, text) } } case "result": break read } } } running := false for i := 0; i < 30 && !running; i++ { running = sleeping(marker) time.Sleep(100 * time.Millisecond) } _ = cmd.Process.Kill() <-done if !running { t.Error("the background command never ran") } all := "" for _, r := range results { all += r + "\n" } t.Logf("%s mode: %d tool results, %d asked", mode, len(results), len(asked)) expect := func(command, want string) { t.Helper() got, ok := results[command] if !ok || !strings.Contains(got, want) { t.Errorf("%s: %q, want %q (stderr %s)", command, got, want, stderr.String()) } } expect(`cd internal && ls`, "door.go") expect(`echo ok > /workspace/written && echo ws-ok`, "ws-ok") for _, c := range hidden { // Scrub mode has no automatic approval: each reaches the step. if mode == "token" && !strings.Contains(asked[c], `"allow"`) { t.Errorf("%s: not approved through the step's callback: %q", c, asked[c]) } } expect(hidden[0], "read-rc=1") expect(hidden[1], "listed") expect(hidden[2], "cred-rc=1") expect(hidden[3], "env-done") expect(hidden[4], "wrote") expect(hidden[5], "refused") if strings.Contains(all, canary) || strings.Contains(all, `"enabled":true`) || strings.Contains(all, ".credentials.json\n") { t.Errorf("a sandboxed command read a credential or the policy:\n%s", all) } for _, name := range []string{filepath.Join(cfg, "written"), filepath.Join(cred, "written"), filepath.Join(runnerHome, "written")} { if _, err := os.Stat(name); err == nil { t.Errorf("a sandboxed command wrote %s", name) } } if _, err := os.Stat(filepath.Join(work, "written")); err != nil { t.Error("the workspace write did not land") } if _, ok := asked[`cd internal && ls`]; mode == "token" && !ok { t.Error("in scrub mode an ordinary command did not reach the step's callback") } if api.calls() < len(script)+1 { t.Errorf("the scripted turn did not finish: %d API calls", api.calls()) } for i := 0; i < 50 && sleeping(marker); i++ { time.Sleep(100 * time.Millisecond) } if sleeping(marker) { t.Errorf("background command outlived the session: sleep %s", marker) } } // sleeping reports a host process running `sleep marker`. func sleeping(marker string) bool { entries, _ := os.ReadDir("/proc") for _, e := range entries { raw, err := os.ReadFile(filepath.Join("/proc", e.Name(), "cmdline")) if err == nil && strings.Contains(string(raw), "sleep\x00"+marker) { return true } } return false } type tool struct { name string input map[string]any } func bash(command string) tool { return tool{"Bash", map[string]any{"command": command}} } type api struct { *httptest.Server mu sync.Mutex tools []tool next int n int } func (a *api) script(tools []tool) { a.mu.Lock(); a.tools = tools; a.mu.Unlock() } func (a *api) calls() int { a.mu.Lock(); defer a.mu.Unlock(); return a.n } // fakeAPI answers the Messages API on loopback: each request offering // the Bash tool gets the next scripted tool call, then a closing text. func fakeAPI(t *testing.T) *api { a := &api{} l, err := net.Listen("tcp", "127.0.0.1:0") if err != nil { t.Fatal(err) } a.Server = httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { var body struct { Model string Stream bool Tools []struct{ Name string } } _ = json.NewDecoder(r.Body).Decode(&body) if !strings.HasSuffix(r.URL.Path, "/v1/messages") { if strings.HasSuffix(r.URL.Path, "/count_tokens") { w.Write([]byte(`{"input_tokens":10}`)) return } http.NotFound(w, r) return } block := map[string]any{"type": "text", "text": "done"} stop := "end_turn" if slices.ContainsFunc(body.Tools, func(x struct{ Name string }) bool { return x.Name == "Bash" }) { a.mu.Lock() a.n++ if a.next < len(a.tools) { tl := a.tools[a.next] block = map[string]any{"type": "tool_use", "id": fmt.Sprintf("toolu_%03d", a.next), "name": tl.name, "input": tl.input} stop = "tool_use" a.next++ } a.mu.Unlock() } msg := map[string]any{"id": "msg_x", "type": "message", "role": "assistant", "model": body.Model, "content": []any{}, "stop_reason": nil, "stop_sequence": nil, "usage": map[string]int{"input_tokens": 1, "output_tokens": 1}} if !body.Stream { msg["content"], msg["stop_reason"] = []any{block}, stop json.NewEncoder(w).Encode(msg) return } w.Header().Set("content-type", "text/event-stream") ev := func(name string, v any) { raw, _ := json.Marshal(v) fmt.Fprintf(w, "event: %s\ndata: %s\n\n", name, raw) } ev("message_start", map[string]any{"type": "message_start", "message": msg}) if block["type"] == "tool_use" { input, _ := json.Marshal(block["input"]) ev("content_block_start", map[string]any{"type": "content_block_start", "index": 0, "content_block": map[string]any{"type": "tool_use", "id": block["id"], "name": block["name"], "input": map[string]any{}}}) ev("content_block_delta", map[string]any{"type": "content_block_delta", "index": 0, "delta": map[string]any{"type": "input_json_delta", "partial_json": string(input)}}) } else { ev("content_block_start", map[string]any{"type": "content_block_start", "index": 0, "content_block": map[string]any{"type": "text", "text": ""}}) ev("content_block_delta", map[string]any{"type": "content_block_delta", "index": 0, "delta": map[string]any{"type": "text_delta", "text": "done"}}) } ev("content_block_stop", map[string]any{"type": "content_block_stop", "index": 0}) ev("message_delta", map[string]any{"type": "message_delta", "delta": map[string]any{"stop_reason": stop, "stop_sequence": nil}, "usage": map[string]int{"output_tokens": 1}}) ev("message_stop", map[string]any{"type": "message_stop"}) })) a.Server.Listener.Close() a.Server.Listener = l a.Start() t.Cleanup(a.Close) return a }