@cratis/pi 7.131.1 → 7.131.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -6,13 +6,13 @@
6
6
  # reads and credential files. This guard is what enforces it: every simple command in the shell command is
7
7
  # found (quotes, $( ), backticks, subshells, pipelines, here-documents, `bash -c`, `eval`, `kubectl exec ... --`
8
8
  # and `docker exec`, and the wrappers sudo/env/timeout/xargs/rtk are looked through) and classified. A command
9
- # that only mentions a word inside an argument (echo, rg, grep, git commit -m) is never a finding.
10
- # Exit 2 blocks the tool call and sends stderr back to the model; every other command exits 0.
9
+ # that names a protected file is subject to the conservative literal-command rule below.
10
+ # Exit 2 blocks the tool call and sends stderr back to the model; every other command exits 0. While jq is
11
+ # missing the guard cannot read the tool call, so it refuses every call.
11
12
  #
12
- # What it sees is the command text. A credential reached through a variable, an alias, a function, a script
13
- # file or a pipe into a shell is invisible to it, as is a recursive search with no named file; a projection it
14
- # cannot see through (a template or `-o jsonpath` that is not a bare `{.}`) is trusted. A redirect does not
15
- # exempt anything: `env > f` is blocked like `env`. See .cratis/ai/hooks/README.md.
13
+ # The guard is conservative: a command naming a protected file runs only as a single literal read or template
14
+ # copy, and other such commands must be split into literal calls. Names produced by programs, inherited values,
15
+ # aliases, functions, script files and recursive searches without named files remain outside its text analysis.
16
16
  #
17
17
  # Escape hatch for a human who authorized the read — set in the environment the agent harness was started
18
18
  # from, never inside the command (an assignment in the command is ignored):
@@ -28,24 +28,39 @@ set -euo pipefail
28
28
 
29
29
  input="$(hook_read_stdin)"
30
30
  [ -n "$input" ] || exit 0
31
- hook_have jq || exit 0
31
+ hook_require_jq cratis-guard-secrets CRATIS_HOOKS_ALLOW_SECRET_READS
32
32
 
33
- command_text="$(hook_json "$input" '.tool_input.command')"
33
+ parser_failed() {
34
+ printf '%s\n' 'BLOCKED by cratis-guard-secrets: parser failed; cannot check this tool call.' >&2
35
+ exit 2
36
+ }
37
+
38
+ command_text="$(jq -r '.tool_input.command // empty' <<<"$input")" || parser_failed
34
39
  [ -n "$command_text" ] || exit 0
35
40
 
36
- # Cheap exit for the overwhelming majority of shell commands, which mention none of these words.
37
- case "$(printf '%s' "$command_text" | tr '[:upper:]' '[:lower:]')" in
41
+ # Cheap exit for the overwhelming majority of shell commands, which mention none of these words. The shell
42
+ # reads a word after removing quotes, escapes and line continuations, so the words are looked for in that
43
+ # form. A command that still shows none is parsed anyway when its raw text has an expansion, glob or brace
44
+ # character: this list must stay a superset of the protected stems the parser can resolve.
45
+ probe=${command_text//\\$'\n'/}
46
+ probe=${probe//[\'\"\\]/}
47
+ probe_lower="$(printf '%s' "$probe" | tr '[:upper:]' '[:lower:]')" || parser_failed
48
+ case "$probe_lower" in
38
49
  *kubectl*|*printenv*|*env*|*docker*|*podman*|*"gh "*|*vault*|*pulumi*|*show-secret*|*aws*|*"az "*|*gcloud*|*kubeconfig*|*.kube*|\
39
- *export*|*declare*|*typeset*|*id_rsa*|*id_ed25519*|*id_ecdsa*|*id_dsa*|*.pem*|*.p12*|*.pfx*|*token*|*.netrc*|*.npmrc*|\
40
- *credentials*|*.pgpass*|*secrets*) ;;
41
- *) exit 0 ;;
50
+ *sh*|*extglob*|*set*|*emulate*|*'-o'*|*'+o'*|*globignore*|*export*|*declare*|*id_rsa*|*id_ed25519*|*id_ecdsa*|*id_dsa*|*.pem*|*.p12*|*.pfx*|*token*|*.netrc*|*.npmrc*|\
51
+ *credentials*|*.pgpass*|*pypirc*|*secrets*) ;;
52
+ *)
53
+ case "$command_text" in
54
+ *'$'*|*'*'*|*'?'*|*'['*|*'{'*|*'('*|*'^'*|*'~'*|*'`'*) ;;
55
+ *) exit 0 ;;
56
+ esac ;;
42
57
  esac
43
58
 
44
59
  IFS= read -r -d '' awk_program <<'AWK' || true
45
60
  function report(what, alt) {
46
61
  if (what in seen) return
47
62
  seen[what] = 1
48
- printf "%s\t%s\n", what, alt
63
+ reports = reports sprintf("%s\t%s\n", what, alt)
49
64
  }
