| #!/usr/bin/env magpie-python | |
| # Licensed to the Apache Software Foundation (ASF) under one | |
| # or more contributor license agreements. See the NOTICE file | |
| # distributed with this work for additional information | |
| # regarding copyright ownership. The ASF licenses this file | |
| # to you under the Apache License, Version 2.0 (the | |
| # "License"); you may not use this file except in compliance | |
| # with the License. You may obtain a copy of the License at | |
| # | |
| # http://www.apache.org/licenses/LICENSE-2.0 | |
| # | |
| # Unless required by applicable law or agreed to in writing, | |
| # software distributed under the License is distributed on an | |
| # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY | |
| # KIND, either express or implied. See the License for the | |
| # specific language governing permissions and limitations | |
| # under the License. | |
| """Refuse framework Python started other than through `magpie-python`. | |
| Every start of the framework's Python goes through the launcher | |
| `plugins/magpie-setup/bin/magpie-python`: installed as `magpie-python` on | |
| PATH for skills, tools and hooks, run in place as | |
| `sh plugins/magpie-setup/bin/magpie-python` by this repository's prek and CI. | |
| It runs an installed Python 3.14 found by `uv python find --no-config | |
| --system`: never the machine's own `python3` (macOS's is 3.9), never a | |
| working-directory `.venv` or uv config, never anything from uv's cache. | |
| Reported, in prek hook entries, GitHub workflows, `hooks.json` / settings | |
| files, shell scripts, the shebang of every Python file, and commands in | |
| Markdown: | |
| - a bare interpreter (`python`, `python3`, `python3.N`) running `-m`, `-c` or | |
| a `.py` file; | |
| - a package's `__init__.py` run by path, under any interpreter: it loads the | |
| file as `__main__` beside a second copy of the module, so run `-m <package>`; | |
| - any `uvx … python@…`: uvx runs an ephemeral venv out of uv's cache, which | |
| the agent's sandbox can write, so a host-side run would execute whatever a | |
| sandboxed command left there. | |
| `uv run --project <tool> …` / `uv run --directory <tool> …` is accepted | |
| anywhere: it runs that workspace member's own environment, the form for tools | |
| with third-party dependencies. Any other `uv run … python` only in CI | |
| (`.github/`) and the adopter workflow templates, where a fresh runner checkout | |
| has no launcher and no `.venv`. | |
| A file that has to start Python another way is listed in `ALLOWED` with its | |
| reason; nothing is skipped silently. | |
| Usage: check-no-bare-python.py [FILE ...] (no files: the whole tree) | |
| Exit status: 0 clean, 1 findings. | |
| """ | |
| import re | |
| import subprocess | |
| import sys | |
| from pathlib import Path | |
| #: An interpreter that starts code: `python`, `python3` or `python3.N`, then | |
| #: optional flags, then `-m <module>`, `-c`, `-` (a program on stdin) or a | |
| #: `.py` path. | |
| BARE = re.compile( | |
| r"""(?<![\w@./-])python(?:3(?:\.\d+)?)?(?=\s)""" | |
| r"""(?:\s+-[A-Za-z]+)*\s+(?:-m\s+[\w.]+|-c\b|-(?=\s|$)|(?:\\?["'])?[^\s"'|;&)\\]*\.py\b)""" | |
| ) | |
| #: Running a package's `__init__.py` by path, under any interpreter. | |
| INIT_PATH = re.compile( | |
| r"""(?:\bpython[\w.@]*|magpie-python)(?:\s+-[A-Za-z]+)*\s+(?:\\?["'])?[^\s"'|;&)\\]*/__init__\.py\b""" | |
| ) | |
| #: `uvx` running an interpreter: an ephemeral venv out of uv's cache. Each | |
| #: option parses one way only (its name starts with a word character, a value | |
| #: is `=…` or a word not starting with `-`), so a run of dashes cannot make the | |
| #: match backtrack exponentially. | |
| UVX_PYTHON = re.compile(r"""\buvx\s+(?:--?\w[\w-]*(?:=\S*|\s+[^\s-]\S*)?\s+)*python(?:@|\s|$)""") | |
| #: The uv forms a bare match is part of (`uv run … python x.py`). | |
| UV_PREFIX = re.compile(r"""\buv\s+run\b[^|;&\n]*$""") | |
| #: `uv run` against a named workspace member (`--project` / `--directory`): | |
| #: the tool's own environment, the form for tools with dependencies. | |
| UV_RUN_MEMBER = re.compile(r"""\buv\s+run\b[^|;&\n]*--(?:project|directory)[ =][^|;&\n]*$""") | |
| #: Where any other `uv run … python` is the right form: a fresh CI checkout. | |
| UV_RUN_OK = (".github/", "plugins/magpie-setup/templates/workflows/") | |
| SHEBANG = re.compile(r"^#!.*(?<![\w-])python(?:3(?:\.\d+)?)?\s*$") | |
| LAUNCHER_SHEBANG = "#!/usr/bin/env magpie-python" | |
| #: path (or path prefix ending in "/") -> why Python starts another way there. | |
| ALLOWED: dict[str, str] = { | |
| # The agent-guard hooks and the other host-side launchers move to the | |
| # fail-closed `magpie-python` start in the follow-up that changes how a | |
| # missing launcher blocks each harness's hook (sandbox-lint parses them). | |
| "tools/agent-isolation/gpg-touch-overlay.sh": "probes for a python with tkinter for the touch window", | |
| "tools/agent-isolation/gpg-touch-overlay-window.py": "run by the overlay's tkinter-probed python, not by its shebang", | |
| "tools/agent-isolation/gpg-touch-overlay-window-macos.py": "run by the overlay's tkinter-probed python, not by its shebang", | |
| "tools/agent-isolation/hook-manager-shim.sh": ( | |
| "runs in adopter repos without the launcher; its stdlib composer.json read is optional and skipped without python3" | |
| ), | |
| "plugins/magpie-setup/skills/isolated-setup-doctor/scripts/probe-2-localhost-bind.sh": ( | |
| "a stdlib-only sandbox probe that must run when the launcher is broken; probe 3 reports the launcher" | |
| ), | |
| # Documentation that quotes a command rather than starting framework code. | |
| "docs/release-management/atr-release-runbook.md": "the operator's own venv for the ATR client", | |
| "docs/setup/sandbox-troubleshooting.md": "a quoted session transcript", | |
| "docs/setup/secure-agent-internals.md": "an example of a command an attacker would run", | |
| "docs/setup/secure-agent-setup.md": "a screenshot's alt text quoting the old command", | |
| "tools/spec-loop/specs/sandbox-diagnostics.md": "quotes doctor probe 2's command", | |
| } | |
| #: Never scanned: generated copies, history, and test inputs that quote | |
| #: commands as data. | |
| EXCLUDED = ( | |
| "plugins/magpie-agent-guard/tools/", | |
| "plugins/magpie-security-tools/tools/", | |
| "plugins/magpie-security-tools/plugins/", | |
| "plugins/magpie-vetted-ops/tools/", | |
| "docs/rfcs/", | |
| "tools/skill-evals/evals/", | |
| "tools/dev/check-no-bare-python.py", | |
| "tools/dev/tests/test_check_no_bare_python.py", | |
| ) | |
| SCANNED_SUFFIXES = (".md", ".sh", ".yml", ".yaml", ".json", ".py", ".toml") | |
| def _excluded(path: str) -> bool: | |
| return path.startswith(EXCLUDED) or "/tests/" in path or "/fixtures/" in path or path.startswith("tests/") | |
| def _allowed(path: str) -> bool: | |
| return any(path == key or (key.endswith("/") and path.startswith(key)) for key in ALLOWED) | |
| def _shebang(path: str, line: str) -> list[str]: | |
| if SHEBANG.match(line): | |
| return [f"{path}:1: shebang runs a bare python; use `{LAUNCHER_SHEBANG}`"] | |
| return [] | |
| def findings_in(path: str, text: str) -> list[str]: | |
| """`path:line: message` for each start that bypasses the launcher.""" | |
| lines = text.splitlines() | |
| if path.endswith(".py"): | |
| return _shebang(path, lines[0]) if lines else [] | |
| out: list[str] = [] | |
| uv_run_ok = path.startswith(UV_RUN_OK) | |
| for number, line in enumerate(lines, start=1): | |
| if number == 1 and path.endswith(".sh"): | |
| out.extend(_shebang(path, line)) | |
| for _ in UVX_PYTHON.finditer(line): | |
| out.append( | |
| f"{path}:{number}: `uvx … python` runs from uv's sandbox-writable cache; use `magpie-python`" | |
| ) | |
| for match in INIT_PATH.finditer(line): | |
| out.append( | |
| f"{path}:{number}: runs a package's __init__.py by path; use `-m <package>`: {match.group(0)!r}" | |
| ) | |
| for match in BARE.finditer(line): | |
| before = line[: match.start()] | |
| if UV_RUN_MEMBER.search(before) or (uv_run_ok and UV_PREFIX.search(before)): | |
| continue | |
| out.append( | |
| f"{path}:{number}: `{match.group(0).split()[0]}` starts Python directly; use `magpie-python`" | |
| ) | |
| return out | |
| def tracked_files() -> list[str]: | |
| listed = subprocess.run(["git", "ls-files", "-z"], capture_output=True, text=True, check=True).stdout | |
| return [p for p in listed.split("\0") if p] | |
| def main(argv: list[str]) -> int: | |
| paths = argv or tracked_files() | |
| found: list[str] = [] | |
| for path in paths: | |
| if not path.endswith(SCANNED_SUFFIXES) or _excluded(path) or _allowed(path): | |
| continue | |
| try: | |
| text = Path(path).read_text(encoding="utf-8") | |
| except OSError, UnicodeDecodeError: | |
| continue | |
| found.extend(findings_in(path, text)) | |
| for line in found: | |
| print(line) | |
| if found: | |
| print( | |
| f"\n{len(found)} start(s) bypass the launcher. Use `magpie-python …` " | |
| "(`sh plugins/magpie-setup/bin/magpie-python …` in this repository's prek and CI), " | |
| "or list the file in ALLOWED with the reason.", | |
| file=sys.stderr, | |
| ) | |
| return 1 if found else 0 | |
| if __name__ == "__main__": | |
| sys.exit(main(sys.argv[1:])) |