@codyswann/lisa 4.90.0 → 4.90.2

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