macos_signing.py 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. """Managed interpreter identity, available before PM or application imports."""
  2. from __future__ import annotations
  3. import logging
  4. from pathlib import Path
  5. import platform
  6. import shutil
  7. import subprocess
  8. logger = logging.getLogger(__name__)
  9. _IDENTIFIER = "com.nousresearch.hermes.managed-python"
  10. def sign_managed_python(python: Path) -> bool:
  11. """Pin the designated requirement across downloaded Python generations.
  12. PBS's ad-hoc cdhash changes on upgrades. A stable identifier preserves
  13. TCC identity without a Developer ID certificate. Signing remains best
  14. effort so unavailable codesign cannot prevent a bootable interpreter.
  15. """
  16. if platform.system() != "Darwin":
  17. return False
  18. codesign = shutil.which("codesign")
  19. if not codesign:
  20. logger.info("macOS codesign is unavailable; using the downloaded Python signature")
  21. return False
  22. try:
  23. signed = subprocess.run(
  24. [codesign, "--force", "--deep", "--sign", "-", "--timestamp=none",
  25. "--identifier", _IDENTIFIER, "--requirements",
  26. f'=designated => identifier "{_IDENTIFIER}"', str(python)],
  27. check=False, capture_output=True, text=True, encoding="utf-8", errors="replace",
  28. )
  29. if signed.returncode != 0:
  30. logger.warning("could not stably sign managed Python %s: %s", python,
  31. (signed.stderr or signed.stdout or "codesign failed").strip())
  32. return False
  33. verified = subprocess.run(
  34. [codesign, "--verify", "--deep", "--strict", str(python)],
  35. check=False, capture_output=True, text=True, encoding="utf-8", errors="replace",
  36. )
  37. if verified.returncode != 0:
  38. logger.warning("macOS signature verification failed for managed Python %s: %s", python,
  39. (verified.stderr or verified.stdout or "verification failed").strip())
  40. return False
  41. return True
  42. except Exception as exc:
  43. logger.warning("could not sign managed Python %s: %s", python, exc)
  44. return False