Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions .changes/disk-hygiene/work-issue-6242-7d2e4b1a.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
---
bump: patch
---

### Fixed

- **The engine gate no longer denies a simple reader command that only quotes the engine file name.** `gh issue create --title '... hygiene.py ...'` and the other commands on a closed reader allowlist (`cat`, `head`, `tail`, `wc`, `grep`, `rg` without `--pre`, `git show`/`log`/`diff`/`grep` without `-c` or `-O`, `gh issue`/`pr`) now treat single-quoted and `$`/backtick-free double-quoted literals as data. A pipeline, `awk`, `sed`, any unquoted operator, and a word that resolves to the engine still gate. On Bash and PowerShell alike, a quoted word that is a link to the engine under any name now gates too. Refs #6242.
147 changes: 134 additions & 13 deletions plugins/disk-hygiene/skills/clean/scripts/destructive_guard.py
Original file line number Diff line number Diff line change
Expand Up @@ -843,6 +843,91 @@ def _powershell_without_string_data(command: str) -> str | None:
return None if command_word in blocked else stripped


# Outside string data: expansion, escape, comment, statement-separator, grouping
# and redirection syntax. Any of them keeps the gate, so a pipeline or a second
# command never reads as one simple reader.
_BASH_CODE_CHARS = frozenset("$`\\#;&|<>(){}\r\n")
# Reader command words whose arguments cannot run a string. ``git`` and ``gh``
# are further limited to the subcommands in ``_BASH_READER_SUBCOMMANDS``.
_BASH_READERS = frozenset({"cat", "head", "tail", "wc", "grep", "rg", "git", "gh"})
_BASH_READER_SUBCOMMANDS = {
"git": frozenset({"show", "log", "diff", "grep"}),
"gh": frozenset({"issue", "pr"}),
}
_BASH_QUOTE_STRIP = str.maketrans("", "", "'\"")


def _bash_without_string_data(command: str) -> str | None:
"""``command`` with each string literal replaced by ``_``, or None to keep it.

The Bash counterpart of ``_powershell_without_string_data``, narrower
because Bash quoting is easier to misread. Returns a rewrite only for ONE
simple command (no unquoted operator, expansion, escape, comment or
newline, so a pipeline stays fail-closed) whose command word is a bare name
on the closed reader allowlist: ``cat``, ``head``, ``tail``, ``wc``,
``grep``, ``rg`` without ``--pre``, ``git show``/``log``/``diff``/``grep``
without ``-c`` or ``-O``/``--open-files-in-pager``, and ``gh issue``/``pr``.
Single-quoted literals are blanked as data, double-quoted ones only when
they hold no ``$`` or backtick. None, meaning the caller must classify the
command as written, for anything else: a quoted or path-qualified command
word, a reader outside the allowlist (``awk`` and ``sed`` can run a quoted
program), a git option before the subcommand, an unterminated literal.
"""
if "\\" in command:
# An escaped quote in a double-quoted literal flips the quote parity of
# a scanner that does not model it, hiding a real separator.
return None
out: list[str] = []
index = 0
while index < len(command):
char = command[index]
if char in {"'", '"'}:
end = command.find(char, index + 1)
if end < 0:
return None
if char == '"' and ("$" in command[index:end] or "`" in command[index:end]):
return None
out.append("_")
index = end + 1
continue
if char in _BASH_CODE_CHARS:
return None
out.append(char)
index += 1
words = "".join(out).split()
if not words or command.lstrip(" \t")[:1] in {"'", '"'}:
return None
if words[0] not in _BASH_READERS:
return None
subcommands = _BASH_READER_SUBCOMMANDS.get(words[0])
if subcommands is not None and (len(words) < 2 or words[1] not in subcommands):
return None
# Read the options with the quotes removed: ``rg '--pre' sh`` is ``--pre``.
if any(
_bash_reader_option_runs_program(words[0], word)
for word in command.translate(_BASH_QUOTE_STRIP).split()[1:]
):
return None
return "".join(out)


def _bash_reader_option_runs_program(reader: str, word: str) -> bool:
"""Whether ``word`` may be an option that makes ``reader`` run a program.

Conservative: git's short options cluster (``-nO<cmd>``) and its long
options abbreviate to any unique prefix (``--open``), so a short cluster
holding ``c`` or ``O`` and any prefix of ``--open-files-in-pager`` count.
"""
if reader == "rg":
return word.startswith(("--pre", "--hostname-bin"))
if reader != "git" or not word.startswith("-"):
return False
if word.startswith("--"):
name = word.split("=", 1)[0]
return len(name) > 2 and "--open-files-in-pager".startswith(name)
return "c" in word or "O" in word


