import json import subprocess import sys import tempfile import unittest from types import SimpleNamespace from unittest.mock import patch import rollback import deployment_lock import release_refs import release_state from rollback import ( image_restore_plan, require_running_image_ids, require_tag_rollback, tag_previous_images, verify_previous_images, ) class RollbackPlanTests(unittest.TestCase): def setUp(self): self.manifest = { "images": { "backend": {"configured": "akyldash/backend:local", "image_id": "sha256:" + "a" * 64}, "opensearch": {"configured": "akyldash/opensearch:local", "image_id": "sha256:" + "b" * 64}, } } self.configured = { "backend": "akyldash/backend:local", "opensearch": "akyldash/opensearch:local", } def test_plans_only_recorded_local_images(self): plan = image_restore_plan(self.manifest, self.configured) self.assertEqual(plan["backend"][1], "akyldash/backend:local") self.assertEqual(plan["opensearch"][1], "akyldash/opensearch:local") def test_rollback_rejects_running_images_that_differ_from_restore_plan(self): expected = {"backend": "sha256:" + "a" * 64, "opensearch": "sha256:" + "b" * 64} actual = {**expected, "opensearch": "sha256:" + "c" * 64} with self.assertRaisesRegex(ValueError, "rollback plan"): require_running_image_ids(expected, actual, "rollback plan") def test_refuses_changed_compose_image_reference(self): with self.assertRaisesRegex(ValueError, "reference changed"): image_restore_plan(self.manifest, {**self.configured, "backend": "other/backend:tag"}) def test_release_state_allows_guarded_digest_to_legacy_and_legacy_to_digest_restore(self): previous = self.manifest["images"].copy() self.configured["backend"] = "registry/backend@sha256:" + "d" * 64 plan = image_restore_plan(self.manifest, self.configured, previous) self.assertEqual(plan["backend"][1], "akyldash/backend:local") old_digest = "registry/backend@sha256:" + "c" * 64 self.manifest["images"]["backend"] = { "configured": old_digest, "image_id": "sha256:" + "a" * 64 } previous["backend"] = self.manifest["images"]["backend"] self.configured["backend"] = "akyldash/backend:local" plan = image_restore_plan(self.manifest, self.configured, previous) self.assertEqual(plan["backend"][1], old_digest) def test_refuses_digest_reference_that_cannot_be_retagged(self): self.manifest["images"]["backend"]["configured"] = "registry/backend@sha256:" + "c" * 64 self.configured["backend"] = self.manifest["images"]["backend"]["configured"] plan = image_restore_plan(self.manifest, self.configured) self.assertEqual(plan["backend"], ("sha256:" + "a" * 64, self.configured["backend"])) with self.assertRaisesRegex(ValueError, "not supported safely"): require_tag_rollback(plan) def test_refuses_malformed_digest_reference(self): self.manifest["images"]["backend"]["configured"] = "registry/backend@sha256:xyz" self.configured["backend"] = self.manifest["images"]["backend"]["configured"] with self.assertRaisesRegex(ValueError, "invalid image reference"): image_restore_plan(self.manifest, self.configured) def test_refuses_invalid_recorded_image_id(self): self.manifest["images"]["backend"]["image_id"] = "sha256:not-a-digest" with self.assertRaisesRegex(ValueError, "invalid previous image ID"): image_restore_plan(self.manifest, self.configured) def test_digest_reference_must_resolve_to_recorded_image_id(self): digest = "registry/backend@sha256:" + "c" * 64 self.manifest["images"]["backend"]["configured"] = digest self.configured["backend"] = digest plan = image_restore_plan(self.manifest, self.configured) with patch("rollback.run", side_effect=["sha256:" + "a" * 64, "sha256:" + "a" * 64, "sha256:" + "b" * 64]): verify_previous_images(plan) with patch("rollback.run", side_effect=["sha256:" + "a" * 64, "sha256:" + "d" * 64]): with self.assertRaisesRegex(ValueError, "does not match its recorded image"): verify_previous_images(plan) def test_missing_previous_image_fails_closed(self): plan = image_restore_plan(self.manifest, self.configured) with patch("rollback.run", side_effect=subprocess.CalledProcessError(1, "docker")): with self.assertRaisesRegex(ValueError, "previous image is unavailable"): verify_previous_images(plan) def test_digest_reference_is_restored_without_retagging(self): digest = "registry/backend@sha256:" + "c" * 64 plan = {"backend": ("sha256:" + "a" * 64, digest)} with patch("rollback.run") as run_mock: tag_previous_images(plan) run_mock.assert_not_called() def test_digest_rollback_fails_before_stopping_or_changing_references(self): backend_id = "sha256:" + "a" * 64 opensearch_id = "sha256:" + "b" * 64 digest = "registry/backend@sha256:" + "c" * 64 manifest = { "images": { "backend": {"configured": digest, "image_id": backend_id}, "opensearch": self.manifest["images"]["opensearch"], }, "deployment_files": { "deploy/production/compose.yaml": "compose-hash", "deploy/production/Caddyfile": "caddy-hash", }, } rendered = { "services": { "backend": {"image": digest}, "opensearch": {"image": self.configured["opensearch"]}, } } fake_archive = SimpleNamespace( digest=lambda path: "compose-hash" if path.name == "compose.yaml" else "caddy-hash", verify_archive=lambda _backup: manifest, ) with tempfile.TemporaryDirectory() as temporary: temporary = rollback.Path(temporary) backup_dir = temporary / "backups" backup_dir.mkdir() backup = backup_dir / "synthetic.tar.gz" original_stat = rollback.Path.stat def stat_backup_only(path, *args, **kwargs): if path in {backup, rollback.Path(f"{backup}.sha256")}: return SimpleNamespace(st_uid=0, st_mode=0o100600) return original_stat(path, *args, **kwargs) with ( patch.object(deployment_lock, "LOCK_FILE", temporary / "deploy.lock"), patch.object(rollback, "JOURNAL_FILE", temporary / "recovery.json"), patch.object(rollback, "STATE_FILE", temporary / "release-state.json"), patch.object(rollback, "ENV_FILE", temporary / "production.env"), patch.object(rollback, "DEPLOYED_IMAGE_FILE", temporary / "deployed-image.txt"), patch.object(rollback, "BACKUP_DIR", backup_dir), patch.object(rollback, "ROOT", temporary / "checkout"), patch.object(rollback, "COMPOSE_FILE", temporary / "checkout/deploy/production/compose.yaml"), patch.object(rollback, "BACKUP_TOOL", temporary / "archive.py"), patch("rollback.Path.is_file", return_value=True), patch("rollback.Path.is_symlink", return_value=False), patch("pathlib.Path.stat", autospec=True, side_effect=stat_backup_only), patch("rollback.compose", return_value=json.dumps(rendered)) as compose_mock, patch("rollback.running_image_ids", return_value={ "backend": backend_id, "opensearch": self.manifest["images"]["opensearch"]["image_id"], }), patch("rollback.run", side_effect=[backend_id, backend_id, opensearch_id]) as run_mock, patch.dict(sys.modules, {"archive": fake_archive}), ): with self.assertRaisesRegex(ValueError, "not supported safely"): rollback.rollback(backup, data_compatible=True) compose_mock.assert_called_once_with("config", "--format", "json", capture=True) self.assertEqual(run_mock.call_count, 3) self.assertTrue(all(call.args[0][:3] == ["docker", "image", "inspect"] for call in run_mock.call_args_list)) def test_mismatched_release_backup_is_rejected_before_stopping_services(self): current = { "backend": {"configured": "registry/backend@sha256:" + "d" * 64, "image_id": "sha256:" + "e" * 64}, "opensearch": {"configured": "registry/search@sha256:" + "f" * 64, "image_id": "sha256:" + "1" * 64}, } previous = { "backend": {"configured": "registry/backend@sha256:" + "a" * 64, "image_id": "sha256:" + "2" * 64}, "opensearch": {"configured": "registry/search@sha256:" + "b" * 64, "image_id": "sha256:" + "3" * 64}, } manifest = { "images": { "backend": {"configured": "registry/backend@sha256:" + "c" * 64, "image_id": previous["backend"]["image_id"]}, "opensearch": previous["opensearch"], }, "deployment_files": {"deploy/production/compose.yaml": "compose-hash", "deploy/production/Caddyfile": "caddy-hash"}, } state = {"schema_version": 1, "commit": "a" * 40, "manifest_sha256": "b" * 64, "current": current, "previous": previous} rendered = {"services": {"backend": {"image": current["backend"]["configured"]}, "opensearch": {"image": current["opensearch"]["configured"]}}} fake_archive = SimpleNamespace( digest=lambda path: "compose-hash" if path.name == "compose.yaml" else "caddy-hash", verify_archive=lambda _backup: manifest, ) with tempfile.TemporaryDirectory() as directory: root = rollback.Path(directory) backup_dir = root / "backups" backup_dir.mkdir() backup = backup_dir / "synthetic.tar.gz" state_file = root / "release-state.json" checksum = rollback.Path(f"{backup}.sha256") original_stat = rollback.Path.stat def stat_backup_only(path, *args, **kwargs): if path in {backup, checksum}: return SimpleNamespace(st_uid=0, st_mode=0o100600) return original_stat(path, *args, **kwargs) with ( patch.object(deployment_lock, "LOCK_FILE", root / "deploy.lock"), patch.object(rollback, "JOURNAL_FILE", root / "recovery.json"), patch.object(rollback, "STATE_FILE", state_file), patch.object(rollback, "ENV_FILE", root / "production.env"), patch.object(rollback, "DEPLOYED_IMAGE_FILE", root / "deployed-image.txt"), patch.object(rollback, "BACKUP_DIR", backup_dir), patch.object(rollback, "ROOT", root / "checkout"), patch.object(rollback, "COMPOSE_FILE", root / "checkout/deploy/production/compose.yaml"), patch.object(rollback, "BACKUP_TOOL", root / "archive.py"), patch("pathlib.Path.exists", autospec=True, side_effect=lambda path: path == state_file), patch("pathlib.Path.is_file", return_value=True), patch("pathlib.Path.is_symlink", return_value=False), patch("pathlib.Path.stat", autospec=True, side_effect=stat_backup_only), patch("rollback.compose", side_effect=lambda *args, **_kwargs: ( json.dumps(rendered) if args[:2] == ("config", "--format") else "backend-container" if args[-1] == "backend" else "search-container" )) as compose_mock, patch("rollback.run", side_effect=lambda command, **_kwargs: "true\t" + current[ "backend" if command[-1] == "backend-container" else "opensearch" ]["image_id"]), patch("release_state.read_json", return_value=state), patch.dict(sys.modules, {"archive": fake_archive}), ): with self.assertRaisesRegex(ValueError, "backup does not match the pinned previous backend"): rollback.rollback(backup, data_compatible=True) self.assertFalse(any(call.args and call.args[0] == "stop" for call in compose_mock.call_args_list)) def test_mismatched_running_rollback_images_preserve_state_and_recovery_journal(self): current = { "backend": {"configured": "registry/backend@sha256:" + "d" * 64, "image_id": "sha256:" + "e" * 64}, "opensearch": {"configured": "registry/search@sha256:" + "f" * 64, "image_id": "sha256:" + "1" * 64}, } previous = { "backend": {"configured": "akyldash/backend:previous", "image_id": "sha256:" + "a" * 64}, "opensearch": {"configured": "akyldash/opensearch:previous", "image_id": "sha256:" + "b" * 64}, } manifest = { "images": previous, "deployment_files": {"deploy/production/compose.yaml": "compose-hash", "deploy/production/Caddyfile": "caddy-hash"}, } state = {"schema_version": 1, "commit": "a" * 40, "manifest_sha256": "b" * 64, "current": current, "previous": previous} current_refs = {"BACKEND_IMAGE": current["backend"]["configured"], "OPENSEARCH_IMAGE": current["opensearch"]["configured"]} previous_refs = {"BACKEND_IMAGE": previous["backend"]["configured"], "OPENSEARCH_IMAGE": previous["opensearch"]["configured"]} rendered = {"services": {"backend": {"image": current_refs["BACKEND_IMAGE"]}, "opensearch": {"image": current_refs["OPENSEARCH_IMAGE"]}}} fake_archive = SimpleNamespace( digest=lambda path: "compose-hash" if path.name == "compose.yaml" else "caddy-hash", verify_archive=lambda _backup: manifest, ) expected_current_ids = {service: current[service]["image_id"] for service in current} unexpected_ids = {"backend": previous["backend"]["image_id"], "opensearch": "sha256:" + "c" * 64} with tempfile.TemporaryDirectory() as directory: root = rollback.Path(directory) backup_dir = root / "backups" backup_dir.mkdir() backup = backup_dir / "verified.tar.gz" state_file = root / "state.json" state_file.write_text(json.dumps(state), encoding="utf-8") env_file = root / "production.env" env_file.write_text( f"BACKEND_IMAGE={current_refs['BACKEND_IMAGE']}\n" f"OPENSEARCH_IMAGE={current_refs['OPENSEARCH_IMAGE']}\n", encoding="utf-8", ) checksum = rollback.Path(f"{backup}.sha256") original_stat = rollback.Path.stat def stat_backup_only(path, *args, **kwargs): if path in {backup, checksum}: return SimpleNamespace(st_uid=0, st_mode=0o100600) return original_stat(path, *args, **kwargs) original_replace = release_refs.replace_images def replace_without_root(path, expected, replacement): return original_replace(path, expected, replacement, require_root=False) with ( patch.object(deployment_lock, "LOCK_FILE", root / "deploy.lock"), patch.object(rollback, "JOURNAL_FILE", root / "recovery.json"), patch.object(rollback, "STATE_FILE", state_file), patch.object(rollback, "ENV_FILE", env_file), patch.object(rollback, "DEPLOYED_IMAGE_FILE", root / "deployed-image.txt"), patch.object(rollback, "BACKUP_DIR", backup_dir), patch.object(rollback, "ROOT", root / "checkout"), patch.object(rollback, "COMPOSE_FILE", root / "checkout/deploy/production/compose.yaml"), patch.object(rollback, "BACKUP_TOOL", root / "archive.py"), patch("pathlib.Path.is_file", return_value=True), patch("pathlib.Path.is_symlink", return_value=False), patch("pathlib.Path.stat", autospec=True, side_effect=stat_backup_only), patch("rollback.compose", side_effect=lambda *args, **_kwargs: ( json.dumps(rendered) if args[:2] == ("config", "--format") else "backend-container" if args[-1] == "backend" else "search-container" if args[-1] == "opensearch" else "" )), patch("rollback.running_image_ids", side_effect=[ expected_current_ids, unexpected_ids, expected_current_ids ]), patch("rollback.run", side_effect=lambda command, **_kwargs: ( command[-1] if command[1:3] == ["image", "inspect"] else current["backend"]["image_id"] if command[:2] == ["docker", "inspect"] else "" )), patch("release_refs.replace_images", side_effect=replace_without_root), patch("release_state.read_json", return_value=state), patch("release_state.write_json_atomic", wraps=release_state.write_json_atomic), patch.dict(sys.modules, {"archive": fake_archive}), ): with self.assertRaisesRegex(ValueError, "rollback plan"): rollback.rollback(backup, data_compatible=True) journal = json.loads((root / "recovery.json").read_text(encoding="utf-8")) self.assertEqual(journal["status"], "rollback-failed") self.assertIn("current release references restored", journal["recovery"]) self.assertEqual(json.loads(state_file.read_text(encoding="utf-8")), state) self.assertEqual(release_refs.read_images(env_file)[1], current_refs) def test_tag_rollback_keeps_existing_image_tag_operation(self): plan = image_restore_plan(self.manifest, self.configured) with patch("rollback.run") as run_mock: tag_previous_images(plan) self.assertEqual(run_mock.call_count, 2) run_mock.assert_any_call(["docker", "image", "tag", "sha256:" + "a" * 64, "akyldash/backend:local"]) if __name__ == "__main__": unittest.main()