fix(approval): fold an escaped space in the home whatever the quote state

The quote check read the shell with a lexical scanner that a quote in a
comment, heredoc body or backtick desyncs, so a real unquoted
/home/John\ Smith/hermes/config.yaml after one looked quoted, stayed
unfolded and passed as safe. Read every \ inside the home as a space:
a quoted one now costs a prompt instead of a lost gate. The rule for a
\ right after the home needs no quote state and stays. Dropping the
scanner also removes its per-$( recursion.
This commit is contained in:
Maciej Lisiewski
2026-11-18 21:10:38 +01:00
parent a2d96bf5b4
commit c6bc048fcc
2 changed files with 48 additions and 41 deletions

View File

@@ -113,10 +113,12 @@ class TestShellEscapedSpaceInWindowsHome:
assert _is_dangerous(r"sed -i s/a/b/ /c/Users/John\ Smith/AppData/Local/hermes2/config.yaml") is False
class TestEscapedSpaceFollowsShellQuoting:
r"""``\ `` is the same character as a space only where the shell reads it as an escape. Folding it
anywhere else names a directory the command does not touch, and gates a harmless command as an
edit of Hermes's own home."""
class TestEscapedSpaceFailsClosed:
r"""An unquoted ``\ `` is the same character as a space, so a path spelled through it is the home.
Whether a given ``\ `` is unquoted takes a full shell parse: a quote in a comment, a heredoc body
or a backtick flips every lexical quote model for the rest of the command. The fold therefore
reads every ``\ `` inside a home spelling as a space; a quoted one costs a prompt, a misread one
would lose the gate on the approval policy file."""
@pytest.fixture
def spaced_hermes_home(self, monkeypatch):
@@ -134,7 +136,9 @@ class TestEscapedSpaceFollowsShellQuoting:
def test_an_escaped_space_after_the_home_continues_the_name(self, spaced_hermes_home):
# `hermes\ data\ backup` is one directory, a sibling of the home, not the home plus a word.
# Quoted, the backslash is literal and the name is no closer to the home: no quote state matters.
assert _is_dangerous(r"mv /home/tester/hermes\ data\ backup /home/tester/backup") is False
assert _is_dangerous(r"mv '/home/tester/hermes\ data\ backup' /home/tester/backup") is False
def test_an_escaped_space_after_a_spaceless_home_continues_the_name(self, monkeypatch):
monkeypatch.setenv("HOME", "/home/tester")
@@ -145,17 +149,40 @@ class TestEscapedSpaceFollowsShellQuoting:
assert _is_dangerous(r"sed -i s/a/b/ /home/John\ Smith/hermes/config.yaml") is True
assert _is_dangerous(r"sed -i s/a/b/ /home/John\ Smith/hermes2/config.yaml") is False
@pytest.mark.parametrize("prefix", [
"echo hi # don't\n",
"# it's\n",
"cat <<EOF >/dev/null\nit's\nEOF\n",
"cat <<-EOF >/dev/null\n\tit's\n\tEOF\n",
': <<EOF\n"\nEOF\n',
"echo `echo '`; ",
'echo `echo "`; ',
"echo ${x#'}; ",
"echo {a,'}; ",
])
@pytest.mark.parametrize("home, hermes_home, path", [
("/home/John Smith", "/home/John Smith/hermes", r"/home/John\ Smith/hermes/config.yaml"),
("/home/tester", "/home/tester/hermes data", r"/home/tester/hermes\ data/config.yaml"),
])
def test_a_stray_quote_earlier_does_not_hide_an_unquoted_escape(
self, monkeypatch, prefix, home, hermes_home, path):
# Each command runs in bash and rewrites HERMES_HOME/config.yaml: the quote before it is
# inert (comment, heredoc body, backtick body, expansion), the path after it is unquoted.
monkeypatch.setenv("HOME", home)
monkeypatch.setenv("HERMES_HOME", hermes_home)
assert _is_dangerous(prefix + "sed -i s/a/b/ " + path) is True
@pytest.mark.parametrize("command", [
r"sed -i s/a/b/ '/home/John\ Smith/hermes/config.yaml'",
r'sed -i s/a/b/ "/home/John\ Smith/hermes/config.yaml"',
r"mv '/home/John\ Smith/hermes' /tmp/x",
])
def test_a_quoted_backslash_is_a_literal_name_character(self, spaced_user_home, command):
assert _is_dangerous(command) is False
@pytest.mark.parametrize("command", [
r'bash -c "sed -i s/a/b/ /home/John\ Smith/hermes/config.yaml"',
r'echo "$(sed -i s/a/b/ /home/John\ Smith/hermes/config.yaml)"',
])
def test_an_escape_read_by_an_inner_shell_still_folds(self, spaced_user_home, command):
def test_an_escape_in_any_quote_context_gates(self, spaced_user_home, command):
assert _is_dangerous(command) is True
def test_deeply_nested_substitutions_fold_without_recursing(self, spaced_user_home):
path = r"/home/John\ Smith/hermes/config.yaml"
# Every level is a double-quoted `"$(`, a fresh quote context the shell reads the escape in.
command = "echo " + '"$(' * 3000 + "sed -i s/a/b/ " + path + ')"' * 3000
assert "~/.hermes/config.yaml" in approval_home_fold._rewrite_resolved_hermes_home(command)

View File

@@ -11,7 +11,6 @@ import os
import re
from hermes_platform.host import facts
from tools.approval_parser_budget import _scan_shell
# Shell metacharacters, quotes, and whitespace that terminate a path token.
@@ -29,39 +28,20 @@ def _spell_component(component: str) -> str:
return re.escape(component).replace(r"\ ", r"\\? ")
def _live_space_escapes(command: str, start: int = 0, end: int | None = None, found: set | None = None) -> set:
"""Indexes of each backslash in *command* the shell reads as escaping a space or tab: unquoted, or
unquoted inside a ``$(...)`` / backtick body (a fresh quote context). Inside single or double
quotes the backslash is a literal character."""
found = set() if found is None else found
for kind, i, j, quote in _scan_shell(command, start, end, subst="q"):
if kind == "subst":
_live_space_escapes(command, i + (2 if command.startswith("$(", i) else 1), j - 1, found)
elif kind == "esc" and quote is None and command[i + 1] in " \t":
found.add(i)
return found
def _fold_matches(pattern, command: str, replace) -> str:
"""``pattern.sub(replace, command)``, keeping a match as written when an escaped space in it is
not what the shell reads:
"""``pattern.sub(replace, command)``, except a match that ends on the backslash of a ``\\ ``:
unquoted it continues the last name (``hermes\\ data\\ backup`` is a sibling of the home
``hermes data``, ``config.yaml\\ `` is another file), quoted it is a literal name character.
Either way the command does not name what the fold would, so that rule needs no quote state.
- a quoted ``\\ `` is a literal backslash, so ``'/home/John\\ Smith'`` is another directory than
the ``John Smith`` the optional escape in :func:`_spell_component` stands for;
- an unquoted ``\\ `` right after the match continues the last name instead of separating a child:
``hermes\\ data\\ backup`` is a sibling of the home ``hermes data``, not inside it.
An escaped space INSIDE the home is always read as a space, quoted or not. Telling the two apart
takes a full shell parse (a quote in a comment, heredoc body or backtick flips every lexical quote
model for the rest of the command), so the fold fails closed: a quoted ``'/home/John\\ Smith/...'``
costs a prompt, a misread unquoted one would lose the gate on the approval policy file.
"""
live = None
def fold(match: re.Match) -> str:
nonlocal live
escapes = [i for i in range(match.start(), match.end()) if command.startswith(("\\ ", "\\\t"), i)]
if escapes:
live = _live_space_escapes(command) if live is None else live
for i in escapes:
# Inside the match the escape spells a component's space; at its end it follows the home.
if (i in live) != (i + 1 < match.end()):
return match.group(0)
if command.startswith(("\\ ", "\\\t"), match.end() - 1):
return match.group(0)
return replace(match)
return pattern.sub(fold, command)