def _engine_gate_relevant(command: str, tool_name: str = "Bash") -> bool:
"""Decide whether the plugin-level engine gate should act on ``command``.

Expand Down Expand Up @@ -894,6 +979,23 @@ def _engine_gate_relevant(command: str, tool_name: str = "Bash") -> bool:
executor list does not name that runs a string naming the engine
(``ssh host './hygiene.py scan'``) reads as data.

On Bash the same holds for ONE simple reader command only
(``_bash_without_string_data``): ``cat``, ``head``, ``tail``, ``wc``,
``grep``, ``rg`` without ``--pre``, ``git show``/``log``/``diff``/``grep``
without ``-c`` or ``-O``/``--open-files-in-pager``, and ``gh issue``/``pr``,
with no unquoted operator, and only single-quoted and ``$``/backtick-free
double-quoted literals blanked. So ``gh issue create --title '... hygiene.py
...'`` defers. A pipeline of readers, ``awk`` and ``sed`` (a quoted program
can run code) stay classified as written, and identity is again checked
before blanking. Accepted residual: the gate reads ``gh`` by its first two
words, so a ``gh`` alias that runs a shell command (``gh alias set --shell``
or a ``!`` expansion) is not modeled; the allowlist names only ``issue``
and ``pr``.

On both shells, the identity check before blanking reads every word, not
only those carrying the marker, so a quoted link to the engine under any
name (``gh issue create --title x 'alias'``) still gates.

A word that is the SAME FILE as the bundled engine — a symlink or hard link
under any name — gates regardless of its filename. Without the marker, each
distinct whitespace token (or ``_literal_shell_words`` word) is read two
Expand Down Expand Up @@ -945,9 +1047,25 @@ def _same_file_as_bundled(word: str) -> bool:
"""
return _samefile(word) or (not os.path.isabs(word) and _in_engine_dir(word))

engine_drive = os.path.splitdrive(bundled.parent)[0].casefold()

def _names_engine(candidate: str) -> bool:
# As written, or joined to the engine's directory when relative,
# non-empty and carrying no drive or the engine's own.
return _samefile(candidate) or (
bool(candidate)
and not os.path.isabs(candidate)
and os.path.splitdrive(candidate)[0].casefold() in {"", engine_drive}
and _in_engine_dir(candidate)
)

allow_backslash = tool_name == "PowerShell"
data_free = _powershell_without_string_data(command) if allow_backslash else None
if data_free is not None:
data_free = (
_powershell_without_string_data(command)
if allow_backslash
else _bash_without_string_data(command)
)
if data_free is not None and (allow_backslash or data_free != command):
Comment thread
melodic-automation-lanes[bot] marked this conversation as resolved.
Resolved
Comment thread
kyle-sexton marked this conversation as resolved.
Resolved
# Identity is read on the command AS WRITTEN, before any literal is
# blanked: a word naming one of this plugin's engines gates even when
# it sits in string data.
Expand All @@ -958,6 +1076,19 @@ def _same_file_as_bundled(word: str) -> bool:
for candidate in (token, word)
):
return True
# Marker-free names too: a link to the engine under a name without the
# marker, written in quotes, would otherwise be blanked to `_` and
# never identity-checked. Same all-tokens scan as the marker-free
# branch below, over the command as written.
written_words = _literal_shell_words(command, allow_backslash=allow_backslash)
Comment thread
kyle-sexton marked this conversation as resolved.
Resolved
if any(
_samefile(candidate)
Comment thread
kyle-sexton marked this conversation as resolved.
Resolved
for candidate in dict.fromkeys(
[token.strip("'\"") for token in command.split()]
+ ([] if written_words is None else list(written_words))
)
):
return True
command = data_free
marker_candidates = _marker_tokens(command)
if not any(_carries_marker(token) for token in marker_candidates):
Expand Down Expand Up @@ -991,17 +1122,7 @@ def _same_file_as_bundled(word: str) -> bool:
if words is None
else list(words)
)
engine_drive = os.path.splitdrive(bundled.parent)[0].casefold()
return any(
_samefile(candidate)
or (
bool(candidate)
and not os.path.isabs(candidate)
and os.path.splitdrive(candidate)[0].casefold() in {"", engine_drive}
and _in_engine_dir(candidate)
)
for candidate in dict.fromkeys(candidates)
)
return any(_names_engine(candidate) for candidate in dict.fromkeys(candidates))
words = _literal_shell_words(command, allow_backslash=allow_backslash)
if words is None:
# Marker present but not literally parseable (operators, compounds).
Expand Down
83 changes: 81 additions & 2 deletions plugins/disk-hygiene/skills/clean/scripts/test_hygiene.py
Original file line number Diff line number Diff line change
Expand Up @@ -10781,12 +10781,72 @@ def test_engine_gate_gates_a_relative_word_that_resolves_to_the_engine(
self._gated_reason(command),
)

