oficina / equipo Public

Clone
git clone https://amadan.net/oficina/equipo

Plain git — no account needed to clone.

Download

Download this file

1package claude
2
3import (
4 "bytes"
5 "context"
6 "crypto/rand"
7 "encoding/json"
8 "io"
9 "os"
10 "path/filepath"
11 "slices"
12 "strings"
13
14 "amadan.net/oficina/equipo/internal/runner/provider"
15)
16
17type permissionRequest struct {
18 Tool string `json:"tool_name"`
19 ToolUseID string `json:"tool_use_id,omitempty"`
20 Input json.RawMessage `json:"input"`
21}
22type pendingPermission struct {
23 raw json.RawMessage
24 request permissionRequest
25 turn string
26 reply chan json.RawMessage
27}
28
29// Permission is called only by the bound MCP endpoint. Respond resolves this
30// exact call; it never writes a user message to Claude's stdin.
31func (l *Launcher) Permission(ctx context.Context, session provider.Session, raw json.RawMessage) (json.RawMessage, error) {
32 var q permissionRequest
33 d := json.NewDecoder(bytes.NewReader(raw))
34 d.DisallowUnknownFields()
35 if !uniqueJSON(raw) || d.Decode(&q) != nil || d.Decode(new(any)) != io.EOF || q.Tool == "" || !uniqueJSON(q.Input) || len(raw) > MaxFrameBytes {
36 return nil, errProtocol
37 }
38 var input map[string]json.RawMessage
39 if json.Unmarshal(q.Input, &input) != nil || input == nil {
40 return nil, errProtocol
41 }
42 l.mu.Lock()
43 s, e := l.state(session)
44 if e != nil {
45 l.mu.Unlock()
46 return nil, e
47 }
48 if !s.active || s.closed || s.err != nil || s.ctx.Err() != nil || !s.attached {
49 l.mu.Unlock()
50 return nil, errNotReady
51 }
52 if policy := s.launch.Policy; darwinDecided(q, policy) {
53 // A Mac's file actions and network requests are the port's alone:
54 // decided once, outside the lock, allow or deny, never a person's.
55 l.mu.Unlock()
56 return StepPermission(raw, policy), nil
57 }
58 if protectedNativePath(q, s.launch.Policy) {
59 l.mu.Unlock()
60 return permissionResult(q, provider.Answer{Behavior: "deny"}, s.launch.Policy)
61 }
62 // Workspace file actions are within the profile: Equipo answers them after
63 // the protected-path check, so the person is only asked beyond the profile.
64 if workspaceNativePath(q, s.launch.Policy) {
65 l.mu.Unlock()
66 return permissionResult(q, provider.Answer{Behavior: "allow"}, s.launch.Policy)
67 }
68 id := "permission:" + rand.Text()
69 p := &pendingPermission{raw: bytes.Clone(raw), request: q, turn: s.turn.ID, reply: make(chan json.RawMessage, 1)}
70 if s.permissions == nil {
71 s.permissions = map[string]*pendingPermission{}
72 }
73 if len(s.permissions) >= 64 {
74 l.mu.Unlock()
75 return nil, errNotReady
76 }
77 s.permissions[id] = p
78 ev := provider.Event{SessionID: session.ID, TurnID: s.turn.ID, RequestID: id, Kind: "request", Payload: bytes.Clone(raw)}
79 select {
80 case s.events <- ev:
81 default:
82 delete(s.permissions, id)
83 l.mu.Unlock()
84 return nil, errNotReady
85 }
86 l.mu.Unlock()
87 defer func() { l.mu.Lock(); delete(s.permissions, id); l.mu.Unlock() }()
88 select {
89 case reply := <-p.reply:
90 return reply, nil
91 case <-ctx.Done():
92 return nil, ctx.Err()
93 case <-s.ctx.Done():
94 return nil, errNotReady
95 }
96}
97func permissionResult(q permissionRequest, a provider.Answer, policy provider.Policy) (json.RawMessage, error) {
98 if a.Behavior == "deny" && len(a.Input) == 0 {
99 return json.Marshal(map[string]string{"behavior": "deny", "message": provider.ErrPolicy.Error()})
100 }
101 if a.Behavior != "allow" || protectedNativePath(q, policy) {
102 return nil, provider.ErrPolicy
103 }
104 var input map[string]json.RawMessage
105 if json.Unmarshal(q.Input, &input) != nil || input == nil {
106 return nil, provider.ErrPolicy
107 }
108 if q.Tool == "AskUserQuestion" || q.Tool == "ask_person" {
109 var keys []string
110 if q.Tool == "ask_person" {
111 var text string
112 if json.Unmarshal(input["question"], &text) != nil || strings.TrimSpace(text) == "" {
113 return nil, provider.ErrPolicy
114 }
115 keys = []string{"answer"}
116 } else {
117 var questions []struct{ Question string }
118 if json.Unmarshal(input["questions"], &questions) != nil {
119 return nil, provider.ErrPolicy
120 }
121 for _, v := range questions {
122 keys = append(keys, v.Question)
123 }
124 }
125 if !uniqueJSON(a.Input) {
126 return nil, provider.ErrPolicy
127 }
128 answers, e := provider.QuestionAnswers(a.Input, keys)
129 if e != nil {
130 return nil, e
131 }
132 input["answers"], _ = json.Marshal(answers)
133 } else {
134 // Only the original native action can be allowed, under the unchanged policy.
135 if len(a.Input) != 0 {
136 return nil, provider.ErrPolicy
137 }
138 if e := nativeInput(q, input, policy); e != nil {
139 return nil, e
140 }
141 }
142 return json.Marshal(map[string]any{"behavior": "allow", "updatedInput": input})
143}
144
145// nativeInput checks a native action's own fields against the policy:
146// a pinned tool the policy lists, only that tool's fields, nothing that
147// asks to leave the sandbox, and absolute paths outside the denied ones.
148// It reads no file; where the action lands is the path rules' question.
149func nativeInput(q permissionRequest, input map[string]json.RawMessage, policy provider.Policy) error {
150 if !slices.Contains([]string{"Read", "Write", "Edit", "Glob", "Grep", "Bash"}, q.Tool) {
151 return provider.ErrPolicy
152 }
153 var m manifest
154 if json.Unmarshal(policy.Manifest, &m) != nil || !slices.Contains(m.Tools, q.Tool) {
155 return provider.ErrPolicy
156 }
157 fields := map[string][]string{
158 "Read": {"file_path", "offset", "limit", "pages"},
159 "Write": {"file_path", "content"},
160 "Edit": {"file_path", "old_string", "new_string", "replace_all"},
161 "Glob": {"pattern", "path"},
162 "Grep": {"pattern", "path", "glob", "output_mode", "-A", "-B", "-C", "context", "-n", "-i", "type", "head_limit", "offset", "multiline"},
163 "Bash": {"command", "description", "timeout", "run_in_background"},
164 }
165 for key := range input {
166 if !slices.Contains(fields[q.Tool], key) {
167 return provider.ErrPolicy
168 }
169 }
170 for key := range input {
171 switch key {
172 case "dangerouslyDisableSandbox", "permissions", "sandbox", "permissionMode", "updatedPermissions":
173 return provider.ErrPolicy
174 }
175 }
176 for _, key := range []string{"file_path", "path"} {
177 var path string
178 if v, ok := input[key]; ok {
179 if json.Unmarshal(v, &path) != nil {
180 return provider.ErrPolicy
181 }
182 if !filepath.IsAbs(path) {
183 return provider.ErrPolicy
184 }
185 path = filepath.Clean(path)
186 for _, deny := range m.DeniedPaths {
187 if path == deny || strings.HasPrefix(path, deny+"/") {
188 return provider.ErrPolicy
189 }
190 }
191 }
192 }
193 return nil
194}
195
196// A step's permission callback refuses with a fixed reason: the rule
197// that refused and what to do instead. It never repeats the request.
198const (
199 refusePath = "file tools need an absolute path under /workspace; for Glob and Grep, pass path, such as /workspace"
200 refuseOutside = "this step can use files only under /workspace (and read /research)"
201 refuseProtected = "that path is protected: credentials, runtime files and links are never available"
202 refuseResearch = "/research is read-only: use Read, Glob and Grep there"
203 // refuseReadOnlyRoot follows a read-only path (/render).
204 refuseReadOnlyRoot = " is read-only: use Read, Glob and Grep there"
205 refuseFields = "the request has a field this step does not accept"
206 refuseSandbox = "commands run only inside the sandbox; dangerouslyDisableSandbox is not available"
207 refusePerson = "this step's policy keeps shell commands for a person's approval, and nobody is asked during a step"
208 refuseTool = "this tool is not available to this step"
209 refuseReadOnly = "this step only reads: use Read, Glob and Grep under /workspace"
210 refuseShell = "this step's policy does not keep commands in the sandbox, so it runs none"
211)
212
213func refusal(rule string) json.RawMessage {
214 out, _ := json.Marshal(map[string]string{"behavior": "deny", "message": provider.ErrPolicy.Error() + ": " + rule})
215 return out
216}
217
218// StepPermission answers an Engineering step's permission callback when
219// nobody is asked. A workspace file action passes the same protected-path
220// and field checks as an approved one and is allowed. A shell command is
221// allowed when the policy confines every command to the CLI's sandbox
222// (sandboxedShell): the CLI asks for one only where its own automatic
223// approval is off or declines, as it always is for a token connection
224// (CLAUDE_CODE_SUBPROCESS_ENV_SCRUB). Everything else is denied with the
225// rule that refused it. The result is the callback's JSON text.
226func StepPermission(raw json.RawMessage, policy provider.Policy) json.RawMessage {
227 return stepPermission(raw, policy, nil)
228}
229
230// DesignPermission answers the Design step's permission callback:
231// Engineering's (StepPermission), and Read, Glob and Grep of the
232// design-v1 profile's read-only paths (/render, its captures); a write
233// there is refused. Handed any policy but the Design step's, it is
234// Engineering's callback and reads nothing more.
235func DesignPermission(raw json.RawMessage, policy provider.Policy) json.RawMessage {
236 var reads []string
237 if policy.RenderReader() {
238 reads = provider.DesignReadOnly()
239 }
240 return stepPermission(raw, policy, reads)
241}
242
243// stepPermission is StepPermission with reads, the paths beyond
244// Engineering's that the step's native file tools may read only.
245func stepPermission(raw json.RawMessage, policy provider.Policy, reads []string) json.RawMessage {
246 var q permissionRequest
247 d := json.NewDecoder(bytes.NewReader(raw))
248 d.DisallowUnknownFields()
249 if !uniqueJSON(raw) || d.Decode(&q) != nil || q.Tool == "" || !uniqueJSON(q.Input) || len(raw) > MaxFrameBytes {
250 return refusal(refuseFields)
251 }
252 m, _ := policyManifest(policy)
253 switch {
254 case q.Tool == "SandboxNetworkAccess":
255 // A sandboxed command asking for a host: a step has no network,
256 // whatever the platform (on a Mac an empty allowedDomains asks).
257 return refusal(refuseTool)
258 case q.Tool == "Bash":
259 if rule := sandboxedShell(q, policy); rule != "" {
260 return refusal(rule)
261 }
262 default:
263 if rule := stepPathRule(q, policy, reads); rule != "" {
264 return refusal(m.say(rule))
265 }
266 if m.darwin() {
267 // Decided once by stepPathRule; only the fields remain.
268 var input map[string]json.RawMessage
269 if json.Unmarshal(q.Input, &input) != nil || input == nil || nativeInput(q, input, policy) != nil {
270 return refusal(refuseFields)
271 }
272 out, _ := json.Marshal(map[string]any{"behavior": "allow", "updatedInput": input})
273 return out
274 }
275 }
276 out, err := permissionResult(q, provider.Answer{Behavior: "allow"}, policy)
277 if err != nil {
278 return refusal(refuseFields)
279 }
280 return out
281}
282
283// stepPathRule names the rule refusing a native file action in a step, or
284// "" when the action is inside the step's profile: reads are the paths
285// beyond Engineering's it may read only (none for Engineering).
286func stepPathRule(q permissionRequest, policy provider.Policy, reads []string) string {
287 if !slices.Contains([]string{"Read", "Write", "Edit", "Glob", "Grep"}, q.Tool) {
288 return refuseTool
289 }
290 if m, ok := policyManifest(policy); !ok || !m.portable() {
291 return refuseProtected
292 } else if m.darwin() {
293 switch darwinPlace(q, m) {
294 case placeBadPath:
295 return refusePath
296 case placeWorkspace:
297 return ""
298 case placeResearch:
299 if slices.Contains([]string{"Read", "Glob", "Grep"}, q.Tool) {
300 return ""
301 }
302 return refuseResearch
303 case placeOutside:
304 return refuseOutside
305 }
306 return refuseProtected
307 }
308 var input map[string]json.RawMessage
309 if json.Unmarshal(q.Input, &input) != nil {
310 return refuseFields
311 }
312 path := ""
313 for _, key := range []string{"file_path", "path"} {
314 if raw, ok := input[key]; ok {
315 if json.Unmarshal(raw, &path) != nil {
316 return refuseFields
317 }
318 break
319 }
320 }
321 switch {
322 case path == "" || strings.HasPrefix(path, "~") || !filepath.IsAbs(path):
323 return refusePath
324 case protectedNativePath(q, policy):
325 return refuseProtected
326 case workspaceNativePath(q, policy) || researchNativePath(q, policy):
327 return ""
328 case filepath.Clean(path) == "/research" || strings.HasPrefix(filepath.Clean(path), "/research/"):
329 return refuseResearch
330 }
331 for _, root := range reads {
332 if readNativePath(q, policy, root) {
333 return ""
334 }
335 if clean := filepath.Clean(path); clean == root || strings.HasPrefix(clean, root+"/") {
336 return root + refuseReadOnlyRoot
337 }
338 }
339 return refuseOutside
340}
341
342// sandboxedShell names the rule refusing a shell command in a step, or ""
343// when the step may run it: the policy keeps every command in the CLI's
344// sandbox (enabled, no unconfined fallback or exemption, no weaker nesting),
345// the request cannot ask to leave it, and the policy reserves no shell
346// approval for a person. The command's text is never consulted: a shell
347// rule cannot stop a sandboxed command producing any text, so a policy
348// with a Bash ask rule refuses every shell request in a step.
349func sandboxedShell(q permissionRequest, policy provider.Policy) string {
350 var input map[string]json.RawMessage
351 var command string
352 if json.Unmarshal(q.Input, &input) != nil {
353 return refuseFields
354 }
355 for _, key := range []string{"dangerouslyDisableSandbox", "sandbox"} {
356 if _, ok := input[key]; ok {
357 return refuseSandbox
358 }
359 }
360 if json.Unmarshal(input["command"], &command) != nil || strings.TrimSpace(command) == "" {
361 return refuseFields
362 }
363 var m manifest
364 var settings struct {
365 Sandbox *struct {
366 Enabled, FailIfUnavailable, AllowUnsandboxedCommands *bool
367 ExcludedCommands []string
368 EnableWeakerNestedSandbox *bool
369 }
370 Permissions struct{ Ask []string }
371 }
372 if json.Unmarshal(policy.Manifest, &m) != nil || json.Unmarshal(m.Settings, &settings) != nil {
373 return refuseShell
374 }
375 s := settings.Sandbox
376 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 {
377 return refuseShell
378 }
379 for _, rule := range settings.Permissions.Ask {
380 if rule == "Bash" || strings.HasPrefix(rule, "Bash(") {
381 return refusePerson
382 }
383 }
384 return ""
385}
386
387// ReadPermission is StepPermission for a read-only step: only Read, Glob
388// and Grep inside the workspace; every write, shell or other tool is
389// denied.
390func ReadPermission(raw json.RawMessage, policy provider.Policy) json.RawMessage {
391 var q struct {
392 Tool string `json:"tool_name"`
393 }
394 if json.Unmarshal(raw, &q) != nil || !slices.Contains([]string{"Read", "Glob", "Grep"}, q.Tool) {
395 m, _ := policyManifest(policy)
396 return refusal(m.say(refuseReadOnly))
397 }
398 return StepPermission(raw, policy)
399}
400
401func (l *Launcher) respond(ctx context.Context, session provider.Session, a provider.Answer) error {
402 l.mu.Lock()
403 defer l.mu.Unlock()
404 s, e := l.state(session)
405 if e != nil {
406 return e
407 }
408 p := s.permissions[a.RequestID]
409 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 {
410 return errNotReady
411 }
412 if e = s.lease.ValidatePolicy(ctx); e != nil {
413 return e
414 }
415 result, e := permissionResult(p.request, a, s.launch.Policy)
416 if e != nil {
417 return e
418 }
419 if a.Behavior == "allow" && p.request.Tool != "AskUserQuestion" && p.request.Tool != "ask_person" {
420 if a.Authorize == nil {
421 return provider.ErrPolicy
422 }
423 ev := provider.Event{Kind: "request", SessionID: session.ID, TurnID: p.turn, RequestID: a.RequestID, Payload: p.raw}
424 if e = a.Authorize(ctx, ev); e != nil {
425 return e
426 }
427 }
428 delete(s.permissions, a.RequestID)
429 p.reply <- result
430 return nil
431}
432
433// Protected file requests never reach the human approval path. Refuse workspace
434// aliases here as well: the provider resolves its paths inside the namespace.
435func protectedNativePath(q permissionRequest, policy provider.Policy) bool {
436 if !slices.Contains([]string{"Read", "Write", "Edit", "Glob", "Grep"}, q.Tool) {
437 return false
438 }
439 var m manifest
440 var input map[string]json.RawMessage
441 if json.Unmarshal(policy.Manifest, &m) != nil || json.Unmarshal(q.Input, &input) != nil || !m.portable() {
442 return true
443 }
444 if m.darwin() {
445 // Nobody is asked on a Mac: only the port's own decision
446 // (StepPermission) allows a file action, so none is a person's
447 // to approve and an approval allows none.
448 return true
449 }
450 path := ""
451 for _, key := range []string{"file_path", "path"} {
452 if raw, ok := input[key]; ok {
453 if json.Unmarshal(raw, &path) != nil || path == "" {
454 return true
455 }
456 break
457 }
458 }
459 if strings.HasPrefix(path, "~") {
460 return true
461 }
462 if !filepath.IsAbs(path) {
463 return true
464 }
465 if q.Tool == "Glob" {
466 var pattern string
467 if raw, ok := input["pattern"]; ok {
468 if json.Unmarshal(raw, &pattern) != nil || filepath.IsAbs(pattern) || slices.Contains(strings.Split(pattern, "/"), "..") {
469 return true
470 }
471 // Only the literal base is known before Glob expands the pattern.
472 for _, part := range strings.Split(pattern, "/") {
473 if strings.ContainsAny(part, "*?[{\\") {
474 break
475 }
476 path = filepath.Join(path, part)
477 }
478 }
479 }
480 path = filepath.Clean(path)
481 if path == "/home" || strings.HasPrefix(path, "/home/") {
482 return true
483 }
484 for _, deny := range m.DeniedPaths {
485 if path == deny || strings.HasPrefix(path, deny+"/") {
486 return true
487 }
488 }
489 if path != "/workspace" && !strings.HasPrefix(path, "/workspace/") {
490 return false
491 }
492 host := m.Workspace
493 if !filepath.IsAbs(host) {
494 return true
495 }
496 rel := strings.TrimPrefix(strings.TrimPrefix(path, "/workspace"), "/")
497 if rel == "" {
498 return false
499 }
500 for _, part := range strings.Split(rel, "/") {
501 host = filepath.Join(host, part)
502 info, err := os.Lstat(host)
503 if os.IsNotExist(err) {
504 return false
505 }
506 if err != nil || info.Mode()&os.ModeSymlink != 0 {
507 return true
508 }
509 }
510 return false
511}
512
513// darwinDecided reports a request on a Mac policy that only the port
514// decides: a native file action or a sandboxed command's network request.
515func darwinDecided(q permissionRequest, policy provider.Policy) bool {
516 m, ok := policyManifest(policy)
517 return ok && m.darwin() && (q.Tool == "SandboxNetworkAccess" || slices.Contains([]string{"Read", "Write", "Edit", "Glob", "Grep"}, q.Tool))
518}
519
520// researchNativePath reports a read (Read, Glob or Grep) of /research,
521// where containment binds a task's kept Research images read-only for
522// Engineering and Review (a flat directory of regular files; nothing is
523// there for any other launch). Writes there are never allowed.
524func researchNativePath(q permissionRequest, policy provider.Policy) bool {
525 return readNativePath(q, policy, "/research")
526}
527
528// readNativePath reports a Read, Glob or Grep whose path is root or
529// under it, on a Linux policy only (a Mac's file actions are decided by
530// darwinPlace). Callers must first refuse protectedNativePath.
531func readNativePath(q permissionRequest, policy provider.Policy, root string) bool {
532 if !slices.Contains([]string{"Read", "Glob", "Grep"}, q.Tool) {
533 return false
534 }
535 if m, ok := policyManifest(policy); !ok || !m.portable() {
536 return false
537 } else if m.darwin() {
538 return false
539 }
540 var input map[string]json.RawMessage
541 if json.Unmarshal(q.Input, &input) != nil {
542 return false
543 }
544 path := ""
545 for _, key := range []string{"file_path", "path"} {
546 if raw, ok := input[key]; ok {
547 if json.Unmarshal(raw, &path) != nil {
548 return false
549 }
550 break
551 }
552 }
553 if !filepath.IsAbs(path) {
554 return false
555 }
556 path = filepath.Clean(path)
557 return path == root || strings.HasPrefix(path, root+"/")
558}
559
560// workspaceNativePath reports a native file action whose path is inside
561// /workspace. Callers must first refuse protectedNativePath, which also
562// rejects existing workspace symlinks. A symlink swapped after Equipo checks
563// remains a race: Claude's own symlink-aware /home deny rules must catch it.
564// This is an accepted residual risk, not an atomic filesystem guarantee.
565func workspaceNativePath(q permissionRequest, policy provider.Policy) bool {
566 if !slices.Contains([]string{"Read", "Write", "Edit", "Glob", "Grep"}, q.Tool) {
567 return false
568 }
569 if m, ok := policyManifest(policy); !ok || !m.portable() {
570 return false
571 } else if m.darwin() {
572 return false
573 }
574 var input map[string]json.RawMessage
575 if json.Unmarshal(q.Input, &input) != nil {
576 return false
577 }
578 path := ""
579 for _, key := range []string{"file_path", "path"} {
580 if raw, ok := input[key]; ok {
581 if json.Unmarshal(raw, &path) != nil || path == "" || strings.HasPrefix(path, "~") {
582 return false
583 }
584 break
585 }
586 }
587 if !filepath.IsAbs(path) {
588 return false
589 }
590 path = filepath.Clean(path)
591 return path == "/workspace" || strings.HasPrefix(path, "/workspace/")
592}
593