| 1 | // Package realcli runs the pinned Claude CLI itself, in bubblewrap, |
| 2 | // against a fake Messages API on loopback. |
| 3 | package realcli |
| 4 | |
| 5 | import ( |
| 6 | "bufio" |
| 7 | "crypto/sha256" |
| 8 | "encoding/hex" |
| 9 | "encoding/json" |
| 10 | "fmt" |
| 11 | "io" |
| 12 | "net" |
| 13 | "net/http" |
| 14 | "net/http/httptest" |
| 15 | "os" |
| 16 | "os/exec" |
| 17 | "path/filepath" |
| 18 | "runtime" |
| 19 | "slices" |
| 20 | "strconv" |
| 21 | "strings" |
| 22 | "sync" |
| 23 | "testing" |
| 24 | "time" |
| 25 | |
| 26 | "amadan.net/oficina/equipo/internal/runner/provider" |
| 27 | "amadan.net/oficina/equipo/internal/runner/provider/claude" |
| 28 | "amadan.net/oficina/equipo/internal/testci" |
| 29 | ) |
| 30 | |
| 31 | const canary = "sk-ant-oat01-equipo-canary-0f3a9c" |
| 32 | |
| 33 | // TestStepApprovalInThePinnedCLI: production 2026-11-22. A token |
| 34 | // connection sets CLAUDE_CODE_SUBPROCESS_ENV_SCRUB, which turns the |
| 35 | // pinned CLI's sandbox auto-approval off, so Engineering's ordinary shell |
| 36 | // commands reached the step's permission callback and were refused. This |
| 37 | // runs the real CLI under Equipo's Engineering settings, answers every |
| 38 | // permission request with claude.StepPermission (over the CLI's stdio |
| 39 | // control channel; production carries the same request over MCP), and |
| 40 | // holds the approved commands to the sandbox: they run, but read no |
| 41 | // protected file, see no credential, reach no network, write nothing |
| 42 | // outside the workspace, and leave no process behind. |
| 43 | func TestStepApprovalInThePinnedCLI(t *testing.T) { |
| 44 | testci.Tools(t, "try-bin", "bwrap") |
| 45 | binary := pinnedCLI(t) |
| 46 | for _, mode := range []string{"token", "subscription"} { |
| 47 | t.Run(mode, func(t *testing.T) { approvalRun(t, binary, mode) }) |
| 48 | } |
| 49 | } |
| 50 | |
| 51 | func pinnedCLI(t *testing.T) string { |
| 52 | home, err := os.UserHomeDir() |
| 53 | if err != nil { |
| 54 | t.Fatal(err) |
| 55 | } |
| 56 | binary := filepath.Join(home, ".local/share/equipo/try/bin/claude") |
| 57 | f, err := os.Open(binary) |
| 58 | if os.IsNotExist(err) { |
| 59 | testci.Absent(t, "pinned Claude 2.1.312 binary absent; the approval regression runs the local pinned installation") |
| 60 | } |
| 61 | if err != nil { |
| 62 | t.Fatal(err) |
| 63 | } |
| 64 | sum := sha256.New() |
| 65 | _, err = io.Copy(sum, f) |
| 66 | f.Close() |
| 67 | pin, ok := claude.ReleasePin(runtime.GOARCH) |
| 68 | if err != nil || !ok || hex.EncodeToString(sum.Sum(nil)) != pin { |
| 69 | t.Fatal("pinned Claude digest differs") |
| 70 | } |
| 71 | return binary |
| 72 | } |
| 73 | |
| 74 | func approvalRun(t *testing.T, binary, mode string) { |
| 75 | root := t.TempDir() |
| 76 | work, runnerHome, cred, cfg := filepath.Join(root, "workspace"), filepath.Join(root, "home"), filepath.Join(root, "cred"), filepath.Join(root, "config") |
| 77 | for _, d := range []string{filepath.Join(work, "internal"), runnerHome, cred, cfg} { |
| 78 | if err := os.MkdirAll(d, 0o700); err != nil { |
| 79 | t.Fatal(err) |
| 80 | } |
| 81 | } |
| 82 | os.WriteFile(filepath.Join(work, "internal", "door.go"), []byte("package internal\n"), 0o600) |
| 83 | os.WriteFile(filepath.Join(cred, ".credentials.json"), []byte(`{"canary":"`+canary+`"}`), 0o600) |
| 84 | env := []string{} |
| 85 | if mode == "token" { |
| 86 | env = append(env, provider.OAuthTokenEnv+"="+canary, provider.ScrubEnv+"=1") |
| 87 | } else { |
| 88 | os.MkdirAll(filepath.Join(runnerHome, ".claude"), 0o700) |
| 89 | 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) |
| 90 | } |
| 91 | b := provider.Binding{ID: "binding", Provider: "claude", Home: runnerHome, CredentialHome: cred, RuntimeRoot: filepath.Join(root, "runtime")} |
| 92 | profile, _ := provider.Profile("implement") |
| 93 | in, err := claude.PolicyInputs(b, provider.PolicyInputs{Action: "implement", Tools: profile.MCPTools()}, profile.Specialist, "claude-opus-5-5") |
| 94 | if err != nil { |
| 95 | t.Fatal(err) |
| 96 | } |
| 97 | // StepPermission reads the policy's manifest: its settings and tools. |
| 98 | manifest, _ := json.Marshal(map[string]any{"Settings": in.Settings, "Tools": in.Tools, "DeniedPaths": in.DeniedPaths}) |
| 99 | policy := provider.Policy{Manifest: manifest} |
| 100 | os.WriteFile(filepath.Join(cfg, "equipo-settings.json"), in.Settings, 0o600) |
| 101 | os.WriteFile(filepath.Join(cfg, "equipo-mcp.json"), []byte(`{"mcpServers":{}}`), 0o600) |
| 102 | |
| 103 | marker := "3" + strconv.Itoa(1000+os.Getpid()%8000) |
| 104 | api := fakeAPI(t) |
| 105 | port := api.URL[strings.LastIndex(api.URL, ":")+1:] |
| 106 | // The protected paths come from command substitution, so the CLI |
| 107 | // cannot check them itself: only the sandbox stands between the |
| 108 | // command and the file. |
| 109 | hidden := []string{ |
| 110 | `c=$(printf /config); cat $c/equipo-settings.json 2>&1; echo read-rc=$?`, |
| 111 | `h=$(printf /home/runner); ls -A $h $h/.claude 2>&1; cat $h/.claude/.credentials.json 2>&1; echo listed`, |
| 112 | `k=$(printf ` + cred + `); cat $k/.credentials.json 2>&1; echo cred-rc=$?`, |
| 113 | `p=$(printf /proc); env; tr '\0' '\n' < $p/self/environ 2>&1; tr '\0' '\n' < $p/1/environ 2>&1; echo env-done`, |
| 114 | `for d in $(printf '/config ` + cred + ` /home/runner'); do echo probe > $d/written 2>&1; done; echo wrote`, |
| 115 | `timeout 3 bash -c 'echo > /dev/tcp/127.0.0.1/` + port + `' 2>&1 && echo connected || echo refused`, |
| 116 | } |
| 117 | script := []tool{bash(`cd internal && ls`), bash(`echo ok > /workspace/written && echo ws-ok`)} |
| 118 | for _, c := range hidden { |
| 119 | script = append(script, bash(c)) |
| 120 | } |
| 121 | api.script(append(script, tool{"Bash", map[string]any{"command": "sleep " + marker, "run_in_background": true}})) |
| 122 | // The argv Equipo launches, with the permission callback on the CLI's |
| 123 | // stdio channel and no MCP servers (this test answers in-process). |
| 124 | argv := slices.Clone(in.Argv) |
| 125 | for i := range argv { |
| 126 | switch argv[i] { |
| 127 | case "mcp__equipo__permission": |
| 128 | argv[i] = "stdio" |
| 129 | } |
| 130 | } |
| 131 | args := []string{"--unshare-user", "--unshare-pid", "--unshare-ipc", "--unshare-uts", "--die-with-parent", "--new-session", |
| 132 | "--ro-bind", "/usr", "/usr", "--symlink", "usr/bin", "/bin", "--symlink", "usr/lib", "/lib", "--symlink", "usr/lib64", "/lib64", |
| 133 | "--ro-bind", "/etc", "/etc", "--proc", "/proc", "--dev", "/dev", "--tmpfs", "/tmp", |
| 134 | "--bind", runnerHome, "/home/runner", "--bind", work, "/workspace", "--bind", cred, cred, "--bind", cfg, "/config", |
| 135 | "--ro-bind", binary, "/opt/claude", "--chdir", "/workspace", "--clearenv", |
| 136 | "--setenv", "HOME", "/home/runner", "--setenv", "TMPDIR", "/tmp", "--setenv", "PATH", "/usr/bin:/bin:/opt", "--setenv", "CLAUDE_CODE_TMPDIR", "/tmp", |
| 137 | "--setenv", "ANTHROPIC_BASE_URL", api.URL, "--setenv", "CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC", "1", "--setenv", "DISABLE_AUTOUPDATER", "1"} |
| 138 | for _, kv := range env { |
| 139 | k, v, _ := strings.Cut(kv, "=") |
| 140 | args = append(args, "--setenv", k, v) |
| 141 | } |
| 142 | cmd := exec.Command("bwrap", append(args, argv...)...) |
| 143 | stdin, _ := cmd.StdinPipe() |
| 144 | stdout, _ := cmd.StdoutPipe() |
| 145 | var stderr strings.Builder |
| 146 | cmd.Stderr = &stderr |
| 147 | if err := cmd.Start(); err != nil { |
| 148 | t.Fatal(err) |
| 149 | } |
| 150 | done := make(chan struct{}) |
| 151 | t.Cleanup(func() { _ = cmd.Process.Kill(); <-done }) |
| 152 | go func() { _ = cmd.Wait(); close(done) }() |
| 153 | send := func(v any) { raw, _ := json.Marshal(v); stdin.Write(append(raw, '\n')) } |
| 154 | send(map[string]any{"type": "user", "message": map[string]any{"role": "user", "content": "go"}}) |
| 155 | |
| 156 | results, asked := map[string]string{}, map[string]string{} |
| 157 | uses := map[string]string{} |
| 158 | lines := make(chan []byte) |
| 159 | go func() { |
| 160 | sc := bufio.NewScanner(stdout) |
| 161 | sc.Buffer(make([]byte, 1<<20), 16<<20) |
| 162 | for sc.Scan() { |
| 163 | lines <- slices.Clone(sc.Bytes()) |
| 164 | } |
| 165 | close(lines) |
| 166 | }() |
| 167 | deadline := time.After(150 * time.Second) |
| 168 | read: |
| 169 | for { |
| 170 | select { |
| 171 | case <-deadline: |
| 172 | t.Fatalf("no result in time; stderr: %s", stderr.String()) |
| 173 | case line, ok := <-lines: |
| 174 | if !ok { |
| 175 | break read |
| 176 | } |
| 177 | var m struct { |
| 178 | RequestID string `json:"request_id"` |
| 179 | Kind string `json:"type"` |
| 180 | Request struct { |
| 181 | Subtype string |
| 182 | ToolName string `json:"tool_name"` |
| 183 | Input json.RawMessage `json:"input"` |
| 184 | ToolUseID string `json:"tool_use_id"` |
| 185 | } |
| 186 | Message struct{ Content []json.RawMessage } |
| 187 | } |
| 188 | if json.Unmarshal(line, &m) != nil { |
| 189 | continue |
| 190 | } |
| 191 | switch m.Kind { |
| 192 | case "control_request": |
| 193 | if m.Request.Subtype != "can_use_tool" { |
| 194 | continue |
| 195 | } |
| 196 | raw, _ := json.Marshal(map[string]any{"tool_name": m.Request.ToolName, "tool_use_id": m.Request.ToolUseID, "input": m.Request.Input}) |
| 197 | answer := claude.StepPermission(raw, policy) |
| 198 | var in struct{ Command string } |
| 199 | _ = json.Unmarshal(m.Request.Input, &in) |
| 200 | asked[in.Command] = string(answer) |
| 201 | send(map[string]any{"type": "control_response", "response": map[string]any{"subtype": "success", "request_id": m.RequestID, "response": json.RawMessage(answer)}}) |
| 202 | case "assistant", "user": |
| 203 | for _, c := range m.Message.Content { |
| 204 | var b struct { |
| 205 | Type, ID, Name string |
| 206 | ToolUseID string `json:"tool_use_id"` |
| 207 | Input map[string]any |
| 208 | Content json.RawMessage |
| 209 | IsError bool `json:"is_error"` |
| 210 | } |
| 211 | if json.Unmarshal(c, &b) != nil { |
| 212 | continue |
| 213 | } |
| 214 | if b.Type == "tool_use" { |
| 215 | uses[b.ID], _ = b.Input["command"].(string) |
| 216 | } |
| 217 | if b.Type == "tool_result" { |
| 218 | var text string |
| 219 | if json.Unmarshal(b.Content, &text) != nil { |
| 220 | text = string(b.Content) |
| 221 | } |
| 222 | results[uses[b.ToolUseID]] = fmt.Sprintf("error=%v %s", b.IsError, text) |
| 223 | } |
| 224 | } |
| 225 | case "result": |
| 226 | break read |
| 227 | } |
| 228 | } |
| 229 | } |
| 230 | running := false |
| 231 | for i := 0; i < 30 && !running; i++ { |
| 232 | running = sleeping(marker) |
| 233 | time.Sleep(100 * time.Millisecond) |
| 234 | } |
| 235 | _ = cmd.Process.Kill() |
| 236 | <-done |
| 237 | if !running { |
| 238 | t.Error("the background command never ran") |
| 239 | } |
| 240 | all := "" |
| 241 | for _, r := range results { |
| 242 | all += r + "\n" |
| 243 | } |
| 244 | t.Logf("%s mode: %d tool results, %d asked", mode, len(results), len(asked)) |
| 245 | expect := func(command, want string) { |
| 246 | t.Helper() |
| 247 | got, ok := results[command] |
| 248 | if !ok || !strings.Contains(got, want) { |
| 249 | t.Errorf("%s: %q, want %q (stderr %s)", command, got, want, stderr.String()) |
| 250 | } |
| 251 | } |
| 252 | expect(`cd internal && ls`, "door.go") |
| 253 | expect(`echo ok > /workspace/written && echo ws-ok`, "ws-ok") |
| 254 | for _, c := range hidden { |
| 255 | // Scrub mode has no automatic approval: each reaches the step. |
| 256 | if mode == "token" && !strings.Contains(asked[c], `"allow"`) { |
| 257 | t.Errorf("%s: not approved through the step's callback: %q", c, asked[c]) |
| 258 | } |
| 259 | } |
| 260 | expect(hidden[0], "read-rc=1") |
| 261 | expect(hidden[1], "listed") |
| 262 | expect(hidden[2], "cred-rc=1") |
| 263 | expect(hidden[3], "env-done") |
| 264 | expect(hidden[4], "wrote") |
| 265 | expect(hidden[5], "refused") |
| 266 | if strings.Contains(all, canary) || strings.Contains(all, `"enabled":true`) || strings.Contains(all, ".credentials.json\n") { |
| 267 | t.Errorf("a sandboxed command read a credential or the policy:\n%s", all) |
| 268 | } |
| 269 | for _, name := range []string{filepath.Join(cfg, "written"), filepath.Join(cred, "written"), filepath.Join(runnerHome, "written")} { |
| 270 | if _, err := os.Stat(name); err == nil { |
| 271 | t.Errorf("a sandboxed command wrote %s", name) |
| 272 | } |
| 273 | } |
| 274 | if _, err := os.Stat(filepath.Join(work, "written")); err != nil { |
| 275 | t.Error("the workspace write did not land") |
| 276 | } |
| 277 | if _, ok := asked[`cd internal && ls`]; mode == "token" && !ok { |
| 278 | t.Error("in scrub mode an ordinary command did not reach the step's callback") |
| 279 | } |
| 280 | if api.calls() < len(script)+1 { |
| 281 | t.Errorf("the scripted turn did not finish: %d API calls", api.calls()) |
| 282 | } |
| 283 | for i := 0; i < 50 && sleeping(marker); i++ { |
| 284 | time.Sleep(100 * time.Millisecond) |
| 285 | } |
| 286 | if sleeping(marker) { |
| 287 | t.Errorf("background command outlived the session: sleep %s", marker) |
| 288 | } |
| 289 | } |
| 290 | |
| 291 | // sleeping reports a host process running `sleep marker`. |
| 292 | func sleeping(marker string) bool { |
| 293 | entries, _ := os.ReadDir("/proc") |
| 294 | for _, e := range entries { |
| 295 | raw, err := os.ReadFile(filepath.Join("/proc", e.Name(), "cmdline")) |
| 296 | if err == nil && strings.Contains(string(raw), "sleep\x00"+marker) { |
| 297 | return true |
| 298 | } |
| 299 | } |
| 300 | return false |
| 301 | } |
| 302 | |
| 303 | type tool struct { |
| 304 | name string |
| 305 | input map[string]any |
| 306 | } |
| 307 | |
| 308 | func bash(command string) tool { return tool{"Bash", map[string]any{"command": command}} } |
| 309 | |
| 310 | type api struct { |
| 311 | *httptest.Server |
| 312 | mu sync.Mutex |
| 313 | tools []tool |
| 314 | next int |
| 315 | n int |
| 316 | } |
| 317 | |
| 318 | func (a *api) script(tools []tool) { a.mu.Lock(); a.tools = tools; a.mu.Unlock() } |
| 319 | func (a *api) calls() int { a.mu.Lock(); defer a.mu.Unlock(); return a.n } |
| 320 | |
| 321 | // fakeAPI answers the Messages API on loopback: each request offering |
| 322 | // the Bash tool gets the next scripted tool call, then a closing text. |
| 323 | func fakeAPI(t *testing.T) *api { |
| 324 | a := &api{} |
| 325 | l, err := net.Listen("tcp", "127.0.0.1:0") |
| 326 | if err != nil { |
| 327 | t.Fatal(err) |
| 328 | } |
| 329 | a.Server = httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 330 | var body struct { |
| 331 | Model string |
| 332 | Stream bool |
| 333 | Tools []struct{ Name string } |
| 334 | } |
| 335 | _ = json.NewDecoder(r.Body).Decode(&body) |
| 336 | if !strings.HasSuffix(r.URL.Path, "/v1/messages") { |
| 337 | if strings.HasSuffix(r.URL.Path, "/count_tokens") { |
| 338 | w.Write([]byte(`{"input_tokens":10}`)) |
| 339 | return |
| 340 | } |
| 341 | http.NotFound(w, r) |
| 342 | return |
| 343 | } |
| 344 | block := map[string]any{"type": "text", "text": "done"} |
| 345 | stop := "end_turn" |
| 346 | if slices.ContainsFunc(body.Tools, func(x struct{ Name string }) bool { return x.Name == "Bash" }) { |
| 347 | a.mu.Lock() |
| 348 | a.n++ |
| 349 | if a.next < len(a.tools) { |
| 350 | tl := a.tools[a.next] |
| 351 | block = map[string]any{"type": "tool_use", "id": fmt.Sprintf("toolu_%03d", a.next), "name": tl.name, "input": tl.input} |
| 352 | stop = "tool_use" |
| 353 | a.next++ |
| 354 | } |
| 355 | a.mu.Unlock() |
| 356 | } |
| 357 | 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}} |
| 358 | if !body.Stream { |
| 359 | msg["content"], msg["stop_reason"] = []any{block}, stop |
| 360 | json.NewEncoder(w).Encode(msg) |
| 361 | return |
| 362 | } |
| 363 | w.Header().Set("content-type", "text/event-stream") |
| 364 | ev := func(name string, v any) { |
| 365 | raw, _ := json.Marshal(v) |
| 366 | fmt.Fprintf(w, "event: %s\ndata: %s\n\n", name, raw) |
| 367 | } |
| 368 | ev("message_start", map[string]any{"type": "message_start", "message": msg}) |
| 369 | if block["type"] == "tool_use" { |
| 370 | input, _ := json.Marshal(block["input"]) |
| 371 | 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{}}}) |
| 372 | 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)}}) |
| 373 | } else { |
| 374 | ev("content_block_start", map[string]any{"type": "content_block_start", "index": 0, "content_block": map[string]any{"type": "text", "text": ""}}) |
| 375 | ev("content_block_delta", map[string]any{"type": "content_block_delta", "index": 0, "delta": map[string]any{"type": "text_delta", "text": "done"}}) |
| 376 | } |
| 377 | ev("content_block_stop", map[string]any{"type": "content_block_stop", "index": 0}) |
| 378 | 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}}) |
| 379 | ev("message_stop", map[string]any{"type": "message_stop"}) |
| 380 | })) |
| 381 | a.Server.Listener.Close() |
| 382 | a.Server.Listener = l |
| 383 | a.Start() |
| 384 | t.Cleanup(a.Close) |
| 385 | return a |
| 386 | } |
| 387 | |