def test_engine_gate_defers_a_simple_reader_that_only_quotes_the_engine_name(
self,
) -> None:
"""#6242: quoted data naming the engine is a mention for a closed reader set."""
with tempfile.TemporaryDirectory() as tmp, chdir_context(tmp):
for command in (
"gh issue create --title 'gate denies (only name hygiene.py)'"
" --body-file body.md",
"gh issue create --title 'x' --body 'run python3 hygiene.py scan'",
'gh issue list --search "python3 hygiene.py"',
"gh pr view 5 --comment 'hygiene.py scan (see)'",
"git log --grep 'hygiene.py (engine)'",
"git diff -- 'hygiene.py'",
"cat 'notes (hygiene.py).md'",
"rg 'python3 hygiene.py' README.md",
"gh issue create --body 'line one\nhygiene.py\nline three'",
):
with self.subTest(command=command):
self.assertFalse(guard._engine_gate_relevant(command, "Bash"))

def test_engine_gate_keeps_gating_what_the_string_data_rule_does_not_cover(
Comment thread
kyle-sexton marked this conversation as resolved.
Resolved
self,
) -> None:
engine = guard._display_path(guard._engine_script_path())
with tempfile.TemporaryDirectory() as tmp, chdir_context(tmp):
for command in (
# A pipeline stays fail-closed.
"git show 'hygiene.py (x)' | grep foo",
"gh issue create --title 'hygiene.py' && echo done",
"gh issue create --title 'hygiene.py'; echo done",
# Readers outside the allowlist read as written.
"awk '/hygiene.py/ {print}' notes.txt",
"sed -n '/hygiene.py (x)/p' notes.txt",
"echo 'python3 hygiene.py scan (x)'",
"bash -c 'python3 hygiene.py scan'",
# A double-quoted literal holding an expansion is not data.
'gh issue create --title "hygiene.py $(whoami)"',
'gh issue create --title "python3 hygiene.py $X"',
'gh issue create --title "python3 hygiene.py `x`"',
# Options that make a reader run another program.
"rg --pre 'python3 hygiene.py (x)' foo",
"rg '--pre' 'python3 hygiene.py (x)' foo",
"git -c 'alias.x=!python3 hygiene.py' show HEAD",
"git grep -O'python3 hygiene.py (x)' foo",
'grep "a\\" "; python3 hygiene.py apply; echo \\"',
"git grep -nO'python3 hygiene.py apply' x",
"git grep -nc'python3 hygiene.py apply' x",
"git grep --open-files-in-p 'python3 hygiene.py apply' x",
"git grep --open 'python3 hygiene.py apply' x",
"rg --hostname-bin 'python3 hygiene.py apply' x",
# A subcommand outside the allowlist.
"gh api -X POST 'hygiene.py (x)'",
"git push 'hygiene.py (x)'",
# Identity is read on the command as written.
f"cat '{engine}'",
f'gh issue create --body "{engine}"',
f"head -n 3 '{engine}' ",
):
with self.subTest(command=command):
self.assertTrue(guard._engine_gate_relevant(command, "Bash"))

def test_engine_gate_denial_names_the_payload_word_it_gated(self) -> None:
cases = (
'gh issue list --search "python3 hygiene.py"',
'gh issue list --search "hygiene.py scan"',
'echo "run python3 hygiene.py"',
'"python3 hygiene.py scan"',
'echo "hygiene.py scan"',
Comment thread
kyle-sexton marked this conversation as resolved.
Resolved
)
with tempfile.TemporaryDirectory() as tmp, chdir_context(tmp):
for command in cases:
Expand Down Expand Up @@ -11733,6 +11793,25 @@ def test_engine_gate_bare_link_outside_engine_dir_gates(self) -> None:
assert result is not None
self.assertEqual("deny", result["hookSpecificOutput"]["permissionDecision"])

def test_engine_gate_quoted_marker_free_link_gates_a_reader(self) -> None:
"""A quoted word naming a marker-free link to the engine gates a reader.

Blanking string data would hide the quoted name from the marker-free
branch, so identity is read on the command as written, for both shells.
`@@` holds no path-legal character, so no marker token reaches it and
only the whole-word scan sees it.
"""
for name in ("cleanup", "@@"):
command = f"gh issue create --title 'x' '{name}'"
for shell in ("Bash", "PowerShell"):
with self.subTest(name=name, shell=shell):
with tempfile.TemporaryDirectory(dir=SCRIPT_DIR) as tmp:
with chdir_context(tmp):
gated = guard._engine_gate_relevant
self.assertFalse(gated(command, shell))
self._hard_link_or_skip(Path(tmp) / name)
self.assertTrue(gated(command, shell))

def test_engine_gate_marker_free_probes_each_distinct_word_twice(self) -> None:
"""Counted `os.path.samefile` calls for marker-free commands.

Expand Down
Loading