package claude import ( "bytes" "context" "crypto/rand" "encoding/json" "io" "os" "path/filepath" "slices" "strings" "amadan.net/oficina/equipo/internal/runner/provider" ) type permissionRequest struct { Tool string `json:"tool_name"` ToolUseID string `json:"tool_use_id,omitempty"` Input json.RawMessage `json:"input"` } type pendingPermission struct { raw json.RawMessage request permissionRequest turn string reply chan json.RawMessage } // Permission is called only by the bound MCP endpoint. Respond resolves this // exact call; it never writes a user message to Claude's stdin. func (l *Launcher) Permission(ctx context.Context, session provider.Session, raw json.RawMessage) (json.RawMessage, error) { var q permissionRequest d := json.NewDecoder(bytes.NewReader(raw)) d.DisallowUnknownFields() if !uniqueJSON(raw) || d.Decode(&q) != nil || d.Decode(new(any)) != io.EOF || q.Tool == "" || !uniqueJSON(q.Input) || len(raw) > MaxFrameBytes { return nil, errProtocol } var input map[string]json.RawMessage if json.Unmarshal(q.Input, &input) != nil || input == nil { return nil, errProtocol } l.mu.Lock() s, e := l.state(session) if e != nil { l.mu.Unlock() return nil, e } if !s.active || s.closed || s.err != nil || s.ctx.Err() != nil || !s.attached { l.mu.Unlock() return nil, errNotReady } if policy := s.launch.Policy; darwinDecided(q, policy) { // A Mac's file actions and network requests are the port's alone: // decided once, outside the lock, allow or deny, never a person's. l.mu.Unlock() return StepPermission(raw, policy), nil } if protectedNativePath(q, s.launch.Policy) { l.mu.Unlock() return permissionResult(q, provider.Answer{Behavior: "deny"}, s.launch.Policy) } // Workspace file actions are within the profile: Equipo answers them after // the protected-path check, so the person is only asked beyond the profile. if workspaceNativePath(q, s.launch.Policy) { l.mu.Unlock() return permissionResult(q, provider.Answer{Behavior: "allow"}, s.launch.Policy) } id := "permission:" + rand.Text() p := &pendingPermission{raw: bytes.Clone(raw), request: q, turn: s.turn.ID, reply: make(chan json.RawMessage, 1)} if s.permissions == nil { s.permissions = map[string]*pendingPermission{} } if len(s.permissions) >= 64 { l.mu.Unlock() return nil, errNotReady } s.permissions[id] = p ev := provider.Event{SessionID: session.ID, TurnID: s.turn.ID, RequestID: id, Kind: "request", Payload: bytes.Clone(raw)} select { case s.events <- ev: default: delete(s.permissions, id) l.mu.Unlock() return nil, errNotReady } l.mu.Unlock() defer func() { l.mu.Lock(); delete(s.permissions, id); l.mu.Unlock() }() select { case reply := <-p.reply: return reply, nil case <-ctx.Done(): return nil, ctx.Err() case <-s.ctx.Done(): return nil, errNotReady } } func permissionResult(q permissionRequest, a provider.Answer, policy provider.Policy) (json.RawMessage, error) { if a.Behavior == "deny" && len(a.Input) == 0 { return json.Marshal(map[string]string{"behavior": "deny", "message": provider.ErrPolicy.Error()}) } if a.Behavior != "allow" || protectedNativePath(q, policy) { return nil, provider.ErrPolicy } var input map[string]json.RawMessage if json.Unmarshal(q.Input, &input) != nil || input == nil { return nil, provider.ErrPolicy } if q.Tool == "AskUserQuestion" || q.Tool == "ask_person" { var keys []string if q.Tool == "ask_person" { var text string if json.Unmarshal(input["question"], &text) != nil || strings.TrimSpace(text) == "" { return nil, provider.ErrPolicy } keys = []string{"answer"} } else { var questions []struct{ Question string } if json.Unmarshal(input["questions"], &questions) != nil { return nil, provider.ErrPolicy } for _, v := range questions { keys = append(keys, v.Question) } } if !uniqueJSON(a.Input) { return nil, provider.ErrPolicy } answers, e := provider.QuestionAnswers(a.Input, keys) if e != nil { return nil, e } input["answers"], _ = json.Marshal(answers) } else { // Only the original native action can be allowed, under the unchanged policy. if len(a.Input) != 0 { return nil, provider.ErrPolicy } if e := nativeInput(q, input, policy); e != nil { return nil, e } } return json.Marshal(map[string]any{"behavior": "allow", "updatedInput": input}) } // nativeInput checks a native action's own fields against the policy: // a pinned tool the policy lists, only that tool's fields, nothing that // asks to leave the sandbox, and absolute paths outside the denied ones. // It reads no file; where the action lands is the path rules' question. func nativeInput(q permissionRequest, input map[string]json.RawMessage, policy provider.Policy) error { if !slices.Contains([]string{"Read", "Write", "Edit", "Glob", "Grep", "Bash"}, q.Tool) { return provider.ErrPolicy } var m manifest if json.Unmarshal(policy.Manifest, &m) != nil || !slices.Contains(m.Tools, q.Tool) { return provider.ErrPolicy } fields := map[string][]string{ "Read": {"file_path", "offset", "limit", "pages"}, "Write": {"file_path", "content"}, "Edit": {"file_path", "old_string", "new_string", "replace_all"}, "Glob": {"pattern", "path"}, "Grep": {"pattern", "path", "glob", "output_mode", "-A", "-B", "-C", "context", "-n", "-i", "type", "head_limit", "offset", "multiline"}, "Bash": {"command", "description", "timeout", "run_in_background"}, } for key := range input { if !slices.Contains(fields[q.Tool], key) { return provider.ErrPolicy } } for key := range input { switch key { case "dangerouslyDisableSandbox", "permissions", "sandbox", "permissionMode", "updatedPermissions": return provider.ErrPolicy } } for _, key := range []string{"file_path", "path"} { var path string if v, ok := input[key]; ok { if json.Unmarshal(v, &path) != nil { return provider.ErrPolicy } if !filepath.IsAbs(path) { return provider.ErrPolicy } path = filepath.Clean(path) for _, deny := range m.DeniedPaths { if path == deny || strings.HasPrefix(path, deny+"/") { return provider.ErrPolicy } } } } return nil } // A step's permission callback refuses with a fixed reason: the rule // that refused and what to do instead. It never repeats the request. const ( refusePath = "file tools need an absolute path under /workspace; for Glob and Grep, pass path, such as /workspace" refuseOutside = "this step can use files only under /workspace (and read /research)" refuseProtected = "that path is protected: credentials, runtime files and links are never available" refuseResearch = "/research is read-only: use Read, Glob and Grep there" // refuseReadOnlyRoot follows a read-only path (/render). refuseReadOnlyRoot = " is read-only: use Read, Glob and Grep there" refuseFields = "the request has a field this step does not accept" refuseSandbox = "commands run only inside the sandbox; dangerouslyDisableSandbox is not available" refusePerson = "this step's policy keeps shell commands for a person's approval, and nobody is asked during a step" refuseTool = "this tool is not available to this step" refuseReadOnly = "this step only reads: use Read, Glob and Grep under /workspace" refuseShell = "this step's policy does not keep commands in the sandbox, so it runs none" ) func refusal(rule string) json.RawMessage { out, _ := json.Marshal(map[string]string{"behavior": "deny", "message": provider.ErrPolicy.Error() + ": " + rule}) return out } // StepPermission answers an Engineering step's permission callback when // nobody is asked. A workspace file action passes the same protected-path // and field checks as an approved one and is allowed. A shell command is // allowed when the policy confines every command to the CLI's sandbox // (sandboxedShell): the CLI asks for one only where its own automatic // approval is off or declines, as it always is for a token connection // (CLAUDE_CODE_SUBPROCESS_ENV_SCRUB). Everything else is denied with the // rule that refused it. The result is the callback's JSON text. func StepPermission(raw json.RawMessage, policy provider.Policy) json.RawMessage { return stepPermission(raw, policy, nil) } // DesignPermission answers the Design step's permission callback: // Engineering's (StepPermission), and Read, Glob and Grep of the // design-v1 profile's read-only paths (/render, its captures); a write // there is refused. Handed any policy but the Design step's, it is // Engineering's callback and reads nothing more. func DesignPermission(raw json.RawMessage, policy provider.Policy) json.RawMessage { var reads []string if policy.RenderReader() { reads = provider.DesignReadOnly() } return stepPermission(raw, policy, reads) } // stepPermission is StepPermission with reads, the paths beyond // Engineering's that the step's native file tools may read only. func stepPermission(raw json.RawMessage, policy provider.Policy, reads []string) json.RawMessage { var q permissionRequest d := json.NewDecoder(bytes.NewReader(raw)) d.DisallowUnknownFields() if !uniqueJSON(raw) || d.Decode(&q) != nil || q.Tool == "" || !uniqueJSON(q.Input) || len(raw) > MaxFrameBytes { return refusal(refuseFields) } m, _ := policyManifest(policy) switch { case q.Tool == "SandboxNetworkAccess": // A sandboxed command asking for a host: a step has no network, // whatever the platform (on a Mac an empty allowedDomains asks). return refusal(refuseTool) case q.Tool == "Bash": if rule := sandboxedShell(q, policy); rule != "" { return refusal(rule) } default: if rule := stepPathRule(q, policy, reads); rule != "" { return refusal(m.say(rule)) } if m.darwin() { // Decided once by stepPathRule; only the fields remain. var input map[string]json.RawMessage if json.Unmarshal(q.Input, &input) != nil || input == nil || nativeInput(q, input, policy) != nil { return refusal(refuseFields) } out, _ := json.Marshal(map[string]any{"behavior": "allow", "updatedInput": input}) return out } } out, err := permissionResult(q, provider.Answer{Behavior: "allow"}, policy) if err != nil { return refusal(refuseFields) } return out } // stepPathRule names the rule refusing a native file action in a step, or // "" when the action is inside the step's profile: reads are the paths // beyond Engineering's it may read only (none for Engineering). func stepPathRule(q permissionRequest, policy provider.Policy, reads []string) string { if !slices.Contains([]string{"Read", "Write", "Edit", "Glob", "Grep"}, q.Tool) { return refuseTool } if m, ok := policyManifest(policy); !ok || !m.portable() { return refuseProtected } else if m.darwin() { switch darwinPlace(q, m) { case placeBadPath: return refusePath case placeWorkspace: return "" case placeResearch: if slices.Contains([]string{"Read", "Glob", "Grep"}, q.Tool) { return "" } return refuseResearch case placeOutside: return refuseOutside } return refuseProtected } var input map[string]json.RawMessage if json.Unmarshal(q.Input, &input) != nil { return refuseFields } path := "" for _, key := range []string{"file_path", "path"} { if raw, ok := input[key]; ok { if json.Unmarshal(raw, &path) != nil { return refuseFields } break } } switch { case path == "" || strings.HasPrefix(path, "~") || !filepath.IsAbs(path): return refusePath case protectedNativePath(q, policy): return refuseProtected case workspaceNativePath(q, policy) || researchNativePath(q, policy): return "" case filepath.Clean(path) == "/research" || strings.HasPrefix(filepath.Clean(path), "/research/"): return refuseResearch } for _, root := range reads { if readNativePath(q, policy, root) { return "" } if clean := filepath.Clean(path); clean == root || strings.HasPrefix(clean, root+"/") { return root + refuseReadOnlyRoot } } return refuseOutside } // sandboxedShell names the rule refusing a shell command in a step, or "" // when the step may run it: the policy keeps every command in the CLI's // sandbox (enabled, no unconfined fallback or exemption, no weaker nesting), // the request cannot ask to leave it, and the policy reserves no shell // approval for a person. The command's text is never consulted: a shell // rule cannot stop a sandboxed command producing any text, so a policy // with a Bash ask rule refuses every shell request in a step. func sandboxedShell(q permissionRequest, policy provider.Policy) string { var input map[string]json.RawMessage var command string if json.Unmarshal(q.Input, &input) != nil { return refuseFields } for _, key := range []string{"dangerouslyDisableSandbox", "sandbox"} { if _, ok := input[key]; ok { return refuseSandbox } } if json.Unmarshal(input["command"], &command) != nil || strings.TrimSpace(command) == "" { return refuseFields } var m manifest var settings struct { Sandbox *struct { Enabled, FailIfUnavailable, AllowUnsandboxedCommands *bool ExcludedCommands []string EnableWeakerNestedSandbox *bool } Permissions struct{ Ask []string } } if json.Unmarshal(policy.Manifest, &m) != nil || json.Unmarshal(m.Settings, &settings) != nil { return refuseShell } s := settings.Sandbox if s == nil || s.Enabled == nil || !*s.Enabled || s.FailIfUnavailable == nil || !*s.FailIfUnavailable || s.AllowUnsandboxedCommands == nil || *s.AllowUnsandboxedCommands || len(s.ExcludedCommands) != 0 || s.EnableWeakerNestedSandbox != nil && *s.EnableWeakerNestedSandbox { return refuseShell } for _, rule := range settings.Permissions.Ask { if rule == "Bash" || strings.HasPrefix(rule, "Bash(") { return refusePerson } } return "" } // ReadPermission is StepPermission for a read-only step: only Read, Glob // and Grep inside the workspace; every write, shell or other tool is // denied. func ReadPermission(raw json.RawMessage, policy provider.Policy) json.RawMessage { var q struct { Tool string `json:"tool_name"` } if json.Unmarshal(raw, &q) != nil || !slices.Contains([]string{"Read", "Glob", "Grep"}, q.Tool) { m, _ := policyManifest(policy) return refusal(m.say(refuseReadOnly)) } return StepPermission(raw, policy) } func (l *Launcher) respond(ctx context.Context, session provider.Session, a provider.Answer) error { l.mu.Lock() defer l.mu.Unlock() s, e := l.state(session) if e != nil { return e } p := s.permissions[a.RequestID] if p == nil || !s.active || s.closed || s.err != nil || ctx.Err() != nil || s.ctx.Err() != nil || a.TurnID != s.turn.ID || p.turn != a.TurnID { return errNotReady } if e = s.lease.ValidatePolicy(ctx); e != nil { return e } result, e := permissionResult(p.request, a, s.launch.Policy) if e != nil { return e } if a.Behavior == "allow" && p.request.Tool != "AskUserQuestion" && p.request.Tool != "ask_person" { if a.Authorize == nil { return provider.ErrPolicy } ev := provider.Event{Kind: "request", SessionID: session.ID, TurnID: p.turn, RequestID: a.RequestID, Payload: p.raw} if e = a.Authorize(ctx, ev); e != nil { return e } } delete(s.permissions, a.RequestID) p.reply <- result return nil } // Protected file requests never reach the human approval path. Refuse workspace // aliases here as well: the provider resolves its paths inside the namespace. func protectedNativePath(q permissionRequest, policy provider.Policy) bool { if !slices.Contains([]string{"Read", "Write", "Edit", "Glob", "Grep"}, q.Tool) { return false } var m manifest var input map[string]json.RawMessage if json.Unmarshal(policy.Manifest, &m) != nil || json.Unmarshal(q.Input, &input) != nil || !m.portable() { return true } if m.darwin() { // Nobody is asked on a Mac: only the port's own decision // (StepPermission) allows a file action, so none is a person's // to approve and an approval allows none. return true } path := "" for _, key := range []string{"file_path", "path"} { if raw, ok := input[key]; ok { if json.Unmarshal(raw, &path) != nil || path == "" { return true } break } } if strings.HasPrefix(path, "~") { return true } if !filepath.IsAbs(path) { return true } if q.Tool == "Glob" { var pattern string if raw, ok := input["pattern"]; ok { if json.Unmarshal(raw, &pattern) != nil || filepath.IsAbs(pattern) || slices.Contains(strings.Split(pattern, "/"), "..") { return true } // Only the literal base is known before Glob expands the pattern. for _, part := range strings.Split(pattern, "/") { if strings.ContainsAny(part, "*?[{\\") { break } path = filepath.Join(path, part) } } } path = filepath.Clean(path) if path == "/home" || strings.HasPrefix(path, "/home/") { return true } for _, deny := range m.DeniedPaths { if path == deny || strings.HasPrefix(path, deny+"/") { return true } } if path != "/workspace" && !strings.HasPrefix(path, "/workspace/") { return false } host := m.Workspace if !filepath.IsAbs(host) { return true } rel := strings.TrimPrefix(strings.TrimPrefix(path, "/workspace"), "/") if rel == "" { return false } for _, part := range strings.Split(rel, "/") { host = filepath.Join(host, part) info, err := os.Lstat(host) if os.IsNotExist(err) { return false } if err != nil || info.Mode()&os.ModeSymlink != 0 { return true } } return false } // darwinDecided reports a request on a Mac policy that only the port // decides: a native file action or a sandboxed command's network request. func darwinDecided(q permissionRequest, policy provider.Policy) bool { m, ok := policyManifest(policy) return ok && m.darwin() && (q.Tool == "SandboxNetworkAccess" || slices.Contains([]string{"Read", "Write", "Edit", "Glob", "Grep"}, q.Tool)) } // researchNativePath reports a read (Read, Glob or Grep) of /research, // where containment binds a task's kept Research images read-only for // Engineering and Review (a flat directory of regular files; nothing is // there for any other launch). Writes there are never allowed. func researchNativePath(q permissionRequest, policy provider.Policy) bool { return readNativePath(q, policy, "/research") } // readNativePath reports a Read, Glob or Grep whose path is root or // under it, on a Linux policy only (a Mac's file actions are decided by // darwinPlace). Callers must first refuse protectedNativePath. func readNativePath(q permissionRequest, policy provider.Policy, root string) bool { if !slices.Contains([]string{"Read", "Glob", "Grep"}, q.Tool) { return false } if m, ok := policyManifest(policy); !ok || !m.portable() { return false } else if m.darwin() { return false } var input map[string]json.RawMessage if json.Unmarshal(q.Input, &input) != nil { return false } path := "" for _, key := range []string{"file_path", "path"} { if raw, ok := input[key]; ok { if json.Unmarshal(raw, &path) != nil { return false } break } } if !filepath.IsAbs(path) { return false } path = filepath.Clean(path) return path == root || strings.HasPrefix(path, root+"/") } // workspaceNativePath reports a native file action whose path is inside // /workspace. Callers must first refuse protectedNativePath, which also // rejects existing workspace symlinks. A symlink swapped after Equipo checks // remains a race: Claude's own symlink-aware /home deny rules must catch it. // This is an accepted residual risk, not an atomic filesystem guarantee. func workspaceNativePath(q permissionRequest, policy provider.Policy) bool { if !slices.Contains([]string{"Read", "Write", "Edit", "Glob", "Grep"}, q.Tool) { return false } if m, ok := policyManifest(policy); !ok || !m.portable() { return false } else if m.darwin() { return false } var input map[string]json.RawMessage if json.Unmarshal(q.Input, &input) != nil { return false } path := "" for _, key := range []string{"file_path", "path"} { if raw, ok := input[key]; ok { if json.Unmarshal(raw, &path) != nil || path == "" || strings.HasPrefix(path, "~") { return false } break } } if !filepath.IsAbs(path) { return false } path = filepath.Clean(path) return path == "/workspace" || strings.HasPrefix(path, "/workspace/") }