package stage import ( "encoding/json" "fmt" "io" "path/filepath" "strings" ) // Nil means normal stage defaults; an explicit empty list denies that action. type ToolPolicy struct { Edit []string `json:"edit"` Shell []string `json:"shell"` } func StagePermissions(def Definition) (ToolPolicy, error) { text, present := def.Blocks["permissions"] if !present { return ToolPolicy{}, nil } if err := validateUniqueJSON(text); err != nil { return ToolPolicy{}, fmt.Errorf("invalid permissions JSON: %w", err) } var fields map[string]json.RawMessage if json.Unmarshal([]byte(text), &fields) == nil { for name, value := range fields { if string(value) == "null" { return ToolPolicy{}, fmt.Errorf("permissions %s must be an array, not null", name) } } } decoder := json.NewDecoder(strings.NewReader(text)) decoder.DisallowUnknownFields() var policy *ToolPolicy if err := decoder.Decode(&policy); err != nil { return ToolPolicy{}, fmt.Errorf("permissions must be a JSON object with edit/shell lists: %w", err) } var extra any if err := decoder.Decode(&extra); err != io.EOF || policy == nil { return ToolPolicy{}, fmt.Errorf("permissions must be one non-null JSON object") } tools, err := effectiveTools(def) if err != nil { return ToolPolicy{}, err } has := func(action string) bool { for _, tool := range tools { if tool == action { return true } } return false } if policy.Edit != nil && !has("edit") { return ToolPolicy{}, fmt.Errorf("edit permissions require the edit tool") } if policy.Shell != nil && !has("shell") { return ToolPolicy{}, fmt.Errorf("shell permissions require the shell tool") } if len(policy.Edit) > 20 || len(policy.Shell) > 20 { return ToolPolicy{}, fmt.Errorf("permissions allow at most 20 resources per action") } seen := map[string]bool{} for _, pattern := range policy.Edit { if pattern == "" || strings.TrimSpace(pattern) != pattern || filepath.IsAbs(pattern) || strings.ContainsAny(pattern, "\\\r\n") { return ToolPolicy{}, fmt.Errorf("edit permissions must be nonempty run-directory-relative patterns") } for _, part := range strings.Split(pattern, "/") { if part == ".." || part == "." || part == "" { return ToolPolicy{}, fmt.Errorf("edit patterns must not traverse directories") } } if seen[pattern] { return ToolPolicy{}, fmt.Errorf("duplicate edit permission") } seen[pattern] = true } seen = map[string]bool{} for _, command := range policy.Shell { if command == "" || strings.TrimSpace(command) != command || strings.ContainsAny(command, "*?;|&<>`$\r\n\\") { return ToolPolicy{}, fmt.Errorf("shell permissions must be exact commands without wildcards, chaining, redirects, or expansion") } if seen[command] { return ToolPolicy{}, fmt.Errorf("duplicate shell permission") } seen[command] = true } // An unrestricted shell can bypass any edit-tool path restriction. if policy.Edit != nil && has("shell") && policy.Shell == nil { return ToolPolicy{}, fmt.Errorf("restricted edit paths require an explicit shell command list (or no shell tool)") } return *policy, nil }