mirror of
https://github.com/headroomlabs-ai/headroom.git
synced 2026-11-24 19:52:53 +08:00
fix(binaries): ignore tool binaries found via the current directory (#4838)
## Description
`headroom.binaries._path_lookup()` (used by `which()`, `resolve()` and
`ensure_tools()`) and `status()` returned `shutil.which(name)` before
looking at the SHA-256-pinned cache. On Windows `shutil.which` searches
the current directory before PATH (unless
`NoDefaultCurrentDirectoryInExePath` is set), and on any OS a relative
PATH entry (`.`, an empty entry, `bin`) resolves against the cwd. The
cwd is usually the project being worked on, so a file there named
`ast-grep`, `difft`, `scc`, ... was run in place of the real tool, and
the cache's pin never applied to it.
A PATH hit is now ignored when it comes from a relative PATH entry or
lives in the current directory; lookup then falls back to the
interpreter's Scripts/bin dir and the verified cache (or a pinned fetch
in `resolve()`). `status()` (`headroom tools doctor`) uses the same rule
so it no longer reports such a file as `on-path`.
## Type of Change
- [x] Bug fix (non-breaking change that fixes an issue)
## Changes Made
- `headroom/binaries.py`: new `_which_outside_cwd()`; `_path_lookup()`
and `status()` use it. A warning names the ignored file.
- `tests/test_binaries.py`: real `shutil.which` with `PATH=.` and a tool
in the cwd for `which()`, `resolve()` and `status()`, plus a test that a
normal PATH hit outside the cwd is still used.
## Testing
- [x] Unit tests pass (`pytest`)
- [x] Linting passes (`ruff check .`)
- [x] Type checking passes (`mypy headroom`)
- [x] New tests added for new functionality
- [x] Manual testing performed
### Test Output
```text
# new tests on origin/main (fix stashed)
$ pytest -q tests/test_binaries.py
FAILED tests/test_binaries.py::test_which_ignores_a_tool_in_the_current_directory
FAILED tests/test_binaries.py::test_resolve_ignores_a_tool_in_the_current_directory
FAILED tests/test_binaries.py::test_status_does_not_report_a_cwd_tool_as_on_path
========================= 3 failed, 45 passed in 3.19s =========================
# with the fix
$ pytest -q tests/test_binaries.py tests/test_binaries_refusal_reaches_callers.py tests/test_bundled_tools_savings.py tests/test_cli_tools.py tests/test_offline_egress_chokepoint.py tests/test_ssl_context.py
================== 286 passed, 4 skipped in 156.19s (0:02:36) ==================
$ ruff check / ruff format --check (0.17.3) on changed files
All checks passed!
2 files already formatted
$ mypy headroom/binaries.py --ignore-missing-imports
Success: no issues found in 1 source file
```
## Real Behavior Proof
- Environment: macOS, Python 3.12 venv; empty `HEADROOM_BINARIES_CACHE`,
`HEADROOM_BINARIES_OFFLINE=1`.
- Exact command / steps: in a directory containing an executable
`difft`, run with `PATH=.`: `python -c 'from headroom import binaries as
b; print(b.which("difft")); print([(r["state"], r["path"]) for r in
b.status() if r["tool"]=="difft"])'`.
- Observed result:
- main: `which: difft`, `status: [('on-path', './difft')]`
- this branch: `Ignoring difft found via the current directory
(.../proj/difft); using the interpreter's Scripts dir or the Headroom
cache instead`, `which: None`, `status: [('missing', None)]`
- Not tested: on a Windows host (the Windows case is the same code path:
`shutil.which` returns a relative `.\name` hit there).
## Runtime Rollout Safety
- Rollout-managed feature(s): none
- Minimum rollout channel: n/a
- Stable/default behavior changed: a tool binary that is only reachable
through the current directory or a relative PATH entry is no longer
used; Headroom uses its verified cached copy instead. Running Headroom
from inside a directory that is itself listed on PATH also falls back to
the cache for tools in that directory.
- Kill switch / disable path: put the tool in a directory listed on PATH
by absolute path.
- Unsafe override required: no
- Qualification impact: none
- Rollback path: revert this PR
## Review Readiness
- [x] I have performed a self-review
- [x] This PR is ready for human review
## Checklist
- [x] My code follows the project's style guidelines
- [x] I have performed a self-review of my code
- [x] I have commented my code, particularly in hard-to-understand areas
- [ ] I have made corresponding changes to the documentation
- [x] My changes generate no new warnings
- [x] I have added tests that prove my fix is effective or that my
feature works
- [x] New and existing unit tests pass locally with my changes
- [x] I did **not** edit `CHANGELOG.md`
## Additional Notes
No docs change needed. Fix adapted from a proposal by HetCreep (this
version also ignores hits from relative PATH entries other than `.`).
🤖 Generated with [Claude Code](https://claude.com/claude-code)
<!-- devin-review-badge-begin -->
---
<a href="https://app.devin.ai/review/headroomlabs-ai/headroom/pull/4838"
target="_blank"><picture><source media="(prefers-color-scheme: dark)"
srcset="https://static.devin.ai/assets/gh-devin-review-dark.svg?v=4"><img
src="https://static.devin.ai/assets/gh-devin-review-light.svg?v=4"
alt="Devin Review"></picture></a>
<!-- devin-review-badge-end -->
---------
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: JerrettDavis <mxjerrett@gmail.com>
This commit is contained in:
co-authored by
Claude Opus 5.5
JerrettDavis
parent
f2cdcedb08
commit
7a0f15f563
+71
-8
@@ -548,6 +548,69 @@ def _in_registry(tool: str) -> bool:
|
||||
return tool in _registry().get("tools", {})
|
||||
|
||||
|
||||
_WARNED_CWD_HITS: set[str] = set()
|
||||
|
||||
|
||||
def _in_cwd(found: str) -> bool:
|
||||
"""True if a ``shutil.which`` hit came from a relative PATH entry or the cwd."""
|
||||
if not os.path.isabs(found):
|
||||
return True
|
||||
try:
|
||||
return os.path.samefile(os.path.dirname(found), os.getcwd())
|
||||
except OSError:
|
||||
return False
|
||||
|
||||
|
||||
def _which_outside_cwd(name: str) -> Path | None:
|
||||
"""``shutil.which(name)``, skipping any hit in the current directory.
|
||||
|
||||
On Windows ``shutil.which`` looks in the current directory before PATH
|
||||
unless ``NoDefaultCurrentDirectoryInExePath`` is set, and on any OS a
|
||||
relative PATH entry (``.``, empty, ``bin``) resolves against the cwd. The
|
||||
cwd is usually the project being worked on, so a same-named file there
|
||||
would run instead of the real tool. Such a hit is skipped and the search
|
||||
continues through the absolute PATH entries; with no other hit the caller
|
||||
falls back to the interpreter's Scripts dir or the verified cache. This also
|
||||
applies when the cwd is itself an absolute PATH entry (e.g. ``~/.local/bin``).
|
||||
"""
|
||||
found = shutil.which(name)
|
||||
if not found:
|
||||
return None
|
||||
if not _in_cwd(found):
|
||||
return Path(found)
|
||||
ignored = os.path.abspath(found)
|
||||
# resolve() runs per tool result in the proxy; say it once per file.
|
||||
if ignored not in _WARNED_CWD_HITS:
|
||||
_WARNED_CWD_HITS.add(ignored)
|
||||
logger.warning("Ignoring %s in the current directory (%s)", name, ignored)
|
||||
for entry in os.environ.get("PATH", "").split(os.pathsep):
|
||||
if not entry or not os.path.isabs(entry):
|
||||
continue
|
||||
hit = _executable_in(entry, name)
|
||||
if hit and not _in_cwd(hit):
|
||||
return Path(hit)
|
||||
return None
|
||||
|
||||
|
||||
def _executable_in(directory: str, name: str) -> str | None:
|
||||
"""Look for `name` in one directory only, like ``shutil.which`` minus its cwd step.
|
||||
|
||||
``shutil.which(name, path=directory)`` still searches the current directory
|
||||
first on Windows, so it cannot be used to skip a hit there. PATHEXT is
|
||||
honoured the same way ``shutil.which`` does.
|
||||
"""
|
||||
names = [name]
|
||||
if sys.platform.startswith("win"):
|
||||
exts = [e for e in os.environ.get("PATHEXT", ".COM;.EXE;.BAT;.CMD").split(";") if e]
|
||||
if not any(name.lower().endswith(ext.lower()) for ext in exts):
|
||||
names = [name + ext for ext in exts]
|
||||
for candidate in names:
|
||||
path = os.path.join(directory, candidate)
|
||||
if os.path.isfile(path) and os.access(path, os.X_OK):
|
||||
return path
|
||||
return None
|
||||
|
||||
|
||||
def _path_lookup(tool: str) -> Path | None:
|
||||
"""Find `tool` on PATH or in this interpreter's Scripts/bin directory.
|
||||
|
||||
@@ -563,14 +626,15 @@ def _path_lookup(tool: str) -> Path | None:
|
||||
candidates.append(alias)
|
||||
|
||||
for name in candidates:
|
||||
found = shutil.which(name)
|
||||
found = _which_outside_cwd(name)
|
||||
if found:
|
||||
return Path(found)
|
||||
return found
|
||||
|
||||
scripts_dir = Path(sys.prefix) / ("Scripts" if sys.platform.startswith("win") else "bin")
|
||||
for name in candidates:
|
||||
exe = scripts_dir / (name + (".exe" if sys.platform.startswith("win") else ""))
|
||||
if exe.exists():
|
||||
# Same test shutil.which applies: a regular file we may execute.
|
||||
if exe.is_file() and os.access(exe, os.X_OK):
|
||||
return exe
|
||||
return None
|
||||
|
||||
@@ -703,12 +767,11 @@ def status() -> list[dict[str, Any]]:
|
||||
"path": None,
|
||||
"state": "missing",
|
||||
}
|
||||
# Honor PATH.
|
||||
on_path = shutil.which(name) or (
|
||||
shutil.which(entry["binary"]) if entry.get("binary") else None
|
||||
)
|
||||
# Same lookup as which()/resolve(): PATH outside the cwd, then the
|
||||
# interpreter's Scripts dir.
|
||||
on_path = _path_lookup(name)
|
||||
if on_path:
|
||||
row["path"] = on_path
|
||||
row["path"] = str(on_path)
|
||||
row["state"] = "on-path"
|
||||
out.append(row)
|
||||
continue
|
||||
|
||||
@@ -7,6 +7,7 @@ from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import io
|
||||
import os
|
||||
import ssl
|
||||
import sys
|
||||
import tarfile
|
||||
@@ -196,6 +197,110 @@ def test_resolve_honors_path(monkeypatch, tmp_path):
|
||||
assert binaries.resolve("scc") == fake_bin
|
||||
|
||||
|
||||
def _plant_in_cwd(monkeypatch, tmp_path, name: str) -> None:
|
||||
"""Put an executable `name` in a fresh cwd and make PATH resolve it there."""
|
||||
project = tmp_path / "project"
|
||||
project.mkdir()
|
||||
planted = project / name
|
||||
planted.write_text("#!/bin/sh\n")
|
||||
planted.chmod(0o755)
|
||||
monkeypatch.chdir(project)
|
||||
monkeypatch.setenv("PATH", ".")
|
||||
monkeypatch.setattr(binaries.sys, "prefix", str(tmp_path / "venv"))
|
||||
|
||||
|
||||
def test_which_ignores_a_tool_in_the_current_directory(monkeypatch, tmp_path):
|
||||
_plant_in_cwd(monkeypatch, tmp_path, "difft")
|
||||
assert binaries.which("difft") is None
|
||||
|
||||
|
||||
def test_resolve_ignores_a_tool_in_the_current_directory(monkeypatch, tmp_path):
|
||||
_set_platform(monkeypatch, sys_plat="darwin", machine="arm64")
|
||||
_plant_in_cwd(monkeypatch, tmp_path, "difft")
|
||||
monkeypatch.setenv("HEADROOM_BINARIES_OFFLINE", "1")
|
||||
with pytest.raises(binaries.OfflineError):
|
||||
binaries.resolve("difft")
|
||||
|
||||
|
||||
def test_status_does_not_report_a_cwd_tool_as_on_path(monkeypatch, tmp_path):
|
||||
_set_platform(monkeypatch, sys_plat="darwin", machine="arm64")
|
||||
_plant_in_cwd(monkeypatch, tmp_path, "difft")
|
||||
row = next(r for r in binaries.status() if r["tool"] == "difft")
|
||||
assert row["state"] == "missing"
|
||||
assert row["path"] is None
|
||||
|
||||
|
||||
def test_which_skips_a_cwd_hit_and_finds_the_next_path_entry(monkeypatch, tmp_path):
|
||||
_plant_in_cwd(monkeypatch, tmp_path, "difft")
|
||||
bin_dir = tmp_path / "bin"
|
||||
bin_dir.mkdir()
|
||||
tool = bin_dir / "difft"
|
||||
tool.write_text("#!/bin/sh\n")
|
||||
tool.chmod(0o755)
|
||||
monkeypatch.setenv("PATH", os.pathsep.join([".", str(bin_dir)]))
|
||||
assert binaries.which("difft") == tool
|
||||
row = next(r for r in binaries.status() if r["tool"] == "difft")
|
||||
assert (row["state"], row["path"]) == ("on-path", str(tool))
|
||||
|
||||
|
||||
def test_which_skips_a_cwd_hit_with_windows_lookup_rules(monkeypatch, tmp_path):
|
||||
"""On Windows shutil.which() checks the cwd before every PATH it is given."""
|
||||
project = tmp_path / "project"
|
||||
project.mkdir()
|
||||
(project / "difft.exe").write_text("")
|
||||
bin_dir = tmp_path / "bin"
|
||||
bin_dir.mkdir()
|
||||
installed = bin_dir / "difft.exe"
|
||||
installed.write_text("")
|
||||
installed.chmod(0o755)
|
||||
monkeypatch.chdir(project)
|
||||
monkeypatch.setattr(binaries.sys, "platform", "win32")
|
||||
monkeypatch.setattr(binaries.sys, "prefix", str(tmp_path / "venv"))
|
||||
monkeypatch.setenv("PATH", str(bin_dir))
|
||||
monkeypatch.setenv("PATHEXT", ".exe")
|
||||
monkeypatch.setattr(
|
||||
binaries.shutil, "which", lambda name, path=None: os.path.join(".", f"{name}.exe")
|
||||
)
|
||||
assert binaries._which_outside_cwd("difft") == installed
|
||||
|
||||
|
||||
def test_status_reports_a_tool_in_the_interpreter_scripts_dir(monkeypatch, tmp_path):
|
||||
_set_platform(monkeypatch, sys_plat="darwin", machine="arm64")
|
||||
monkeypatch.setenv("PATH", "/no-such-bin")
|
||||
scripts = tmp_path / "venv" / "bin"
|
||||
scripts.mkdir(parents=True)
|
||||
(scripts / "difft").write_text("#!/bin/sh\n")
|
||||
(scripts / "difft").chmod(0o755)
|
||||
monkeypatch.setattr(binaries.sys, "prefix", str(tmp_path / "venv"))
|
||||
row = next(r for r in binaries.status() if r["tool"] == "difft")
|
||||
assert (row["state"], row["path"]) == ("on-path", str(scripts / "difft"))
|
||||
|
||||
|
||||
@pytest.mark.skipif(sys.platform.startswith("win"), reason="POSIX execute bit")
|
||||
def test_status_ignores_a_non_executable_file_in_the_scripts_dir(monkeypatch, tmp_path):
|
||||
_set_platform(monkeypatch, sys_plat="darwin", machine="arm64")
|
||||
monkeypatch.setenv("PATH", "/no-such-bin")
|
||||
scripts = tmp_path / "venv" / "bin"
|
||||
scripts.mkdir(parents=True)
|
||||
(scripts / "difft").write_text("not a program\n")
|
||||
(scripts / "difft").chmod(0o644)
|
||||
monkeypatch.setattr(binaries.sys, "prefix", str(tmp_path / "venv"))
|
||||
assert binaries.which("difft") is None
|
||||
row = next(r for r in binaries.status() if r["tool"] == "difft")
|
||||
assert (row["state"], row["path"]) == ("missing", None)
|
||||
|
||||
|
||||
def test_which_keeps_a_tool_on_path_outside_the_current_directory(monkeypatch, tmp_path):
|
||||
bin_dir = tmp_path / "bin"
|
||||
bin_dir.mkdir()
|
||||
tool = bin_dir / "difft"
|
||||
tool.write_text("#!/bin/sh\n")
|
||||
tool.chmod(0o755)
|
||||
monkeypatch.chdir(tmp_path)
|
||||
monkeypatch.setenv("PATH", str(bin_dir))
|
||||
assert binaries.which("difft") == tool
|
||||
|
||||
|
||||
# -------- Offline / mirror / fetch behavior ------------------------------ #
|
||||
|
||||
|
||||
|
||||
Reference in New Issue
Block a user