package claude import ( "bytes" "context" "crypto/sha256" "encoding/hex" "encoding/json" "os" "strings" "testing" "time" "amadan.net/oficina/equipo/internal/runner/provider" ) func TestClaudePermissionResponse(t *testing.T) { f := fixtureFor(t, "Engineering") s, events := openFixture(t, f) f.l.mu.Lock() st, _ := f.l.state(s) st.active = true st.turn = provider.Turn{ID: "turn"} f.l.mu.Unlock() ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second) defer cancel() raw := json.RawMessage(`{"tool_name":"AskUserQuestion","input":{"questions":[{"question":"Which?","options":[{"label":"blue"}]}]}}`) result := make(chan json.RawMessage, 1) errs := make(chan error, 1) go func() { v, e := f.l.Permission(ctx, s, raw); result <- v; errs <- e }() var ev provider.Event select { case ev = <-events: case <-ctx.Done(): t.Fatal("permission not relayed") } if ev.Kind != "request" || ev.RequestID == "" { t.Fatal(ev) } for _, input := range []string{`{"answers":{"Which?":"blue"},"command":"evil"}`, `{"answers":{"Other?":"blue"}}`} { if f.l.Respond(ctx, s, provider.Answer{TurnID: "turn", RequestID: ev.RequestID, Behavior: "allow", Input: json.RawMessage(input)}) == nil { t.Fatal("widened answer accepted", input) } } f.capture.mu.Lock() before := f.capture.inputs f.capture.mu.Unlock() if e := f.l.Respond(ctx, s, provider.Answer{TurnID: "turn", RequestID: ev.RequestID, Behavior: "allow", Input: json.RawMessage(`{"answers":{"Which?":"blue"}}`)}); e != nil { t.Fatal(e) } reply := <-result if e := <-errs; e != nil { t.Fatal(e) } var v struct { Behavior string UpdatedInput map[string]json.RawMessage } if json.Unmarshal(reply, &v) != nil || v.Behavior != "allow" || !strings.Contains(string(v.UpdatedInput["questions"]), "options") || !strings.Contains(string(v.UpdatedInput["answers"]), "blue") { t.Fatal(string(reply)) } f.capture.mu.Lock() after := f.capture.inputs f.capture.mu.Unlock() if before != after { t.Fatal("permission reply sent an ordinary prompt") } if f.l.Respond(ctx, s, provider.Answer{TurnID: "turn", RequestID: ev.RequestID, Behavior: "deny"}) == nil { t.Fatal("replayed answer") } for _, name := range f.inputs.Tools { if name == "AskUserQuestion" { t.Fatal("built-in question added to specialist tools") } } } func TestClaudePermissionResponseNativePolicy(t *testing.T) { f := fixtureFor(t, "Engineering") original := permissionRequest{Tool: "Write", Input: json.RawMessage(`{"file_path":"/workspace/hello.txt","content":"hi"}`)} reply, e := permissionResult(original, provider.Answer{Behavior: "allow"}, f.launch.Policy) if e != nil || !strings.Contains(string(reply), `"content":"hi"`) { t.Fatal("original input lost", string(reply), e) } for _, raw := range []string{`{"file_path":"/tool/equipo.sock","content":"hi"}`, `{"file_path":"/workspace/a","content":"hi","policyAmendment":true}`, `{"file_path":"/workspace/a","content":"hi","dangerouslyDisableSandbox":true}`} { bad := original bad.Input = json.RawMessage(raw) if _, e := permissionResult(bad, provider.Answer{Behavior: "allow"}, f.launch.Policy); e == nil { t.Fatal("native policy widened", raw) } } if _, e := permissionResult(original, provider.Answer{Behavior: "allow", Input: json.RawMessage(`{"file_path":"/workspace/replaced"}`)}, f.launch.Policy); e == nil { t.Fatal("native tool input replaced") } deny, e := permissionResult(original, provider.Answer{Behavior: "deny"}, f.launch.Policy) var denied struct{ Behavior, Message string } if e != nil || json.Unmarshal(deny, &denied) != nil || denied.Behavior != "deny" || strings.TrimSpace(denied.Message) == "" { t.Fatal(string(deny), e) } } func TestClaudePermissionResponseScopedMCPPolicy(t *testing.T) { f := fixtureFor(t, "Engineering") in := f.inputs in.Tools = []string{"mcp__equipo__ask_person", "mcp__equipo__submit_candidate"} got, e := PolicyInputs(f.lease.Binding(), in, "Engineering", "claude-haiku-5-5") if e != nil { t.Fatal(e) } var settings struct{ Permissions struct{ Allow []string } } if json.Unmarshal(got.Settings, &settings) != nil || !strings.HasPrefix(strings.Join(settings.Permissions.Allow, ","), strings.Join(in.Tools, ",")) { t.Fatal("scoped MCP would fall through native permission hook", string(got.Settings)) } in.Tools = []string{"mcp__equipo__publish"} if _, e = PolicyInputs(f.lease.Binding(), in, "Engineering", "claude-haiku-5-5"); e == nil { t.Fatal("unscoped MCP permission") } } func TestClaudePermissionResponsePinnedWire(t *testing.T) { raw, e := os.ReadFile("testdata/permission-prompt-2.1.312.json") if e != nil { t.Fatal(e) } var fixture struct{ Request json.RawMessage } if e = json.Unmarshal(raw, &fixture); e != nil { t.Fatal(e) } f := fixtureFor(t, "Engineering") s, events := openFixture(t, f) f.l.mu.Lock() st, _ := f.l.state(s) st.active = true st.turn = provider.Turn{ID: "turn"} f.l.mu.Unlock() ctx, cancel := context.WithTimeout(context.Background(), time.Second) defer cancel() type response struct { raw json.RawMessage err error } // A workspace action inside the profile is answered by Equipo, not relayed. allowed, e := f.l.Permission(ctx, s, fixture.Request) var allow struct{ Behavior string } if e != nil || json.Unmarshal(allowed, &allow) != nil || allow.Behavior != "allow" { t.Fatalf("workspace action not allowed in profile: %s %v", allowed, e) } select { case ev := <-events: t.Fatalf("workspace action relayed to a person: %s", ev.Payload) default: } // Outside the workspace the pinned request still reaches the person. outside := bytes.Replace(fixture.Request, []byte(`/workspace/hello.txt`), []byte(`/srv/hello.txt`), 1) result := make(chan response, 1) go func() { raw, err := f.l.Permission(ctx, s, outside); result <- response{raw, err} }() select { case ev := <-events: if e = f.l.Respond(ctx, s, provider.Answer{TurnID: "turn", RequestID: ev.RequestID, Behavior: "deny"}); e != nil { t.Fatal(e) } case got := <-result: t.Fatalf("pinned permission input rejected: %v", got.err) case <-ctx.Done(): t.Fatal("permission not relayed") } got := <-result var deny struct{ Behavior, Message string } if got.err != nil || json.Unmarshal(got.raw, &deny) != nil || deny.Behavior != "deny" || strings.TrimSpace(deny.Message) == "" { t.Fatalf("pinned denial needs message: %s %v", got.raw, got.err) } // Only the three pinned input fields are accepted. if _, e = f.l.Permission(ctx, s, json.RawMessage(`{"tool_name":"Write","input":{},"tool_use_id":"fixture","permissions":{}}`)); e == nil { t.Fatal("unknown field accepted") } } // TestStepPermission: with nobody to ask, an Engineering step may use its // file tools inside /workspace under the same checks, and its shell, which // the policy confines to the CLI's sandbox; nothing else. func TestStepPermission(t *testing.T) { f := fixtureFor(t, "Engineering") allowed := func(raw string) bool { var v struct{ Behavior string } out := StepPermission(json.RawMessage(raw), f.launch.Policy) if json.Unmarshal(out, &v) != nil { t.Fatalf("not JSON: %s", out) } return v.Behavior == "allow" } for _, raw := range []string{ `{"tool_name":"Edit","input":{"file_path":"/workspace/README.md","old_string":"teh","new_string":"the"}}`, `{"tool_name":"Write","input":{"file_path":"/workspace/panes/new.go","content":"package panes"}}`, `{"tool_name":"Read","input":{"file_path":"/workspace/README.md"}}`, `{"tool_name":"Grep","input":{"pattern":"swipe","path":"/workspace"}}`, `{"tool_name":"Bash","input":{"command":"curl example.com"}}`, } { if !allowed(raw) { t.Fatalf("refused %s", raw) } } for _, raw := range []string{ `{"tool_name":"Edit","input":{"file_path":"/etc/passwd","old_string":"a","new_string":"b"}}`, `{"tool_name":"Read","input":{"file_path":"/workspace/../home/runner/.credentials.json"}}`, `{"tool_name":"Write","input":{"file_path":"/tool/equipo.sock","content":"x"}}`, `{"tool_name":"Write","input":{"file_path":"/workspace/a","content":"x","dangerouslyDisableSandbox":true}}`, `{"tool_name":"Bash","input":{"command":"ls","dangerouslyDisableSandbox":true}}`, `{"tool_name":"mcp__equipo__submit_candidate","input":{}}`, `{"tool_name":"Read","input":{"file_path":"README.md"}}`, `{"tool_name":"Edit","input":{"file_path":"/workspace/a"},"extra":1}`, `not json`, } { if allowed(raw) { t.Fatalf("allowed %s", raw) } } } // TestStepPermissionReadsResearch: Engineering and Review may read the // kept Research images at /research (Read, Glob, Grep only); nothing // writes there, and nothing reaches past it. func TestStepPermissionReadsResearch(t *testing.T) { f := fixtureFor(t, "Engineering") allowed := func(check func(json.RawMessage, provider.Policy) json.RawMessage, raw string) bool { var v struct{ Behavior string } if json.Unmarshal(check(json.RawMessage(raw), f.launch.Policy), &v) != nil { t.Fatalf("not JSON for %s", raw) } return v.Behavior == "allow" } for _, check := range []func(json.RawMessage, provider.Policy) json.RawMessage{StepPermission, ReadPermission} { for _, raw := range []string{ `{"tool_name":"Read","input":{"file_path":"/research/img1-logo.png"}}`, `{"tool_name":"Glob","input":{"pattern":"*.png","path":"/research"}}`, `{"tool_name":"Grep","input":{"pattern":"x","path":"/research/"}}`, } { if !allowed(check, raw) { t.Fatalf("refused %s", raw) } } for _, raw := range []string{ `{"tool_name":"Write","input":{"file_path":"/research/img9.png","content":"x"}}`, `{"tool_name":"Edit","input":{"file_path":"/research/img1-logo.png","old_string":"a","new_string":"b"}}`, `{"tool_name":"Read","input":{"file_path":"/research/../home/runner/.credentials.json"}}`, `{"tool_name":"Read","input":{"file_path":"/research/../etc/passwd"}}`, `{"tool_name":"Read","input":{"file_path":"/researchers/a"}}`, `{"tool_name":"Read","input":{"file_path":"research/img1-logo.png"}}`, `{"tool_name":"Glob","input":{"pattern":"../home/*","path":"/research"}}`, } { if allowed(check, raw) { t.Fatalf("allowed %s", raw) } } } // Engineering's shell runs in the sandbox, which binds /research // read-only; a read-only step runs no shell through its callback. if allowed(ReadPermission, `{"tool_name":"Bash","input":{"command":"cat /research/img1-logo.png"}}`) { t.Fatal("read-only step allowed a shell read") } } // TestStepPermissionRunsSandboxedShell: production 2026-11-22, a token // connection (claude-2). Token launches set CLAUDE_CODE_SUBPROCESS_ENV_SCRUB, // and in that mode the pinned CLI turns sandbox auto-approval off, so its // ordinary shell commands reached this callback and every one was refused. // The policy forces every command into the CLI's sandbox, so the step // allows them exactly as the CLI's auto-approval would. No command's text // is special; a policy that reserves shell approval for a person (any // Bash ask rule) refuses every shell request in a step instead. func TestStepPermissionRunsSandboxedShell(t *testing.T) { f := fixtureFor(t, "Engineering") // The commands the CLI escalated in that step (its reason codes: // cd-compound-read, too-complex, no-rule-match, outside the working // directory). for _, command := range []string{ `cd internal/home; grep -ln "operator/confirm" *_test.go`, `cd /workspace/internal/home; ls *operator*`, `export PATH=/opt/go/bin:$PATH GOMODCACHE=/opt/go-mod GOTOOLCHAIN=local; go test ./internal/home/`, `GOTOOLCHAIN=local CGO_ENABLED=0 /opt/go/bin/go test -count=1 ./internal/home/ 2>&1 | tail -30`, `/opt/go/bin/go version`, `ls /opt/go/bin`, `which go gofmt; ls /opt`, `printf equipo-cert-deny`, `printf "equipo-cert-allow"`, `env printf equipo-cert-deny`, } { input, _ := json.Marshal(map[string]any{"command": command, "description": "d", "timeout": 600000}) raw, _ := json.Marshal(map[string]any{"tool_name": "Bash", "tool_use_id": "toolu_x", "input": json.RawMessage(input)}) var v struct { Behavior string UpdatedInput json.RawMessage } if json.Unmarshal(StepPermission(raw, f.launch.Policy), &v) != nil || v.Behavior != "allow" || !sameJSON(v.UpdatedInput, input) { t.Fatalf("sandboxed command refused or changed: %s -> %+v", command, v) } } for _, raw := range []string{ `{"tool_name":"Bash","input":{"command":"ls","dangerouslyDisableSandbox":false}}`, `{"tool_name":"Bash","input":{"command":"ls","sandbox":false}}`, `{"tool_name":"Bash","input":{"command":7}}`, `{"tool_name":"Bash","input":{}}`, } { if stepBehavior(t, StepPermission, raw, f.launch.Policy) == "allow" { t.Fatalf("allowed %s", raw) } } // Only a policy that keeps every command in the sandbox lets the step // approve shell commands itself. for name, mutate := range map[string]func(map[string]any){ "sandbox off": func(s map[string]any) { s["enabled"] = false }, "unsandboxed allowed": func(s map[string]any) { s["allowUnsandboxedCommands"] = true }, "may run unconfined": func(s map[string]any) { s["failIfUnavailable"] = false }, "excluded commands": func(s map[string]any) { s["excludedCommands"] = []string{"go"} }, "weaker nested": func(s map[string]any) { s["enableWeakerNestedSandbox"] = true }, "no sandbox key": nil, } { p := withSandboxSettings(t, f.launch.Policy, mutate) if stepBehavior(t, StepPermission, `{"tool_name":"Bash","input":{"command":"ls"}}`, p) == "allow" { t.Fatalf("%s: shell allowed", name) } } reserved := withSettings(t, f.launch.Policy, func(s map[string]any) { s["permissions"].(map[string]any)["ask"] = []string{"Bash(git push:*)"} }) if stepBehavior(t, StepPermission, `{"tool_name":"Bash","input":{"command":"ls"}}`, reserved) == "allow" { t.Fatal("a policy reserving shell approval for a person let a step approve") } // Review keeps its read-only callback: no shell through it. r := fixtureFor(t, "Review") if stepBehavior(t, ReadPermission, `{"tool_name":"Bash","input":{"command":"ls"}}`, r.launch.Policy) == "allow" { t.Fatal("read-only step allowed a shell command") } } // TestStepPermissionNamesTheRule: a refusal tells the model which rule // refused it and what to do instead, in fixed words that never repeat // the request. func TestStepPermissionNamesTheRule(t *testing.T) { f := fixtureFor(t, "Engineering") secret := "sk-ant-oat01-zzzz" for _, tc := range []struct{ raw, want string }{ {`{"tool_name":"Glob","input":{"pattern":"internal/home/*` + secret + `*"}}`, "absolute path"}, {`{"tool_name":"Read","input":{"file_path":"README-` + secret + `.md"}}`, "absolute path"}, {`{"tool_name":"Read","input":{"file_path":"~/` + secret + `"}}`, "absolute path"}, {`{"tool_name":"Read","input":{"file_path":"/etc/` + secret + `"}}`, "/workspace"}, {`{"tool_name":"Write","input":{"file_path":"/tool/equipo.sock","content":"` + secret + `"}}`, "protected"}, {`{"tool_name":"Write","input":{"file_path":"/research/a","content":"` + secret + `"}}`, "read"}, {`{"tool_name":"Bash","input":{"command":"ls ` + secret + `","dangerouslyDisableSandbox":true}}`, "sandbox"}, {`{"tool_name":"WebFetch","input":{"url":"https://` + secret + `"}}`, "not available"}, {`{"tool_name":"Edit","input":{"file_path":"/workspace/a","old_string":"` + secret + `","new_string":"b","extra":1}}`, "field"}, } { out := StepPermission(json.RawMessage(tc.raw), f.launch.Policy) var v struct{ Behavior, Message string } if json.Unmarshal(out, &v) != nil || v.Behavior != "deny" { t.Fatalf("not denied: %s -> %s", tc.raw, out) } if !strings.HasPrefix(v.Message, provider.ErrPolicy.Error()+": ") || !strings.Contains(v.Message, tc.want) || strings.Contains(v.Message, secret) { t.Fatalf("%s: message %q, want the rule naming %q and no request text", tc.raw, v.Message, tc.want) } } r := fixtureFor(t, "Review") var v struct{ Behavior, Message string } if json.Unmarshal(ReadPermission(json.RawMessage(`{"tool_name":"Bash","input":{"command":"ls"}}`), r.launch.Policy), &v) != nil || v.Behavior != "deny" || !strings.Contains(v.Message, "Read, Glob and Grep") { t.Fatalf("read-only refusal does not name its rule: %+v", v) } } // TestPermissionLinuxUnchanged: the Mac port (task 7 of slice F) leaves // every Linux launch exactly as certified. The digests are of the // settings, argv, tools and denied paths PolicyInputs renders for each // Linux launch shape, taken at 098407b0 before the port; the existing // answer tests above keep passing beside it. func TestPermissionLinuxUnchanged(t *testing.T) { for _, c := range linuxGoldenCases() { if got := linuxSettingsDigest(t, c.action, c.role); got != c.digest { t.Errorf("Linux launch %s/%s changed: %s", c.action, c.role, got) } } // A Linux policy reads as Linux: /workspace and /research, and a // refusal's words are the fixed ones. f := fixtureFor(t, "Engineering") if w, r := Roots(f.launch.Policy); LinuxWorkspaceRoot != "/workspace" || LinuxResearchRoot != "/research" || w != LinuxWorkspaceRoot || r != LinuxResearchRoot { t.Fatalf("Linux roots %q %q", w, r) } var v struct{ Behavior, Message string } if json.Unmarshal(StepPermission(json.RawMessage(`{"tool_name":"Read","input":{"file_path":"/etc/passwd"}}`), f.launch.Policy), &v) != nil || v.Message != provider.ErrPolicy.Error()+": "+refuseOutside { t.Fatalf("Linux refusal changed: %+v", v) } // SandboxNetworkAccess is refused on Linux as before: not a step tool. if json.Unmarshal(StepPermission(json.RawMessage(`{"tool_name":"SandboxNetworkAccess","input":{"host":"example.com"}}`), f.launch.Policy), &v) != nil || v.Behavior != "deny" || v.Message != provider.ErrPolicy.Error()+": "+refuseTool { t.Fatalf("Linux network answer changed: %+v", v) } } type linuxGolden struct{ action, role, digest string } func linuxGoldenCases() []linuxGolden { return []linuxGolden{ {"", "Engineering", "c6e60b449d74ee60e3c9aaf1eac5ca25ce11935352630317483243abebec73a9"}, {"", "Copy", "5a0a805f511b3fe0279fa14559de79b485710c9b7edfe7b4f2b7ccf5a857509c"}, {"", "Review", "0dadd06fc34ce8574b36610916c9afbdb2e9f89a33887c7338b8e7b0d6ac705f"}, {"", "Reviewer", "75816fb0ac63443d22e1af355dd024d2ae4f32c10806625d648d460c7a4b1b65"}, {"", "Answerer", "5fc13350c7f125299b9379f7fc56305e6d5c7ed4bdbfbae2d828261bb2346faa"}, {"", "Coordinator", "b07b942edf4adc989ecb0e94bb6ef42739f99cf1b0872f69ab676ad1bab62cb7"}, {"implement", "", "7bff2dd969a1a40de62495b1feb4b42c6140ee54f1fb2ecff53602a968963d48"}, {"copy", "", "9c331b861ab54acc34395eebdfe49f97fd1a44088f15d832018c05d3e56f3f16"}, {"design", "", "bb15be7302f9751339a4383d7c3769a4d444045759aa6fc32de9a93fc1508c90"}, {"review", "", "25b61566499af8c549dade811ff947a9b2df86f6e278833b226842450eae11d6"}, {"inspect", "", "d560cd170556bd85493ce037540d95222818c931d12ef9991f4064803cd42326"}, {"answer", "", "1ca67f173bd6b222c69e024ef1064a0a1ca69f7901d82e97fa343ab6c617ca51"}, {"scope", "", "b0f8f413cc6147912376d23fa298000ff2219d997dddb8cda9f1fd4c77dde6aa"}, {"research", "", "709577e8d5973f8914a27f4b86aca35d5c204ec43c6da68abad63934f9945e9e"}, {"reproduce", "", "abfc371fef557a74133b246295d9c1c46534934c2913f06576676c6367a125f7"}, {"coordinate", "", "f75f6b326f242d5f2c4ed09f3d937afa35acd4a7edc5deee52e67e6d0933f120"}, {"converse", "", "453f436806e4f24a18fb08f24f09d43afe33d8913ea055218854b176509408ec"}, {"assist", "", "f04e6fe8fb11e7aa8bfe5d926fc68624590d667f60c8b569a5316a8e460d4743"}, {provider.ResearchStepAction, "", "353b55fcff5dd3a4f6829a7aec71e1a94c2332d476066c3d61fe577e7c4ac8bb"}, {provider.GlanceAction, "", "4c2a746684372478a8f262c6755bcb33055ff05d18a7a7d0baea2b0b33250a89"}, } } // linuxSettingsDigest renders one Linux launch's inputs on a fixed binding // and returns the digest of what the certified policy is made from. func linuxSettingsDigest(t *testing.T, action, role string) string { t.Helper() b := provider.Binding{Provider: "claude", CredentialHome: "/private/account", Home: "/private/run", RuntimeRoot: "/private/runtime"} in := provider.PolicyInputs{Action: action, DeniedPaths: []string{"/private/state", "/alias/login"}} if action != "" { p, err := provider.Profile(action) if err != nil { t.Fatal(err) } role, in.Tools = p.Specialist, p.MCPTools() } got, err := PolicyInputs(b, in, role, "claude-haiku-5-5") if err != nil { t.Fatalf("%s/%s: %v", action, role, err) } raw, _ := json.Marshal([]any{got.Settings, got.MCP, got.ThreadPolicy, got.TurnPolicy, got.Argv, got.Tools, got.DeniedPaths, got.Env}) sum := sha256.Sum256(raw) return hex.EncodeToString(sum[:]) } func stepBehavior(t *testing.T, check func(json.RawMessage, provider.Policy) json.RawMessage, raw string, p provider.Policy) string { t.Helper() var v struct{ Behavior string } if out := check(json.RawMessage(raw), p); json.Unmarshal(out, &v) != nil { t.Fatalf("not JSON: %s", out) } return v.Behavior } // withSandboxSettings returns p with its manifest's sandbox settings // changed by mutate (nil removes the sandbox key). func withSandboxSettings(t *testing.T, p provider.Policy, mutate func(map[string]any)) provider.Policy { return withSettings(t, p, func(s map[string]any) { if mutate == nil { delete(s, "sandbox") } else { mutate(s["sandbox"].(map[string]any)) } }) } // withSettings returns p with its manifest's settings changed by mutate. func withSettings(t *testing.T, p provider.Policy, mutate func(map[string]any)) provider.Policy { t.Helper() var m map[string]json.RawMessage var settings map[string]any if json.Unmarshal(p.Manifest, &m) != nil || json.Unmarshal(m["Settings"], &settings) != nil { t.Fatal("manifest settings unreadable") } mutate(settings) m["Settings"], _ = json.Marshal(settings) p.Manifest, _ = json.Marshal(m) return p }