test_amd64_release_script_safety.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258
  1. from __future__ import annotations
  2. import re
  3. import subprocess
  4. from pathlib import Path
  5. ROOT = Path(__file__).resolve().parents[1]
  6. INSTALL = ROOT / "deploy" / "amd64-release" / "install.sh"
  7. UNINSTALL = ROOT / "deploy" / "amd64-release" / "uninstall.sh"
  8. MATRIX = ROOT / "tools" / "run_amd64_release_matrix.sh"
  9. def _text(path: Path) -> str:
  10. return path.read_text(encoding="utf-8")
  11. def _assert_removals_are_inside_helper(
  12. script: Path, helper: str, next_helper: str, allowed_outside: tuple[str, ...] = ()
  13. ) -> None:
  14. source = _text(script)
  15. helper_start = source.index(f"{helper}() {{")
  16. helper_end = source.index(f"\n{next_helper}() {{", helper_start)
  17. offset = 0
  18. for line_number, line in enumerate(source.splitlines(keepends=True), start=1):
  19. stripped = line.lstrip()
  20. if not stripped.startswith("#") and re.search(r"(?<![A-Za-z0-9_])(rm|rmdir)\s", line):
  21. inside = helper_start <= offset < helper_end
  22. explicitly_allowed = any(fragment in line for fragment in allowed_outside)
  23. assert inside or explicitly_allowed, (
  24. f"unguarded removal in {script.name}:{line_number}: {line.rstrip()}"
  25. )
  26. offset += len(line)
  27. def test_release_shell_entrypoints_parse() -> None:
  28. for script in (INSTALL, UNINSTALL, MATRIX):
  29. subprocess.run(["bash", "-n", str(script)], check=True)
  30. def test_all_tracked_shell_entrypoints_are_executable() -> None:
  31. scripts = sorted(ROOT.rglob("*.sh"))
  32. assert scripts
  33. for script in scripts:
  34. assert script.stat().st_mode & 0o111 == 0o111, f"not executable: {script}"
  35. def test_uninstall_allowlist_covers_every_owned_target_type() -> None:
  36. source = _text(UNINSTALL)
  37. expected = {
  38. "file:/usr/local/bin/hthd",
  39. "file:/usr/local/bin/hthctl",
  40. "file:/usr/local/bin/hth-capture",
  41. "file:/etc/systemd/system/hthd.service",
  42. "file:/etc/systemd/system/hthd@.service",
  43. "file:/usr/lib/sysusers.d/hth.conf",
  44. "file:/usr/lib/tmpfiles.d/hth.conf",
  45. "file:/usr/local/share/hth/sdk/hth_sdk-*.whl",
  46. "config:/etc/hth/hthd.yaml",
  47. "config:/etc/hth/release-metadata.json",
  48. "config:/etc/hth/install-manifest.txt",
  49. "config:/etc/hth/profiles/6400-control/profile.json",
  50. "config:/etc/hth/profiles/prod2u-door-temp/profile.json",
  51. "symlink:/etc/systemd/system/multi-user.target.wants/hthd.service",
  52. "managed_tree:/run/hth",
  53. "managed_tree:/var/lib/hth/captures",
  54. "managed_tree:/var/lib/hth/replay",
  55. "managed_tree:/var/lib/hth/receipts",
  56. "owned_dir:/usr/local/share/hth/sdk",
  57. "owned_dir:/usr/local/share/hth",
  58. "owned_dir:/etc/hth/profiles/6400-control",
  59. "owned_dir:/etc/hth/profiles/prod2u-door-temp",
  60. "owned_dir:/etc/hth/profiles",
  61. "owned_dir:/etc/hth",
  62. "owned_dir:/var/lib/hth",
  63. }
  64. missing = sorted(entry for entry in expected if entry not in source)
  65. assert not missing, f"uninstall allowlist is missing: {missing}"
  66. assert 'resolved="$(realpath -m -s -- "$path")"' in source
  67. assert '[[ "$resolved" == "$path" ]]' in source
  68. assert '${resolved#/usr/local/share/hth/sdk/}' in source
  69. assert '!= */*' in source
  70. def test_symlink_parent_guard_rejects_adversarial_parent(tmp_path: Path) -> None:
  71. source = _text(UNINSTALL)
  72. start = source.index("no_symlink_parents() {")
  73. end = source.index("\nsafe_path() {", start)
  74. helper = source[start:end]
  75. real_parent = tmp_path / "real-parent"
  76. linked_parent = tmp_path / "linked-parent"
  77. real_parent.mkdir()
  78. linked_parent.symlink_to(real_parent, target_is_directory=True)
  79. real_result = subprocess.run(
  80. ["bash", "-c", f'{helper}\nno_symlink_parents "$1"', "guard", str(real_parent / "file")],
  81. check=False,
  82. )
  83. linked_result = subprocess.run(
  84. ["bash", "-c", f'{helper}\nno_symlink_parents "$1"', "guard", str(linked_parent / "file")],
  85. check=False,
  86. )
  87. assert real_result.returncode == 0
  88. assert linked_result.returncode != 0
  89. assert 'no_symlink_parents "$resolved"' in source
  90. def test_product_removals_use_the_guarded_dispatchers() -> None:
  91. _assert_removals_are_inside_helper(
  92. UNINSTALL, "remove_owned_path", "manifest_identity_rejected"
  93. )
  94. _assert_removals_are_inside_helper(
  95. INSTALL,
  96. "remove_product_path",
  97. "identity_allowed",
  98. allowed_outside=('temp_config:-',),
  99. )
  100. assert 'rm -f -- "$SHAREDIR/sdk"/*.whl' not in _text(INSTALL)
  101. def test_current_manifest_never_claims_service_identity_ownership() -> None:
  102. install = _text(INSTALL)
  103. marker = 'cat >"$ETCDIR/install-manifest.txt" <<EOF'
  104. manifest = install.split(marker, 1)[1].split("\nEOF", 1)[0]
  105. assert "\naccount " not in manifest
  106. assert "\ngroup " not in manifest
  107. assert "\ncreated_account " not in manifest
  108. assert "\ncreated_group " not in manifest
  109. assert 'echo "created_account $identity_name"' not in install
  110. assert 'echo "created_group $identity_name"' not in install
  111. assert "/etc/hth/profiles/prod2u-door-temp" not in manifest
  112. assert "multi-user.target.wants/hthd.service" not in manifest
  113. assert 'if [[ -L "$UNITDIR/multi-user.target.wants/hthd.service" ]]' in install
  114. def test_purge_never_deletes_service_identities() -> None:
  115. uninstall = _text(UNINSTALL)
  116. assert "userdel " not in uninstall
  117. assert "groupdel " not in uninstall
  118. assert "current manifest cannot claim service identity ownership" in uninstall
  119. assert "created_account|created_group) manifest_identity_rejected" in uninstall
  120. def test_manifestless_paths_fail_closed_and_legacy_upgrade_is_fingerprinted() -> None:
  121. install = _text(INSTALL)
  122. uninstall = _text(UNINSTALL)
  123. expected_hashes = {
  124. "498ee4146b2d44490d58d0e13404978331772fd85bf546f5eea7cdded8c55ad8",
  125. "b57403ff3d3dfc0163aba4b35af33d26cb9aa64e54e4017e52f124aae0cf2421",
  126. "382e3e72f61732d26ce77b50323432c8ad534dffba2bea6b9ec029f89fcd1f43",
  127. "a6a83979d4d2195adf4704719dc750c0abdd48e803f6f8cc178234695d4afc7e",
  128. "4894e25647825ea614f8ffaffd72c66b0dc31c6efda1c8481dddd2316a07ae96",
  129. "3c783b5dfb7a17ed1f44eccb1956c5a8ec25e5daebab5d5287111c1387166364",
  130. "348a07b6b23a9fd3e860b830c15e0bdea17d1da5f28a380bea4065f6fbe800ac",
  131. }
  132. assert expected_hashes.issubset(set(re.findall(r"[0-9a-f]{64}", install)))
  133. assert 'if [[ "$ACTION" == upgrade && ! -f "$OLD_MANIFEST" ]]' in install
  134. assert "verify_legacy_v011" in install
  135. assert "unexpected hthd@.service beside legacy v0.1.1" in install
  136. assert "unknown old manifest kind" in install
  137. assert "old manifest is incomplete" in install
  138. assert "trusted install manifest requires release metadata" in install
  139. assert "old manifest claims an unowned legacy door-temperature path" in install
  140. for child_dir in (
  141. '"$SHAREDIR/sdk"',
  142. '"$ETCDIR/profiles"',
  143. '"$ETCDIR/profiles/6400-control"',
  144. '"$STATEDIR/captures"',
  145. '"$STATEDIR/replay"',
  146. '"$STATEDIR/receipts"',
  147. ):
  148. assert child_dir in install
  149. assert '"$ETCDIR/profiles/6400-control/profile.json"' in install
  150. assert '"$LIBDIR/sysusers.d/hth.conf"' in install
  151. assert "find \"$SHAREDIR/sdk\" -maxdepth 1" in install
  152. assert "HTH-like files exist without a trusted install manifest" in uninstall
  153. assert "declare -a FILES=()" in uninstall
  154. assert "declare -a CONFIGS=()" in uninstall
  155. footprint = install.split("FOOTPRINT=0", 1)[1].split(
  156. "declare -A OLD_MANIFEST_ENTRIES", 1
  157. )[0]
  158. for managed_tree in (
  159. '"$RUNDIR"',
  160. '"$STATEDIR/captures"',
  161. '"$STATEDIR/replay"',
  162. '"$STATEDIR/receipts"',
  163. ):
  164. assert managed_tree in footprint
  165. def test_uninstall_requires_strict_current_manifest_before_mutation() -> None:
  166. uninstall = _text(UNINSTALL)
  167. validation_end = uninstall.index('systemctl disable --now "$SERVICE"')
  168. validator = uninstall[:validation_end]
  169. assert '[[ -f "$ROOT/RELEASE-METADATA.json" ]]' in validator
  170. assert 'trusted install manifest requires installed release metadata' in validator
  171. assert 'installed release metadata does not match this uninstall package' in validator
  172. assert 'install manifest header does not match installed release metadata' in validator
  173. assert 'immutable installed file does not match uninstall package' in validator
  174. assert 'required immutable installed file is missing or not regular' in validator
  175. for artifact in (
  176. '"$BINDIR/hthd" "$ROOT/bin/hthd"',
  177. '"$BINDIR/hthctl" "$ROOT/bin/hthctl"',
  178. '"$BINDIR/hth-capture" "$ROOT/bin/hth-capture"',
  179. '"$UNITDIR/hthd.service" "$ROOT/service/hthd.service"',
  180. '"$LIBDIR/sysusers.d/hth.conf" "$ROOT/service/hth.conf"',
  181. '"$LIBDIR/tmpfiles.d/hth.conf"',
  182. '"$ETCDIR/profiles/6400-control/profile.json"',
  183. '"$EXPECTED_WHEEL" "${PACKAGE_WHEELS[0]}"',
  184. '"$ETCDIR/release-metadata.json"',
  185. ):
  186. assert artifact in validator
  187. assert 'duplicate current manifest entry' in validator
  188. assert 'current manifest is incomplete' in validator
  189. assert 'current manifest must contain exactly one owned SDK wheel' in validator
  190. assert 'entry is not valid for a current HTH manifest' in validator
  191. assert "userdel " not in validator
  192. assert "groupdel " not in validator
  193. assert not any(
  194. line.lstrip().startswith("remove_owned_path ") for line in validator.splitlines()
  195. )
  196. purge_residual = uninstall.split('if [[ "$PURGE" -eq 1 ]]; then', 2)[2]
  197. assert '"$ETCDIR/profiles/prod2u-door-temp/profile.json"' not in purge_residual
  198. manifestless_footprint = uninstall.split('if [[ ! -f "$MANIFEST" ]]', 1)[1].split(
  199. '[[ -f "$ROOT/RELEASE-METADATA.json" ]]', 1
  200. )[0]
  201. assert '"$ETCDIR/profiles/prod2u-door-temp/profile.json"' not in manifestless_footprint
  202. def test_matrix_preserves_preexisting_identities() -> None:
  203. matrix = _text(MATRIX)
  204. assert "SCENARIO_PREEXISTING_IDENTITIES" in matrix
  205. assert 'identities_before="$(identity_snapshot)"' in matrix
  206. assert 'identities_after="$(identity_snapshot)"' in matrix
  207. assert '[ "$identities_before" = "$identities_after" ]' in matrix
  208. assert "service identity was incorrectly claimed by HTH" in matrix
  209. assert "preexisting_identity_preservation=PASS" in matrix
  210. def test_matrix_contains_destructive_path_adversarial_scenarios() -> None:
  211. matrix = _text(MATRIX)
  212. assert "SCENARIO_SYMLINK_PATH_REJECTION" in matrix
  213. assert "SCENARIO_FAKE_MANIFEST_REJECTION" in matrix
  214. assert "SCENARIO_UNKNOWN_LEGACY_PROFILE_PRESERVED" in matrix
  215. assert "SCENARIO_CURRENT_PROFILE_SENTINEL_REJECTION" in matrix
  216. assert "SCENARIO_MANAGED_TREE_SENTINEL_REJECTION" in matrix
  217. assert "SCENARIO_FAKE_MANIFEST_UNINSTALL_REJECTION" in matrix
  218. assert "SCENARIO_FULL_MANIFEST_PARTIAL_CLOSURE_REJECTION" in matrix
  219. assert "install unexpectedly accepted symlink path" in matrix
  220. assert "upgrade unexpectedly accepted a fake manifest" in matrix
  221. assert "symlink_path_rejection=PASS" in matrix
  222. assert "fake_manifest_rejection=PASS" in matrix
  223. assert "unknown_legacy_profile_preserved=PASS" in matrix
  224. assert "current_profile_sentinel_rejection=PASS" in matrix
  225. assert "managed_tree_sentinel_rejection=PASS" in matrix
  226. assert "fake_manifest_uninstall_rejection=PASS" in matrix
  227. assert "full_manifest_partial_closure_rejection=PASS" in matrix
  228. assert "/etc/hth/profiles/prod2u-door-temp/profile.json" in matrix