@codyswann/lisa 4.90.0 → 4.90.1

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.
Files changed (139) hide show
  1. package/all/copy-overwrite/scripts/lisa-enforcement-fallback.sh +2 -2
  2. package/all/copy-overwrite/scripts/lisa-enforcement-freshness.mjs +1 -2
  3. package/all/copy-overwrite/scripts/lisa-hooks/parity-safety-net.sh +9 -3634
  4. package/all/copy-overwrite/scripts/lisa-postinstall.mjs +16 -5
  5. package/dist/cli/apply.d.ts.map +1 -1
  6. package/dist/cli/apply.js +25 -4
  7. package/dist/cli/apply.js.map +1 -1
  8. package/dist/cli/lisa-test-run-process-group.d.ts.map +1 -1
  9. package/dist/cli/lisa-test-run-process-group.js +19 -2
  10. package/dist/cli/lisa-test-run-process-group.js.map +1 -1
  11. package/dist/core/bootstrap-environment.d.ts +10 -1
  12. package/dist/core/bootstrap-environment.d.ts.map +1 -1
  13. package/dist/core/bootstrap-environment.js +14 -5
  14. package/dist/core/bootstrap-environment.js.map +1 -1
  15. package/dist/core/enforcement-coverage.d.ts +2 -2
  16. package/dist/core/enforcement-coverage.d.ts.map +1 -1
  17. package/dist/core/enforcement-coverage.js +2 -3
  18. package/dist/core/enforcement-coverage.js.map +1 -1
  19. package/dist/core/lisa-owned-hash-ledger.d.ts.map +1 -1
  20. package/dist/core/lisa-owned-hash-ledger.js +10 -0
  21. package/dist/core/lisa-owned-hash-ledger.js.map +1 -1
  22. package/dist/core/native-safety-net-retirement.d.ts +13 -0
  23. package/dist/core/native-safety-net-retirement.d.ts.map +1 -0
  24. package/dist/core/native-safety-net-retirement.js +23 -0
  25. package/dist/core/native-safety-net-retirement.js.map +1 -0
  26. package/dist/core/nightly-e2e-guard-behavior-certificate.js +2 -2
  27. package/dist/core/upstream-evidence-manifest.d.ts.map +1 -1
  28. package/dist/core/upstream-evidence-manifest.js +39 -53
  29. package/dist/core/upstream-evidence-manifest.js.map +1 -1
  30. package/dist/migrations/index.d.ts +1 -0
  31. package/dist/migrations/index.d.ts.map +1 -1
  32. package/dist/migrations/index.js +3 -0
  33. package/dist/migrations/index.js.map +1 -1
  34. package/dist/migrations/retire-native-safety-net.d.ts +18 -0
  35. package/dist/migrations/retire-native-safety-net.d.ts.map +1 -0
  36. package/dist/migrations/retire-native-safety-net.js +36 -0
  37. package/dist/migrations/retire-native-safety-net.js.map +1 -0
  38. package/dist/opencode/plugin-catalog.d.ts.map +1 -1
  39. package/dist/opencode/plugin-catalog.js +1 -0
  40. package/dist/opencode/plugin-catalog.js.map +1 -1
  41. package/dist/opencode/plugin-templates/lisa-parity-safety-net.ts +2 -48
  42. package/dist/opencode/plugin-templates/parity-safety-net.sh +9 -3634
  43. package/package.json +8 -6
  44. package/plugins/lisa/.claude-plugin/plugin.json +1 -1
  45. package/plugins/lisa/.codex-plugin/plugin.json +1 -1
  46. package/plugins/lisa/hooks/parity-safety-net.agy.sh +5 -49
  47. package/plugins/lisa/hooks/parity-safety-net.sh +9 -3634
  48. package/plugins/lisa-agy/hooks/parity-safety-net.agy.sh +5 -49
  49. package/plugins/lisa-agy/hooks/parity-safety-net.sh +9 -3634
  50. package/plugins/lisa-agy/plugin.json +1 -1
  51. package/plugins/lisa-cdk/.claude-plugin/plugin.json +1 -1
  52. package/plugins/lisa-cdk/.codex-plugin/plugin.json +1 -1
  53. package/plugins/lisa-cdk-agy/plugin.json +1 -1
  54. package/plugins/lisa-cdk-copilot/.claude-plugin/plugin.json +1 -1
  55. package/plugins/lisa-cdk-cursor/.claude-plugin/plugin.json +1 -1
  56. package/plugins/lisa-cdk-devin/.claude-plugin/plugin.json +1 -1
  57. package/plugins/lisa-cdk-devin/.devin-plugin/plugin.json +1 -1
  58. package/plugins/lisa-copilot/.claude-plugin/plugin.json +1 -1
  59. package/plugins/lisa-copilot/hooks/parity-safety-net.sh +9 -3634
  60. package/plugins/lisa-cursor/.claude-plugin/plugin.json +1 -1
  61. package/plugins/lisa-cursor/hooks/parity-safety-net.sh +9 -3634
  62. package/plugins/lisa-devin/.claude-plugin/plugin.json +1 -1
  63. package/plugins/lisa-devin/.devin-plugin/plugin.json +1 -1
  64. package/plugins/lisa-devin/hooks/parity-safety-net.sh +9 -3634
  65. package/plugins/lisa-expo/.claude-plugin/plugin.json +1 -1
  66. package/plugins/lisa-expo/.codex-plugin/plugin.json +1 -1
  67. package/plugins/lisa-expo-agy/plugin.json +1 -1
  68. package/plugins/lisa-expo-copilot/.claude-plugin/plugin.json +1 -1
  69. package/plugins/lisa-expo-cursor/.claude-plugin/plugin.json +1 -1
  70. package/plugins/lisa-expo-devin/.claude-plugin/plugin.json +1 -1
  71. package/plugins/lisa-expo-devin/.devin-plugin/plugin.json +1 -1
  72. package/plugins/lisa-harper-fabric/.claude-plugin/plugin.json +1 -1
  73. package/plugins/lisa-harper-fabric/.codex-plugin/plugin.json +1 -1
  74. package/plugins/lisa-harper-fabric-agy/plugin.json +1 -1
  75. package/plugins/lisa-harper-fabric-copilot/.claude-plugin/plugin.json +1 -1
  76. package/plugins/lisa-harper-fabric-cursor/.claude-plugin/plugin.json +1 -1
  77. package/plugins/lisa-harper-fabric-devin/.claude-plugin/plugin.json +1 -1
  78. package/plugins/lisa-harper-fabric-devin/.devin-plugin/plugin.json +1 -1
  79. package/plugins/lisa-nestjs/.claude-plugin/plugin.json +1 -1
  80. package/plugins/lisa-nestjs/.codex-plugin/plugin.json +1 -1
  81. package/plugins/lisa-nestjs-agy/plugin.json +1 -1
  82. package/plugins/lisa-nestjs-copilot/.claude-plugin/plugin.json +1 -1
  83. package/plugins/lisa-nestjs-cursor/.claude-plugin/plugin.json +1 -1
  84. package/plugins/lisa-nestjs-devin/.claude-plugin/plugin.json +1 -1
  85. package/plugins/lisa-nestjs-devin/.devin-plugin/plugin.json +1 -1
  86. package/plugins/lisa-openclaw/.claude-plugin/plugin.json +1 -1
  87. package/plugins/lisa-openclaw/.codex-plugin/plugin.json +1 -1
  88. package/plugins/lisa-openclaw-agy/plugin.json +1 -1
  89. package/plugins/lisa-openclaw-copilot/.claude-plugin/plugin.json +1 -1
  90. package/plugins/lisa-openclaw-cursor/.claude-plugin/plugin.json +1 -1
  91. package/plugins/lisa-openclaw-devin/.claude-plugin/plugin.json +1 -1
  92. package/plugins/lisa-openclaw-devin/.devin-plugin/plugin.json +1 -1
  93. package/plugins/lisa-phaser/.claude-plugin/plugin.json +1 -1
  94. package/plugins/lisa-phaser/.codex-plugin/plugin.json +1 -1
  95. package/plugins/lisa-phaser-agy/plugin.json +1 -1
  96. package/plugins/lisa-phaser-copilot/.claude-plugin/plugin.json +1 -1
  97. package/plugins/lisa-phaser-cursor/.claude-plugin/plugin.json +1 -1
  98. package/plugins/lisa-phaser-devin/.claude-plugin/plugin.json +1 -1
  99. package/plugins/lisa-phaser-devin/.devin-plugin/plugin.json +1 -1
  100. package/plugins/lisa-rails/.claude-plugin/plugin.json +1 -1
  101. package/plugins/lisa-rails/.codex-plugin/plugin.json +1 -1
  102. package/plugins/lisa-rails-agy/plugin.json +1 -1
  103. package/plugins/lisa-rails-copilot/.claude-plugin/plugin.json +1 -1
  104. package/plugins/lisa-rails-cursor/.claude-plugin/plugin.json +1 -1
  105. package/plugins/lisa-rails-devin/.claude-plugin/plugin.json +1 -1
  106. package/plugins/lisa-rails-devin/.devin-plugin/plugin.json +1 -1
  107. package/plugins/lisa-typescript/.claude-plugin/plugin.json +1 -1
  108. package/plugins/lisa-typescript/.codex-plugin/plugin.json +1 -1
  109. package/plugins/lisa-typescript-agy/plugin.json +1 -1
  110. package/plugins/lisa-typescript-copilot/.claude-plugin/plugin.json +1 -1
  111. package/plugins/lisa-typescript-cursor/.claude-plugin/plugin.json +1 -1
  112. package/plugins/lisa-typescript-devin/.claude-plugin/plugin.json +1 -1
  113. package/plugins/lisa-typescript-devin/.devin-plugin/plugin.json +1 -1
  114. package/plugins/lisa-wiki/.claude-plugin/plugin.json +1 -1
  115. package/plugins/lisa-wiki/.codex-plugin/plugin.json +1 -1
  116. package/plugins/lisa-wiki-agy/plugin.json +1 -1
  117. package/plugins/lisa-wiki-copilot/.claude-plugin/plugin.json +1 -1
  118. package/plugins/lisa-wiki-cursor/.claude-plugin/plugin.json +1 -1
  119. package/plugins/lisa-wiki-devin/.claude-plugin/plugin.json +1 -1
  120. package/plugins/lisa-wiki-devin/.devin-plugin/plugin.json +1 -1
  121. package/plugins/src/base/hooks/parity-safety-net.agy.sh +5 -49
  122. package/plugins/src/base/hooks/parity-safety-net.sh +9 -3634
  123. package/scripts/build-plugins.sh +3 -0
  124. package/scripts/check-generated-artifact-merge-coverage.mjs +7 -0
  125. package/scripts/fixtures/native-safety-net-retirement/Dockerfile +5 -0
  126. package/scripts/fixtures/native-safety-net-retirement/invoke-opencode.mjs +13 -0
  127. package/scripts/fixtures/native-safety-net-retirement/isolated-linker.mjs +101 -0
  128. package/scripts/fixtures/native-safety-net-retirement/journey.mjs +381 -0
  129. package/scripts/fixtures/native-safety-net-retirement/probes.mjs +208 -0
  130. package/scripts/fixtures/native-safety-net-retirement/reduced-core.mjs +93 -0
  131. package/scripts/generate-lisa-owned-hash-ledger.mjs +1 -1
  132. package/scripts/generate-retired-safety-net-manifest.mjs +56 -0
  133. package/scripts/install-claude-plugins.sh +9 -5
  134. package/scripts/lib/retired-safety-net-manifest.json +150 -0
  135. package/scripts/lisa-enforcement-fallback.sh +2 -2
  136. package/scripts/lisa-enforcement-freshness.mjs +1 -2
  137. package/scripts/remedy-conformance.mjs +5 -1
  138. package/scripts/retire-native-safety-net.mjs +237 -0
  139. package/scripts/verify-native-safety-net-retirement.mjs +287 -0
@@ -1,3638 +1,13 @@
1
1
  #!/usr/bin/env bash
