diff --git a/lanes/dev1/repair_overlay/scripture_archive_platform/transport/contracts.py b/lanes/dev1/repair_overlay/scripture_archive_platform/transport/contracts.py index ee663c478..ae7d9a423 100644 --- a/lanes/dev1/repair_overlay/scripture_archive_platform/transport/contracts.py +++ b/lanes/dev1/repair_overlay/scripture_archive_platform/transport/contracts.py @@ -22,7 +22,7 @@ "authoring.undo","authoring.redo","authoring.publish_version","authoring.list_versions","authoring.rollback_version", "keymap.list","keymap.rebind","keymap.clear","keymap.reset_context","keymap.reset_all", "keymap.export","keymap.import","settings.get","settings.set", - "speech.status","speech.synthesize_prompt","application_update.select_verify","application_update.select_verify_stage","application_update.pending_status","application_update.prepare_apply","application_update.apply_and_restart","application_update.commit_post_restart_health","application_update.cancel_pending","dossier.get","diagnostics.get_report" + "speech.status","speech.synthesize_prompt","application_update.select_verify","application_update.select_verify_stage","application_update.pending_status","application_update.prepare_apply","application_update.apply_and_restart","application_update.cancel_pending","application_update.commit_post_restart_health","dossier.get","diagnostics.get_report" }) _PLAYER_TRUTH_OWNERS = frozenset({"D5/runtime", "REFERENCE_TEST_ONLY"}) @@ -102,7 +102,7 @@ def validate_request_shape(request:Any)->tuple[str,str,dict[str,Any]]: raise ValueError('authoring.pack_compatibility accepts an empty payload') if cmd=='speech.status' and payload: raise ValueError('speech.status accepts an empty payload') - if cmd in {'application_update.pending_status','application_update.prepare_apply','application_update.apply_and_restart','application_update.commit_post_restart_health','application_update.cancel_pending'} and payload: + if cmd in {'application_update.pending_status','application_update.prepare_apply','application_update.apply_and_restart','application_update.cancel_pending','application_update.commit_post_restart_health'} and payload: raise ValueError(f'{cmd} accepts an empty payload') if cmd=='speech.synthesize_prompt': allowed={'provider_id','voice_id','speed','allow_network'} diff --git a/lanes/dev1/repair_overlay/tests/test_application_update_transport_contracts.py b/lanes/dev1/repair_overlay/tests/test_application_update_transport_contracts.py new file mode 100644 index 000000000..8e1b1a07f --- /dev/null +++ b/lanes/dev1/repair_overlay/tests/test_application_update_transport_contracts.py @@ -0,0 +1,48 @@ +from __future__ import annotations + +import unittest + +from scripture_archive_platform.transport.contracts import validate_request_shape + + +API_VERSION = "scripture.transport.v1" +UPDATE_COMMANDS = ( + "application_update.apply_and_restart", + "application_update.commit_post_restart_health", +) + + +def request(command: str, payload=None, *, request_id: str = "update-contract-rid"): + return { + "api_version": API_VERSION, + "request_id": request_id, + "command": command, + "payload": {} if payload is None else payload, + } + + +class ApplicationUpdateTransportContractTests(unittest.TestCase): + def test_host_owned_update_commands_are_allowlisted_with_empty_payload(self) -> None: + for command in UPDATE_COMMANDS: + with self.subTest(command=command): + rid, parsed_command, payload = validate_request_shape(request(command)) + self.assertEqual(rid, "update-contract-rid") + self.assertEqual(parsed_command, command) + self.assertEqual(payload, {}) + + def test_browser_cannot_supply_update_process_path_or_identity_authority(self) -> None: + injected_payloads = ( + {"pid": 1}, + {"path": r"C:\attacker.exe"}, + {"version": "9.9.9"}, + {"sha256": "0" * 64}, + ) + for command in UPDATE_COMMANDS: + for payload in injected_payloads: + with self.subTest(command=command, payload=payload): + with self.assertRaisesRegex(ValueError, "empty payload"): + validate_request_shape(request(command, payload)) + + +if __name__ == "__main__": + unittest.main() diff --git a/lanes/dev1/repair_overlay/tests/test_packaged_diagnostics.py b/lanes/dev1/repair_overlay/tests/test_packaged_diagnostics.py index e97bfbe1a..ab9b50e49 100644 --- a/lanes/dev1/repair_overlay/tests/test_packaged_diagnostics.py +++ b/lanes/dev1/repair_overlay/tests/test_packaged_diagnostics.py @@ -173,20 +173,26 @@ def test_builder_fails_closed_on_native_failure_and_stale_artifact(self): 'Assert-NativeSuccess "updater artifact verification"', ): self.assertIn(step, build) - stale_cleanup_loop = "foreach ($artifact in @($Out, $UpdaterOut))" stale_cleanup = "Remove-Item -LiteralPath $artifact -Force" - self.assertIn(stale_cleanup_loop, build) + self.assertIn("foreach ($artifact in @($Out, $UpdaterOut))", build) self.assertIn(stale_cleanup, build) - self.assertLess(build.index(stale_cleanup_loop), build.index("pyinstaller.exe")) self.assertLess(build.index(stale_cleanup), build.index("pyinstaller.exe")) self.assertLess( - build.index('Assert-NativeSuccess "PyInstaller updater build"'), + build.index('Assert-NativeSuccess "PyInstaller application build"'), build.index('if (-not (Test-Path -LiteralPath $Out -PathType Leaf))'), ) self.assertLess( - build.index('Assert-NativeSuccess "updater artifact verification"'), + build.index('Assert-NativeSuccess "PyInstaller updater build"'), + build.index('if (-not (Test-Path -LiteralPath $UpdaterOut -PathType Leaf))'), + ) + self.assertLess( + build.index('Assert-NativeSuccess "application artifact verification"'), build.index('Write-Output "Built $Out'), ) + self.assertLess( + build.index('Assert-NativeSuccess "updater artifact verification"'), + build.index('Write-Output "Built $UpdaterOut'), + ) def test_desktop_host_wraps_update_layer_with_read_only_diagnostics(self): platform = Path(__file__).resolve().parents[1] diff --git a/lanes/dev1/repair_overlay/tests/test_packaged_updater_host_launch.py b/lanes/dev1/repair_overlay/tests/test_packaged_updater_host_launch.py index 4395d7647..5c7f5c36a 100644 --- a/lanes/dev1/repair_overlay/tests/test_packaged_updater_host_launch.py +++ b/lanes/dev1/repair_overlay/tests/test_packaged_updater_host_launch.py @@ -251,7 +251,7 @@ def test_frontend_exposes_accessible_two_step_install_without_html_injection(sel self.assertIn("pending-update-apply-restart", script) self.assertIn("Встановити й перезапустити", script) self.assertIn("apply.disabled=true", script) - self.assertIn("button.disabled=busy||", script) + self.assertIn("button.disabled=busy", script) self.assertIn("aria-live", script) self.assertIn("textContent", script) self.assertNotIn("innerHTML", script) diff --git a/runtime_engine/scripture_archive_runtime/application_update_updater.py b/runtime_engine/scripture_archive_runtime/application_update_updater.py index 49cffdfa2..249a479b1 100644 --- a/runtime_engine/scripture_archive_runtime/application_update_updater.py +++ b/runtime_engine/scripture_archive_runtime/application_update_updater.py @@ -119,7 +119,11 @@ def _consume_apply_handoff_locked( installed_sha = _sha256_file(target) if installed_sha != pending.artifact_sha256: raise ApplicationUpdateError("installed artifact failed exact-byte verification") - discard_apply_handoff(root) + post_publish_handoff = inspect_apply_handoff(root, current_version=current_version) + if post_publish_handoff != pending: + raise ApplicationUpdateError("apply handoff changed after atomic publication") + if discard_apply_handoff(root) is not True: + raise ApplicationUpdateError("apply handoff disappeared during disarm") except Exception as apply_error: try: candidate.unlink() @@ -297,20 +301,38 @@ def _discard_file(path: Path) -> None: def _copy_exact(source: Path, destination: Path) -> None: try: - descriptor = os.open(destination, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o700) + source_handle = source.open("rb") except OSError as exc: - raise ApplicationUpdateError("could not create update copy safely") from exc - try: - with source.open("rb") as src, os.fdopen(descriptor, "wb", closefd=True) as dst: - shutil.copyfileobj(src, dst, length=_COPY_CHUNK) - dst.flush() - os.fsync(dst.fileno()) - except Exception: + raise ApplicationUpdateError("update source could not be opened") from exc + + with source_handle as src: try: - destination.unlink() - except OSError: - pass - raise + descriptor = os.open(destination, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o700) + except OSError as exc: + raise ApplicationUpdateError("could not create update copy safely") from exc + try: + destination_handle = os.fdopen(descriptor, "wb", closefd=True) + except Exception: + try: + os.close(descriptor) + finally: + try: + destination.unlink() + except OSError: + pass + raise + + try: + with destination_handle as dst: + shutil.copyfileobj(src, dst, length=_COPY_CHUNK) + dst.flush() + os.fsync(dst.fileno()) + except Exception: + try: + destination.unlink() + except OSError: + pass + raise def _sha256_file(path: Path) -> str: diff --git a/runtime_engine/tests/test_application_update_health.py b/runtime_engine/tests/test_application_update_health.py index 6a6aa2a29..3c459511f 100644 --- a/runtime_engine/tests/test_application_update_health.py +++ b/runtime_engine/tests/test_application_update_health.py @@ -24,6 +24,32 @@ def _sha(data: bytes) -> str: return hashlib.sha256(data).hexdigest() +def _fixture(tmp_path: Path): + root = tmp_path / "state" / "updates" + root.mkdir(parents=True) + target = tmp_path / "install" / "Scripture Archive.exe" + target.parent.mkdir() + previous = b"previous-installed-exact-bytes" + installed = b"updated-installed-exact-bytes" + target.write_bytes(installed) + rollback = target.with_name(target.name + ".scripture-archive.rollback") + rollback.write_bytes(previous) + return root, target, rollback, previous, installed + + +def _publish(tmp_path: Path): + root, target, rollback, previous, installed = _fixture(tmp_path) + receipt = publish_update_health_receipt( + root, + previous_version=PREVIOUS_VERSION, + target_version=TARGET_VERSION, + install_target=target, + previous_sha256=_sha(previous), + installed_sha256=_sha(installed), + ) + return root, target, rollback, previous, installed, receipt + + class ApplicationUpdateHealthTests(unittest.TestCase): def setUp(self) -> None: self.temp = tempfile.TemporaryDirectory() @@ -32,32 +58,8 @@ def setUp(self) -> None: def tearDown(self) -> None: self.temp.cleanup() - def _fixture(self): - root = self.tmp_path / "state" / "updates" - root.mkdir(parents=True) - target = self.tmp_path / "install" / "Scripture Archive.exe" - target.parent.mkdir() - previous = b"previous-installed-exact-bytes" - installed = b"updated-installed-exact-bytes" - target.write_bytes(installed) - rollback = target.with_name(target.name + ".scripture-archive.rollback") - rollback.write_bytes(previous) - return root, target, rollback, previous, installed - - def _publish(self): - root, target, rollback, previous, installed = self._fixture() - receipt = publish_update_health_receipt( - root, - previous_version=PREVIOUS_VERSION, - target_version=TARGET_VERSION, - install_target=target, - previous_sha256=_sha(previous), - installed_sha256=_sha(installed), - ) - return root, target, rollback, previous, installed, receipt - def test_publish_and_inspect_bind_version_name_and_exact_installed_rollback_bytes(self) -> None: - root, target, rollback, previous, installed, receipt = self._publish() + root, target, rollback, previous, installed, receipt = _publish(self.tmp_path) self.assertEqual(receipt.previous_version, PREVIOUS_VERSION) self.assertEqual(receipt.target_version, TARGET_VERSION) @@ -82,7 +84,7 @@ def test_publish_and_inspect_bind_version_name_and_exact_installed_rollback_byte self.assertNotIn("rollback_path", payload) def test_publish_is_idempotent_only_for_same_exact_identity(self) -> None: - root, target, rollback, previous, installed, first = self._publish() + root, target, rollback, previous, installed, first = _publish(self.tmp_path) before = (root / "update-health.json").read_bytes() second = publish_update_health_receipt( root, @@ -106,7 +108,7 @@ def test_publish_is_idempotent_only_for_same_exact_identity(self) -> None: ) def test_inspect_fails_closed_on_version_installed_or_rollback_tamper(self) -> None: - root, target, rollback, previous, installed, receipt = self._publish() + root, target, rollback, previous, installed, receipt = _publish(self.tmp_path) with self.assertRaisesRegex(ApplicationUpdateError, "target version is not current"): inspect_update_health_receipt(root, current_version="1.2.0", install_target=target) @@ -121,7 +123,7 @@ def test_inspect_fails_closed_on_version_installed_or_rollback_tamper(self) -> N inspect_update_health_receipt(root, current_version=TARGET_VERSION, install_target=target) def test_receipt_shape_extra_field_and_symlink_fail_closed(self) -> None: - root, target, rollback, previous, installed, receipt = self._publish() + root, target, rollback, previous, installed, receipt = _publish(self.tmp_path) path = root / "update-health.json" payload = json.loads(path.read_text(encoding="utf-8")) payload["unexpected"] = True @@ -140,7 +142,7 @@ def test_receipt_shape_extra_field_and_symlink_fail_closed(self) -> None: inspect_update_health_receipt(root, current_version=TARGET_VERSION, install_target=target) def test_commit_disarms_old_pending_then_receipt_and_rollback_after_exact_proof(self) -> None: - root, target, rollback, previous, installed, receipt = self._publish() + root, target, rollback, previous, installed, receipt = _publish(self.tmp_path) pending = root / "pending-update.json" pending.write_text("old-version journal need not be parsed", encoding="utf-8") @@ -156,7 +158,7 @@ def test_commit_disarms_old_pending_then_receipt_and_rollback_after_exact_proof( self.assertEqual(target.read_bytes(), installed) def test_failed_health_proof_preserves_receipt_pending_and_rollback(self) -> None: - root, target, rollback, previous, installed, receipt = self._publish() + root, target, rollback, previous, installed, receipt = _publish(self.tmp_path) pending = root / "pending-update.json" pending.write_text("old-version journal", encoding="utf-8") target.write_bytes(b"tampered") @@ -168,9 +170,9 @@ def test_failed_health_proof_preserves_receipt_pending_and_rollback(self) -> Non self.assertTrue(rollback.exists()) def test_discard_only_disarms_receipt_and_preserves_recovery_bytes(self) -> None: - root, target, rollback, previous, installed, receipt = self._publish() - self.assertTrue(discard_update_health_receipt(root)) - self.assertFalse(discard_update_health_receipt(root)) + root, target, rollback, previous, installed, receipt = _publish(self.tmp_path) + self.assertIs(discard_update_health_receipt(root), True) + self.assertIs(discard_update_health_receipt(root), False) self.assertEqual(rollback.read_bytes(), previous) self.assertEqual(target.read_bytes(), installed) diff --git a/runtime_engine/tests/test_application_update_parent_wait.py b/runtime_engine/tests/test_application_update_parent_wait.py index e22ecc7c4..aafb2497e 100644 --- a/runtime_engine/tests/test_application_update_parent_wait.py +++ b/runtime_engine/tests/test_application_update_parent_wait.py @@ -32,13 +32,19 @@ def backend(pid: int, timeout_ms: int) -> None: def test_wait_rejects_invalid_pid(self) -> None: for pid in [0, -1, True, 1.5, "1"]: - with self.subTest(pid=pid), self.assertRaises(ParentProcessWaitError): - wait_for_parent_exit(pid, wait_backend=lambda *_: None) + with self.subTest(pid=pid): + with self.assertRaises(ParentProcessWaitError): + wait_for_parent_exit(pid, wait_backend=lambda *_: None) # type: ignore[arg-type] def test_wait_rejects_invalid_or_unbounded_timeout(self) -> None: for timeout_ms in [0, -1, 120_001, True, 1.5]: - with self.subTest(timeout_ms=timeout_ms), self.assertRaises(ParentProcessWaitError): - wait_for_parent_exit(4242, timeout_ms=timeout_ms, wait_backend=lambda *_: None) + with self.subTest(timeout_ms=timeout_ms): + with self.assertRaises(ParentProcessWaitError): + wait_for_parent_exit( # type: ignore[arg-type] + 4242, + timeout_ms=timeout_ms, + wait_backend=lambda *_: None, + ) def test_wait_is_windows_only_without_injected_backend(self) -> None: with self.assertRaisesRegex(ParentProcessWaitError, "Windows-only"): diff --git a/runtime_engine/tests/test_application_update_process.py b/runtime_engine/tests/test_application_update_process.py index c5106b341..ddb75ba75 100644 --- a/runtime_engine/tests/test_application_update_process.py +++ b/runtime_engine/tests/test_application_update_process.py @@ -13,6 +13,18 @@ ) +def _files(tmp_path: Path) -> tuple[Path, Path, Path]: + install = tmp_path / "Program Files" / "Архів Писання" + install.mkdir(parents=True) + app = install / "Scripture Archive.exe" + updater = install / "Scripture Archive Updater.exe" + app.write_bytes(b"installed") + updater.write_bytes(b"updater") + staging = tmp_path / "state" / "updates" + staging.mkdir(parents=True) + return updater, app, staging + + class ApplicationUpdateProcessTests(unittest.TestCase): def setUp(self) -> None: self.temp = tempfile.TemporaryDirectory() @@ -21,19 +33,8 @@ def setUp(self) -> None: def tearDown(self) -> None: self.temp.cleanup() - def _files(self) -> tuple[Path, Path, Path]: - install = self.tmp_path / "Program Files" / "Архів Писання" - install.mkdir(parents=True) - app = install / "Scripture Archive.exe" - updater = install / "Scripture Archive Updater.exe" - app.write_bytes(b"installed") - updater.write_bytes(b"updater") - staging = self.tmp_path / "state" / "updates" - staging.mkdir(parents=True) - return updater, app, staging - def test_build_plan_binds_sibling_packaged_updater_current_pid_and_fixed_argv(self) -> None: - updater, app, staging = self._files() + updater, app, staging = _files(self.tmp_path) plan = build_updater_process_plan( updater_executable=updater, installed_executable=app, @@ -58,7 +59,7 @@ def test_build_plan_binds_sibling_packaged_updater_current_pid_and_fixed_argv(se ) def test_build_plan_rejects_external_updater(self) -> None: - updater, app, staging = self._files() + updater, app, staging = _files(self.tmp_path) external = self.tmp_path / "outside-updater.exe" external.write_bytes(updater.read_bytes()) with self.assertRaisesRegex(UpdateProcessError, "packaged beside"): @@ -69,7 +70,7 @@ def test_build_plan_rejects_external_updater(self) -> None: ) def test_build_plan_rejects_current_app_as_updater(self) -> None: - _, app, staging = self._files() + _, app, staging = _files(self.tmp_path) with self.assertRaisesRegex(UpdateProcessError, "distinct"): build_updater_process_plan( updater_executable=app, @@ -78,7 +79,7 @@ def test_build_plan_rejects_current_app_as_updater(self) -> None: ) def test_build_plan_rejects_symlinked_updater_target_and_staging(self) -> None: - updater, app, staging = self._files() + updater, app, staging = _files(self.tmp_path) updater_link = updater.parent / "link-updater.exe" staging_link = self.tmp_path / "state-link" try: @@ -100,7 +101,7 @@ def test_build_plan_rejects_symlinked_updater_target_and_staging(self) -> None: ) def test_build_plan_rejects_foreign_parent_pid(self) -> None: - updater, app, staging = self._files() + updater, app, staging = _files(self.tmp_path) with self.assertRaisesRegex(UpdateProcessError, "current host process"): build_updater_process_plan( updater_executable=updater, @@ -110,7 +111,7 @@ def test_build_plan_rejects_foreign_parent_pid(self) -> None: ) def test_launch_is_shell_free_fixed_cwd_and_returns_child_pid(self) -> None: - updater, app, staging = self._files() + updater, app, staging = _files(self.tmp_path) plan = build_updater_process_plan( updater_executable=updater, installed_executable=app, @@ -135,7 +136,7 @@ def fake_popen(argv, **kwargs): self.assertEqual(seen["creationflags"], 0) def test_launch_wraps_process_failure(self) -> None: - updater, app, staging = self._files() + updater, app, staging = _files(self.tmp_path) plan = build_updater_process_plan( updater_executable=updater, installed_executable=app, @@ -149,7 +150,7 @@ def broken_popen(*args, **kwargs): launch_updater_process(plan, popen=broken_popen) def test_parser_accepts_only_fixed_host_contract(self) -> None: - updater, app, staging = self._files() + updater, app, staging = _files(self.tmp_path) plan = build_updater_process_plan( updater_executable=updater, installed_executable=app, @@ -161,16 +162,26 @@ def test_parser_accepts_only_fixed_host_contract(self) -> None: self.assertEqual(parsed_staging, staging.resolve()) def test_parser_rejects_noncanonical_or_extended_commands(self) -> None: - cases = [ + invalid_commands = [ (), ("--scripture-archive-apply",), ("--wrong", "--wait-pid", "1", "--installed-executable", "a", "--staging-root", "b"), ("--scripture-archive-apply", "--wait-pid", "01", "--installed-executable", "a", "--staging-root", "b"), - ("--scripture-archive-apply", "--wait-pid", "1", "--installed-executable", "a", "--staging-root", "b", "--extra"), + ( + "--scripture-archive-apply", + "--wait-pid", + "1", + "--installed-executable", + "a", + "--staging-root", + "b", + "--extra", + ), ] - for argv in cases: - with self.subTest(argv=argv), self.assertRaises(UpdateProcessError): - parse_trusted_updater_argv(argv) + for argv in invalid_commands: + with self.subTest(argv=argv): + with self.assertRaises(UpdateProcessError): + parse_trusted_updater_argv(argv) if __name__ == "__main__": diff --git a/runtime_engine/tests/test_application_update_runner.py b/runtime_engine/tests/test_application_update_runner.py index fef0f8101..87a7551eb 100644 --- a/runtime_engine/tests/test_application_update_runner.py +++ b/runtime_engine/tests/test_application_update_runner.py @@ -15,6 +15,22 @@ from scripture_archive_runtime.application_update_updater import UpdateApplyResult +def _plan(tmp_path: Path): + install = tmp_path / "Program Files" / "Архів Писання" + install.mkdir(parents=True) + app = install / "Scripture Archive.exe" + updater = install / "Scripture Archive Updater.exe" + app.write_bytes(b"installed") + updater.write_bytes(b"updater") + staging = tmp_path / "state" / "updates" + staging.mkdir(parents=True) + return build_updater_process_plan( + updater_executable=updater, + installed_executable=app, + staging_root=staging, + ) + + def _result(plan) -> UpdateApplyResult: return UpdateApplyResult( previous_sha256="1" * 64, @@ -43,23 +59,8 @@ def setUp(self) -> None: def tearDown(self) -> None: self.temp.cleanup() - def _plan(self): - install = self.tmp_path / "Program Files" / "Архів Писання" - install.mkdir(parents=True) - app = install / "Scripture Archive.exe" - updater = install / "Scripture Archive Updater.exe" - app.write_bytes(b"installed") - updater.write_bytes(b"updater") - staging = self.tmp_path / "state" / "updates" - staging.mkdir(parents=True) - return build_updater_process_plan( - updater_executable=updater, - installed_executable=app, - staging_root=staging, - ) - def test_runner_waits_applies_publishes_health_then_relaunches_exact_target(self) -> None: - plan = self._plan() + plan = _plan(self.tmp_path) events: list[object] = [] sentinel = _result(plan) @@ -118,7 +119,7 @@ def launch(target: Path) -> None: self.assertEqual(events[3], ("launch", plan.installed_executable)) def test_runner_health_publish_failure_rolls_back_and_disarms_before_no_launch(self) -> None: - plan = self._plan() + plan = _plan(self.tmp_path) sentinel = _result(plan) events: list[object] = [] @@ -159,7 +160,7 @@ def launch(target: Path) -> None: ) def test_runner_rolls_back_and_disarms_health_when_updated_process_cannot_start(self) -> None: - plan = self._plan() + plan = _plan(self.tmp_path) sentinel = _result(plan) events: list[object] = [] @@ -203,7 +204,7 @@ def discard(staging_root: Path) -> bool: ) def test_runner_surfaces_combined_relaunch_and_rollback_failure(self) -> None: - plan = self._plan() + plan = _plan(self.tmp_path) sentinel = _result(plan) with self.assertRaisesRegex( @@ -225,7 +226,7 @@ def test_runner_surfaces_combined_relaunch_and_rollback_failure(self) -> None: ) def test_runner_rolls_back_consumer_target_substitution_before_health_or_launch(self) -> None: - plan = self._plan() + plan = _plan(self.tmp_path) sentinel = UpdateApplyResult( previous_sha256="1" * 64, installed_sha256="2" * 64, @@ -266,7 +267,7 @@ def rollback(target: Path, *, expected_previous_sha256: str) -> str: ) def test_runner_never_consumes_when_parent_exit_cannot_be_proven(self) -> None: - plan = self._plan() + plan = _plan(self.tmp_path) consumed = False def blocked_wait(parent_pid: int) -> None: @@ -312,9 +313,10 @@ def consume(*args, **kwargs): self.assertFalse(consumed) def test_runner_rejects_invalid_trusted_current_version_before_wait(self) -> None: - for current_version in ["", "1", "01.0.0", "1.0", "1.0.0 "]: + invalid_versions = ["", "1", "01.0.0", "1.0", "1.0.0 "] + for current_version in invalid_versions: with self.subTest(current_version=current_version): - plan = self._plan() + plan = _plan(self.tmp_path / current_version.replace(".", "_").replace(" ", "_")) waited = False def wait_for_exit(parent_pid: int) -> None: @@ -329,14 +331,9 @@ def wait_for_exit(parent_pid: int) -> None: wait_for_exit=wait_for_exit, ) self.assertFalse(waited) - # Recreate the temporary fixture for the next subtest. - if current_version != "1.0.0 ": - self.temp.cleanup() - self.temp = tempfile.TemporaryDirectory() - self.tmp_path = Path(self.temp.name) def test_runner_requires_callable_security_dependencies_before_wait(self) -> None: - cases = [ + overrides = [ ({"verify_same_publisher": None}, "same-publisher verifier"), ({"wait_for_exit": None}, "parent-exit waiter"), ({"consume": None}, "apply consumer"), @@ -345,9 +342,9 @@ def test_runner_requires_callable_security_dependencies_before_wait(self) -> Non ({"publish_health": None}, "health receipt publisher"), ({"discard_health": None}, "health receipt discarder"), ] - for override, message in cases: - with self.subTest(override=override, message=message): - plan = self._plan() + for index, (override, message) in enumerate(overrides): + with self.subTest(message=message): + plan = _plan(self.tmp_path / f"dependency-{index}") kwargs = { "current_version": "1.0.0", "verify_same_publisher": lambda installed, staged: True, @@ -355,9 +352,6 @@ def test_runner_requires_callable_security_dependencies_before_wait(self) -> Non kwargs.update(override) with self.assertRaisesRegex(ApplicationUpdateError, message): execute_trusted_updater(plan.argv()[1:], **kwargs) # type: ignore[arg-type] - self.temp.cleanup() - self.temp = tempfile.TemporaryDirectory() - self.tmp_path = Path(self.temp.name) if __name__ == "__main__": diff --git a/runtime_engine/tests/test_application_update_updater.py b/runtime_engine/tests/test_application_update_updater.py index dff112d17..cdf97e150 100644 --- a/runtime_engine/tests/test_application_update_updater.py +++ b/runtime_engine/tests/test_application_update_updater.py @@ -1,6 +1,7 @@ from __future__ import annotations import hashlib +import os from pathlib import Path import tempfile import unittest @@ -9,6 +10,7 @@ from scripture_archive_runtime.application_update import ApplicationUpdateError from scripture_archive_runtime.application_update_pending import PendingApplicationUpdate from scripture_archive_runtime.application_update_updater import ( + _copy_exact, consume_apply_handoff, rollback_installed_update, ) @@ -49,6 +51,9 @@ def test_consume_handoff_replaces_exact_bytes_and_keeps_verified_rollback(self): ), patch( "scripture_archive_runtime.application_update_updater.staged_artifact_path", return_value=staged, + ), patch( + "scripture_archive_runtime.application_update_updater.discard_apply_handoff", + return_value=True, ): result = consume_apply_handoff( root, @@ -148,9 +153,7 @@ def test_consume_handoff_fails_closed_when_publisher_check_rejects(self): with tempfile.TemporaryDirectory() as tmp: root = Path(tmp) target = root / "ScriptureArchive.exe" - staged = root / "ScriptureArchive.new.exe" target.write_bytes(old) - staged.write_bytes(new) pending = self._pending(new) staged_named = root / "staged" / pending.artifact_name staged_named.parent.mkdir() @@ -334,6 +337,126 @@ def fail_post_publish_hash(path: Path) -> str: old, ) + def test_consume_handoff_rolls_back_when_authority_changes_after_publication(self): + old = b"old executable bytes" + new = b"new signed executable bytes" + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + target = root / "ScriptureArchive.exe" + staged = root / "staged" / "ScriptureArchive.exe" + staged.parent.mkdir() + target.write_bytes(old) + staged.write_bytes(new) + pending = self._pending(new) + inspections = [pending, pending, pending, None] + + with patch( + "scripture_archive_runtime.application_update_updater.inspect_apply_handoff", + side_effect=inspections, + ) as inspect, patch( + "scripture_archive_runtime.application_update_updater.staged_artifact_path", + return_value=staged, + ), patch( + "scripture_archive_runtime.application_update_updater.discard_apply_handoff", + return_value=True, + ) as discard: + with self.assertRaisesRegex( + ApplicationUpdateError, + "failed after publication; rollback restored", + ): + consume_apply_handoff( + root, + current_version="1.0.0", + install_target=target, + verify_same_publisher=lambda _current, _candidate: True, + ) + + self.assertEqual(inspect.call_count, 4) + discard.assert_not_called() + self.assertEqual(target.read_bytes(), old) + self.assertEqual( + (root / "ScriptureArchive.exe.scripture-archive.rollback").read_bytes(), + old, + ) + + def test_consume_handoff_rolls_back_if_disarm_reports_missing_authority(self): + old = b"old executable bytes" + new = b"new signed executable bytes" + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + target = root / "ScriptureArchive.exe" + staged = root / "staged" / "ScriptureArchive.exe" + staged.parent.mkdir() + target.write_bytes(old) + staged.write_bytes(new) + pending = self._pending(new) + + with patch( + "scripture_archive_runtime.application_update_updater.inspect_apply_handoff", + return_value=pending, + ), patch( + "scripture_archive_runtime.application_update_updater.staged_artifact_path", + return_value=staged, + ), patch( + "scripture_archive_runtime.application_update_updater.discard_apply_handoff", + return_value=False, + ): + with self.assertRaisesRegex( + ApplicationUpdateError, + "failed after publication; rollback restored", + ): + consume_apply_handoff( + root, + current_version="1.0.0", + install_target=target, + verify_same_publisher=lambda _current, _candidate: True, + ) + + self.assertEqual(target.read_bytes(), old) + + def test_copy_exact_source_open_failure_never_creates_destination(self): + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + source = root / "source.exe" + destination = root / "destination.exe" + + with patch.object( + Path, + "open", + side_effect=OSError("forced source-open failure"), + ), patch( + "scripture_archive_runtime.application_update_updater.os.open", + ) as destination_open: + with self.assertRaisesRegex( + ApplicationUpdateError, + "update source could not be opened", + ): + _copy_exact(source, destination) + + destination_open.assert_not_called() + self.assertFalse(destination.exists()) + + def test_copy_exact_fdopen_failure_closes_descriptor_and_removes_destination(self): + source_bytes = b"source bytes" + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + source = root / "source.exe" + destination = root / "destination.exe" + source.write_bytes(source_bytes) + + with patch( + "scripture_archive_runtime.application_update_updater.os.fdopen", + side_effect=OSError("forced fdopen failure"), + ), patch( + "scripture_archive_runtime.application_update_updater.os.close", + wraps=os.close, + ) as close_descriptor: + with self.assertRaisesRegex(OSError, "forced fdopen failure"): + _copy_exact(source, destination) + + close_descriptor.assert_called_once() + self.assertFalse(destination.exists()) + def test_consume_handoff_disarms_apply_authority_after_success(self): old = b"old executable bytes" new = b"new signed executable bytes"