test_deploy.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408
  1. import io
  2. import io
  3. import json
  4. import os
  5. import shutil
  6. import sys
  7. import tarfile
  8. import tempfile
  9. import unittest
  10. from pathlib import Path
  11. from unittest.mock import patch
  12. ROOT = Path(__file__).resolve().parents[1]
  13. sys.path.insert(0, str(ROOT / "scripts"))
  14. import deploy
  15. class DeploymentTests(unittest.TestCase):
  16. def setUp(self):
  17. self.temporary = tempfile.TemporaryDirectory()
  18. self.home = Path(self.temporary.name) / "home"
  19. self.home.mkdir()
  20. self.registry_path = self.home / ".local/state/rigforge/deployment.json"
  21. self.commands = []
  22. self.run_patcher = patch.object(deploy, "run", side_effect=self.fake_run)
  23. self.run_patcher.start()
  24. self.home_patcher = patch.object(deploy.Path, "home", return_value=self.home)
  25. self.home_patcher.start()
  26. self.root_patcher = patch.object(deploy, "ROOT", ROOT)
  27. self.root_patcher.start()
  28. self.registry_patcher = patch.object(deploy, "STATE_PATH", self.registry_path)
  29. self.registry_patcher.start()
  30. def tearDown(self):
  31. patch.stopall()
  32. self.temporary.cleanup()
  33. def fake_run(self, command):
  34. self.commands.append(command)
  35. def nam_config(self, tag="v0.2.3"):
  36. return {
  37. "tag": tag,
  38. "archive_url": (
  39. "https://github.com/mikeoliphant/neural-amp-modeler-lv2/releases/download/"
  40. f"{tag}/neural_amp_modeler_lv2_rpi5.tgz"
  41. ),
  42. "bundle_directory": "neural_amp_modeler.lv2",
  43. }
  44. def plugin_config(self, component):
  45. return deploy.load_deployment()[component]
  46. def make_plugin_archive(self, destination, config):
  47. if config["archive_format"] == "7z":
  48. destination.write_bytes(b"simulated 7z archive")
  49. return
  50. with tarfile.open(destination, "w:xz") as archive:
  51. for bundle_name, bundle_path in config["bundle_paths"].items():
  52. directory = tarfile.TarInfo(bundle_path)
  53. directory.type = tarfile.DIRTYPE
  54. archive.addfile(directory)
  55. for filename, content in {
  56. "manifest.ttl": b"<urn:plugin> a <urn:Plugin> .\\n",
  57. "plugin.so": b"binary",
  58. }.items():
  59. info = tarfile.TarInfo(f"{bundle_path}/{filename}")
  60. info.size = len(content)
  61. info.mode = 0o755 if filename.endswith(".so") else 0o644
  62. archive.addfile(info, io.BytesIO(content))
  63. def install_plugin(self, component, config=None):
  64. config = config or self.plugin_config(component)
  65. def download(url, destination):
  66. self.make_plugin_archive(destination, config)
  67. with patch.object(deploy, "download_archive", side_effect=download):
  68. if config["archive_format"] == "7z":
  69. def extract_7z(archive_path, bundle_paths, extraction_root):
  70. extracted = {}
  71. for name in bundle_paths:
  72. bundle = extraction_root / name
  73. bundle.mkdir()
  74. (bundle / "manifest.ttl").write_text("plugin manifest", encoding="utf-8")
  75. (bundle / "plugin.so").write_bytes(b"binary")
  76. extracted[name] = bundle
  77. return extracted
  78. with patch.object(deploy, "extract_7z_bundles", side_effect=extract_7z):
  79. deploy.deploy_lv2_archives("install", component, config, deploy.read_registry())
  80. else:
  81. deploy.deploy_lv2_archives("install", component, config, deploy.read_registry())
  82. def pipewire_config(self):
  83. return {
  84. "fragment_source": "config/pipewire/filter-chain.conf.d/rigforge-direct-mix.conf",
  85. "fragment_destination": ".config/pipewire/filter-chain.conf.d/rigforge-direct-mix.conf",
  86. "user_service": "filter-chain.service",
  87. }
  88. def make_archive(self, destination, files=None):
  89. files = files or {"manifest.ttl": b"<urn:nam> a <urn:Plugin> .\n", "plugin.so": b"binary"}
  90. with tarfile.open(destination, "w:gz") as archive:
  91. directory = tarfile.TarInfo("neural_amp_modeler.lv2")
  92. directory.type = tarfile.DIRTYPE
  93. archive.addfile(directory)
  94. for name, content in files.items():
  95. info = tarfile.TarInfo(f"neural_amp_modeler.lv2/{name}")
  96. info.size = len(content)
  97. archive.addfile(info, io.BytesIO(content))
  98. def install_nam(self, config=None):
  99. config = config or self.nam_config()
  100. def download(url, destination):
  101. self.make_archive(destination)
  102. with patch.object(deploy, "download_archive", side_effect=download):
  103. deploy.deploy_namlv2("install", config, deploy.read_registry())
  104. def test_pipewire_install_is_atomic_scoped_and_idempotent(self):
  105. config = self.pipewire_config()
  106. deploy.deploy_pipewire("install", config, deploy.read_registry(), 128)
  107. installed = self.home / config["fragment_destination"]
  108. self.assertEqual(installed.read_bytes(), (ROOT / config["fragment_source"]).read_bytes())
  109. self.assertEqual(
  110. self.commands,
  111. [
  112. ["pw-metadata", "-n", "settings", "0", "clock.force-quantum", "128"],
  113. ["systemctl", "--user", "restart", "filter-chain.service"],
  114. ["systemctl", "--user", "is-active", "--quiet", "filter-chain.service"],
  115. ],
  116. )
  117. self.commands.clear()
  118. deploy.deploy_pipewire("install", config, deploy.read_registry(), 128)
  119. self.assertEqual(
  120. self.commands,
  121. [["pw-metadata", "-n", "settings", "0", "clock.force-quantum", "128"]],
  122. )
  123. self.assertFalse(any("pipewire.service" in command for command in self.commands))
  124. def test_pipewire_uninstall_restores_previous_file(self):
  125. config = self.pipewire_config()
  126. destination = self.home / config["fragment_destination"]
  127. destination.parent.mkdir(parents=True)
  128. destination.write_text("previous config", encoding="utf-8")
  129. deploy.deploy_pipewire("install", config, deploy.read_registry(), 128)
  130. self.commands.clear()
  131. deploy.deploy_pipewire("uninstall", config, deploy.read_registry(), 128)
  132. self.assertEqual(destination.read_text(encoding="utf-8"), "previous config")
  133. self.assertEqual(self.commands[0][-1], "0")
  134. self.assertEqual(self.commands[1], ["systemctl", "--user", "restart", "filter-chain.service"])
  135. self.assertNotIn("pipewire", deploy.read_registry())
  136. self.assertFalse(deploy.read_registry().get("pipewire_pending_reload"))
  137. def test_pipewire_pending_uninstall_recovers_after_prior_file_restored(self):
  138. config = self.pipewire_config()
  139. destination = self.home / config["fragment_destination"]
  140. destination.parent.mkdir(parents=True)
  141. destination.write_text("prior config", encoding="utf-8")
  142. deploy.deploy_pipewire("install", config, deploy.read_registry(), 128)
  143. registry = deploy.read_registry()
  144. registry["pipewire"]["pending_uninstall"] = True
  145. deploy.write_registry(registry)
  146. destination.write_text("prior config", encoding="utf-8")
  147. Path(registry["pipewire"]["backup"]).unlink()
  148. deploy.deploy_pipewire("uninstall", config, registry, 128)
  149. self.assertEqual(destination.read_text(encoding="utf-8"), "prior config")
  150. self.assertNotIn("pipewire", deploy.read_registry())
  151. def test_pipewire_pending_uninstall_recovers_after_fragment_removal(self):
  152. config = self.pipewire_config()
  153. deploy.deploy_pipewire("install", config, deploy.read_registry(), 128)
  154. destination = self.home / config["fragment_destination"]
  155. destination.unlink()
  156. registry = deploy.read_registry()
  157. registry["pipewire"]["pending_uninstall"] = True
  158. deploy.write_registry(registry)
  159. deploy.deploy_pipewire("uninstall", config, registry, 128)
  160. self.assertFalse(destination.exists())
  161. self.assertNotIn("pipewire", deploy.read_registry())
  162. self.assertEqual(self.commands[-3:], [
  163. ["pw-metadata", "-n", "settings", "0", "clock.force-quantum", "0"],
  164. ["systemctl", "--user", "restart", "filter-chain.service"],
  165. ["systemctl", "--user", "is-active", "--quiet", "filter-chain.service"],
  166. ])
  167. def test_pipewire_uninstall_refuses_local_changes(self):
  168. config = self.pipewire_config()
  169. deploy.deploy_pipewire("install", config, deploy.read_registry(), 128)
  170. destination = self.home / config["fragment_destination"]
  171. destination.write_text("local edit", encoding="utf-8")
  172. with self.assertRaisesRegex(RuntimeError, "changed locally"):
  173. deploy.deploy_pipewire("uninstall", config, deploy.read_registry(), 128)
  174. self.assertEqual(destination.read_text(encoding="utf-8"), "local edit")
  175. def test_lsp_install_uninstall_restores_existing_bundle_and_is_idempotent(self):
  176. component = "lsp"
  177. config = self.plugin_config(component)
  178. destination = self.home / ".lv2/lsp-plugins.lv2"
  179. destination.mkdir(parents=True)
  180. (destination / "old.txt").write_text("prior plugin", encoding="utf-8")
  181. self.install_plugin(component, config)
  182. self.assertTrue((destination / "manifest.ttl").is_file())
  183. registry = deploy.read_registry()
  184. self.assertEqual(registry[component]["tag"], "1.2.37")
  185. self.assertTrue(registry[component]["archive_sha256"])
  186. self.commands.clear()
  187. with patch.object(deploy, "download_archive", side_effect=AssertionError("must not download")):
  188. deploy.deploy_lv2_archives("install", component, config, registry)
  189. deploy.deploy_lv2_archives("uninstall", component, config, registry)
  190. self.assertEqual((destination / "old.txt").read_text(encoding="utf-8"), "prior plugin")
  191. self.assertNotIn(component, deploy.read_registry())
  192. def test_dragonfly_install_and_uninstall_manage_all_bundles(self):
  193. component = "dragonfly_reverb"
  194. config = self.plugin_config(component)
  195. first_name = next(iter(config["bundle_paths"]))
  196. first_destination = self.home / ".lv2" / first_name
  197. first_destination.mkdir(parents=True)
  198. (first_destination / "old.txt").write_text("prior plugin", encoding="utf-8")
  199. self.install_plugin(component, config)
  200. registry = deploy.read_registry()
  201. self.assertEqual(set(registry[component]["bundles"]), set(config["bundle_paths"]))
  202. for name in config["bundle_paths"]:
  203. self.assertTrue((self.home / ".lv2" / name / "manifest.ttl").is_file())
  204. deploy.deploy_lv2_archives("uninstall", component, config, registry)
  205. self.assertEqual((first_destination / "old.txt").read_text(encoding="utf-8"), "prior plugin")
  206. self.assertNotIn(component, deploy.read_registry())
  207. def test_plugin_update_preserves_old_bundles_when_staging_fails(self):
  208. component = "dragonfly_reverb"
  209. config = self.plugin_config(component)
  210. self.install_plugin(component, config)
  211. destinations = {
  212. name: self.home / ".lv2" / name for name in config["bundle_paths"]
  213. }
  214. original_hashes = {name: deploy.tree_sha256(path) for name, path in destinations.items()}
  215. updated = dict(config, tag="3.2.11")
  216. def fail_copy(source, destination, **kwargs):
  217. if Path(destination).name == "DragonflyPlateReverb.lv2.rigforge-new":
  218. raise OSError("simulated staging failure")
  219. return original_copytree(source, destination, **kwargs)
  220. original_copytree = deploy.shutil.copytree
  221. with patch.object(deploy, "download_archive", side_effect=lambda url, path: self.make_plugin_archive(path, config)):
  222. with patch.object(deploy, "extract_tar_bundles", return_value={name: self.home / "source" / name for name in config["bundle_paths"]}):
  223. source_root = self.home / "source"
  224. for name in config["bundle_paths"]:
  225. bundle = source_root / name
  226. bundle.mkdir(parents=True)
  227. (bundle / "manifest.ttl").write_text("new plugin", encoding="utf-8")
  228. with patch.object(deploy.shutil, "copytree", side_effect=fail_copy):
  229. with self.assertRaisesRegex(OSError, "simulated staging failure"):
  230. deploy.deploy_lv2_archives("install", component, updated, deploy.read_registry())
  231. self.assertEqual(
  232. {name: deploy.tree_sha256(path) for name, path in destinations.items()},
  233. original_hashes,
  234. )
  235. leftover_names = {path.name for path in (self.home / ".lv2").iterdir()}
  236. self.assertFalse(any(name.endswith(".rigforge-new") or name.endswith(".rigforge-old") for name in leftover_names))
  237. def test_plugin_pending_uninstall_recovers_after_bundle_removal(self):
  238. component = "dragonfly_reverb"
  239. config = self.plugin_config(component)
  240. self.install_plugin(component, config)
  241. registry = deploy.read_registry()
  242. registry[component]["pending_uninstall"] = True
  243. deploy.write_registry(registry)
  244. removed_name = "DragonflyEarlyReflections.lv2"
  245. destination = self.home / ".lv2" / removed_name
  246. shutil.rmtree(destination)
  247. deploy.deploy_lv2_archives("uninstall", component, config, registry)
  248. self.assertFalse(destination.exists())
  249. self.assertNotIn(component, deploy.read_registry())
  250. def test_plugin_install_refuses_local_edits_and_reload_is_noop(self):
  251. component = "dragonfly_reverb"
  252. config = self.plugin_config(component)
  253. self.install_plugin(component, config)
  254. destination = self.home / ".lv2/DragonflyHallReverb.lv2"
  255. (destination / "manifest.ttl").write_text("local edit", encoding="utf-8")
  256. with self.assertRaisesRegex(RuntimeError, "changed locally"):
  257. deploy.deploy_lv2_archives("uninstall", component, config, deploy.read_registry())
  258. self.assertEqual((destination / "manifest.ttl").read_text(encoding="utf-8"), "local edit")
  259. self.commands.clear()
  260. deploy.deploy_lv2_archives("reload", component, config, deploy.read_registry())
  261. self.assertEqual(self.commands, [])
  262. def test_release_archive_layouts_match_declarations(self):
  263. lsp_listing = """Path = /tmp/lsp.7z
  264. Type = 7z
  265. Physical Size = 456
  266. Path = lsp-plugins-1.2.37-Linux-aarch64/LV2/lsp-plugins.lv2
  267. Attributes = D_ drwxr-xr-xr
  268. Path = lsp-plugins-1.2.37-Linux-aarch64/LV2/lsp-plugins.lv2/manifest.ttl
  269. Attributes = A_ -rw-r--r--
  270. """
  271. self.assertEqual(
  272. deploy.inspect_7z_archive(
  273. self.plugin_config("lsp")["bundle_paths"], lsp_listing
  274. ),
  275. (
  276. {Path("lsp-plugins-1.2.37-Linux-aarch64/LV2/lsp-plugins.lv2")},
  277. [
  278. (Path("lsp-plugins-1.2.37-Linux-aarch64/LV2/lsp-plugins.lv2"), True),
  279. (Path("lsp-plugins-1.2.37-Linux-aarch64/LV2/lsp-plugins.lv2/manifest.ttl"), False),
  280. ],
  281. ),
  282. )
  283. def test_7z_plugin_archive_rejects_path_traversal(self):
  284. listing = """Path = /tmp/lsp.7z
  285. Type = 7z
  286. Physical Size = 456
  287. Path = ../escape
  288. Attributes = A_ -rw-r--r--
  289. """
  290. with self.assertRaisesRegex(RuntimeError, "unsafe archive path"):
  291. deploy.inspect_7z_archive(self.plugin_config("lsp")["bundle_paths"], listing)
  292. def test_tar_plugin_archive_rejects_path_traversal(self):
  293. archive_path = self.home / "bad.tar.xz"
  294. with tarfile.open(archive_path, "w:xz") as archive:
  295. info = tarfile.TarInfo("../escape")
  296. info.size = 1
  297. archive.addfile(info, io.BytesIO(b"x"))
  298. with self.assertRaisesRegex(RuntimeError, "unsafe archive path"):
  299. deploy.inspect_tar_archive(archive_path, self.plugin_config("dragonfly_reverb")["bundle_paths"])
  300. def test_nam_install_and_uninstall_restore_existing_bundle(self):
  301. destination = self.home / ".lv2/neural_amp_modeler.lv2"
  302. destination.mkdir(parents=True)
  303. (destination / "old.txt").write_text("prior plugin", encoding="utf-8")
  304. self.install_nam()
  305. self.assertTrue((destination / "manifest.ttl").is_file())
  306. self.assertTrue((destination / "plugin.so").is_file())
  307. registry = deploy.read_registry()
  308. self.assertEqual(registry["namlv2"]["tag"], "v0.2.3")
  309. self.assertTrue(registry["namlv2"]["archive_sha256"])
  310. self.assertTrue(registry["namlv2"]["installed_sha256"])
  311. deploy.deploy_namlv2("uninstall", self.nam_config(), registry)
  312. self.assertEqual((destination / "old.txt").read_text(encoding="utf-8"), "prior plugin")
  313. self.assertNotIn("manifest.ttl", {path.name for path in destination.iterdir()})
  314. self.assertNotIn("namlv2", deploy.read_registry())
  315. def test_nam_pending_uninstall_recovers_after_bundle_removal(self):
  316. destination = self.home / ".lv2/neural_amp_modeler.lv2"
  317. destination.mkdir(parents=True)
  318. (destination / "old.txt").write_text("prior plugin", encoding="utf-8")
  319. self.install_nam()
  320. registry = deploy.read_registry()
  321. registry["namlv2"]["pending_uninstall"] = True
  322. deploy.write_registry(registry)
  323. shutil.rmtree(destination)
  324. deploy.deploy_namlv2("uninstall", self.nam_config(), registry)
  325. self.assertTrue((destination / "old.txt").is_file())
  326. self.assertNotIn("namlv2", deploy.read_registry())
  327. def test_nam_install_same_tag_is_idempotent(self):
  328. self.install_nam()
  329. self.commands.clear()
  330. with patch.object(deploy, "download_archive", side_effect=AssertionError("must not download")):
  331. deploy.deploy_namlv2("install", self.nam_config(), deploy.read_registry())
  332. self.assertEqual(self.commands, [])
  333. def test_nam_install_update_refuses_local_changes_and_restore_baseline(self):
  334. self.install_nam()
  335. destination = self.home / ".lv2/neural_amp_modeler.lv2"
  336. (destination / "manifest.ttl").write_text("user edit", encoding="utf-8")
  337. with patch.object(deploy, "download_archive", side_effect=AssertionError("must not download")):
  338. with self.assertRaisesRegex(RuntimeError, "changed locally"):
  339. deploy.deploy_namlv2("install", self.nam_config("v0.2.4"), deploy.read_registry())
  340. self.assertEqual((destination / "manifest.ttl").read_text(encoding="utf-8"), "user edit")
  341. def test_nam_reload_is_informational_only(self):
  342. deploy.deploy_namlv2("reload", self.nam_config(), {})
  343. self.assertEqual(self.commands, [])
  344. def test_nam_archive_rejects_path_traversal(self):
  345. archive_path = self.home / "bad.tgz"
  346. with tarfile.open(archive_path, "w:gz") as archive:
  347. info = tarfile.TarInfo("../escape")
  348. info.size = 1
  349. archive.addfile(info, io.BytesIO(b"x"))
  350. with self.assertRaisesRegex(RuntimeError, "unsafe archive path"):
  351. deploy.inspect_archive(archive_path, "neural_amp_modeler.lv2")
  352. def test_nam_registry_is_valid_json(self):
  353. self.install_nam()
  354. registry = json.loads(self.registry_path.read_text(encoding="utf-8"))
  355. self.assertIn("namlv2", registry)
  356. if __name__ == "__main__":
  357. unittest.main()