summaryrefslogtreecommitdiff
path: root/plugins
diff options
context:
space:
mode:
authorMohamed Hegazy <mhegazy@anthropic.com>2026-10-20 23:24:19 +0000
committerClaude <noreply@anthropic.com>2026-10-20 23:24:19 +0000
commit218862e1b0814b66361e9d215c409a10df2304ae (patch)
treea47f13ba4e36c3e22dc89f61ac122dda3a11a22e /plugins
parent8d582c39ac3868b5d85cd5a06497b3a02e11c5dd (diff)
security-guidance: find the earlier version of a file reached through a symlinked foldermhegazy/sg-baseline-subdir
When the tool's path and the session directory name the same repo through different symlinks (/tmp and /var on macOS), the relative path between the two spellings left the repo and the lookup found nothing, so a rewrite re-reported code that was already in the file. The lookup now tries again with both paths resolved. The first attempt is unchanged.
Diffstat (limited to 'plugins')
-rw-r--r--plugins/security-guidance/hooks/diffstate.py40
-rw-r--r--plugins/security-guidance/tests/test_baseline_lookup.py48
2 files changed, 73 insertions, 15 deletions
diff --git a/plugins/security-guidance/hooks/diffstate.py b/plugins/security-guidance/hooks/diffstate.py
index 5844f763..9ebb2b1b 100644
--- a/plugins/security-guidance/hooks/diffstate.py
+++ b/plugins/security-guidance/hooks/diffstate.py
@@ -286,21 +286,31 @@ def get_baseline_file_content(session_id, file_path, cwd):
try:
abs_path = os.path.abspath(file_path)
cwd_abs = os.path.abspath(cwd) if cwd else os.getcwd()
- try:
- rel_path = os.path.relpath(abs_path, cwd_abs)
- except ValueError:
- return None
- # `<rev>:<path>` is read from the repo root unless the path starts
- # with `./`, and takes forward slashes only. Without both, the lookup
- # fails for a session started below the repo root, and on Windows for
- # any file that is not directly in the session directory.
- rel_path = rel_path.replace(os.sep, "/")
- result = subprocess.run(
- [*GIT_CMD, "show", f"{baseline_sha}:./{rel_path}"],
- cwd=cwd, capture_output=True, timeout=5
- )
- if result.returncode == 0:
- return (result.stdout or b"").decode("utf-8", errors="replace")
+ attempts = [(abs_path, cwd_abs, cwd)]
+ # The tool's path and the session directory can name the same place
+ # through different symlinks (/tmp and /var on macOS). The relative
+ # path between the two spellings then leaves the repo and git finds
+ # nothing, so the lookup is tried again with both resolved.
+ real_path, real_cwd = os.path.realpath(abs_path), os.path.realpath(cwd_abs)
+ if (real_path, real_cwd) != (abs_path, cwd_abs):
+ attempts.append((real_path, real_cwd, real_cwd))
+ for path, start, git_cwd in attempts:
+ try:
+ rel_path = os.path.relpath(path, start)
+ except ValueError:
+ continue
+ # `<rev>:<path>` is read from the repo root unless the path starts
+ # with `./`, and takes forward slashes only. Without both, the
+ # lookup fails for a session started below the repo root, and on
+ # Windows for any file that is not directly in the session
+ # directory.
+ rel_path = rel_path.replace(os.sep, "/")
+ result = subprocess.run(
+ [*GIT_CMD, "show", f"{baseline_sha}:./{rel_path}"],
+ cwd=git_cwd, capture_output=True, timeout=5
+ )
+ if result.returncode == 0:
+ return (result.stdout or b"").decode("utf-8", errors="replace")
return None
except (subprocess.TimeoutExpired, FileNotFoundError, OSError, ValueError):
return None
diff --git a/plugins/security-guidance/tests/test_baseline_lookup.py b/plugins/security-guidance/tests/test_baseline_lookup.py
index ef8ab360..d6d2e34d 100644
--- a/plugins/security-guidance/tests/test_baseline_lookup.py
+++ b/plugins/security-guidance/tests/test_baseline_lookup.py
@@ -1,3 +1,5 @@
+import os
+
import pytest
from conftest import git, make_repo, run_hook, ups_payload
@@ -32,6 +34,22 @@ def repo(tmp_path):
return repo
+def _symlink(link, target):
+ try:
+ link.symlink_to(target, target_is_directory=target.is_dir())
+ except (OSError, NotImplementedError):
+ if os.name != "nt":
+ raise
+ pytest.skip("this Windows account cannot create symlinks")
+
+
+@pytest.fixture
+def linked(repo, tmp_path):
+ """The same repo, reached through a symlinked parent directory."""
+ _symlink(tmp_path / "alias", tmp_path / "ws")
+ return tmp_path / "alias" / "mono"
+
+
@pytest.fixture
def baseline(repo, monkeypatch):
sha = git(repo, "rev-parse", "HEAD").strip()
@@ -74,6 +92,20 @@ class TestBaselineFileContent:
for cwd in (repo, repo / "packages" / "app"):
assert diffstate.get_baseline_file_content("s1", str(twin), str(cwd)) is None
+ @pytest.mark.parametrize("session_dir", ["", "packages/app"])
+ def test_found_through_a_symlinked_directory(self, repo, baseline, linked, session_dir):
+ """macOS reaches /tmp and /var through symlinks, so the tool's path and
+ the session directory can spell the same repo differently."""
+ real, alias = repo / session_dir, linked / session_dir
+ for cwd, path in ((real, linked / FILE), (alias, repo / FILE), (alias, linked / FILE)):
+ assert diffstate.get_baseline_file_content("s1", str(path), str(cwd)) == OLD
+
+ def test_session_directory_is_a_symlink_into_the_repo(self, repo, baseline, tmp_path):
+ _symlink(tmp_path / "app", repo / "packages" / "app")
+ for path in (tmp_path / "app" / "main.py", repo / FILE):
+ assert diffstate.get_baseline_file_content(
+ "s1", str(path), str(tmp_path / "app")) == OLD
+
def test_committed_content_not_the_working_copy(self, repo, baseline):
(repo / FILE).write_text("print('rewritten')\n")
assert diffstate.get_baseline_file_content(
@@ -81,6 +113,22 @@ class TestBaselineFileContent:
@pytest.mark.parametrize("session_dir", ["", "packages/app"])
+def test_rewrite_through_a_symlinked_path_does_not_re_flag(repo, linked, hook_env, session_dir):
+ """The session runs in the real directory and the tool names the file
+ through the symlink, as under /tmp on macOS."""
+ cwd = repo / session_dir
+ env = {**hook_env, "CLAUDE_PROJECT_DIR": str(cwd)}
+ run_hook(ups_payload(cwd), env)
+
+ _rc, stdout, _err = run_hook(write_payload(cwd, linked / FILE, OLD + "print('x')\n"), env)
+ assert "additionalContext" not in stdout
+
+ _rc, stdout, _err = run_hook(
+ write_payload(cwd, linked / FILE, OLD + "import pickle\npickle.loads(data)\n"), env)
+ assert "pickle" in stdout and "os.system" not in stdout
+
+
+@pytest.mark.parametrize("session_dir", ["", "packages/app"])
def test_rewrite_does_not_re_flag_code_that_was_already_there(repo, hook_env, session_dir):
"""A full-file Write that keeps a pre-existing risky call is not a new
finding, whether the session runs at the repo root or below it."""