Skip to content

The agent that grows with you

fix(pm): contain review security and dependency verification regressions

ethernetbd392ba92242
diff --git a/pm/cli.py b/pm/cli.py
index 452f85e0aef..10f3af63b8b 100644
--- a/pm/cli.py
+++ b/pm/cli.py
@@ -243,7 +243,9 @@ def cmd_env(args) -> int:
from pm.install import env_for
names = args.names or _lockfile().names()
- print(json.dumps(env_for(*names), indent=2, sort_keys=True))
+ # Show only package exports, never the caller's environment (which can
+ # contain credentials and is commonly pasted into support reports).
+ print(json.dumps(env_for(*names, base_env={}), indent=2, sort_keys=True))
return 0
diff --git a/pm/launch.py b/pm/launch.py
index ce4dcee3acf..389a817def7 100644
--- a/pm/launch.py
+++ b/pm/launch.py
@@ -4,13 +4,17 @@ import sys
import truststore
-# PM's import closure constructs HTTPS clients; install platform trust first.
-truststore.inject_into_ssl()
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
-from pm.cli import main
-from pm.runtime import lease_current_runtime
+def main() -> int:
+ # PM's import closure constructs HTTPS clients; install platform trust
+ # before importing it, but never mutate SSL merely by importing launch.
+ truststore.inject_into_ssl()
+ from pm.cli import main as cli_main
+ from pm.runtime import lease_current_runtime
-if __name__ == "__main__":
lease_current_runtime()
+ return cli_main()
+
+if __name__ == "__main__":
raise SystemExit(main())
diff --git a/pm/lock.py b/pm/lock.py
index 40419dba343..ba3ef60a149 100644
--- a/pm/lock.py
+++ b/pm/lock.py
@@ -151,7 +151,7 @@ class Facts:
self._packages = _read(path, strict=strict)["packages"]
def reload(self) -> None:
- self._packages = _read(self.path)["packages"]
+ self._packages = _read(self.path, strict=True)["packages"]
def get(self, name: str) -> dict | None:
return self._packages.get(name)
@@ -225,7 +225,7 @@ class Facts:
def _merge_and_write(self, name: str, fact: dict) -> None:
"""Read-modify-write against disk so concurrent installs of
different packages never clobber each other."""
- on_disk = _read(self.path)["packages"]
+ on_disk = _read(self.path, strict=True)["packages"]
for key, value in self._packages.items():
on_disk.setdefault(key, value)
self._packages = on_disk
diff --git a/pm/packages.py b/pm/packages.py
index d567c18b001..eea7d798874 100644
--- a/pm/packages.py
+++ b/pm/packages.py
@@ -621,18 +621,9 @@ class Git(BinaryPackage):
return out
def unpack(self, archive: Path, staged: Path, target: str) -> None:
- """stdlib tar extract, but skip members the data filter refuses —
- the MSYS tree ships dev/fd → /proc/self/fd style links that mean
- nothing on Windows and must not fail the install."""
- import tarfile
+ from pm.store import extract_tar
- staged.mkdir(parents=True, exist_ok=True)
- with tarfile.open(archive) as tf:
- for member in tf:
- try:
- tf.extract(member, staged, filter="data")
- except (tarfile.FilterError, OSError):
- continue
+ extract_tar(archive, staged, git_msys=True)
def env(self, entry: Path, target: str) -> dict:
return {"PATH": [str(entry / "cmd"), str(entry / "usr" / "bin")]}
diff --git a/pm/plugins_state.py b/pm/plugins_state.py
index af30c531e83..ca1e4f9fb0f 100644
--- a/pm/plugins_state.py
+++ b/pm/plugins_state.py
@@ -7,6 +7,9 @@ from __future__ import annotations
from pathlib import Path
from typing import Any, Optional
+import logging
+
+LOG = logging.getLogger(__name__)
def _profiles_root() -> Path:
@@ -112,7 +115,9 @@ def dependency_homes() -> list[Path]:
return homes
-def enabled_plugins_ordered(*, proposed_home=None, enabled=None, disabled=None, installing: Path | None = None) -> dict[Path, list[str]]:
+def enabled_plugins_ordered(*, proposed_home=None, enabled=None, disabled=None,
+ installing: Path | None = None,
+ skip_invalid_secondary: bool = False) -> dict[Path, list[str]]:
"""plugins_dir → ordered enabled list, per home. Keyed by the
PLUGINS DIR (where the member dirs live), not the home itself.
@@ -122,9 +127,16 @@ def enabled_plugins_ordered(*, proposed_home=None, enabled=None, disabled=None,
the union. Admission refuses a conflicting candidate without changing
the active environment or disabling an existing provider."""
out: dict[Path, list[str]] = {}
- for home in dependency_homes():
+ homes = dependency_homes()
+ for home in homes:
# ONE parse per home feeds both queries (enabled + provider).
- config = read_home_selection(home)
+ try:
+ config = read_home_selection(home)
+ except ValueError as exc:
+ if not skip_invalid_secondary or home == homes[0]:
+ raise
+ LOG.warning("Skipping broken secondary profile %s during dependency verification: %s", home, exc)
+ continue
config = config or {}
if proposed_home is not None and home.resolve() == Path(proposed_home).resolve():
config = {**config, "plugins": {"enabled": list(enabled or ()), "disabled": list(disabled or ())}}
diff --git a/pm/security_packages.py b/pm/security_packages.py
index 6b6110961d9..77840e8325e 100644
--- a/pm/security_packages.py
+++ b/pm/security_packages.py
@@ -3,6 +3,8 @@ from __future__ import annotations
import logging
import shutil
+import subprocess
+import tempfile
from pathlib import Path
from urllib.parse import urlparse
@@ -124,6 +126,24 @@ class IronProxy(_SignedBinary):
return [archive, f"{base}/checksums.txt", f"{base}/checksums.txt.asc", self.signing_key_url]
def verify_provenance(self, directory: Path) -> None:
- from agent.proxy_sources.iron_proxy import _verify_checksums_signature
-
- _verify_checksums_signature(directory, directory / "checksums.txt")
\ No newline at end of file
+ # Keep package provenance inside PM rather than calling a private
+ # helper in the running proxy (which also owns runtime subprocesses).
+ gpg = shutil.which("gpg")
+ if not gpg:
+ logging.getLogger(__name__).warning("gpg unavailable; iron-proxy archive checksum remains enforced")
+ return
+ with tempfile.TemporaryDirectory(prefix="hermes-iron-signature-") as home:
+ args = [gpg, "--homedir", home, "--batch", "--no-tty"]
+ signature = directory / "checksums.txt.asc"
+ key = directory / "public-key.asc"
+ if not signature.is_file() or not key.is_file():
+ raise InstallError(self.name, "pinned signature assets missing")
+ imported = subprocess.run([*args, "--import", str(key)], stdin=subprocess.DEVNULL,
+ capture_output=True, timeout=60, check=False)
+ if imported.returncode:
+ logging.getLogger(__name__).warning("Could not import iron-proxy signing key; archive checksum remains enforced")
+ return
+ verified = subprocess.run([*args, "--verify", str(signature), str(directory / "checksums.txt")],
+ stdin=subprocess.DEVNULL, capture_output=True, timeout=60, check=False)
+ if verified.returncode:
+ raise InstallError(self.name, "GPG signature verification failed")
\ No newline at end of file
diff --git a/pm/shell.py b/pm/shell.py
index 8c0372505f0..458b665effa 100644
--- a/pm/shell.py
+++ b/pm/shell.py
@@ -8,7 +8,8 @@ of hunting fixed locations.
Resolution order:
1. Windows: the git Package's staged bash (via facts.json) — the store
structurally guarantees it in a bundle; no hunt.
- 2. Windows: conventional Git for Windows under Program Files, then PATH —
+ 2. Windows: explicit override, Program Files, per-user and PortableGit,
+ then PATH —
minus C:\Windows\System32\bash.exe (the WSL launcher stub, first on PATH
on most machines; #116818) and WindowsApps\bash.exe (an MSIX alias that
only spawns inside its package). See windows_bash_candidates().
@@ -25,6 +26,7 @@ from __future__ import annotations
import ntpath
import os
import shutil
+import subprocess
from collections.abc import Mapping
from pm import paths
@@ -65,33 +67,52 @@ _WINDOWS_BASH_STUB_DIRS = ("system32", "windowsapps")
def windows_bash_candidates(on_path: str | None, env: Mapping[str, str]) -> list[str]:
"""Ordered bash.exe candidates for a Windows host, as pure data: the
- conventional Git for Windows dirs first, then ``on_path`` (the
- ``shutil.which("bash")`` result) unless it is a stub. Program Files beats
- PATH because System32 precedes Git on most PATHs (#116818)."""
+ explicit override and Git for Windows roots first, then ``on_path``
+ (the ``shutil.which("bash")`` result) unless it is a stub. System32
+ precedes Git on most PATHs (#116818)."""
programfiles = env.get("ProgramFiles", r"C:\Program Files")
- candidates = [
- ntpath.join(programfiles, "Git", "bin", "bash.exe"),
- ntpath.join(programfiles, "Git", "usr", "bin", "bash.exe"),
- ]
+ candidates = []
+ if env.get("HERMES_GIT_BASH_PATH"):
+ candidates.append(env["HERMES_GIT_BASH_PATH"])
+ roots = [ntpath.join(programfiles, "Git")]
+ if env.get("ProgramFiles(x86)"):
+ roots.append(ntpath.join(env["ProgramFiles(x86)"], "Git"))
+ if env.get("LOCALAPPDATA"):
+ roots.extend((ntpath.join(env["LOCALAPPDATA"], "hermes", "git"),
+ ntpath.join(env["LOCALAPPDATA"], "Programs", "Git")))
+ for root in roots:
+ candidates.extend((ntpath.join(root, "bin", "bash.exe"),
+ ntpath.join(root, "usr", "bin", "bash.exe")))
if on_path:
norm = ntpath.normpath(on_path).lower()
if not any(stub in norm for stub in _WINDOWS_BASH_STUB_DIRS):
candidates.append(on_path)
- return candidates
+ return list(dict.fromkeys(candidates))
+
+
+def _bash_starts(candidate: str) -> bool:
+ """An existing bash.exe can still be broken or be a launcher stub."""
+ try:
+ return subprocess.run(
+ [candidate, "-c", "exit 0"], stdin=subprocess.DEVNULL,
+ stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
+ timeout=5, creationflags=getattr(subprocess, "CREATE_NO_WINDOW", 0),
+ check=False,
+ ).returncode == 0
+ except (OSError, subprocess.TimeoutExpired):
+ return False
def bash() -> str | None:
"""Resolve the bash binary to use, or None if none is available."""
staged = _staged_bash()
- if staged:
+ if staged and _bash_starts(staged):
return staged
on_path = shutil.which("bash")
if os.name == "nt":
- return next(
- (c for c in windows_bash_candidates(on_path, os.environ) if os.path.isfile(c)),
- None,
- )
+ return next((c for c in windows_bash_candidates(on_path, os.environ)
+ if os.path.isfile(c) and _bash_starts(c)), None)
if on_path:
return on_path
diff --git a/pm/store.py b/pm/store.py
index b775160c5b6..ba122971b6e 100644
--- a/pm/store.py
+++ b/pm/store.py
@@ -29,41 +29,50 @@ ALL_TARGETS = (
def _native_machine() -> str:
- """The MACHINE's architecture, not the interpreter's. An x64 python on
- Windows-on-ARM reports AMD64 — staging a payload for the wrong target.
- IsWow64Process2 reports the real machine regardless of emulation."""
- if sys.platform.startswith("win"):
+ """Native host arch; PM also runs alone before the app is importable."""
+ try:
+ from hermes_platform.host.facts import native_arch
+ except ModuleNotFoundError as exc:
+ if exc.name != "hermes_platform":
+ raise
+ else:
+ return native_arch()
+
+ # Bootstrap's independent PM runtime contains only pm/, not the app.
+ # Consult the OS for translated processes rather than trusting Python's
+ # process architecture (Rosetta and WOW64 both report the wrong target).
+ if sys.platform == "darwin" and platform.machine().lower() in ("x86_64", "amd64"):
+ try:
+ import ctypes
+
+ value = ctypes.c_int()
+ size = ctypes.c_size_t(ctypes.sizeof(value))
+ if ctypes.CDLL(None).sysctlbyname(b"sysctl.proc_translated", ctypes.byref(value),
+ ctypes.byref(size), None, 0) == 0 and value.value == 1:
+ return "arm64"
+ except (AttributeError, OSError):
+ pass
+ if sys.platform == "win32":
try:
import ctypes
from ctypes import wintypes
- k32 = ctypes.WinDLL("kernel32", use_last_error=True)
- k32.GetCurrentProcess.restype = wintypes.HANDLE
- k32.IsWow64Process2.argtypes = [
- wintypes.HANDLE,
- ctypes.POINTER(ctypes.c_ushort),
- ctypes.POINTER(ctypes.c_ushort),
- ]
- k32.IsWow64Process2.restype = wintypes.BOOL
- process_machine = ctypes.c_ushort()
- native_machine = ctypes.c_ushort()
- if k32.IsWow64Process2(
- k32.GetCurrentProcess(),
- ctypes.byref(process_machine),
- ctypes.byref(native_machine),
- ):
- if native_machine.value == 0xAA64:
+ kernel = ctypes.WinDLL("kernel32", use_last_error=True)
+ kernel.GetCurrentProcess.restype = wintypes.HANDLE
+ kernel.IsWow64Process2.argtypes = [wintypes.HANDLE, ctypes.POINTER(ctypes.c_ushort),
+ ctypes.POINTER(ctypes.c_ushort)]
+ kernel.IsWow64Process2.restype = wintypes.BOOL
+ process, native = ctypes.c_ushort(), ctypes.c_ushort()
+ if kernel.IsWow64Process2(kernel.GetCurrentProcess(), ctypes.byref(process), ctypes.byref(native)):
+ if native.value == 0xAA64:
return "arm64"
- if native_machine.value == 0x8664:
+ if native.value == 0x8664:
return "x86_64"
- except Exception:
+ except (AttributeError, OSError):
pass
- # Pre-IsWow64Process2 hosts: WOW64 exposes the real machine here.
- wow = os.environ.get("PROCESSOR_ARCHITEW6432", "")
- if wow.upper() == "ARM64":
- return "arm64"
- if wow.upper() == "AMD64":
- return "x86_64"
+ wow = os.environ.get("PROCESSOR_ARCHITEW6432", "").lower()
+ if wow in ("arm64", "amd64"):
+ return wow
return platform.machine().lower()
@@ -148,17 +157,33 @@ def _tar_filter(member, dest: str):
return member.replace(deep=False, uid=None, gid=None, uname=None, gname=None, mode=None)
return tarfile.data_filter(member, dest)
+def extract_tar(archive: Path, dest: Path, *, git_msys: bool = False) -> None:
+ """Extract a tarball with one containment policy for PM's tar consumers.
-def extract(archive: Path, dest: Path) -> None:
+ MSYS Git ships dev/fd links into /proc; those aren't usable on Windows.
+ Skip only those known links, never a filter error or failed file write.
+ """
import tarfile
+ dest.mkdir(parents=True, exist_ok=True)
+ real_dest = os.path.realpath(dest)
+ with tarfile.open(archive) as tf:
+ if git_msys:
+ members = (m for m in tf if not (
+ m.issym() and m.name.lstrip("./").startswith("dev/")
+ and m.linkname.startswith("/proc/")))
+ for member in members:
+ tf.extract(member, dest, filter=lambda item, path: _tar_filter(item, real_dest))
+ else:
+ tf.extractall(dest, filter=lambda member, path: _tar_filter(member, real_dest))
+
+
+def extract(archive: Path, dest: Path) -> None:
shutil.rmtree(dest, ignore_errors=True)
dest.mkdir(parents=True, exist_ok=True)
name = archive.name.lower()
if name.endswith((".tar.gz", ".tgz", ".tar.xz", ".txz", ".tar.bz2")):
- real_dest = os.path.realpath(dest)
- with tarfile.open(archive) as tf:
- tf.extractall(dest, filter=lambda member, path: _tar_filter(member, real_dest))
+ extract_tar(archive, dest)
elif name.endswith(".zip"):
_extract_zip(archive, dest)
else:
diff --git a/pm/workspace.py b/pm/workspace.py
index 0fb587d04b4..5890c0e93c1 100644
--- a/pm/workspace.py
+++ b/pm/workspace.py
@@ -167,12 +167,14 @@ def _is_member_candidate(plugin_dir: Path) -> bool:
return read_python_declaration(plugin_dir).is_member
-def enabled_plugin_dirs(*, proposed_home=None, enabled=None, disabled=None, installing: Path | None = None) -> list[Path]:
+def enabled_plugin_dirs(*, proposed_home=None, enabled=None, disabled=None,
+ installing: Path | None = None, skip_invalid_secondary: bool = False) -> list[Path]:
"""Resolve the effective plugin selection without filtering dependency declarations."""
from pm.plugins_state import _is_directory, enabled_plugins_ordered
selection = enabled_plugins_ordered(
proposed_home=proposed_home, enabled=enabled, disabled=disabled, installing=installing,
+ skip_invalid_secondary=skip_invalid_secondary,
)
members = []
for plugins_dir, names in selection.items():
@@ -191,7 +193,8 @@ def enabled_plugin_dirs(*, proposed_home=None, enabled=None, disabled=None, inst
def enabled_member_dirs(*, proposed_home=None, enabled=None, disabled=None) -> list[Path]:
"""Keep every selected member or refuse an incompatible selection."""
- selected = enabled_plugin_dirs(proposed_home=proposed_home, enabled=enabled, disabled=disabled)
+ selected = enabled_plugin_dirs(proposed_home=proposed_home, enabled=enabled, disabled=disabled,
+ skip_invalid_secondary=proposed_home is None)
members = []
for path in selected:
declaration = read_python_declaration(path)
diff --git a/tests/pm/test_lockfile_publication.py b/tests/pm/test_lockfile_publication.py
index a948e89acd8..96f326f54b9 100644
--- a/tests/pm/test_lockfile_publication.py
+++ b/tests/pm/test_lockfile_publication.py
@@ -8,7 +8,19 @@ import threading
import pytest
-from pm.lock import Lockfile
+from pm.lock import Facts, Lockfile
+
+
+def test_corrupt_package_state_cannot_be_replaced_by_a_partial_write(tmp_path):
+ path = tmp_path / "facts.json"
+ facts = Facts(path)
+ facts.record_state("venv", "old", ["all"])
+ path.write_bytes(b"not JSON")
+ with pytest.raises(ValueError, match="recorded package state"):
+ facts.reload()
+ with pytest.raises(ValueError, match="recorded package state"):
+ facts.record_state("venv", "new", [])
+ assert path.read_bytes() == b"not JSON"
def test_pin_writers_merge_without_losing_other_rows(tmp_path):
diff --git a/tests/pm/test_plugins_state.py b/tests/pm/test_plugins_state.py
index ea9c6dc1590..52e2a0aa84b 100644
--- a/tests/pm/test_plugins_state.py
+++ b/tests/pm/test_plugins_state.py
@@ -64,7 +64,7 @@ def test_only_live_profiles_join_the_dependency_union(homes):
assert set(by_root) == {default_home / "plugins", profile_home / "plugins"}
[email protected]("boundary", ["profile-listing", "profile-stat", "config-read", "plugin-stat", "manifest-read", "manifest-stat", "provider-stat"])
[email protected]("boundary", ["profile-listing", "profile-stat", "plugin-stat", "manifest-read", "manifest-stat", "provider-stat"])
def test_unreadable_profile_state_is_not_an_empty_selection(homes, monkeypatch, boundary):
from pm.workspace import enabled_member_dirs
@@ -79,7 +79,6 @@ def test_unreadable_profile_state_is_not_an_empty_selection(homes, monkeypatch,
method, target = {
"profile-listing": ("iterdir", profile_home.parent),
"profile-stat": ("stat", profile_home),
- "config-read": ("read_text", profile_home / "config.yaml"),
"plugin-stat": ("stat", plugin),
"manifest-read": ("read_text", manifest),
"manifest-stat": ("stat", manifest),
@@ -120,6 +119,24 @@ def test_enabled_read_refuses_invalid_existing_config(homes, content):
pstate.enabled_plugins_ordered()
assert config.read_bytes() == before
+def test_verify_skips_bad_secondary_but_admission_refuses_it(homes, caplog):
+ from pm.workspace import enabled_member_dirs, enabled_plugin_dirs
+
+ default_home, profile_home = homes
+ plugin = default_home / "plugins" / "working"
+ plugin.mkdir(parents=True)
+ (plugin / "plugin.yaml").write_text("name: working\npython_dependencies: [requests]\n", encoding="utf-8")
+ _write_config(default_home, ["working"])
+ bad = profile_home / "config.yaml"
+ bad.write_text("plugins: [invalid]\n", encoding="utf-8")
+
+ assert enabled_member_dirs() == [plugin]
+ assert str(bad) in caplog.text
+ with pytest.raises(ValueError, match=re.escape(str(bad))):
+ enabled_plugin_dirs(proposed_home=default_home, enabled=["working"])
+ bad.write_text("plugins: {enabled: []}\n", encoding="utf-8")
+ assert enabled_member_dirs() == [plugin]
+
@pytest.mark.parametrize("content", ["", "# empty config\n", "null", "{}", "plugins: {}", "plugins:\n enabled: []"])
def test_empty_config_is_an_explicit_empty_selection(homes, content):
diff --git a/tests/pm/test_pm_core.py b/tests/pm/test_pm_core.py
index e77277b47ce..43de34f8543 100644
--- a/tests/pm/test_pm_core.py
+++ b/tests/pm/test_pm_core.py
@@ -184,6 +184,25 @@ def test_deps_compose_dependents_win(pm_env):
path = runner.env["PATH"]
assert path.index("toptool-1.0") < path.index("deptool-1.0")
+def test_cli_env_reports_only_package_exports(pm_env, monkeypatch, capsys):
+ import json
+ from argparse import Namespace
+ from pm.cli import cmd_env
+ from pm.install import ensure
+
+ lockfile_path, _, docroot, _ = pm_env
+ _, digest = make_tar(docroot, "deptool-1.0.tar.gz", {"bin/faketool": "y"})
+ _pin(lockfile_path, "deptool", "1.0", digest)
+ ensure("deptool", explicit=True)
+ monkeypatch.setenv("FAKE_API_KEY", "never-print-this-secret")
+ monkeypatch.setenv("PATH", "inherited-path-is-not-a-pm-export")
+ assert cmd_env(Namespace(names=["deptool"])) == 0
+ output = capsys.readouterr().out
+ assert "never-print-this-secret" not in output
+ assert "inherited-path-is-not-a-pm-export" not in output
+ assert json.loads(output)["DEPTOOL_SEEN"] == "1"
+ assert "deptool-1.0" in json.loads(output)["PATH"]
+
def test_activation_trusts_a_recorded_entry_a_deliberate_install_repairs(pm_env, monkeypatch):
"""Shell activation skips the byte re-hash; a deliberate install keeps it.
diff --git a/tests/pm/test_recovery.py b/tests/pm/test_recovery.py
index 12c97c70ab8..7f869d3ee21 100644
--- a/tests/pm/test_recovery.py
+++ b/tests/pm/test_recovery.py
@@ -159,7 +159,7 @@ def test_repair_restores_recorded_plugin_dependencies_without_config(tmp_path, m
assert config.read_bytes() == config_before
-def test_uncertain_profile_selection_refuses_sync_but_not_recorded_repair(tmp_path, monkeypatch, recovery_graph):
+def test_uncertain_profile_selection_skips_sync_but_not_admission_or_recorded_repair(tmp_path, monkeypatch, recovery_graph, caplog):
import pm.paths as paths
from hermes_cli.plugins_admission import AdmissionRefused, admit_plugin_set_change
from pm.environments import install_state_dir, selected_venv, site_packages
@@ -195,8 +195,6 @@ def test_uncertain_profile_selection_refuses_sync_but_not_recorded_repair(tmp_pa
sibling_config.write_text("plugins:\n enabled: [unclosed\n", encoding="utf-8")
damaged_config = sibling_config.read_bytes()
- with pytest.raises(ValueError, match="config.yaml"):
- engine.sync_venv(explicit=True)
with pytest.raises(AdmissionRefused, match="config.yaml"):
admit_plugin_set_change(set(), set(), active_plugins_dir=home / "plugins")
assert paths.runtime_facts_path().read_bytes() == before_facts
@@ -215,5 +213,14 @@ def test_uncertain_profile_selection_refuses_sync_but_not_recorded_repair(tmp_pa
)
assert result.stdout.strip() == "1.0"
assert Path(Facts(paths.runtime_facts_path()).get("venv")["resolved_lock"]).read_bytes() == old_lock
+ engine.sync_venv(explicit=True)
+ assert str(sibling_config) in caplog.text
+ current = selected_venv(core)
+ result = subprocess.run(
+ [str(current / ("Scripts/python.exe" if os.name == "nt" else "bin/python")),
+ "-I", "-c", "import core_dep; print(core_dep.__version__)"],
+ cwd=tmp_path, capture_output=True, text=True, check=True, timeout=30,
+ )
+ assert result.stdout.strip() == "1.0"
assert active_config.read_bytes() == before_config
assert sibling_config.read_bytes() == damaged_config
diff --git a/tests/pm/test_runtime_bootstrap_tls.py b/tests/pm/test_runtime_bootstrap_tls.py
index 51d6b5f706b..89c0c31ffd5 100644
--- a/tests/pm/test_runtime_bootstrap_tls.py
+++ b/tests/pm/test_runtime_bootstrap_tls.py
@@ -175,3 +175,13 @@ raise SystemExit(module['main']())
server.shutdown()
server.server_close()
thread.join(timeout=5)
+def test_importing_launch_does_not_patch_ssl_context():
+ import subprocess
+ import sys
+
+ from pm.paths import repo_root
+ child = subprocess.run(
+ [sys.executable, "-c", "import ssl; original = ssl.SSLContext; import pm.launch; assert ssl.SSLContext is original"],
+ cwd=repo_root(), capture_output=True, text=True, timeout=30, check=False,
+ )
+ assert child.returncode == 0, child.stderr
diff --git a/tests/pm/test_shell_candidates.py b/tests/pm/test_shell_candidates.py
index 889cc67d749..4a2539f4d88 100644
--- a/tests/pm/test_shell_candidates.py
+++ b/tests/pm/test_shell_candidates.py
@@ -22,3 +22,19 @@ def test_program_files_git_precedes_the_path_bash():
candidates = windows_bash_candidates(on_path, {"ProgramFiles": PF})
assert candidates[0] == PF + r"\Git\bin\bash.exe"
assert candidates[-1] == on_path
+
+def test_per_user_and_32bit_git_roots_are_candidates():
+ candidates = windows_bash_candidates(None, {
+ "ProgramFiles": PF, "ProgramFiles(x86)": r"D:\Progs32",
+ "LOCALAPPDATA": r"C:\Users\u\AppData\Local",
+ })
+ assert r"D:\Progs32\Git\bin\bash.exe" in candidates
+ assert r"C:\Users\u\AppData\Local\Programs\Git\bin\bash.exe" in candidates
+ assert r"C:\Users\u\AppData\Local\hermes\git\usr\bin\bash.exe" in candidates
+
+def test_nonstarting_bash_is_rejected(monkeypatch):
+ import subprocess
+ from pm import shell
+
+ monkeypatch.setattr(shell.subprocess, "run", lambda *a, **kw: subprocess.CompletedProcess(a, 1))
+ assert shell._bash_starts("broken-bash.exe") is False
diff --git a/tests/pm/test_store_extract.py b/tests/pm/test_store_extract.py
index da4832aeb63..683b053de7e 100644
--- a/tests/pm/test_store_extract.py
+++ b/tests/pm/test_store_extract.py
@@ -41,3 +41,31 @@ def test_symlinks_escaping_the_destination_are_rejected(tmp_path, linkname):
with pytest.raises(tarfile.FilterError):
extract(archive, tmp_path / "out")
assert not (tmp_path / "out" / "python/bin/evil").is_symlink()
+
+def test_git_tar_skips_only_msys_proc_links_and_rejects_other_unsafe_entries(tmp_path):
+ from pm.packages import Git
+
+ archive = tmp_path / "git.tar.bz2"
+ with tarfile.open(archive, "w:bz2") as tf:
+ proc = tarfile.TarInfo("dev/fd")
+ proc.type, proc.linkname = tarfile.SYMTYPE, "/proc/self/fd"
+ tf.addfile(proc)
+ good = tarfile.TarInfo("cmd/git.exe")
+ good.size = 1
+ tf.addfile(good, io.BytesIO(b"x"))
+ escape = tarfile.TarInfo("../../escaped")
+ escape.size = 1
+ tf.addfile(escape, io.BytesIO(b"z"))
+ with pytest.raises(tarfile.FilterError):
+ Git().unpack(archive, tmp_path / "out", "win32-x64")
+ assert (tmp_path / "out/cmd/git.exe").read_bytes() == b"x"
+ assert not (tmp_path / "out/dev/fd").exists()
+ assert not (tmp_path / "escaped").exists()
+
+
+def test_target_uses_shared_native_arch(monkeypatch):
+ from hermes_platform.host import facts
+ from pm import store
+
+ monkeypatch.setattr(facts, "native_arch", lambda: "arm64")
+ assert store._native_machine() == "arm64"