Files
akyldash/infra/deploy/windows_release_launcher.py
codex 710c483f34
CI / tests-and-images (pull_request) Successful in 2m15s
Runner smoke test / runner-smoke (pull_request) Successful in 3s
Harden external release preparation workflow
2026-11-03 09:38:37 +03:00

107 lines
4.4 KiB
Python

"""Harden the fixed Windows Python process before loading the release receiver."""
from __future__ import annotations
import importlib
import ntpath
import os
import shutil
import sys
from pathlib import Path
PYTHON_EXE = Path(r"C:\Python313\python.exe")
APP_DIR = Path(__file__).resolve().parent
WINDOWS_TOOLS = {
"ssh.exe": Path(r"C:\Windows\System32\OpenSSH\ssh.exe"),
"git.exe": Path(r"C:\Program Files\Git\cmd\git.exe"),
"powershell.exe": Path(r"C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe"),
}
WINDOWS_PATH = os.pathsep.join((
r"C:\Windows\System32\OpenSSH",
r"C:\Program Files\Git\cmd",
r"C:\Windows\System32",
r"C:\Windows",
))
def configure_windows_tool_environment(*, environ=None, which=shutil.which,
windows_root: Path = Path(r"C:\Windows")) -> None:
"""Remove inherited command lookup and Git overrides before receiver imports."""
environment = os.environ if environ is None else environ
system_root = str(windows_root)
environment["SystemRoot"] = system_root
environment["PATH"] = WINDOWS_PATH
environment["PATHEXT"] = ".EXE"
environment["PSModulePath"] = ntpath.join(
str(windows_root), "System32", "WindowsPowerShell", "v1.0", "Modules")
for name in tuple(environment):
if name.upper().startswith("GIT_"):
del environment[name]
for command, expected in WINDOWS_TOOLS.items():
resolved = which(command)
if resolved is None or os.path.normcase(os.path.abspath(resolved)) != os.path.normcase(os.path.abspath(expected)):
raise RuntimeError(f"required Windows tool is missing from its protected path: {command}")
def _is_beneath(path: Path, root: Path) -> bool:
try:
path.resolve().relative_to(root.resolve())
return True
except (OSError, ValueError):
return False
def configure_import_path(*, executable: Path, app_dir: Path, python_root: Path,
path_entries: list[str] | None = None,
expected_executable: Path = PYTHON_EXE,
protected_app_root: Path = Path(r"C:\Program Files")) -> None:
"""Keep only stdlib paths and the protected app directory; discard CWD/env paths."""
executable = Path(executable).resolve()
app_dir = Path(app_dir).resolve()
python_root = Path(python_root).resolve()
if os.path.normcase(str(executable)) != os.path.normcase(str(expected_executable.resolve())):
raise RuntimeError("release trigger must use the verified Python 3.13 installation")
if not app_dir.is_dir() or not _is_beneath(app_dir, protected_app_root):
raise RuntimeError("release receiver directory is outside protected Program Files")
if not python_root.is_dir() or not _is_beneath(executable, python_root):
raise RuntimeError("Python executable is outside its protected installation")
entries = sys.path if path_entries is None else path_entries
safe_stdlib = []
for value in entries:
if not value:
continue
candidate = Path(value)
if _is_beneath(candidate, python_root):
safe_stdlib.append(str(candidate))
if not safe_stdlib:
raise RuntimeError("Python standard library path is unavailable")
sys.path[:] = safe_stdlib + [str(app_dir)]
def _verify_module_origin(module, root: Path) -> None:
origin = getattr(module, "__file__", None)
if not isinstance(origin, str) or not _is_beneath(Path(origin), root):
raise RuntimeError(f"release module was loaded outside its protected directory: {module.__name__}")
def main() -> int:
flags = sys.flags
if not (flags.ignore_environment and flags.no_user_site and flags.no_site):
raise RuntimeError("launch Python with -E -s -S to disable environment and site imports")
configure_import_path(executable=Path(sys.executable), app_dir=APP_DIR,
python_root=PYTHON_EXE.parent)
if os.name == "nt":
configure_windows_tool_environment()
for name in ("json", "ssl", "subprocess", "pathlib"):
module = importlib.import_module(name)
_verify_module_origin(module, PYTHON_EXE.parent)
receiver = importlib.import_module("receive_external")
_verify_module_origin(receiver, APP_DIR)
for name in ("archive", "external_session"):
_verify_module_origin(importlib.import_module(name), APP_DIR)
return receiver.main()
if __name__ == "__main__":
raise SystemExit(main())