Split the 1341-line __init__.py into 5 focused modules: _state.py - home root helpers, mutable poll state _parser.py - shell tokenizer (independent) _predicates.py - terminal predicates + bounded output _guards.py - all 9 guard implementations + AST helpers __init__.py - thin entry point + dispatcher + re-exports Split the 2226-line test_guard.py into 14 dedicated files: 13 test_*.py files + tests/_support.py (shared helpers) Key changes: - Package-relative imports throughout (Hermes loader compatible) - No top-level module pollution (hermes_plugins.kuri_tool_guard.* only) - Typechecked via ty with symlink alias for hyphenated dir name - All 10 guard policies, messages, and block/allow behaviour preserved - 338 tests (336 original + 2 new: isolation + loader contract) - ty, ruff, bandit, vulture all pass in just verify
307 lines
10 KiB
Python
307 lines
10 KiB
Python
"""kuri-tool-guard — terminal predicate functions for shell command policy."""
|
||
|
||
from __future__ import annotations
|
||
|
||
import os
|
||
import re
|
||
import shlex
|
||
from typing import Any
|
||
|
||
from . import _parser
|
||
|
||
# ── Terminal message constants ──────────────────────────────────
|
||
|
||
|
||
_CAT_TERMINAL_MSG = (
|
||
"不允許用 cat 將完整檔案內容直接輸出到終端。"
|
||
"完整閱讀請用 read_file,搜尋內容請用 search_files。" # noqa: RUF001
|
||
"不要改用其他 shell 指令繞過這個限制。"
|
||
)
|
||
|
||
_SHELL_WRITE_MSG = (
|
||
"不允許透過 shell 建立或修改檔案;" # noqa: RUF001
|
||
"這些方式會跳過語法檢查、hook 注入與檔案權限驗證。"
|
||
"建立新檔請用 write_file,修改既有檔請用 patch。" # noqa: RUF001
|
||
"不要改用其他 shell 語法或 wrapper 繞過這個限制。"
|
||
)
|
||
|
||
|
||
# ── Cat direct-read check ────────────────────────────────────────
|
||
|
||
|
||
def _cat_direct_read(command: str) -> str | None:
|
||
"""Check cat usage policy.
|
||
|
||
Returns 'cat_terminal' if cat outputs to terminal (stdout or via >&2).
|
||
Returns 'cat_file_write' if cat's pipeline writes to a file.
|
||
Returns None if cat is used in a legitimate pipeline or not a real cat command.
|
||
"""
|
||
for seg in _parser._split_chain_segments(command):
|
||
pipe_cmds = _parser._split_pipe_commands(seg)
|
||
for cmd_idx, scmd_text in enumerate(pipe_cmds):
|
||
try:
|
||
tokens = shlex.split(scmd_text)
|
||
except ValueError:
|
||
continue
|
||
|
||
if not _parser._is_cat_command(tokens):
|
||
continue
|
||
|
||
if (
|
||
_parser._has_file_write(scmd_text)
|
||
or _parser._stdout_destination(scmd_text) == "file"
|
||
):
|
||
return "cat_file_write"
|
||
|
||
dest = _parser._stdout_destination(scmd_text)
|
||
|
||
if dest == "fd":
|
||
return "cat_terminal"
|
||
|
||
if dest in ("devnull", "subst"):
|
||
rest = " ".join(pipe_cmds[cmd_idx + 1 :]) if cmd_idx < len(pipe_cmds) - 1 else ""
|
||
if rest and _parser._has_file_write(rest):
|
||
return "cat_file_write"
|
||
continue
|
||
|
||
# dest == "terminal"
|
||
if cmd_idx < len(pipe_cmds) - 1:
|
||
rest = " ".join(pipe_cmds[cmd_idx + 1 :])
|
||
if _parser._has_file_write(rest):
|
||
return "cat_file_write"
|
||
continue
|
||
|
||
return "cat_terminal"
|
||
|
||
return None
|
||
|
||
|
||
# ── Remaining predicates ─────────────────────────────────────────
|
||
|
||
|
||
def _heredoc_direct(cmd: str) -> bool:
|
||
return bool(
|
||
re.search(
|
||
r"<<[-']?[\'\"\"]?\w+[\'\"\"]?(?:\s+[>]{1,2})?\s*\S",
|
||
cmd,
|
||
re.IGNORECASE,
|
||
)
|
||
)
|
||
|
||
|
||
def _echo_redirect(cmd: str) -> bool:
|
||
stripped = _parser._STRIP_QUOTES.sub("", cmd)
|
||
for m in re.finditer(r"\becho\b", stripped, re.IGNORECASE):
|
||
rest = stripped[m.end() :]
|
||
rest = re.split(r"[;|]", rest)[0]
|
||
if any(
|
||
not _parser._DEVNULL.match(t.group(1))
|
||
for t in re.finditer(r"[>]{1,2}\s*(?!&)(\S+)", rest)
|
||
):
|
||
return True
|
||
return False
|
||
|
||
|
||
def _printf_redirect(cmd: str) -> bool:
|
||
stripped = _parser._STRIP_QUOTES.sub("", cmd)
|
||
for m in re.finditer(r"\bprintf\b", stripped, re.IGNORECASE):
|
||
rest = stripped[m.end() :]
|
||
rest = re.split(r"[;|]", rest)[0]
|
||
if any(
|
||
not _parser._DEVNULL.match(t.group(1))
|
||
for t in re.finditer(r"[>]{1,2}\s*(?!&)(\S+)", rest)
|
||
):
|
||
return True
|
||
return False
|
||
|
||
|
||
def _bare_redirect(cmd: str) -> bool:
|
||
return any(
|
||
not _parser._DEVNULL.match(t.group(1))
|
||
for t in re.finditer(r"(?:^|[:;]\s*)[>]{1,2}\s*(?!&)(\S+)", cmd)
|
||
)
|
||
|
||
|
||
def _tee_write(cmd: str) -> bool:
|
||
stripped = _parser._STRIP_QUOTES.sub("", cmd)
|
||
return bool(
|
||
re.search(
|
||
r"(?:^|[(|;&])\s*(?:(?:command|env|time|nice|nohup)\s+)?tee\b",
|
||
stripped,
|
||
re.IGNORECASE,
|
||
)
|
||
)
|
||
|
||
|
||
def _sed_inplace(cmd: str) -> bool:
|
||
"""True if cmd runs sed with -i or --in-place for in-place editing.
|
||
|
||
Uses token-based parsing (via shlex) to correctly handle:
|
||
- Env assignments (``FOO=1 sed -i``)
|
||
- Combined short options (``sed -ni``)
|
||
- Separated flags (``sed -n -i``, ``sed -n --in-place``)
|
||
- Wrapper commands (``time sed -i``, ``env -i sed -i``, ``nice -n 10 sed -i``)
|
||
- Subshell wrappers (``(sed -i ...)``)
|
||
"""
|
||
try:
|
||
tokens = shlex.split(cmd)
|
||
except ValueError:
|
||
return False
|
||
idx = _parser._first_command_token_index(tokens)
|
||
if idx >= len(tokens):
|
||
return False
|
||
# Strip leading subshell parens from the command token
|
||
cmd_name = tokens[idx].lstrip("(")
|
||
if os.path.basename(cmd_name) != "sed":
|
||
return False
|
||
for token in tokens[idx + 1 :]:
|
||
if token == "--in-place": # nosec B105
|
||
return True
|
||
return any(token.startswith("-") and "i" in token.lstrip("-") for token in tokens[idx + 1 :])
|
||
|
||
|
||
def _perl_inplace(cmd: str) -> bool:
|
||
"""True if cmd runs perl with -i for in-place editing.
|
||
|
||
Uses token-based parsing (via shlex) to correctly handle:
|
||
- Env assignments (``LC_ALL=C perl -pi``)
|
||
- Separated flags (``perl -i -pe``)
|
||
- Combined flags (``perl -pi``)
|
||
- Wrapper commands (``time perl -pi``, ``env perl -pi``)
|
||
- Subshell wrappers (``(perl -pi ...)``)
|
||
"""
|
||
try:
|
||
tokens = shlex.split(cmd)
|
||
except ValueError:
|
||
return False
|
||
idx = _parser._first_command_token_index(tokens)
|
||
if idx >= len(tokens):
|
||
return False
|
||
# Strip leading subshell parens from the command token
|
||
cmd_name = tokens[idx].lstrip("(")
|
||
if os.path.basename(cmd_name) != "perl":
|
||
return False
|
||
return any(token.startswith("-") and "i" in token.lstrip("-") for token in tokens[idx + 1 :])
|
||
|
||
|
||
# ── Bounded-output predicates ────────────────────────────────────
|
||
|
||
|
||
_BOUNDED_OUTPUT_MSG = (
|
||
"指令可能產出大量輸出。因未設定量或上限。"
|
||
"請考慮使用 -maxdepth、-print -quit、git ls-files 或 pipe to head 限制。"
|
||
)
|
||
|
||
|
||
def _effective_commands(all_segments: list[list[str]]) -> list[str]:
|
||
"""Return the effective (wrapper-skipped) command name per pipe segment."""
|
||
result: list[str] = []
|
||
for segment in all_segments:
|
||
if not segment:
|
||
result.append("")
|
||
continue
|
||
idx = _parser._first_command_token_index(segment)
|
||
result.append(segment[idx] if idx < len(segment) else "")
|
||
return result
|
||
|
||
|
||
def _has_find_type_f(segment: list[str]) -> bool:
|
||
"""True if *segment* contains ``-type f`` (flag and value correctly paired)."""
|
||
for j, t in enumerate(segment):
|
||
if t == "-type" and j + 1 < len(segment) and segment[j + 1] == "f":
|
||
return True
|
||
return False
|
||
|
||
|
||
def _check_find_bounded_output(
|
||
find_idx: int, all_segments: list[list[str]], effective_cmds: list[str]
|
||
) -> str | None:
|
||
"""Check if a ``find`` pipeline produces bounded output."""
|
||
segment = all_segments[find_idx]
|
||
if not _has_find_type_f(segment):
|
||
return None
|
||
if "-maxdepth" in segment:
|
||
return None
|
||
if "-print" in segment and "-quit" in segment:
|
||
return None
|
||
# Pipeline analysis: the first command after find determines boundedness
|
||
if find_idx + 1 < len(effective_cmds):
|
||
nxt = effective_cmds[find_idx + 1]
|
||
if nxt == "head":
|
||
return None # find | head → bounded
|
||
if nxt == "sort":
|
||
return _BOUNDED_OUTPUT_MSG # sort consumes full output regardless of what follows
|
||
return _BOUNDED_OUTPUT_MSG # unbounded find -type f
|
||
|
||
|
||
def _check_rg_bounded_output(segment: list[str], effective_cmd: str) -> bool:
|
||
"""True if *segment* is an unbounded ``rg`` invocation."""
|
||
return (
|
||
effective_cmd == "rg"
|
||
and "--files" in segment
|
||
and "--hidden" in segment
|
||
and "--no-ignore" in segment
|
||
)
|
||
|
||
|
||
def _bounded_output(command: str) -> str | None:
|
||
"""Block commands likely to produce unbounded output.
|
||
|
||
Pipeline-aware: ``find | head`` is ALLOWED (head limits output),
|
||
but ``find | sort | head`` is BLOCKED (sort consumes full output first).
|
||
|
||
Uses ``_first_command_token_index`` to skip ``command``, ``env``,
|
||
``nice``, ``time`` wrappers correctly.
|
||
"""
|
||
all_segments = _parser._get_command_tokens(command)
|
||
if not all_segments:
|
||
return None
|
||
|
||
effective_cmds = _effective_commands(all_segments)
|
||
|
||
# find — pipeline-aware boundedness check
|
||
for i, cmd in enumerate(effective_cmds):
|
||
if cmd == "find":
|
||
result = _check_find_bounded_output(i, all_segments, effective_cmds)
|
||
if result is not None:
|
||
return result
|
||
break # only the first find matters
|
||
|
||
# rg --files --hidden --no-ignore
|
||
for segment, cmd in zip(all_segments, effective_cmds, strict=False):
|
||
if segment and _check_rg_bounded_output(segment, cmd):
|
||
return _BOUNDED_OUTPUT_MSG
|
||
|
||
# fd --hidden --no-ignore
|
||
for segment, cmd in zip(all_segments, effective_cmds, strict=False):
|
||
if segment and cmd == "fd" and "--hidden" in segment and "--no-ignore" in segment:
|
||
return _BOUNDED_OUTPUT_MSG
|
||
|
||
return None
|
||
|
||
|
||
# ── Predicate registry and dispatcher ────────────────────────────
|
||
|
||
|
||
_TERMINAL_PREDICATES: list[tuple[str, Any]] = [
|
||
("bounded_output", _bounded_output),
|
||
("cat_direct_read", _cat_direct_read),
|
||
("heredoc_direct", _heredoc_direct),
|
||
("echo_redirect", _echo_redirect),
|
||
("printf_redirect", _printf_redirect),
|
||
("bare_redirect", _bare_redirect),
|
||
("tee_write", _tee_write),
|
||
("sed_inplace", _sed_inplace),
|
||
("perl_inplace", _perl_inplace),
|
||
]
|
||
|
||
|
||
def _match_terminal_predicate(command: str) -> str | None:
|
||
"""Return the matching predicate's reason name, or None."""
|
||
for name, pred in _TERMINAL_PREDICATES:
|
||
result = pred(command)
|
||
if result:
|
||
if isinstance(result, str):
|
||
return result
|
||
return name
|
||
return None
|