fix(hooks): skip project hints for external searches
Only omit hints when recognized literal targets all resolve outside the project. Preserve advisory hints for mixed paths and uncertain shell syntax.
Fixes #4961
Co-Authored-By: OpenAI Codex <noreply@openai.com>
(cherry picked from commit 2ef48b214f)
This commit is contained in:
1 parent
7433c0a805
commit
227028de75
3 files changed
+187
-2
No files matched your search
@@ -130,6 +130,14 @@ retires Go entries created before these receiver-binding rules.
|
||||
4. Add the tree-sitter package to `pyproject.toml` dependencies.
|
||||
5. Add a fixture file to `tests/fixtures/` and tests to `tests/test_languages.py`.
|
||||
|
||||
## Search hook scope
|
||||
|
||||
The search hook omits project hints when a structured Grep path or every literal
|
||||
target of a simple grep/rg command resolves outside the project. Mixed targets,
|
||||
implicit paths, shell composition/expansion, wrappers, unknown options and
|
||||
unmapped Windows shell drive paths retain the advisory hint. It does not execute
|
||||
shell input or change search permissions.
|
||||
|
||||
## Security
|
||||
|
||||
All external input passes through `graphify/security.py` before use:
|
||||
|
||||
+68
-2
@@ -1178,6 +1178,71 @@ def _bash_invokes_search(cmd_str: str) -> bool:
|
||||
return False
|
||||
|
||||
|
||||
def _search_is_outside_project(tool_input: dict) -> bool:
|
||||
"""Skip only searches whose literal targets are all outside the project.
|
||||
|
||||
Structured Grep paths and simple grep/rg commands are supported. Shell
|
||||
composition, expansion, wrappers and unknown options remain advisory as
|
||||
before; this is deliberately not a shell interpreter or an access gate.
|
||||
"""
|
||||
command = str(tool_input.get("command") or "")
|
||||
if command:
|
||||
import shlex
|
||||
if any(c in command for c in "$`;&|<>\n\\"):
|
||||
return False
|
||||
try:
|
||||
tokens = shlex.split(command)
|
||||
except ValueError:
|
||||
return False
|
||||
if not tokens or tokens[0].rsplit("/", 1)[-1] not in {
|
||||
"grep", "egrep", "fgrep", "zgrep", "rg", "ripgrep",
|
||||
}:
|
||||
return False
|
||||
positional = []
|
||||
explicit_pattern = False
|
||||
options = True
|
||||
args = iter(tokens[1:])
|
||||
for arg in args:
|
||||
if options and arg == "--":
|
||||
options = False
|
||||
elif options and arg in ("-e", "--regexp", "-f", "--file"):
|
||||
if next(args, None) is None:
|
||||
return False
|
||||
explicit_pattern = True
|
||||
elif options and arg.startswith(("--regexp=", "--file=")):
|
||||
explicit_pattern = True
|
||||
elif options and arg in _HINT_VALUE_FLAGS:
|
||||
if next(args, None) is None:
|
||||
return False
|
||||
elif options and arg.startswith("--"):
|
||||
if arg.split("=", 1)[0] in _HINT_VALUE_FLAGS and "=" in arg:
|
||||
continue
|
||||
if arg not in {"--ignore-case", "--line-number", "--recursive",
|
||||
"--fixed-strings", "--word-regexp", "--invert-match"}:
|
||||
return False
|
||||
elif options and arg.startswith("-"):
|
||||
if not re.fullmatch(r"-[nriIvVwxlLchHqsoEFGPRUa]+", arg):
|
||||
return False
|
||||
else:
|
||||
positional.append(arg)
|
||||
paths = positional if explicit_pattern else positional[1:]
|
||||
else:
|
||||
paths = [str(tool_input.get("path") or "")]
|
||||
if not paths or any(not p or p == "-" or re.search(r"[$`*?\[\]{}~]", p) for p in paths):
|
||||
return False
|
||||
# Bash on Windows may use /c/... or /mnt/c/... paths that pathlib does
|
||||
# not map to the shell's drive. Keep the hint when that mapping is unknown.
|
||||
if command and os.name == "nt" and any(p.startswith("/") for p in paths):
|
||||
return False
|
||||
try:
|
||||
root = Path(os.environ.get("CLAUDE_PROJECT_DIR") or os.getcwd()).resolve()
|
||||
# Relative search targets resolve against the tool's working directory,
|
||||
# which can be below CLAUDE_PROJECT_DIR. Resolve symlinks and '..' too.
|
||||
return all(not Path(p).resolve().is_relative_to(root) for p in paths)
|
||||
except (ValueError, OSError, RuntimeError):
|
||||
return False
|
||||
|
||||
|
||||
def _run_hook_guard(kind: str, strict: bool = False) -> None:
|
||||
"""Shell-agnostic PreToolUse guard (#522).
|
||||
|
||||
@@ -1225,7 +1290,8 @@ def _run_hook_guard(kind: str, strict: bool = False) -> None:
|
||||
# Grep tool carries `pattern` (plus optional path/glob) and no
|
||||
# command. Grep is scoped below to the project's source targets.
|
||||
# Bash searches remain advisory: compound shell commands have no
|
||||
# single reliable target.
|
||||
# single reliable target, but a search whose every literal target is
|
||||
# outside the project emits no project hint (#4961).
|
||||
pattern = t.get("pattern")
|
||||
is_grep_tool = not cmd_str and isinstance(pattern, str) and bool(pattern) \
|
||||
and d.get("tool_name") in (None, "Grep")
|
||||
@@ -1256,7 +1322,7 @@ def _run_hook_guard(kind: str, strict: bool = False) -> None:
|
||||
and _mark_session_denied(str(d.get("session_id") or "")):
|
||||
sys.stdout.write(_with_hint(_SEARCH_DENY, terms=_search_hint_terms(t)))
|
||||
return
|
||||
if _nudge_allowed(d):
|
||||
if not _search_is_outside_project(t) and _nudge_allowed(d):
|
||||
sys.stdout.write(_with_hint(_nudge_for_out(_SEARCH_NUDGE), terms=_search_hint_terms(t)))
|
||||
elif kind == "read":
|
||||
vals = [str(t.get("file_path") or ""), str(t.get("pattern") or ""), str(t.get("path") or "")]
|
||||
|
||||
@@ -0,0 +1,111 @@
|
||||
"""Only searches known to target files outside the graph should lose the hint."""
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
|
||||
import pytest
|
||||
|
||||
from graphify.cli import _run_hook_guard, _search_is_outside_project
|
||||
|
||||
|
||||
def _invoke(monkeypatch, project, tool_input):
|
||||
monkeypatch.chdir(project)
|
||||
monkeypatch.setenv("CLAUDE_PROJECT_DIR", str(project))
|
||||
monkeypatch.delenv("GRAPHIFY_OUT", raising=False)
|
||||
monkeypatch.setattr(sys, "stdin", io.TextIOWrapper(io.BytesIO(json.dumps({
|
||||
"session_id": "scope-test", "tool_input": tool_input,
|
||||
}).encode())))
|
||||
output = io.StringIO()
|
||||
monkeypatch.setattr(sys, "stdout", output)
|
||||
_run_hook_guard("search")
|
||||
return output.getvalue()
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def project(tmp_path):
|
||||
root = tmp_path / "project"
|
||||
(root / "graphify-out").mkdir(parents=True)
|
||||
(root / "graphify-out" / "graph.json").write_text("{}", encoding="utf-8")
|
||||
return root
|
||||
|
||||
|
||||
@pytest.mark.parametrize("command", [
|
||||
"grep -rn Findings '{outside}'",
|
||||
"rg Findings '{outside}'",
|
||||
"grep -n -e Findings '{outside}'",
|
||||
"rg --glob '*.txt' -e Findings '{outside}'",
|
||||
"grep -A 2 Findings '{outside}'",
|
||||
"grep -f patterns.txt '{outside}'",
|
||||
"rg --regexp=Findings '{outside}'",
|
||||
"rg --glob=*.txt Findings '{outside}'",
|
||||
"grep -- Findings '{outside}'",
|
||||
"grep Findings ../external.txt",
|
||||
])
|
||||
def test_shell_external_search_is_silent(monkeypatch, project, command):
|
||||
outside = (project.parent / "external log.txt").as_posix()
|
||||
assert not _invoke(monkeypatch, project, {"command": command.format(outside=outside)})
|
||||
assert not (project / "graphify-out/cache/hook_sessions/scope-test.nudges").exists()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("relative", [False, True])
|
||||
def test_grep_tool_external_search_is_silent(monkeypatch, project, relative):
|
||||
outside = "../external.txt" if relative else str(project.parent / "external.txt")
|
||||
assert not _invoke(monkeypatch, project, {"pattern": "Findings", "path": outside})
|
||||
|
||||
|
||||
@pytest.mark.parametrize("tool_input", [
|
||||
{"pattern": "Findings"},
|
||||
{"pattern": "Findings", "path": "."},
|
||||
{"pattern": "Findings", "path": "src"},
|
||||
{"command": "grep Findings src.txt ../external.txt"},
|
||||
{"command": "rg Findings"},
|
||||
{"command": "grep Findings ../external.txt && rg Findings ."},
|
||||
{"command": "grep Findings $TARGET"},
|
||||
{"command": "grep Findings ../*.txt"},
|
||||
{"command": "grep --unknown-option ../external.txt"},
|
||||
{"command": "grep -e Findings"},
|
||||
{"command": "grep -A"},
|
||||
{"command": "grep -e"},
|
||||
{"command": "grep Findings 'unterminated"},
|
||||
{"command": "sudo grep Findings ../external.txt"},
|
||||
{"command": "find ../external -name '*.txt'"},
|
||||
{"command": "rg Findings -"},
|
||||
])
|
||||
def test_project_or_uncertain_search_keeps_nudge(monkeypatch, project, tool_input):
|
||||
assert "graphify query" in _invoke(monkeypatch, project, tool_input)
|
||||
|
||||
|
||||
def test_project_absolute_path_keeps_nudge(monkeypatch, project):
|
||||
assert "graphify query" in _invoke(monkeypatch, project, {
|
||||
"pattern": "Findings", "path": str(project / "source.txt"),
|
||||
})
|
||||
|
||||
|
||||
def test_sibling_with_project_prefix_is_external(monkeypatch, project):
|
||||
assert not _invoke(monkeypatch, project, {
|
||||
"pattern": "Findings", "path": str(project.parent / "project-other"),
|
||||
})
|
||||
|
||||
|
||||
def test_relative_path_is_resolved_from_working_directory(monkeypatch, project):
|
||||
nested = project / "nested"
|
||||
nested.mkdir()
|
||||
monkeypatch.chdir(nested)
|
||||
monkeypatch.setenv("CLAUDE_PROJECT_DIR", str(project))
|
||||
assert not _search_is_outside_project({"command": "rg Findings ../src"})
|
||||
assert _search_is_outside_project({"command": "rg Findings ../../external"})
|
||||
|
||||
|
||||
@pytest.mark.skipif(os.name != "nt", reason="Windows shell drive mappings")
|
||||
@pytest.mark.parametrize("path", ["/c/project", "/mnt/c/project"])
|
||||
def test_unmapped_shell_drive_path_keeps_nudge(monkeypatch, project, path):
|
||||
assert "graphify query" in _invoke(monkeypatch, project, {"command": f"rg Findings {path}"})
|
||||
|
||||
|
||||
def test_in_project_symlink_to_external_is_silent(monkeypatch, project, requires_symlinks):
|
||||
target = project.parent / "external"
|
||||
target.mkdir()
|
||||
link = project / "linked"
|
||||
link.symlink_to(target, target_is_directory=True)
|
||||
assert not _invoke(monkeypatch, project, {"pattern": "Findings", "path": str(link)})
|
||||
Reference in new issue
Block a user