50
65
  function enqueue(text) {
51
66
  if (text == "" || queued >= 64) return
@@ -54,16 +69,255 @@ function enqueue(text) {
54
69
  function base(word) { word = tolower(word); sub(/.*\//, "", word); return word }
55
70
 
56
71
  # ── tokenizer: splits text into simple commands, queueing nested command text ──
72
+ # Appends text to the current word and records how the shell reads each character in the parallel mask wmask:
73
+ # l literal (single-quoted, escaped or ANSI-C decoded), d inside double quotes, u unquoted, c command output.
74
+ # An uppercase mask character marks the first character after a quote boundary, including an empty segment.
75
+ function addw(text, kind, k) {
76
+ word = word text
77
+ for (k = 1; k <= length(text); k++) { wmask = wmask (quote_boundary ? toupper(kind) : kind); quote_boundary = 0 }
78
+ }
57
79
  function flush_word() {
58
- if (inword) { W[++nw] = word; WP[nw] = wplain }
59
- word = ""; inword = 0; wquoted = 0; wplain = 0
80
+ if (inword) { W[++nw] = word; WP[nw] = wplain; WM[nw] = wmask }
81
+ word = ""; wmask = ""; inword = 0; wquoted = 0; wplain = 0; quote_boundary = 0
82
+ }
83
+ # Decodes the body of an ANSI-C string $'...' (i is just after the opening quote) into the word and returns the
84
+ # position after the closing quote. The same decoder is in cratis-guard-store-mutations.sh (`ansi_c`).
85
+ function ansi_c(s, i, n, c, c2, v, d, k, lim, stop, digits) {
86
+ stop = 0
87
+ while (i <= n) {
88
+ c = substr(s, i, 1)
89
+ if (c == "\047") return i + 1
90
+ if (c != "\\") { if (!stop) addw(c, "l"); i++; continue }
91
+ c2 = substr(s, i + 1, 1); i += 2; v = -1
92
+ if (c2 in ESC) v = ESC[c2]
93
+ else if (c2 ~ /^[0-7]$/) {
94
+ v = c2 + 0
95
+ for (k = 0; k < 2 && substr(s, i, 1) ~ /^[0-7]$/; k++) { v = v * 8 + substr(s, i, 1); i++ }
96
+ v = v % 256
97
+ } else if (c2 == "x" || c2 == "u" || c2 == "U") {
98
+ lim = (c2 == "x") ? 2 : (c2 == "u") ? 4 : 8; v = 0; digits = 0
99
+ while (digits < lim && (d = tolower(substr(s, i, 1))) != "" && (d in HEX)) { v = v * 16 + HEX[d]; i++; digits++ }
100
+ if (digits == 0) { if (!stop) addw("\\" c2, "l"); continue }
101
+ if (c2 != "x" && v >= 128) { if (!stop) addw("?", "c"); continue }
102
+ } else if (c2 == "c" && i <= n) { v = ORD[substr(s, i, 1)] % 32; i++ }
103
+ else { if (!stop) addw("\\" c2, "l"); continue }
104
+ if (v == 0) stop = 1
105
+ else if (!stop) addw(CH[v], "l")
106
+ }
107
+ return i
60
108
  }
61
109
  # Output redirections are removed before a command is analyzed, so a redirect never shifts a CLI's subcommand
62
110
  # or operands (`kubectl get > /dev/stdout secrets`). Nothing is exempted: the command itself is still analyzed.
63
111
  # A word is a redirection only when its whole operator lies in the word's unquoted prefix (WP: characters before
64
112
  # the first quoted or escaped one), so `1">"b` and `">x"` stay operands; input redirections (`< file`) stay too.
65
- function end_cmd( k, m, w) {
113
+ function stem_boundary(t, start, finish, stem, a, b, before, after) {
114
+ if (stem == "/environ" && substr(t, finish + 1, 1) ~ /[a-z0-9_]/) return 0
115
+ if (stem !~ /^(id_rsa|id_ed25519|id_ecdsa|id_dsa|kubeconfig|credentials)$/) return 1
116
+ a = start; b = finish
117
+ while (a > 1 && substr(t, a - 1, 1) ~ /[a-z0-9_]/) a--
118
+ while (b < length(t) && substr(t, b + 1, 1) ~ /[a-z0-9_]/) b++
119
+ before = substr(t, a - 1, 1); after = substr(t, b + 1)
120
+ return !(before == "$" || before == "-" || (before == "{" && substr(t, a - 2, 1) == "$") || after ~ /^(=|\+=)/)
121
+ }
122
+ function glob_end(t, p, j, depth, c) {
123
+ for (j = p; j <= length(t); j++) {
124
+ c = substr(t, j, 1)
125
+ if (c ~ /[ \t\n\047"]/) return 0
126
+ if (c == "(") depth++
127
+ else if (c == ")" && --depth == 0) return j
128
+ }
129
+ return 0
130
+ }
131
+ # Memoized matching keeps stars and grouped globs bounded by the length of a protected stem.
132
+ # Two literal characters are required: a generic pattern such as *.md is not a protected name.
133
+ function glob_negation(t, p) { return substr(t, p, 1) ~ /^[~^]$/ && p > 1 && substr(t, p - 1, 1) !~ /[\/=:]/ }
134
+ function stem_match(t, stem, p, k, literals, wildcard, key, c, end, nextp, j, result, bracket) {
135
+ key = p SUBSEP k SUBSEP literals SUBSEP wildcard
136
+ if (key in SM) return SM[key]
137
+ if (k > length(stem)) return SM[key] = (wildcard && literals >= 2 ? p - 1 : 0)
138
+ c = substr(t, p, 1)
139
+ if (c == "" || c ~ /[\001-\007]/) return SM[key] = 0
140
+ nextp = 0
141
+ if (c ~ /[?*+@!]/ && substr(t, p + 1, 1) == "(") nextp = glob_end(t, p + 1) + 1
142
+ else if (c == "(" && (end = glob_end(t, p))) nextp = end + 1
143
+ if (nextp > p || c == "*" || glob_negation(t, p)) {
144
+ if (!nextp) nextp = p + 1
145
+ for (j = k; j <= length(stem) + 1; j++) {
146
+ result = stem_match(t, stem, nextp, j, literals, 1)
147
+ if (result) return SM[key] = result
148
+ }
149
+ } else if (c == "?") return SM[key] = stem_match(t, stem, p + 1, k + 1, literals, 1)
150
+ else if (c == "[" && (end = bracket_end(t, p)) > 0) {
151
+ bracket = substr(t, p + 1, end - p - 1)
152
+ if (bracket !~ /[ \t\n\047"]/ && substr(stem, k, 1) ~ rxize("\006" bracket "\007"))
153
+ return SM[key] = stem_match(t, stem, end + 1, k + 1, literals, 1)
154
+ } else if (c == substr(stem, k, 1)) return SM[key] = stem_match(t, stem, p + 1, k + 1, literals < 2 ? literals + 1 : 2, wildcard)
155
+ return SM[key] = 0
156
+ }
157
+ function stem_units(t, m, start, stem) {
158
+ delete SM
159
+ return stem_match(t, stem, start, 1, 0, 0)
160
+ }
161
+ function stem_scan(text, mode, t, k, stem, pos, offset, first, found, end, p, candidate) {
162
+ t = tolower(text)
163
+ for (k = 1; k <= nstem; k++) {
164
+ stem = STEM[k]; offset = 0
165
+ while ((pos = index(substr(t, offset + 1), stem)) > 0) {
166
+ pos += offset; end = pos + length(stem) - 1
167
+ if (stem_boundary(t, pos, end, stem) && (!first || pos < first)) { first = pos; found = stem; break }
168
+ offset = pos
169
+ }
170
+ if (stem == ".kube/") {
171
+ pos = index(t, ".kube")
172
+ if (pos && (pos + 5 > length(t) || substr(t, pos + 5, 1) ~ /^[ \t\n;|&]$/) && (!first || pos < first)) { first = pos; found = stem }
173
+ }
174
+ }
175
+ if (mode != "resolved" && t ~ /[*?[(~^]/) {
176
+ for (p = 1; p <= length(t) && (!first || p < first); p++) {
177
+ candidate = substr(t, p, 1)
178
+ for (k = 1; k <= nstem; k++) {
179
+ stem = STEM[k]
180
+ if (candidate != substr(stem, 1, 1) && candidate !~ /[*?[(@+!~^]/) continue
181
+ end = stem_units(t, mode, p, stem)
182
+ if (end && stem_boundary(t, p, end, stem)) { first = p; found = stem; break }
183
+ }
184
+ }
185
+ }
186
+ return found
187
+ }
188
+ function literal_word(w, m, k, c, mk) {
189
+ for (k = 1; k <= length(w); k++) {
190
+ c = substr(w, k, 1); mk = tolower(substr(m, k, 1))
191
+ if (mk == "c" || (c == "$" && mk != "l") || (mk == "u" && (c ~ /[*?[()]/ || glob_negation(w, k)))) return 0
192
+ }
193
+ return !(substr(w, 1, 1) == "~" && substr(w, 2, 1) != "/")
194
+ }
195
+ # RP records only exempt regex text. Other option values are skipped while locating the pattern, not while scanning stems.
196
+ # With any -e or -f there is no implicit pattern operand. Attached patterns exempt only their suffix.
197
+ function regex_flag(w) {
198
+ return w ~ /^--(ignore-case|no-ignore-case|word-regexp|line-regexp|fixed-strings|basic-regexp|extended-regexp|perl-regexp|invert-match|line-number|no-line-number|count|files-with-matches|files-without-match|only-matching|quiet|silent|text|binary|no-messages|with-filename|no-filename|heading|no-heading|no-ignore|hidden|no-hidden|recursive|help|version|color|colour)$/
199
+ }
200
+ function regex_value(w) {
201
+ return w ~ /^--(file|glob|iglob|include|exclude|exclude-dir|type|type-not|type-add|type-clear|max-count|max-depth|maxdepth|max-filesize|encoding|engine|pre|pre-glob|sort|sortr|threads|replace|label|colors|after-context|before-context|context|ignore-file|path-separator|hostname-bin)$/
202
+ }
203
+ function regex_short_flag(b, c) {
204
+ return c ~ /^[EFGPivwxcnNlLoqsaHIhVzuUSyZ0]$/ || (c ~ /^[rRT]$/ && b != "rg")
205
+ }
206
+ function regex_slots(A, s, n, b, k, j, w, c, explicit, ended, attached, uncertain) {
207
+ delete RP; delete ROPER
208
+ b = base(A[s])
209
+ if (b !~ /^(grep|egrep|fgrep|rg|ag)$/) return
210
+ for (k = s + 1; k <= n; k++) {
211
+ w = A[k]
212
+ if (!ended && w == "--") { ended = 1; continue }
213
+ if (!ended && w ~ /^--/) {
214
+ if (w ~ /^--(regexp|file)(=|$)/) explicit = 1
215
+ if (w ~ /^--regexp=/) RP[k] = index(w, "=")
216
+ else if (w == "--regexp") RP[++k] = -1
217
+ else if (w !~ /=/ && regex_value(w)) k++
218
+ continue
219
+ }
220
+ if (!ended && w ~ /^-./) {
221
+ for (j = 2; j <= length(w); j++) {
222
+ c = substr(w, j, 1)
223
+ if (c == "e" || c == "f") explicit = 1
224
+ if (!regex_short_flag(b, c)) {
225
+ if (!index("efgGtTmABCjdrD", c)) uncertain = 1
226
+ attached = (j < length(w))
227
+ if (c == "e") { if (attached) RP[k] = j; else RP[++k] = -1 }
228
+ else if (!attached) k++
229
+ break
230
+ }
231
+ }
232
+ continue
233
+ }
234
+ ROPER[k] = 1
235
+ }
236
+ if (!explicit && !uncertain) for (k = s + 1; k <= n; k++) if (k in ROPER) { RP[k] = -1; delete ROPER[k]; break }
237
+ }
238
+ function shell_quote(w, k, c, out) {
239
+ out = "\047"
240
+ for (k = 1; k <= length(w); k++) {
241
+ c = substr(w, k, 1)
242
+ out = out (c == "\047" ? "\047\\\047\047" : c)
243
+ }
244
+ return out "\047"
245
+ }
246
+ function directory_operand(w, path) {
247
+ if (w ~ /\/$/ || w == "." || w == "..") return 1
248
+ path = w
249
+ if (path ~ /^~\//) path = ENVIRON["HOME"] substr(path, 2)
250
+ if (path !~ /^\//) path = ENVIRON["GS_CWD"] "/" path
251
+ return system("test -d " shell_quote(path)) == 0
252
+ }
253
+ function metadata_shape(A, M, n, k, j, c, mk) {
254
+ if (A[1] != "ls" && A[1] != "stat") return 0
255
+ for (k = 1; k <= n; k++) for (j = 1; j <= length(A[k]); j++) {
256
+ c = substr(A[k], j, 1); mk = tolower(substr(M[k], j, 1))
257
+ if (mk == "c" || (c == "$" && mk != "l")) return 0
258
+ }
259
+ return 1
260
+ }
261
+ function literal_shape(A, M, n, k, j, b, words, count, pattern, ended, w, paths, flags) {
262
+ if (metadata_shape(A, M, n)) return 1
263
+ delete words
264
+ for (k = 1; k <= n; k++) {
265
+ if (is_assign(A[k]) || !literal_word(A[k], M[k])) return 0
266
+ resolve(A[k], M[k])
267
+ for (j = 1; j <= nalt; j++) {
268
+ if (has_sentinel(ALT[j])) return 0
269
+ words[++count] = ALT[j]
270
+ }
271
+ }
272
+ b = words[1]
273
+ if (b ~ /\// || b !~ /^(cat|head|tail|less|more|wc|grep|egrep|fgrep|rg|ls|stat|test|cp)$/) return 0
274
+ if (b ~ /^(ls|stat|test)$/) return 1
275
+ if (b == "cp") return count == 3 && words[2] !~ /^-/ && words[3] !~ /^-/ && sensitive_path(words[2]) == ""
276
+ pattern = (b ~ /^(grep|egrep|fgrep|rg)$/)
277
+ regex_slots(words, 1, count)
278
+ for (k = 2; k <= count; k++) {
279
+ w = words[k]
280
+ if (k in RP) { if (RP[k] < 0) continue; w = substr(w, 1, RP[k]) }
281
+ if (!ended && w == "--") { ended = 1; continue }
282
+ if (!ended && w ~ /^-./) {
283
+ if (pattern) {
284
+ if (w == "-e" || w == "--regexp" || w == "--regexp=") continue
285
+ if (w ~ /^--/) {
286
+ if (w == "--recursive" || !regex_flag(w)) return 0
287
+ } else {
288
+ flags = substr(w, 2)
289
+ if (flags ~ /[rR]/) return 0
290
+ for (j = 1; j <= length(flags); j++) if (!regex_short_flag(b, substr(flags, j, 1)) && !(substr(flags, j, 1) == "e" && (k in RP))) return 0
291
+ }
292
+ }
293
+ if (stem_scan(w, "raw") != "") return 0
294
+ continue
295
+ }
296
+ if (sensitive_path(w) != "") return 0
297
+ if (pattern && (k in ROPER)) {
298
+ paths++
299
+ if (b == "rg" && directory_operand(w)) return 0
300
+ }
301
+ }
302
+ return b != "rg" || paths > 0
303
+ }
304
+ function end_cmd( k, m, w, j, hit) {
66
305
  flush_word()
306
+ if (nw > 0) {
307
+ commands++
308
+ regex_slots(W, 1, nw)
309
+ for (k = 1; k <= nw; k++) {
310
+ if (is_assign(W[k])) set_var(W[k], WM[k])
311
+ if ((k in RP) && RP[k] < 0) continue
312
+ w = (k in RP) ? substr(W[k], 1, RP[k]) : W[k]
313
+ hit = stem_scan(w, "raw"); if (TAINT == "") TAINT = hit
314
+ if (!(k in RP) && expands(W[k], WM[k])) {
315
+ resolve(W[k], WM[k])
316
+ for (j = 1; j <= nalt; j++) { hit = stem_scan(ALT[j], "resolved"); if (TAINT == "") TAINT = hit }
317
+ }
318
+ }
319
+ if (!literal_shape(W, WM, nw)) simple_ok = 0
320
+ }
67
321
  m = 0
68
322
  for (k = 1; k <= nw; k++) {
69
323
  w = W[k]
@@ -71,12 +325,13 @@ function end_cmd( k, m, w) {
71
325
  if (RLENGTH == length(w)) k++
72
326
  continue
73
327
  }
74
- V[++m] = w
328
+ V[++m] = w; VM[m] = WM[k]
75
329
  }
76
- if (m > 0) analyze(V, 1, m)
77
- split("", W); split("", WP); split("", V); nw = 0
330
+ if (m > 0) { check_inputs(V, 1, m); analyze(V, 1, m) }
331
+ delete W; delete WP; delete WM; delete V; delete VM; nw = 0
78
332
  }
79
333
  function cmdsub(s, i, n, start, depth, c, j) {
334
+ complex = 1
80
335
  start = i; depth = 1
81
336
  while (i <= n) {
82
337
  c = substr(s, i, 1)
@@ -111,43 +366,47 @@ function read_heredocs(s, i, n, h, e, line, cmp, body) {
111
366
  return i
112
367
  }
113
368
  function tokenize(s, i, n, c, c2, j, dash, delim) {
114
- n = length(s); i = 1; nw = 0; word = ""; inword = 0; wquoted = 0; wplain = 0; nheredoc = 0; hd_shell = 0
115
- split("", W); split("", WP)
369
+ n = length(s); i = 1; nw = 0; word = ""; wmask = ""; inword = 0; wquoted = 0; wplain = 0; nheredoc = 0; hd_shell = 0; quote_boundary = 0
370
+ delete W; delete WP; delete WM
116
371
  while (i <= n) {
117
372
  c = substr(s, i, 1)
118
373
  if (c == "\\") {
119
374
  c2 = substr(s, i + 1, 1)
120
375
  if (c2 == "\n") { i += 2; continue }
121
- wquoted = 1; word = word c2; inword = 1; i += 2; continue
376
+ wquoted = 1; addw(c2, "l"); inword = 1; i += 2; continue
122
377
  }
123
378
  if (c == "\047") {
124
- wquoted = 1; inword = 1
379
+ wquoted = 1; inword = 1; quote_boundary = 1
125
380
  j = index(substr(s, i + 1), "\047")
126
- if (j == 0) { word = word substr(s, i + 1); i = n + 1; continue }
127
- word = word substr(s, i + 1, j - 1); i += j + 1; continue
381
+ if (j == 0) { addw(substr(s, i + 1), "l"); i = n + 1; continue }
382
+ addw(substr(s, i + 1, j - 1), "l"); quote_boundary = 1; i += j + 1; continue
128
383
  }
384
+ if (c == "$" && substr(s, i + 1, 1) == "\047") { wquoted = 1; inword = 1; quote_boundary = 1; i = ansi_c(s, i + 2, n); quote_boundary = 1; continue }
385
+ if (c == "$" && substr(s, i + 1, 1) == "\"") { i++; c = "\"" }
129
386
  if (c == "\"") {
130
- wquoted = 1; inword = 1; i++
387
+ wquoted = 1; inword = 1; quote_boundary = 1; i++
131
388
  while (i <= n) {
132
389
  c = substr(s, i, 1)
133
- if (c == "\\") { word = word substr(s, i + 1, 1); i += 2; continue }
134
- if (c == "\"") { i++; break }
135
- if (c == "$" && substr(s, i + 1, 1) == "(") { i = cmdsub(s, i + 2, n); word = word "x"; continue }
390
+ if (c == "\\") { addw(substr(s, i + 1, 1), "l"); i += 2; continue }
391
+ if (c == "\"") { quote_boundary = 1; i++; break }
392
+ if (c == "$" && substr(s, i + 1, 1) == "(") { i = cmdsub(s, i + 2, n); addw("x", "c"); continue }
136
393
  if (c == "`") {
394
+ complex = 1
137
395
  j = index(substr(s, i + 1), "`")
138
396
  if (j == 0) { i = n + 1; break }
139
- enqueue(substr(s, i + 1, j - 1)); i += j + 1; word = word "x"; continue
397
+ enqueue(substr(s, i + 1, j - 1)); i += j + 1; addw("x", "c"); continue
140
398
  }
141
- word = word c; i++
399
+ addw(c, "d"); i++
142
400
  }
143
401
  continue
144
402
  }
145
- if (c == "$" && substr(s, i + 1, 1) == "(") { wquoted = 1; inword = 1; i = cmdsub(s, i + 2, n); word = word "x"; continue }
403
+ if (c == "$" && substr(s, i + 1, 1) == "(") { wquoted = 1; inword = 1; i = cmdsub(s, i + 2, n); addw("x", "c"); continue }
146
404
  if (c == "`") {
405
+ complex = 1
147
406
  wquoted = 1; inword = 1
148
407
  j = index(substr(s, i + 1), "`")
149
408
  if (j == 0) { i = n + 1; continue }
150
- enqueue(substr(s, i + 1, j - 1)); i += j + 1; word = word "x"; continue
409
+ enqueue(substr(s, i + 1, j - 1)); i += j + 1; addw("x", "c"); continue
151
410
  }
152
411
  if (c == "#" && !inword) {
153
412
  j = index(substr(s, i), "\n")
@@ -161,10 +420,18 @@ function tokenize(s, i, n, c, c2, j, dash, delim) {
161
420
  continue
162
421
  }
163
422
  # `>&`, `>|` and `&>` are parts of a redirection operator, not command separators.
164
- if ((c == "&" || c == "|") && inword && !wquoted && word ~ />$/) { word = word c; wplain++; i++; continue }
165
- if (c == "&" && substr(s, i + 1, 1) == ">") { flush_word(); word = c; inword = 1; wplain = 1; i++; continue }
166
- if (c == ";" || c == "&" || c == "|" || c == "(" || c == ")") { end_cmd(); i++; continue }
423
+ if ((c == "&" || c == "|") && inword && !wquoted && word ~ />$/) { addw(c, "u"); wplain++; i++; continue }
424
+ if (c == "&" && substr(s, i + 1, 1) == ">") { flush_word(); addw(c, "u"); inword = 1; wplain = 1; i++; continue }
425
+ if (c == "(" && (j = glob_end(s, i)) > 0 && (inword || nw > 0 || substr(s, j + 1, 1) ~ /^[A-Za-z0-9_.]$/)) {
426
+ inword = 1; addw(substr(s, i, j - i + 1), "u"); i = j + 1; continue
427
+ }
428
+ if (c == ";" || c == "&" || c == "|" || c == "(" || c == ")") {
429
+ end_cmd()
430
+ complex = 1
431
+ i++; continue
432
+ }
167
433
  if (substr(s, i, 2) == "<<" && substr(s, i, 3) != "<<<") {
434
+ complex = 1
168
435
  flush_word(); i += 2; dash = 0
169
436
  if (substr(s, i, 1) == "-") { dash = 1; i++ }
170
437
  while (substr(s, i, 1) == " " || substr(s, i, 1) == "\t") i++
@@ -178,15 +445,23 @@ function tokenize(s, i, n, c, c2, j, dash, delim) {
178
445
  nheredoc++; HD[nheredoc] = delim; HDDASH[nheredoc] = dash
179
446
  continue
180
447
  }
448
+ if (c == "<") {
449
+ complex = 1
450
+ if (word !~ /^[0-9]+$/ || wquoted) flush_word()
451
+ addw(c, "u"); inword = 1; wplain++; i++
452
+ while (i <= n && substr(s, i, 1) ~ /[<>&]/) { addw(substr(s, i, 1), "u"); wplain++; i++ }
453
+ flush_word(); continue
454
+ }
455
+ if (c == ">") complex = 1
181
456
  if (!wquoted) wplain++
182
- word = word c; inword = 1; i++
457
+ addw(c, "u"); inword = 1; i++
183
458
  }
184
459
  end_cmd()
185
460
  }
186
461
 
187
462
  # ── option parsing shared by the CLIs: positionals P/PI, output format, -f/--format value, --raw ──
188
463
  function kparse(A, s, n, shortvals, i, w, eq, key, val, f, rest) {
189
- split("", P); split("", PI)
464
+ delete P; delete PI
190
465
  np = 0; outfmt = ""; fmtval = ""; tmpl = ""; dd = 0; raw = 0
191
466
  for (i = s; i <= n; i++) {
192
467
  w = A[i]
@@ -227,7 +502,7 @@ function skipopts(A, s, n, vals) {
227
502
  }
228
503
  return s
229
504
  }
230
- function is_assign(w) { return w ~ /^[A-Za-z_][A-Za-z0-9_]*=/ }
505
+ function is_assign(w) { return w ~ /^[A-Za-z_][A-Za-z0-9_]*(\[[^]]*\])?\+?=/ }
231
506
 
232
507
  # ── file classification for the reader commands ──
233
508
  function code_file(b) { return b ~ /\.(cs|ts|tsx|js|jsx|mjs|cjs|go|py|java|kt|rs|md)$/ }
@@ -245,14 +520,405 @@ function sensitive_path(w, l, b) {
245
520
  if (b ~ /\.(pem|p12|pfx)$/) return "a key or certificate file"
246
521
  if (b == "id_rsa" || b == "id_ed25519" || b == "id_ecdsa" || b == "id_dsa") return "a private key"
247
522
  if (b ~ /(^|[._-])tokens?($|[._-])/ && !code_file(b) && !token_ok(l, b)) return "a token file"
248
- if (b == ".netrc" || b == ".npmrc" || b == ".pgpass" || b == ".git-credentials") return "a credentials file"
249
- if (b == "credentials" && l ~ /\.aws\//) return "the AWS credentials file"
523
+ if (b == ".netrc" || b == ".npmrc" || b == ".pgpass" || b == ".pypirc" || b == ".git-credentials") return "a credentials file"
524
+ if (b == "credentials") return "a credentials file"
250
525
  if (l ~ /\.docker\/config\.json$/) return "the Docker registry credentials"
251
526
  if (l ~ /\/proc\/[^\/]*\/environ$/) return "a process environment"
252
527
  if (l ~ /^\/(var\/)?run\/secrets\//) return "mounted secrets"
253
528
  return ""
254
529
  }
255
530
 
531
+ # ── word resolution: what the shell reads a word as ──
532
+ # resolve() fills ALT[1..nalt]. \001 is an unresolved expansion; \003 is an external runtime value.
533
+ # \004 and \005 are pathname glob stars and single-character patterns, subject to default shell dot rules.
534
+ # Bindings anywhere in the command contribute alternatives. An incomplete expansion or a reached cap is never
535
+ # discarded: it becomes unresolved and is checked against protected names before a read is allowed.
536
+ function mask_of(A, k, m) { m = VM[k]; return (length(m) == length(A[k])) ? m : "" }
537
+ function expands(w, m, k, c, mk) {
538
+ if (m == "") return 0
539
+ for (k = length(w); k > 0; k--) {
540
+ c = substr(w, k, 1); mk = tolower(substr(m, k, 1))
541
+ if (mk == "c" || (c == "$" && mk != "l") || (mk == "u" && (c ~ /[*?[{()]/ || glob_negation(w, k)))) return 1
542
+ }
543
+ return 0
544
+ }
545
+ function find_group( i, j, depth, c) {
546
+ for (i = 1; i <= length(gw); i++) {
547
+ if (tolower(substr(gm, i, 1)) != "u" || substr(gw, i, 1) != "{" || (i > 1 && substr(gw, i - 1, 1) == "$")) continue
548
+ depth = 0; gnc = 0
549
+ for (j = i; j <= length(gw); j++) {
550
+ if (tolower(substr(gm, j, 1)) != "u") continue
551
+ c = substr(gw, j, 1)
552
+ if (c == "{") depth++
553
+ else if (c == "}") { depth--; if (depth == 0) break }
554
+ else if (c == "," && depth == 1) GCP[++gnc] = j
555
+ }
556
+ if (j > length(gw)) continue
557
+ gs = i; ge = j
558
+ if (gnc > 0) return 1
559
+ if (index(substr(gw, i, j - i), "..")) return 2
560
+ }
561
+ return 0
562
+ }
563
+ function brace_all(w, m, head, tail, r, k, e, a, pre, prem, suf, sufm) {
564
+ nf = 0; delete FW; delete FM; delete QW; delete QM
565
+ head = 1; tail = 1; QW[1] = w; QM[1] = m
566
+ while (head <= tail) {
567
+ gw = QW[head]; gm = QM[head]; head++
568
+ r = find_group()
569
+ if (r == 0) { FW[++nf] = gw; FM[nf] = gm; continue }
570
+ pre = substr(gw, 1, gs - 1); prem = substr(gm, 1, gs - 1)
571
+ suf = substr(gw, ge + 1); sufm = substr(gm, ge + 1)
572
+ if (r == 2 || (tail - head + 1) + nf + gnc + 1 > 64) { overflow = 1; return }
573
+ a = gs + 1
574
+ for (k = 1; k <= gnc + 1; k++) {
575
+ e = (k <= gnc) ? GCP[k] : ge
576
+ tail++; QW[tail] = pre substr(gw, a, e - a) suf; QM[tail] = prem substr(gm, a, e - a) sufm; a = e + 1
577
+ }
578
+ }
579
+ }
580
+ # Parses the parameter expansion that starts at w[i] and fills PC[1..npc] with what it can be; returns the index of
581
+ # its last character. ${NAME:-w} ${NAME-w} ${NAME:=w} ${NAME=w} add w, ${NAME:+w} ${NAME+w} give w or nothing.
582
+ function variable_values(name, k, j, count, result, values, masks, value_parts) {
583
+ if (UNK[name] || ACTIVE[name] || value_depth >= 4) return "\001"
584
+ ACTIVE[name] = 1; value_depth++
585
+ result = "\003"; count = BVN[name]
586
+ delete values; delete masks
587
+ for (k = 1; k <= count; k++) { values[k] = BV[name, k]; masks[k] = BVM[name, k] }
588
+ for (k = 1; k <= count; k++) {
589
+ resolve(values[k], masks[k])
590
+ for (j = 1; j <= nalt; j++) result = result "\034" ALT[j]
591
+ delete value_parts
592
+ if (split(result, value_parts, "\034") > 64) { result = "\001"; break }
593
+ }
594
+ value_depth--; delete ACTIVE[name]
595
+ return result
596
+ }
597
+ function param(w, m, i, c, j, name, inner, op, base, rest, depth, bad, special, kind) {
598
+ delete PC; npc = 1; PC[1] = "$"
599
+ c = substr(w, i + 1, 1); name = ""; op = ""; rest = ""
600
+ if (c == "{") {
601
+ depth = 1
602
+ for (j = i + 2; j <= length(w); j++) {
603
+ c = substr(w, j, 1)
604
+ if (c == "{") depth++
605
+ else if (c == "}" && --depth == 0) break
606
+ }
607
+ if (depth != 0) { PC[1] = "\001"; return length(w) }
608
+ inner = substr(w, i + 2, j - i - 2); i = j
609
+ if (match(inner, /^[A-Za-z_][A-Za-z0-9_]*/)) {
610
+ name = substr(inner, 1, RLENGTH); rest = substr(inner, RLENGTH + 1)
611
+ if (rest != "") {
612
+ if (match(rest, /^:?[-=+]/)) { op = substr(rest, RLENGTH, 1); rest = substr(rest, RLENGTH + 1) } else bad = 1
613
+ }
614
+ } else if (inner ~ /^([0-9]+|[@*])$/) special = "\001"
615
+ else if (inner ~ /^[?$!#-]$/) special = "\003"
616
+ else bad = 1
617
+ if (rest ~ /[$`{}]/) bad = 1
618
+ } else if (c ~ /^[A-Za-z_]$/) {
619
+ kind = tolower(substr(m, i, 1))
620
+ for (j = i + 1; j <= length(w) && substr(w, j, 1) ~ /^[A-Za-z0-9_]$/ && substr(m, j, 1) == kind; j++) name = name substr(w, j, 1)
621
+ i = j - 1
622
+ } else if (c ~ /^[0-9@*#?$!-]$/) { special = (c ~ /^[1-9@*]$/) ? "\001" : "\003"; i++ }
623
+ else return i
624
+ if (name == "_") special = "\001"
625
+ if (bad) { PC[1] = "\001"; return i }
626
+ if (op == "=") bind_value(name, rest, "")
627
+ base = (special != "") ? special : variable_values(name)
628
+ delete PC; npc = split(base, PC, "\034")
629
+ if (op == "+") { npc = 2; PC[1] = rest; PC[2] = "" }
630
+ else if (op == "-" || op == "=") PC[++npc] = rest
631
+ return i
632
+ }
633
+ function cross( k, j, t) {
634
+ t = 0
635
+ if (ncur * npc > 64) { overflow = 1; return }
636
+ for (k = 1; k <= ncur; k++) for (j = 1; j <= npc; j++) NXT[++t] = CUR[k] PC[j]
637
+ delete CUR
638
+ for (k = 1; k <= t; k++) CUR[k] = NXT[k]
639
+ ncur = t; delete NXT
640
+ }
641
+ function bracket_end(w, i, j, marker, end) {
642
+ j = i + 1
643
+ if (substr(w, j, 1) ~ /[!^]/) j++
644
+ if (substr(w, j, 1) == "]") j++
645
+ for (; j <= length(w); j++) {
646
+ if (substr(w, j, 1) == "]") return j
647
+ marker = substr(w, j + 1, 1)
648
+ if (substr(w, j, 1) == "[" && marker ~ /[:.=]/) {
649
+ end = index(substr(w, j + 2), marker "]")
650
+ if (!end) return 0
651
+ j += end + 2
652
+ }
653
+ }
654
+ return 0
655
+ }
656
+ function expand_item(w, m, i, n, c, mk, lit, j, saved, count) {
657
+ n = length(w); ncur = 1; delete CUR; CUR[1] = ""; lit = ""
658
+ for (i = 1; i <= n; i++) {
659
+ c = substr(w, i, 1); mk = tolower(substr(m, i, 1))
660
+ if (mk == "c") lit = lit "\003"
661
+ else if (c == "$" && mk != "l") {
662
+ delete PC; npc = 1; PC[1] = lit; cross(); lit = ""
663
+ delete saved; count = ncur
664
+ for (j = 1; j <= count; j++) saved[j] = CUR[j]
665
+ i = param(w, m, i)
666
+ delete CUR; ncur = count
667
+ for (j = 1; j <= count; j++) CUR[j] = saved[j]
668
+ if (mk == "u") for (j = 1; j <= npc; j++) if (PC[j] ~ /[*?[ \t\n]/) PC[j] = "\001"
669
+ cross()
670
+ }
671
+ else if (mk == "u" && (c == "*" || glob_negation(w, i))) lit = lit "\004"
672
+ else if (mk == "u" && c == "?") lit = lit "\005"
673
+ else if (mk == "u" && c == "[" && (j = bracket_end(w, i)) > 0) { lit = lit "\006" substr(w, i + 1, j - i - 1) "\007"; i = j }
674
+ else if (mk == "u" && c == "{") lit = lit "\001"
675
+ else lit = lit c
676
+ }
677
+ delete PC; npc = 1; PC[1] = lit; cross()
678
+ }
679
+ function resolve(w, m, k, j, words, masks, count, resolved_values, nr, failed) {
680
+ overflow = 0; brace_all(w, m)
681
+ delete words; delete masks; delete resolved_values
682
+ count = nf; failed = overflow
683
+ for (k = 1; k <= count; k++) { words[k] = FW[k]; masks[k] = FM[k] }
684
+ for (k = 1; k <= count && !failed; k++) {
685
+ expand_item(words[k], masks[k])
686
+ if (overflow || nr + ncur > 64) failed = 1
687
+ else for (j = 1; j <= ncur; j++) resolved_values[++nr] = CUR[j]
688
+ }
689
+ delete ALT; nalt = nr
690
+ for (j = 1; j <= nr; j++) ALT[j] = resolved_values[j]
691
+ if (failed) { delete ALT; nalt = 1; ALT[1] = "\001" }
692
+ }
693
+ function has_sentinel(b) { return b ~ /[\001-\007]/ }
694
+ function only_runtime(b, t) { t = b; gsub("\003", "", t); return t == "" }
695
+ # An anchored regex for a name that can hold sentinels: \001 and \003 match any string, \002 one character.
696
+ function rxize(b, k, c, r, j, bracket) {
697
+ r = ""
698
+ for (k = 1; k <= length(b); k++) {
699
+ c = substr(b, k, 1)
700
+ if (c == "\001" || c == "\003") r = r ".*"
701
+ else if (c == "\004") r = r "[^/]*"
702
+ else if (c == "\002" || c == "\005") r = r "[^/]"
703
+ else if (c == "\006") {
704
+ j = index(substr(b, k + 1), "\007"); bracket = substr(b, k + 1, j - 1)
705
+ sub(/^!/, "^", bracket); r = r "[" bracket "]"; k += j
706
+ }
707
+ else if (index(".[]()*+?{}|^$\\", c)) r = r "\\" c
708
+ else r = r c
709
+ }
710
+ return "^" r "$"
711
+ }
712
+ # Globs use case-sensitive, per-segment matching with Bash default leading-dot rules. Runtime expansions
713
+ # are different: they can supply a leading dot without pathname expansion.
714
+ function pattern_match(pattern, candidate, pattern_parts, candidate_parts, np, nc, k) {
715
+ delete pattern_parts; delete candidate_parts
716
+ np = split(pattern, pattern_parts, "/"); nc = split(candidate, candidate_parts, "/")
717
+ if (np != nc) return 0
718
+ for (k = 1; k <= np; k++) {
719
+ if (substr(candidate_parts[k], 1, 1) == "." && substr(pattern_parts[k], 1, 1) ~ /[\004-\006]/) return 0
720
+ if (candidate_parts[k] !~ rxize(pattern_parts[k])) return 0
721
+ }
722
+ return 1
723
+ }
724
+ # Intersection of two wildcard segments, used for the complete protected extension suffixes rather than
725
+ # a handful of sample key names. States advance monotonically, including empty star transitions.
726
+ function pattern_units(a, U, k, n, j) {
727
+ delete U
728
+ for (k = 1; k <= length(a); k++) {
729
+ if (substr(a, k, 1) == "\006") {
730
+ j = index(substr(a, k + 1), "\007"); U[++n] = substr(a, k, j + 1); k += j
731
+ } else U[++n] = substr(a, k, 1)
732
+ }
733
+ return n
734
+ }
735
+ function non_dot_character(unit, k, rx) {
736
+ if (substr(unit, 1, 1) != "\006") return unit != "."
737
+ if (unit ~ /[^\001-\177]/) return 1
738
+ rx = rxize(unit)
739
+ for (k = 1; k < 128; k++) if (k != 46 && k != 47 && CH[k] ~ rx) return 1
740
+ return 0
741
+ }
742
+ function overlap(a, b, states, i, j, z, x, y, ax, by, na, nb, au, bu, hidden) {
743
+ delete states
744
+ na = pattern_units(a, au); nb = pattern_units(b, bu); states[0,0,0] = 1
745
+ hidden = (substr(a, 1, 1) ~ /[\004-\006]/)
746
+ for (i = 0; i <= na; i++) for (j = 0; j <= nb; j++) for (z = 0; z <= 1; z++) {
747
+ if (!states[i,j,z]) continue
748
+ x = au[i + 1]; y = bu[j + 1]
749
+ ax = (x ~ /^[\001\003\004]$/); by = (y == "\004")
750
+ if (ax) states[i+1,j,z] = 1
751
+ if (by) states[i,j+1,z] = 1
752
+ if (i == na || j == nb) continue
753
+ if (ax && by) states[i,j,1] = 1
754
+ else if (ax) {
755
+ if (!hidden || z || y != ".") states[i,j+1,1] = 1
756
+ } else if (by) {
757
+ if (!hidden || z || non_dot_character(x)) states[i+1,j,1] = 1
758
+ } else if ((!hidden || z || y != ".") && y ~ rxize(x)) states[i+1,j+1,1] = 1
759
+ }
760
+ return states[na,nb,1]
761
+ }
762
+ function path_probe(a, probe, path_parts, probe_parts, n, m, k, tail) {
763
+ delete path_parts; delete probe_parts
764
+ n = split(a, path_parts, "/"); m = split(probe, probe_parts, "/")
765
+ if (n < m) return 0
766
+ tail = path_parts[n-m+1]
767
+ for (k = n-m+2; k <= n; k++) tail = tail "/" path_parts[k]
768
+ return pattern_match(tail, probe)
769
+ }
770
+ # Literal words retain the full classifier. Glob words use canonical names and all protected extensions;
771
+ # substring-only token names outside that canonical set are not glob probes.
772
+ function alt_kind(a, b, d, kind, k, glob) {
773
+ # An unsupported expansion may supply slashes too, reaching a protected directory even with a fixed suffix.
774
+ if (index(a, "\001")) return "an unresolved file name that may name a protected file"
775
+ b = a; sub(/.*\//, "", b)
776
+ glob = (a ~ /[\004-\006]/)
777
+ if (!has_sentinel(a)) return sensitive_path(a)
778
+ if (!glob) {
779
+ kind = sensitive_path(a)
780
+ if (kind != "") return kind
781
+ if (only_runtime(b)) return ""
782
+ a = tolower(a); b = tolower(b)
783
+ }
784
+ d = a; sub(/[^\/]*$/, "", d)
785
+ if (has_sentinel(b)) {
786
+ for (k = 1; k <= nprobe; k++) if (pattern_match(b, PROBE[k])) {
787
+ kind = sensitive_path(d PROBE[k])
788
+ if (kind != "") return kind
789
+ if (PROBE[k] == "credentials" || PROBE[k] == ".pypirc") return "a credentials file"
790
+ }
791
+ for (k = 1; k <= nextension; k++) if (overlap(b, "\004." EXT[k])) return "a key or certificate file"
792
+ } else if (glob) {
793
+ for (k = 1; k <= nprobe; k++) if (b == PROBE[k]) {
794
+ kind = sensitive_path(d b)
795
+ if (kind != "") return kind
796
+ if (b == "credentials" || b == ".pypirc") return "a credentials file"
797
+ }
798
+ for (k = 1; k <= nextension; k++) if (b ~ ("\\." EXT[k] "$")) return "a key or certificate file"
799
+ }
800
+ for (k = 1; k <= nprobe2; k++) if (path_probe(a, PROBE2[k])) return sensitive_path(PROBE2[k])
801
+ return ""
802
+ }
803
+ # The kind of protected file operand k of A names; via_pattern says the answer came from a pattern or a variable.
804
+ function operand_kind(A, k, off, w, m, j, kind) {
805
+ w = A[k]; m = mask_of(A, k); via_pattern = 0
806
+ if (off > 0) { w = substr(w, off + 1); m = substr(m, off + 1) }
807
+ if (!expands(w, m)) return sensitive_path(w)
808
+ resolve(w, m); via_pattern = 1
809
+ for (j = 1; j <= nalt; j++) { kind = alt_kind(ALT[j]); if (kind != "") return kind }
810
+ return ""
811
+ }
812
+ function bind_value(name, w, m, key) {
813
+ key = qi SUBSEP name SUBSEP w SUBSEP m
814
+ if (key in BINDING) return
815
+ if (pass == 2) { report("a variable the guard cannot follow", "run the read on its own with literal paths"); return }
816
+ BINDING[key] = 1; bindings++
817
+ BV[name, ++BVN[name]] = w; BVM[name, BVN[name]] = m
818
+ }
819
+ function unknown_binding(name) {
820
+ UNK[name] = 1
821
+ bind_value(name, "\001", "")
822
+ }
823
+ function set_var(w, m, eq, name, append) {
824
+ eq = index(w, "="); name = substr(w, 1, eq - 1); append = sub(/\+$/, "", name); sub(/\[.*$/, "", name)
825
+ if (append) unknown_binding(name)
826
+ bind_value(name, substr(w, eq + 1), substr(m, eq + 1))
827
+ }
828
+ function collect_bindings(A, s, n, b, k, w, nameref) {
829
+ if (b == "for" || b == "select") {
830
+ if (A[s + 2] != "in") unknown_binding(A[s + 1])
831
+ else for (k = s + 3; k <= n; k++) bind_value(A[s + 1], A[k], mask_of(A, k))
832
+ }
833
+ if (b ~ /^(declare|typeset|local)$/) for (k = s + 1; k <= n; k++) if (A[k] ~ /^-[a-zA-Z]*n/) nameref = 1
834
+ for (k = s + 1; k <= n; k++) {
835
+ w = A[k]
836
+ if (b == "unset" && w !~ /^-/) bind_value(w, "", "")
837
+ if ((b ~ /^(read|mapfile|readarray)$/ || nameref) && w ~ /^[A-Za-z_][A-Za-z0-9_]*$/) unknown_binding(w)
838
+ if ((b == "getopts" && k == s + 2) || (b == "printf" && A[k - 1] == "-v") || (b == "wait" && A[k - 1] == "-p")) unknown_binding(w)
839
+ }
840
+ }
841
+ function protected_config(w) { return w ~ /^(GLOBIGNORE|BASHOPTS|BASH_ENV|ENV)(\+?=|$)/ }
842
+ function config_report() {
843
+ report("a protected shell configuration change cannot be checked with default glob matching", "run without changing shell glob options")
844
+ }
845
+ function allowed_option(option) { return option ~ /^(errexit|nounset|pipefail|xtrace|verbose|noglob|errtrace|functrace)$/ }
846
+ function shell_invocation(A, s, n, k, j, flags, c, script) {
847
+ for (k = s + 1; k <= n; k++) {
848
+ if (A[k] == "--" || A[k] !~ /^[-+]/) break
849
+ if (A[k] ~ /^--/) continue
850
+ flags = substr(A[k], 2); script = index(flags, "c")
851
+ for (j = 1; j <= length(flags); j++) {
852
+ c = substr(flags, j, 1)
853
+ if (c != "o" && c != "O") continue
854
+ if (j != length(flags) || expands(A[k + 1], mask_of(A, k + 1)) || !allowed_option(A[k + 1])) config_report()
855
+ k++; break
856
+ }
857
+ if (script) { enqueue(A[k + 1]); return }
858
+ }
859
+ if (nheredoc > 0) hd_shell = 1
860
+ }
861
+ function shell_config(A, s, n, b, k, option, j, flags, c) {
862
+ if (b ~ /^(setopt|unsetopt|emulate)$/) config_report()
863
+ if (b ~ /^(export|declare|typeset|local|readonly)$/)
864
+ for (k = s + 1; k <= n; k++) if (protected_config(A[k])) config_report()
865
+ if (b == "set") {
866
+ for (k = s + 1; k <= n; k++) if (expands(A[k], mask_of(A, k))) config_report()
867
+ for (k = s + 1; k <= n; k++) {
868
+ if (A[k] == "--" || A[k] !~ /^[-+]/) break
869
+ flags = substr(A[k], 2)
870
+ for (j = 1; j <= length(flags); j++) {
871
+ c = substr(flags, j, 1)
872
+ if (c == "o") {
873
+ option = (j < length(flags)) ? substr(flags, j + 1) : A[++k]
874
+ if (!allowed_option(option)) config_report()
875
+ break
876
+ }
877
+ if (c !~ /^[euxfvET]$/) config_report()
878
+ }
879
+ }
880
+ }
881
+ if (b != "shopt") return
882
+ for (k = s + 1; k <= n; k++) {
883
+ if (A[k] == "extglob" || expands(A[k], mask_of(A, k)) || A[k] ~ /^-[a-zA-Z]*[su]/) config_report()
884
+ }
885
+ }
886
+ function check_inputs(A, s, n, k, kind) {
887
+ for (k = s; k < n; k++) {
888
+ if (A[k] !~ /^[0-9]*<+[>&]?$/ || tolower(substr(mask_of(A, k), 1, 1)) != "u") continue
889
+ kind = operand_kind(A, k + 1, 0)
890
+ if (kind != "") report("an input redirection reads " kind, "name the file and the key you need; for an env template read the .env.example")
891
+ k++
892
+ }
893
+ }
894
+ function note_redirect(A, s) {
895
+ if (A[s] ~ /^[0-9]*<$/) { REDIRECT_TOKENS[++nrt] = s + 1; ROFF[nrt] = 0 }
896
+ else if (match(A[s], /^[0-9]*<[^<>&]/)) { REDIRECT_TOKENS[++nrt] = s; ROFF[nrt] = RLENGTH - 1 }
897
+ }
898
+ function generic_files(A, s, n, why, k, kind) {
899
+ for (k = s + 1; k <= n; k++) {
900
+ if (substr(A[k], 1, 1) == "-" && length(A[k]) > 1) continue
901
+ kind = operand_kind(A, k, 0)
902
+ if (kind != "") report(why " reads " kind " and prints credentials", "name the file and the key you need in your report; ask the user to confirm a value instead of printing it; list the directory with ls, then name the exact files")
903
+ }
904
+ }
905
+ # A command word the shell builds by expansion: run the normal analysis for every name it can be, and refuse the
906
+ # operands that name a protected file when it cannot be resolved to one.
907
+ function dyn_command(A, s, n, j, na, b, d, S, unresolved, rx) {
908
+ resolve(A[s], mask_of(A, s))
909
+ na = nalt; for (j = 1; j <= na; j++) S[j] = ALT[j]
910
+ unresolved = 0
911
+ for (j = 1; j <= na; j++) {
912
+ b = tolower(S[j]); sub(/.*\//, "", b)
913
+ if (!has_sentinel(b)) { A[s] = S[j]; VM[s] = ""; analyze(A, s, n); continue }
914
+ unresolved = 1
915
+ if (only_runtime(b)) continue
916
+ rx = rxize(b)
917
+ for (d = 1; d <= ndispatch; d++) if (DN[d] ~ rx) { A[s] = DN[d]; VM[s] = ""; analyze(A, s, n) }
918
+ }
919
+ if (unresolved) generic_files(A, s, n, "a command whose name is built from a pattern or variable")
920
+ }
921
+
256
922
  # ── tools ──
257
923
  function kube(A, s, n, verb, m, parts, k, r, rlist) {
258
924
  kparse(A, s + 1, n, "nlcsfkLR")
@@ -270,6 +936,7 @@ function kube(A, s, n, verb, m, parts, k, r, rlist) {
270
936
  # `get pods,cm` and `get pod web` name one resource type; `get svc/web secret/db` names one per argument.
271
937
  rlist = P[2]
272
938
  if (index(P[2], "/")) for (k = 3; k <= np; k++) if (index(P[k], "/")) rlist = rlist "," P[k]
939
+ delete parts
273
940
  m = split(tolower(rlist), parts, ",")
274
941
  for (k = 1; k <= m; k++) {
275
942
  r = parts[k]; sub(/\/.*/, "", r); sub(/\..*/, "", r)
@@ -383,8 +1050,9 @@ function reader(A, s, n, b, k, w, mode, havepat, need, afterdd, kind, valued,
383
1050
  continue
384
1051
  }
385
1052
  if (need) { need = 0; continue }
386
- kind = sensitive_path(w)
387
- if (kind != "") report(b " of " kind " prints credentials", "name the file and the key you need in your report; ask the user to confirm a value instead of printing it; for an env template read the .env.example")
1053
+ kind = operand_kind(A, k, 0)
1054
+ if (kind != "" && via_pattern) report(b " of a name that can match " kind " prints credentials", "list the directory with ls, then name the exact files; for an env template read the .env.example")
1055
+ else if (kind != "") report(b " of " kind " prints credentials", "name the file and the key you need in your report; ask the user to confirm a value instead of printing it; for an env template read the .env.example")
388
1056
  }
389
1057
  }
390
1058
 
@@ -397,13 +1065,30 @@ function drop_redirects(A, s, n, k, m, w) {
397
1065
  }
398
1066
  return m
399
1067
  }
400
- function analyze(A, s, n, w, b, k, names, p, config, get, show) {
1068
+ function transfer_files(A, s, n, b, k, last, options, kind, w, eq, off, ended) {
1069
+ for (k = s + 1; k <= n; k++) if (A[k] ~ /^-./) options = 1
1070
+ last = n
1071
+ if (b ~ /^(cp|mv|ln)$/ && !options && n == s + 2) last--
1072
+ for (k = s + 1; k <= last; k++) {
1073
+ w = A[k]; off = 0
1074
+ if (!ended && w == "--") { ended = 1; continue }
1075
+ if (!ended && w ~ /^-./) {
1076
+ eq = index(w, "=")
1077
+ if (w !~ /^--/ || !eq) continue
1078
+ off = eq
1079
+ }
1080
+ kind = operand_kind(A, k, off)
1081
+ if (kind != "") report(b " reads " kind, "name only non-credential source files")
1082
+ }
1083
+ }
1084
+ function analyze(A, s, n, w, b, k, names, p, config, get, show, first) {
1085
+ nrt = 0; delete REDIRECT_TOKENS; delete ROFF; first = s
401
1086
  while (s <= n) {
402
1087
  w = A[s]; b = base(w)
403
- if (is_assign(w)) { s++; continue }
404
- if (w ~ /^[0-9]*[<>]/) { s += (w ~ /^[0-9]*[<>]+&?-?$/) ? 2 : 1; continue }
1088
+ if (is_assign(w)) { if (protected_config(w)) config_report(); s++; continue }
1089
+ if (w ~ /^[0-9]*[<>]/) { note_redirect(A, s); s += (w ~ /^[0-9]*[<>]+&?-?$/) ? 2 : 1; continue }
405
1090
  if (b in KW) { s++; continue }
406
- if (b == "command" || b == "builtin") { s++; if (s <= n && (A[s] == "-v" || A[s] == "-V")) return; if (s <= n && A[s] == "-p") s++; continue }
1091
+ if (b == "command" || b == "builtin") { s++; if (s <= n && (A[s] == "-v" || A[s] == "-V")) return; if (s <= n && A[s] == "-p") s++; if (A[s] == "--") s++; continue }
407
1092
  if (b == "sudo" || b == "doas") { s = skipopts(A, s + 1, n, "ugChprtUD"); continue }
408
1093
  if (b == "xargs") { s = skipopts(A, s + 1, n, "IniPLdsEa"); continue }
409
1094
  if (b == "timeout") { s = skipopts(A, s + 1, n, "ks") + 1; continue }
@@ -414,7 +1099,7 @@ function analyze(A, s, n, w, b, k, names, p, config, get, show) {
414
1099
  s++
415
1100
  while (s <= n) {
416
1101
  w = A[s]
417
- if (is_assign(w)) s++
1102
+ if (is_assign(w)) { if (protected_config(w)) config_report(); s++ }
418
1103
  else if (w ~ /^[0-9]*[<>]/) s += (w ~ /^[0-9]*[<>]+&?-?$/) ? 2 : 1
419
1104
  else if (w == "-u" || w == "-C" || w == "-S" || w == "--unset" || w == "--chdir" || w == "--split-string") s += 2
420
1105
  else if (substr(w, 1, 1) == "-") s++
@@ -425,18 +1110,26 @@ function analyze(A, s, n, w, b, k, names, p, config, get, show) {
425
1110
  }
426
1111
  break
427
1112
  }
428
- if (s > n) return
1113
+ if (s > n) {
1114
+ for (k = first; k <= n; k++) if (is_assign(A[k])) set_var(A[k], mask_of(A, k))
1115
+ return
1116
+ }
1117
+ if (expands(A[s], mask_of(A, s))) return dyn_command(A, s, n)
429
1118
  b = base(A[s])
430
- if (b == "bash" || b == "sh" || b == "zsh" || b == "dash" || b == "ksh") {
431
- for (k = s + 1; k <= n; k++)
432
- if (A[k] ~ /^-[a-zA-Z]*c[a-zA-Z]*$/) { enqueue(A[k + 1]); return }
433
- if (nheredoc > 0) hd_shell = 1
1119
+ shell_config(A, s, n, b)
1120
+ collect_bindings(A, s, n, b)
1121
+ if (b == "for" || b == "select" || b == "unset") return
1122
+ if (b == "dd") {
1123
+ for (k = s + 1; k <= n; k++) if (A[k] ~ /^if=/ && (config = operand_kind(A, k, 3)) != "") report("dd reads " config, "name only a non-credential input file")
434
1124
  return
435
1125
  }
1126
+ if (b ~ /^(cp|mv|ln|rsync|scp|tar|zip)$/) { transfer_files(A, s, n, b); return }
1127
+ if (b ~ /^(export|declare|typeset|local|readonly)$/) for (k = s + 1; k <= n; k++) if (is_assign(A[k])) set_var(A[k], mask_of(A, k))
1128
+ if (b == "bash" || b == "sh" || b == "zsh" || b == "dash" || b == "ksh") { shell_invocation(A, s, n); return }
436
1129
  if (b == "eval") { p = ""; for (k = s + 1; k <= n; k++) p = p " " A[k]; enqueue(p); return }
437
1130
  if (b == "kubectl" || b == "oc") return kube(A, s, n)
438
1131
  if (b == "docker" || b == "podman") return dock(A, s, n)
439
- if (b == "docker-compose") { split("", T); T[1] = "docker"; T[2] = "compose"; for (k = s + 1; k <= n; k++) T[k - s + 2] = A[k]; return dock(T, 1, n - s + 2) }
1132
+ if (b == "docker-compose") { delete T; T[1] = "docker"; T[2] = "compose"; for (k = s + 1; k <= n; k++) T[k - s + 2] = A[k]; return dock(T, 1, n - s + 2) }
440
1133
  if (b == "gh") return gh(A, s, n)
441
1134
  if (b == "vault") return vault(A, s, n)
442
1135
  if (b == "aws") return aws(A, s, n)
@@ -481,24 +1174,57 @@ function analyze(A, s, n, w, b, k, names, p, config, get, show) {
481
1174
  if (p && names == 0) report(b " -p/-x with no variable name prints the whole environment, including credentials", "printenv with the one non-credential variable you need")
482
1175
  return
483
1176
  }
484
- if (b ~ /^(cat|tac|nl|less|more|head|tail|bat|batcat|strings|xxd|od|hexdump|cut|sort|uniq|base64|grep|egrep|fgrep|rg|ag|sed|awk|gawk|jq|yq)$/) reader(A, s, n)
1177
+ if (b ~ /^(cat|tac|nl|less|more|head|tail|bat|batcat|strings|xxd|od|hexdump|cut|sort|uniq|base64|wc|grep|egrep|fgrep|rg|ag|sed|awk|gawk|jq|yq)$/) {
1178
+ reader(A, s, n)
1179
+ for (k = 1; k <= nrt; k++) {
1180
+ if (REDIRECT_TOKENS[k] > n || operand_kind(A, REDIRECT_TOKENS[k], ROFF[k]) == "") continue
1181
+ report(b " of " operand_kind(A, REDIRECT_TOKENS[k], ROFF[k]) " through an input redirection prints credentials", "name the file and the key you need in your report; ask the user to confirm a value instead of printing it; for an env template read the .env.example")
1182
+ }
1183
+ }
485
1184
  }
486
1185
 
487
1186
  BEGIN {
488
1187
  SQ = "\047"
489
1188
  split("namespace context kubeconfig server cluster user as as-group selector field-selector container label-columns sort-by request-timeout filename kustomize template chunk-size token env env-file workdir host config project-name file profile detach-keys log-level method header field raw-field jq repo hostname input region query endpoint-url vault-name subscription resource-group name id version project secret account", L, " ")
490
1189
  for (i in L) LV["--" L[i]] = 1
491
- split("! { } if then else elif do while until", L, " ")
1190
+ delete L; split("! { } if then else elif do while until", L, " ")
492
1191
  for (i in L) KW[L[i]] = 1
493
- split("pods po pod deployments deployment deploy statefulsets statefulset sts daemonsets daemonset ds jobs job cronjobs cronjob cj configmaps configmap cm replicasets replicaset rs replicationcontrollers rc all", L, " ")
1192
+ delete L; split("pods po pod deployments deployment deploy statefulsets statefulset sts daemonsets daemonset ds jobs job cronjobs cronjob cj configmaps configmap cm replicasets replicaset rs replicationcontrollers rc all", L, " ")
494
1193
  for (i in L) SENS[L[i]] = 1
1194
+ # Decoding tables for $'...' strings, and the names a pattern is probed against.
1195
+ for (i = 1; i < 256; i++) { CH[i] = sprintf("%c", i); ORD[CH[i]] = i }
1196
+ delete L; split("0 1 2 3 4 5 6 7 8 9 a b c d e f", L, " ")
1197
+ for (i = 1; i <= 16; i++) HEX[L[i]] = i - 1
1198
+ delete L; split("a b e E f n r t v", L, " "); split("7 8 27 27 12 10 13 9 11", L2, " ")
1199
+ for (i = 1; i <= 9; i++) ESC[L[i]] = L2[i] + 0
1200
+ ESC["\\"] = 92; ESC["\047"] = 39; ESC["\""] = 34; ESC["?"] = 63
1201
+ nprobe = split(".env .env.local .env.production .envrc id_rsa id_ed25519 id_ecdsa id_dsa credentials token token.json tokens.json github_token .netrc .npmrc .pypirc .pgpass .git-credentials kubeconfig", PROBE, " ")
1202
+ nprobe2 = split(".kube/config .aws/credentials .docker/config.json /proc/1/environ /run/secrets/token /var/run/secrets/token", PROBE2, " ")
1203
+ nextension = split("pem key p12 pfx jks keystore kdbx kubeconfig env", EXT, " ")
1204
+ ndispatch = split("cat tac nl less more head tail bat batcat strings xxd od hexdump cut sort uniq base64 wc dd cp mv ln rsync scp tar zip shopt set setopt unsetopt emulate grep egrep fgrep rg ag sed awk gawk jq yq kubectl oc docker podman docker-compose gh vault aws az gcloud pulumi cratis printenv export declare typeset env bash sh zsh dash ksh eval", DN, " ")
1205
+ nstem = split(".env .pem .p12 .pfx id_rsa id_ed25519 id_ecdsa id_dsa .netrc .npmrc .pgpass .pypirc .git-credentials .kube/ kubeconfig credentials .docker/ /environ run/secrets", STEM, " ")
495
1206
  CMD = ENVIRON["GS_COMMAND"]
496
- enqueue(CMD)
497
- while (qi < queued) { qi++; tokenize(queue[qi]) }
1207
+ for (pass = 1; pass <= 2; pass++) {
1208
+ delete queue; queued = 0; qi = 0; delete seen; reports = ""
1209
+ nheredoc = 0; hd_shell = 0; commands = 0; complex = 0; simple_ok = 1; TAINT = ""
1210
+ enqueue(CMD)
1211
+ while (qi < queued) { qi++; tokenize(queue[qi]) }
1212
+ if (pass == 1 && bindings > 0) continue
1213
+ if (TAINT != "" && (complex || queued != 1 || commands != 1 || !simple_ok)) {
1214
+ other_reports = reports; reports = ""
1215
+ report("the command names a protected file (" TAINT ") and is not a single literal read", "run the read on its own with literal paths, e.g. cat .env.example or cp .env.example .env; split compound commands into separate calls; do not build the name with variables, globs, loops, pipes, redirections or nested shells; for a commit message or PR body that mentions the name, write the text to a file with the file tool and pass the file")
1216
+ reports = reports other_reports
1217
+ }
1218
+ printf "%s", reports
1219
+ break
1220
+ }
498
1221
  }
499
1222
  AWK
500
1223
 
501
- findings="$(GS_COMMAND="$command_text" LC_ALL=C awk "$awk_program" </dev/null)"
1224
+ # Only literal rg needs the invocation directory to distinguish file and directory operands.
1225
+ command_cwd="$PWD"
1226
+ case "$probe" in *rg*) command_cwd="$(jq -r '.cwd // empty' <<<"$input")" || parser_failed; command_cwd="${command_cwd:-$PWD}" ;; esac
1227
+ findings="$(GS_COMMAND="$command_text" GS_CWD="$command_cwd" LC_ALL=C awk "$awk_program" </dev/null)" || parser_failed
502
1228
  [ -n "$findings" ] || exit 0
503
1229
 
504
1230
  {
@@ -521,5 +1247,8 @@ Do not retry this, rephrase it, or work around the guard (another wrapper, a scr
521
1247
  alias). A person who authorized the read sets CRATIS_HOOKS_ALLOW_SECRET_READS=1 in the environment the agent
522
1248
  harness was started from; setting it inside the command has no effect.
523
1249
  EOF
1250
+ case "$findings" in
1251
+ *"the command names a protected file ("*) printf '%s\n' 'Running the read on its own with literal paths, as suggested above, is the intended retry.' ;;
1252
+ esac
524
1253
  } >&2
525
1254
  exit 2