返回 DeepSeek-Reasonix
shellsafe.go
根目录 / internal / shellsafe / shellsafe.go
1 // Package shellsafe is the single source of truth for which shell commands are
2 // read-only — they don't modify filesystem, network, or process state. The
3 // permission auto-approve path and explicitly read-only runners share these
4 // tables so their command classification cannot drift.
5 package shellsafe
6
7 import (
8 "strings"
9
10 "mvdan.cc/sh/v3/syntax"
11
12 "reasonix/internal/shellparse"
13 )
14
15 // readOnlyCommands holds single-word commands whose base name alone implies a
16 // read-only operation. The first word of a command (lowercased) is looked up
17 // here. Commands that are read-only only for certain subcommands (e.g. git) are
18 // in readOnlyPrefixes.
19 var readOnlyCommands = map[string]bool{
20 "cat": true, "head": true, "tail": true, "less": true, "more": true,
21 "ls": true, "find": true, "locate": true, "which": true, "whereis": true, "type": true,
22 "grep": true, "egrep": true, "fgrep": true, "rg": true,
23 "echo": true, "printf": true,
24 "pwd": true, "cd": true, "whoami": true, "id": true, "uname": true, "hostname": true,
25 "date": true, "printenv": true,
26 "wc": true, "sort": true, "uniq": true, "cut": true, "tr": true,
27 "stat": true, "file": true, "du": true, "df": true,
28 "ps": true, "top": true, "htop": true,
29 "diff": true, "cmp": true, "comm": true,
30 "man": true, "info": true, "help": true,
31 "true": true, "false": true, "test": true, "[": true,
32 "basename": true, "dirname": true, "realpath": true, "readlink": true,
33 // PowerShell inspection cmdlets. Keep this list intentionally narrow: only
34 // cmdlets whose verb is intrinsically observational belong here. The parser
35 // still rejects pipelines, substitutions, redirections, and command chains.
36 "get-childitem": true, "get-content": true, "get-item": true,
37 "get-location": true, "get-process": true, "get-command": true,
38 "get-nettcpconnection": true,
39 "resolve-path": true, "select-string": true, "measure-object": true,
40 "compare-object": true,
41 }
42
43 // workspaceNonMutatingCommands holds commands that do not write workspace
44 // state but are not safe to auto-allow as permission-layer readers. Keep this
45 // separate from readOnlyCommands: Test-NetConnection performs network I/O and
46 // must still pass through the user's permission policy even though Delivery
47 // does not need to serialize it behind the workspace writer.
48 var workspaceNonMutatingCommands = map[string]bool{
49 "test-netconnection": true,
50 }
51
52 // readOnlyPrefixes maps a base command to the set of subcommands (the second
53 // word) that are read-only. A subcommand not listed here is treated as not
54 // read-only (fail-closed): write-capable subcommands (git branch/remote/config,
55 // go build/test, npm install, …) are deliberately absent.
56 var readOnlyPrefixes = map[string]map[string]bool{
57 "git": {
58 "log": true, "status": true, "diff": true, "show": true,
59 "tag": true,
60 "blame": true, "grep": true, "ls-files": true, "ls-tree": true,
61 "rev-parse": true, "rev-list": true, "describe": true, "reflog": true,
62 "shortlog": true, "whatchanged": true, "cherry": true,
63 "cat-file": true, "for-each-ref": true, "name-rev": true,
64 },
65 "go": {
66 "vet": true, "doc": true, "list": true,
67 "version": true, "env": true,
68 },
69 "npm": {
70 "ls": true, "list": true, "view": true, "info": true,
71 "outdated": true, "audit": true,
72 },
73 "cargo": {
74 // check/doc are deliberately absent: cargo runs the crate's build.rs
75 // (arbitrary code) even for them — classifyCargo already bills both as
76 // code-executing writers, and this legacy table must not disagree.
77 "search": true,
78 },
79 "docker": {
80 "ps": true, "images": true, "inspect": true, "logs": true,
81 "stats": true, "info": true, "version": true,
82 },
83 "kubectl": {
84 "get": true, "describe": true, "logs": true, "explain": true,
85 "api-resources": true, "api-versions": true,
86 },
87 // Version/help probes for common runtimes (the second word is a flag).
88 "node": {"-v": true, "--version": true},
89 "python": {},
90 "python3": {},
91 }
92
93 // readOnlyPrefix reports whether word, the second word of a call to base, keeps
94 // it read-only. Python's probes are matched by exact spelling: lowercasing would
95 // read -V as -v, and -v is verbose import tracing, so `python3 -v script.py`
96 // runs the script.
97 func readOnlyPrefix(base, word string) bool {
98 if base == "python" || base == "python3" {
99 return word == "--version" || word == "-V"
100 }
101 return readOnlyPrefixes[base][strings.ToLower(word)]
102 }
103
104 // ContainsShellSyntax reports whether a command uses shell operators or
105 // substitution — chaining/redirection/expansion can smuggle a write past a
106 // read-only base-word check, so any such command is treated as not read-only.
107 func ContainsShellSyntax(cmd string) bool {
108 return shellparse.ContainsShellSyntax(cmd)
109 }
110
111 // CommandIsReadOnly is the legacy coarse read-only adapter.
112 // Deprecated: production policy must use ClassifyBash and project its axis.
113 func CommandIsReadOnly(command string) (base, sub string, ok bool) {
114 base, sub, _, ok = ClassifyReadOnlyCommand(command)
115 return base, sub, ok
116 }
117
118 // ClassifyReadOnlyCommand returns the resolved argument fields as well as the
119 // command classification. Dynamic fields are opaque placeholders and are
120 // returned only for the narrowly verified substitution shape above.
121 // Deprecated: retained for compatibility and narrow substitution validation.
122 func ClassifyReadOnlyCommand(command string) (base, sub string, fields []string, ok bool) {
123 fields, malformed := shellparse.StaticFields(command)
124 if malformed != "" {
125 var dynamic bool
126 fields, dynamic, ok = resolvedReadOnlyFields(command, false)
127 if !ok || !dynamic {
128 return "", "", nil, false
129 }
130 }
131 if len(fields) == 0 {
132 return "", "", nil, false
133 }
134 base = strings.ToLower(fields[0])
135 if readOnlyCommands[base] {
136 if hasResolvedSubstitution(fields) && !substitutionSafeCommands[base] {
137 return "", "", nil, false
138 }
139 return base, "", fields, true
140 }
141 if len(fields) > 1 {
142 if _, prefixed := readOnlyPrefixes[base]; prefixed {
143 sub = strings.ToLower(fields[1])
144 if readOnlyPrefix(base, fields[1]) {
145 return base, sub, fields, true
146 }
147 }
148 }
149 return "", "", nil, false
150 }
151
152 const resolvedSubstitutionPlaceholder = "__reasonix_read_only_substitution__"
153
154 var substitutionSafeCommands = map[string]bool{
155 "cat": true, "head": true, "tail": true, "ls": true,
156 "grep": true, "egrep": true, "fgrep": true, "rg": true,
157 "echo": true, "printf": true, "pwd": true, "whoami": true,
158 "id": true, "uname": true, "hostname": true, "wc": true,
159 "stat": true, "file": true, "du": true, "df": true,
160 "cmp": true, "comm": true, "true": true, "false": true,
161 "test": true, "[": true, "basename": true, "dirname": true,
162 "realpath": true, "readlink": true,
163 }
164
165 func hasResolvedSubstitution(fields []string) bool {
166 for _, field := range fields {
167 if strings.Contains(field, resolvedSubstitutionPlaceholder) {
168 return true
169 }
170 }
171 return false
172 }
173
174 // resolvedReadOnlyFields accepts one narrow dynamic shape: a command from the
175 // read-only table with a double-quoted command substitution whose nested
176 // command is itself a single, static, argument-safe read-only command. It never
177 // evaluates output. Unquoted substitutions, parameters, arithmetic, process
178 // substitutions, redirects, assignments, chains, and background jobs remain
179 // fail-closed.
180 func resolvedReadOnlyFields(command string, nested bool) ([]string, bool, bool) {
181 file, err := shellparse.ParseBash(command)
182 if err != nil || len(file.Stmts) != 1 {
183 return nil, false, false
184 }
185 return resolvedReadOnlyStmt(file.Stmts[0], nested)
186 }
187
188 func resolvedReadOnlyStmt(stmt *syntax.Stmt, nested bool) ([]string, bool, bool) {
189 if stmt == nil || stmt.Negated || stmt.Background || stmt.Coprocess || stmt.Disown || len(stmt.Redirs) > 0 {
190 return nil, false, false
191 }
192 call, ok := stmt.Cmd.(*syntax.CallExpr)
193 if !ok || len(call.Assigns) > 0 || len(call.Args) == 0 {
194 return nil, false, false
195 }
196 fields := make([]string, 0, len(call.Args))
197 dynamic := false
198 for _, word := range call.Args {
199 field, wordDynamic, ok := resolvedReadOnlyWord(word)
200 if !ok {
201 return nil, false, false
202 }
203 fields = append(fields, field)
204 dynamic = dynamic || wordDynamic
205 }
206 base, sub, tableOK := readOnlyFields(fields)
207 if !tableOK || (nested && (!substitutionSafeCommands[base] || !nestedReadOnlyArgsSafe(base, sub, fields))) {
208 return nil, false, false
209 }
210 return fields, dynamic, true
211 }
212
213 func resolvedReadOnlyWord(word *syntax.Word) (string, bool, bool) {
214 if static, ok := shellparse.StaticWord(word); ok {
215 return static, false, true
216 }
217 if word == nil {
218 return "", false, false
219 }
220 var out strings.Builder
221 dynamic := false
222 for _, part := range word.Parts {
223 value, partDynamic, ok := resolvedReadOnlyWordPart(part, false)
224 if !ok {
225 return "", false, false
226 }
227 out.WriteString(value)
228 dynamic = dynamic || partDynamic
229 }
230 return out.String(), dynamic, true
231 }
232
233 func resolvedReadOnlyWordPart(part syntax.WordPart, doubleQuoted bool) (string, bool, bool) {
234 switch value := part.(type) {
235 case *syntax.Lit:
236 return value.Value, false, true
237 case *syntax.SglQuoted:
238 return value.Value, false, true
239 case *syntax.DblQuoted:
240 var out strings.Builder
241 dynamic := false
242 for _, nested := range value.Parts {
243 text, partDynamic, ok := resolvedReadOnlyWordPart(nested, true)
244 if !ok {
245 return "", false, false
246 }
247 out.WriteString(text)
248 dynamic = dynamic || partDynamic
249 }
250 return out.String(), dynamic, true
251 case *syntax.CmdSubst:
252 if !doubleQuoted || value.TempFile || value.ReplyVar || len(value.Stmts) != 1 {
253 return "", false, false
254 }
255 if _, _, ok := resolvedReadOnlyStmt(value.Stmts[0], true); !ok {
256 return "", false, false
257 }
258 return resolvedSubstitutionPlaceholder, true, true
259 default:
260 return "", false, false
261 }
262 }
263
264 func readOnlyFields(fields []string) (base, sub string, ok bool) {
265 if len(fields) == 0 {
266 return "", "", false
267 }
268 base = strings.ToLower(fields[0])
269 if readOnlyCommands[base] {
270 return base, "", true
271 }
272 if len(fields) > 1 {
273 sub = strings.ToLower(fields[1])
274 if readOnlyPrefix(base, fields[1]) {
275 return base, sub, true
276 }
277 }
278 return "", "", false
279 }
280
281 func nestedReadOnlyArgsSafe(base, sub string, fields []string) bool {
282 args := fields[1:]
283 if sub != "" && len(args) > 0 {
284 args = args[1:]
285 }
286 for _, arg := range args {
287 switch {
288 case base == "find" && (arg == "-exec" || arg == "-execdir" || arg == "-delete" || arg == "-ok" || arg == "-okdir" || arg == "-fls" || arg == "-fprint" || arg == "-fprint0" || arg == "-fprintf"):
289 return false
290 case base == "sed" && (strings.HasPrefix(arg, "-i") || strings.HasPrefix(arg, "--in-place")):
291 return false
292 case base == "sort" && (strings.HasPrefix(arg, "-o") || arg == "--output" || strings.HasPrefix(arg, "--output=")):
293 return false
294 case base == "git" && (sub == "diff" || sub == "show" || sub == "log") && (arg == "--output" || strings.HasPrefix(arg, "--output=")):
295 return false
296 case base == "go" && sub == "env" && (arg == "-w" || arg == "-u"):
297 return false
298 }
299 }
300 return base != "git" || sub != "tag" || len(args) == 0 || args[0] == "-l" || args[0] == "--list"
301 }
302
303 // CommandIsWorkspaceNonMutating reports commands that Delivery can execute
304 // without acquiring the workspace writer. Permission-safe readers are a
305 // subset; network probes live only in workspaceNonMutatingCommands so this
306 // classification cannot silently widen approval or read-only subagent access.
307 // Deprecated: production policy consumers must use ClassifyBash.
308 func CommandIsWorkspaceNonMutating(command string) (base, sub string, ok bool) {
309 base, sub, _, ok = ClassifyWorkspaceNonMutatingCommand(command)
310 return base, sub, ok
311 }
312
313 // ClassifyWorkspaceNonMutatingCommand is the field-carrying form used by
314 // Delivery mutation accounting.
315 // Deprecated: retained as a compatibility adapter.
316 func ClassifyWorkspaceNonMutatingCommand(command string) (base, sub string, fields []string, ok bool) {
317 if base, sub, fields, ok = ClassifyReadOnlyCommand(command); ok {
318 return base, sub, fields, true
319 }
320 fields, malformed := shellparse.StaticFields(command)
321 if malformed != "" || len(fields) == 0 {
322 return "", "", nil, false
323 }
324 base = strings.ToLower(fields[0])
325 if workspaceNonMutatingCommands[base] {
326 return base, "", fields, true
327 }
328 return "", "", nil, false
329 }
330
330 lines GO