2
- # PreToolUse hook for Bash: a safety net that blocks destructive shell commands
3
- # before they run. Lisa-native reimplementation of the upstream
4
- # `safety-net@cc-marketplace` plugin's PreToolUse Bash-guard (parity work,
5
- # issues #1059 and #1960). It does NOT port upstream code — it re-expresses the
6
- # behavior in Lisa's hook conventions, modeled on block-no-verify.sh.
7
- #
8
- # It reads the hook stdin JSON, inspects the proposed Bash command, and EXITS
9
- # NON-ZERO (2) to BLOCK when a known-destructive pattern matches:
10
- # - `rm -rf` of a root / home / wildcard path (quote-aware boundaries, so
11
- # `bash -c "rm -rf /"` and interpreter one-liners are caught too; the rm
12
- # guards also match path-prefixed invocations like `/bin/rm` and `./rm`)
13
- # - `rm -rf` of the cwd (`.`), a `..`-traversal path, a `~/`-anchored path,
14
- # an absolute path outside the project (with a /tmp, /var/tmp, $TMPDIR
15
- # allowance, each also matched by its symlink-resolved spelling so /tmp and
16
- # /private/tmp are ONE location), a `$VAR` target that neither is $TMPDIR
17
- # nor resolves through an unambiguous in-command assignment, or ANY
18
- # recursive forced delete while cwd is $HOME
19
- # - force-pushing a protected branch (main/master/production/prod/release) —
20
- # feature-branch force-push stays allowed (sanctioned rebase workflow;
21
- # deliberate divergence from upstream's any-branch block). Every git guard
22
- # sees through leading git GLOBAL options (`-C <path>`, `-c <k>=<v>`,
23
- # `--git-dir[=…]`, `--no-pager`, …), so `git -C /path <destructive>` cannot
24
- # dodge the subcommand anchor
25
- # - `git reset --hard` / `--merge` while the working tree is dirty. Deliberate
26
- # divergence: upstream blocks unconditionally; Lisa allows clean-tree resets.
27
- # Residual risk (documented, accepted): the dirty check runs in the hook's
28
- # cwd at hook time, so a `cd elsewhere && git reset --hard` evades it.
29
- # - `git read-tree` with an update flag AND `--reset` while the working tree
30
- # is dirty (issue #3978): the plumbing spelling of the same discard, on the
31
- # same condition, printing the same remedy. Index-only `read-tree`, and
32
- # `read-tree -m -u` without `--reset` (which git itself refuses rather than
33
- # clobber a modified file), stay allowed. Lisa-only guard.
34
- # - `git rebase --abort`/`--quit` while the in-progress rebase holds
35
- # human-made conflict resolutions (AUTO_MERGE discriminator; issue #1956).
36
- # Clean or untouched rebase state stays abortable; the apply backend and a
37
- # missing AUTO_MERGE ref fail closed. Deliberate divergence: upstream
38
- # blocks `rebase --abort` unconditionally, which strands agents mid-rebase.
39
- # - `git checkout` discards (`--`, `-f/--force`, `--pathspec-from-file`,
40
- # bare `.` — the bare-`.` block exceeds upstream)
41
- # - `git switch --discard-changes` / `-f/--force`
42
- # - `git restore` touching the worktree (allowed only with `--staged` and
43
- # without `--worktree`)
44
- # - `git stash drop` / `git stash clear`
45
- # - `git clean` with force and no dry-run (`-n`/`--dry-run` anywhere wins)
46
- # - `git branch -D` (or `-d` + `-f` in any spelling)
47
- # - `git tag -d`, `git reflog delete`, `git worktree remove --force`
48
- # - `find ... -delete`, `find ... -exec rm -rf`, `xargs ... rm -rf`
49
- # - disk destroyers: `dd of=/dev/...`, `mkfs ... /dev/...`, `shred`
50
- # - dropping or truncating a database/schema/table (Lisa-only guard)
51
- # Otherwise it exits 0 and the command proceeds. Malformed hook input fails
52
- # CLOSED: any parse error exits 2 (a non-2 exit would be a non-blocking hook
53
- # error in Claude Code, silently failing open).
54
- #
55
- # Narrowed false-positive class (issue #3106): the rm TARGET WALK is now scoped
56
- # to the quoting region that contains the rm, so a recursive delete quoted as
57
- # PROSE no longer turns every later token on the line into a deletion target. A
58
- # variable in an unrelated argument — a `gh issue create --body-file "$G/x"`, a
59
- # `git commit -F "$MSG"` — is no longer read as the thing being deleted. An rm
60
- # outside quotes, or first inside its quoted run (`bash -c "rm -rf /"`,
61
- # `echo "$(rm -rf /)"`), still hands the whole statement to the walk. See
62
- # rm_scan_scope below for the rule and its accepted residual.
63
- #
64
- # Known accepted false-positive class: this is a text scan, not a shell engine,
65
- # so display commands quoting a destructive string (`echo "docs about rm -rf /"`)
66
- # can match — including one whose target sits in the SAME quoted run as the
67
- # prose, which the #3106 scoping deliberately does not reach. Upstream exempts
68
- # those through an engine-only DISPLAY_COMMANDS list that a grep hook cannot
69
- # replicate. WHAT TO DO WHEN YOU HIT IT (issue #3191): do not reword the prose.
70
- # When the destructive text is a commit message, an issue body or a results
71
- # table, the string IS the deliverable and there is no narrower spelling that
72
- # still says what it must say. Write the text to a file with the Write tool and
73
- # pass it BY PATH — `gh issue comment --body-file <file>`, `git commit -F
74
- # <file>` — because these guards scan the COMMAND and never the file. block()
75
- # prints this at the wall so the operator is told rather than left to find it.
76
- # The same text-scan limit means the rm guard treats
77
- # a substitution-wrapped catastrophic delete as verdict-neutral (issue #1982): an
78
- # executable `echo "$(rm -rf /)"` is blocked, but so are inert twins the shell
79
- # would never expand — a single-quoted `echo '$(rm -rf /)'` or an escaped
80
- # `echo "\$(rm -rf /)"` — because the scan has no quote-context awareness. That
81
- # over-block stays inside this accepted class. Workaround: the write-to-a-file
82
- # and pass-by-path form above, or quote-break the string,
83
- # or use the gh-writer heredoc form, whose payload is stripped before the guards
84
- # run — spelled with a QUOTE-PAIR delimiter (`<<'EOF'`). That exact spelling is
85
- # what the SAFE path recognises; `<<"EOF"` and `<<\EOF` do not reach it, and
86
- # since #1993 a `gh … <<\EOF` writer fails closed instead (see parse_marker).
87
- #
88
- # Known accepted BYPASS class (the symmetric error direction, issue #1993): the
89
- # heredoc classifier in parity-safety-net-heredoc.py re-implements bash's
90
- # here-doc lexing in Python, and any divergence from real bash is a shape it
91
- # mis-classifies. Five rounds on #1958 and three more on #1993 (R5a swallowed
92
- # terminator, R5b body-apostrophe quote-state poisoning, R5c backslash-quoted
93
- # delimiter) established that enumerating those divergences is an open-ended
94
- # arms race, so the class is CLOSED as accepted rather than chased further. This
95
- # is survivable because of where a mis-classification lands: ONLY the narrow
96
- # gh-writer SAFE path strips payload text, and every other classifier exit hands
97
- # the RAW command to the guards below. A missed here-doc therefore degrades to
98
- # the content guards; it does not bypass them. Since #1982 taught those guards to
99
- # see through substitution wrappers, every destructive class this net exists to
100
- # stop is blocked on the raw text regardless of how the here-doc was read. The
101
- # net catches ACCIDENTAL catastrophic commands; it is not a wall against an
102
- # adversary who knows bash's lexer, and it was never the only thing standing
103
- # between an agent and arbitrary execution.
104
- #
105
- # Operators extend the built-in rules with a project-local rule file — one
106
- # extended-regex (ERE) per line, blank lines and `#` comments ignored — managed
107
- # by the parity-safety-net-rules skill. Default location (overridable via
108
- # SAFETY_NET_RULES_FILE):
109
- # ${CLAUDE_PROJECT_DIR:-$PWD}/.claude/safety-net-rules.txt
110
- set -euo pipefail
111
-
112
- # Fail CLOSED on any unexpected error (malformed JSON, missing jq, …): exit 2 so
113
- # the tool call is denied instead of surfacing a non-blocking hook warning.
114
- # Deliberately NOT `set -E`: errtrace would propagate this trap into command
115
- # substitutions (e.g. the heredoc parser call, whose non-zero exit codes are
116
- # meaningful protocol) and rewrite their status to 2 before it can be read.
117
- trap 'printf "%s\n" "Blocked by safety-net: hook failed while parsing its input; denying fail-closed." >&2; exit 2' ERR
118
-
119
- input="$(cat)"
120
-
121
- # Evaluate once per tool call when this guard is registered on both channels.
122
- #
123
- # Lisa reaches an agent through the repository dispatcher AND the plugin
124
- # manifest, and where both are live the harness runs this guard twice for one
125
- # tool call. `guard-dedupe.bash` short-circuits the second run ONLY when a
126
- # byte-identical copy already ALLOWED this exact payload on this exact tool
127
- # call; a differing vintage, a refusal, and a host with one channel all
128
- # evaluate exactly as before. Nothing is de-registered by it
129
- # (CodySwannGT/lisa#3814).
130
- #
131
- # Absent library means no dedupe, which is the pre-existing behaviour, so an
132
- # older channel copy that predates it is unaffected.
133
- lisa_guard_hook_dir="${BASH_SOURCE[0]%/*}"
134
- lisa_guard_dedupe_lib="$lisa_guard_hook_dir/guard-dedupe.bash"
135
- if [ -r "$lisa_guard_dedupe_lib" ]; then
136
- # shellcheck source=guard-dedupe.bash
137
- . "$lisa_guard_dedupe_lib"
138
- trap 'lisa_guard_dedupe_record $?' EXIT
139
- lisa_guard_dedupe parity-safety-net "$input" \
140
- "$lisa_guard_hook_dir/parity-safety-net-heredoc.py"
141
- fi
142
-
143
- tool_name="$(printf '%s' "$input" | jq -r '.tool_name // empty')"
144
- if [ "$tool_name" != "Bash" ]; then
145
- exit 0
146
- fi
147
-
148
- command_str="$(printf '%s' "$input" | jq -r '.tool_input.command // empty')"
149
- if [ -z "$command_str" ]; then
150
- exit 0
151
- fi
152
-
153
- # Guidance printed under an ordinary destructive-guard refusal.
154
- #
155
- # It teaches the remedy at the wall, the way block_heredoc() does (gardener
156
- # #1789, extended by issue #3191). It used to end in "narrow the command so it
157
- # no longer matches the guard", which is advice the accepted prose class CANNOT
158
- # follow: when the destructive text is a commit message, an issue body or a
159
- # results table, the string IS the deliverable and there is no narrower spelling
160
- # that still says what it must say. An operator acts on a printed remedy, so a
161
- # remedy that cannot be performed is worse than none — it spends the detour and
162
- # teaches that the refusal was a formality. The remedy that does work is the
163
- # sibling heredoc one, one surface over: write the text with the Write tool,
164
- # then pass it BY PATH. The guards scan the COMMAND and never the file, so the
165
- # path form carries the text through intact.
166
- #
167
- # Both branches are printed on every ordinary refusal, deliberately: this guard
168
- # is a text scan and CANNOT tell which one applies, so naming both and letting
169
- # the reader pick is the only honest shape. Deciding for them is what the
170
- # engine-only DISPLAY_COMMANDS list does, and the header explains why a grep
171
- # hook cannot have one.
172
- DESTRUCTIVE_GUIDANCE="$(
173
- cat <<'EOF'
174
- This command matched a destructive-operation guard. The guard is a text scan,
175
- not a shell engine, so it cannot tell a destructive command you are RUNNING
176
- from the same text quoted as CONTENT you are writing. Take the branch that
177
- describes yours:
178
-
179
- - The destructive text is only QUOTED CONTENT — a commit message, an issue or
180
- PR body, a report, a results table, a note. Do not try to reword it; the
181
- string is the deliverable and no narrower spelling still says what it must.
182
- Write the text to a file with the Write tool and pass it BY PATH instead:
183
- `gh issue comment --body-file <file>`, `gh pr create --body-file <file>`,
184
- `git commit -F <file>`, or read the file back with the Read tool. This guard
185
- scans the command, never the file, so the path form goes through intact.
186
-
187
- - You genuinely intend to run the destructive operation. Ask the user to
188
- confirm, then run it manually outside the agent.
189
- EOF
190
- )"
191
-
192
- # How to preserve uncommitted work before an operation that would discard it.
193
- #
194
- # This is appended to the reasons that refuse a discarding operation, and its
195
- # whole point is what it does NOT say (issue #3722). The obvious advice is
196
- # "stash it first", and on a single-checkout repository that is fine. Here it
197
- # is the most dangerous thing an agent can be told: the stash is ONE STACK PER
198
- # CLONE, shared by every worktree, so with concurrent agents a sibling's push
199
- # can shift your entry and a sibling's pop can consume it. `lint-staged` pushes
200
- # one on every commit too, so agent and tooling entries interleave.
201
- #
202
- # A remedy fires at the exact moment an agent is holding the work most worth
203
- # protecting, and a guard's own output reads as authoritative — so pointing it
204
- # at shared mutable state there is worse than the refusal it accompanies.
205
- #
206
- # The patch file is per-worktree: `mktemp` names it, so nothing has to invent a
207
- # filename, and it lives in this agent's own TMPDIR where no sibling can reach
208
- # it. Untracked files are unaffected by both refused operations, so `git diff`
209
- # captures everything at risk. `HEAD` includes staged and unstaged changes, and
210
- # `--binary` keeps binary edits recoverable rather than emitting a text-only
211
- # placeholder that cannot be applied.
212
- #
213
- # Three corrections from issue #3696, each found by EXECUTING the text below
214
- # rather than reading it:
215
- #
216
- # 1. It preserved but never RECOVERED. The text taught how to save the work and
217
- # how to restore it later, and stopped there — so an agent that followed it
218
- # exactly and successfully was returned to the identical refusal, because the
219
- # tree was still dirty. A remedy that does not clear the wall it is printed
220
- # at is a detour, and #3722 shipped only half the path. The discard branch
221
- # below is the other half, and every command in it is one THIS GUARD ALREADY
222
- # PERMITS: mixed `git reset`, `git diff`, and `git apply` are matched by no
223
- # guard in this file. Nothing was loosened to make room for it — a blind
224
- # `git reset --hard` on a dirty tree is still refused, unconditionally.
225
- #
226
- # That the operator must first WRITE DOWN what they are discarding is the
227
- # feature, not a cost. It is a better acknowledgement than a marker the guard
228
- # could look for, because a marker agents can type is a marker agents learn
229
- # to type reflexively; this one cannot be satisfied without producing the
230
- # artifact that makes the discard reversible.
231
- #
232
- # 2. It did not run as printed. `[-- <path>]` is conventional notation for an
233
- # optional argument, but bash expands `[...]` as a glob, so pasting the line
234
- # verbatim failed with `bash: path: No such file or directory` and wrote no
235
- # patch at all. Guard remedies are unreviewed prose that agents execute
236
- # literally, so the optional part is now prose and every line is runnable.
237
- #
238
- # 3. `mktemp` was silently a no-op. BSD/macOS mktemp substitutes only TRAILING
239
- # `X`s, so the `.patch` suffix meant the template came back as the literal
240
- # string `lisa-preserve-XXXXXX.patch` — one FIXED filename, where successive
241
- # preserves overwrite each other, in the exact place the comment above claims
242
- # uniqueness. The suffix is gone rather than spelled portably: GNU mktemp
243
- # offers `--suffix` and BSD does not, and a patch file does not need an
244
- # extension. The regression test asserts the produced name DIFFERS from the
245
- # template, because asserting that the word `mktemp` appears is what let this
246
- # ship.
247
- #
248
- # NO APOSTROPHES IN THE BODY BELOW. It is a quoted heredoc nested inside a `$( )`
249
- # command substitution, and bash tracks quote state through the body when it
250
- # scans for the closing paren — so a single `'` (in "the agent's TMPDIR", say)
251
- # poisons the parse from there to the next quote and the whole file stops being
252
- # valid shell, with the reported error landing hundreds of lines away in
253
- # untouched code. Every guidance body in this file avoids them for this reason.
254
- # Write "of this session" rather than a possessive.
255
- PRESERVE_GUIDANCE="$(
256
- cat <<'EOF'
257
- Preserve the work first, per-worktree. `mktemp` names the file, so nothing has
258
- to invent one, and it lands in the TMPDIR of this session, where no sibling
259
- agent can reach it:
260
-
261
- patch="$(mktemp "${TMPDIR:-/tmp}/lisa-preserve-XXXXXX")"
262
- git diff --binary HEAD > "$patch"
263
-
264
- Add `-- <path>` before the `>` to scope the capture to one path. Restore it
265
- later with `git apply "$patch"`.
266
-
267
- If the work is NOT yours -- a concurrent agent dirtied this worktree and your
268
- judgement is "none of this is mine" -- that same capture is how you return the
269
- tree to HEAD. This block is self-contained; paste it as it stands:
270
-
271
- patch="$(mktemp "${TMPDIR:-/tmp}/lisa-preserve-XXXXXX")"
272
- git reset
273
- git diff --binary HEAD > "$patch"
274
- git apply -R "$patch"
275
-
276
- It names the file itself rather than inheriting one from the block above,
277
- because the two blocks are alternatives and only one of them gets run. A remedy
278
- printed at the moment an agent is blocked is followed literally; one that
279
- depends on a variable the reader never set fails on its first line, and the
280
- guard that printed it stops being believed.
281
-
282
- `git reset` clears staged and unmerged entries first, so the capture sees the
283
- whole tree as one diff; reversing it leaves the tree at HEAD with "$patch" as
284
- the record of what you discarded. Untracked files survive, exactly as they
285
- survive `git reset --hard`.
286
-
287
- Do NOT reach for `git stash`. One stash stack is shared by every worktree of a
288
- clone, so a concurrently running agent can consume the entry you just pushed.
289
- EOF
290
- )"
291
-
292
- # block() prints the reason to stderr (surfaced to the model) and exits 2 so the
293
- # Bash tool call is denied. $1 = human-readable reason for the block.
294
- #
295
- # $2 = optional guidance REPLACING $DESTRUCTIVE_GUIDANCE. block_heredoc() passes
296
- # its own, because the two remedies are mutually exclusive by construction
297
- # (issue #1958 F6): a heredoc payload IS executable shell, so the quoted-content
298
- # branch is exactly the misdirection that finding removed, and the file-based
299
- # execution advice is exactly what an ordinary prose refusal must not be given.
300
- #
301
- # The refusal must not need file space. A heredoc is staged in a temp file on
302
- # Bash 3.2, and under a file-size limit that staging fails: `set -e` then ended
303
- # the hook with 1 (or SIGXFSZ with 153) instead of 2, so a refusal became an
304
- # allow to the enforcement fallback. `printf` is a builtin that writes straight
305
- # to stderr, SIGXFSZ is ignored so a refused write returns an error instead of
306
- # killing the shell, and a failed write never costs the exit 2
307
- # (CodySwannGT/lisa#4571). scan_failed() writes the same way.
308
- block() {
309
- trap '' XFSZ
310
- printf 'Blocked by safety-net: %s\n\n%s\n' "$1" "${2:-$DESTRUCTIVE_GUIDANCE}" >&2 || true
311
- exit 2
312
- }
313
-
314
- # grep answers three ways, not two: 0 it matched, 1 it did not match, and >=2 "I
315
- # could not do this" — it was never exec'd, the pattern was rejected, the input
316
- # could not be read. Every guard in this file used to reach its verdict through
317
- # a bare `| grep -q` in a condition, where >=2 is indistinguishable from 1. So
318
- # "the scan could not run" was read as "this command is safe", and the safety
319
- # net stopped guarding without ever saying so.
320
- #
321
- # Measured rather than feared (CodySwannGT/lisa#3054). With a `grep` that exits
322
- # 2 first on PATH, this hook ALLOWED `rm -rf /`, `git push --force origin main`,
323
- # `dd of=/dev/disk0` and `git branch -D main` — every built-in guard, silently,
324
- # exit 0. And the condition that gets there is live rather than theoretical: on
325
- # the machine this was found on, 7,679 orphaned processes were outstanding
326
- # against a `kern.maxprocperuid` of 10,666, putting a fork() that returns EAGAIN
327
- # a few hundred spawns away.
328
- #
329
- # The reasoning is ALREADY in this file, at the bottom, for the project custom
330
- # rules: a malformed ERE used to silently disable a rule the project believed it
331
- # had, and that was fixed by reading grep's STATUS instead of its truthiness. It
332
- # was never extended to the built-in guards. This is that extension.
333
- #
334
- # Fails CLOSED, which is this hook's stated contract everywhere else, and NAMES
335
- # the environment failure — a guard that reports "safe" when it means "I could
336
- # not tell" is the exact shape #3054 exists to remove.
337
- #
338
- # $1 = grep flags (-Ei / -E), $2 = text to scan, $3 = pattern.
339
- scan() {
340
- local flags="$1" text="$2" pattern="$3" status=0
341
- printf '%s' "$text" | grep "$flags" -q -- "$pattern" || status=$?
342
- case "$status" in
343
- 0) return 0 ;;
344
- 1) return 1 ;;
345
- *) scan_failed "$status" ;;
346
- esac
347
- }
348
-
349
- # Deny, and say what actually happened. Deliberately NOT block(): block() tells
350
- # the reader their command matched a destructive pattern, which is a claim about
351
- # the COMMAND. This is a claim about the MACHINE, and printing the first when
352
- # the second is true is precisely what sends an operator to re-run instead of to
353
- # look — the reporting failure #3054 is about.
354
- scan_failed() {
355
- trap '' XFSZ
356
- printf '%s\n' \
357
- "Blocked by safety-net: a guard's pattern scan FAILED TO RUN (grep exited $1); denying fail-closed." \
358
- '' \
359
- 'This is an ENVIRONMENT failure, not a property of your command. The guard could' \
360
- 'not be evaluated at all, so the safety net denied rather than guessed — a scan' \
361
- 'that cannot answer must never read as "safe".' \
362
- '' \
363
- 'The usual cause is a machine at its per-user process limit, where fork() starts' \
364
- 'returning EAGAIN. Compare:' \
365
- '' \
366
- ' ps -u $(id -u) | wc -l' \
367
- ' sysctl -n kern.maxprocperuid # Linux: ulimit -u' \
368
- '' \
369
- 'Re-running is reasonable. If it repeats, the machine cannot fork and no number' \
370
- 'of re-runs will change that.' >&2 || true
371
- exit 2
372
- }
373
-
374
- # Heredoc payloads are data only for a deliberately narrow set of GitHub CLI
375
- # write commands. A companion parser proves that shape before removing payload
376
- # text from the destructive-command scans below. Unknown executable heredocs
377
- # remain visible to every built-in and custom rule. Ambiguous or malformed
378
- # heredocs fail closed instead of guessing which text the shell would execute.
379
- #
380
- # block_heredoc() teaches the remediation the moment the wall is hit: a bare
381
- # denial strands the agent with no path forward (gardener #1789). The remedy
382
- # depends on the command shape (issue #1958): `git commit -m "$(cat <<EOF …)"`
383
- # attempts get the commit -F text; every other heredoc denial gets the
384
- # file-based execution guidance instead — the commit text is misleading there.
385
- # Both are passed as block()'s SECOND argument, which REPLACES the ordinary
386
- # destructive guidance rather than appending to it (issue #3191): that guidance
387
- # offers a quoted-content branch, and a heredoc payload is executable shell, so
388
- # printing it here would reintroduce the misdirection #1958 F6 removed.
389
- # The git-commit detection inlines the GIT_GLOBAL_OPTS shape (defined later in
390
- # this file, after the heredoc dispatch runs) so `git -C <path> commit` and
391
- # `git -c k=v commit` spellings are still recognized.
392
- block_heredoc() {
393
- if scan -E "$command_str" \
394
- '(^|[^[:alnum:]_-])git[[:space:]]+(-[^;&|[:space:]]+([[:space:]]+[^-;&|[:space:]][^;&|[:space:]]*)?[[:space:]]+)*commit([^[:alnum:]_-]|$)'; then
395
- block "$1" "Heredoc commit invocations are blocked (the payload is executable shell).
396
- Fix: write the commit message to a file and run \`git commit -F <file>\`.
397
- Every commit must also carry a Co-authored-by trailer for a supported agent
398
- (Claude/Codex/Cursor/OpenCode/Antigravity/Copilot). OpenCode, and any agent
399
- outside that fleet (e.g. Devin), must also carry AI-Agent/AI-Model/AI-Effort
400
- trailers — the commit-msg hook enforces this."
401
- fi
402
- block "$1" "Heredoc payloads are blocked here (the payload is executable shell).
403
- Fix: write the payload to a file with the Write tool, then run the file
404
- (\`bash <file>\`). These guards READ the shell script an invocation runs, so a
405
- destructive command inside that file is refused exactly as the inline form is:
406
- the file is a way to get the payload out of a heredoc, never a way past the
407
- guards."
408
- }
409
-
410
- command_for_guards="$command_str"
411
- case "$command_str" in
412
- *'<<'*)
413
- hook_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
414
- heredoc_parser="$hook_dir/parity-safety-net-heredoc.py"
415
- if ! command -v python3 >/dev/null 2>&1 || [ ! -r "$heredoc_parser" ]; then
416
- block_heredoc "cannot safely classify heredoc command because its parser runtime is unavailable"
417
- fi
418
- if ! printf '%s\n' "$command_str" | /bin/bash -n >/dev/null 2>&1; then
419
- block_heredoc "malformed heredoc command failed shell syntax validation"
420
- fi
421
-
422
- parser_status=0
423
- if parser_output="$(printf '%s' "$command_str" | python3 "$heredoc_parser" 2>/dev/null)"; then
424
- parser_status=0
425
- else
426
- parser_status=$?
427
- fi
428
-
429
- case "$parser_status" in
430
- 0) command_for_guards="$parser_output" ;;
431
- 10) command_for_guards="$command_str" ;;
432
- 20) block_heredoc "malformed or ambiguous heredoc command cannot be safely classified" ;;
433
- *) block_heredoc "heredoc parser failed; command was denied fail-closed" ;;
434
- esac
435
- ;;
436
- esac
437
-
438
- custom_command_for_guards="$command_for_guards"
439
- # A single literal printer writes data, not shell commands. Keep its actual
440
- # redirection in the scan; unsupported syntax and unavailable parsing retain
441
- # the original text. Chained commands and shell substitutions never qualify.
442
- if [[ "$command_for_guards" =~ ^[[:blank:]]*(printf|echo)[[:blank:]] ]] \
443
- && command -v python3 >/dev/null 2>&1; then
444
- if display_projection="$(printf '%s' "$command_for_guards" | python3 \
445
- "$lisa_guard_hook_dir/parity-safety-net-heredoc.py" --literal-display 2>/dev/null)"; then
446
- command_for_guards="$display_projection"
447
- fi
448
- fi
449
-
450
- # ─── Follow execution into the file a command RUNS (issue #3612) ─────────────
451
- #
452
- # Every guard below classifies SHELL COMMAND TEXT, and until this block existed
453
- # the only text they ever saw was the command string. A destructive line
454
- # written into a file and then executed reached them as an interpreter name and
455
- # a path, and was ALLOWED — silently, with no output at all — while the same
456
- # line typed inline was refused. Nine spellings were measured against 4.31.1 and
457
- # all nine allowed: `bash <file>`, `sh <file>`, `zsh <file>`, `env bash <file>`,
458
- # `source <file>`, `. <file>`, a shebang script invoked directly,
459
- # `bash -c 'bash <file>'`, and `eval "$(cat <file>)"`. Two more found while
460
- # fixing it — `bash < <file>` and `cat <file> | bash` — allowed as well.
461
- #
462
- # Three more found by review before this shipped, all one shape: a WRAPPER'S OWN
463
- # OPERAND closing the command position before the program is reached, so
464
- # `nice -n 5 bash <file>`, `sudo -u nobody bash <file>` and `timeout 5 bash
465
- # <file>` walked past the invocation. See the wrapper-prefix arms below.
466
- #
467
- # A guard that fails CLOSED spends time; this one failed OPEN on destructive
468
- # actions and reported nothing, so an operator who installed it to gate `rm -rf`
469
- # outside the project got no signal that the check had not run.
470
- #
471
- # WHY IT IS THE DEFAULT PATH rather than an edge case: block_heredoc() above
472
- # refuses heredocs with an instruction to write the payload to a file and
473
- # execute that file. The tooling therefore routed agents onto exactly the shape
474
- # the destructive scan could not see. Nobody had to evade anything. That remedy
475
- # is reworded above, and this block is the half that makes the reworded remedy
476
- # true.
477
- #
478
- # THE RULE: the blind spot is precisely FILE CONTENTS. Every other part of a
479
- # command — including the inner command of a substitution — is text these guards
480
- # already read. So resolve the file an invocation actually RUNS, read it under a
481
- # size cap, and hand it to the guards as further command text.
482
- #
483
- # WHAT THIS DELIBERATELY DOES NOT DO — the known-wrong fix, already made once in
484
- # this family. #3484 was fixed by teaching a sibling guard to read the contents
485
- # of any file a command NAMES, and that produced #3604: the guard now opens any
486
- # readable file named by any argument and attributes its contents to the
487
- # command, including a path quoted as prose inside a fenced code block in a
488
- # `--body-file` markdown. A path is followed here ONLY when the command EXECUTES
489
- # it. `grep -n x <file>`, `gh pr create --body-file <file>` and
490
- # `git commit -F <file>` name a file as DATA — and $DESTRUCTIVE_GUIDANCE above
491
- # tells operators to use exactly those forms when the destructive text is a
492
- # deliverable, so reading them would break the one remedy that works.
493
- #
494
- # FAIL CLOSED ON WHAT IT CANNOT FOLLOW. At the top level a computed target
495
- # (`bash "$SCRIPT"`), a target that does not exist or cannot be read, a file
496
- # past the size cap, and an operand that is not a path at all (`find … -exec
497
- # bash {} \;`) are each REFUSED with a reason. Silence on an unclassifiable
498
- # destructive command is the bug being fixed, and a truncated scan would report
499
- # a confident ALLOW about text it never read.
500
- #
501
- # NOT FOLLOWED, deliberately. Each one is text these guards were never able to
502
- # classify in the first place, so failing closed on it would spend the operator
503
- # a refusal it cannot buy anything with:
504
- # - Non-shell interpreters (`python3 <file>`, `node <file>`). These patterns
505
- # are shell syntax; running them over a Python or JS file buys
506
- # mis-attribution, not coverage. The heredoc remedy no longer names one.
507
- # - A payload piped from a program's OUTPUT (`curl … | bash`). There is no
508
- # file to read, and the producing command's own text is already scanned.
509
- # - An indirection nested inside an ALREADY-FOLLOWED file whose target is
510
- # computed — `source "$(dirname "$0")/lib.sh"` is the universal shell idiom,
511
- # and failing closed on it would refuse most real scripts. Top-level
512
- # indirection is authored by the agent in the command it just wrote, which
513
- # is where a refusal is both actionable and rare.
514
- # Each is a fail-open the header's ACCEPTED-BYPASS reasoning already covers: the
515
- # net catches ACCIDENTAL catastrophic commands.
516
- readonly FOLLOW_MAX_BYTES=262144
517
- readonly FOLLOW_MAX_TOTAL_BYTES=524288
518
- readonly FOLLOW_MAX_FILES=8
519
- readonly FOLLOW_MAX_DEPTH=3
520
- readonly FOLLOW_MAX_FUNCTION_DEPTH=16
521
- readonly FOLLOW_MAX_FUNCTION_CALLS=128
522
-
523
- # Effective working directory established by a literal `cd` in the command, and
524
- # the flag that says a `cd` happened whose target could NOT be read literally.
525
- # Empty + 0 means no `cd` has been seen and the session's own cwd governs.
526
- follow_cwd=""
527
- follow_cwd_unknown=0
528
- follow_normalized=""
529
- follow_paths=$'\n'
530
- follow_names=""
531
- follow_count=0
532
- follow_bytes=0
533
- follow_function_calls=0
534
- follow_function_bytes=0
535
- followed_text=""
536
- followed_rm_text=""
537
- # Generated from the canonical reviewed supervisor, never from a host manifest.
538
- # Regenerate through scripts/generate-scratch-supervisor-profile.mjs.
2
+ # Retired in #4672. Kept callable for persisted and already-loaded hooks.
3
+ # The Lisa plugin and every unrelated guard remain enabled.
4
+ # The shared parser remains for active instruction guards and legacy copies.
5
+ # No input parsing, command execution, dependencies, or policy refusals.
6
+ # Retained source-profile metadata for compatibility with build tooling. The
7
+ # retired hook never uses this profile to classify a command.
539
8
  readonly SCRATCH_SUPERVISOR_SHA256='76ccf8ca6f98b214361f02ebf6ad58041129b76ed29128455e810095db6c292f'
540
9
  readonly SCRATCH_SUPERVISOR_CLEANUP_COUNT='7'
541
-
542
- # An authenticated public supervisor owns its fixed cleanup sites. Its original
543
- # source remains visible to every other policy; its actual payload is followed.
544
- follow_supervisor() {
545
- local token="$1" depth="$2" statement="$3" path="" profile="" payload="" rm_source="" original=""
546
- case "$token" in *lisa-scratch-run.sh) ;; *) return 1 ;; esac
547
- follow_locate "$token" || follow_refuse "$token" "supervisor source could not be resolved"
548
- path="$follow_located"
549
- profile="$(python3 - "$path" "$SCRATCH_SUPERVISOR_SHA256" "$statement" "$token" "$SCRATCH_SUPERVISOR_CLEANUP_COUNT" <<'PY'
550
- import hashlib
551
- import json
552
- import os
553
- import re
554
- import shlex
555
- import stat
556
- import sys
557
-
558
- path, digest, statement, operand, expected_count = sys.argv[1:]
559
- def refuse():
560
- sys.exit(2)
561
-
562
- try:
563
- info = os.lstat(path)
564
- if not stat.S_ISREG(info.st_mode) or info.st_size > 262144:
565
- refuse()
566
- raw = open(path, 'rb').read(262145)
567
- if len(raw) != info.st_size or not re.fullmatch(r'[0-9a-f]{64}', digest):
568
- refuse()
569
- if hashlib.sha256(raw).hexdigest() != digest:
570
- refuse()
571
- tokens = shlex.split(statement)
572
- indices = [index for index, token in enumerate(tokens) if token == operand]
573
- if len(indices) != 1 or '$' in operand or '`' in operand:
574
- refuse()
575
- index = indices[0]
576
- if index < 1 or tokens[index - 1] not in ('sh', 'bash', '/bin/sh', '/bin/bash'):
577
- refuse()
578
- prefix = tokens[:index - 1]
579
- if prefix[:1] == ['env']:
580
- prefix = prefix[1:]
581
- assignments = {}
582
- for token in prefix:
583
- if '=' not in token or re.search(r'[$`\r\n]', token):
584
- refuse()
585
- key, value = token.split('=', 1)
586
- if key not in ('LISA_SCRATCH_BASE', 'LISA_SCRATCH_TRACE', 'TMPDIR') or key in assignments:
587
- refuse()
588
- assignments[key] = value
589
- # Match actual shell :- precedence, including inherited and
590
- # explicitly empty values. TMPDIR cannot override a nonempty inherited base.
591
- effective = dict(os.environ, **assignments)
592
- base = effective.get('LISA_SCRATCH_BASE') or effective.get('TMPDIR') or '/tmp'
593
- if not base or not os.path.isabs(base) or re.search(r'[$`\r\n]', base):
594
- refuse()
595
- real_base = os.path.realpath(base)
596
- roots = ['/tmp', '/var/tmp', os.environ.get('TMPDIR', '/tmp')]
597
- if not any(os.path.commonpath([real_base, os.path.realpath(root)]) == os.path.realpath(root) for root in roots if root and os.path.isabs(root)):
598
- refuse()
599
- args = tokens[index + 1:]
600
- if len(args) < 4 or args[0] != '--suite' or args[2] != '--':
601
- refuse()
602
- if not re.fullmatch(r'[A-Za-z0-9._-]{1,64}', args[1]):
603
- refuse()
604
- payload = args[3:]
605
- if not payload[0] or payload[0].startswith('-') or any(re.search(r'[$`\x00\r\n]', value) for value in payload):
606
- refuse()
607
- source = raw.decode('utf8')
608
- cleaned, count = re.subn(r'(?m)^(\s*)rm -rf "(\$_quarantine|\$_root|\$_entry|\$LISA_SCRATCH_ROOT)"', r'\1:', source)
609
- if not re.fullmatch(r'[1-9][0-9]*', expected_count) or count != int(expected_count):
610
- refuse()
611
- print(json.dumps({'source': cleaned, 'original': source, 'payload': shlex.join(payload)}))
612
- except (OSError, UnicodeError, ValueError):
613
- refuse()
614
- PY
615
- )" || follow_refuse "$path" "supervisor source or public entry authority could not be authenticated"
616
- rm_source="$(printf '%s' "$profile" | jq -er '.source')" || follow_refuse "$path" "invalid supervisor profile"
617
- original="$(printf '%s' "$profile" | jq -er '.original')" || follow_refuse "$path" "invalid supervisor source"
618
- payload="$(printf '%s' "$profile" | jq -er '.payload')" || follow_refuse "$path" "invalid supervisor payload"
619
- follow_take "$path" "$depth" "$rm_source" "$original"
620
- [ "$depth" -lt "$FOLLOW_MAX_DEPTH" ] || follow_refuse "$path" "supervisor payload exceeds inspection depth"
621
- follow_scan "$payload" "$((depth + 1))"
622
- return 0
623
- }
624
-
625
- FOLLOW_GUIDANCE="This command EXECUTES a file. These guards classify shell text, so the script an
626
- invocation runs is read and scanned as part of the command — a destructive line
627
- inside the file is refused exactly as the inline form is. This one could not be
628
- read, so the guard denied rather than passed: a destructive command it cannot
629
- see is the thing it exists to stop.
630
-
631
- - Name the script by a LITERAL path that exists and is readable — \`bash
632
- ./scripts/x.sh\` rather than \`bash \"\$SCRIPT\"\` — and the guard can classify it.
633
- - A leading \`cd\` the guard cannot read literally — \`cd \"\$DIR\" && bash x.sh\` —
634
- leaves it unable to say WHICH copy of \`x.sh\` would run, and a same-named file
635
- in another directory is a different file. Spell the directory out, or give the
636
- script its full path.
637
- - A file past the inspection cap is refused rather than half-scanned, because a
638
- truncated scan reports a confident ALLOW about text it never read. Split it,
639
- or run it manually outside the agent.
640
- - You genuinely intend to run it as it stands. Ask the user to confirm, then run
641
- it manually outside the agent."
642
-
643
- # Deny, naming the file the guard could not classify. Deliberately NOT the
644
- # ordinary destructive guidance: that guidance is about a pattern the COMMAND
645
- # matched, and this is a claim that the guard could not look at all.
646
- follow_refuse() {
647
- block "cannot classify the file this command executes ($1): $2" "$FOLLOW_GUIDANCE"
648
- }
649
-
650
- # Result of the last follow_unwrap / follow_next_operand. These two SET a global
651
- # rather than printing, and every caller reads it.
652
- #
653
- # Printing would be the natural shape, but `$(follow_unwrap …)` is a FORK, and
654
- # the walk runs it once per token of every followed file. Measured: a script
655
- # just under the 256 KiB inspection cap holds ~48k tokens and cost 27 SECONDS of
656
- # wall clock — inside a PreToolUse hook that gates every Bash call. Both
657
- # functions are pure parameter expansion, so the subshell bought nothing.
658
- #
659
- # The concurrent-process ceiling was never the risk: the forks are sequential,
660
- # so peak process count never rises. The latency was the whole problem.
661
- follow_unwrapped=""
662
- follow_operand_index=0
663
- follow_located=""
664
-
665
- # Strip substitution, quote and alias wrappers off one token. A sibling of
666
- # strip_subst_wrappers() below rather than a call to it: that one is defined
667
- # after this block runs, and it exists for a different job (normalizing a
668
- # DELETION TARGET). Kept separate so tightening either cannot silently move the
669
- # other's verdicts.
670
- follow_unwrap() {
671
- local t="$1" prev=""
672
- while [ "$t" != "$prev" ]; do
673
- prev="$t"
674
- case "$t" in
675
- '$(('*) break ;;
676
- '\'*) t="${t#\\}" ;;
677
- '$('*) t="${t#'$('}" ;;
678
- '<('*) t="${t#'<('}" ;;
679
- '>('*) t="${t#'>('}" ;;
680
- '"'*) t="${t#'"'}" ;;
681
- "'"*) t="${t#\'}" ;;
682
- '`'*) t="${t#'`'}" ;;
683
- '('*) t="${t#(}" ;;
684
- esac
685
- done
686
- prev=""
687
- while [ "$t" != "$prev" ]; do
688
- prev="$t"
689
- case "$t" in
690
- *')') t="${t%)}" ;;
691
- *'`') t="${t%'`'}" ;;
692
- *'"') t="${t%'"'}" ;;
693
- *"'") t="${t%\'}" ;;
694
- *';') t="${t%;}" ;;
695
- esac
696
- done
697
- follow_unwrapped="$t"
698
- }
699
-
700
- # A shell interpreter, bare or path-prefixed. Only shells: see NOT FOLLOWED.
701
- follow_is_interpreter() {
702
- case "$1" in
703
- bash | sh | zsh | ksh | ksh93 | dash | ash \
704
- | */bash | */sh | */zsh | */ksh | */ksh93 | */dash | */ash) return 0 ;;
705
- esac
706
- return 1
707
- }
708
-
709
- # Could this token itself be the thing a wrapper prefix goes on to invoke?
710
- #
711
- # Used ONLY to yield when stepping over a wrapper's own operand, so that
712
- # step-over can never swallow the invocation. Deliberately generous, because the
713
- # cost of the two answers is asymmetric: yielding wrongly leaves the walk where
714
- # it already was, while consuming wrongly loses the program and the guard falls
715
- # open — which is the entire defect this block exists to close. Anything
716
- # path-shaped yields too, so `env -i <file>` still reaches the script rather
717
- # than eating it as a value `-i` does not take.
718
- follow_may_invoke() {
719
- follow_is_interpreter "$1" && return 0
720
- # shellcheck disable=SC2088
721
- case "$1" in
722
- "" | -* | [A-Za-z_]*=*) return 0 ;;
723
- /* | ./* | ../* | '~/'* | */*) return 0 ;;
724
- sudo | env | command | exec | nohup | nice | time | builtin | timeout \
725
- | do | then | else | while | until | if | '!' | '{' \
726
- | eval | find | xargs | cd | source | . | cat) return 0 ;;
727
- esac
728
- return 1
729
- }
730
-
731
- # Both the policy view and statement parser use these exact comment boundaries.
732
- # This is fixed awk source, never source derived from the inspected command.
733
- follow_comment_awk() {
734
- printf '%s\n' '
735
- # A hash starts a comment only at an unescaped shell word boundary.
736
- # Backslash-newline pairs disappear before token recognition; a quoted or
737
- # escaped blank is part of a word, not a boundary before its next hash.
738
- function comment_start(at, before, escapes, k) {
739
- before = at - 1;
740
- while (before > 1 && substr(s, before, 1) == "\n" && substr(s, before - 1, 1) == "\\" && !comment_newline[before]) {
741
- lookahead_step();
742
- escapes = 0;
743
- for (k = before - 1; k > 0 && substr(s, k, 1) == "\\"; k--) { lookahead_step(); escapes++ }
744
- if (escapes % 2 == 0) { break }
745
- before -= 2;
746
- }
747
- if (before == 0 || comment_newline[before]) { return 1 }
748
- if (substr(s, before, 1) !~ /[ \t\n;&|()<>]/) { return 0 }
749
- escapes = 0;
750
- for (k = before - 1; k > 0 && substr(s, k, 1) == "\\"; k--) { lookahead_step(); escapes++ }
751
- return escapes % 2 == 0;
752
- }
753
- function comment_end(at, end) {
754
- # Address one byte at a time rather than copying the remaining file for
755
- # every short comment. Repeated lookahead shares the existing work cap.
756
- for (end = at; end <= n && substr(s, end, 1) != "\n"; end++) { lookahead_step() }
757
- # Backslashes inside discarded comments do not escape their newline.
758
- # Share this fact with the main walk and every lookahead that skips it.
759
- if (end <= n) { comment_newline[end] = 1 }
760
- return end;
761
- }
762
- # Lexical lookahead keeps an asynchronous return from ending its parent
763
- # scan before the trailing & event. Aggregate work is capped linearly in
764
- # input size, including overlap from nested scopes; no partial parse passes.
765
- function lookahead_step() {
766
- if (++lookahead_work > 8 * n + 1024) { exit 2 }
767
- }
768
- '
769
- }
770
-
771
- # Split the command into statements at UNQUOTED separators, printing one
772
- # statement per line as "<separator><TAB><statement>". Quote-aware on purpose: a
773
- # `;` or `|` inside a quoted string is not a statement boundary, and splitting
774
- # there would invent a command position in the middle of a quoted argument and
775
- # make prose look like an invocation — the #3604 failure mode, arrived at from
776
- # the other side. Literal subshell parentheses carry scope events, while quoted
777
- # parentheses and substitutions stay in their original statement so `eval
778
- # "$(cat <file>)"` retains its command position and executed-file inspection.
779
- #
780
- # awk rather than a bash char loop because this runs on EVERY intercepted Bash
781
- # command, and it addresses the text by index instead of accumulating it a
782
- # character at a time so the cost stays linear on a followed file. The text
783
- # arrives through the ENVIRONMENT: `awk -v` processes backslash escapes in the
784
- # value it is given and would rewrite the command before it was ever read.
785
- follow_split() {
786
- LC_ALL=C SN_FOLLOW_TEXT="$1" awk "$(follow_comment_awk)"'
787
- function brace_pipe(from, opening, closing, j, c, quote, escape, braces, nesting, tail, tail_cases, tail_header, word, word_end, parameters) {
788
- quote = ""; escape = 0; braces = 1; nesting = 0; brace_redirect = ""; tail_cases = 0; tail_header = 0; parameters = 0;
789
- for (j = from; j <= n; j++) {
790
- lookahead_step(); c = substr(s, j, 1);
791
- if (escape) { if (c == "$") { literal_dollars[j] = 1 } escape = 0; continue }
792
- if (c == "\\" && quote != "\047") { escape = 1; continue }
793
- if (quote != "") { if (c == quote) { quote = "" } continue }
794
- if (c == "\"" || c == "\047" || c == "`") { quote = c; continue }
795
- if (c == "{" && (parameters > 0 || (substr(s, j - 1, 1) == "$" && !literal_dollars[j - 1]))) { parameters++; continue }
796
- if (c == "}" && parameters > 0) { parameters--; continue }
797
- if (c == "#" && parameters == 0 && comment_start(j)) { j = comment_end(j) - 1; continue }
798
- if (braces > 0) {
799
- # A case-pattern ) is not the closing parenthesis of its shell.
800
- if (opening == "(" && c ~ /[A-Za-z_]/) {
801
- word_end = j + 1;
802
- while (word_end <= n && substr(s, word_end, 1) ~ /[A-Za-z_0-9-]/) { lookahead_step(); word_end++ }
803
- word = substr(s, j, word_end - j); j = word_end - 1;
804
- if (word == "case" && (tail_cases == 0 || !tail_patterns[tail_cases])) { tail_header++ }
805
- if (word == "in" && tail_header > 0) {
806
- tail_header--; tail_patterns[++tail_cases] = 1; tail_levels[tail_cases] = braces;
807
- }
808
- if (word == "esac" && tail_cases > 0) { tail_cases-- }
809
- continue;
810
- }
811
- if (tail_cases > 0 && tail_levels[tail_cases] == braces) {
812
- if (c == ")" && tail_patterns[tail_cases]) { tail_patterns[tail_cases] = 0; continue }
813
- if (c == ";" && substr(s, j + 1, 1) == ";") { tail_patterns[tail_cases] = 1; j++; continue }
814
- }
815
- if (c == opening) { braces++ }
816
- if (c == closing && --braces == 0) { tail = j + 1 }
817
- continue;
818
- }
819
- # Redirections belong to the compound command too. Quoted operator
820
- # bytes and nested substitutions are operands, not the pipeline edge.
821
- if (c == "(") { nesting++; continue }
822
- if (c == ")") { if (nesting == 0) { brace_redirect = substr(s, tail, j - tail); return 0 } nesting--; continue }
823
- if (nesting > 0) { continue }
824
- if (c == "|") { brace_redirect = substr(s, tail, j - tail); return substr(s, j + 1, 1) != "|" }
825
- if (c == ";" || c == "\n") { brace_redirect = substr(s, tail, j - tail); return 0 }
826
- if (c == "&" && substr(s, j - 1, 1) !~ /[<>]/ && substr(s, j + 1, 1) != ">") { brace_redirect = substr(s, tail, j - tail); return 0 }
827
- }
828
- if (tail > 0) { brace_redirect = substr(s, tail) }
829
- return 0;
830
- }
831
- function list_async(from, j, c, quote, escape, nesting, braces, parameters) {
832
- quote = ""; escape = 0; nesting = 0; braces = 0; parameters = 0;
833
- for (j = from; j <= n; j++) {
834
- lookahead_step();
835
- c = substr(s, j, 1);
836
- if (escape) { if (c == "$") { literal_dollars[j] = 1 } escape = 0; continue }
837
- if (c == "\\" && quote != "\047") { escape = 1; continue }
838
- if (quote != "") { if (c == quote) { quote = "" } continue }
839
- if (c == "\"" || c == "\047" || c == "`") { quote = c; continue }
840
- if (c == "{" && (parameters > 0 || (substr(s, j - 1, 1) == "$" && !literal_dollars[j - 1]))) { parameters++; continue }
841
- if (c == "}" && parameters > 0) { parameters--; continue }
842
- if (c == "#" && parameters == 0 && comment_start(j)) { j = comment_end(j) - 1; continue }
843
- if (c == "(") { nesting++; continue }
844
- if (c == ")") { if (nesting == 0) { return 0 } nesting--; continue }
845
- if (c == "{") { braces++; continue }
846
- if (c == "}") { if (braces > 0) { braces-- } continue }
847
- if (nesting > 0 || braces > 0) { continue }
848
- if (c == ";" || c == "\n") { return 0 }
849
- if (c == "&" && substr(s, j - 1, 1) !~ /[&<>]/ && substr(s, j + 1, 1) !~ /[&>]/) { return 1 }
850
- }
851
- return 0;
852
- }
853
- # The reader consumes physical lines, but an unquoted/double-quoted
854
- # backslash-newline is absent from the shell word. Preserve that join in
855
- # emitted statements too: otherwise the next physical line can start with
856
- # a literal word-owned hash and be discarded as a full-line comment.
857
- function logical_lines(text, k, c, quote, escape, from, out) {
858
- quote = ""; escape = 0; from = 1; out = "";
859
- for (k = 1; k <= length(text); k++) {
860
- c = substr(text, k, 1);
861
- if (escape) {
862
- if (c == "\n") { out = out substr(text, from, k - from - 1); from = k + 1 }
863
- escape = 0; continue;
864
- }
865
- if (c == "\\" && quote != "\047") { escape = 1; continue }
866
- if (quote != "") { if (c == quote) { quote = "" } continue }
867
- if (c == "\"" || c == "\047") { quote = c }
868
- }
869
- return out substr(text, from);
870
- }
871
- # U records tell the walker the stream below may not match the shell, so
872
- # a compound closer can no longer be trusted (follow_compound_close). They
873
- # only ever ADD distrust; every other record is emitted exactly as before.
874
- #
875
- # A statement spanning lines (a quoted newline, a backslash continuation)
876
- # reaches the line-oriented reader as several records, and a later line
877
- # can spell `done` or `fi` on its own.
878
- function record(kind, text) {
879
- if (text ~ /\n/) { printf "U\t\n" }
880
- text = logical_lines(text);
881
- printf "%s\t%s\n", kind, text;
882
- }
883
- # The first word of one separator-delimited piece of a comment, as the
884
- # walker would read it if the split hands it over as a statement.
885
- function comment_reserved(piece) {
886
- sub(/^[[:space:]]+/, "", piece); sub(/[[:space:]].*$/, "", piece);
887
- gsub(/["\047]/, "", piece);
888
- return piece ~ /^(fi|done|esac|case|if|then|else|elif|do|while|until|for|select|function|!|\{|\})$/;
889
- }
890
- # Retain the existing distrust signal for comments whose former split could
891
- # change scope. Removing their text must not loosen a refusal that depended
892
- # on conservative flow tracking. A comment is harmless to that tracking only
893
- # when its former split cannot change any structure the walker
894
- # tracks: no piece after a separator starts with a reserved word, quotes
895
- # close, parentheses and braces balance, and nothing escapes or substitutes.
896
- # Inside a case pattern a `)` ends the pattern, so it is never harmless
897
- # there; a `(` is ignored there, which keeps the Gradle `#(` safe.
898
- # Anything else is reported, and the walker stops restoring flow.
899
- function comment_unsafe(from, pattern, j, c, cq, parens, braces, pieces, piece) {
900
- cq = ""; parens = 0; braces = 0; pieces = 0; piece = "";
901
- for (j = from; j <= n; j++) {
902
- c = substr(s, j, 1);
903
- if (c == "\n") { break }
904
- if (c == "\\" || c == "`") { return 1 }
905
- if (cq != "") {
906
- if (c == cq) { cq = "" }
907
- else if (cq == "\"" && c == "(" && substr(s, j - 1, 1) == "$") { return 1 }
908
- piece = piece c; continue;
909
- }
910
- if (c == "\"" || c == "\047") { cq = c; piece = piece c; continue }
911
- if (c ~ /[;&|(){}]/) {
912
- if (pieces > 0 && comment_reserved(piece)) { return 1 }
913
- pieces++; piece = "";
914
- if (c == "(" && !pattern) { parens++ }
915
- if (c == ")" && (pattern || --parens < 0)) { return 1 }
916
- if (c == "{") { braces++ }
917
- if (c == "}" && --braces < 0) { return 1 }
918
- continue;
919
- }
920
- piece = piece c;
921
- }
922
- if (pieces > 0 && comment_reserved(piece)) { return 1 }
923
- return cq != "" || parens != 0 || braces != 0;
924
- }
925
- function comment_check(at, pattern, from) {
926
- # Full physical comment lines were absent from the old policy view and
927
- # must not introduce new scope uncertainty merely because the parser now
928
- # receives raw source. Inline comments keep the existing distrust rule.
929
- if (at != 1 && substr(s, at - 1, 1) !~ /[[:space:];&|()]/) { return }
930
- for (from = at - 1; from > 0 && substr(s, from, 1) != "\n"; from--) { lookahead_step() }
931
- if (substr(s, from + 1, at - from - 1) ~ /^[[:space:]]*$/) { return }
932
- if ((at == 1 || substr(s, at - 1, 1) ~ /[[:space:];&|()]/) && comment_unsafe(at + 1, pattern)) {
933
- printf "U\t\n";
934
- }
935
- }
936
- BEGIN {
937
- s = ENVIRON["SN_FOLLOW_TEXT"]; n = length(s);
938
- q = ""; esc = 0; start = 1; sep = "o"; parens = 0;
939
- functions = 0; cases = 0; backtick = 0; brace_depth = 0; post_brace = 0; parameters = 0;
940
- printf "L\t%d\n", list_async(1);
941
- for (i = 1; i <= n; i++) {
942
- c = substr(s, i, 1); comment_from = 0;
943
- if (esc == 1) { if (c == "$") { literal_dollars[i] = 1 } esc = 0; continue }
944
- if (c == "\\" && q != "\047") { esc = 1; continue }
945
- if (functions > 0) {
946
- if (q != "") { if (c == q) { q = "" } continue }
947
- if (c == "\"" || c == "\047") { q = c; continue }
948
- if (c == "{" && (parameters > 0 || (substr(s, i - 1, 1) == "$" && !literal_dollars[i - 1]))) { parameters++; continue }
949
- if (parameters > 0) { if (c == "}") { parameters-- } continue }
950
- if (c == "#") {
951
- comment_check(i, 0);
952
- if (comment_start(i)) { i = comment_end(i) - 1; continue }
953
- }
954
- if (c == "{") { functions++ }
955
- if (c == "}" && --functions == 0) {
956
- printf "N\t%s\t%s\n", sep, function_name;
957
- body = substr(s, function_start, i - function_start);
958
- count = split(body, body_lines, "\n");
959
- for (j = 1; j <= count; j++) { printf "D\t%s\n", body_lines[j] }
960
- printf "F\t\n"; start = i + 1; sep = "o";
961
- }
962
- continue;
963
- }
964
- quoted_expression = q == "\"" && ((c == "(" && substr(s, i - 1, 1) == "$" && !literal_dollars[i - 1]) || c == "`");
965
- if (q != "" && !quoted_expression) { if (c == q) { q = "" } continue }
966
- if (c == "\"" || c == "\047") { q = c; continue }
967
- if (c == "{" && (parameters > 0 || (substr(s, i - 1, 1) == "$" && !literal_dollars[i - 1]))) { parameters++; continue }
968
- if (c == "}" && parameters > 0) { parameters--; continue }
969
- if (c == "#") {
970
- comment_check(i, cases > 0 && case_scopes[cases] == parens && case_patterns[cases]);
971
- if (parameters == 0 && comment_start(i)) { comment_from = i; i = comment_end(i); if (i > n) { i = n } c = "\n" }
972
- }
973
- if (c == "`") {
974
- if (backtick) {
975
- piece = substr(s, start, i - start);
976
- if (piece ~ /[^[:space:]]/) { record(sep, piece); sep = "o" }
977
- printf "]\t\n"; start = backtick_start; q = backtick_quote; backtick = 0;
978
- } else {
979
- backtick_start = start; backtick_quote = q; q = ""; backtick = 1;
980
- printf "[\t\nL\t%d\n", list_async(i + 1); start = i + 1;
981
- }
982
- continue;
983
- }
984
- if (i == start && c ~ /[ \t\n]/) { start = i + 1; continue }
985
- if (c ~ /[[:space:]]/ && substr(s, i - 1, 1) !~ /[[:space:]]/ && substr(s, start, 4) == "case") {
986
- piece = substr(s, start, i - start);
987
- if (piece ~ /^case[[:space:]].*[[:space:]]in$/) {
988
- case_scopes[++cases] = parens;
989
- case_patterns[cases] = 1; printf "C\t\n"; start = i + 1; continue;
990
- }
991
- }
992
- if (cases > 0 && c ~ /[[:space:];&|)]/ && substr(s, start, 4) == "esac") {
993
- piece = substr(s, start, i - start);
994
- if (piece ~ /^esac[[:space:]]*$/) { cases--; printf "K\t\n" }
995
- }
996
- if (cases > 0 && case_scopes[cases] == parens && case_patterns[cases]) {
997
- if (c == ")") { case_patterns[cases] = 0; start = i + 1 }
998
- continue;
999
- }
1000
- if (c == "{") {
1001
- piece = substr(s, start, i - start);
1002
- definition = piece ~ /^[ \t\n]*([A-Za-z_][A-Za-z_0-9]*[ \t]*\([ \t]*\)|function[ \t]+[A-Za-z_][A-Za-z_0-9]*([ \t]*\([ \t]*\))?)[ \t\n]*$/;
1003
- if (definition) {
1004
- function_name = piece;
1005
- sub(/^[ \t\n]*(function[ \t]+)?/, "", function_name);
1006
- sub(/[ \t\n\(].*$/, "", function_name);
1007
- functions = 1; function_start = i + 1;
1008
- continue;
1009
- }
1010
- previous = i > 1 ? substr(s, i - 1, 1) : "";
1011
- group = (i == 1 || previous ~ /[ \t\n;&|()]/) && substr(s, i + 1, 1) ~ /[ \t\n;]/ &&
1012
- piece ~ /^[ \t\n]*((then|do|else|!|time)[ \t\n]+)*$/;
1013
- brace_groups[++brace_depth] = group;
1014
- if (group) {
1015
- brace_sep = sep;
1016
- if (piece ~ /[^[:space:]]/) { record(sep, piece); sep = "o" }
1017
- # A pipeline owns the whole compound command, not just the final
1018
- # statement before |. Snapshot before any brace-body cd/return.
1019
- outgoing = brace_pipe(i + 1, "{", "}");
1020
- brace_pipes[brace_depth] = brace_sep == "|" || outgoing;
1021
- if (brace_pipes[brace_depth]) { printf "(\t%s%s\nL\t%d\n", (brace_sep == "|" ? "|" : ""), (outgoing ? "+" : ""), list_async(i + 1) }
1022
- printf "G\t%s\nL\t%d\n", brace_sep, list_async(i + 1);
1023
- if (brace_redirect ~ /[^[:space:]]/) { record("I", brace_redirect) }
1024
- # P retains incoming stdin provenance without wrapping each body
1025
- # statement in another child: all statements share the brace cwd.
1026
- if (brace_sep == "|") { sep = "P" }
1027
- start = i + 1; continue;
1028
- }
1029
- }
1030
- if (c == "}" && brace_depth > 0) {
1031
- group = brace_groups[brace_depth--];
1032
- if (group) {
1033
- piece = substr(s, start, i - start);
1034
- if (piece ~ /[^[:space:]]/) { record(sep, piece); sep = "o" }
1035
- printf "H\t\n";
1036
- if (brace_pipes[brace_depth + 1]) { printf ")\t\n" }
1037
- start = i + 1; post_brace = 1; continue;
1038
- }
1039
- }
1040
- if (c == "(") {
1041
- previous = i > 1 ? substr(s, i - 1, 1) : "";
1042
- piece = substr(s, start, i - start);
1043
- header = piece ~ /^[ \t]*(function[ \t]+)?[A-Za-z_][A-Za-z_0-9]*[ \t]*$/ && substr(s, i + 1) ~ /^[ \t]*\)/;
1044
- expression = previous ~ /[$<>]/ && !literal_dollars[i - 1] && substr(s, i + 1, 1) != "(";
1045
- group = (parens == 0 || scopes[parens] != 0) &&
1046
- (i == 1 || previous ~ /[ \t\n;&|()]/) && substr(s, i + 1, 1) != "(" && !header;
1047
- scopes[++parens] = expression ? 2 : group;
1048
- if (expression) {
1049
- expression_starts[parens] = start;
1050
- expression_quotes[parens] = q; q = "";
1051
- printf "[\t\nL\t%d\n", list_async(i + 1); start = i + 1; continue;
1052
- }
1053
- if (group) {
1054
- piece = substr(s, start, i - start);
1055
- if (piece ~ /[^[:space:]]/) { record(sep, piece); sep = "o" }
1056
- outgoing = brace_pipe(i + 1, "(", ")");
1057
- printf "(\t%s%s\nL\t%d\n", sep, (outgoing ? "+" : ""), list_async(i + 1);
1058
- if (brace_redirect ~ /[^[:space:]]/) { record("I", brace_redirect) }
1059
- if (sep == "|") { sep = "P" }
1060
- start = i + 1; continue;
1061
- }
1062
- }
1063
- if (c == ")" && parens > 0) {
1064
- piece = substr(s, start, i - start);
1065
- group = scopes[parens--];
1066
- if (group == 2) {
1067
- if (piece ~ /[^[:space:]]/) { record(sep, piece); sep = "o" }
1068
- printf "]\t\n"; start = expression_starts[parens + 1]; q = expression_quotes[parens + 1]; continue;
1069
- }
1070
- if (group) {
1071
- piece = substr(s, start, i - start);
1072
- if (piece ~ /[^[:space:]]/) { record(sep, piece); sep = "o" }
1073
- printf ")\t\n"; start = i + 1; post_brace = 1; continue;
1074
- }
1075
- }
1076
- if (c == ";" || c == "&" || c == "|" || c == "\n") {
1077
- if (parens > 0 && scopes[parens] == 0) { continue }
1078
- if (c == "&" && (substr(s, i - 1, 1) ~ /[<>]/ || substr(s, i + 1, 1) == ">")) { continue }
1079
- piece = substr(s, start, (comment_from ? comment_from : i) - start);
1080
- pipe = c == "|" && substr(s, i + 1, 1) != "|";
1081
- if (pipe || sep == "|") { printf "(\t%s%s\nL\t%d\n", (sep == "|" ? "|" : ""), (pipe ? "+" : ""), list_async(start) }
1082
- if (piece ~ /[^[:space:]]/) { record(post_brace ? "R" : sep, piece) }
1083
- post_brace = 0;
1084
- if (pipe || sep == "|") { printf ")\t\n" }
1085
- if (c == ";" && substr(s, i + 1, 1) == ";" && cases > 0) {
1086
- case_patterns[cases] = 1; printf "A\t\n"; i++;
1087
- }
1088
- if (c == "|" && substr(s, i + 1, 1) == "|") {
1089
- i++; sep = "?";
1090
- } else if (c == "&" && substr(s, i + 1, 1) == "&") {
1091
- i++; sep = "&";
1092
- } else if (c == "|") { sep = "|" } else { sep = "o" }
1093
- if (c == "&" && sep == "o" && substr(s, i - 1, 1) !~ /[&<>]/ && substr(s, i + 1, 1) != ">") {
1094
- printf "B\t\n";
1095
- }
1096
- if ((c == ";" || c == "\n" || c == "&") && sep == "o") { printf "L\t%d\n", list_async(i + 1) }
1097
- start = i + 1;
1098
- continue
1099
- }
1100
- }
1101
- if (sep == "|") { printf "(\t|\nL\t%d\n", list_async(start) }
1102
- record(sep, substr(s, start, n - start + 1));
1103
- if (sep == "|") { printf ")\t\n" }
1104
- }
1105
- '
1106
- }
1107
-
1108
- # Collapse `.`, `..` and empty segments so the path a verdict NAMES is the one a
1109
- # reader recognises. Purely lexical, and it cannot move a verdict: every
1110
- # component has already been proven to exist by the `-d` test that follows, and
1111
- # the `-f`/`-r` tests are applied to the collapsed path either way.
1112
- follow_normalize() {
1113
- local p="$1" out="" seg
1114
- local IFS=/
1115
- set -f
1116
- # The word split is the point: `$p` is being addressed one path segment at a
1117
- # time, and the glob guard above keeps a literal `*` from expanding.
1118
- # shellcheck disable=SC2086
1119
- for seg in $p; do
1120
- case "$seg" in
1121
- "" | .) ;;
1122
- ..) out="${out%/*}" ;;
1123
- *) out="$out/$seg" ;;
1124
- esac
1125
- done
1126
- set +f
1127
- follow_normalized="${out:-/}"
1128
- }
1129
-
1130
- # Track the working directory a literal `cd` establishes, so a relative executed
1131
- # path resolves against the directory the command will actually have.
1132
- #
1133
- # This REPLACES the session's own cwd rather than adding to it. It used to be an
1134
- # extra base appended AFTER `$PWD`, so `$PWD` always won and
1135
- # `cd <other-checkout> && bash scripts/x.sh` was classified against the session
1136
- # checkout's same-named copy. That is not a resolution failure — it succeeds,
1137
- # against a real and readable file, and the verdict is reported with full
1138
- # confidence about text nobody was about to run (CodySwannGT/lisa#3933). Two
1139
- # checkouts of one repository differ by exactly the work in flight, which is the
1140
- # entire point of the second one, so the copy that would RUN is the only copy
1141
- # whose verdict means anything. Wrong in both directions, and the expensive
1142
- # direction is silent: the dangerous line sits in the copy that would run and
1143
- # the guard reads the pristine one.
1144
- #
1145
- # A target this hook cannot turn into a literal directory marks the cwd UNKNOWN
1146
- # instead of leaving a stale one in place. `follow_locate` then refuses a
1147
- # relative token rather than guessing, which is the honest-refusal doctrine the
1148
- # rest of this block already follows: a confident scan of the wrong file is
1149
- # strictly worse than saying it could not tell.
1150
- follow_cd() {
1151
- local d="$1" home="${HOME:-}"
1152
- # The tilde arms are LITERAL text — the unexpanded spelling the hook was
1153
- # handed — for the reason follow_locate's arms document.
1154
- # shellcheck disable=SC2088
1155
- case "$d" in
1156
- '~') d="$home" ;;
1157
- '~/'*) d="$home/${d#'~/'}" ;;
1158
- esac
1159
- case "$d" in
1160
- "" | -* | *'$'* | *'*'* | *'?'* | *'`'* | *'{'* | *'['*)
1161
- follow_cwd=""
1162
- follow_cwd_unknown=1
1163
- return 0
1164
- ;;
1165
- esac
1166
- case "$d" in
1167
- /*) ;;
1168
- *)
1169
- # A relative cd cannot recover an unknown base. Falling back to this
1170
- # hook's PWD would confidently inspect another directory (#4299).
1171
- [ "$follow_cwd_unknown" -eq 0 ] || return 0
1172
- d="${follow_cwd:-$PWD}/$d"
1173
- ;;
1174
- esac
1175
- follow_normalize "$d"
1176
- d="$follow_normalized"
1177
- if [ -d "$d" ]; then
1178
- follow_cwd="$d"
1179
- follow_cwd_unknown=0
1180
- else
1181
- follow_cwd=""
1182
- follow_cwd_unknown=1
1183
- fi
1184
- }
1185
-
1186
- # Resolve one executed-file operand to a readable regular file, or fail.
1187
- #
1188
- # The variable expansions are LOCATE-ONLY and cannot widen a verdict: a wrong
1189
- # guess simply fails to find a file, and an unresolved target is refused, not
1190
- # passed. They are here because an agent's own scratch path arrives spelled with
1191
- # one of them, and refusing every `bash "$TMPDIR/x.sh"` would be a wall with no
1192
- # door. Nothing else is expanded — any remaining `$`, glob or brace is a target
1193
- # this hook cannot evaluate.
1194
- follow_locate() {
1195
- local token="$1" home="${HOME:-}" tmp="${TMPDIR:-/tmp}" proj="${CLAUDE_PROJECT_DIR:-$PWD}" base
1196
- local cwd="${follow_cwd:-$PWD}"
1197
- follow_located=""
1198
- tmp="${tmp%/}"
1199
- [ -n "$tmp" ] || tmp="/tmp"
1200
- # The tilde arms below are LITERAL text: this is the unexpanded spelling the
1201
- # hook was handed, and turning it into a path is the whole point of the arm.
1202
- # shellcheck disable=SC2088
1203
- case "$token" in
1204
- '~') token="$home" ;;
1205
- '~/'*) token="$home/${token#'~/'}" ;;
1206
- '$TMPDIR' | '$TMPDIR'/*) token="$tmp${token#'$TMPDIR'}" ;;
1207
- '${TMPDIR}' | '${TMPDIR}'/*) token="$tmp${token#'${TMPDIR}'}" ;;
1208
- '$HOME' | '$HOME'/*) token="$home${token#'$HOME'}" ;;
1209
- '${HOME}' | '${HOME}'/*) token="$home${token#'${HOME}'}" ;;
1210
- '$PWD' | '$PWD'/*)
1211
- [ "$follow_cwd_unknown" -eq 0 ] || return 1
1212
- token="$cwd${token#'$PWD'}"
1213
- ;;
1214
- '${PWD}' | '${PWD}'/*)
1215
- [ "$follow_cwd_unknown" -eq 0 ] || return 1
1216
- token="$cwd${token#'${PWD}'}"
1217
- ;;
1218
- '$CLAUDE_PROJECT_DIR' | '$CLAUDE_PROJECT_DIR'/*) token="$proj${token#'$CLAUDE_PROJECT_DIR'}" ;;
1219
- '${CLAUDE_PROJECT_DIR}' | '${CLAUDE_PROJECT_DIR}'/*) token="$proj${token#'${CLAUDE_PROJECT_DIR}'}" ;;
1220
- esac
1221
- case "$token" in
1222
- "" | *'$'* | *'*'* | *'?'* | *'`'* | *'{'* | *'['*) return 1 ;;
1223
- /*)
1224
- [ -f "$token" ] && [ -r "$token" ] || return 1
1225
- follow_located="$token"
1226
- return 0
1227
- ;;
1228
- esac
1229
- # Past this point the token is RELATIVE, so which directory it is resolved
1230
- # from decides which file the verdict is about.
1231
- if [ "$follow_cwd_unknown" -eq 1 ]; then
1232
- return 1
1233
- fi
1234
- if [ -n "$follow_cwd" ]; then
1235
- # A literal `cd` names the directory the shell will be in. It is the only
1236
- # candidate — falling back to `$PWD` here is what made the guard report
1237
- # confidently about a same-named file in another checkout.
1238
- [ -f "$follow_cwd/$token" ] && [ -r "$follow_cwd/$token" ] || return 1
1239
- follow_located="$follow_cwd/$token"
1240
- return 0
1241
- fi
1242
- while IFS= read -r base; do
1243
- [ -n "$base" ] || continue
1244
- if [ -f "$base/$token" ] && [ -r "$base/$token" ]; then
1245
- follow_located="$base/$token"
1246
- return 0
1247
- fi
1248
- done <<<"$PWD"$'\n'"$proj"
1249
- return 1
1250
- }
1251
-
1252
- # Drop a physical comment line only at a real logical shell word boundary.
1253
- # A blank after a joined newline can start a comment, but a hash in a quoted or
1254
- # continued word cannot. Keep the old conservative inline-comment policy while
1255
- # sharing comment/newline provenance and work bounds with the statement parser.
1256
- follow_policy_text() {
1257
- LC_ALL=C SN_FOLLOW_TEXT="$1" awk "$(follow_comment_awk)"'
1258
- BEGIN {
1259
- s = ENVIRON["SN_FOLLOW_TEXT"]; n = length(s);
1260
- quote = ""; escape = 0; parameters = 0; line_start = 1; from = 1;
1261
- for (i = 1; i <= n; i++) {
1262
- lookahead_step(); c = substr(s, i, 1);
1263
- if (c == "\n") { line_start = i + 1 }
1264
- if (escape) { if (c == "$") { literal_dollars[i] = 1 } escape = 0; continue }
1265
- if (c == "\\" && quote != "\047") { escape = 1; continue }
1266
- if (quote != "") { if (c == quote) { quote = "" } continue }
1267
- if (c == "\"" || c == "\047" || c == "`") { quote = c; continue }
1268
- if (c == "{" && (parameters > 0 || (substr(s, i - 1, 1) == "$" && !literal_dollars[i - 1]))) { parameters++; continue }
1269
- if (c == "}" && parameters > 0) { parameters--; continue }
1270
- if (c == "#" && parameters == 0 && comment_start(i)) {
1271
- end = comment_end(i);
1272
- if (substr(s, line_start, i - line_start) ~ /^[ \t]*$/) {
1273
- printf "%s", substr(s, from, line_start - from);
1274
- from = end;
1275
- }
1276
- # Ignore quotes and backslashes owned by any real comment, including
1277
- # inline comments whose bytes the conservative policy view retains.
1278
- i = end - 1;
1279
- }
1280
- }
1281
- printf "%s", substr(s, from);
1282
- }
1283
- '
1284
- }
1285
-
1286
- # Read one executed file into the text the guards will scan, then follow what IT
1287
- # executes, to a bounded depth. Text policies retain their comment-free view;
1288
- # the statement parser needs original physical lines to distinguish a comment
1289
- # from a word-owned hash after a backslash-newline join.
1290
- follow_take() {
1291
- local path="$1" depth="$2" size="" content="" source_content="" rm_content="${3-}"
1292
- local invocation_kind=child
1293
- if [ "$#" -eq 3 ]; then invocation_kind="$3"; fi
1294
- case "$follow_paths" in
1295
- *$'\n'"$path"$'\n'*)
1296
- # Sourcing executes in the caller each time; a read cache cannot erase
1297
- # its directory changes or newly defined functions.
1298
- [ "$invocation_kind" = source ] || return 0
1299
- ;;
1300
- esac
1301
- follow_paths="$follow_paths$path"$'\n'
1302
- follow_count=$((follow_count + 1))
1303
- if [ "$follow_count" -gt "$FOLLOW_MAX_FILES" ]; then
1304
- follow_refuse "$path" "this command executes more files than the guard will inspect (${FOLLOW_MAX_FILES})"
1305
- fi
1306
- size="$(wc -c <"$path" 2>/dev/null | tr -cd '0-9')" || size=""
1307
- case "$size" in
1308
- "") follow_refuse "$path" "its size could not be determined" ;;
1309
- esac
1310
- if [ "$size" -gt "$FOLLOW_MAX_BYTES" ]; then
1311
- follow_refuse "$path" "it is larger than the ${FOLLOW_MAX_BYTES}-byte inspection cap"
1312
- fi
1313
- follow_bytes=$((follow_bytes + size))
1314
- if [ "$follow_bytes" -gt "$FOLLOW_MAX_TOTAL_BYTES" ]; then
1315
- follow_refuse "$path" "the files this command executes total more than the ${FOLLOW_MAX_TOTAL_BYTES}-byte inspection budget"
1316
- fi
1317
- if [ "$#" -eq 4 ]; then
1318
- # Scan the same complete bytes whose digest was authenticated, not a
1319
- # second file read that could pair changed source with the cleanup view.
1320
- source_content="$4"
1321
- else
1322
- source_content="$(LC_ALL=C tr -d '\000' <"$path")" \
1323
- || follow_refuse "$path" "it could not be read"
1324
- fi
1325
- content="$(follow_policy_text "$source_content")" || follow_refuse "$path" "source policy view could not be read"
1326
- follow_names="$follow_names $path"
1327
- followed_text="$followed_text"$'\n'"$content"
1328
- if [ "$#" -ne 4 ]; then
1329
- rm_content="$content"
1330
- else
1331
- rm_content="$(follow_policy_text "$rm_content")" || follow_refuse "$path" "supervisor cleanup view could not be read"
1332
- fi
1333
- followed_rm_text="$followed_rm_text"$'\n'"$rm_content"
1334
- if [ "$depth" -lt "$FOLLOW_MAX_DEPTH" ]; then
1335
- # Child scripts inherit cwd but cannot change their parent. A sourced
1336
- # script runs in the caller and keeps both cwd and function definitions.
1337
- local saved_cwd="$follow_cwd" saved_unknown="$follow_cwd_unknown"
1338
- if [ "$#" -eq 4 ]; then
1339
- # Only follow_supervisor reaches this form, after exact byte identity and
1340
- # the public argv profile were authenticated. Its owned bootstrap is
1341
- # already scanned in full by every text policy; its user payload is
1342
- # followed separately by follow_supervisor. Re-expanding all bootstrap
1343
- # functions would re-interpret its internal protocol, not inspect a new
1344
- # user-controlled file, and multiplied its native hook time fourfold.
1345
- follow_scan "$source_content" "$((depth + 1))" 0 1
1346
- else
1347
- follow_scan "$source_content" "$((depth + 1))" 0 0 "$invocation_kind"
1348
- fi
1349
- if [ "$invocation_kind" != source ]; then
1350
- follow_cwd="$saved_cwd"
1351
- follow_cwd_unknown="$saved_unknown"
1352
- fi
1353
- fi
1354
- }
1355
-
1356
- # An operand a command EXECUTES. Unresolvable at the top level is a refusal;
1357
- # nested inside an already-followed script it is the documented residual above.
1358
- follow_target() {
1359
- local token="$1" depth="$2" path=""
1360
- local invocation_kind="${3:-child}"
1361
- [ -n "$token" ] || return 0
1362
- if [ "$follow_cwd_unknown" -ne 0 ]; then
1363
- case "$token" in
1364
- /* | '~/'*) ;;
1365
- *) follow_refuse "$token" "the execution directory is unknown" ;;
1366
- esac
1367
- fi
1368
- # Entry authority belongs to each invocation, not the file-read cache. Only
1369
- # follow_supervisor may admit the exact public interpreter/argv profile.
1370
- case "$token" in
1371
- *lisa-scratch-run.sh) follow_refuse "$token" "supervisor requires its authenticated public interpreter entry" ;;
1372
- esac
1373
- if ! follow_locate "$token"; then
1374
- if [ "$depth" -eq 0 ]; then
1375
- follow_refuse "$token" "no readable file could be resolved for it"
1376
- fi
1377
- return 0
1378
- fi
1379
- path="$follow_located"
1380
- follow_take "$path" "$depth" "$invocation_kind"
1381
- }
1382
-
1383
- # A command word that IS the executable (`./deploy.sh`, `/tmp/x.sh`). Followed
1384
- # only when the file's shebang names a shell: a compiled binary or a Python/Node
1385
- # script is not text these patterns can classify, and `/usr/bin/git` sitting at
1386
- # a command position must stay an ordinary command.
1387
- #
1388
- # This arm alone does NOT fail closed on an unresolvable token, and the line is
1389
- # deliberate. Elsewhere the command TEXT declares that a file is being executed
1390
- # — `bash <file>` says so whether or not the file can be read — so "I cannot
1391
- # read it" is a real inability to classify a stated execution. Here the only
1392
- # evidence that the token is a script at all is the shebang inside it, so an
1393
- # unreadable token is not an unclassifiable execution; it is a command word this
1394
- # hook cannot see, and a shell that cannot see it cannot run it either. Refusing
1395
- # on shape alone would deny `/usr/bin/charm x` and `./scripts/confirm -rf /`,
1396
- # both of which the guard-parity matrix pins as ALLOW (#1960 PR-A2/PR-A3).
1397
- # Accepted residual: a shebang script whose relative path resolves only from a
1398
- # working directory this hook does not share is not followed.
1399
- follow_direct() {
1400
- local token="$1" depth="$2" path="" first="" raw="" char="" k=0
1401
- local LC_ALL=C
1402
- if ! follow_locate "$token"; then
1403
- return 0
1404
- fi
1405
- path="$follow_located"
1406
- case "$path" in
1407
- *lisa-scratch-run.sh) follow_refuse "$path" "supervisor requires its authenticated public interpreter entry" ;;
1408
- esac
1409
- IFS= read -r -n 256 raw <"$path" 2>/dev/null || true
1410
- while [ "$k" -lt "${#raw}" ]; do
1411
- char="${raw:k:1}"
1412
- case "$char" in [[:print:]]) first="$first$char" ;; esac
1413
- k=$((k + 1))
1414
- done
1415
- case "$first" in
1416
- '#!'*[/[:space:]]bash* | '#!'*[/[:space:]]sh* | '#!'*[/[:space:]]zsh* \
1417
- | '#!'*[/[:space:]]ksh* | '#!'*[/[:space:]]dash* | '#!'*[/[:space:]]ash*) ;;
1418
- *) return 0 ;;
1419
- esac
1420
- follow_take "$path" "$depth"
1421
- }
1422
-
1423
- # Index of the next non-option token after $1, or $2 when there is none.
1424
- follow_next_operand() {
1425
- local from="$1" upto="$2" j
1426
- j=$((from + 1))
1427
- while [ "$j" -lt "$upto" ]; do
1428
- follow_unwrap "${toks[j]}"
1429
- case "$follow_unwrapped" in
1430
- -*) j=$((j + 1)) ;;
1431
- *) break ;;
1432
- esac
1433
- done
1434
- follow_operand_index="$j"
1435
- }
1436
-
1437
- # Resolve a piped file in the PRODUCER's directory, which can differ from the
1438
- # interpreter's after a subshell closes. Preserve unknown-state provenance too.
1439
- follow_pipe_target() {
1440
- local saved_cwd="$follow_cwd" saved_unknown="$follow_cwd_unknown"
1441
- follow_cwd="$3"
1442
- follow_cwd_unknown="$4"
1443
- follow_target "$1" "$2"
1444
- follow_cwd="$saved_cwd"
1445
- follow_cwd_unknown="$saved_unknown"
1446
- }
1447
-
1448
- # Carry branch uncertainty into sourced declarations as well as cwd changes.
1449
- # The local projection lasts only for this source invocation, not later scans.
1450
- follow_source_target() {
1451
- local follow_source_flow_unknown="$3"
1452
- follow_target "$1" "$2" source
1453
- }
1454
-
1455
- # Extract the literal -c operand without evaluating it or treating positional
1456
- # arguments after its closing quote as commands. Prefix indexing matches the
1457
- # whitespace tokens used by follow_scan; the operand keeps its internal bytes.
1458
- follow_inline() {
1459
- local stmt="$1" from="$2" depth="$3" body
1460
- local follow_inline_depth="${follow_inline_depth:-0}"
1461
- [ "$follow_inline_depth" -lt "$FOLLOW_MAX_FUNCTION_DEPTH" ] || follow_refuse "-c" "inline shells exceed the inspection depth"
1462
- follow_inline_depth=$((follow_inline_depth + 1))
1463
- body="$(LC_ALL=C SN_INLINE_TEXT="$stmt" SN_INLINE_FROM="$from" awk '
1464
- BEGIN {
1465
- s = ENVIRON["SN_INLINE_TEXT"]; n = length(s); i = 1;
1466
- for (word = 0; word < ENVIRON["SN_INLINE_FROM"]; word++) {
1467
- while (i <= n && substr(s, i, 1) ~ /[[:space:]]/) { i++ }
1468
- while (i <= n && substr(s, i, 1) !~ /[[:space:]]/) { i++ }
1469
- }
1470
- while (i <= n && substr(s, i, 1) ~ /[[:space:]]/) { i++ }
1471
- q = substr(s, i, 1);
1472
- if (q == "\047" || q == "\"") {
1473
- start = ++i; esc = 0;
1474
- for (; i <= n; i++) {
1475
- c = substr(s, i, 1);
1476
- if (esc) { esc = 0; continue }
1477
- if (c == "\\" && q == "\"") { esc = 1; continue }
1478
- if (c == q) {
1479
- # Adjacent quoted/unquoted fragments are the same shell operand.
1480
- # Refuse unsupported concatenation instead of scanning a prefix.
1481
- if (i < n && substr(s, i + 1, 1) !~ /[[:space:]]/) { exit 1 }
1482
- printf "%s", substr(s, start, i - start); exit;
1483
- }
1484
- }
1485
- exit 1;
1486
- }
1487
- start = i;
1488
- while (i <= n && substr(s, i, 1) !~ /[[:space:]]/) {
1489
- c = substr(s, i, 1);
1490
- if (c == "\047" || c == "\"" || c == "\\") { exit 1 }
1491
- i++;
1492
- }
1493
- printf "%s", substr(s, start, i - start);
1494
- }
1495
- ')" || follow_refuse "-c" "its command string could not be determined"
1496
- local saved_cwd="$follow_cwd" saved_unknown="$follow_cwd_unknown"
1497
- follow_scan "$body" "$depth"
1498
- follow_cwd="$saved_cwd"
1499
- follow_cwd_unknown="$saved_unknown"
1500
- }
1501
-
1502
- # Resolve literal descriptor duplication without running the proposed shell.
1503
- # Compound input is established before its body; output is projected when the
1504
- # producer reaches the pipe. Unknown descriptors refuse rather than drop bytes.
1505
- follow_redirect_io() {
1506
- local statement="$1" mode="$2" result
1507
- result="$(SN_COMPOUND_REDIRECT="$statement" SN_DESCRIPTOR_MAP="$follow_descriptor_map" SN_REDIRECT_CWD="$follow_cwd" SN_REDIRECT_UNKNOWN="$follow_cwd_unknown" python3 - "$mode" <<'PY'
1508
- import json
1509
- import os
1510
- import sys
1511
- try:
1512
- mode = sys.argv[1]
1513
- text = os.environ['SN_COMPOUND_REDIRECT']
1514
- tokens = []
1515
- cursor = 0
1516
- # Keep syntax provenance and byte adjacency: quoted/escaped > is data,
1517
- # and `cat 2 >&2` names a file rather than redirecting descriptor 2.
1518
- while cursor < len(text):
1519
- if text[cursor].isspace():
1520
- cursor += 1
1521
- continue
1522
- start = cursor
1523
- syntax = text[cursor] in '<>&'
1524
- plain = True
1525
- value = ''
1526
- quote = ''
1527
- if syntax:
1528
- while cursor < len(text) and text[cursor] in '<>&':
1529
- value += text[cursor]; cursor += 1
1530
- else:
1531
- while cursor < len(text):
1532
- char = text[cursor]
1533
- if not quote and (char.isspace() or char in '<>&'):
1534
- break
1535
- if char == '\\' and quote != "'":
1536
- plain = False
1537
- cursor += 1
1538
- if cursor == len(text):
1539
- raise ValueError('trailing escape')
1540
- if text[cursor] == '\n':
1541
- cursor += 1
1542
- continue
1543
- if quote == '"' and text[cursor] not in '$`"\\':
1544
- value += '\\'
1545
- value += text[cursor]; cursor += 1
1546
- continue
1547
- if char in ('"', "'"):
1548
- if not quote:
1549
- quote = char; plain = False; cursor += 1
1550
- continue
1551
- if quote == char:
1552
- quote = ''; cursor += 1
1553
- continue
1554
- value += char; cursor += 1
1555
- if quote:
1556
- raise ValueError('unterminated quote')
1557
- tokens.append((value, syntax, plain, start, cursor))
1558
- descriptors = {int(fd): value for fd, value in json.loads(os.environ['SN_DESCRIPTOR_MAP']).items()}
1559
- operators = ('<', '>', '>>', '<>', '<&', '>&', '&>', '&>>')
1560
- index = 0
1561
- while index < len(tokens):
1562
- fd = None
1563
- token, syntax, plain, start, end = tokens[index]
1564
- if token.isdigit() and plain and index + 1 < len(tokens) and tokens[index + 1][1] and end == tokens[index + 1][3]:
1565
- fd = int(token); index += 1
1566
- token, syntax, plain, start, end = tokens[index]
1567
- if not syntax or token not in operators:
1568
- if mode == 'cat':
1569
- index += 1
1570
- continue
1571
- sys.exit(2)
1572
- if index + 1 >= len(tokens):
1573
- sys.exit(2)
1574
- operator = token
1575
- operand, operand_syntax, _, _, _ = tokens[index + 1]
1576
- if operand_syntax:
1577
- sys.exit(2)
1578
- index += 2
1579
- if fd is None:
1580
- fd = 0 if operator.startswith('<') else 1
1581
- if operator in ('<&', '>&'):
1582
- if operand == '-':
1583
- descriptors[fd] = {'kind': 'closed'}
1584
- elif operand.isdigit():
1585
- descriptors[fd] = descriptors.get(int(operand), {'kind': 'unknown'})
1586
- else:
1587
- sys.exit(2)
1588
- else:
1589
- descriptors[fd] = {'kind': 'file', 'path': operand, 'cwd': os.environ['SN_REDIRECT_CWD'], 'unknown': int(os.environ['SN_REDIRECT_UNKNOWN'])}
1590
- if operator.startswith('&>'):
1591
- descriptors[2] = descriptors[fd]
1592
- output = descriptors[1]['kind']
1593
- if output == 'unknown' or descriptors[0]['kind'] == 'unknown':
1594
- sys.exit(2)
1595
- print(json.dumps({'input': descriptors[0], 'output': output, 'descriptors': descriptors}))
1596
- except (ValueError, OSError):
1597
- sys.exit(2)
1598
- PY
1599
- )" || follow_refuse "compound redirection" "its input or pipeline output could not be determined"
1600
- follow_redirect_input="$(printf '%s' "$result" | jq -er '.input.kind')" || follow_refuse "compound redirection" "invalid input projection"
1601
- follow_redirect_path="$(printf '%s' "$result" | jq -r '.input.path // ""')" || follow_refuse "compound redirection" "invalid input path"
1602
- follow_redirect_map="$(printf '%s' "$result" | jq -ce '.descriptors')" || follow_refuse "compound redirection" "invalid descriptor projection"
1603
- follow_redirect_input_cwd="$(printf '%s' "$result" | jq -r '.input.cwd // ""')" || follow_refuse "compound redirection" "invalid input cwd"
1604
- follow_redirect_input_unknown="$(printf '%s' "$result" | jq -r '.input.unknown // 1')" || follow_refuse "compound redirection" "invalid input uncertainty"
1605
- follow_redirect_output="$(printf '%s' "$result" | jq -er '.output')" || follow_refuse "compound redirection" "invalid output projection"
1606
- }
1607
-
1608
- # Enter a compound command (`if`, `while`/`until`/`for`/`select`, `case`).
1609
- #
1610
- # Reaching anything inside it depends on runtime flow, so a definition there is
1611
- # conditional. The enclosing flow state is saved so the matching closer can put
1612
- # it back: a compound that has CLOSED no longer decides whether the next
1613
- # top-level definition runs. Leaving the flag raised past the closer marked
1614
- # every function defined after any loop or case as conditional, which refused
1615
- # every Gradle-generated start script (CodySwannGT/lisa#4470). Brace groups
1616
- # already restore this way through brace_flows.
1617
- #
1618
- # These read and write follow_scan's locals through bash's dynamic scoping.
1619
- follow_compound_open() {
1620
- local frame_scope=$scope_depth
1621
- # A pipeline element is its own scope, but `if a | b; then` and
1622
- # `x | while read l; do` open their compound at the ENCLOSING level.
1623
- if [ "$scope_depth" -gt 0 ]; then
1624
- case "${scope_kinds[scope_depth - 1]}" in '+' | '|' | '|+') frame_scope=$((scope_depth - 1)) ;; esac
1625
- fi
1626
- compound_flows[compound_depth]=$function_flow_unknown
1627
- compound_kinds[compound_depth]="$1"
1628
- compound_frame_scopes[compound_depth]=$frame_scope
1629
- compound_opened_at="$compound_opened_at${i:-} "
1630
- compound_depth=$((compound_depth + 1))
1631
- function_flow_unknown=1
1632
- }
1633
-
1634
- # Close the innermost compound, restoring the flow state that encloses it.
1635
- #
1636
- # Only a closer of the SAME kind as the innermost open compound may lower the
1637
- # flag. The walker splits text, it does not parse shell: a comment's `;` or a
1638
- # heredoc payload line can reach it as a `fi`/`done` statement. A closer that
1639
- # matches nothing, or arrives after a heredoc (see compound_trusted), proves the
1640
- # walk has lost the structure, so every later closer keeps the flag where it is
1641
- # — the verdict this walker gave before closers restored anything.
1642
- #
1643
- # A conditional `return` inside the compound can skip whatever follows it in a
1644
- # function body or sourced file, so it re-raises the flag, as H does for a brace
1645
- # group. `break`/`continue` resume at or inside the loop, so they never skip a
1646
- # definition after `done`, and `exit` ends the shell before any later call runs:
1647
- # neither needs to persist past the closer. A `break` inside a function body
1648
- # can end the CALLER's loop and skip the rest of that body, but such a call only
1649
- # has that effect when the call itself sits inside a loop body, which is
1650
- # already conditional.
1651
- #
1652
- # The closer must also sit in the scope its compound opened in: a `done` inside
1653
- # a command substitution (`$( … )` or backticks) is a different shell's syntax
1654
- # error, not the end of this loop. The one cross-scope closer is `done | cmd`,
1655
- # whose `done` is the first element of a pipeline. Callers pass only a closer
1656
- # spelled as the bare first word of its statement; see the fi/done arm.
1657
- follow_compound_close() {
1658
- local frame_scope
1659
- if [ "$compound_trusted" -eq 0 ] || [ "$compound_depth" -eq 0 ] \
1660
- || [ "${compound_kinds[compound_depth - 1]}" != "$1" ]; then
1661
- compound_trusted=0
1662
- return 0
1663
- fi
1664
- frame_scope="${compound_frame_scopes[compound_depth - 1]}"
1665
- if [ "$scope_depth" -ne "$frame_scope" ]; then
1666
- case "$((scope_depth - frame_scope)):${scope_kinds[scope_depth - 1]}" in
1667
- '1:+' | '1:|' | '1:|+') ;;
1668
- *)
1669
- compound_trusted=0
1670
- return 0
1671
- ;;
1672
- esac
1673
- fi
1674
- compound_depth=$((compound_depth - 1))
1675
- function_flow_unknown="${compound_flows[compound_depth]}"
1676
- if [ "$return_flow_unknown" -ne 0 ]; then function_flow_unknown=1; fi
1677
- }
1678
-
1679
- # Walk one text for the files it executes. Runs in the PARENT shell, never in a
1680
- # command substitution: follow_refuse() must be able to deny, and an exit inside
1681
- # a subshell ends that subshell rather than this hook — the mistake documented
1682
- # on the rm segmentation below.
1683
- follow_scan() {
1684
- local text="$1" depth="$2"
1685
- local function_call_depth="${3:-0}"
1686
- local authenticated_bootstrap="${4:-0}"
1687
- local invocation_kind="${5:-child}"
1688
- local function_flow_unknown="${6:-0}" function_lookup_allowed statement_conditional function_conditional=0
1689
- local and_cwd="" and_unknown=1 and_ready=0 join_cwd join_unknown
1690
- if [ "$invocation_kind" = source ]; then
1691
- function_flow_unknown="${follow_source_flow_unknown:-0}"
1692
- fi
1693
- local return_scope_depth=-1
1694
- local return_list_depth=-1
1695
- local return_flow_unknown=0
1696
- local list_depth=0 list_index
1697
- local split_out line sep stmt t tj i j n cmd_pos eval_mode inline arg_exec
1698
- local heredoc redirected pipe_cat prev_cat pending_operand stdin_mode
1699
- local pipe_cwd pipe_unknown prev_cwd prev_unknown
1700
- local follow_stdin_cat="${follow_stdin_cat:-}" follow_stdin_cwd="${follow_stdin_cwd:-}" follow_stdin_unknown="${follow_stdin_unknown:-1}"
1701
- local follow_redirect_input follow_redirect_path follow_redirect_output follow_redirect_map follow_redirect_input_cwd follow_redirect_input_unknown
1702
- local follow_descriptor_map="${follow_descriptor_map:-}"
1703
- if [ -z "$follow_descriptor_map" ]; then
1704
- follow_descriptor_map='{"0":{"kind":"input"},"1":{"kind":"pipe"},"2":{"kind":"stderr"}}'
1705
- fi
1706
- local find_mode dispatch_pending
1707
- local scope_depth=0 case_depth=0 function_name="" function_body="" function_index function_found
1708
- local -a toks=()
1709
- local -a cwd_scopes=() unknown_scopes=() cat_scopes=() cat_cwd_scopes=() cat_unknown_scopes=() function_scopes=() flow_scopes=() return_flows=()
1710
- local -a list_cwds=() list_unknowns=() list_functions=() list_flows=() list_asyncs=() list_scope_depths=() list_return_flows=() brace_flows=()
1711
- local -a brace_descriptor_maps=() scope_descriptor_maps=()
1712
- local -a brace_stdin_cats=() brace_stdin_cwds=() brace_stdin_unknowns=() scope_stdin_cats=() scope_stdin_cwds=() scope_stdin_unknowns=()
1713
- local -a case_cwds=() case_unknowns=() case_changes=()
1714
- # Open compound commands of THIS text, innermost last. See
1715
- # follow_compound_open. The stack starts empty, so a closer can never lower
1716
- # the flag below the value this scan was entered with.
1717
- local compound_depth=0 compound_trusted=1 compound_opened_at=" " compound_prev
1718
- local -a compound_flows=() compound_kinds=() compound_scopes=() compound_frame_scopes=() scope_kinds=()
1719
- # The split treats every [[:space:]] byte as a blank, but bash separates words
1720
- # only on space and tab (and ends a command on newline). A form feed,
1721
- # vertical tab or carriage return is an ordinary word byte to bash, so
1722
- # `<FF>done` is a command name there and a bare closer here. With none of the
1723
- # three present, every [[:space:]] the split tests is a bash blank or a
1724
- # newline, so this one check covers each such test in the split.
1725
- case "$text" in *$'\f'* | *$'\v'* | *$'\r'*) compound_trusted=0 ;; esac
1726
- if [ "$function_call_depth" -eq 0 ] && [ "$invocation_kind" != source ]; then
1727
- # Ordinary child shells do not inherit unexported functions. Sourcing and
1728
- # function calls share the caller's definitions instead.
1729
- local function_count=0
1730
- local -a function_names=() function_bodies=() function_uncertainties=()
1731
- fi
1732
- split_out="$(follow_split "$text")" || follow_refuse "shell scope" "scope parsing exceeds the inspection budget"
1733
- prev_cat=""
1734
- while IFS= read -r line; do
1735
- sep="${line%%$'\t'*}"
1736
- stmt="${line#*$'\t'}"
1737
- statement_conditional=0
1738
- case "$sep" in '&' | '?') statement_conditional=1 ;; esac
1739
- # A heredoc payload reaches this walk as statements, so a payload line can
1740
- # spell a closer. Once one starts, closers stop restoring flow for the rest
1741
- # of this text. Checked before any skip so an unread payload still counts.
1742
- # A here-string (`<<<`) carries no payload lines.
1743
- # The same test also matches an arithmetic shift such as `$((1 << 2))`.
1744
- # That only withholds a restore, which is the safe direction.
1745
- case "${stmt//<<</}" in *'<<'*) compound_trusted=0 ;; esac
1746
- if [ "$sep" = U ]; then compound_trusted=0; continue; fi
1747
- # A reached && successor observes the preceding successful command's cwd.
1748
- # Scope/list events invalidate this projection; it must never carry a
1749
- # child's or a background list's directory into another shell/list.
1750
- case "$sep" in
1751
- L | G | H | B | N | F | C | A | K | '(' | '[' | ')' | ']') and_ready=0 ;;
1752
- esac
1753
- if [ "$return_list_depth" -ge 0 ]; then
1754
- case "$sep" in
1755
- B) [ "$list_depth" -eq "$return_list_depth" ] || continue ;;
1756
- '(' | '[' | ')' | ']' | G | H) ;;
1757
- *) continue ;;
1758
- esac
1759
- fi
1760
- if [ "$return_scope_depth" -ge 0 ]; then
1761
- # A return in a child scope ends that child, not its enclosing function.
1762
- # Keep only scope events until the matching close restores the parent.
1763
- case "$sep" in '(' | '[' | ')' | ']' | G | H) ;; *) continue ;; esac
1764
- fi
1765
- case "$sep" in
1766
- L)
1767
- list_cwds[list_depth]="$follow_cwd"
1768
- list_unknowns[list_depth]="$follow_cwd_unknown"
1769
- list_functions[list_depth]=$function_count
1770
- list_flows[list_depth]=$function_flow_unknown
1771
- list_asyncs[list_depth]="$stmt"
1772
- list_scope_depths[list_depth]=$scope_depth
1773
- list_return_flows[list_depth]=$return_flow_unknown
1774
- continue
1775
- ;;
1776
- G)
1777
- brace_flows[list_depth]=$function_flow_unknown
1778
- brace_descriptor_maps[list_depth]="$follow_descriptor_map"
1779
- brace_stdin_cats[list_depth]="$follow_stdin_cat"
1780
- brace_stdin_cwds[list_depth]="$follow_stdin_cwd"
1781
- brace_stdin_unknowns[list_depth]="$follow_stdin_unknown"
1782
- if [ "$stmt" = "|" ]; then
1783
- follow_stdin_cat="$prev_cat"; follow_stdin_cwd="${prev_cwd:-}"; follow_stdin_unknown="${prev_unknown:-1}"
1784
- fi
1785
- case "$stmt" in '&' | '?') function_flow_unknown=1 ;; esac
1786
- list_depth=$((list_depth + 1)); continue
1787
- ;;
1788
- H)
1789
- list_depth=$((list_depth - 1))
1790
- function_flow_unknown="${brace_flows[list_depth]}"
1791
- follow_descriptor_map="${brace_descriptor_maps[list_depth]}"
1792
- follow_stdin_cat="${brace_stdin_cats[list_depth]}"
1793
- follow_stdin_cwd="${brace_stdin_cwds[list_depth]}"
1794
- follow_stdin_unknown="${brace_stdin_unknowns[list_depth]}"
1795
- # A conditional return may exit this function/source before commands
1796
- # after the brace. Unlike a child return, that uncertainty persists.
1797
- if [ "$return_flow_unknown" -ne 0 ]; then function_flow_unknown=1; fi
1798
- continue
1799
- ;;
1800
- B)
1801
- # A single & runs the whole AND/OR list asynchronously. Its cwd and
1802
- # definitions cannot escape into the parent's next list.
1803
- follow_cwd="${list_cwds[list_depth]}"
1804
- follow_cwd_unknown="${list_unknowns[list_depth]}"
1805
- function_flow_unknown="${list_flows[list_depth]}"
1806
- return_flow_unknown="${list_return_flows[list_depth]}"
1807
- return_list_depth=-1
1808
- while [ "$function_count" -gt "${list_functions[list_depth]}" ]; do
1809
- function_count=$((function_count - 1))
1810
- function_index=$function_count
1811
- unset 'function_names[function_index]' 'function_bodies[function_index]' 'function_uncertainties[function_index]'
1812
- done
1813
- continue
1814
- ;;
1815
- N)
1816
- function_name="${stmt#*$'\t'}"; function_body=""
1817
- function_conditional="$function_flow_unknown"
1818
- case "${stmt%%$'\t'*}" in '&' | '?') function_conditional=1 ;; esac
1819
- continue
1820
- ;;
1821
- D)
1822
- if [ "$authenticated_bootstrap" -eq 0 ]; then
1823
- function_body="$function_body$stmt"$'\n'
1824
- fi
1825
- continue
1826
- ;;
1827
- F)
1828
- [ "$authenticated_bootstrap" -eq 0 ] || continue
1829
- function_index=$function_count
1830
- function_names[function_index]="$function_name"
1831
- function_bodies[function_index]="$function_body"
1832
- function_uncertainties[function_index]="$function_conditional"
1833
- function_count=$((function_count + 1))
1834
- continue
1835
- ;;
1836
- C)
1837
- follow_compound_open case
1838
- case_cwds[case_depth]="$follow_cwd"
1839
- case_unknowns[case_depth]="$follow_cwd_unknown"
1840
- case_changes[case_depth]=0
1841
- case_depth=$((case_depth + 1))
1842
- continue
1843
- ;;
1844
- A | K)
1845
- function_index=$((case_depth - 1))
1846
- if [ "$follow_cwd" != "${case_cwds[function_index]}" ] || [ "$follow_cwd_unknown" != "${case_unknowns[function_index]}" ]; then
1847
- case_changes[function_index]=1
1848
- fi
1849
- follow_cwd="${case_cwds[function_index]}"
1850
- follow_cwd_unknown="${case_unknowns[function_index]}"
1851
- if [ "$sep" = K ]; then
1852
- if [ "${case_changes[function_index]}" -ne 0 ]; then
1853
- follow_cwd=""; follow_cwd_unknown=1
1854
- fi
1855
- case_depth=$((case_depth - 1))
1856
- # K closes the case; the literal `esac` statement the split emits
1857
- # after it is not a closer and must not close another frame.
1858
- follow_compound_close case
1859
- fi
1860
- continue
1861
- ;;
1862
- '(' | '[')
1863
- cwd_scopes[scope_depth]="$follow_cwd"
1864
- unknown_scopes[scope_depth]="$follow_cwd_unknown"
1865
- cat_scopes[scope_depth]="$prev_cat"
1866
- cat_cwd_scopes[scope_depth]="${prev_cwd:-}"
1867
- cat_unknown_scopes[scope_depth]="${prev_unknown:-1}"
1868
- scope_descriptor_maps[scope_depth]="$follow_descriptor_map"
1869
- function_scopes[scope_depth]=$function_count
1870
- flow_scopes[scope_depth]=$function_flow_unknown
1871
- compound_scopes[scope_depth]=$compound_depth
1872
- # `[` is a substitution; for `(` the split's tail says whether this is
1873
- # a pipeline element (`+`, `|`, `|+`) or a literal subshell.
1874
- if [ "$sep" = '[' ]; then scope_kinds[scope_depth]='['; else scope_kinds[scope_depth]="$stmt"; fi
1875
- return_flows[scope_depth]=$return_flow_unknown
1876
- scope_stdin_cats[scope_depth]="$follow_stdin_cat"
1877
- scope_stdin_cwds[scope_depth]="$follow_stdin_cwd"
1878
- scope_stdin_unknowns[scope_depth]="$follow_stdin_unknown"
1879
- if [ "$stmt" = "|" ] || [ "$stmt" = "|+" ]; then
1880
- follow_stdin_cat="$prev_cat"; follow_stdin_cwd="${prev_cwd:-}"; follow_stdin_unknown="${prev_unknown:-1}"
1881
- follow_descriptor_map="$(printf '%s' "$follow_descriptor_map" | jq -ce '.["0"] = {kind:"input"}')" || follow_refuse "pipeline input" "its descriptor could not be established"
1882
- fi
1883
- case "$stmt" in
1884
- *+)
1885
- follow_descriptor_map="$(printf '%s' "$follow_descriptor_map" | jq -ce '.["1"] = {kind:"pipe"}')" || follow_refuse "pipeline output" "its descriptor could not be established"
1886
- ;;
1887
- esac
1888
- scope_depth=$((scope_depth + 1))
1889
- list_depth=$((list_depth + 1))
1890
- continue
1891
- ;;
1892
- ')' | ']')
1893
- scope_depth=$((scope_depth - 1))
1894
- list_depth=$((list_depth - 1))
1895
- follow_cwd="${cwd_scopes[scope_depth]}"
1896
- follow_descriptor_map="${scope_descriptor_maps[scope_depth]}"
1897
- follow_cwd_unknown="${unknown_scopes[scope_depth]}"
1898
- function_flow_unknown="${flow_scopes[scope_depth]}"
1899
- return_flow_unknown="${return_flows[scope_depth]}"
1900
- # A pipeline element is a scope of its own, so `done | cmd` closes, in
1901
- # here, a loop opened outside. The scope must not undo that closer: the
1902
- # flow after the pipeline is the one the loop's frame saved. The stack
1903
- # itself is never rewound here. `if a | b; then` opens its `if` inside
1904
- # the first element, and discarding that frame would let the `fi` close
1905
- # an ENCLOSING compound instead.
1906
- if [ "$compound_depth" -lt "${compound_scopes[scope_depth]}" ]; then
1907
- function_flow_unknown="${compound_flows[compound_depth]}"
1908
- if [ "$return_flow_unknown" -ne 0 ]; then function_flow_unknown=1; fi
1909
- fi
1910
- follow_stdin_cat="${scope_stdin_cats[scope_depth]}"
1911
- follow_stdin_cwd="${scope_stdin_cwds[scope_depth]}"
1912
- follow_stdin_unknown="${scope_stdin_unknowns[scope_depth]}"
1913
- while [ "$function_count" -gt "${function_scopes[scope_depth]}" ]; do
1914
- function_count=$((function_count - 1))
1915
- function_index=$function_count
1916
- unset 'function_names[function_index]' 'function_bodies[function_index]' 'function_uncertainties[function_index]'
1917
- done
1918
- if [ "$sep" = ']' ]; then
1919
- prev_cat="${cat_scopes[scope_depth]}"
1920
- prev_cwd="${cat_cwd_scopes[scope_depth]}"
1921
- prev_unknown="${cat_unknown_scopes[scope_depth]}"
1922
- fi
1923
- if [ "$return_scope_depth" -ge 0 ] && [ "$scope_depth" -lt "$return_scope_depth" ]; then
1924
- return_scope_depth=-1
1925
- fi
1926
- continue
1927
- ;;
1928
- I)
1929
- follow_redirect_io "$stmt" compound
1930
- follow_descriptor_map="$follow_redirect_map"
1931
- case "$follow_redirect_input" in
1932
- file)
1933
- follow_stdin_cat="$follow_redirect_path"
1934
- follow_stdin_cwd="$follow_redirect_input_cwd"; follow_stdin_unknown="$follow_redirect_input_unknown"
1935
- ;;
1936
- closed) follow_stdin_cat="" ;;
1937
- input) ;;
1938
- *) follow_refuse "compound redirection" "its input source could not be determined" ;;
1939
- esac
1940
- continue
1941
- ;;
1942
- R)
1943
- # The whole compound tail was applied before its body by I. Its cat
1944
- # producer already records whether its effective output reaches pipe.
1945
- continue
1946
- ;;
1947
- esac
1948
- join_cwd="$follow_cwd"; join_unknown="$follow_cwd_unknown"
1949
- if [ "$sep" = '&' ] && [ "$and_ready" -eq 1 ]; then
1950
- follow_cwd="$and_cwd"; follow_cwd_unknown="$and_unknown"
1951
- fi
1952
- and_ready=0
1953
- pipe_cat="$follow_stdin_cat"
1954
- pipe_cwd="$follow_stdin_cwd"
1955
- pipe_unknown="$follow_stdin_unknown"
1956
- if [ "$sep" = "|" ]; then
1957
- pipe_cat="$prev_cat"
1958
- pipe_cwd="${prev_cwd:-}"
1959
- pipe_unknown="${prev_unknown:-1}"
1960
- fi
1961
- prev_cat=""
1962
- case "$stmt" in
1963
- *[![:space:]]*) ;;
1964
- *) continue ;;
1965
- esac
1966
- set -f
1967
- # The word split is the point: this is shell tokenization, and the glob
1968
- # guard above keeps a literal `*` from expanding against the hook's cwd.
1969
- # shellcheck disable=SC2206
1970
- toks=($stmt)
1971
- set +f
1972
- n=${#toks[@]}
1973
- [ "$n" -gt 0 ] || continue
1974
- i=0
1975
- compound_opened_at=" "
1976
- cmd_pos=1
1977
- function_lookup_allowed=1
1978
- eval_mode=0
1979
- arg_exec=0
1980
- pending_operand=0
1981
- find_mode=0
1982
- dispatch_pending=0
1983
- while [ "$i" -lt "$n" ]; do
1984
- # Only a COMMAND POSITION can execute something. A path anywhere else is
1985
- # an argument, and an argument is data (#3604).
1986
- #
1987
- # The one exception is a dispatcher that BUILDS a command out of its own
1988
- # arguments: `find … -exec bash {} \;` and `xargs bash` put an interpreter
1989
- # at a command position the text does not spell as one. Scoping the
1990
- # exception to a `find`/`xargs` statement is what keeps it from becoming
1991
- # "an interpreter name anywhere is an invocation", which would read
1992
- # `echo "run bash <file>"` as one.
1993
- if [ "$cmd_pos" -ne 1 ]; then
1994
- # A dispatcher BUILDS a command out of its own arguments, putting an
1995
- # interpreter at a command position the text does not spell as one.
1996
- # That position is exactly ONE token: the word after `find -exec` or
1997
- # `-execdir`, and the first operand of `xargs`.
1998
- #
1999
- # Latching "any interpreter NAME until the statement ends" instead was
2000
- # a false positive, because an interpreter name is far more often data
2001
- # than a command: it refused `find . -name bash`, where `bash` is a
2002
- # filename PATTERN, and `find … | xargs grep bash`, where it is a
2003
- # search term. Both are ordinary commands that delete nothing.
2004
- if [ "$dispatch_pending" -ne 1 ]; then
2005
- if [ "$find_mode" -eq 1 ]; then
2006
- follow_unwrap "${toks[i]}"
2007
- case "$follow_unwrapped" in
2008
- -exec | -execdir) dispatch_pending=1 ;;
2009
- esac
2010
- fi
2011
- i=$((i + 1))
2012
- continue
2013
- fi
2014
- follow_unwrap "${toks[i]}"
2015
- t="$follow_unwrapped"
2016
- # `xargs -n1 bash` — the dispatcher's own options precede its command.
2017
- case "$t" in
2018
- -*)
2019
- i=$((i + 1))
2020
- continue
2021
- ;;
2022
- esac
2023
- dispatch_pending=0
2024
- cmd_pos=1
2025
- else
2026
- follow_unwrap "${toks[i]}"
2027
- t="$follow_unwrapped"
2028
- fi
2029
- function_found=0
2030
- for ((function_index = function_count - 1; function_lookup_allowed && function_index >= 0; function_index--)); do
2031
- if [ "$t" = "${function_names[function_index]}" ]; then
2032
- [ "${function_uncertainties[function_index]}" -eq 0 ] || follow_refuse "$t" "its function definition is conditional"
2033
- # Calls execute in this shell and do not consume a file-follow depth.
2034
- # A separate bound refuses recursion without truncating the body.
2035
- [ "$function_call_depth" -lt "$FOLLOW_MAX_FUNCTION_DEPTH" ] || follow_refuse "$t" "function calls exceed the inspection depth"
2036
- follow_function_calls=$((follow_function_calls + 1))
2037
- follow_function_bytes=$((follow_function_bytes + ${#function_bodies[function_index]}))
2038
- if [ "$follow_function_calls" -gt "$FOLLOW_MAX_FUNCTION_CALLS" ] || [ "$follow_function_bytes" -gt "$FOLLOW_MAX_TOTAL_BYTES" ]; then
2039
- follow_refuse "$t" "function expansion exceeds the inspection budget"
2040
- fi
2041
- local call_cwd="$follow_cwd" call_unknown="$follow_cwd_unknown"
2042
- follow_scan "${function_bodies[function_index]}" "$depth" "$((function_call_depth + 1))" 0 child "$((function_flow_unknown || statement_conditional))"
2043
- if { [ "$function_flow_unknown" -ne 0 ] || [ "$statement_conditional" -ne 0 ]; } && { [ "$follow_cwd" != "$call_cwd" ] || [ "$follow_cwd_unknown" != "$call_unknown" ]; }; then
2044
- follow_cwd=""; follow_cwd_unknown=1
2045
- fi
2046
- function_found=1
2047
- break
2048
- fi
2049
- done
2050
- if [ "$function_found" -eq 1 ]; then
2051
- cmd_pos=0; i=$((i + 1)); continue
2052
- fi
2053
- case "$t" in
2054
- return)
2055
- if [ "$statement_conditional" -ne 0 ]; then function_flow_unknown=1; fi
2056
- if { [ "$function_call_depth" -gt 0 ] || [ "$invocation_kind" = source ]; } && [ "$function_flow_unknown" -ne 0 ]; then
2057
- return_flow_unknown=1
2058
- fi
2059
- if { [ "$function_call_depth" -gt 0 ] || [ "$invocation_kind" = source ]; } && [ "$function_flow_unknown" -eq 0 ]; then
2060
- # Ordinary braces share the shell but have distinct list frames.
2061
- # A surrounding background brace list ends only its child; do not
2062
- # cross a literal subshell boundary while finding that parent list.
2063
- for ((list_index = list_depth; list_index >= 0; list_index--)); do
2064
- [ "${list_scope_depths[list_index]}" -eq "$scope_depth" ] || break
2065
- if [ "${list_asyncs[list_index]}" -ne 0 ]; then
2066
- return_list_depth="$list_index"
2067
- break
2068
- fi
2069
- done
2070
- if [ "$return_list_depth" -ge 0 ]; then
2071
- :
2072
- elif [ "$scope_depth" -eq 0 ]; then
2073
- return 0
2074
- else
2075
- return_scope_depth="$scope_depth"
2076
- fi
2077
- fi
2078
- cmd_pos=0; i=$((i + 1)); continue
2079
- ;;
2080
- if)
2081
- follow_compound_open if
2082
- i=$((i + 1)); continue
2083
- ;;
2084
- while | until)
2085
- follow_compound_open loop
2086
- i=$((i + 1)); continue
2087
- ;;
2088
- for | select)
2089
- follow_compound_open loop
2090
- cmd_pos=0; i=$((i + 1)); continue
2091
- ;;
2092
- # A closer counts only as the bare, unquoted FIRST word of its
2093
- # statement. Anything else that unwraps to one — `"done"`, `\fi`,
2094
- # `x=1 done`, `eval done`, `command done`, the tail of `x='a; fi'` — is
2095
- # not a reserved word to the shell, so its appearance means the walk
2096
- # cannot prove where compounds end. A literal `esac` statement follows
2097
- # every K record and is harmless in that one spelling.
2098
- 'fi' | 'done' | 'esac')
2099
- if [ "$i" -ne 0 ] || [ "${toks[0]}" != "$t" ]; then
2100
- compound_trusted=0
2101
- elif [ "$t" = 'fi' ]; then
2102
- follow_compound_close if
2103
- elif [ "$t" = 'done' ]; then
2104
- follow_compound_close loop
2105
- fi
2106
- cmd_pos=0; i=$((i + 1)); continue
2107
- ;;
2108
- # Prefixes that keep the command position open: assignments, wrappers,
2109
- # and the shell keywords a statement can start with. Without them
2110
- # `if …; then bash <file>` and `env bash <file>` walk past the
2111
- # invocation.
2112
- "" | [A-Za-z_]*=* | --*) i=$((i + 1)); continue ;;
2113
- -*)
2114
- # A SHORT option inside a wrapper prefix can take a separate VALUE,
2115
- # and that value is not a command. `nice -n 5 bash <file>` and
2116
- # `sudo -u nobody bash <file>` put `5` and `nobody` where the walk
2117
- # expected the program, so the invocation was never reached and the
2118
- # file was never scanned — the same fail-open this whole block exists
2119
- # to close, one layer along. Step the value over.
2120
- #
2121
- # But YIELD whenever the next token could itself be the invocation,
2122
- # so `env -i bash <file>` still reads `bash` as the program: `-i`
2123
- # takes no value, and consuming one would lose the interpreter.
2124
- #
2125
- # Long options are deliberately left alone. Their value is spelled
2126
- # with `=`, and a `--foo <path> bash <file>` is rare enough that
2127
- # consuming the operand would cost more than it buys.
2128
- i=$((i + 1))
2129
- if [ "$i" -lt "$n" ]; then
2130
- follow_unwrap "${toks[i]}"
2131
- follow_may_invoke "$follow_unwrapped" || i=$((i + 1))
2132
- fi
2133
- continue
2134
- ;;
2135
- timeout | */timeout)
2136
- # `timeout` takes a mandatory DURATION before the program. A bare
2137
- # number is not an option, so the short-option arm above cannot see
2138
- # it. Mark the operand pending and let the fall-through consume it,
2139
- # which keeps working when options sit in between — `timeout -s KILL
2140
- # 5 bash <file>` reaches `bash` just as `timeout 5 bash <file>` does.
2141
- pending_operand=1
2142
- function_lookup_allowed=0
2143
- i=$((i + 1))
2144
- continue
2145
- ;;
2146
- sudo | env | command | exec | nohup | nice | time | builtin \
2147
- | do | then | else | elif | '!' | '{' \
2148
- | */sudo | */env | */nohup | */nice | */time)
2149
- case "$t" in
2150
- sudo | env | command | exec | nohup | nice | builtin | */sudo | */env | */nohup | */nice) function_lookup_allowed=0 ;;
2151
- # `elif` starts a condition list at a command position, so an
2152
- # opener after it is a real compound (`elif if x; then …; fi`).
2153
- do | then | else | elif) function_flow_unknown=1 ;;
2154
- esac
2155
- i=$((i + 1))
2156
- continue
2157
- ;;
2158
- eval)
2159
- # `eval` executes its ARGUMENTS as shell, so a file whose contents are
2160
- # interpolated into them is executed text.
2161
- eval_mode=1
2162
- i=$((i + 1))
2163
- continue
2164
- ;;
2165
- find | */find)
2166
- # `find` only builds a command after `-exec`/`-execdir`. Every other
2167
- # operand is a path, a predicate, or a pattern.
2168
- arg_exec=1
2169
- find_mode=1
2170
- cmd_pos=0
2171
- i=$((i + 1))
2172
- continue
2173
- ;;
2174
- xargs | */xargs)
2175
- # `xargs` takes its command as the first non-option operand; anything
2176
- # after that is an argument TO that command, not another command.
2177
- arg_exec=1
2178
- dispatch_pending=1
2179
- cmd_pos=0
2180
- i=$((i + 1))
2181
- continue
2182
- ;;
2183
- cd)
2184
- if [ $((i + 1)) -lt "$n" ]; then
2185
- follow_unwrap "${toks[i + 1]}"
2186
- follow_cd "$follow_unwrapped"
2187
- else
2188
- # A bare `cd` is `cd "$HOME"`, and leaving the previous directory in
2189
- # place would resolve later tokens from a directory the shell left.
2190
- follow_cd "${HOME:-}"
2191
- fi
2192
- if [ "$function_flow_unknown" -ne 0 ]; then
2193
- follow_cwd=""; follow_cwd_unknown=1
2194
- fi
2195
- cmd_pos=0
2196
- i=$((i + 1))
2197
- continue
2198
- ;;
2199
- source | .)
2200
- follow_next_operand "$i" "$n"
2201
- j="$follow_operand_index"
2202
- if [ "$j" -lt "$n" ]; then
2203
- follow_unwrap "${toks[j]}"
2204
- local source_cwd="$follow_cwd" source_unknown="$follow_cwd_unknown"
2205
- follow_source_target "$follow_unwrapped" "$depth" "$((function_flow_unknown || statement_conditional))"
2206
- if { [ "$function_flow_unknown" -ne 0 ] || [ "$statement_conditional" -ne 0 ]; } && { [ "$follow_cwd" != "$source_cwd" ] || [ "$follow_cwd_unknown" != "$source_unknown" ]; }; then
2207
- follow_cwd=""; follow_cwd_unknown=1
2208
- fi
2209
- fi
2210
- cmd_pos=0
2211
- i=$((j + 1))
2212
- continue
2213
- ;;
2214
- cat | '<')
2215
- follow_next_operand "$i" "$n"
2216
- j="$follow_operand_index"
2217
- follow_unwrapped=""
2218
- if [ "$j" -lt "$n" ]; then follow_unwrap "${toks[j]}"; fi
2219
- if [ "$t" = cat ] && { [ "$j" -ge "$n" ] || [ "$follow_unwrapped" = - ]; }; then
2220
- # Bare cat and cat - forward the group's named stdin unchanged.
2221
- prev_cat="$pipe_cat"; prev_cwd="$pipe_cwd"; prev_unknown="$pipe_unknown"
2222
- if [ "$eval_mode" -eq 1 ] && [ -n "$prev_cat" ]; then
2223
- follow_pipe_target "$prev_cat" "$depth" "$prev_cwd" "$prev_unknown"
2224
- fi
2225
- elif [ "$j" -lt "$n" ]; then
2226
- if [ "$eval_mode" -eq 1 ]; then
2227
- follow_target "$follow_unwrapped" "$depth"
2228
- else
2229
- # Not executed here — the pipe consumer decides whether the
2230
- # producer's file content becomes an executable shell input.
2231
- prev_cat="$follow_unwrapped"
2232
- prev_cwd="$follow_cwd"; prev_unknown="$follow_cwd_unknown"
2233
- fi
2234
- fi
2235
- if [ -n "$prev_cat" ] && [ "$eval_mode" -eq 0 ]; then
2236
- if [[ "$stmt" == *'>'* ]] || [ "$follow_descriptor_map" != '{"0":{"kind":"input"},"1":{"kind":"pipe"},"2":{"kind":"stderr"}}' ]; then
2237
- follow_redirect_io "$stmt" cat
2238
- case "$follow_redirect_output" in
2239
- pipe) ;;
2240
- file | closed | stderr | input) prev_cat="" ;;
2241
- *) follow_refuse "cat redirection" "its output destination could not be determined" ;;
2242
- esac
2243
- fi
2244
- fi
2245
- cmd_pos=0
2246
- i=$((j + 1))
2247
- continue
2248
- ;;
2249
- esac
2250
- if follow_is_interpreter "$t"; then
2251
- inline=0
2252
- redirected=""
2253
- heredoc=0
2254
- stdin_mode=0
2255
- noexec=0
2256
- j=$((i + 1))
2257
- while [ "$j" -lt "$n" ]; do
2258
- follow_unwrap "${toks[j]}"
2259
- tj="$follow_unwrapped"
2260
- case "$tj" in
2261
- --) j=$((j + 1)); break ;;
2262
- # A heredoc or here-string payload is IN the command text, which the
2263
- # guards already read. It is not a file, and treating it as one
2264
- # refused `bash <<EOF` outright.
2265
- '<<'*) heredoc=1; break ;;
2266
- # `bash < <file>` executes the file just as `bash <file>` does.
2267
- '<')
2268
- j=$((j + 1))
2269
- if [ "$j" -lt "$n" ]; then
2270
- follow_unwrap "${toks[j]}"
2271
- redirected="$follow_unwrapped"
2272
- fi
2273
- break
2274
- ;;
2275
- '<'*) redirected="${tj#<}"; break ;;
2276
- # An output redirection names a DESTINATION, never the script. Step
2277
- # over it (and its target when the operator stands alone) so the
2278
- # operand scan does not stop on `>` and read `/dev/null` as a
2279
- # script it cannot resolve.
2280
- *'>'*)
2281
- case "$tj" in
2282
- *'>') j=$((j + 2)) ;;
2283
- *) j=$((j + 1)) ;;
2284
- esac
2285
- ;;
2286
- # `-n` is NOEXEC: the shell reads and parses its operand, then exits
2287
- # without running a line of it. So a syntax check is the one shape
2288
- # that puts a path at a command position while provably executing
2289
- # nothing, and following it reads a file the command never runs.
2290
- #
2291
- # This guard hit that on ITSELF: its pattern list is destructive
2292
- # command literals living inside the guard, so `bash -n` on its own
2293
- # source was refused by its own patterns — and the same held for any
2294
- # file documenting destructive commands. See CodySwannGT/lisa#3803.
2295
- #
2296
- # `bash <file>` still executes and is still followed. Noexec is the
2297
- # distinction, not the program: this is not a read-only exemption.
2298
- --noexec) noexec=1; break ;;
2299
- --*) j=$((j + 1)) ;;
2300
- -*c*) inline=1; j=$((j + 1)) ;;
2301
- -*n*) noexec=1; break ;;
2302
- -s | -[a-zA-Z]*s[a-zA-Z]*) stdin_mode=1; j=$((j + 1)) ;;
2303
- -*) j=$((j + 1)) ;;
2304
- *) break ;;
2305
- esac
2306
- done
2307
- if [ "$noexec" -eq 1 ]; then
2308
- # Nothing runs, so there is no script to follow and nothing to fail
2309
- # closed about. Checked before the heredoc and dispatcher arms: those
2310
- # decide WHICH text to read, and here there is no execution at all.
2311
- cmd_pos=0
2312
- i=$((j + 1))
2313
- continue
2314
- fi
2315
- if [ "$heredoc" -eq 1 ] && [ "$inline" -eq 0 ]; then
2316
- cmd_pos=0
2317
- i=$((j + 1))
2318
- continue
2319
- fi
2320
- if [ -n "$redirected" ]; then
2321
- follow_target "$redirected" "$depth"
2322
- cmd_pos=0
2323
- i=$((j + 1))
2324
- continue
2325
- fi
2326
- if [ "$inline" -eq 1 ]; then
2327
- # The command string runs in a child shell. It gets its own function
2328
- # map and cwd effects; positional arguments are data, not commands.
2329
- follow_inline "$stmt" "$j" "$depth"
2330
- cmd_pos=0
2331
- i="$n"
2332
- continue
2333
- fi
2334
- if [ "$stdin_mode" -eq 1 ]; then
2335
- # `sh -s -- -y` reads its program from stdin; tokens after `--` are
2336
- # positional arguments to that program, never a script path.
2337
- [ -z "$pipe_cat" ] || follow_pipe_target "$pipe_cat" "$depth" "$pipe_cwd" "$pipe_unknown"
2338
- cmd_pos=0
2339
- i="$n"
2340
- continue
2341
- fi
2342
- if [ "$j" -ge "$n" ]; then
2343
- # A dispatcher supplies the script from ANOTHER command's output, so
2344
- # the operand exists but is unreadable here. That is the fail-closed
2345
- # case, not the interactive one.
2346
- if [ "$arg_exec" -eq 1 ]; then
2347
- follow_refuse "$t" "a dispatcher supplies its script from another command's output"
2348
- fi
2349
- # No operand: an interactive or stdin-fed interpreter. Only the
2350
- # `cat <file> | bash` shape names a FILE, and only that is followed.
2351
- [ -z "$pipe_cat" ] || follow_pipe_target "$pipe_cat" "$depth" "$pipe_cwd" "$pipe_unknown"
2352
- cmd_pos=0
2353
- i="$j"
2354
- continue
2355
- fi
2356
- follow_unwrap "${toks[j]}"
2357
- tj="$follow_unwrapped"
2358
- if ! follow_supervisor "$tj" "$depth" "$stmt"; then
2359
- follow_target "$tj" "$depth"
2360
- fi
2361
- cmd_pos=0
2362
- i=$((j + 1))
2363
- continue
2364
- fi
2365
- if [ "$pending_operand" -eq 1 ]; then
2366
- # A wrapper's own mandatory operand (a `timeout` duration), not the
2367
- # program it wraps. Consume it and leave the command position OPEN so
2368
- # the walk carries on to the invocation. Yields on anything that could
2369
- # itself be the program, for the reason follow_may_invoke documents.
2370
- pending_operand=0
2371
- if ! follow_may_invoke "$t"; then
2372
- i=$((i + 1))
2373
- continue
2374
- fi
2375
- fi
2376
- # The tilde arm is LITERAL text, not a path this line expands:
2377
- # follow_locate turns it into one.
2378
- # shellcheck disable=SC2088
2379
- case "$t" in
2380
- /* | ./* | ../* | '~/'* | */*) follow_direct "$t" "$depth" ;;
2381
- esac
2382
- cmd_pos=0
2383
- i=$((i + 1))
2384
- done
2385
- # Keep successful-branch provenance separate from the continuation join.
2386
- # OR can skip its RHS and still reach a following &&, so it cannot prove
2387
- # that RHS's cwd. A semicolon observes every possible preceding outcome.
2388
- # Every opener must have pushed a frame, or its own closer pops the
2389
- # ENCLOSING one and restores flow inside a compound that is still open.
2390
- # Bash reads a reserved word wherever a command may start, which this walk
2391
- # does not fully model: after `coproc NAME`, after a function header whose
2392
- # body is a bare compound (`f () while …`), or after `function NAME`. So an
2393
- # opener word the walk did not open stops all later restores unless the
2394
- # word before it is a plain argument (`echo if`, `# loops for x`), where
2395
- # bash reads it as data too. `case` never opens here (the split's C record
2396
- # does), so a statement-initial `case` means the split missed its `in`.
2397
- if [ "$compound_trusted" -ne 0 ]; then
2398
- for ((j = 0; j < n; j++)); do
2399
- case "${toks[j]}" in
2400
- coproc) compound_trusted=0 ;;
2401
- function) [ "$j" -ne 0 ] || compound_trusted=0 ;;
2402
- if | while | until | for | select | case)
2403
- case "$compound_opened_at" in *" $j "*) continue ;; esac
2404
- if [ "$j" -eq 0 ]; then
2405
- compound_trusted=0
2406
- else
2407
- compound_prev="${toks[j - 1]}"
2408
- case "$compound_prev" in
2409
- '' | *[!A-Za-z0-9_./,:=+@%-]* | elif | coproc | function | time | then | do | else)
2410
- compound_trusted=0
2411
- ;;
2412
- esac
2413
- fi
2414
- ;;
2415
- esac
2416
- [ "$compound_trusted" -ne 0 ] || break
2417
- done
2418
- fi
2419
- and_cwd="$follow_cwd"; and_unknown="$follow_cwd_unknown"
2420
- if [ "$sep" != '?' ] && [ "$function_flow_unknown" -eq 0 ]; then and_ready=1; fi
2421
- if [ "$statement_conditional" -ne 0 ] && { [ "$join_unknown" -ne 0 ] || [ "$follow_cwd_unknown" -ne 0 ] || [ "$follow_cwd" != "$join_cwd" ]; }; then
2422
- follow_cwd=""; follow_cwd_unknown=1
2423
- fi
2424
- done <<<"$split_out"
2425
- }
2426
-
2427
- follow_scan "$command_for_guards" 0
2428
- rm_command_for_guards="$command_for_guards"$'\n'"$followed_rm_text"
2429
- if [ -n "$follow_names" ]; then
2430
- command_for_guards="$command_for_guards"$'\n'"$followed_text"
2431
- # A refusal must say WHERE the match is. Without this the operator reads
2432
- # advice about rewording a quoted string for a line they never typed.
2433
- DESTRUCTIVE_GUIDANCE="$DESTRUCTIVE_GUIDANCE
2434
-
2435
- The match may be inside a file this command EXECUTES rather than in the command
2436
- you typed. These scripts were read and scanned as part of it:$follow_names
2437
- Edit the file, or ask the user to confirm and run it manually outside the agent."
2438
- fi
2439
-
2440
- # Normalize bash line-continuations (a trailing backslash + newline → space)
2441
- # before segmenting the command. Without this, "git push --force origin
2442
- # \<newline>main" splits into a segment matching --force but not `main`, letting a
2443
- # protected force-push slip past. Uses awk (POSIX) instead of a GNU-only
2444
- # `sed ':a;N;$!ba;…'`, which errors on BSD sed (macOS) and there silently no-ops.
2445
- normalized_command_str="$(printf '%s' "$command_for_guards" \
2446
- | awk '{ if (sub(/\\$/, "")) printf "%s ", $0; else print }')"
2447
- rm_normalized_command_str="$(printf '%s' "$rm_command_for_guards" \
2448
- | awk '{ if (sub(/\\$/, "")) printf "%s ", $0; else print }')"
2449
-
2450
- # matches / matches_cs run an ERE against the guarded command text. matches is
2451
- # case-insensitive (the default for these guards); matches_cs is case-SENSITIVE
2452
- # for guards where flag case is meaningful (`git branch -d` vs `-D`).
2453
- #
2454
- # Both read the NORMALIZED text. They used to read $command_for_guards, so only
2455
- # the two segment-walking guards (rm, git push) were protected against line
2456
- # continuations and every guard expressed through these helpers could be evaded
2457
- # by breaking the command across lines:
2458
- #
2459
- # git reset --hard \
2460
- # origin/main
2461
- #
2462
- # The patterns match on intermediate whitespace, and an embedded "\<newline>" is
2463
- # not whitespace to grep -E, so the anchor failed to span the break. Defined
2464
- # after the normalization above so the value exists when these are first called.
2465
- matches() {
2466
- scan -Ei "$normalized_command_str" "$1"
2467
- }
2468
- matches_cs() {
2469
- scan -E "$normalized_command_str" "$1"
2470
- }
2471
-
2472
- # Shared ERE fragments. GIT_TOKENS walks over intermediate argv tokens without
2473
- # crossing a statement separator, so a flag in a LATER statement can never be
2474
- # attributed to an earlier git subcommand.
2475
- readonly GIT_TOKENS='([[:space:]]+[^;&|[:space:]]+)*[[:space:]]+'
2476
- # Git GLOBAL options (`-C <path>`, `-c <k>=<v>`, `--git-dir[=…]`, `--no-pager`,
2477
- # …) legally sit between `git` and its subcommand, so every subcommand guard
2478
- # consumes them — otherwise `git -C /path checkout -- f` dodges the anchor
2479
- # (issue #1960 security review F1). Shape: zero or more dash-led tokens, each
2480
- # optionally followed by ONE non-dash value token, which covers both the
2481
- # `--git-dir=/x` and `--git-dir /x` spellings without naming every option.
2482
- readonly GIT_GLOBAL_OPTS='(-[^;&|[:space:]]+([[:space:]]+[^-;&|[:space:]][^;&|[:space:]]*)?[[:space:]]+)*'
2483
- # Anchor for every git subcommand guard: word-bounded `git`, whitespace, then
2484
- # any run of global options. Callers append the subcommand name directly.
2485
- readonly GIT_CMD='(^|[^[:alnum:]_-])git[[:space:]]+'"$GIT_GLOBAL_OPTS"
2486
- # An rm invocation: bare `rm` or a path whose basename is exactly `rm`
2487
- # (`/bin/rm`, `./rm`) — issue #1960 security review F2. The optional prefix must
2488
- # END IN `/` immediately before `rm`, so charm/confirm/informant/rmdir never
2489
- # match. The preceding-char class still excludes `.`, `/`, and `-` to keep
2490
- # `--rm`-style flags and `foo.rm` names out.
2491
- readonly RM_CMD='(^|[^[:alnum:]_./-])([[:alnum:]_./-]*/)?rm'
2492
- # Where a recursive-forced flag cluster is allowed to END.
2493
- #
2494
- # It used to be `([[:space:]]|$)` — whitespace or end of segment — and a closing
2495
- # parenthesis is neither, so a SUBSHELL-wrapped pipeline fell out of every guard
2496
- # built on these two patterns while its brace-wrapped twin was caught: `{ find
2497
- # .git -type d | parallel rm -rf; }` matched because the `;` supplied the
2498
- # boundary, and `(find .git -type d | parallel rm -rf)` did not (issue #3494).
2499
- #
2500
- # So the two STATEMENT-GROUPING terminators join whitespace here, and nothing
2501
- # else. The general spelling — "any character that cannot be part of a flag",
2502
- # `([^[:alnum:]-]|$)` — is the more principled statement of the intent, and is
2503
- # deliberately NOT used: these patterns feed the rm TARGET WALK, the guard with
2504
- # this file's longest false-positive history, and it would newly match ordinary
2505
- # prose punctuation (`echo "rm -rf, then …"` on the comma). Paren and semicolon
2506
- # buy the brace/paren parity the defect is about and buy nothing else.
2507
- #
2508
- # The cluster must still END at the boundary, so `-rfoo` is not read as `-rf`.
2509
- readonly RM_RF_END='([[:space:];)]|$)'
2510
- # rm invoked with BOTH a recursive and a force flag — clustered (-rf/-fr, any
2511
- # extra letters) or split, in either order. The split gate pairs ANY recursive
2512
- # form (short cluster containing r, or --recursive) with ANY force form (short
2513
- # cluster containing f, or --force), so mixed spellings like `rm -r --force /`
2514
- # and `rm --recursive -f /` cannot slip between the short/short and long/long
2515
- # alternations (PR #1976 review).
2516
- #
2517
- # The FLAG TAILS are named separately from the `rm`-anchored patterns because
2518
- # the find/xargs family below needs the identical flag vocabulary against a
2519
- # different verb anchor. Before #3494 it carried its own short-cluster-only copy
2520
- # and therefore missed `rm --recursive --force` — a divergence that could only
2521
- # happen because the spelling set was written twice.
2522
- readonly RM_RF_TAIL_CLUSTER='([[:space:]]+-[[:alnum:]-]+)*[[:space:]]+(-[[:alnum:]]*r[[:alnum:]]*f|-[[:alnum:]]*f[[:alnum:]]*r)'"$RM_RF_END"
2523
- readonly RM_RF_TAIL_SPLIT='(([[:space:]][^;&|]*)?[[:space:]](-[[:alnum:]]*r[[:alnum:]]*|--recursive)([[:space:]][^;&|]*)?[[:space:]](-[[:alnum:]]*f[[:alnum:]]*|--force)'"$RM_RF_END"'|([[:space:]][^;&|]*)?[[:space:]](-[[:alnum:]]*f[[:alnum:]]*|--force)([[:space:]][^;&|]*)?[[:space:]](-[[:alnum:]]*r[[:alnum:]]*|--recursive)'"$RM_RF_END"')'
2524
- readonly RM_RF_CLUSTER="$RM_CMD$RM_RF_TAIL_CLUSTER"
2525
- readonly RM_RF_SPLIT="$RM_CMD$RM_RF_TAIL_SPLIT"
2526
-
2527
- # 1. Recursive forced delete (`rm -rf`) of a filesystem root, home, or top-level
2528
- # wildcard. Two gates ANDed: the statement must invoke `rm` with BOTH a
2529
- # recursive and a force flag, AND name a catastrophic target. Splitting the
2530
- # flag check from the target check keeps each regex legible and testable.
2531
- # The target boundary classes include quote characters (issue #1960): without
2532
- # them, `bash -c "rm -rf /"` and interpreter one-liners like
2533
- # `python -c "… os.system('rm -rf /')"` slip through because the target is
2534
- # quote-adjacent instead of space-bounded.
2535
- # Both gates run PER STATEMENT inside the shared rm loop below (quality
2536
- # review S1): a harmless `/` in a LATER statement (`rm -rf build && cd /`)
2537
- # is never attributed to the rm in an earlier one.
2538
- qc="'\""
2539
- # Path/home targets also accept the command-substitution closers `)` and backtick
2540
- # as a trailing boundary (issue #1982): in `echo "$(rm -rf /)"` the target `/` is
2541
- # followed by `)`, not a space or quote, so without them an executable
2542
- # substitution-wrapped `rm -rf <root>` slips past this gate. Leading boundary is
2543
- # unchanged — the target is always space-separated from the recursive+force flag.
2544
- tc="'\"\`)"
2545
- # The bare-`*` wildcard deliberately KEEPS the narrow (space/quote/end) boundary:
2546
- # admitting `)` there would misread a shell `case … in *)` default arm as a
2547
- # catastrophic `rm -rf *` (T4b F1). A genuinely substitution-wrapped bare `*`
2548
- # (`echo "$(rm -rf *)"`) is instead caught by the token-walk (guard 1b) below.
2549
- readonly RM_CATASTROPHIC_TARGET='([[:space:]='"$qc"'])((/|/\*|/\.\*?|~|~/\*?|\$HOME\b|\$\{HOME\})([[:space:]'"$tc"']|/?\*?['"$tc"']?$)|\*([[:space:]'"$qc"']|/?\*?['"$qc"']?$))'
2550
-
2551
- # 1b. rm target hardening (issue #1960). For every statement that invokes rm
2552
- # with recursive+force flags, additionally block when:
2553
- # - cwd is $HOME (any target is one argument away from wiping home), or
2554
- # - the target is the cwd itself (`.` / `./`), or
2555
- # - the target traverses out via `..`, or
2556
- # - the target is home-anchored (`~/…` — the shell expands it to $HOME at
2557
- # execution time, so it is always outside the project), or
2558
- # - the target is an absolute path outside the project — with an allowance
2559
- # for /tmp, /var/tmp, and $TMPDIR — or
2560
- # - the target is a `$VAR` expansion other than the sanctioned $TMPDIR.
2561
- # Globbing is disabled around the token walk so a literal `*` in the command
2562
- # is never expanded against the hook's own cwd.
2563
- project_dir="${CLAUDE_PROJECT_DIR:-$PWD}"
2564
- tmp_dir_allow="${TMPDIR:-/tmp}"
2565
- tmp_dir_allow="${tmp_dir_allow%/}"
2566
- [ -n "$tmp_dir_allow" ] || tmp_dir_allow="/tmp"
2567
- # Physical (symlink-resolved) spelling of an allowed root — issue #3106 arm B.
2568
- # The allowance below is a set of LITERAL string prefixes, so on macOS, where
2569
- # /tmp is a symlink to /private/tmp, one directory had two spellings and only
2570
- # one of them was allowed: `rm -rf /tmp/x` passed while `rm -rf /private/tmp/x`
2571
- # — the SAME directory, and the spelling an agent's own scratchpad path is
2572
- # handed to it in — was refused as "outside the project". Two opposite verdicts
2573
- # for one location is a defect regardless of which verdict is right.
2574
- #
2575
- # This widens no LOCATION. It adds the second name of a location the guard has
2576
- # always allowed, computed from the filesystem rather than hardcoded, so a
2577
- # platform where /tmp is not a symlink gains nothing. Falls back to the logical
2578
- # path when the directory does not exist or resolves to `/`, so the allowance
2579
- # can never become an empty or root-anchored prefix (an empty prefix would make
2580
- # `""/*` match every absolute path).
2581
- phys_dir() {
2582
- local logical="$1" real=""
2583
- real="$(cd -- "$logical" 2>/dev/null && pwd -P)" || real=""
2584
- case "$real" in
2585
- "" | /) printf '%s' "$logical" ;;
2586
- *) printf '%s' "$real" ;;
2587
- esac
2588
- }
2589
- project_dir_phys="$(phys_dir "$project_dir")"
2590
- tmp_phys="$(phys_dir /tmp)"
2591
- var_tmp_phys="$(phys_dir /var/tmp)"
2592
- tmp_dir_allow_phys="$(phys_dir "$tmp_dir_allow")"
2593
- [ -n "$project_dir_phys" ] || project_dir_phys="$project_dir"
2594
- [ -n "$tmp_phys" ] || tmp_phys="/tmp"
2595
- [ -n "$var_tmp_phys" ] || var_tmp_phys="/var/tmp"
2596
- [ -n "$tmp_dir_allow_phys" ] || tmp_dir_allow_phys="$tmp_dir_allow"
2597
- # Peel command-substitution wrappers off a token so an rm nested in `$(…)`,
2598
- # backticks, `<(…)`/`>(…)`, a `"…"`/`'…'` quote, or a leading `\` alias-bypass
2599
- # (`\rm`) is recognized and its target classified as if the token were unwrapped
2600
- # (issue #1982) — substitution-wrapping is verdict-neutral for the rm guard.
2601
- # Leading wrappers (\ $( ` ( <( >( and quotes) and trailing closers () ` and
2602
- # quotes) are stripped in runs, so `"$(\rm` → `rm` and `/etc)"` → `/etc`. `$((`
2603
- # is ARITHMETIC, never command substitution: the LEADING peel stops at it (its
2604
- # case is ordered first), so the inner expression is never exposed as a command
2605
- # or a target. The trailing loop may still trim a closing `))`, but that is
2606
- # harmless — an arithmetic token like `$((10/2))` still keeps its `$` for the
2607
- # variable-target guard and can never be mis-normalized into an rm or a `/`-target.
2608
- strip_subst_wrappers() {
2609
- local t="$1" prev=""
2610
- while [ "$t" != "$prev" ]; do
2611
- prev="$t"
2612
- case "$t" in
2613
- '$(('*) break ;;
2614
- '\'*) t="${t#\\}" ;;
2615
- '$('*) t="${t#'$('}" ;;
2616
- '<('*) t="${t#'<('}" ;;
2617
- '>('*) t="${t#'>('}" ;;
2618
- '"'*) t="${t#'"'}" ;;
2619
- "'"*) t="${t#\'}" ;;
2620
- '`'*) t="${t#'`'}" ;;
2621
- '('*) t="${t#(}" ;;
2622
- esac
2623
- done
2624
- prev=""
2625
- while [ "$t" != "$prev" ]; do
2626
- prev="$t"
2627
- case "$t" in
2628
- *')') t="${t%)}" ;;
2629
- *'`') t="${t%'`'}" ;;
2630
- *'"') t="${t%'"'}" ;;
2631
- *"'") t="${t%\'}" ;;
2632
- esac
2633
- done
2634
- printf '%s' "$t"
2635
- }
2636
- # Decide which text of an rm statement the TARGET WALK may read — issue #3106
2637
- # arm A. The statement selector matches the RAW command text, so a recursive
2638
- # delete quoted as PROSE inside a string argument selects the line, and every
2639
- # remaining token on it is then classified as a deletion target. Three
2640
- # independent sightings in one day, all of them commands that delete nothing:
2641
- # a `printf` reduction, a `gh issue create --title …` filing the report about
2642
- # this guard, and a commit message describing it. Each was refused for a
2643
- # variable in a LATER, unrelated argument.
2644
- #
2645
- # The rule is structural, with no allowlist of "display commands":
2646
- # - an rm invocation OUTSIDE any quote is real; the walk reads the whole
2647
- # statement, exactly as before (`rm -rf "$HOME"` keeps its target),
2648
- # - an rm at the START of its quoted run is an invocation the quote merely
2649
- # wraps (`bash -c "rm -rf /"`, `echo "$(rm -rf /)"`); the walk reads the
2650
- # whole statement, exactly as before,
2651
- # - an rm preceded by other words INSIDE its quoted run is prose; the walk is
2652
- # scoped to that run, so the rm's own quoted arguments are still classified
2653
- # in full while a variable in a later argument is no longer read as a
2654
- # deletion target.
2655
- #
2656
- # Failure directions all point at blocking: an unterminated quote, an
2657
- # over-long statement, or any run the scan cannot place falls back to the whole
2658
- # statement. Residual (accepted, documented): `eval "prose rm -rf" "$X"` would
2659
- # concatenate its words at run time and is scoped to the first run here.
2660
- rm_scan_scope() {
2661
- local stmt="$1"
2662
- local n=${#stmt}
2663
- # Long statements fall back to the full walk rather than pay a char scan.
2664
- if [ "$n" -gt 4000 ]; then
2665
- printf '%s' "$stmt"
2666
- return
2667
- fi
2668
- local i=0 ch q="" esc=0 outside="" cur_run="" rm_runs="" found=0
2669
- local run_leading=0
2670
- while [ "$i" -lt "$n" ]; do
2671
- ch="${stmt:i:1}"
2672
- i=$((i + 1))
2673
- if [ "$esc" -eq 1 ]; then
2674
- esc=0
2675
- if [ -n "$q" ]; then cur_run="$cur_run$ch"; else outside="$outside$ch"; fi
2676
- continue
2677
- fi
2678
- if [ "$ch" = '\' ] && [ "$q" != "'" ]; then
2679
- esc=1
2680
- continue
2681
- fi
2682
- if [ -n "$q" ]; then
2683
- if [ "$ch" = "$q" ]; then
2684
- case "$cur_run" in
2685
- *[Rr][Mm]*)
2686
- if scan -Ei "$cur_run" "$RM_CMD"'([[:space:]]|$)'; then
2687
- found=$((found + 1))
2688
- if [ -n "$rm_runs" ]; then rm_runs="$rm_runs"$'\n'; fi
2689
- rm_runs="$rm_runs$cur_run"
2690
- if scan -Ei "$cur_run" \
2691
- '^[[:space:]]*(\\|\$\(|`|\(|<\(|>\()*[[:space:]]*([[:alnum:]_./-]*/)?rm([[:space:]]|$)'; then
2692
- run_leading=1
2693
- fi
2694
- fi
2695
- ;;
2696
- esac
2697
- q=""
2698
- cur_run=""
2699
- else
2700
- cur_run="$cur_run$ch"
2701
- fi
2702
- continue
2703
- fi
2704
- case "$ch" in
2705
- '"' | "'")
2706
- q="$ch"
2707
- cur_run=""
2708
- ;;
2709
- *) outside="$outside$ch" ;;
2710
- esac
2711
- done
2712
- # An unterminated quote is text the scan cannot place: treat it as unquoted so
2713
- # the fallback below hands back the whole statement.
2714
- [ -z "$q" ] || outside="$outside$cur_run"
2715
- if scan -Ei "$outside" "$RM_CMD"'([[:space:]]|$)'; then
2716
- printf '%s' "$stmt"
2717
- return
2718
- fi
2719
- if [ "$found" -eq 0 ]; then
2720
- printf '%s' "$stmt"
2721
- return
2722
- fi
2723
- # `rm` first in ANY run (modulo whitespace and substitution/alias openers) is
2724
- # an invocation, not prose. Inspect every run before deciding: returning on
2725
- # the first prose run used to hide a real delete in a later quoted run.
2726
- if [ "$run_leading" -eq 1 ]; then
2727
- printf '%s' "$stmt"
2728
- return
2729
- fi
2730
- printf '%s' "$rm_runs"
2731
- }
2732
- # Look up the ONE unambiguous assignment of NAME inside the command being
2733
- # classified — issue #3106 arm B, the variable half.
2734
- #
2735
- # Prints the recorded right-hand side, or fails when the name is not assigned
2736
- # before the first rm token or is assigned more than one distinct value there.
2737
- # A later write cannot affect an earlier delete, and a quoted assignment-like
2738
- # argument can be prose, so neither is considered. Only assignments literally
2739
- # present in this command are ever trusted; nothing is expanded from the hook's
2740
- # own environment.
2741
- rm_assignment_stmt=""
2742
- rm_assignment_value() {
2743
- local name="$1"
2744
- case "$name" in
2745
- "" | *[!A-Za-z0-9_]*) return 1 ;;
2746
- esac
2747
- # Only assignments that occur before this statement's rm token can influence
2748
- # its delete safely. A later assignment is too late at runtime, and an
2749
- # assignment whose NAME begins inside a quoted argument can be prose. The
2750
- # small lexer below preserves quoted right-hand sides such as V="/tmp/x"
2751
- # while excluding an argument such as echo "V=/tmp/x". Any ambiguity fails
2752
- # closed.
2753
- RM_ASSIGNMENT_NAME="$name" RM_ASSIGNMENT_COMMAND="$rm_normalized_command_str" \
2754
- RM_ASSIGNMENT_STATEMENT="$rm_assignment_stmt" \
2755
- python3 - <<'PY'
2756
- import os
2757
- import re
2758
- import sys
2759
-
2760
- name = os.environ.get("RM_ASSIGNMENT_NAME", "")
2761
- command = os.environ.get("RM_ASSIGNMENT_COMMAND", "")
2762
- statement = os.environ.get("RM_ASSIGNMENT_STATEMENT", "")
2763
- if not re.fullmatch(r"[A-Za-z_][A-Za-z0-9_]*", name):
2764
- sys.exit(1)
2765
-
2766
- rm_pattern = re.compile(
2767
- r"(?i)(?<![A-Za-z0-9_./-])(?:[A-Za-z0-9_./-]*/)?rm(?=$|[\s;&|()'\"`])",
2768
- )
2769
- rm_token = rm_pattern.search(statement)
2770
- if rm_token is None or not statement or command.count(statement) != 1:
2771
- sys.exit(1)
2772
- statement_start = command.find(statement)
2773
- if statement_start < 0:
2774
- sys.exit(1)
2775
- prefix = command[: statement_start + rm_token.start()]
2776
-
2777
- tokens = []
2778
- buffer = []
2779
- quote = None
2780
- escaped = False
2781
- started = False
2782
- started_unquoted = False
2783
-
2784
- def flush():
2785
- global buffer, started, started_unquoted
2786
- if started:
2787
- tokens.append(("".join(buffer), started_unquoted))
2788
- buffer = []
2789
- started = False
2790
- started_unquoted = False
2791
-
2792
- for char in prefix:
2793
- if escaped:
2794
- buffer.append(char)
2795
- escaped = False
2796
- continue
2797
- if quote is not None:
2798
- if char == quote:
2799
- quote = None
2800
- elif char == "\\" and quote == '"':
2801
- escaped = True
2802
- else:
2803
- buffer.append(char)
2804
- continue
2805
- if char in "'\"":
2806
- if not started:
2807
- started = True
2808
- started_unquoted = False
2809
- quote = char
2810
- elif char == "\\":
2811
- if not started:
2812
- started = True
2813
- started_unquoted = True
2814
- escaped = True
2815
- elif char.isspace() or char in ";&|()":
2816
- flush()
2817
- else:
2818
- if not started:
2819
- started = True
2820
- started_unquoted = True
2821
- buffer.append(char)
2822
- flush()
2823
-
2824
- needle = f"{name}="
2825
- hits = [token[len(needle):] for token, outside in tokens
2826
- if outside and token.startswith(needle)]
2827
- distinct = set(hits)
2828
- if len(distinct) != 1:
2829
- sys.exit(1)
2830
- value = hits[0]
2831
- if not value:
2832
- sys.exit(1)
2833
- sys.stdout.write(value)
2834
- PY
2835
- }
2836
- # Rewrite a leading `$NAME` / `${NAME}` in a deletion target to the value the
2837
- # command itself assigns it, so the target is classified as if the agent had
2838
- # written that value literally — issue #3106 arm B.
2839
- #
2840
- # The guard's standing reason for refusing variable targets is that "unset or
2841
- # mistyped variables can point anywhere", and that reason survives intact: a
2842
- # name with no in-command assignment, an ambiguous one, or a value that is
2843
- # itself a command substitution never resolves and stays refused. What changes
2844
- # is only that a target the agent could have spelled literally is no longer
2845
- # refused for being spelled through a variable.
2846
- resolve_var_prefix() {
2847
- local token="$1" name="" rest="" value=""
2848
- case "$token" in
2849
- '${'*'}'*)
2850
- name="${token#'${'}"
2851
- name="${name%%\}*}"
2852
- rest="${token#'${'"$name"'}'}"
2853
- ;;
2854
- '$'*)
2855
- rest="${token#'$'}"
2856
- name="${rest%%[!A-Za-z0-9_]*}"
2857
- rest="${rest#"$name"}"
2858
- ;;
2859
- *) return 1 ;;
2860
- esac
2861
- [ -n "$name" ] || return 1
2862
- value="$(rm_assignment_value "$name")" || return 1
2863
- # A value that is itself a command substitution names no location the guard
2864
- # can read, so it never resolves — the refusal stands. `$(…)` already fails
2865
- # below (its leading `$` yields no variable name); backticks are named here so
2866
- # both spellings of substitution behave the same way.
2867
- case "$value" in
2868
- *'`'*) return 1 ;;
2869
- esac
2870
- case "$value" in
2871
- '"'*'"')
2872
- value="${value#\"}"
2873
- value="${value%\"}"
2874
- ;;
2875
- "'"*"'")
2876
- value="${value#\'}"
2877
- value="${value%\'}"
2878
- ;;
2879
- esac
2880
- [ -n "$value" ] || return 1
2881
- printf '%s%s' "$value" "$rest"
2882
- }
2883
- # Classify ONE deletion target. Extracted from the token walk so a variable
2884
- # target can be re-classified through every arm after resolution (#3106),
2885
- # instead of the variable arm being a terminal verdict of its own.
2886
- classify_rm_target() {
2887
- local token="$1" depth="${2:-0}" resolved=""
2888
- case "$token" in
2889
- -*) return 0 ;;
2890
- . | ./)
2891
- set +f
2892
- block "recursive forced delete of the current directory (rm -rf .)"
2893
- ;;
2894
- .git | .git/* | */.git | */.git/*)
2895
- set +f
2896
- block "recursive forced delete of the git control plane (.git holds every commit, branch and stash not already pushed; nothing in the working tree can rebuild it)"
2897
- ;;
2898
- .. | ../* | */.. | */../*)
2899
- set +f
2900
- block "recursive forced delete of a path outside the project (.. traversal)"
2901
- ;;
2902
- '~' | '~'/*)
2903
- set +f
2904
- block "recursive forced delete of a home-anchored path (~/…) outside the project"
2905
- ;;
2906
- /*)
2907
- case "$token" in
2908
- "$project_dir" | "$project_dir"/* | "$project_dir_phys" | "$project_dir_phys"/* \
2909
- | /tmp | /tmp/* | "$tmp_phys" | "$tmp_phys"/* \
2910
- | /var/tmp | /var/tmp/* | "$var_tmp_phys" | "$var_tmp_phys"/* \
2911
- | "$tmp_dir_allow" | "$tmp_dir_allow"/* | "$tmp_dir_allow_phys" | "$tmp_dir_allow_phys"/*) : ;;
2912
- *)
2913
- set +f
2914
- block "recursive forced delete of an absolute path outside the project (only the project, /tmp, /var/tmp, and \$TMPDIR are allowed)"
2915
- ;;
2916
- esac
2917
- ;;
2918
- '*')
2919
- # Bare top-level wildcard expands to every entry in the cwd. Guard 1a no
2920
- # longer bounds `*)` (T4b F1), so a substitution-wrapped `rm -rf *` is
2921
- # caught here after the trailing-closer strip peels `*)"` down to `*`.
2922
- set +f
2923
- block "recursive forced delete of a top-level wildcard (rm -rf *)"
2924
- ;;
2925
- *'$'*)
2926
- case "$token" in
2927
- '$TMPDIR' | '$TMPDIR'/* | '${TMPDIR}' | '${TMPDIR}'/*) : ;;
2928
- *)
2929
- if [ "$depth" -lt 4 ] \
2930
- && resolved="$(resolve_var_prefix "$token")" \
2931
- && [ -n "$resolved" ] \
2932
- && [ "$resolved" != "$token" ]; then
2933
- classify_rm_target "$resolved" $((depth + 1))
2934
- else
2935
- set +f
2936
- block "recursive forced delete of a variable-expanded target (unset or mistyped variables can point anywhere; \$TMPDIR is the only sanctioned dynamic target)"
2937
- fi
2938
- ;;
2939
- esac
2940
- ;;
2941
- esac
2942
- return 0
2943
- }
2944
- # Segmented in the PARENT shell rather than in a process substitution, and the
2945
- # `|| true` that used to sit on the feeder is gone. Both together were the same
2946
- # three-way read as a bare `grep -q` condition (see scan() above), just wearing
2947
- # a loop: a grep that could not run produced no lines, the body never executed,
2948
- # and the guard was silently skipped with the command ALLOWED. `exit` inside a
2949
- # process substitution cannot deny anything either — it ends that subshell, not
2950
- # this hook.
2951
- rm_segments_status=0
2952
- rm_segments="$(printf '%s' "$rm_normalized_command_str" | tr '&|;' '\n' \
2953
- | grep -Ei -- "$RM_CMD"'([[:space:]]|$)')" || rm_segments_status=$?
2954
- case "$rm_segments_status" in
2955
- 0 | 1) ;;
2956
- *) scan_failed "$rm_segments_status" ;;
2957
- esac
2958
- while IFS= read -r rm_stmt; do
2959
- # A here-string over empty input still yields one empty line.
2960
- [ -n "$rm_stmt" ] || continue
2961
- if ! scan -Ei "$rm_stmt" "$RM_RF_CLUSTER" \
2962
- && ! scan -Ei "$rm_stmt" "$RM_RF_SPLIT"; then
2963
- continue
2964
- fi
2965
- # Guard 1: catastrophic target named in the SAME statement as the rm -rf.
2966
- if scan -E "$rm_stmt" "$RM_CATASTROPHIC_TARGET"; then
2967
- block "recursive forced delete of a root, home, or wildcard path (rm -rf)"
2968
- fi
2969
- # Physical-path comparison (pwd -P): on macOS $HOME or the cwd may arrive via
2970
- # a symlink (/var → /private/var), and a string compare would miss the match.
2971
- if [ -n "${HOME:-}" ] \
2972
- && [ "$(pwd -P)" = "$(cd -- "$HOME" 2>/dev/null && pwd -P)" ]; then
2973
- block "recursive forced delete while the working directory is \$HOME (cd into a project first)"
2974
- fi
2975
- # Scope the walk to the quoting region that actually contains the rm (#3106
2976
- # arm A). Unquoted and run-leading invocations get the whole statement back,
2977
- # so this is a no-op for every real delete.
2978
- rm_assignment_stmt="$rm_stmt"
2979
- rm_walk_status=0
2980
- rm_walk_text="$(rm_scan_scope "$rm_stmt")" || rm_walk_status=$?
2981
- if [ "$rm_walk_status" -ne 0 ]; then
2982
- # The substitution above runs in a subshell. A denial inside it cannot stop
2983
- # this parent hook, so carry the failure out explicitly and deny here.
2984
- scan_failed "$rm_walk_status"
2985
- fi
2986
- while IFS= read -r rm_scope; do
2987
- set -f
2988
- seen_rm=0
2989
- for raw_token in $rm_scope; do
2990
- token="$(strip_subst_wrappers "$raw_token")"
2991
- if [ "$seen_rm" -eq 0 ]; then
2992
- # Path-prefixed spellings (`/bin/rm`, `./rm`) are still rm (F2).
2993
- case "$token" in
2994
- rm | */rm) seen_rm=1 ;;
2995
- esac
2996
- continue
2997
- fi
2998
- classify_rm_target "$token"
2999
- done
3000
- set +f
3001
- done <<< "$rm_walk_text"
3002
- done <<<"$rm_segments"
3003
-
3004
- # 2. Force-pushing a protected branch. `--force-with-lease` is the safe,
3005
- # non-clobbering alternative and is intentionally NOT blocked. Deliberate
3006
- # divergence from upstream (which blocks force-push on ANY branch):
3007
- # feature-branch force-push is a sanctioned rebase-and-push agent workflow.
3008
- #
3009
- # The force flag AND the protected-branch name must appear in the SAME
3010
- # `git push` statement. Checking them independently over the whole command is
3011
- # a false-positive magnet: an unrelated `-f` (a `[ -f file ]` test, `rm -f`,
3012
- # `grep -f`, `tail -f`) plus an unrelated protected name (`--base main`,
3013
- # `origin/main`, `git fetch origin main`) alongside any feature-branch
3014
- # `git push` would wrongly block. So split the command into statements
3015
- # (`;`, `&&`, `||`, `|`, newlines), keep only the `git push` segments, and
3016
- # inspect each in isolation — a real `git push --force origin main` still
3017
- # matches, while a feature-branch push next to `[ -f ]`/`--base main` passes.
3018
- # Same reason as the rm segmentation above: a feeder that swallows grep's error
3019
- # skips the guard entirely and allows the command.
3020
- push_segments_status=0
3021
- push_segments="$(printf '%s' "$normalized_command_str" | tr '&|;' '\n' \
3022
- | grep -Ei -- "${GIT_CMD}push\b")" || push_segments_status=$?
3023
- case "$push_segments_status" in
3024
- 0 | 1) ;;
3025
- *) scan_failed "$push_segments_status" ;;
3026
- esac
3027
- while IFS= read -r push_stmt; do
3028
- [ -n "$push_stmt" ] || continue
3029
- if scan -Ei "$push_stmt" \
3030
- '(--force([[:space:]]|=|$)|[[:space:]]-f([[:space:]]|$))' \
3031
- && ! scan -Ei "$push_stmt" '--force-with-lease' \
3032
- && scan -Ei "$push_stmt" \
3033
- '(^|[^[:alnum:]_/-])(main|master|production|prod|release)([^[:alnum:]_/-]|$)'; then
3034
- block "force-pushing a protected branch (use --force-with-lease, or push a feature branch)"
3035
- fi
3036
- done <<<"$push_segments"
3037
-
3038
- # 3. `git reset --hard` / `git reset --merge` while the working tree has
3039
- # uncommitted changes — both silently discard them. Only blocks when the tree
3040
- # is actually dirty, so a clean-tree reset (a legitimate workflow) passes.
3041
- # Deliberate divergence from upstream's unconditional block; the accepted
3042
- # residual risk (dirty check runs at hook time in the hook's cwd) is
3043
- # documented in the header.
3044
- if matches "${GIT_CMD}"'reset\b.*--(hard|merge)\b'; then
3045
- if git rev-parse --is-inside-work-tree >/dev/null 2>&1 \
3046
- && [ -n "$(git status --porcelain 2>/dev/null)" ]; then
3047
- block "git reset --hard/--merge on a dirty working tree would discard uncommitted changes (commit first, or preserve as below)" "$PRESERVE_GUIDANCE
3048
-
3049
- $DESTRUCTIVE_GUIDANCE"
3050
- fi
3051
- fi
3052
-
3053
- # 3a. `git read-tree` with BOTH an update flag and `--reset`, on the same dirty
3054
- # tree — the plumbing spelling of guard 3 (issue #3978). It resets the index
3055
- # and writes the result into the working tree, discarding tracked
3056
- # modifications: the identical destruction, reached through a command that
3057
- # carries no `--hard` and no `reset` subcommand, so every pattern in
3058
- # guard 3 misses it. A guard an agent can walk around is a guard that stops
3059
- # the honest caller and not the one looking for a way through, and this
3060
- # spelling is strictly worse than the blocked one — it discards WITHOUT
3061
- # preserving, which is exactly the property guard 3's remedy supplies. Both
3062
- # refusals therefore print the same $PRESERVE_GUIDANCE, so what they teach
3063
- # cannot drift apart.
3064
- #
3065
- # `--reset` is the discriminator, not `-u`, and the pairing is deliberate:
3066
- #
3067
- # - `read-tree` with no update flag touches the INDEX only and destroys
3068
- # nothing in the working tree, so a blanket `read-tree` block would be
3069
- # over-broad.
3070
- # - `read-tree -m -u` (a merge without `--reset`) is safe by git's own
3071
- # construction: it REFUSES rather than overwrite a locally modified file
3072
- # ("entry would be overwritten by merge"). `--reset` is precisely the flag
3073
- # that switches that refusal off.
3074
- #
3075
- # So the destructive combination is an update flag AND `--reset` together,
3076
- # in either order. The update flag is matched in the checkout guard's idiom
3077
- # so a bundled short option (`-iu`) cannot dodge the anchor, with leading
3078
- # whitespace required so a `--index-output=/tmp/out-u` style value cannot
3079
- # read as the flag. Same conditional dirty-tree shape and same accepted
3080
- # residual risk as guard 3: the probe runs in the hook's cwd at hook time.
3081
- readonly GIT_READ_TREE="${GIT_CMD}read-tree"
3082
- if matches "${GIT_READ_TREE}"'[^;&|]*[[:space:]]--reset([[:space:]]|$)' \
3083
- && matches "${GIT_READ_TREE}"'[^;&|]*[[:space:]](-[[:alnum:]]*u[[:alnum:]]*|--update)([[:space:]]|=|$)'; then
3084
- if git rev-parse --is-inside-work-tree >/dev/null 2>&1 \
3085
- && [ -n "$(git status --porcelain 2>/dev/null)" ]; then
3086
- block "git read-tree -u --reset on a dirty working tree would discard uncommitted changes (commit first, or preserve as below)" "$PRESERVE_GUIDANCE
3087
-
3088
- $DESTRUCTIVE_GUIDANCE"
3089
- fi
3090
- fi
3091
-
3092
- # 3b. `git rebase --abort` / `--quit` ONLY while human/agent conflict
3093
- # resolutions exist (issue #1956). `--abort` restores the pre-rebase branch
3094
- # and discards every resolution; `--quit` deletes the rebase bookkeeping
3095
- # (head-name, todo) while stranding a detached HEAD, making recovery
3096
- # ambiguous — both are treated the same, conditionally. A rebase state with
3097
- # nothing human-made in it (a clean-pick wedge, or a conflict stop nobody
3098
- # has touched) is agent-recoverable, so aborting it stays ALLOWED.
3099
- # Discriminator (empirical, git 2.53): diff the worktree/index against the
3100
- # AUTO_MERGE ref (the merge-ort recorded conflicted tree). Abort-safe ⇔
3101
- # worktree diff is quiet AND (the cached diff is quiet OR unmerged index
3102
- # entries exist — an untouched conflict stop has unmerged entries that make
3103
- # the cached diff non-quiet without any human edit). Fail CLOSED on the
3104
- # rebase-apply backend (no AUTO_MERGE contract) and on a missing AUTO_MERGE
3105
- # ref while rebase-merge state exists. Same accepted residual risk as
3106
- # guard 3: the probes run in the hook's cwd at hook time.
3107
- if matches "${GIT_CMD}"'rebase'"${GIT_TOKENS}"'--(abort|quit)([[:space:]]|$)'; then
3108
- rebase_apply_dir="$(git rev-parse --git-path rebase-apply 2>/dev/null || true)"
3109
- rebase_merge_dir="$(git rev-parse --git-path rebase-merge 2>/dev/null || true)"
3110
- if [ -n "$rebase_apply_dir" ] && [ -d "$rebase_apply_dir" ]; then
3111
- block "git rebase --abort/--quit on an apply-backend rebase cannot prove no conflict resolutions would be lost (fail closed; finish or continue the rebase instead)"
3112
- fi
3113
- if [ -n "$rebase_merge_dir" ] && [ -d "$rebase_merge_dir" ]; then
3114
- if ! git rev-parse -q --verify AUTO_MERGE >/dev/null 2>&1; then
3115
- block "git rebase --abort/--quit with an unresolvable AUTO_MERGE ref cannot prove no conflict resolutions would be lost (fail closed)"
3116
- fi
3117
- if ! git diff --quiet AUTO_MERGE 2>/dev/null; then
3118
- block "git rebase --abort/--quit would discard conflict resolutions in the working tree (finish resolving and run git rebase --continue instead)"
3119
- fi
3120
- unmerged_entries="$(git ls-files -u 2>/dev/null || true)"
3121
- if [ -z "$unmerged_entries" ] \
3122
- && ! git diff --cached --quiet AUTO_MERGE 2>/dev/null; then
3123
- block "git rebase --abort/--quit would discard staged conflict resolutions (finish resolving and run git rebase --continue instead)"
3124
- fi
3125
- fi
3126
- fi
3127
-
3128
- # 4. `git checkout` worktree discards: the `--` pathspec form (with or without a
3129
- # ref), `-f/--force`, `--pathspec-from-file`, and bare `git checkout .`.
3130
- # Blocking bare `.` exceeds upstream (which allows any single positional) —
3131
- # issue #1960 names it explicitly: it discards the entire tree. Branch
3132
- # switches and creation (`-b`/`-B`) stay allowed.
3133
- readonly GIT_CHECKOUT="${GIT_CMD}checkout"
3134
- if matches "${GIT_CHECKOUT}${GIT_TOKENS}"'--([[:space:]]|$)' \
3135
- || matches "${GIT_CHECKOUT}${GIT_TOKENS}"'(-[[:alnum:]]*f[[:alnum:]]*|--force)([[:space:]]|=|$)' \
3136
- || matches "${GIT_CHECKOUT}"'[[:space:]][^;&|]*--pathspec-from-file' \
3137
- || matches "${GIT_CHECKOUT}"'[[:space:]]+\.(/)?([[:space:]]|$)'; then
3138
- block "git checkout discarding local changes (--, -f/--force, --pathspec-from-file, or bare .)" "$PRESERVE_GUIDANCE
3139
-
3140
- $DESTRUCTIVE_GUIDANCE"
3141
- fi
3142
-
3143
- # 5. `git switch` discards: `--discard-changes` and its `-f/--force` aliases.
3144
- # Carries the same guidance as guards 3 and 4 (issue #3696). It discards the
3145
- # same uncommitted work by the same mechanism, so a refusal that named no
3146
- # remedy left the reader to invent one — and the one they invent is the
3147
- # stash, which is the single thing $PRESERVE_GUIDANCE exists to steer off.
3148
- if matches "${GIT_CMD}switch${GIT_TOKENS}"'(--discard-changes|--force|-f)([[:space:]]|=|$)'; then
3149
- block "git switch discarding local changes (--discard-changes/-f/--force)" "$PRESERVE_GUIDANCE
3150
-
3151
- $DESTRUCTIVE_GUIDANCE"
3152
- fi
3153
-
3154
- # 6. `git restore` defaults to overwriting the WORKTREE — a silent discard. Only
3155
- # the pure staging-area form is safe: `--staged` present and `--worktree`
3156
- # absent. Two conditions, because an ERE has no lookahead: `--staged
3157
- # --worktree` still discards, so `--worktree` blocks regardless of `--staged`.
3158
- # Carries the same guidance as guards 3 and 4 (issue #3696). The permitted
3159
- # alternative this reason names — `git restore --staged <path>` — is real,
3160
- # but it only unstages; it leaves the worktree exactly as dirty as it found
3161
- # it. So the operator who reached for `git restore` to CLEAN a tree is told
3162
- # of an operation that does not do what they came for, and was told nothing
3163
- # about what does. This is the refusal #3696 was filed from.
3164
- if matches "${GIT_CMD}"'restore([[:space:]]|$)'; then
3165
- if matches "${GIT_CMD}"'restore[^;&|]*--worktree' \
3166
- || ! matches "${GIT_CMD}"'restore[^;&|]*--staged'; then
3167
- block "git restore overwriting worktree files (only 'git restore --staged <path>' without --worktree is allowed)" "$PRESERVE_GUIDANCE
3168
-
3169
- $DESTRUCTIVE_GUIDANCE"
3170
- fi
3171
- fi
3172
-
3173
- # 7. `git stash drop` / `git stash clear` destroy stashed work. push/pop/list/
3174
- # apply stay ALLOWED — this guard moves no verdict on them — but they are no
3175
- # longer RECOMMENDED anywhere in this file, and this comment used to say the
3176
- # opposite (issue #3692). It called them "the safe alternatives the reset
3177
- # guard recommends", which stopped being true when #3722 rewrote guards 3
3178
- # and 4 to point at $PRESERVE_GUIDANCE instead. A stale comment endorsing
3179
- # the stash is the same hazard as a stale message doing it: the next reader
3180
- # takes the file's word for what the file does. See $PRESERVE_GUIDANCE for
3181
- # why one stack shared by every worktree of a clone makes push/pop unsafe
3182
- # under this project's concurrency.
3183
- if matches "${GIT_CMD}"'stash[[:space:]]+(drop|clear)([[:space:]]|$)'; then
3184
- block "git stash drop/clear destroys stashed work"
3185
- fi
3186
-
3187
- # 8. `git clean` with a force flag wipes untracked files. A dry-run flag
3188
- # (`-n`/`--dry-run`) ANYWHERE wins — git itself performs no deletion under
3189
- # dry-run, so `git clean -fdn` is a safe preview.
3190
- readonly GIT_CLEAN="${GIT_CMD}clean"
3191
- if matches "${GIT_CLEAN}${GIT_TOKENS}"'(-[[:alnum:]]*f[[:alnum:]]*|--force)([[:space:]]|=|$)' \
3192
- && ! matches "${GIT_CLEAN}${GIT_TOKENS}"'(-[[:alnum:]]*n[[:alnum:]]*|--dry-run)([[:space:]]|=|$)'; then
3193
- block "git clean --force deletes untracked files (preview with git clean -n first)"
3194
- fi
3195
-
3196
- # 9. `git branch` force-delete loses unmerged commits: `-D`, `-d` combined with
3197
- # `-f` (clustered or split), or `--delete` + `--force`. Case-SENSITIVE so the
3198
- # safe `-d` (which refuses unmerged work) and rename `-m` stay allowed.
3199
- readonly GIT_BRANCH="${GIT_CMD}branch"
3200
- if matches_cs "${GIT_BRANCH}${GIT_TOKENS}"'-[[:alnum:]]*D[[:alnum:]]*([[:space:]]|$)' \
3201
- || { matches_cs "${GIT_BRANCH}${GIT_TOKENS}"'-[[:alnum:]]*d[[:alnum:]]*([[:space:]]|$)' \
3202
- && matches_cs "${GIT_BRANCH}${GIT_TOKENS}"'-[[:alnum:]]*f[[:alnum:]]*([[:space:]]|$)'; } \
3203
- || { matches "${GIT_BRANCH}"'[^;&|]*--delete' && matches "${GIT_BRANCH}"'[^;&|]*--force'; }; then
3204
- block "git branch force-delete (-D) loses unmerged commits (use -d, which refuses unmerged work)"
3205
- fi
3206
-
3207
- # 10. Cheap destructive-ref guards: `git tag -d` (tags are shared refs),
3208
- # `git reflog delete` (erases recovery history), and
3209
- # `git worktree remove --force` (discards a dirty worktree). Tag deletion is
3210
- # case-SENSITIVE so annotated-tag `-a` and message `-m` flags never match.
3211
- if matches_cs "${GIT_CMD}tag${GIT_TOKENS}"'(-[[:alnum:]]*d[[:alnum:]]*([[:space:]]|$)|--delete([[:space:]]|=|$))'; then
3212
- block "git tag -d deletes a shared ref"
3213
- fi
3214
- if matches "${GIT_CMD}"'reflog[[:space:]]+delete([[:space:]]|$)'; then
3215
- block "git reflog delete erases recovery history"
3216
- fi
3217
- if matches "${GIT_CMD}"'worktree[[:space:]]+remove[^;&|]*(--force([[:space:]]|=|$)|[[:space:]]-[[:alnum:]]*f[[:alnum:]]*([[:space:]]|$))'; then
3218
- block "git worktree remove --force discards a dirty worktree (remove without --force, which refuses dirty trees)"
3219
- fi
3220
-
3221
- # 11. Deletion through find/xargs, where the target never appears as a literal
3222
- # argument: `find … -delete`, `find … -exec rm -rf`, and `xargs … rm -rf`
3223
- # (targets arrive from dynamic stdin — unauditable). Plain `rm` (no
3224
- # recursive+force) on find/xargs output stays allowed for normal cleanups.
3225
- if matches '(^|[^[:alnum:]_./-])find[[:space:]][^;&|]*[[:space:]]-delete([[:space:]]|$)'; then
3226
- block "find -delete removes files tree-wide (use -print to preview, or an explicit rm on reviewed paths)"
3227
- fi
3228
- if matches '(^|[^[:alnum:]_./-])find[[:space:]][^;&|]*-exec[[:space:]]+rm[[:space:]]+(-[[:alnum:]]*r[[:alnum:]]*f|-[[:alnum:]]*f[[:alnum:]]*r)([[:space:]]|$)'; then
3229
- block "find -exec rm -rf performs a recursive forced delete on unreviewed paths"
3230
- fi
3231
- # A command that reads its operands from STDIN and runs a program on them. The
3232
- # targets are therefore whatever the upstream stage emitted, which is exactly
3233
- # what makes a recursive forced delete behind one unauditable.
3234
- #
3235
- # Three fail-opens closed here (issue #3494), all of them the same mistake —
3236
- # this rule was written standalone instead of inheriting vocabulary the file
3237
- # already had:
3238
- #
3239
- # 1. The old prefix was `(^|[^[:alnum:]_./-])xargs`, whose excluded class
3240
- # contains `/`, so the character before `xargs` in `/usr/bin/xargs` was
3241
- # itself disqualifying and a PATH-SPELLED invocation never matched.
3242
- # `gxargs` — the GNU findutils spelling shipped by macOS package managers —
3243
- # failed the same way on the alphanumeric side. RM_CMD above solved this
3244
- # exact problem for `rm` by putting the boundary before the WHOLE path and
3245
- # making the directory part optional; that shape is reused verbatim.
3246
- # 2. `parallel` was absent. It is a drop-in `xargs` substitute reaching the
3247
- # same delete on the same unaudited stdin, and guard 14 below already had
3248
- # to name it in its own evidence — it was missing only here.
3249
- # 3. The flag set was a short-cluster-only copy, so `rm --recursive --force`
3250
- # was allowed where `rm -rf` was refused. It now uses the SAME tails as the
3251
- # rm walk, which is what makes that class of divergence unrepeatable.
3252
- readonly STDIN_DELETER='(^|[^[:alnum:]_./-])([[:alnum:]_./-]*/)?(g?xargs|parallel)[[:space:]]([^;&|]*[[:space:]])?rm'
3253
- if matches "$STDIN_DELETER$RM_RF_TAIL_CLUSTER" \
3254
- || matches "$STDIN_DELETER$RM_RF_TAIL_SPLIT"; then
3255
- block "xargs/parallel rm -rf performs a recursive forced delete on dynamic stdin input"
3256
- fi
3257
-
3258
- # 12. Disk destroyers, always on (exceeds upstream, which only scans these
3259
- # inside interpreter one-liners): writing to a raw /dev node via dd,
3260
- # formatting a device with mkfs, and shred's unrecoverable overwrite.
3261
- # dd/mkfs against regular files (imaging) stays allowed.
3262
- if matches '(^|[^[:alnum:]_./-])dd[[:space:]]+([^;&|]*[[:space:]])?of=/dev/'; then
3263
- block "dd writing to a raw device (of=/dev/…) destroys it"
3264
- fi
3265
- if matches '(^|[^[:alnum:]_./-])mkfs(\.[[:alnum:]]+)?[[:space:]][^;&|]*/dev/'; then
3266
- block "mkfs formatting a device erases it"
3267
- fi
3268
- if matches '(^|[^[:alnum:]_./-])shred([[:space:]]|$)'; then
3269
- block "shred overwrites files unrecoverably"
3270
- fi
3271
-
3272
- # 13. Dropping or truncating a database / schema / table (Lisa-only guard —
3273
- # upstream has no SQL protection; keep).
3274
- #
3275
- # The two arms used to be asymmetric, and only the lopsided one produced false
3276
- # positives (issue #3530). The `drop` arm requires a following keyword —
3277
- # `drop database|schema|table` — so `drop the ball` never matched it. The
3278
- # `truncate` arm made that keyword OPTIONAL:
3279
- #
3280
- # truncate[[:space:]]+(table[[:space:]]+)?[[:alnum:]_."`]+
3281
- #
3282
- # which reduces to "`truncate`, whitespace, any identifier-ish word", so
3283
- # `truncate the board`, `truncate results` and `truncate output` all matched.
3284
- # A session was refused for a bug-report TITLE describing a connection that
3285
- # truncates results — and a title has no escape hatch, because the remedy this
3286
- # hook prints at the wall (write the text to a file, pass it BY PATH) covers a
3287
- # body, while the title flag of an issue-filing CLI is necessarily inline. The
3288
- # only exit left was to reword, which is what trains people to route around a
3289
- # guard.
3290
- #
3291
- # The fix keeps the coverage and drops the English, in three arms.
3292
- #
3293
- # ARM 1 — `drop`, byte-identical to before. It was already correct, and a
3294
- # rewrite that unified the arms could only make it permissive.
3295
- readonly SQL_DROP='\bdrop[[:space:]]+(database|schema|table)\b'
3296
- # ARM 2 — `truncate` carrying its own evidence that it is a statement rather
3297
- # than a verb: the TABLE keyword (what the drop arm demands), a
3298
- # schema-qualified name, a quoted identifier, a trailing `;`, or one of the
3299
- # tail keywords that only ever follow a TRUNCATE. English has none of these.
3300
- readonly SQL_TRUNCATE_TAIL='(cascade|restrict|restart[[:space:]]+identity|continue[[:space:]]+identity)([^[:alnum:]_]|$)'
3301
- readonly SQL_TRUNCATE_EVIDENCE='\btruncate[[:space:]]+(table[[:space:]]+[[:alnum:]_."`]+|(only[[:space:]]+)?([[:alnum:]_]+\.[[:alnum:]_."`]+|["`][[:alnum:]_. ]+["`]|[[:alnum:]_]+[[:space:]]*(;|'"$SQL_TRUNCATE_TAIL"')))'
3302
- # ARM 3 — the permissive-dialect `TRUNCATE <name>` with none of that evidence.
3303
- # Deleting this shape is what a lazy fix does: it passes every prose scenario
3304
- # while silently removing the coverage a regression fixture already asserts
3305
- # (`mysql -e 'TRUNCATE sessions'`). So it is recognized by CONTEXT instead —
3306
- # the same command must also invoke a command-line database client. Prose in a
3307
- # tracker filing or a commit message invokes none, which is exactly the
3308
- # difference the text scan could not see on its own.
3309
- readonly SQL_CLIENT_TRUNCATE='(^|[;&|()][[:space:]]*)([[:alnum:]_./-]*/)?(psql|pgcli|mysql|mysqladmin|mysqlsh|mariadb|mycli|sqlite3|sqlcmd|cqlsh|clickhouse-client|cockroach|mongosh|duckdb|usql)([[:space:]]+[^;&|()]*)?[[:space:]]+(-e|-c|--command|--eval)(=|[[:space:]]+)[^;&|()]*\btruncate[[:space:]]+(only[[:space:]]+)?[[:alnum:]_."`]'
3310
- # Residual, accepted and stated: a bare `TRUNCATE <name>` with no terminator,
3311
- # no qualification and no recognized client in the same command goes unmatched
3312
- # — the same trade the `drop` arm has always made for `drop the ball`. No DROP
3313
- # shape is weakened, and the guard still fails in the safe direction.
3314
- if matches "$SQL_DROP" \
3315
- || matches "$SQL_TRUNCATE_EVIDENCE" \
3316
- || matches "$SQL_CLIENT_TRUNCATE"; then
3317
- block "destructive SQL (DROP/TRUNCATE) detected"
3318
- fi
3319
-
3320
- # 14. The git control plane. A recursive forced delete of `.git` destroys every
3321
- # commit, branch and stash that is not already pushed — the one directory whose
3322
- # loss is not recoverable from the working tree.
3323
- #
3324
- # This is not a new principle, it is a hole in one the guard already holds. Rule
3325
- # 4 above already refuses `rm -rf "$SOMEDIR"` and paths outside the project;
3326
- # `rm -rf .git` was permitted only because nothing named it. Measured before
3327
- # this rule existed: `rm -rf .git`, `rm -rf ./.git` and `rm -rf .git/objects`
3328
- # were all ALLOWED while the variable-expanded case was correctly blocked.
3329
- #
3330
- # `.git` must be a whole path component. `.gitignore`, `.gitattributes`,
3331
- # `.github/` and a `.git-old` backup are ordinary files a project deletes on
3332
- # purpose, and blocking those would be the collision that gets a guard switched
3333
- # off. The trailing `([/[:space:]'"$qc"']|$)` is what draws that line.
3334
- readonly GIT_CONTROL_PLANE='(^|[[:space:]='"$qc"'./])\.git([/[:space:]'"$qc"']|$)'
3335
- # This guard is the one segment walk that pairs TWO facts found in different
3336
- # places: the protected target (`.git`) and the destructive verb (a recursive
3337
- # forced delete). That makes its segmentation load-bearing in a way the rm and
3338
- # push walks' is not — those two read a verb and its own operands, which are
3339
- # always in one pipeline stage, so splitting on `|` costs them nothing.
3340
- #
3341
- # Here it cost everything. The old feeder was `tr '&|;' '\n'`, which cut a
3342
- # PIPELINE into pieces before the pairing question was asked, and a pipeline is
3343
- # exactly how a delete reaches a target named upstream of it:
3344
- # `find .git -type f -print0 | xargs -0 rm -rf` became `find .git -type f
3345
- # -print0` (a target, no verb) and `xargs -0 rm -rf` (a verb, no target), and
3346
- # neither half could answer. Measured before this fix, with the blanket
3347
- # `xargs rm -rf` rule masking the reported shape: `find .git -type d | parallel
3348
- # rm -rf`, `… | /usr/bin/xargs rm -rf`, `… | xargs -0 -- rm --recursive
3349
- # --force`, `… 2>&1 | parallel rm -rf`, `… |& parallel rm -rf` and
3350
- # `cat .git/config | grep url | rm -rf refs` were ALL allowed (CodySwannGT/lisa#3320).
3351
- #
3352
- # So segment on STATEMENT boundaries and nothing else. A pipe joins stages of
3353
- # one statement; `;`, `&`, `&&` and `||` end one. Three spellings have to be
3354
- # normalized first or a naive split gets them wrong in both directions:
3355
- #
3356
- # `|&` bash's pipe-with-stderr. Splitting its `&` would halve a pipeline —
3357
- # the same fail-open, wearing a different operator. Becomes `|`.
3358
- # `2>&1` a redirection, not a boundary (also `>&2`, `<&3`, `&>file`). These
3359
- # are where `&` appears WITHOUT ending a statement, and they are
3360
- # common enough that ignoring them would reopen the hole on any
3361
- # pipeline that redirects stderr. The `&` is folded away.
3362
- # `||` a real boundary that happens to be built from pipe characters, so it
3363
- # must be recognized BEFORE a single `|` is spared. Becomes `;`.
3364
- #
3365
- # Every one of those rewrites only ever REMOVES a boundary or leaves it intact,
3366
- # so each can merge two segments but never split one — the fail-closed
3367
- # direction. `&` and `;` still separate, so unrelated commands are not joined.
3368
- #
3369
- # The leading awk is the same idea one level up. A line ending in `|` is bash's
3370
- # OTHER implicit continuation — the pipeline resumes on the next line — and the
3371
- # per-line read below would otherwise part the stages exactly as `tr` did, so
3372
- # `find .git -type d |`↵` parallel rm -rf` fails open through the newline
3373
- # instead of through the pipe. This mirrors the backslash-continuation join that
3374
- # `normalized_command_str` already performs for the same reason. It is done here
3375
- # rather than in that shared normalization deliberately: this guard is the one
3376
- # that pairs facts across stages, so it is the one that needs the stages kept
3377
- # together, and widening the shared normalization would change every other
3378
- # guard's segmentation for no defect anyone has measured.
3379
- #
3380
- # The status check is the second half of the fix and closes a quieter hole. This
3381
- # feeder had none, while the rm and push walks above both have one: a segmenter
3382
- # that could not run produced no lines, the loop body never executed, and the
3383
- # guard was skipped with the command ALLOWED. A segmentation that cannot answer
3384
- # must refuse, exactly like a scan that cannot answer.
3385
- # 14b. Linked worktrees, which are the same principle one level out. `.git` is
3386
- # protected because nothing in the working tree can rebuild it; a linked
3387
- # worktree is protected because nothing OUTSIDE it can rebuild what it holds.
3388
- # The asymmetry is exact and it is invisible from the prompt: `.git/refs` and
3389
- # the object store are shared by every worktree of a repository, while
3390
- # `.git/index` and the working files are per-worktree. So `git commit` moves
3391
- # work somewhere a deletion cannot reach, and `git add` does not — a staged file
3392
- # shows green in `git status`, which reads as saved, and dies with the
3393
- # directory.
3394
- #
3395
- # Measured twice in one evening (issue #3863): one worktree lost a 284-line
3396
- # staged test file, and a second lost nothing from the identical event purely
3397
- # because a gate had forced its work into a commit first. Neither deletion
3398
- # announced itself. That is the second reason this is a block rather than a
3399
- # warning — a worktree deletion destroys the only evidence its own case could
3400
- # leave, so there is no after-the-fact detection to fall back on.
3401
- #
3402
- # `git worktree remove` (guard 12) already refuses a dirty tree, and
3403
- # `--force` is already blocked. This closes the spelling that walks around both:
3404
- # `rm -rf` on the directory, which git never sees.
3405
- #
3406
- # Matching is by REGISTERED path — `git worktree list` names them — so an
3407
- # ordinary directory that merely lives near one is untouched. A repository that
3408
- # cannot be read answers "no": this guard adds protection to a shape that was
3409
- # fully allowed a moment ago, and failing it closed would deny every recursive
3410
- # delete on every path outside a repository.
3411
- #
3412
- # The comparison is on WHOLE TOKENS, which is the only spelling that gets both
3413
- # error directions right. Substring containment would let a worktree named
3414
- # `wt-1` claim `rm -rf wt-10`, an over-block on an unrelated directory; and
3415
- # hand-written boundary classes leak the other way, because `rm -rf <wt>/`
3416
- # with one trailing slash ends on a character every such class treats as
3417
- # "inside a path". So every non-path character — quote, space, parenthesis,
3418
- # redirection — is folded to a space first, which makes each argument a
3419
- # space-delimited token regardless of how it was quoted, and the match is then
3420
- # an equality test on that token. A SUBPATH (`rm -rf <wt>/node_modules`) is
3421
- # deliberately not this guard's business: it is not a worktree deletion, and
3422
- # blocking routine cleanup inside a worktree is how a guard gets switched off.
3423
- names_linked_worktree() {
3424
- local stmt="$1" probe root listed line primary wt rel
3425
- root="$(git -C "${CLAUDE_PROJECT_DIR:-$PWD}" rev-parse --show-toplevel 2> /dev/null)" || return 1
3426
- [ -n "$root" ] || return 1
3427
- listed="$(git -C "$root" worktree list --porcelain 2> /dev/null)" || return 1
3428
- probe=" $(printf '%s' "$stmt" | tr -c 'A-Za-z0-9_./-' ' ') "
3429
- primary=""
3430
- while IFS= read -r line; do
3431
- case "$line" in
3432
- worktree\ *) wt="${line#worktree }" ;;
3433
- *) continue ;;
3434
- esac
3435
- # First entry is the primary checkout, which is not a linked worktree.
3436
- if [ -z "$primary" ]; then
3437
- primary="$wt"
3438
- continue
3439
- fi
3440
- case "$probe" in
3441
- *" $wt "* | *" $wt/ "*) return 0 ;;
3442
- esac
3443
- rel="${wt#"$primary"/}"
3444
- [ "$rel" != "$wt" ] || continue
3445
- # `./` is the same path spelled the way an agent in the project root types
3446
- # it, and a token comparison is exact, so it has to be spelled here too.
3447
- case "$probe" in
3448
- *" $rel "* | *" $rel/ "* | *" ./$rel "* | *" ./$rel/ "*) return 0 ;;
3449
- esac
3450
- done <<EOF
3451
- $listed
3452
- EOF
3453
- return 1
3454
- }
3455
-
3456
- git_segments_status=0
3457
- git_segments="$(printf '%s' "$normalized_command_str" \
3458
- | awk '{ if (/\|[ \t]*$/) printf "%s ", $0; else print }' \
3459
- | sed -e 's/|&/|/g' \
3460
- -e 's/&>/>/g' \
3461
- -e 's/[0-9]*>&[0-9-]*/>/g' \
3462
- -e 's/[0-9]*<&[0-9-]*/</g' \
3463
- -e 's/||/;/g' \
3464
- | tr '&;' '\n' \
3465
- | grep -E -- "$RM_RF_CLUSTER|$RM_RF_SPLIT")" || git_segments_status=$?
3466
- case "$git_segments_status" in
3467
- 0 | 1) ;;
3468
- *) scan_failed "$git_segments_status" ;;
3469
- esac
3470
- while IFS= read -r git_stmt; do
3471
- [ -n "$git_stmt" ] || continue
3472
- if ! scan -E "$git_stmt" "$RM_RF_CLUSTER" \
3473
- && ! scan -E "$git_stmt" "$RM_RF_SPLIT"; then
3474
- continue
3475
- fi
3476
- if scan -E "$git_stmt" "$GIT_CONTROL_PLANE"; then
3477
- block "recursive forced delete of the git control plane (.git holds every commit, branch and stash not already pushed; nothing in the working tree can rebuild it). Delete a specific ignored artifact instead. Re-cloning is NOT a like-for-like replacement: every linked worktree stores a pointer into this .git, so discarding it discards each of them and any uncommitted work they hold — check \`git worktree list\` before treating the checkout as disposable."
3478
- fi
3479
- if names_linked_worktree "$git_stmt"; then
3480
- block "recursive forced delete of a linked git worktree. A worktree's index and working files are private to it — only commits are shared — so this destroys any staged or unwritten-to-a-commit work another agent left there, and destroys the evidence that it did (CodySwannGT/lisa#3863). Use 'node scripts/lisa-worktree-guard.mjs remove <path>' instead: it deletes clean and already-committed trees without ceremony, names the files when they exist nowhere else, and records an explicit --force override."
3481
- fi
3482
- done <<<"$git_segments"
3483
-
3484
- # 15. Credential stores. Reading one into an agent transcript is disclosure even
3485
- # when nothing is copied anywhere: the value lands in a log, a context window,
3486
- # and whatever retains either.
3487
- #
3488
- # Scoped deliberately rather than by the obvious pattern. Each clause below is a
3489
- # separate judgement about a family where an agent has no legitimate read, and
3490
- # each carries the exclusions that keep ordinary work moving — public keys,
3491
- # known_hosts, ssh config, and `.env.example` are all still readable, because a
3492
- # guard that blocks routine setup is a guard somebody disables.
3493
-
3494
- # The verbs that disclose: read it, duplicate it, or send it. Writing is NOT
3495
- # here — `echo FOO=1 > .env` during setup creates a secret rather than leaking
3496
- # one, and refusing it would block the very workflow that produces the file.
3497
- readonly SECRET_READ_VERB='(^|[^[:alnum:]_./-])([[:alnum:]_./-]*/)?(cat|bat|less|more|head|tail|strings|xxd|od|base64|cp|mv|rsync|scp|sftp|tar|zip|curl|wget|http|nc)([[:space:]]|$)'
3498
-
3499
- # 15a. SSH PRIVATE keys. `id_rsa.pub` and friends are public by construction and
3500
- # stay readable; so do `known_hosts`, `config` and `authorized_keys`, which
3501
- # agents legitimately inspect when diagnosing a remote.
3502
- readonly SSH_PRIVATE_KEY='\.ssh/(id_[[:alnum:]_-]+|[[:alnum:]_.-]*_(rsa|dsa|ecdsa|ed25519))([[:space:]'"$qc"']|$)'
3503
- # 15b. Cloud provider credential files.
3504
- readonly CLOUD_CREDENTIAL='(\.aws/(credentials|config)|\.config/gcloud/[[:alnum:]_./-]*credentials[[:alnum:]_.-]*|\.azure/(accessTokens|msal_token_cache)[[:alnum:]_.-]*|\.kube/config)([[:space:]'"$qc"']|$)'
3505
- # 15c. Coding-agent credential stores — the tokens that impersonate the operator
3506
- # to every service their agent can reach.
3507
- readonly AGENT_CREDENTIAL='(\.(claude|codex|cursor|copilot|gemini|antigravity)/[[:alnum:]_./-]*(credentials|auth|token)[[:alnum:]_.-]*|\.netrc|\.npmrc|\.pypirc|\.docker/config\.json)([[:space:]'"$qc"']|$)'
3508
- # 15d. Dotenv files. `.env.example`, `.sample`, `.template`, `.dist` and
3509
- # `.schema` are checked-in documentation of which keys exist, never the values,
3510
- # so they are excluded — that collision is the one this rule most had to avoid.
3511
- # Decide dotenv privacy per PATH, never by subtracting one command-wide match
3512
- # from another. A command that names `.env.example` and `.env` contains both a
3513
- # public path and a private one; seeing the former cannot authorize the latter.
3514
- #
3515
- # The one write-only shape this guard has always allowed remains explicit:
3516
- # seeding a private dotenv destination from one public template. This is safe
3517
- # because the private path is the destination, not a value being read back.
3518
- has_private_dotenv_path() {
3519
- dotenv_scan_status=0
3520
- dotenv_candidates="$(printf '%s' "$normalized_command_str" \
3521
- | grep -Eio -- '(^|[[:space:]='"$qc"'./])\.env(\.[[:alnum:]_-]+)?')" \
3522
- || dotenv_scan_status=$?
3523
- if [ "$dotenv_scan_status" -gt 1 ]; then
3524
- scan_failed "$dotenv_scan_status"
3525
- fi
3526
-
3527
- while IFS= read -r candidate; do
3528
- [ -n "$candidate" ] || continue
3529
- dotenv_normalize_status=0
3530
- candidate="$(printf '%s' "$candidate" \
3531
- | tr '[:upper:]' '[:lower:]' \
3532
- | grep -Eo -- '\.env(\.[[:alnum:]_-]+)?')" \
3533
- || dotenv_normalize_status=$?
3534
- if [ "$dotenv_normalize_status" -gt 1 ] || [ -z "$candidate" ]; then
3535
- scan_failed "$dotenv_normalize_status"
3536
- fi
3537
- case "$candidate" in
3538
- .env.example | .env.sample | .env.template | .env.dist | .env.schema | .env.defaults) ;;
3539
- *) return 0 ;;
3540
- esac
3541
- done <<EOF
3542
- $dotenv_candidates
3543
- EOF
3544
- return 1
3545
- }
3546
-
3547
- readonly SAFE_DOTENV_SEED='^[[:space:]]*(cp|mv)[[:space:]]+\.env\.(example|sample|template|dist|schema|defaults)[[:space:]]+\.env(\.[[:alnum:]_-]+)?[[:space:]]*$'
3548
-
3549
- if matches "$SECRET_READ_VERB"; then
3550
- if matches "$SSH_PRIVATE_KEY"; then
3551
- block "reading, copying or transmitting an SSH PRIVATE key. Public keys (.pub), known_hosts and ssh config are unaffected; if you need the fingerprint use \`ssh-keygen -lf <key>.pub\`."
3552
- fi
3553
- if matches "$CLOUD_CREDENTIAL"; then
3554
- block "reading, copying or transmitting a cloud provider credential file. Use the provider CLI's own identity command (\`aws sts get-caller-identity\`, \`gcloud auth list\`) instead of reading the file."
3555
- fi
3556
- if matches "$AGENT_CREDENTIAL"; then
3557
- block "reading, copying or transmitting a coding-agent or package-registry credential store. These tokens impersonate the operator to every service the agent can reach."
3558
- fi
3559
- # A public path elsewhere in the command never exempts a private path. The
3560
- # narrow public-template -> private-destination seed is write-only and remains
3561
- # allowed; every other command containing a private dotenv path is refused.
3562
- if has_private_dotenv_path && ! matches "$SAFE_DOTENV_SEED"; then
3563
- block "reading, copying or transmitting a dotenv file holding real values. \`.env.example\`, \`.env.sample\`, \`.env.template\` and \`.env.dist\` are readable, and WRITING a .env is unaffected — only reading one back is refused."
3564
- fi
3565
- # Fail-closed, narrowly. A read whose DIRECTORY is a known credential store
3566
- # but whose leaf is variable-expanded cannot be classified, and #2980's lesson
3567
- # is that a guard which cannot classify must refuse rather than permit. Scoped
3568
- # to credential directories on purpose: refusing every \`cat "\$FILE"\` would be
3569
- # the over-reach that gets the whole hook switched off.
3570
- if matches_cs '(\.ssh|\.aws|\.config/gcloud|\.azure|\.kube)/[^[:space:]'"$qc"']*\$'; then
3571
- block "reading a path inside a credential directory whose filename is variable-expanded, so the guard cannot tell which file it is. Name the file explicitly if it is genuinely not a secret."
3572
- fi
3573
- fi
3574
-
3575
- # 16. Project-local custom rules. Each non-comment line is an ERE; a match blocks.
3576
- rules_file="${SAFETY_NET_RULES_FILE:-${CLAUDE_PROJECT_DIR:-$PWD}/.claude/safety-net-rules.txt}"
3577
- if [ -f "$rules_file" ]; then
3578
- # Custom rules can intentionally govern text itself, so preserve their input.
3579
- custom_command_str="$(printf '%s\n%s' "$custom_command_for_guards" "$followed_text" \
3580
- | awk '{ if (sub(/\\$/, "")) printf "%s ", $0; else print }')"
3581
- while IFS= read -r rule || [ -n "$rule" ]; do
3582
- case "$rule" in
3583
- '' | '#'*) continue ;;
3584
- esac
3585
- # Normalized text, for the same reason every built-in guard uses it: a
3586
- # project rule must not be evadable by breaking the command across lines.
3587
- #
3588
- # `|| rule_status=$?` rather than a bare pipeline: this script runs under
3589
- # `set -e`, and a no-match grep exits 1, which would end the hook right
3590
- # here — before the remaining rules ran, and with an exit status that is
3591
- # not a refusal. The `||` puts the pipeline in a condition context, where
3592
- # a non-zero status is expected rather than fatal.
3593
- # A here-string, never a pipe. With `printf | grep` under pipefail, a grep
3594
- # that stops at its first match (`-q`, and GNU grep whose stdout is
3595
- # /dev/null, which it treats as `-q`) closes the pipe while printf is still
3596
- # writing; printf takes SIGPIPE and the pipeline reports 141 instead of
3597
- # grep's 0. 141 lands in the `*)` arm below and a rule that MATCHED was
3598
- # reported as an invalid regex and not enforced (CodySwannGT/lisa#4564).
3599
- # A here-string has no writer process, so the status is grep's alone.
3600
- #
3601
- # The here-string is staged by the shell (a pipe, or a temp file for a
3602
- # large body or on Bash 3.2), and that staging can fail: no temp space,
3603
- # a file-size limit. A failed redirection on a bare `grep … <<<` returns
3604
- # 1, the same status as "no match", so the rule would silently pass. The
3605
- # brace group separates the two: grep's own status is captured INSIDE it,
3606
- # so the group itself only fails when the redirection could not be set up.
3607
- #
3608
- # SIGXFSZ is ignored first. A temp-file write that the file-size limit
3609
- # refuses raises SIGXFSZ, and by default that kills the shell before
3610
- # `unstaged` can run (measured: this step alone exits 153 on Bash 3.2
3611
- # under `ulimit -f 0`); exit 153 is not a refusal to the enforcement
3612
- # fallback. block() writes its refusal without a temp file for the same
3613
- # reason, so a rule that matched and a command that could not be staged
3614
- # both still end in exit 2 under that limit (CodySwannGT/lisa#4571).
3615
- trap '' XFSZ
3616
- rule_status=0
3617
- { grep -qEi -- "$rule" || rule_status=$?; } <<<"$custom_command_str" \
3618
- || rule_status=unstaged
3619
- case "$rule_status" in
3620
- 0) block "matched a project custom safety rule (${rules_file##*/}): $rule" ;;
3621
- # Fail closed: the rule could not be evaluated at all, which is not the
3622
- # same thing as the rule not matching.
3623
- unstaged) block "could not stage the command to check project custom safety rule (${rules_file##*/}): $rule" ;;
3624
- 1) ;; # no match
3625
- # grep exits 2 on a malformed ERE. Treated as no-match before, so a typo
3626
- # in a project's rules file silently disabled that rule — a guard the
3627
- # project believed it had. Say so instead; still non-fatal, because one
3628
- # bad line must not take the other rules down with it.
3629
- *)
3630
- printf 'parity-safety-net: invalid regex in %s, rule NOT enforced: %s\n' \
3631
- "$rules_file" "$rule" >&2
3632
- ;;
3633
- esac
3634
- done <"$rules_file"
3635
- trap - XFSZ
3636
- fi
3637
-
10
+ # Drain hook input with bounded Bash builtins so native writers do not hit a
11
+ # closed pipe. Nothing in the input is interpreted or executed.
12
+ while IFS= read -r -n 8192 _lisa_retired_chunk || [ -n "$_lisa_retired_chunk" ]; do :; done
3638
13
  exit 0