update_contract.py 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164
  1. """Image-managed install refusal contract.
  2. A refusal prints the real update command for the deployment kind, records a
  3. ``refused`` receipt (so fleet tooling sees "this install cannot self-update,
  4. use <command>" instead of a silent non-update), and exits 2 on CLI surfaces.
  5. """
  6. from __future__ import annotations
  7. import logging
  8. from dataclasses import dataclass
  9. from pathlib import Path
  10. from typing import Callable, Optional
  11. from hermes_cli.steward import STEWARD_APT_TERMUX, STEWARD_DESKTOP, STEWARD_DOCKER, STEWARD_NIX
  12. logger = logging.getLogger(__name__)
  13. COMMIT_BUILD_UPDATE_MESSAGE = (
  14. "This build doesn't get updates. Ask the developer who gave it to you for a new build."
  15. )
  16. def is_commit_build(project_root: Path) -> bool:
  17. from hermes_cli.steward import read_install_stamp
  18. return read_install_stamp(project_root).get("source") == "commit-build"
  19. @dataclass(frozen=True)
  20. class UpdateRefusal:
  21. """Why an in-place update is refused, and what to run instead."""
  22. code: str # image-marker | image-marker-invalid | docker | nix | apt | desktop-app | <steward>
  23. message: str # full user-facing text (multi-line ok)
  24. update_command: str # the one-line remediation command
  25. def _refusal(code: str, method: str, message: Optional[Callable[[str], str]] = None) -> UpdateRefusal:
  26. """Refusal for ``method``: ``message(command)`` if given, else docker's full message / the bare command."""
  27. from hermes_cli.config import format_docker_update_message, recommended_update_command_for_method
  28. command = recommended_update_command_for_method(method)
  29. if message is not None:
  30. text = message(command)
  31. else:
  32. text = format_docker_update_message() if method == "docker" else command
  33. return UpdateRefusal(code=code, message=text, update_command=command)
  34. # Sealed-tree steward -> install method whose CLI command remediates it. The
  35. # refusal code is the steward name itself. APT owns the Termux code tree:
  36. # ``pkg upgrade`` replaces it wholesale, so it must never update in place.
  37. _STEWARD_UPDATE_METHODS: dict[str, str] = {
  38. STEWARD_DOCKER: "docker",
  39. STEWARD_NIX: "nix",
  40. STEWARD_APT_TERMUX: "apt",
  41. }
  42. def _steward_refusal(steward: str) -> UpdateRefusal:
  43. """Refusal for a tree sealed by ``steward``."""
  44. from hermes_cli.steward import steward_update_message
  45. method = _STEWARD_UPDATE_METHODS.get(steward)
  46. if method == "docker":
  47. return _refusal(steward, method)
  48. if method is not None:
  49. return _refusal(steward, method, lambda _command: steward_update_message(steward))
  50. # desktop-app and future package managers have no CLI remediation: the
  51. # steward's own instructions are the remediation, and
  52. # recommended_update_command_for_method would falsely answer "hermes
  53. # update" for methods it doesn't know.
  54. command = (
  55. "Manage updates from within the desktop app"
  56. if steward == STEWARD_DESKTOP
  57. else f"update via {steward}"
  58. )
  59. return UpdateRefusal(code=steward, message=steward_update_message(steward), update_command=command)
  60. def evaluate_update_admission(project_root: Path) -> Optional[UpdateRefusal]:
  61. """Return an :class:`UpdateRefusal` when in-place update must not run.
  62. ``None`` means the install is eligible for in-place update (git checkout or unknown-but-
  63. mutable). Never raises; on any internal error it falls back to the heuristic layer only.
  64. """
  65. if is_commit_build(project_root):
  66. return UpdateRefusal("commit-build", COMMIT_BUILD_UPDATE_MESSAGE, "")
  67. # Layer 1: baked provenance marker — authoritative when present.
  68. try:
  69. from hermes_cli.image_provenance import read_image_provenance
  70. provenance = read_image_provenance()
  71. if provenance is not None:
  72. if not provenance.valid:
  73. # Present but malformed: still image-managed — an integrity defect is never
  74. # permission to mutate the image in place.
  75. return _refusal("image-marker-invalid", "docker", lambda command: (
  76. "✗ This install is image-managed, but its provenance "
  77. f"marker is invalid ({provenance.error}).\n"
  78. " In-place update is disabled. Update by pulling a "
  79. f"new image:\n {command}"
  80. ))
  81. return _refusal("image-marker", provenance.manager)
  82. except Exception as exc:
  83. logger.debug("Image provenance check failed (using heuristics): %s", exc)
  84. # Layer 2: install stamp / steward classification. A sealed tree (no
  85. # ``.git``) belongs to a steward — the desktop app bundle, a Docker
  86. # image, the Nix store — and only the steward updates it. This is the
  87. # rung that covers ``desktop-app``, which the heuristics below never
  88. # detect (the payload has no .install_method stamp and no .git).
  89. try:
  90. from hermes_cli.steward import sealed_steward
  91. steward = sealed_steward(project_root)
  92. if steward is None:
  93. from hermes_constants import is_termux
  94. if is_termux():
  95. from hermes_cli.steward import SOURCE_ON_TERMUX_UPDATE_COMMAND, SOURCE_ON_TERMUX_UPDATE_MESSAGE
  96. return UpdateRefusal(
  97. code=STEWARD_APT_TERMUX,
  98. message=SOURCE_ON_TERMUX_UPDATE_MESSAGE,
  99. update_command=SOURCE_ON_TERMUX_UPDATE_COMMAND,
  100. )
  101. elif steward != "unknown":
  102. return _steward_refusal(steward)
  103. except Exception as exc:
  104. logger.debug("Steward admission check failed: %s", exc)
  105. # Layer 3: pre-existing filesystem heuristics, verbatim semantics.
  106. try:
  107. from hermes_cli.config import detect_install_method, is_nix_install_method
  108. method = detect_install_method(project_root)
  109. if method == "docker":
  110. return _refusal("docker", method)
  111. if is_nix_install_method(method) or method == "apt":
  112. return _refusal(method if method == "apt" else "nix", method)
  113. except Exception as exc:
  114. logger.debug("Install-method admission check failed: %s", exc)
  115. return None
  116. def record_refusal_receipt(refusal: UpdateRefusal) -> None:
  117. """Write a minimal ``refused`` receipt for a blocked update attempt.
  118. Gives fleet tooling a durable record that an update was ATTEMPTED and refused ("not updatable in
  119. place, use <command>") instead of a silent nothing. Best-effort; never raises.
  120. """
  121. try:
  122. from hermes_cli.update_receipt import begin_update_receipt, finalize_update_receipt, record_step
  123. begin_update_receipt()
  124. detail = f"not updatable in place ({refusal.code})"
  125. detail += f"; use: {refusal.update_command}" if refusal.update_command else f"; {refusal.message}"
  126. record_step("admission", False, detail)
  127. finalize_update_receipt("refused", stop_reason=refusal.code)
  128. except Exception as exc:
  129. logger.debug("Could not record refusal receipt: %s", exc)