diff --git a/lanes/dev1/repair_overlay/frontend/application-update.js b/lanes/dev1/repair_overlay/frontend/application-update.js index 42e0abd85..2196936d4 100644 --- a/lanes/dev1/repair_overlay/frontend/application-update.js +++ b/lanes/dev1/repair_overlay/frontend/application-update.js @@ -78,12 +78,19 @@ async function invokeNativeUpdate(command){ } function setBusy(busy){ + const view=$('application-update-view'); + if(view)view.setAttribute('aria-busy',busy?'true':'false'); for(const id of ['application-update-select','application-update-stage']){ const button=$(id); if(button)button.disabled=busy; } } +function reportFailure(error,message){ + console.error('application update operation failed',error); + announce(message); +} + async function selectAndVerify(command=VERIFY_UPDATE_COMMAND){ const staging=command===STAGE_UPDATE_COMMAND; setBusy(true); @@ -109,7 +116,12 @@ async function selectAndVerify(command=VERIFY_UPDATE_COMMAND){ } }catch(error){ clearDetails(); - announce(`${staging?'Оновлення не підготовлено':'Оновлення не перевірено'}: ${error?.message||'невідома помилка'}`); + reportFailure( + error, + staging + ?'Оновлення не підготовлено. Пакет не встановлено й файли програми не змінено.' + :'Оновлення не перевірено. Виберіть локальний manifest і пакет та повторіть перевірку.' + ); }finally{ setBusy(false); } @@ -153,3 +165,4 @@ function mount(){ mount(); void import('./diagnostics-ui.js'); +void import('./pending-update.js'); diff --git a/lanes/dev1/repair_overlay/frontend/pending-update.js b/lanes/dev1/repair_overlay/frontend/pending-update.js new file mode 100644 index 000000000..9067cf23e --- /dev/null +++ b/lanes/dev1/repair_overlay/frontend/pending-update.js @@ -0,0 +1,178 @@ +const API_VERSION='scripture.transport.v1'; +const HEALTH_COMMAND='application_update.commit_post_restart_health'; +const STATUS_COMMAND='application_update.pending_status'; +const PREPARE_APPLY_COMMAND='application_update.prepare_apply'; +const APPLY_AND_RESTART_COMMAND='application_update.apply_and_restart'; +const CANCEL_COMMAND='application_update.cancel_pending'; +const $=id=>document.getElementById(id); +let sequence=0; +let startupCheckStarted=false; + +function setStatus(message,{global=true}={}){ + if(global){ + const live=$('global-status'); + if(live){live.textContent='';requestAnimationFrame(()=>{live.textContent=message})} + } + const local=$('pending-update-status'); + if(local)local.textContent=message; +} + +function element(tag,text){ + const node=document.createElement(tag); + if(text!==undefined)node.textContent=text; + return node; +} + +async function invoke(command){ + const invokeNative=window.pywebview?.api?.invoke; + if(typeof invokeNative!=='function')throw new Error('Ця дія доступна лише у packaged Windows application.'); + const response=await invokeNative({api_version:API_VERSION,request_id:`pending-${Date.now()}-${++sequence}`,command,payload:{}}); + if(!response?.ok)throw new Error(response?.error?.message||'Операція завершилась помилкою.'); + return response.data??{}; +} + +function setBusy(busy){ + const section=$('pending-update-recovery'); + if(section)section.setAttribute('aria-busy',busy?'true':'false'); + for(const id of ['pending-update-check','pending-update-prepare-apply','pending-update-apply-restart','pending-update-cancel']){ + const button=$(id);if(button)button.disabled=busy||(id==='pending-update-apply-restart'&&button.dataset.ready!=='true'); + } +} + +function reportFailure(context,error,message){ + console.error(context,error); + setStatus(message); +} + +function setApplyReady(ready){ + const button=$('pending-update-apply-restart'); + if(!button)return; + button.dataset.ready=ready?'true':'false'; + button.disabled=!ready; +} + +function clearDetails(){$('pending-update-details')?.replaceChildren()} + +function renderPending(data){ + const host=$('pending-update-details'); + if(!host||data.pending!==true)return; + host.replaceChildren(); + const rows=[ + ['Статус',data.status==='apply_ready'?'Намір встановлення підготовлено; можна встановити й перезапустити':'Підготовлено, але не встановлено'], + ['Продукт',data.product_id],['Платформа',data.target_platform], + ['Поточна версія',data.current_version],['Цільова версія',data.target_version], + ['Source head',data.source_head],['Файл пакета',data.artifact_name], + ['Розмір',Number.isFinite(Number(data.artifact_size))?`${data.artifact_size} байт`:'—'], + ['SHA-256',data.artifact_sha256],['Автентичність','Same-publisher Authenticode повторно підтверджено'] + ]; + for(const [label,value] of rows){host.append(element('dt',label),element('dd',value??'—'))} +} + +async function checkPending({startup=false}={}){ + setBusy(true);clearDetails(); + if(!startup)setStatus('Повторно перевіряю підготовлене оновлення.'); + try{ + const data=await invoke(STATUS_COMMAND); + if(data.pending===true&&(data.status==='staged'||data.status==='apply_ready')){ + renderPending(data); + const ready=data.status==='apply_ready'; + setApplyReady(ready); + setStatus(ready + ?`Захищений намір встановлення ${data.artifact_name??'пакета'} → ${data.target_version??'цільова версія'} відновлено й повторно перевірено. Можна встановити та перезапустити програму.` + :`Підготовлене оновлення ${data.artifact_name??'пакет'} → ${data.target_version??'цільова версія'} повторно перевірено. Воно ще не встановлене.`); + }else if(data.pending===false&&data.status==='none'){ + setApplyReady(false); + setStatus('Підготовленого оновлення немає.',{global:!startup}); + }else throw new Error('Отримано неочікуваний стан.'); + }catch(error){ + clearDetails();setApplyReady(false); + reportFailure('pending update status failed',error,'Підготовлене оновлення не вдалося безпечно перевірити. Спробуйте перевірити його ще раз.'); + }finally{setBusy(false)} +} + +async function prepareApply(){ + setBusy(true);setApplyReady(false);setStatus('Повторно перевіряю пакет і готую захищений намір встановлення.'); + try{ + const data=await invoke(PREPARE_APPLY_COMMAND); + if(data.pending===true&&data.status==='apply_ready'&&data.installation_performed===false){ + renderPending(data);setApplyReady(true); + setStatus(`Намір встановлення ${data.artifact_name??'пакета'} → ${data.target_version??'цільова версія'} підготовлено. Файли програми ще не замінювались. Окрема кнопка «Встановити й перезапустити» запускає підписаний native updater.`); + }else throw new Error('Підготовку apply handoff не підтверджено.'); + }catch(error){ + setApplyReady(false); + reportFailure('prepare update apply failed',error,'Не вдалося безпечно підготувати встановлення. Файли програми не змінено.'); + } + finally{setBusy(false)} +} + +async function applyAndRestart(){ + setBusy(true); + setStatus('Запускаю перевірений native updater. Програма закриється; updater дочекається завершення цього процесу, встановить точні повторно перевірені байти й запустить програму знову.'); + try{ + const data=await invoke(APPLY_AND_RESTART_COMMAND); + if(data.pending===true&&data.status==='updater_started'&&data.updater_process_started===true&&data.restart_requested===true){ + setStatus('Native updater запущено. Завершую поточну програму для безпечного встановлення та перезапуску.'); + }else throw new Error('Запуск native updater не підтверджено.'); + }catch(error){ + reportFailure('start native updater failed',error,'Не вдалося безпечно запустити встановлення. Поточна версія програми залишається активною.'); + setBusy(false); + } +} + +async function cancelPending(){ + setBusy(true);clearDetails();setApplyReady(false);setStatus('Скасовую підготовлений стан оновлення.'); + try{ + const data=await invoke(CANCEL_COMMAND); + if(data.pending===false&&(data.status==='cancelled'||data.status==='none')){ + setStatus(data.status==='cancelled'?'Підготовлене оновлення та його apply-наміри скасовано. Інсталяція не виконувалась.':'Підготовленого оновлення вже немає.'); + }else throw new Error('Скасування не підтверджено.'); + }catch(error){ + reportFailure('cancel pending update failed',error,'Не вдалося безпечно скасувати підготовлене оновлення. Повторіть перевірку стану перед наступною дією.'); + } + finally{setBusy(false)} +} + +async function commitPostRestartHealth(){ + setBusy(true); + setStatus('Перевіряю стан після перезапуску та збережений rollback.'); + try{ + const data=await invoke(HEALTH_COMMAND); + if(data.status==='healthy'&&data.health_committed===true&&data.rollback_cleanup_performed===true){ + setStatus(`Оновлена версія ${data.target_version??'програми'} успішно запустила native bridge. Rollback попередньої версії ${data.previous_version??''} безпечно завершено.`); + }else if(data.status!=='none'||data.health_committed!==false){ + throw new Error('Отримано неочікуваний post-update health state.'); + } + await checkPending({startup:true}); + }catch(error){ + clearDetails();setApplyReady(false);setBusy(false); + reportFailure('post-update health check failed',error,'Перевірку стану після перезапуску не підтверджено. Rollback recovery збережено; автоматичне очищення не виконано.'); + } +} + +function startStartupCheck(){ + if(startupCheckStarted)return; + startupCheckStarted=true; + void commitPostRestartHealth(); +} + +function mount(){ + const view=$('application-update-view');if(!view||$('pending-update-recovery'))return; + const section=element('section');section.id='pending-update-recovery';section.className='surface';section.setAttribute('aria-labelledby','pending-update-heading'); + const heading=element('h3','Підготовлене оновлення після перезапуску');heading.id='pending-update-heading'; + const help=element('p','Після запуску програма спочатку перевіряє post-update health receipt: точну поточну версію, встановлені байти та збережений rollback. Лише після успішної перевірки старий rollback і stale pending authority прибираються. Потім програма перевіряє звичайний pending state. «Підготувати встановлення» створює durable apply handoff, а «Встановити й перезапустити» запускає підписаний native updater. Browser не передає шляхів, PID або командного рядка updater.'); + const actions=element('div');actions.className='action-row'; + const check=element('button','Перевірити підготовлене оновлення');check.type='button';check.id='pending-update-check'; + const prepare=element('button','Підготувати встановлення');prepare.type='button';prepare.id='pending-update-prepare-apply'; + const apply=element('button','Встановити й перезапустити');apply.type='button';apply.id='pending-update-apply-restart';apply.dataset.ready='false';apply.disabled=true; + const cancel=element('button','Скасувати підготовлене оновлення');cancel.type='button';cancel.id='pending-update-cancel'; + actions.append(check,prepare,apply,cancel); + const status=element('p','Очікую готовності native host для post-update health і pending перевірки.');status.id='pending-update-status';status.className='notice info';status.setAttribute('role','status');status.setAttribute('aria-live','polite');status.setAttribute('aria-atomic','true'); + const details=element('dl');details.id='pending-update-details';details.className='details-list';details.setAttribute('aria-label','Повторно перевірені метадані підготовленого оновлення'); + section.append(heading,help,actions,status,details);view.append(section); + check.addEventListener('click',()=>checkPending());prepare.addEventListener('click',prepareApply);apply.addEventListener('click',applyAndRestart);cancel.addEventListener('click',cancelPending); + + window.addEventListener('pywebviewready',startStartupCheck,{once:true}); + if(typeof window.pywebview?.api?.invoke==='function')queueMicrotask(startStartupCheck); +} + +mount(); diff --git a/lanes/dev1/repair_overlay/packaging/build_windows.ps1 b/lanes/dev1/repair_overlay/packaging/build_windows.ps1 index 44074d7ad..af756fee0 100644 --- a/lanes/dev1/repair_overlay/packaging/build_windows.ps1 +++ b/lanes/dev1/repair_overlay/packaging/build_windows.ps1 @@ -79,9 +79,13 @@ Assert-NativeSuccess "packaged payload manifest generation" $Sep = ";" $Name = "ScriptureArchive-R06-DEV01" +$UpdaterName = "$Name-Updater" $Out = Join-Path $Dist "$Name.exe" -if (Test-Path -LiteralPath $Out) { - Remove-Item -LiteralPath $Out -Force +$UpdaterOut = Join-Path $Dist "$UpdaterName.exe" +foreach ($artifact in @($Out, $UpdaterOut)) { + if (Test-Path -LiteralPath $artifact) { + Remove-Item -LiteralPath $artifact -Force + } } try { & (Join-Path $Venv "Scripts\pyinstaller.exe") --noconfirm --clean --onefile --windowed ` @@ -99,7 +103,14 @@ try { --paths $PlatformRoot --paths $Repo ` --distpath $Dist --workpath $Work --specpath $Spec ` (Join-Path $PlatformRoot "run_windows.py") - Assert-NativeSuccess "PyInstaller build" + Assert-NativeSuccess "PyInstaller application build" + + & (Join-Path $Venv "Scripts\pyinstaller.exe") --noconfirm --clean --onefile --windowed ` + --name $UpdaterName ` + --paths $PlatformRoot --paths $Repo ` + --distpath $Dist --workpath $Work --specpath $Spec ` + (Join-Path $PlatformRoot "scripture_archive_platform\desktop_host\updater_main.py") + Assert-NativeSuccess "PyInstaller updater build" } finally { Remove-Item -LiteralPath $BuildIdentityDir -Recurse -Force -ErrorAction SilentlyContinue } @@ -107,6 +118,9 @@ try { if (-not (Test-Path -LiteralPath $Out -PathType Leaf)) { throw "Expected executable not produced: $Out" } +if (-not (Test-Path -LiteralPath $UpdaterOut -PathType Leaf)) { + throw "Expected updater executable not produced: $UpdaterOut" +} $PayloadReadback = Join-Path $Dist "packaged_payload_fidelity.json" & $Python $FidelityTool verify ` @@ -117,6 +131,8 @@ Assert-NativeSuccess "embedded packaged payload fidelity verification" $hash = (Get-FileHash -Algorithm SHA256 $Out).Hash.ToLowerInvariant() $size = (Get-Item $Out).Length +$updaterHash = (Get-FileHash -Algorithm SHA256 $UpdaterOut).Hash.ToLowerInvariant() +$updaterSize = (Get-Item $UpdaterOut).Length $payloadEvidenceHash = (Get-FileHash -Algorithm SHA256 $PayloadReadback).Hash.ToLowerInvariant() $pythonVersion = (& $Python --version 2>&1 | Out-String).Trim() Assert-NativeSuccess "Python version query" @@ -127,6 +143,10 @@ $manifest = [ordered]@{ artifact_path = $Out size_bytes = $size sha256 = $hash + updater_artifact_name = (Split-Path -Leaf $UpdaterOut) + updater_artifact_path = $UpdaterOut + updater_size_bytes = $updaterSize + updater_sha256 = $updaterHash built_utc = (Get-Date).ToUniversalTime().ToString("o") git_sha = $actualGitSha github_event_sha = $env:GITHUB_SHA @@ -138,19 +158,20 @@ $manifest = [ordered]@{ packaged_payload_fidelity_file = (Split-Path -Leaf $PayloadReadback) packaged_payload_fidelity_sha256 = $payloadEvidenceHash proof_scope = @( - "PyInstaller build completed", - "artifact size/hash readback verified", + "PyInstaller application and standalone updater builds completed", + "application and updater artifact size/hash readback verified", "embedded frontend/campaign/build-identity bytes verified against exact staged manifest", "Git-tracked embedded frontend overlay/campaign bytes verified against exact checkout Git blob IDs", "WebView2 runtime presence probed before build", "packaged diagnostics build identity bound to exact checkout SHA" ) not_proven = @( + "production Authenticode signing identity is configured", "Python module bytecode identity inside PYZ", "human NVDA acceptance", "full application functional acceptance", "visual correctness", - "recovery execution" + "post-restart health commit" ) } $ManifestPath = Join-Path $Dist "build_manifest.json" @@ -158,11 +179,32 @@ $manifest | ConvertTo-Json -Depth 6 | Set-Content -Encoding utf8 $ManifestPath "SHA256=$hash" | Set-Content -Encoding utf8 (Join-Path $Dist "$Name.sha256.txt") "SIZE=$size" | Add-Content -Encoding utf8 (Join-Path $Dist "$Name.sha256.txt") +"SHA256=$updaterHash" | Set-Content -Encoding utf8 (Join-Path $Dist "$UpdaterName.sha256.txt") +"SIZE=$updaterSize" | Add-Content -Encoding utf8 (Join-Path $Dist "$UpdaterName.sha256.txt") & $Python (Join-Path $PSScriptRoot "windows_release.py") verify-artifact ` --artifact $Out ` --manifest $ManifestPath ` --output (Join-Path $Dist "artifact_readback.json") -Assert-NativeSuccess "artifact verification" +Assert-NativeSuccess "application artifact verification" + +$UpdaterManifestPath = Join-Path $Dist "updater_build_manifest.json" +$updaterManifest = [ordered]@{ + schema_version = 1 + artifact_name = (Split-Path -Leaf $UpdaterOut) + artifact_path = $UpdaterOut + size_bytes = $updaterSize + sha256 = $updaterHash + git_sha = $actualGitSha + application_version_authority = "scripture_archive_platform.desktop_host.version.CURRENT_APPLICATION_VERSION" + authenticode_authority = "scripture_archive_platform.desktop_host.authenticode.verify_same_publisher_authenticode" +} +$updaterManifest | ConvertTo-Json -Depth 4 | Set-Content -Encoding utf8 $UpdaterManifestPath +& $Python (Join-Path $PSScriptRoot "windows_release.py") verify-artifact ` + --artifact $UpdaterOut ` + --manifest $UpdaterManifestPath ` + --output (Join-Path $Dist "updater_artifact_readback.json") +Assert-NativeSuccess "updater artifact verification" Write-Output "Built $Out ($size bytes) SHA256=$hash" +Write-Output "Built $UpdaterOut ($updaterSize bytes) SHA256=$updaterHash" diff --git a/lanes/dev1/repair_overlay/packaging/run_windows_release_gate.ps1 b/lanes/dev1/repair_overlay/packaging/run_windows_release_gate.ps1 index 76b994a2f..b2fde64da 100644 --- a/lanes/dev1/repair_overlay/packaging/run_windows_release_gate.ps1 +++ b/lanes/dev1/repair_overlay/packaging/run_windows_release_gate.ps1 @@ -11,10 +11,14 @@ $OverlayTests = Join-Path $Repo "lanes\dev1\repair_overlay\tests" $Dist = Join-Path $PlatformRoot "dist" $Name = "ScriptureArchive-R06-DEV01" $Exe = Join-Path $Dist "$Name.exe" +$UpdaterExe = Join-Path $Dist "$Name-Updater.exe" $BuildManifest = Join-Path $Dist "build_manifest.json" +$UpdaterBuildManifest = Join-Path $Dist "updater_build_manifest.json" $Diagnostics = Join-Path $Dist "windows_release_diagnostics.json" $WebView2Probe = Join-Path $Dist "webview2_host_probe.json" $StartupProbe = Join-Path $Dist "packaged_startup_probe.json" +$ArtifactReadback = Join-Path $Dist "artifact_readback.json" +$UpdaterArtifactReadback = Join-Path $Dist "updater_artifact_readback.json" if (-not $OutputJson) { $OutputJson = Join-Path $Dist "release_gate.json" } $result = [ordered]@{ @@ -31,6 +35,7 @@ $result = [ordered]@{ tools_smoke = $false build = $false artifact_readback = $false + updater_artifact_readback = $false webview2_detected = $false webview2_host_probe = $false process_liveness = $false @@ -38,8 +43,13 @@ $result = [ordered]@{ running_without_admin = $false artifact_sha256 = $null artifact_size_bytes = $null + updater_artifact_sha256 = $null + updater_artifact_size_bytes = $null status = "RUNNING" not_proven = @( + "production Authenticode signing identity/private key", + "host launch/shutdown handoff to standalone updater", + "post-restart health commit/rollback cleanup", "human NVDA acceptance", "complete functional WebView UI acceptance", "packaged application's own WebView2 content-ready signal", @@ -105,19 +115,54 @@ try { } & (Join-Path $PSScriptRoot "build_windows.ps1") - if (-not (Test-Path $Exe) -or -not (Test-Path $BuildManifest) -or -not (Test-Path $Diagnostics)) { - throw "Build did not produce the complete expected evidence set" + if ( + -not (Test-Path -LiteralPath $Exe -PathType Leaf) -or + -not (Test-Path -LiteralPath $UpdaterExe -PathType Leaf) -or + -not (Test-Path -LiteralPath $BuildManifest -PathType Leaf) -or + -not (Test-Path -LiteralPath $UpdaterBuildManifest -PathType Leaf) -or + -not (Test-Path -LiteralPath $ArtifactReadback -PathType Leaf) -or + -not (Test-Path -LiteralPath $UpdaterArtifactReadback -PathType Leaf) -or + -not (Test-Path -LiteralPath $Diagnostics -PathType Leaf) + ) { + throw "Build did not produce the complete application + updater evidence set" } $result.build = $true $build = Get-Content -Raw -Encoding utf8 $BuildManifest | ConvertFrom-Json + $updaterBuild = Get-Content -Raw -Encoding utf8 $UpdaterBuildManifest | ConvertFrom-Json $diag = Get-Content -Raw -Encoding utf8 $Diagnostics | ConvertFrom-Json - $readbackPath = Join-Path $Dist "artifact_readback.json" - $readback = Get-Content -Raw -Encoding utf8 $readbackPath | ConvertFrom-Json - if (-not $readback.ok) { throw "Artifact hash/size readback did not pass" } + $readback = Get-Content -Raw -Encoding utf8 $ArtifactReadback | ConvertFrom-Json + $updaterReadback = Get-Content -Raw -Encoding utf8 $UpdaterArtifactReadback | ConvertFrom-Json + if (-not $readback.ok) { throw "Application artifact hash/size readback did not pass" } + if (-not $updaterReadback.ok) { throw "Updater artifact hash/size readback did not pass" } + + $actualUpdaterHash = (Get-FileHash -LiteralPath $UpdaterExe -Algorithm SHA256).Hash.ToLowerInvariant() + $actualUpdaterSize = (Get-Item -LiteralPath $UpdaterExe).Length + if ($build.updater_artifact_name -ne (Split-Path -Leaf $UpdaterExe)) { + throw "Main build manifest updater artifact name does not match packaged updater" + } + if ([string]$build.updater_sha256 -ne [string]$updaterBuild.sha256) { + throw "Updater SHA differs between build manifests" + } + if ([long]$build.updater_size_bytes -ne [long]$updaterBuild.size_bytes) { + throw "Updater size differs between build manifests" + } + if ([string]$updaterBuild.sha256 -ne $actualUpdaterHash) { + throw "Updater SHA manifest does not match exact packaged updater bytes" + } + if ([long]$updaterBuild.size_bytes -ne [long]$actualUpdaterSize) { + throw "Updater size manifest does not match exact packaged updater bytes" + } + if ([string]$updaterReadback.actual_sha256 -ne $actualUpdaterHash -or [long]$updaterReadback.actual_size_bytes -ne [long]$actualUpdaterSize) { + throw "Updater artifact readback evidence is detached from exact packaged updater bytes" + } + $result.artifact_readback = $true + $result.updater_artifact_readback = $true $result.artifact_sha256 = $build.sha256 $result.artifact_size_bytes = $build.size_bytes + $result.updater_artifact_sha256 = $actualUpdaterHash + $result.updater_artifact_size_bytes = $actualUpdaterSize $result.webview2_detected = @($diag.webview2_candidates).Count -gt 0 $result.per_user_state_writable = [bool]$diag.state_write_probe.writable $result.running_without_admin = ($diag.is_admin -eq $false) diff --git a/lanes/dev1/repair_overlay/scripture_archive_platform/desktop_host/main.py b/lanes/dev1/repair_overlay/scripture_archive_platform/desktop_host/main.py index 334870a1b..ccaa3a57d 100644 --- a/lanes/dev1/repair_overlay/scripture_archive_platform/desktop_host/main.py +++ b/lanes/dev1/repair_overlay/scripture_archive_platform/desktop_host/main.py @@ -7,14 +7,14 @@ from scripture_archive_platform.application.speech_application import build_default_application from scripture_archive_platform.desktop_host.bridge import DesktopBridge from scripture_archive_platform.desktop_host.diagnostics import NativeDiagnosticsLayer +from scripture_archive_platform.desktop_host.pending_update import NativePendingUpdateLayer +from scripture_archive_platform.desktop_host.post_update_health import NativePostUpdateHealthLayer from scripture_archive_platform.desktop_host.update_application import ( NativeApplicationUpdateLayer, NativeUpdateFileSelector, ) - -# Semantic compatibility version for the current R06-3DEV-A packaged lineage. -# It is deliberately host-owned rather than supplied by an update manifest/web payload. -CURRENT_APPLICATION_VERSION = "0.6.0-r06.3dev.a" +from scripture_archive_platform.desktop_host.updater_launch import launch_packaged_updater +from scripture_archive_platform.desktop_host.version import CURRENT_APPLICATION_VERSION def _runtime_root() -> Path: @@ -52,12 +52,29 @@ def main() -> int: selector = NativeUpdateFileSelector(webview) platform_app = build_default_application(root) + staging_root = Path(platform_app.store.root) / "application-updates" app = NativeApplicationUpdateLayer( platform_app, root, selector, current_version=CURRENT_APPLICATION_VERSION, - staging_root=Path(platform_app.store.root) / "application-updates", + staging_root=staging_root, + ) + # This layer owns one process-local RLock for the complete update command family, + # so verify/stage/status/cancel/execute cannot race shared durable state. + pending_layer = NativePendingUpdateLayer( + app, + root, + staging_root, + current_version=CURRENT_APPLICATION_VERSION, + ) + # Health commit is intentionally outside pending recovery: after a successful + # updater relaunch the pending journal still carries the previous version and must + # be disarmed only after the new packaged native/frontend bridge is alive. + app = NativePostUpdateHealthLayer( + pending_layer, + staging_root, + current_version=CURRENT_APPLICATION_VERSION, ) app = NativeDiagnosticsLayer( app, @@ -80,6 +97,10 @@ def main() -> int: text_select=True, ) selector.bind_window(window) + pending_layer.bind_apply_execution( + lambda: launch_packaged_updater(staging_root), + window.destroy, + ) logging.info("Starting EdgeChromium WebView; frontend=%s log=%s", front, log_path) webview.start(gui="edgechromium", debug=False, private_mode=True) return 0 diff --git a/lanes/dev1/repair_overlay/scripture_archive_platform/desktop_host/pending_update.py b/lanes/dev1/repair_overlay/scripture_archive_platform/desktop_host/pending_update.py new file mode 100644 index 000000000..7086bd5cf --- /dev/null +++ b/lanes/dev1/repair_overlay/scripture_archive_platform/desktop_host/pending_update.py @@ -0,0 +1,300 @@ +from __future__ import annotations + +import sys +import threading +from pathlib import Path +from typing import Any, Callable + +from scripture_archive_platform.desktop_host.authenticode import ( + verify_same_publisher_authenticode, +) +from scripture_archive_platform.transport.contracts import ( + error_response, + ok_response, + validate_request_shape, +) + + +PENDING_UPDATE_STATUS_COMMAND = "application_update.pending_status" +PREPARE_APPLY_COMMAND = "application_update.prepare_apply" +APPLY_AND_RESTART_COMMAND = "application_update.apply_and_restart" +CANCEL_PENDING_UPDATE_COMMAND = "application_update.cancel_pending" +_PENDING_COMMANDS = frozenset( + { + PENDING_UPDATE_STATUS_COMMAND, + PREPARE_APPLY_COMMAND, + APPLY_AND_RESTART_COMMAND, + CANCEL_PENDING_UPDATE_COMMAND, + } +) +_UPDATE_COMMAND_FAMILY = frozenset( + { + "application_update.select_verify", + "application_update.select_verify_stage", + PENDING_UPDATE_STATUS_COMMAND, + PREPARE_APPLY_COMMAND, + APPLY_AND_RESTART_COMMAND, + CANCEL_PENDING_UPDATE_COMMAND, + } +) + + +class NativePendingUpdateLayer: + """Expose serialized fixed-path staged-update recovery and apply execution. + + The outer packaged-host lock serializes the complete application-update command + family so staging, status, prepare-apply, execution and cancellation cannot + publish contradictory durable state. Execution remains two-step: the browser may + request only an empty-payload action after a matching durable apply handoff exists; + all paths, process identity, updater identity and shutdown behavior stay native. + """ + + def __init__( + self, + app: Any, + repo_root: Path, + staging_root: Path, + *, + current_version: str, + authenticity_verifier: Callable[[Path], bool] | None = None, + apply_executor: Callable[[], int] | None = None, + shutdown_request: Callable[[], None] | None = None, + ) -> None: + self._app = app + self._repo_root = Path(repo_root).resolve() + self._staging_root = Path(staging_root) + self._current_version = current_version + self._authenticity_verifier = ( + authenticity_verifier + if authenticity_verifier is not None + else self._default_authenticity_verifier + ) + self._apply_executor = apply_executor + self._shutdown_request = shutdown_request + self._operation_lock = threading.RLock() + + def bind_apply_execution( + self, + apply_executor: Callable[[], int], + shutdown_request: Callable[[], None], + ) -> None: + """Bind host-owned launch/shutdown callbacks after the native window exists.""" + + if not callable(apply_executor): + raise ValueError("apply executor must be callable") + if not callable(shutdown_request): + raise ValueError("shutdown request must be callable") + with self._operation_lock: + self._apply_executor = apply_executor + self._shutdown_request = shutdown_request + + def handle(self, request: Any) -> dict[str, Any]: + if not isinstance(request, dict): + return self._app.handle(request) + command_name = request.get("command") + if command_name not in _UPDATE_COMMAND_FAMILY: + return self._app.handle(request) + with self._operation_lock: + if command_name not in _PENDING_COMMANDS: + return self._app.handle(request) + return self._handle_pending(request) + + def _handle_pending(self, request: dict[str, Any]) -> dict[str, Any]: + rid = str(request.get("request_id", "invalid")) + try: + rid, command, payload = validate_request_shape(request) + if command not in _PENDING_COMMANDS or payload: + raise ValueError("pending update recovery requires an empty payload") + except ValueError as exc: + return error_response(rid, "VALIDATION_ERROR", str(exc)) + + try: + inspect_pending_update, staged_artifact_path, discard_pending_update = ( + self._load_pending_core() + ) + prepare_apply_handoff, inspect_apply_handoff, discard_apply_handoff = ( + self._load_apply_core() + ) + + if command == CANCEL_PENDING_UPDATE_COMMAND: + apply_removed = discard_apply_handoff(self._staging_root) + removed = discard_pending_update(self._staging_root) + return ok_response( + rid, + { + "pending": False, + "status": "cancelled" if removed or apply_removed else "none", + "apply_handoff_removed": apply_removed, + "staged_bytes_removed": False, + "installation_performed": False, + }, + ) + + pending = inspect_pending_update( + self._staging_root, + current_version=self._current_version, + ) + if pending is None: + return ok_response( + rid, + { + "pending": False, + "status": "none", + "installation_performed": False, + }, + ) + + candidate = staged_artifact_path(self._staging_root, pending) + try: + authenticity_verified = bool(self._authenticity_verifier(candidate)) + except Exception: + authenticity_verified = False + if not authenticity_verified: + return error_response( + rid, + "UPDATE_PENDING_AUTHENTICITY_INVALID", + "Pending update no longer has valid same-publisher Authenticode.", + ) + + pending = inspect_pending_update( + self._staging_root, + current_version=self._current_version, + ) + + if command == PREPARE_APPLY_COMMAND: + rebound = prepare_apply_handoff( + self._staging_root, + current_version=self._current_version, + ) + if rebound != pending: + return error_response( + rid, + "UPDATE_APPLY_HANDOFF_INVALID", + "Apply handoff did not remain bound to the verified pending update.", + ) + return self._pending_response( + rid, + rebound, + status="apply_ready", + restart_requested=False, + ) + + if command == APPLY_AND_RESTART_COMMAND: + if not callable(self._apply_executor) or not callable(self._shutdown_request): + return error_response( + rid, + "UPDATE_EXECUTION_UNAVAILABLE", + "Packaged updater execution is unavailable in this host.", + ) + handoff = inspect_apply_handoff( + self._staging_root, + current_version=self._current_version, + ) + if handoff is None or handoff != pending: + return error_response( + rid, + "UPDATE_APPLY_HANDOFF_REQUIRED", + "A current verified apply handoff is required before restart.", + ) + updater_pid = self._apply_executor() + if not isinstance(updater_pid, int) or isinstance(updater_pid, bool) or updater_pid <= 0: + raise ValueError("packaged updater launch did not return a valid process id") + self._shutdown_request() + response = self._pending_response( + rid, + handoff, + status="updater_started", + restart_requested=True, + ) + response["data"]["updater_process_started"] = True + return response + + handoff = inspect_apply_handoff( + self._staging_root, + current_version=self._current_version, + ) + if handoff is not None and handoff != pending: + return error_response( + rid, + "UPDATE_APPLY_HANDOFF_INVALID", + "Apply handoff is detached from the current verified pending update.", + ) + return self._pending_response( + rid, + pending, + status="apply_ready" if handoff == pending else pending.status, + restart_requested=False, + ) + except ValueError: + return error_response( + rid, + "UPDATE_PENDING_INVALID", + "Pending application update state failed closed.", + ) + except OSError: + return error_response( + rid, + "UPDATE_PENDING_FILE_ERROR", + "Pending application update state could not be read safely.", + ) + except Exception: + return error_response( + rid, + "UPDATE_PENDING_FAILED", + "Pending application update recovery failed closed.", + ) + + @staticmethod + def _pending_response( + request_id: str, + pending: Any, + *, + status: str, + restart_requested: bool, + ) -> dict[str, Any]: + return ok_response( + request_id, + { + "pending": True, + "status": status, + "product_id": pending.product_id, + "target_platform": pending.target_platform, + "current_version": pending.current_version, + "target_version": pending.target_version, + "source_head": pending.source_head, + "artifact_name": pending.artifact_name, + "artifact_size": pending.artifact_size, + "artifact_sha256": pending.artifact_sha256, + "authenticity": pending.authenticity, + "installation_performed": False, + "restart_performed": False, + "restart_requested": restart_requested, + }, + ) + + def _default_authenticity_verifier(self, candidate: Path) -> bool: + return verify_same_publisher_authenticode(Path(sys.executable), candidate) + + def _load_pending_core(self) -> tuple[Any, Any, Any]: + root_text = str(self._repo_root) + if root_text not in sys.path: + sys.path.insert(0, root_text) + from runtime_engine.scripture_archive_runtime.application_update_pending import ( + discard_pending_update, + inspect_pending_update, + staged_artifact_path, + ) + + return inspect_pending_update, staged_artifact_path, discard_pending_update + + def _load_apply_core(self) -> tuple[Any, Any, Any]: + root_text = str(self._repo_root) + if root_text not in sys.path: + sys.path.insert(0, root_text) + from runtime_engine.scripture_archive_runtime.application_update_apply import ( + discard_apply_handoff, + inspect_apply_handoff, + prepare_apply_handoff, + ) + + return prepare_apply_handoff, inspect_apply_handoff, discard_apply_handoff diff --git a/lanes/dev1/repair_overlay/scripture_archive_platform/desktop_host/post_update_health.py b/lanes/dev1/repair_overlay/scripture_archive_platform/desktop_host/post_update_health.py new file mode 100644 index 000000000..0855a86c0 --- /dev/null +++ b/lanes/dev1/repair_overlay/scripture_archive_platform/desktop_host/post_update_health.py @@ -0,0 +1,92 @@ +from __future__ import annotations + +from pathlib import Path +import sys +from typing import Any, Callable + +from runtime_engine.scripture_archive_runtime.application_update_health import ( + commit_update_health_receipt, +) +from scripture_archive_platform.transport.contracts import ( + error_response, + ok_response, + validate_request_shape, +) + + +POST_UPDATE_HEALTH_COMMAND = "application_update.commit_post_restart_health" + + +class NativePostUpdateHealthLayer: + """Commit rollback cleanup only after the relaunched packaged bridge is alive. + + The browser can request only this fixed empty-payload action. Executable identity, + current semantic version and staging root are host-owned constructor values. The + runtime health authority re-verifies exact installed and rollback bytes before any + stale pending journal or rollback bytes are disarmed. + """ + + def __init__( + self, + app: Any, + staging_root: Path, + *, + current_version: str, + install_target: Path | None = None, + commit_health: Callable[..., object | None] = commit_update_health_receipt, + ) -> None: + self._app = app + self._staging_root = Path(staging_root) + self._current_version = current_version + self._install_target = Path(sys.executable if install_target is None else install_target) + self._commit_health = commit_health + + def handle(self, request: Any) -> dict[str, Any]: + if not isinstance(request, dict) or request.get("command") != POST_UPDATE_HEALTH_COMMAND: + return self._app.handle(request) + rid = str(request.get("request_id", "invalid")) + try: + rid, command, payload = validate_request_shape(request) + if command != POST_UPDATE_HEALTH_COMMAND or payload: + raise ValueError("post-update health commit requires an empty payload") + except ValueError as exc: + return error_response(rid, "VALIDATION_ERROR", str(exc)) + + if not callable(self._commit_health): + return error_response( + rid, + "UPDATE_HEALTH_UNAVAILABLE", + "Post-update health authority is unavailable.", + ) + try: + receipt = self._commit_health( + self._staging_root, + current_version=self._current_version, + install_target=self._install_target, + ) + except Exception: + return error_response( + rid, + "UPDATE_HEALTH_NOT_COMMITTED", + "Updated application health could not be proven; rollback recovery remains preserved.", + ) + + if receipt is None: + return ok_response( + rid, + { + "status": "none", + "health_committed": False, + "rollback_cleanup_performed": False, + }, + ) + return ok_response( + rid, + { + "status": "healthy", + "health_committed": True, + "rollback_cleanup_performed": True, + "previous_version": receipt.previous_version, + "target_version": receipt.target_version, + }, + ) diff --git a/lanes/dev1/repair_overlay/scripture_archive_platform/desktop_host/updater_launch.py b/lanes/dev1/repair_overlay/scripture_archive_platform/desktop_host/updater_launch.py new file mode 100644 index 000000000..e99098bf7 --- /dev/null +++ b/lanes/dev1/repair_overlay/scripture_archive_platform/desktop_host/updater_launch.py @@ -0,0 +1,98 @@ +from __future__ import annotations + +from collections.abc import Callable +import os +from pathlib import Path +import sys + +from runtime_engine.scripture_archive_runtime.application_update_process import ( + UpdateProcessError, + UpdaterProcessPlan, + build_updater_process_plan, + launch_updater_process, +) +from scripture_archive_platform.desktop_host.authenticode import ( + verify_same_publisher_authenticode, +) + + +PublisherVerifier = Callable[[Path, Path], bool] +PlanBuilder = Callable[..., UpdaterProcessPlan] +ProcessLauncher = Callable[[UpdaterProcessPlan], int] + + +def packaged_updater_path(installed_executable: Path) -> Path: + """Derive the fixed sibling updater name from the packaged executable identity.""" + + installed = Path(installed_executable) + if installed.suffix.casefold() != ".exe": + raise UpdateProcessError("installed packaged executable must have .exe suffix") + return installed.with_name(f"{installed.stem}-Updater{installed.suffix}") + + +def launch_packaged_updater( + staging_root: str | os.PathLike[str], + *, + current_executable: str | os.PathLike[str] | None = None, + verify_same_publisher: PublisherVerifier = verify_same_publisher_authenticode, + build_plan: PlanBuilder = build_updater_process_plan, + launch_process: ProcessLauncher = launch_updater_process, +) -> int: + """Verify and launch only the canonical same-publisher sibling updater. + + The browser supplies none of these values. The installed executable defaults to + the currently running packaged process, the updater path is mechanically derived + beside it, and the existing Authenticode authority must positively prove that + current host and updater share a valid signer before #245's fixed process plan is + constructed or launched. + """ + + if not callable(verify_same_publisher): + raise UpdateProcessError("same-publisher verifier is required") + if not callable(build_plan): + raise UpdateProcessError("updater process-plan builder is required") + if not callable(launch_process): + raise UpdateProcessError("updater process launcher is required") + + installed = Path(sys.executable if current_executable is None else current_executable) + updater = packaged_updater_path(installed) + try: + trusted_updater = bool(verify_same_publisher(installed, updater)) + except Exception as exc: + raise UpdateProcessError("packaged updater authenticity could not be verified") from exc + if not trusted_updater: + raise UpdateProcessError("packaged updater same-publisher authenticity is required") + + requested_staging = Path(staging_root) + plan = build_plan( + updater_executable=updater, + installed_executable=installed, + staging_root=requested_staging, + ) + if not isinstance(plan, UpdaterProcessPlan): + raise UpdateProcessError("updater process-plan builder returned an invalid plan") + try: + expected_updater = updater.resolve(strict=True) + expected_installed = installed.resolve(strict=True) + expected_staging = requested_staging.resolve(strict=True) + except OSError as exc: + raise UpdateProcessError("packaged updater launch authority could not be rebound") from exc + if ( + plan.updater_executable != expected_updater + or plan.installed_executable != expected_installed + or plan.staging_root != expected_staging + ): + raise UpdateProcessError("updater process plan changed host-owned launch authority") + try: + launch_trusted = bool( + verify_same_publisher(plan.installed_executable, plan.updater_executable) + ) + except Exception as exc: + raise UpdateProcessError( + "packaged updater authenticity could not be reverified before launch" + ) from exc + if not launch_trusted: + raise UpdateProcessError( + "packaged updater same-publisher authenticity changed before launch" + ) + return launch_process(plan) diff --git a/lanes/dev1/repair_overlay/scripture_archive_platform/desktop_host/updater_main.py b/lanes/dev1/repair_overlay/scripture_archive_platform/desktop_host/updater_main.py new file mode 100644 index 000000000..c4d04f1f9 --- /dev/null +++ b/lanes/dev1/repair_overlay/scripture_archive_platform/desktop_host/updater_main.py @@ -0,0 +1,92 @@ +from __future__ import annotations + +from collections.abc import Callable, Sequence +from pathlib import Path +import stat +import sys +from typing import Any + +from scripture_archive_platform.desktop_host.authenticode import ( + verify_same_publisher_authenticode, +) +from scripture_archive_platform.desktop_host.version import CURRENT_APPLICATION_VERSION +from runtime_engine.scripture_archive_runtime.application_update_process import ( + parse_trusted_updater_argv, +) +from runtime_engine.scripture_archive_runtime.application_update_runner import ( + execute_trusted_updater, +) + + +UPDATER_OK = 0 +UPDATER_FAILED = 2 +_UPDATER_SUFFIX = "-Updater.exe" + + +def _resolve_packaged_installed_sibling( + argv: Sequence[str], + *, + updater_executable: Path, +) -> tuple[Path, Path]: + """Bind direct invocation to the exact app sibling of this updater executable.""" + + _, installed_argument, _ = parse_trusted_updater_argv(tuple(argv)) + updater = Path(updater_executable) + updater_meta = updater.lstat() + if stat.S_ISLNK(updater_meta.st_mode) or not stat.S_ISREG(updater_meta.st_mode): + raise ValueError("packaged updater executable identity is invalid") + updater = updater.resolve(strict=True) + if not updater.name.casefold().endswith(_UPDATER_SUFFIX.casefold()): + raise ValueError("packaged updater executable name is invalid") + + installed_name = updater.name[: -len(_UPDATER_SUFFIX)] + ".exe" + expected_installed = updater.with_name(installed_name) + installed_meta = installed_argument.lstat() + if stat.S_ISLNK(installed_meta.st_mode) or not stat.S_ISREG(installed_meta.st_mode): + raise ValueError("installed application identity is invalid") + installed = installed_argument.resolve(strict=True) + if installed != expected_installed: + raise ValueError("installed application is not the canonical updater sibling") + return installed, updater + + +def run_updater( + argv: Sequence[str], + *, + execute: Callable[..., Any] = execute_trusted_updater, + verifier: Callable[..., bool] = verify_same_publisher_authenticode, + updater_executable: Path | None = None, +) -> int: + """Run one fixed updater command with packaged trust authorities. + + Direct invocation is bound to the exact application sibling mechanically derived + from this updater's own executable identity. That installed app and this updater + must also share a valid publisher before the runner can consume any apply handoff. + The runner independently verifies installed app versus staged candidate again. + """ + + if not callable(execute) or not callable(verifier): + return UPDATER_FAILED + try: + installed, updater = _resolve_packaged_installed_sibling( + tuple(argv), + updater_executable=Path(sys.executable if updater_executable is None else updater_executable), + ) + if not verifier(installed, updater): + return UPDATER_FAILED + execute( + tuple(argv), + current_version=CURRENT_APPLICATION_VERSION, + verify_same_publisher=verifier, + ) + except Exception: + return UPDATER_FAILED + return UPDATER_OK + + +def main() -> int: + return run_updater(sys.argv[1:]) + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/lanes/dev1/repair_overlay/scripture_archive_platform/desktop_host/version.py b/lanes/dev1/repair_overlay/scripture_archive_platform/desktop_host/version.py new file mode 100644 index 000000000..7cafc6a31 --- /dev/null +++ b/lanes/dev1/repair_overlay/scripture_archive_platform/desktop_host/version.py @@ -0,0 +1,6 @@ +from __future__ import annotations + +# Semantic compatibility version for the current R06-3DEV-A packaged lineage. +# This is host-owned release identity. Update manifests/browser payloads must never +# select or override it. +CURRENT_APPLICATION_VERSION = "0.6.0-r06.3dev.a" 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 987ef91b5..6cfbd54c2 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","dossier.get","diagnostics.get_report","library.text_catalog","library.read_chapter","library.text_search" + "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","library.text_catalog","library.read_chapter","library.text_search" }) _PLAYER_TRUTH_OWNERS = frozenset({"D5/runtime", "REFERENCE_TEST_ONLY"}) @@ -120,6 +120,8 @@ 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.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'} unknown=set(payload)-allowed diff --git a/lanes/dev1/repair_overlay/tests/test_application_update_staging_js_syntax.py b/lanes/dev1/repair_overlay/tests/test_application_update_staging_js_syntax.py index e028c6cec..d5a17b9d2 100644 --- a/lanes/dev1/repair_overlay/tests/test_application_update_staging_js_syntax.py +++ b/lanes/dev1/repair_overlay/tests/test_application_update_staging_js_syntax.py @@ -6,18 +6,24 @@ @unittest.skipUnless(shutil.which("node"), "Node.js is required for frontend syntax qualification") class ApplicationUpdateStagingJavaScriptSyntaxTests(unittest.TestCase): - def test_application_update_module_parses_as_javascript(self): + def test_application_update_modules_parse_as_javascript(self): platform = Path(__file__).resolve().parents[1] - script = platform / "frontend" / "application-update.js" - completed = subprocess.run( - [shutil.which("node"), "--check", str(script)], - capture_output=True, - text=True, - encoding="utf-8", - errors="replace", - check=False, - ) - self.assertEqual(0, completed.returncode, completed.stderr or completed.stdout) + for filename in ("application-update.js", "pending-update.js"): + with self.subTest(filename=filename): + script = platform / "frontend" / filename + completed = subprocess.run( + [shutil.which("node"), "--check", str(script)], + capture_output=True, + text=True, + encoding="utf-8", + errors="replace", + check=False, + ) + self.assertEqual( + 0, + completed.returncode, + completed.stderr or completed.stdout, + ) if __name__ == "__main__": diff --git a/lanes/dev1/repair_overlay/tests/test_application_update_staging_ui.py b/lanes/dev1/repair_overlay/tests/test_application_update_staging_ui.py index 4148a98f1..b463209e8 100644 --- a/lanes/dev1/repair_overlay/tests/test_application_update_staging_ui.py +++ b/lanes/dev1/repair_overlay/tests/test_application_update_staging_ui.py @@ -11,6 +11,9 @@ def test_staging_action_is_semantic_empty_payload_and_truthful_about_boundary(se self.assertIn("payload:{}", script) self.assertIn("application-update-stage", script) self.assertIn("aria-describedby", script) + self.assertIn("aria-busy", script) + self.assertIn("console.error", script) + self.assertNotIn("${error?.message", script) self.assertIn("same-publisher Authenticode", script) self.assertIn("Install, replace, restart і rollback не виконуються", script) self.assertIn("Нічого не встановлено, не замінено й не запущено", script) 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_application_update_apply_handoff.py b/lanes/dev1/repair_overlay/tests/test_packaged_application_update_apply_handoff.py new file mode 100644 index 000000000..efa2db6fb --- /dev/null +++ b/lanes/dev1/repair_overlay/tests/test_packaged_application_update_apply_handoff.py @@ -0,0 +1,221 @@ +import hashlib +import json +import tempfile +import unittest +from pathlib import Path + +from runtime_engine.scripture_archive_runtime.application_update import ( + ApplicationUpdateError, + ApplicationUpdateManifest, +) +from runtime_engine.scripture_archive_runtime.application_update_apply import ( + APPLY_INTENT_SCHEMA, + discard_apply_handoff, + inspect_apply_handoff, + prepare_apply_handoff, +) +from runtime_engine.scripture_archive_runtime.application_update_pending import ( + inspect_pending_update, + staged_artifact_path, +) +from runtime_engine.scripture_archive_runtime.application_update_staging import stage_local_update +from scripture_archive_platform.desktop_host.pending_update import ( + CANCEL_PENDING_UPDATE_COMMAND, + PREPARE_APPLY_COMMAND, + NativePendingUpdateLayer, +) + + +CURRENT_VERSION = "0.6.0-r06.3dev.a" + + +def repository_root() -> Path: + for parent in Path(__file__).resolve().parents: + if (parent / "runtime_engine" / "scripture_archive_runtime" / "application_update.py").exists(): + return parent + raise RuntimeError("repository root with application update runtime not found") + + +def request(command, payload=None): + return { + "api_version": "scripture.transport.v1", + "request_id": "apply-handoff-test-1", + "command": command, + "payload": {} if payload is None else payload, + } + + +class FakeBaseApplication: + def handle(self, value): + return {"ok": True, "data": {"passthrough": value}} + + +class ApplyHandoffFixture(unittest.TestCase): + def setUp(self): + self.temp = tempfile.TemporaryDirectory() + self.root = Path(self.temp.name) + self.staging = self.root / "application-updates" + self.artifact = self.root / "ScriptureArchive-0.6.1.exe" + self.artifact.write_bytes(b"apply-handoff-exact-bytes") + self.digest = hashlib.sha256(self.artifact.read_bytes()).hexdigest() + self.manifest = ApplicationUpdateManifest.from_mapping( + { + "schema": "scripture.application-update.v1", + "product_id": "scripture-archive", + "target_platform": "windows-x64", + "target_version": "0.6.1", + "source_head": "e" * 40, + "artifact_name": self.artifact.name, + "artifact_size": self.artifact.stat().st_size, + "artifact_sha256": self.digest, + } + ) + + def tearDown(self): + self.temp.cleanup() + + def stage(self): + stage_local_update( + self.manifest, + self.artifact, + self.staging, + current_version=CURRENT_VERSION, + same_publisher_authenticode_verified=True, + ) + + +class ApplyHandoffRuntimeTests(ApplyHandoffFixture): + def test_prepare_writes_fixed_path_only_after_pending_reverification(self): + self.stage() + pending = prepare_apply_handoff(self.staging, current_version=CURRENT_VERSION) + self.assertEqual(self.digest, pending.artifact_sha256) + intent_path = self.staging / "apply-update.json" + self.assertTrue(intent_path.is_file()) + payload = json.loads(intent_path.read_text(encoding="utf-8")) + self.assertEqual(APPLY_INTENT_SCHEMA, payload["schema"]) + self.assertEqual("ready", payload["status"]) + self.assertEqual(self.digest, payload["artifact_sha256"]) + self.assertNotIn("path", payload) + self.assertNotIn("source_path", payload) + self.assertNotIn("staged_path", payload) + self.assertEqual(pending, inspect_apply_handoff(self.staging, current_version=CURRENT_VERSION)) + + def test_prepare_is_idempotent_for_same_exact_identity(self): + self.stage() + first = prepare_apply_handoff(self.staging, current_version=CURRENT_VERSION) + before = (self.staging / "apply-update.json").read_bytes() + second = prepare_apply_handoff(self.staging, current_version=CURRENT_VERSION) + self.assertEqual(first, second) + self.assertEqual(before, (self.staging / "apply-update.json").read_bytes()) + + def test_divergent_existing_intent_fails_closed_instead_of_overwrite(self): + self.stage() + prepare_apply_handoff(self.staging, current_version=CURRENT_VERSION) + path = self.staging / "apply-update.json" + payload = json.loads(path.read_text(encoding="utf-8")) + payload["target_version"] = "9.9.9" + path.write_text(json.dumps(payload), encoding="utf-8") + with self.assertRaises(ApplicationUpdateError): + prepare_apply_handoff(self.staging, current_version=CURRENT_VERSION) + self.assertEqual("9.9.9", json.loads(path.read_text(encoding="utf-8"))["target_version"]) + + def test_staged_byte_mutation_detaches_and_blocks_apply_handoff(self): + self.stage() + prepare_apply_handoff(self.staging, current_version=CURRENT_VERSION) + pending = inspect_pending_update(self.staging, current_version=CURRENT_VERSION) + staged_artifact_path(self.staging, pending).write_bytes(b"x" * self.manifest.artifact_size) + with self.assertRaises(ApplicationUpdateError): + inspect_apply_handoff(self.staging, current_version=CURRENT_VERSION) + + def test_discard_removes_only_apply_authority_and_keeps_pending_and_bytes(self): + self.stage() + pending = prepare_apply_handoff(self.staging, current_version=CURRENT_VERSION) + staged = staged_artifact_path(self.staging, pending) + self.assertTrue(discard_apply_handoff(self.staging)) + self.assertFalse((self.staging / "apply-update.json").exists()) + self.assertTrue((self.staging / "pending-update.json").exists()) + self.assertTrue(staged.is_file()) + self.assertIsNone(inspect_apply_handoff(self.staging, current_version=CURRENT_VERSION)) + + def test_no_pending_update_means_no_apply_handoff(self): + with self.assertRaises(ApplicationUpdateError): + prepare_apply_handoff(self.staging, current_version=CURRENT_VERSION) + + +class ApplyHandoffHostTests(ApplyHandoffFixture): + def layer(self, verifier): + return NativePendingUpdateLayer( + FakeBaseApplication(), + repository_root(), + self.staging, + current_version=CURRENT_VERSION, + authenticity_verifier=verifier, + ) + + def test_prepare_command_rechecks_authenticity_and_returns_no_paths(self): + self.stage() + calls = [] + response = self.layer(lambda candidate: calls.append(candidate) or True).handle( + request(PREPARE_APPLY_COMMAND) + ) + self.assertTrue(response["ok"]) + self.assertEqual("apply_ready", response["data"]["status"]) + self.assertFalse(response["data"]["installation_performed"]) + self.assertFalse(response["data"]["restart_performed"]) + self.assertEqual(1, len(calls)) + serialized = json.dumps(response, ensure_ascii=False) + self.assertNotIn(str(self.root), serialized) + self.assertNotIn("path", serialized) + self.assertIsNotNone(inspect_apply_handoff(self.staging, current_version=CURRENT_VERSION)) + + def test_prepare_command_rejects_browser_payload_authority(self): + self.stage() + response = self.layer(lambda candidate: True).handle( + request(PREPARE_APPLY_COMMAND, {"path": "C:\\attacker.exe"}) + ) + self.assertFalse(response["ok"]) + self.assertEqual("VALIDATION_ERROR", response["error"]["code"]) + self.assertFalse((self.staging / "apply-update.json").exists()) + + def test_negative_authenticode_never_creates_apply_handoff(self): + self.stage() + response = self.layer(lambda candidate: False).handle(request(PREPARE_APPLY_COMMAND)) + self.assertFalse(response["ok"]) + self.assertEqual("UPDATE_PENDING_AUTHENTICITY_INVALID", response["error"]["code"]) + self.assertFalse((self.staging / "apply-update.json").exists()) + + def test_signature_then_byte_mutation_never_creates_apply_handoff(self): + self.stage() + + def verifier(candidate): + candidate.write_bytes(b"x" * self.manifest.artifact_size) + return True + + response = self.layer(verifier).handle(request(PREPARE_APPLY_COMMAND)) + self.assertFalse(response["ok"]) + self.assertFalse((self.staging / "apply-update.json").exists()) + + def test_cancel_disarms_apply_intent_before_pending_authority(self): + self.stage() + self.assertTrue(self.layer(lambda candidate: True).handle(request(PREPARE_APPLY_COMMAND))["ok"]) + response = self.layer(lambda candidate: True).handle(request(CANCEL_PENDING_UPDATE_COMMAND)) + self.assertTrue(response["ok"]) + self.assertEqual("cancelled", response["data"]["status"]) + self.assertTrue(response["data"]["apply_handoff_removed"]) + self.assertFalse((self.staging / "apply-update.json").exists()) + self.assertFalse((self.staging / "pending-update.json").exists()) + + def test_frontend_is_keyboard_native_and_explicitly_denies_false_install_claim(self): + platform = Path(__file__).resolve().parents[1] + script = (platform / "frontend" / "pending-update.js").read_text(encoding="utf-8") + self.assertIn("application_update.prepare_apply", script) + self.assertIn("pending-update-prepare-apply", script) + self.assertIn("installation_performed===false", script) + self.assertIn("ще не замінювались", script) + self.assertIn("aria-live", script) + self.assertIn("textContent", script) + self.assertNotIn("innerHTML", script) + + +if __name__ == "__main__": + unittest.main() diff --git a/lanes/dev1/repair_overlay/tests/test_packaged_application_update_pending.py b/lanes/dev1/repair_overlay/tests/test_packaged_application_update_pending.py new file mode 100644 index 000000000..6fcf514b9 --- /dev/null +++ b/lanes/dev1/repair_overlay/tests/test_packaged_application_update_pending.py @@ -0,0 +1,304 @@ +import hashlib +import json +import tempfile +import unittest +from pathlib import Path + +from runtime_engine.scripture_archive_runtime.application_update import ( + ApplicationUpdateError, + ApplicationUpdateManifest, +) +from runtime_engine.scripture_archive_runtime.application_update_pending import ( + discard_pending_update, + inspect_pending_update, + staged_artifact_path, +) +from runtime_engine.scripture_archive_runtime.application_update_staging import ( + stage_local_update, +) +from scripture_archive_platform.desktop_host.pending_update import ( + CANCEL_PENDING_UPDATE_COMMAND, + PENDING_UPDATE_STATUS_COMMAND, + NativePendingUpdateLayer, +) + + +CURRENT_VERSION = "0.6.0-r06.3dev.a" + + +def repository_root() -> Path: + for parent in Path(__file__).resolve().parents: + if (parent / "runtime_engine" / "scripture_archive_runtime" / "application_update.py").exists(): + return parent + raise RuntimeError("repository root with application update runtime not found") + + +def request(command, payload=None): + return { + "api_version": "scripture.transport.v1", + "request_id": "pending-update-test-1", + "command": command, + "payload": {} if payload is None else payload, + } + + +class FakeBaseApplication: + def __init__(self): + self.calls = [] + + def handle(self, value): + self.calls.append(value) + return {"ok": True, "data": {"passthrough": True}} + + +class CountingContextLock: + def __init__(self): + self.entries = 0 + + def __enter__(self): + self.entries += 1 + return self + + def __exit__(self, exc_type, exc, tb): + return False + + +class PendingUpdateRuntimeTests(unittest.TestCase): + def setUp(self): + self.temp = tempfile.TemporaryDirectory() + self.root = Path(self.temp.name) + self.staging = self.root / "application-updates" + self.artifact = self.root / "ScriptureArchive-0.6.1.exe" + self.artifact.write_bytes(b"pending-update-recovery-exact-bytes") + self.digest = hashlib.sha256(self.artifact.read_bytes()).hexdigest() + self.manifest = ApplicationUpdateManifest.from_mapping( + { + "schema": "scripture.application-update.v1", + "product_id": "scripture-archive", + "target_platform": "windows-x64", + "target_version": "0.6.1", + "source_head": "c" * 40, + "artifact_name": self.artifact.name, + "artifact_size": self.artifact.stat().st_size, + "artifact_sha256": self.digest, + } + ) + + def tearDown(self): + self.temp.cleanup() + + def stage(self): + return stage_local_update( + self.manifest, + self.artifact, + self.staging, + current_version=CURRENT_VERSION, + same_publisher_authenticode_verified=True, + ) + + def test_restart_readback_reverifies_exact_staged_bytes(self): + self.stage() + pending = inspect_pending_update(self.staging, current_version=CURRENT_VERSION) + self.assertIsNotNone(pending) + self.assertEqual("staged", pending.status) + self.assertEqual("same_publisher_authenticode_verified", pending.authenticity) + self.assertEqual("0.6.1", pending.target_version) + self.assertEqual(self.digest, pending.artifact_sha256) + staged = staged_artifact_path(self.staging, pending) + self.assertEqual(self.artifact.read_bytes(), staged.read_bytes()) + self.assertNotIn("path", pending.__dict__) + + def test_missing_journal_means_no_pending_update(self): + self.assertIsNone(inspect_pending_update(self.staging, current_version=CURRENT_VERSION)) + self.assertFalse(discard_pending_update(self.staging)) + + def test_staged_byte_mutation_fails_closed(self): + self.stage() + pending = inspect_pending_update(self.staging, current_version=CURRENT_VERSION) + staged = staged_artifact_path(self.staging, pending) + staged.write_bytes(b"x" * self.manifest.artifact_size) + with self.assertRaises(ApplicationUpdateError): + inspect_pending_update(self.staging, current_version=CURRENT_VERSION) + + def test_journal_extra_field_and_version_mismatch_fail_closed(self): + self.stage() + journal_path = self.staging / "pending-update.json" + journal = json.loads(journal_path.read_text(encoding="utf-8")) + journal["unexpected"] = True + journal_path.write_text(json.dumps(journal), encoding="utf-8") + with self.assertRaises(ApplicationUpdateError): + inspect_pending_update(self.staging, current_version=CURRENT_VERSION) + + self.stage() + with self.assertRaises(ApplicationUpdateError): + inspect_pending_update(self.staging, current_version="0.6.0-r06.3dev.b") + + def test_cancel_removes_only_pending_authority_and_keeps_staged_bytes_inert(self): + self.stage() + pending = inspect_pending_update(self.staging, current_version=CURRENT_VERSION) + staged = staged_artifact_path(self.staging, pending) + self.assertTrue(staged.is_file()) + self.assertTrue(discard_pending_update(self.staging)) + self.assertFalse((self.staging / "pending-update.json").exists()) + self.assertTrue(staged.is_file()) + self.assertIsNone(inspect_pending_update(self.staging, current_version=CURRENT_VERSION)) + + def test_corrupt_journal_can_be_disarmed_without_parsing_or_recursive_delete(self): + self.staging.mkdir(parents=True) + journal_path = self.staging / "pending-update.json" + journal_path.write_bytes(b"not-json") + inert = self.staging / "pending" / "untrusted" / "keep.bin" + inert.parent.mkdir(parents=True) + inert.write_bytes(b"inert") + self.assertTrue(discard_pending_update(self.staging)) + self.assertFalse(journal_path.exists()) + self.assertEqual(b"inert", inert.read_bytes()) + + +class PendingUpdateHostTests(unittest.TestCase): + def setUp(self): + self.temp = tempfile.TemporaryDirectory() + self.root = Path(self.temp.name) + self.staging = self.root / "application-updates" + self.artifact = self.root / "ScriptureArchive-0.6.1.exe" + self.artifact.write_bytes(b"host-pending-update-exact-bytes") + digest = hashlib.sha256(self.artifact.read_bytes()).hexdigest() + self.manifest = ApplicationUpdateManifest.from_mapping( + { + "schema": "scripture.application-update.v1", + "product_id": "scripture-archive", + "target_platform": "windows-x64", + "target_version": "0.6.1", + "source_head": "d" * 40, + "artifact_name": self.artifact.name, + "artifact_size": self.artifact.stat().st_size, + "artifact_sha256": digest, + } + ) + self.base = FakeBaseApplication() + + def tearDown(self): + self.temp.cleanup() + + def stage(self): + stage_local_update( + self.manifest, + self.artifact, + self.staging, + current_version=CURRENT_VERSION, + same_publisher_authenticode_verified=True, + ) + + def layer(self, verifier): + return NativePendingUpdateLayer( + self.base, + repository_root(), + self.staging, + current_version=CURRENT_VERSION, + authenticity_verifier=verifier, + ) + + def test_status_reverifies_signature_and_returns_no_local_paths(self): + self.stage() + calls = [] + + def verifier(candidate): + calls.append(candidate) + return True + + response = self.layer(verifier).handle(request(PENDING_UPDATE_STATUS_COMMAND)) + self.assertTrue(response["ok"]) + data = response["data"] + self.assertTrue(data["pending"]) + self.assertEqual("staged", data["status"]) + self.assertEqual("same_publisher_authenticode_verified", data["authenticity"]) + self.assertFalse(data["installation_performed"]) + self.assertEqual(1, len(calls)) + serialized = json.dumps(response, ensure_ascii=False) + self.assertNotIn(str(self.root), serialized) + self.assertNotIn("staged_path", serialized) + self.assertNotIn("source_path", serialized) + + def test_positive_signature_followed_by_mutated_bytes_fails_closed(self): + self.stage() + + def mutate_after_signature(candidate): + candidate.write_bytes(b"x" * self.manifest.artifact_size) + return True + + response = self.layer(mutate_after_signature).handle(request(PENDING_UPDATE_STATUS_COMMAND)) + self.assertFalse(response["ok"]) + self.assertEqual("UPDATE_PENDING_INVALID", response["error"]["code"]) + + def test_negative_signature_fails_closed_without_pending_claim(self): + self.stage() + response = self.layer(lambda candidate: False).handle(request(PENDING_UPDATE_STATUS_COMMAND)) + self.assertFalse(response["ok"]) + self.assertEqual("UPDATE_PENDING_AUTHENTICITY_INVALID", response["error"]["code"]) + + def test_cancel_disarms_even_corrupt_journal_without_signature_execution(self): + self.staging.mkdir(parents=True) + (self.staging / "pending-update.json").write_text("corrupt", encoding="utf-8") + calls = [] + response = self.layer(lambda candidate: calls.append(candidate) or True).handle( + request(CANCEL_PENDING_UPDATE_COMMAND) + ) + self.assertTrue(response["ok"]) + self.assertEqual("cancelled", response["data"]["status"]) + self.assertFalse(response["data"]["pending"]) + self.assertFalse(response["data"]["staged_bytes_removed"]) + self.assertEqual([], calls) + self.assertFalse((self.staging / "pending-update.json").exists()) + + def test_update_command_family_shares_outer_operation_lock(self): + layer = self.layer(lambda candidate: True) + lock = CountingContextLock() + layer._operation_lock = lock + + stage_request = request("application_update.select_verify_stage") + stage_response = layer.handle(stage_request) + self.assertTrue(stage_response["ok"]) + self.assertTrue(stage_response["data"]["passthrough"]) + self.assertEqual([stage_request], self.base.calls) + self.assertEqual(1, lock.entries) + + cancel_response = layer.handle(request(CANCEL_PENDING_UPDATE_COMMAND)) + self.assertTrue(cancel_response["ok"]) + self.assertEqual("none", cancel_response["data"]["status"]) + self.assertEqual(2, lock.entries) + + def test_browser_payload_cannot_supply_pending_state_or_path(self): + response = self.layer(lambda candidate: True).handle( + request(PENDING_UPDATE_STATUS_COMMAND, {"path": "C:\\Users\\attacker\\state.json"}) + ) + self.assertFalse(response["ok"]) + self.assertEqual("VALIDATION_ERROR", response["error"]["code"]) + self.assertEqual([], self.base.calls) + + def test_unrelated_commands_are_delegated(self): + original = request("system.bootstrap") + response = self.layer(lambda candidate: True).handle(original) + self.assertTrue(response["data"]["passthrough"]) + self.assertEqual([original], self.base.calls) + + def test_frontend_exposes_keyboard_native_status_and_cancel_without_html_injection(self): + platform = Path(__file__).resolve().parents[1] + script = (platform / "frontend" / "pending-update.js").read_text(encoding="utf-8") + entry = (platform / "frontend" / "application-update.js").read_text(encoding="utf-8") + self.assertIn("application_update.pending_status", script) + self.assertIn("application_update.cancel_pending", script) + self.assertIn("pending-update-check", script) + self.assertIn("pending-update-cancel", script) + self.assertIn("aria-live", script) + self.assertIn("aria-busy", script) + self.assertIn("console.error", script) + self.assertIn("textContent", script) + self.assertNotIn("innerHTML", script) + self.assertNotIn("${error?.message", script) + self.assertIn("Файли програми не змінено.", script) + self.assertIn("Rollback recovery збережено", script) + self.assertIn("./pending-update.js", entry) + + +if __name__ == "__main__": + unittest.main() diff --git a/lanes/dev1/repair_overlay/tests/test_packaged_application_update_pending_concurrency.py b/lanes/dev1/repair_overlay/tests/test_packaged_application_update_pending_concurrency.py new file mode 100644 index 000000000..d62be45b3 --- /dev/null +++ b/lanes/dev1/repair_overlay/tests/test_packaged_application_update_pending_concurrency.py @@ -0,0 +1,161 @@ +import tempfile +import threading +import unittest +from pathlib import Path + +from scripture_archive_platform.desktop_host.pending_update import ( + CANCEL_PENDING_UPDATE_COMMAND, + PREPARE_APPLY_COMMAND, + NativePendingUpdateLayer, +) + + +CURRENT_VERSION = "0.6.0-r06.3dev.a" + + +def repository_root() -> Path: + for parent in Path(__file__).resolve().parents: + if (parent / "runtime_engine" / "scripture_archive_runtime" / "application_update.py").exists(): + return parent + raise RuntimeError("repository root with application update runtime not found") + + +def request(command, request_id): + return { + "api_version": "scripture.transport.v1", + "request_id": request_id, + "command": command, + "payload": {}, + } + + +class BlockingBaseApplication: + def __init__(self): + self.entered = threading.Event() + self.release = threading.Event() + self.calls = [] + + def handle(self, value): + self.calls.append(value) + if value.get("request_id") == "stage-first": + self.entered.set() + if not self.release.wait(timeout=5): + raise AssertionError("test did not release staged update delegation") + return {"ok": True, "data": {"passthrough": True}} + + +class PendingUpdateConcurrencyTests(unittest.TestCase): + def build_layer(self, staging, base): + return NativePendingUpdateLayer( + base, + repository_root(), + staging, + current_version=CURRENT_VERSION, + authenticity_verifier=lambda candidate: True, + ) + + def test_cancel_waits_for_inflight_staging_family_operation(self): + with tempfile.TemporaryDirectory() as temp: + staging = Path(temp) / "application-updates" + staging.mkdir(parents=True) + journal = staging / "pending-update.json" + journal.write_text("corrupt-but-fixed-path", encoding="utf-8") + + base = BlockingBaseApplication() + layer = self.build_layer(staging, base) + first_result = [] + second_result = [] + second_started = threading.Event() + second_done = threading.Event() + + first = threading.Thread( + target=lambda: first_result.append( + layer.handle( + request("application_update.select_verify_stage", "stage-first") + ) + ) + ) + + def cancel_pending(): + second_started.set() + second_result.append( + layer.handle(request(CANCEL_PENDING_UPDATE_COMMAND, "cancel-second")) + ) + second_done.set() + + second = threading.Thread(target=cancel_pending) + first.start() + self.assertTrue(base.entered.wait(timeout=2)) + second.start() + self.assertTrue(second_started.wait(timeout=2)) + self.assertFalse(second_done.wait(timeout=0.1)) + self.assertTrue(journal.exists()) + + base.release.set() + first.join(timeout=2) + second.join(timeout=2) + self.assertFalse(first.is_alive()) + self.assertFalse(second.is_alive()) + self.assertEqual(1, len(first_result)) + self.assertEqual(1, len(second_result)) + self.assertTrue(first_result[0]["ok"]) + self.assertTrue(second_result[0]["ok"]) + self.assertEqual("cancelled", second_result[0]["data"]["status"]) + self.assertFalse(journal.exists()) + self.assertEqual( + "application_update.select_verify_stage", + base.calls[0]["command"], + ) + + def test_prepare_apply_waits_for_inflight_staging_family_operation(self): + with tempfile.TemporaryDirectory() as temp: + staging = Path(temp) / "application-updates" + staging.mkdir(parents=True) + # A corrupt fixed journal makes prepare fail closed *after* it obtains + # the update-family lock. The assertion here is about serialization, + # not successful apply-handoff creation. + (staging / "pending-update.json").write_text("corrupt", encoding="utf-8") + + base = BlockingBaseApplication() + layer = self.build_layer(staging, base) + first_result = [] + second_result = [] + second_started = threading.Event() + second_done = threading.Event() + + first = threading.Thread( + target=lambda: first_result.append( + layer.handle( + request("application_update.select_verify_stage", "stage-first") + ) + ) + ) + + def prepare_apply(): + second_started.set() + second_result.append( + layer.handle(request(PREPARE_APPLY_COMMAND, "prepare-second")) + ) + second_done.set() + + second = threading.Thread(target=prepare_apply) + first.start() + self.assertTrue(base.entered.wait(timeout=2)) + second.start() + self.assertTrue(second_started.wait(timeout=2)) + self.assertFalse(second_done.wait(timeout=0.1)) + + base.release.set() + first.join(timeout=2) + second.join(timeout=2) + self.assertFalse(first.is_alive()) + self.assertFalse(second.is_alive()) + self.assertEqual(1, len(first_result)) + self.assertEqual(1, len(second_result)) + self.assertTrue(first_result[0]["ok"]) + self.assertFalse(second_result[0]["ok"]) + self.assertEqual("UPDATE_PENDING_INVALID", second_result[0]["error"]["code"]) + + +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 38488669a..ab9b50e49 100644 --- a/lanes/dev1/repair_overlay/tests/test_packaged_diagnostics.py +++ b/lanes/dev1/repair_overlay/tests/test_packaged_diagnostics.py @@ -166,22 +166,33 @@ def test_builder_fails_closed_on_native_failure_and_stale_artifact(self): 'Assert-NativeSuccess "pip upgrade"', 'Assert-NativeSuccess "build dependency install"', 'Assert-NativeSuccess "Windows release diagnostics"', - 'Assert-NativeSuccess "PyInstaller build"', + 'Assert-NativeSuccess "PyInstaller application build"', + 'Assert-NativeSuccess "PyInstaller updater build"', 'Assert-NativeSuccess "Python version query"', - 'Assert-NativeSuccess "artifact verification"', + 'Assert-NativeSuccess "application artifact verification"', + 'Assert-NativeSuccess "updater artifact verification"', ): self.assertIn(step, build) - stale_cleanup = "Remove-Item -LiteralPath $Out -Force" + stale_cleanup = "Remove-Item -LiteralPath $artifact -Force" + self.assertIn("foreach ($artifact in @($Out, $UpdaterOut))", build) self.assertIn(stale_cleanup, build) self.assertLess(build.index(stale_cleanup), build.index("pyinstaller.exe")) self.assertLess( - build.index('Assert-NativeSuccess "PyInstaller build"'), + build.index('Assert-NativeSuccess "PyInstaller application build"'), build.index('if (-not (Test-Path -LiteralPath $Out -PathType Leaf))'), ) self.assertLess( - build.index('Assert-NativeSuccess "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_post_update_health.py b/lanes/dev1/repair_overlay/tests/test_packaged_post_update_health.py new file mode 100644 index 000000000..2e30b80ab --- /dev/null +++ b/lanes/dev1/repair_overlay/tests/test_packaged_post_update_health.py @@ -0,0 +1,132 @@ +from __future__ import annotations + +import json +import unittest +from dataclasses import dataclass +from pathlib import Path + +from scripture_archive_platform.desktop_host.post_update_health import ( + POST_UPDATE_HEALTH_COMMAND, + NativePostUpdateHealthLayer, +) + + +CURRENT_VERSION = "0.6.0-r06.3dev.a" + + +def request(command=POST_UPDATE_HEALTH_COMMAND, payload=None, request_id="health-rid"): + return { + "api_version": "scripture.transport.v1", + "request_id": request_id, + "command": command, + "payload": {} if payload is None else payload, + } + + +class FakeBaseApplication: + def __init__(self): + self.calls = [] + + def handle(self, value): + self.calls.append(value) + return {"ok": True, "data": {"passthrough": True}} + + +@dataclass(frozen=True) +class FakeReceipt: + previous_version: str = "0.5.9" + target_version: str = CURRENT_VERSION + + +class PackagedPostUpdateHealthTests(unittest.TestCase): + def setUp(self): + self.base = FakeBaseApplication() + self.staging = Path("state") / "application-updates" + self.installed = Path("install") / "ScriptureArchive-R06-DEV01.exe" + + def layer(self, commit): + return NativePostUpdateHealthLayer( + self.base, + self.staging, + current_version=CURRENT_VERSION, + install_target=self.installed, + commit_health=commit, + ) + + def test_health_commit_uses_only_host_owned_version_path_and_preserves_request_id(self): + calls = [] + + def commit(staging_root, **kwargs): + calls.append((Path(staging_root), kwargs)) + return FakeReceipt() + + response = self.layer(commit).handle(request(request_id="exact-health-rid")) + self.assertTrue(response["ok"]) + self.assertEqual("exact-health-rid", response["request_id"]) + self.assertEqual("healthy", response["data"]["status"]) + self.assertTrue(response["data"]["health_committed"]) + self.assertTrue(response["data"]["rollback_cleanup_performed"]) + self.assertEqual( + [ + ( + self.staging, + { + "current_version": CURRENT_VERSION, + "install_target": self.installed, + }, + ) + ], + calls, + ) + serialized = json.dumps(response) + self.assertNotIn(str(self.installed), serialized) + self.assertNotIn(str(self.staging), serialized) + + def test_no_receipt_is_successful_noop(self): + response = self.layer(lambda *args, **kwargs: None).handle(request()) + self.assertTrue(response["ok"]) + self.assertEqual("none", response["data"]["status"]) + self.assertFalse(response["data"]["health_committed"]) + self.assertFalse(response["data"]["rollback_cleanup_performed"]) + + def test_failed_exact_health_proof_returns_recovery_preserved_error(self): + def fail(*args, **kwargs): + raise ValueError("tampered installed bytes") + + response = self.layer(fail).handle(request()) + self.assertFalse(response["ok"]) + self.assertEqual("UPDATE_HEALTH_NOT_COMMITTED", response["error"]["code"]) + self.assertIn("rollback recovery remains preserved", response["error"]["message"]) + self.assertNotIn("tampered", json.dumps(response)) + + def test_browser_cannot_supply_health_path_version_or_hash(self): + calls = [] + response = self.layer(lambda *args, **kwargs: calls.append((args, kwargs))).handle( + request(payload={"path": "C:\\attacker.exe", "version": "9.9.9", "sha256": "0" * 64}) + ) + self.assertFalse(response["ok"]) + self.assertEqual("VALIDATION_ERROR", response["error"]["code"]) + self.assertEqual([], calls) + + def test_unrelated_command_is_delegated(self): + original = request(command="system.bootstrap") + response = self.layer(lambda *args, **kwargs: None).handle(original) + self.assertTrue(response["data"]["passthrough"]) + self.assertEqual([original], self.base.calls) + + def test_frontend_runs_health_commit_before_pending_startup_recovery(self): + platform = Path(__file__).resolve().parents[1] + script = (platform / "frontend" / "pending-update.js").read_text(encoding="utf-8") + self.assertIn("application_update.commit_post_restart_health", script) + start = script.index("async function commitPostRestartHealth") + health_call = script.index("invoke(HEALTH_COMMAND)", start) + pending_call = script.index("checkPending({startup:true})", start) + self.assertLess(health_call, pending_call) + self.assertIn("Rollback recovery збережено", script) + self.assertIn("aria-live", script) + self.assertIn("textContent", script) + self.assertNotIn("innerHTML", script) + + +if __name__ == "__main__": + unittest.main() diff --git a/lanes/dev1/repair_overlay/tests/test_packaged_updater_entrypoint.py b/lanes/dev1/repair_overlay/tests/test_packaged_updater_entrypoint.py new file mode 100644 index 000000000..053dd0a73 --- /dev/null +++ b/lanes/dev1/repair_overlay/tests/test_packaged_updater_entrypoint.py @@ -0,0 +1,157 @@ +from __future__ import annotations + +import tempfile +import unittest +from pathlib import Path + +from scripture_archive_platform.desktop_host.updater_main import ( + UPDATER_FAILED, + UPDATER_OK, + run_updater, +) +from scripture_archive_platform.desktop_host.version import CURRENT_APPLICATION_VERSION + + +class PackagedUpdaterEntrypointTests(unittest.TestCase): + def setUp(self) -> None: + self.temp = tempfile.TemporaryDirectory() + self.root = Path(self.temp.name) + self.install = self.root / "Program Files" / "Scripture Archive" + self.install.mkdir(parents=True) + self.installed = self.install / "ScriptureArchive-R06-DEV01.exe" + self.updater = self.install / "ScriptureArchive-R06-DEV01-Updater.exe" + self.installed.write_bytes(b"installed") + self.updater.write_bytes(b"updater") + self.staging = self.root / "state" / "application-updates" + self.staging.mkdir(parents=True) + + def tearDown(self) -> None: + self.temp.cleanup() + + def argv(self, installed: Path | None = None) -> tuple[str, ...]: + return ( + "--scripture-archive-apply", + "--wait-pid", + "41", + "--installed-executable", + str(self.installed if installed is None else installed), + "--staging-root", + str(self.staging), + ) + + def test_forwards_fixed_sibling_argv_with_host_version_and_verifier(self) -> None: + execute_calls: list[tuple[tuple[str, ...], dict[str, object]]] = [] + verify_calls: list[tuple[Path, Path]] = [] + + def execute(argv, **kwargs): + execute_calls.append((tuple(argv), dict(kwargs))) + return object() + + def verifier(installed: Path, updater: Path) -> bool: + verify_calls.append((installed, updater)) + return True + + argv = self.argv() + result = run_updater( + argv, + execute=execute, + verifier=verifier, + updater_executable=self.updater, + ) + + self.assertEqual(result, UPDATER_OK) + self.assertEqual(verify_calls, [(self.installed.resolve(), self.updater.resolve())]) + self.assertEqual(len(execute_calls), 1) + forwarded, kwargs = execute_calls[0] + self.assertEqual(forwarded, argv) + self.assertEqual(kwargs["current_version"], CURRENT_APPLICATION_VERSION) + self.assertIs(kwargs["verify_same_publisher"], verifier) + + def test_existing_noncanonical_installed_target_never_reaches_verifier_or_executor(self) -> None: + other = self.install / "Other.exe" + other.write_bytes(b"other") + verified = [] + executed = [] + result = run_updater( + self.argv(other), + execute=lambda *args, **kwargs: executed.append((args, kwargs)), + verifier=lambda *args: verified.append(args) or True, + updater_executable=self.updater, + ) + self.assertEqual(result, UPDATER_FAILED) + self.assertEqual([], verified) + self.assertEqual([], executed) + + def test_wrong_updater_filename_never_reaches_executor(self) -> None: + wrong = self.install / "Updater.exe" + wrong.write_bytes(b"updater") + executed = [] + self.assertEqual( + run_updater( + self.argv(), + execute=lambda *args, **kwargs: executed.append((args, kwargs)), + verifier=lambda *args: True, + updater_executable=wrong, + ), + UPDATER_FAILED, + ) + self.assertEqual([], executed) + + def test_symlink_installed_target_never_reaches_executor(self) -> None: + real = self.install / "real.exe" + real.write_bytes(b"real") + self.installed.unlink() + try: + self.installed.symlink_to(real) + except (OSError, NotImplementedError): + self.skipTest("symlinks unavailable") + executed = [] + self.assertEqual( + run_updater( + self.argv(), + execute=lambda *args, **kwargs: executed.append((args, kwargs)), + verifier=lambda *args: True, + updater_executable=self.updater, + ), + UPDATER_FAILED, + ) + self.assertEqual([], executed) + + def test_negative_updater_publisher_proof_never_reaches_executor(self) -> None: + executed = [] + self.assertEqual( + run_updater( + self.argv(), + execute=lambda *args, **kwargs: executed.append((args, kwargs)), + verifier=lambda installed, updater: False, + updater_executable=self.updater, + ), + UPDATER_FAILED, + ) + self.assertEqual([], executed) + + def test_malformed_command_fails_before_executor(self) -> None: + calls = 0 + + def execute(argv, **kwargs): + nonlocal calls + calls += 1 + + self.assertEqual( + run_updater( + ("bad",), + execute=execute, + verifier=lambda *args: True, + updater_executable=self.updater, + ), + UPDATER_FAILED, + ) + self.assertEqual(calls, 0) + + def test_requires_callable_execution_and_verifier_authorities(self) -> None: + self.assertEqual(run_updater((), execute=None), UPDATER_FAILED) # type: ignore[arg-type] + self.assertEqual(run_updater((), verifier=None), UPDATER_FAILED) # type: ignore[arg-type] + + +if __name__ == "__main__": + unittest.main() 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 new file mode 100644 index 000000000..4b6b34402 --- /dev/null +++ b/lanes/dev1/repair_overlay/tests/test_packaged_updater_host_launch.py @@ -0,0 +1,304 @@ +from __future__ import annotations + +import hashlib +import json +import tempfile +import unittest +from pathlib import Path + +from runtime_engine.scripture_archive_runtime.application_update import ApplicationUpdateManifest +from runtime_engine.scripture_archive_runtime.application_update_process import ( + UpdateProcessError, + UpdaterProcessPlan, +) +from runtime_engine.scripture_archive_runtime.application_update_staging import stage_local_update +from scripture_archive_platform.desktop_host.pending_update import ( + APPLY_AND_RESTART_COMMAND, + PENDING_UPDATE_STATUS_COMMAND, + PREPARE_APPLY_COMMAND, + NativePendingUpdateLayer, +) +from scripture_archive_platform.desktop_host.updater_launch import ( + launch_packaged_updater, + packaged_updater_path, +) + + +CURRENT_VERSION = "0.6.0-r06.3dev.a" + + +def repository_root() -> Path: + for parent in Path(__file__).resolve().parents: + if (parent / "runtime_engine" / "scripture_archive_runtime" / "application_update.py").exists(): + return parent + raise RuntimeError("repository root with application update runtime not found") + + +def request(command: str, payload=None, request_id: str = "host-launch-1"): + return { + "api_version": "scripture.transport.v1", + "request_id": request_id, + "command": command, + "payload": {} if payload is None else payload, + } + + +class FakeBaseApplication: + def handle(self, value): + return {"ok": True, "data": {"passthrough": value}} + + +class PackagedUpdaterLaunchBoundaryTests(unittest.TestCase): + def setUp(self): + self.temp = tempfile.TemporaryDirectory() + self.root = Path(self.temp.name) + self.install = self.root / "install" + self.install.mkdir() + self.current = self.install / "ScriptureArchive-R06-DEV01.exe" + self.current.write_bytes(b"current-host") + self.updater = self.install / "ScriptureArchive-R06-DEV01-Updater.exe" + self.updater.write_bytes(b"packaged-updater") + self.staging = self.root / "state" / "application-updates" + self.staging.mkdir(parents=True) + + def tearDown(self): + self.temp.cleanup() + + def test_fixed_updater_name_is_derived_from_installed_executable(self): + self.assertEqual(self.updater, packaged_updater_path(self.current)) + with self.assertRaises(UpdateProcessError): + packaged_updater_path(self.install / "not-an-executable") + + def test_same_publisher_is_required_before_plan_or_launch(self): + events = [] + + def verify(current, updater): + events.append(("verify", current, updater)) + return True + + def build_plan(**kwargs): + events.append(("plan", kwargs)) + return UpdaterProcessPlan( + updater_executable=kwargs["updater_executable"].resolve(strict=True), + installed_executable=kwargs["installed_executable"].resolve(strict=True), + staging_root=kwargs["staging_root"].resolve(strict=True), + parent_pid=41, + ) + + def launch(plan): + events.append(("launch", plan)) + return 777 + + pid = launch_packaged_updater( + self.staging, + current_executable=self.current, + verify_same_publisher=verify, + build_plan=build_plan, + launch_process=launch, + ) + self.assertEqual(777, pid) + self.assertEqual(("verify", self.current, self.updater), events[0]) + self.assertEqual("plan", events[1][0]) + self.assertEqual(self.updater, events[1][1]["updater_executable"]) + self.assertEqual(self.current, events[1][1]["installed_executable"]) + self.assertEqual(self.staging, events[1][1]["staging_root"]) + self.assertEqual(("verify", self.current.resolve(), self.updater.resolve()), events[2]) + self.assertEqual("launch", events[3][0]) + + def test_process_plan_cannot_substitute_host_owned_launch_paths(self): + external = self.root / "external-updater.exe" + external.write_bytes(b"external") + launched = [] + + def substituted_plan(**kwargs): + return UpdaterProcessPlan( + updater_executable=external, + installed_executable=kwargs["installed_executable"].resolve(), + staging_root=kwargs["staging_root"].resolve(), + parent_pid=41, + ) + + with self.assertRaisesRegex(UpdateProcessError, "changed host-owned launch authority"): + launch_packaged_updater( + self.staging, + current_executable=self.current, + verify_same_publisher=lambda _current, _updater: True, + build_plan=substituted_plan, + launch_process=lambda plan: launched.append(plan) or 1, + ) + self.assertEqual([], launched) + + def test_publisher_is_reverified_after_plan_before_launch(self): + verdicts = iter((True, False)) + calls = [] + launched = [] + + def verify(current, updater): + calls.append((current, updater)) + return next(verdicts) + + with self.assertRaisesRegex(UpdateProcessError, "changed before launch"): + launch_packaged_updater( + self.staging, + current_executable=self.current, + verify_same_publisher=verify, + launch_process=lambda plan: launched.append(plan) or 1, + ) + self.assertEqual(2, len(calls)) + self.assertEqual([], launched) + + def test_negative_or_failed_publisher_proof_never_builds_process_plan(self): + for verifier in ( + lambda current, updater: False, + lambda current, updater: (_ for _ in ()).throw(RuntimeError("unavailable")), + ): + built = [] + with self.subTest(verifier=verifier), self.assertRaises(UpdateProcessError): + launch_packaged_updater( + self.staging, + current_executable=self.current, + verify_same_publisher=verifier, + build_plan=lambda **kwargs: built.append(kwargs), + launch_process=lambda plan: 1, + ) + self.assertEqual([], built) + + +class PackagedUpdaterHostExecutionTests(unittest.TestCase): + def setUp(self): + self.temp = tempfile.TemporaryDirectory() + self.root = Path(self.temp.name) + self.staging = self.root / "application-updates" + self.artifact = self.root / "ScriptureArchive-0.6.1.exe" + self.artifact.write_bytes(b"host-execution-candidate") + digest = hashlib.sha256(self.artifact.read_bytes()).hexdigest() + manifest = ApplicationUpdateManifest.from_mapping( + { + "schema": "scripture.application-update.v1", + "product_id": "scripture-archive", + "target_platform": "windows-x64", + "target_version": "0.6.1", + "source_head": "f" * 40, + "artifact_name": self.artifact.name, + "artifact_size": self.artifact.stat().st_size, + "artifact_sha256": digest, + } + ) + stage_local_update( + manifest, + self.artifact, + self.staging, + current_version=CURRENT_VERSION, + same_publisher_authenticode_verified=True, + ) + + def tearDown(self): + self.temp.cleanup() + + def layer(self, events, *, pid=222): + return NativePendingUpdateLayer( + FakeBaseApplication(), + repository_root(), + self.staging, + current_version=CURRENT_VERSION, + authenticity_verifier=lambda candidate: True, + apply_executor=lambda: events.append("launch") or pid, + shutdown_request=lambda: events.append("shutdown"), + ) + + def test_status_recovers_durable_apply_ready_with_exact_request_id(self): + events = [] + layer = self.layer(events) + prepared = layer.handle(request(PREPARE_APPLY_COMMAND, request_id="prepare-rid")) + self.assertTrue(prepared["ok"]) + self.assertEqual("prepare-rid", prepared["request_id"]) + + recovered = layer.handle(request(PENDING_UPDATE_STATUS_COMMAND, request_id="status-rid")) + self.assertTrue(recovered["ok"]) + self.assertEqual("status-rid", recovered["request_id"]) + self.assertEqual("apply_ready", recovered["data"]["status"]) + self.assertFalse(recovered["data"]["installation_performed"]) + self.assertEqual([], events) + + def test_explicit_execute_launches_before_shutdown_and_leaks_no_pid_or_path(self): + events = [] + layer = self.layer(events) + self.assertTrue(layer.handle(request(PREPARE_APPLY_COMMAND))["ok"]) + response = layer.handle(request(APPLY_AND_RESTART_COMMAND, request_id="execute-rid")) + self.assertTrue(response["ok"]) + self.assertEqual("execute-rid", response["request_id"]) + self.assertEqual(["launch", "shutdown"], events) + self.assertEqual("updater_started", response["data"]["status"]) + self.assertTrue(response["data"]["updater_process_started"]) + self.assertTrue(response["data"]["restart_requested"]) + self.assertFalse(response["data"]["installation_performed"]) + serialized = json.dumps(response, ensure_ascii=False) + self.assertNotIn("222", serialized) + self.assertNotIn(str(self.root), serialized) + self.assertNotIn("path", serialized) + + def test_execute_without_matching_handoff_never_launches_or_shuts_down(self): + events = [] + response = self.layer(events).handle(request(APPLY_AND_RESTART_COMMAND)) + self.assertFalse(response["ok"]) + self.assertEqual("UPDATE_APPLY_HANDOFF_REQUIRED", response["error"]["code"]) + self.assertEqual([], events) + + def test_browser_payload_cannot_supply_process_or_path_authority(self): + events = [] + layer = self.layer(events) + self.assertTrue(layer.handle(request(PREPARE_APPLY_COMMAND))["ok"]) + response = layer.handle( + request( + APPLY_AND_RESTART_COMMAND, + {"pid": 1, "updater": r"C:\attacker.exe"}, + ) + ) + self.assertFalse(response["ok"]) + self.assertEqual("VALIDATION_ERROR", response["error"]["code"]) + self.assertEqual([], events) + + def test_invalid_child_pid_fails_closed_before_shutdown(self): + events = [] + layer = self.layer(events, pid=0) + self.assertTrue(layer.handle(request(PREPARE_APPLY_COMMAND))["ok"]) + response = layer.handle(request(APPLY_AND_RESTART_COMMAND)) + self.assertFalse(response["ok"]) + self.assertEqual("UPDATE_PENDING_INVALID", response["error"]["code"]) + self.assertEqual(["launch"], events) + + def test_execution_callbacks_can_be_bound_after_window_creation(self): + events = [] + layer = NativePendingUpdateLayer( + FakeBaseApplication(), + repository_root(), + self.staging, + current_version=CURRENT_VERSION, + authenticity_verifier=lambda candidate: True, + ) + unavailable = layer.handle(request(APPLY_AND_RESTART_COMMAND)) + self.assertFalse(unavailable["ok"]) + self.assertEqual("UPDATE_EXECUTION_UNAVAILABLE", unavailable["error"]["code"]) + layer.bind_apply_execution( + lambda: events.append("launch") or 333, + lambda: events.append("shutdown"), + ) + self.assertTrue(layer.handle(request(PREPARE_APPLY_COMMAND))["ok"]) + self.assertTrue(layer.handle(request(APPLY_AND_RESTART_COMMAND))["ok"]) + self.assertEqual(["launch", "shutdown"], events) + + def test_frontend_exposes_accessible_two_step_install_without_html_injection(self): + platform = Path(__file__).resolve().parents[1] + script = (platform / "frontend" / "pending-update.js").read_text(encoding="utf-8") + self.assertIn("application_update.apply_and_restart", script) + self.assertIn("pending-update-apply-restart", script) + self.assertIn("Встановити й перезапустити", script) + self.assertIn("apply.disabled=true", script) + self.assertIn("button.disabled=busy", script) + self.assertIn("aria-live", script) + self.assertIn("textContent", script) + self.assertNotIn("innerHTML", script) + + +if __name__ == "__main__": + unittest.main() diff --git a/runtime_engine/scripture_archive_runtime/application_update_apply.py b/runtime_engine/scripture_archive_runtime/application_update_apply.py new file mode 100644 index 000000000..3923d7640 --- /dev/null +++ b/runtime_engine/scripture_archive_runtime/application_update_apply.py @@ -0,0 +1,215 @@ +"""Durable, fail-closed apply handoff for a verified staged application update. + +This module does not replace or execute application bytes. It creates a fixed, +host-owned apply intent that a future privileged/standalone updater can consume only +after independently re-verifying the same pending journal and exact staged bytes. +Browser code never receives filesystem paths from this module. +""" + +from __future__ import annotations + +import json +import os +from pathlib import Path +import stat +from typing import Any + +from .application_update import ApplicationUpdateError +from .application_update_pending import PendingApplicationUpdate, inspect_pending_update + + +APPLY_INTENT_SCHEMA = "scripture.application-update.apply-intent.v1" +_APPLY_INTENT_NAME = "apply-update.json" +_MAX_INTENT_BYTES = 16 * 1024 +_REQUIRED_KEYS = frozenset( + { + "schema", + "status", + "product_id", + "target_platform", + "current_version", + "target_version", + "source_head", + "artifact_name", + "artifact_size", + "artifact_sha256", + "authenticity", + } +) + + +def prepare_apply_handoff( + staging_root: str | os.PathLike[str], + *, + current_version: str, +) -> PendingApplicationUpdate: + """Persist an idempotent apply intent bound to the current verified pending bytes. + + Existing intent is accepted only when it is a regular non-symlink file and its + complete semantic identity exactly matches the freshly re-verified pending + update. Any divergent/corrupt intent fails closed rather than being overwritten. + """ + + root = Path(staging_root) + pending = inspect_pending_update(root, current_version=current_version) + if pending is None: + raise ApplicationUpdateError("no pending update is available for apply handoff") + + payload = _intent_payload(pending) + encoded = (json.dumps(payload, ensure_ascii=False, sort_keys=True, separators=(",", ":")) + "\n").encode("utf-8") + if len(encoded) > _MAX_INTENT_BYTES: + raise ApplicationUpdateError("apply intent exceeds the size limit") + + intent = root / _APPLY_INTENT_NAME + existing = _read_existing_intent(intent) + if existing is not None: + if existing != payload: + raise ApplicationUpdateError("existing apply intent does not match verified pending update") + return pending + + temp = root / f".{_APPLY_INTENT_NAME}.{os.getpid()}.tmp" + try: + descriptor = os.open(temp, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600) + except OSError as exc: + raise ApplicationUpdateError("could not create apply intent safely") from exc + try: + with os.fdopen(descriptor, "wb", closefd=True) as handle: + handle.write(encoded) + handle.flush() + os.fsync(handle.fileno()) + # Re-verify pending bytes immediately before publication so the durable + # intent is never published from stale verification state. + rebound = inspect_pending_update(root, current_version=current_version) + if rebound != pending: + raise ApplicationUpdateError("pending update changed before apply handoff publication") + os.replace(temp, intent) + _fsync_directory(root) + except Exception: + try: + temp.unlink() + except OSError: + pass + raise + + readback = _read_existing_intent(intent) + if readback != payload: + raise ApplicationUpdateError("apply intent readback does not match verified pending update") + return pending + + +def inspect_apply_handoff( + staging_root: str | os.PathLike[str], + *, + current_version: str, +) -> PendingApplicationUpdate | None: + """Return the verified pending identity only when the fixed apply intent matches it.""" + + root = Path(staging_root) + payload = _read_existing_intent(root / _APPLY_INTENT_NAME) + if payload is None: + return None + pending = inspect_pending_update(root, current_version=current_version) + if pending is None or payload != _intent_payload(pending): + raise ApplicationUpdateError("apply intent is detached from current pending update") + return pending + + +def discard_apply_handoff(staging_root: str | os.PathLike[str]) -> bool: + """Remove only the fixed apply-intent authority; never delete staged bytes.""" + + path = Path(staging_root) / _APPLY_INTENT_NAME + try: + metadata = path.lstat() + except FileNotFoundError: + return False + except OSError as exc: + raise ApplicationUpdateError("apply intent is unavailable") from exc + if not (stat.S_ISREG(metadata.st_mode) or stat.S_ISLNK(metadata.st_mode)): + raise ApplicationUpdateError("apply intent path is unsafe") + try: + path.unlink() + _fsync_directory(path.parent) + except OSError as exc: + raise ApplicationUpdateError("apply intent could not be discarded safely") from exc + return True + + +def _intent_payload(pending: PendingApplicationUpdate) -> dict[str, Any]: + if not isinstance(pending, PendingApplicationUpdate): + raise ApplicationUpdateError("pending update identity is invalid") + return { + "schema": APPLY_INTENT_SCHEMA, + "status": "ready", + "product_id": pending.product_id, + "target_platform": pending.target_platform, + "current_version": pending.current_version, + "target_version": pending.target_version, + "source_head": pending.source_head, + "artifact_name": pending.artifact_name, + "artifact_size": pending.artifact_size, + "artifact_sha256": pending.artifact_sha256, + "authenticity": pending.authenticity, + } + + +def _read_existing_intent(path: Path) -> dict[str, Any] | None: + try: + before = path.lstat() + except FileNotFoundError: + return None + except OSError as exc: + raise ApplicationUpdateError("apply intent is unavailable") from exc + if stat.S_ISLNK(before.st_mode) or not stat.S_ISREG(before.st_mode): + raise ApplicationUpdateError("apply intent must be a regular non-symlink file") + if before.st_size <= 0 or before.st_size > _MAX_INTENT_BYTES: + raise ApplicationUpdateError("apply intent is empty or exceeds the size limit") + identity = (before.st_dev, before.st_ino, before.st_size, before.st_mtime_ns) + try: + with path.open("rb") as handle: + opened = os.fstat(handle.fileno()) + if (opened.st_dev, opened.st_ino, opened.st_size, opened.st_mtime_ns) != identity: + raise ApplicationUpdateError("apply intent changed before readback") + raw = handle.read(_MAX_INTENT_BYTES + 1) + after = path.lstat() + except ApplicationUpdateError: + raise + except OSError as exc: + raise ApplicationUpdateError("apply intent could not be read safely") from exc + if (after.st_dev, after.st_ino, after.st_size, after.st_mtime_ns) != identity or len(raw) != before.st_size: + raise ApplicationUpdateError("apply intent changed during readback") + try: + value = json.loads(raw.decode("utf-8"), object_pairs_hook=_strict_json_object) + except ApplicationUpdateError: + raise + except (UnicodeDecodeError, TypeError, ValueError) as exc: + raise ApplicationUpdateError("apply intent is not valid UTF-8 JSON") from exc + if not isinstance(value, dict) or frozenset(value) != _REQUIRED_KEYS: + raise ApplicationUpdateError("apply intent keys do not match schema") + if value["schema"] != APPLY_INTENT_SCHEMA or value["status"] != "ready": + raise ApplicationUpdateError("apply intent schema or status is invalid") + if value["authenticity"] != "same_publisher_authenticode_verified": + raise ApplicationUpdateError("apply intent lacks same-publisher authenticity") + return value + + +def _strict_json_object(pairs: list[tuple[str, Any]]) -> dict[str, Any]: + out: dict[str, Any] = {} + for key, value in pairs: + if key in out: + raise ApplicationUpdateError(f"apply intent contains duplicate key: {key}") + out[key] = value + return out + + +def _fsync_directory(path: Path) -> None: + flags = os.O_RDONLY | getattr(os, "O_DIRECTORY", 0) + try: + descriptor = os.open(path, flags) + except OSError: + return + try: + os.fsync(descriptor) + except OSError: + pass + finally: + os.close(descriptor) diff --git a/runtime_engine/scripture_archive_runtime/application_update_health.py b/runtime_engine/scripture_archive_runtime/application_update_health.py new file mode 100644 index 000000000..7f0f22b8b --- /dev/null +++ b/runtime_engine/scripture_archive_runtime/application_update_health.py @@ -0,0 +1,396 @@ +"""Durable post-update health receipt for rollback-preserving application updates. + +The standalone updater publishes this fixed-path receipt only after exact-byte atomic +publication and before relaunch. The new packaged application can later prove that +its own executable/version and the preserved rollback bytes still match the receipt +before disarming stale pending authority and rollback recovery state. +""" + +from __future__ import annotations + +from dataclasses import dataclass +import hashlib +import json +import os +from pathlib import Path +import stat +from typing import Any + +from .application_update import ApplicationUpdateError, SemVer +from .application_update_pending import discard_pending_update + + +HEALTH_RECEIPT_SCHEMA = "scripture.application-update-health.v1" +_HEALTH_RECEIPT_NAME = "update-health.json" +_ROLLBACK_SUFFIX = ".scripture-archive.rollback" +_COPY_CHUNK = 1024 * 1024 +_MAX_RECEIPT_BYTES = 4096 +_RECEIPT_KEYS = frozenset( + { + "schema", + "status", + "previous_version", + "target_version", + "installed_executable_name", + "previous_sha256", + "installed_sha256", + } +) + + +@dataclass(frozen=True) +class UpdateHealthReceipt: + previous_version: str + target_version: str + installed_executable_name: str + previous_sha256: str + installed_sha256: str + + +def publish_update_health_receipt( + staging_root: str | os.PathLike[str], + *, + previous_version: str, + target_version: str, + install_target: str | os.PathLike[str], + previous_sha256: str, + installed_sha256: str, +) -> UpdateHealthReceipt: + """Publish one fixed receipt after verifying installed and rollback exact bytes.""" + + SemVer.parse(previous_version) + SemVer.parse(target_version) + _require_sha256(previous_sha256) + _require_sha256(installed_sha256) + target = Path(install_target) + root = Path(staging_root) + _require_real_directory(root, "update staging root") + _require_regular_file(target, "installed application target") + rollback = target.with_name(target.name + _ROLLBACK_SUFFIX) + _require_regular_file(rollback, "rollback artifact") + if _sha256_file(target, "installed application target") != installed_sha256: + raise ApplicationUpdateError("installed bytes do not match health receipt identity") + if _sha256_file(rollback, "rollback artifact") != previous_sha256: + raise ApplicationUpdateError("rollback bytes do not match health receipt identity") + + receipt = UpdateHealthReceipt( + previous_version=previous_version, + target_version=target_version, + installed_executable_name=target.name, + previous_sha256=previous_sha256, + installed_sha256=installed_sha256, + ) + payload = _encode_receipt(receipt) + path = root / _HEALTH_RECEIPT_NAME + existing = _read_receipt_if_present(path) + if existing is not None: + if existing != receipt: + raise ApplicationUpdateError("existing update health receipt has different identity") + return receipt + _atomic_write(path, payload) + if _read_receipt(path) != receipt: + raise ApplicationUpdateError("published update health receipt failed readback") + return receipt + + +def inspect_update_health_receipt( + staging_root: str | os.PathLike[str], + *, + current_version: str, + install_target: str | os.PathLike[str], +) -> UpdateHealthReceipt | None: + """Re-verify a receipt against the currently running version and exact files.""" + + SemVer.parse(current_version) + root = Path(staging_root) + _require_real_directory(root, "update staging root") + path = root / _HEALTH_RECEIPT_NAME + receipt = _read_receipt_if_present(path) + if receipt is None: + return None + target = Path(install_target) + if receipt.target_version != current_version: + raise ApplicationUpdateError("update health receipt target version is not current") + if receipt.installed_executable_name != target.name: + raise ApplicationUpdateError("update health receipt executable identity changed") + _require_regular_file(target, "installed application target") + rollback = target.with_name(target.name + _ROLLBACK_SUFFIX) + _require_regular_file(rollback, "rollback artifact") + if _sha256_file(target, "installed application target") != receipt.installed_sha256: + raise ApplicationUpdateError("installed application bytes changed before health commit") + if _sha256_file(rollback, "rollback artifact") != receipt.previous_sha256: + raise ApplicationUpdateError("rollback bytes changed before health commit") + return receipt + + +def commit_update_health_receipt( + staging_root: str | os.PathLike[str], + *, + current_version: str, + install_target: str | os.PathLike[str], +) -> UpdateHealthReceipt | None: + """Commit a proven healthy relaunch and disarm stale update recovery authority. + + The fixed pending journal is removed first without parsing its old-version identity. + The health receipt is then removed before the rollback artifact, so a crash during + cleanup can leave at most inert rollback bytes rather than live rollback authority. + """ + + receipt = inspect_update_health_receipt( + staging_root, + current_version=current_version, + install_target=install_target, + ) + if receipt is None: + return None + root = Path(staging_root) + target = Path(install_target) + discard_pending_update(root) + _discard_regular_file(root / _HEALTH_RECEIPT_NAME, "update health receipt") + _discard_regular_file( + target.with_name(target.name + _ROLLBACK_SUFFIX), + "rollback artifact", + ) + return receipt + + +def discard_update_health_receipt(staging_root: str | os.PathLike[str]) -> bool: + """Disarm only the fixed health receipt, leaving recovery bytes untouched.""" + + root = Path(staging_root) + _require_real_directory(root, "update staging root") + path = root / _HEALTH_RECEIPT_NAME + try: + metadata = path.lstat() + except FileNotFoundError: + return False + except OSError as exc: + raise ApplicationUpdateError("update health receipt is unavailable") from exc + if stat.S_ISLNK(metadata.st_mode) or not stat.S_ISREG(metadata.st_mode): + raise ApplicationUpdateError("update health receipt must be a regular non-symlink file") + try: + path.unlink() + except OSError as exc: + raise ApplicationUpdateError("update health receipt could not be removed") from exc + return True + + +def _encode_receipt(receipt: UpdateHealthReceipt) -> bytes: + payload = { + "schema": HEALTH_RECEIPT_SCHEMA, + "status": "awaiting_health_commit", + "previous_version": receipt.previous_version, + "target_version": receipt.target_version, + "installed_executable_name": receipt.installed_executable_name, + "previous_sha256": receipt.previous_sha256, + "installed_sha256": receipt.installed_sha256, + } + return (json.dumps(payload, sort_keys=True, separators=(",", ":")) + "\n").encode("utf-8") + + +def _read_receipt_if_present(path: Path) -> UpdateHealthReceipt | None: + try: + path.lstat() + except FileNotFoundError: + return None + except OSError as exc: + raise ApplicationUpdateError("update health receipt is unavailable") from exc + return _read_receipt(path) + + +def _read_receipt(path: Path) -> UpdateHealthReceipt: + try: + before = path.lstat() + except OSError as exc: + raise ApplicationUpdateError("update health receipt is unavailable") from exc + if stat.S_ISLNK(before.st_mode) or not stat.S_ISREG(before.st_mode): + raise ApplicationUpdateError("update health receipt must be a regular non-symlink file") + if before.st_size > _MAX_RECEIPT_BYTES: + raise ApplicationUpdateError("update health receipt is unexpectedly large") + before_identity = (before.st_dev, before.st_ino, before.st_size, before.st_mtime_ns) + try: + with path.open("rb") as handle: + opened = os.fstat(handle.fileno()) + opened_identity = ( + opened.st_dev, + opened.st_ino, + opened.st_size, + opened.st_mtime_ns, + ) + if not stat.S_ISREG(opened.st_mode) or opened_identity != before_identity: + raise ApplicationUpdateError("update health receipt changed before readback") + raw = handle.read(_MAX_RECEIPT_BYTES + 1) + opened_after = os.fstat(handle.fileno()) + opened_after_identity = ( + opened_after.st_dev, + opened_after.st_ino, + opened_after.st_size, + opened_after.st_mtime_ns, + ) + if opened_after_identity != opened_identity: + raise ApplicationUpdateError("update health receipt changed during readback") + after = path.lstat() + except ApplicationUpdateError: + raise + except OSError as exc: + raise ApplicationUpdateError("update health receipt could not be read safely") from exc + after_identity = (after.st_dev, after.st_ino, after.st_size, after.st_mtime_ns) + if ( + after_identity != before_identity + or len(raw) != before.st_size + or len(raw) > _MAX_RECEIPT_BYTES + ): + raise ApplicationUpdateError("update health receipt changed during readback") + try: + payload: Any = json.loads(raw.decode("utf-8")) + except (UnicodeDecodeError, json.JSONDecodeError) as exc: + raise ApplicationUpdateError("update health receipt is invalid JSON") from exc + if not isinstance(payload, dict) or frozenset(payload) != _RECEIPT_KEYS: + raise ApplicationUpdateError("update health receipt shape is invalid") + if payload.get("schema") != HEALTH_RECEIPT_SCHEMA or payload.get("status") != "awaiting_health_commit": + raise ApplicationUpdateError("update health receipt schema/status is invalid") + fields = ( + payload.get("previous_version"), + payload.get("target_version"), + payload.get("installed_executable_name"), + payload.get("previous_sha256"), + payload.get("installed_sha256"), + ) + if not all(isinstance(value, str) for value in fields): + raise ApplicationUpdateError("update health receipt fields must be strings") + previous_version, target_version, executable_name, previous_sha, installed_sha = fields + SemVer.parse(previous_version) + SemVer.parse(target_version) + if not executable_name or Path(executable_name).name != executable_name: + raise ApplicationUpdateError("update health receipt executable name is invalid") + _require_sha256(previous_sha) + _require_sha256(installed_sha) + return UpdateHealthReceipt( + previous_version=previous_version, + target_version=target_version, + installed_executable_name=executable_name, + previous_sha256=previous_sha, + installed_sha256=installed_sha, + ) + + +def _atomic_write(path: Path, content: bytes) -> None: + temp = path.with_name(f".{path.name}.write-{os.getpid()}.tmp") + try: + metadata = temp.lstat() + except FileNotFoundError: + pass + except OSError as exc: + raise ApplicationUpdateError("health receipt temporary path is unavailable") from exc + else: + if stat.S_ISLNK(metadata.st_mode) or not stat.S_ISREG(metadata.st_mode): + raise ApplicationUpdateError("health receipt temporary path is unsafe") + try: + temp.unlink() + except OSError as exc: + raise ApplicationUpdateError("health receipt temporary path could not be cleared") from exc + try: + descriptor = os.open(temp, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600) + except OSError as exc: + raise ApplicationUpdateError("health receipt temporary file could not be created") from exc + try: + with os.fdopen(descriptor, "wb", closefd=True) as handle: + handle.write(content) + handle.flush() + os.fsync(handle.fileno()) + os.replace(temp, path) + _fsync_directory(path.parent) + except Exception: + try: + temp.unlink() + except OSError: + pass + raise + + +def _discard_regular_file(path: Path, label: str) -> None: + _require_regular_file(path, label) + try: + path.unlink() + except OSError as exc: + raise ApplicationUpdateError(f"{label} could not be removed") from exc + + +def _require_sha256(value: str) -> None: + if len(value) != 64 or any(ch not in "0123456789abcdef" for ch in value): + raise ApplicationUpdateError("update health SHA-256 identity is invalid") + + +def _require_regular_file(path: Path, label: str) -> None: + try: + metadata = path.lstat() + except OSError as exc: + raise ApplicationUpdateError(f"{label} is unavailable") from exc + if stat.S_ISLNK(metadata.st_mode) or not stat.S_ISREG(metadata.st_mode): + raise ApplicationUpdateError(f"{label} must be a regular non-symlink file") + + +def _require_real_directory(path: Path, label: str) -> None: + try: + metadata = path.lstat() + except OSError as exc: + raise ApplicationUpdateError(f"{label} is unavailable") from exc + if stat.S_ISLNK(metadata.st_mode) or not stat.S_ISDIR(metadata.st_mode): + raise ApplicationUpdateError(f"{label} must be a real directory") + + +def _sha256_file(path: Path, label: str) -> str: + try: + before = path.lstat() + except OSError as exc: + raise ApplicationUpdateError(f"{label} is unavailable") from exc + if stat.S_ISLNK(before.st_mode) or not stat.S_ISREG(before.st_mode): + raise ApplicationUpdateError(f"{label} must be a regular non-symlink file") + before_identity = (before.st_dev, before.st_ino, before.st_size, before.st_mtime_ns) + digest = hashlib.sha256() + try: + with path.open("rb") as handle: + opened = os.fstat(handle.fileno()) + opened_identity = ( + opened.st_dev, + opened.st_ino, + opened.st_size, + opened.st_mtime_ns, + ) + if not stat.S_ISREG(opened.st_mode) or opened_identity != before_identity: + raise ApplicationUpdateError(f"{label} changed before hashing") + while True: + chunk = handle.read(_COPY_CHUNK) + if not chunk: + break + digest.update(chunk) + opened_after = os.fstat(handle.fileno()) + opened_after_identity = ( + opened_after.st_dev, + opened_after.st_ino, + opened_after.st_size, + opened_after.st_mtime_ns, + ) + if opened_after_identity != opened_identity: + raise ApplicationUpdateError(f"{label} changed during hashing") + after = path.lstat() + except ApplicationUpdateError: + raise + except OSError as exc: + raise ApplicationUpdateError(f"{label} could not be hashed safely") from exc + after_identity = (after.st_dev, after.st_ino, after.st_size, after.st_mtime_ns) + if after_identity != before_identity: + raise ApplicationUpdateError(f"{label} changed during hashing") + return digest.hexdigest() + + +def _fsync_directory(path: Path) -> None: + flags = os.O_RDONLY | getattr(os, "O_DIRECTORY", 0) + try: + descriptor = os.open(path, flags) + except OSError: + return + try: + os.fsync(descriptor) + finally: + os.close(descriptor) diff --git a/runtime_engine/scripture_archive_runtime/application_update_parent_wait.py b/runtime_engine/scripture_archive_runtime/application_update_parent_wait.py new file mode 100644 index 000000000..a802b2243 --- /dev/null +++ b/runtime_engine/scripture_archive_runtime/application_update_parent_wait.py @@ -0,0 +1,97 @@ +from __future__ import annotations + +import ctypes +from ctypes import wintypes +import os +from typing import Callable + + +class ParentProcessWaitError(RuntimeError): + """The updater could not prove that the application process exited.""" + + +_SYNCHRONIZE = 0x00100000 +_WAIT_OBJECT_0 = 0x00000000 +_WAIT_TIMEOUT = 0x00000102 +_WAIT_FAILED = 0xFFFFFFFF +_DEFAULT_TIMEOUT_MS = 120_000 + + +def _validate_parent_pid(parent_pid: int) -> int: + if not isinstance(parent_pid, int) or isinstance(parent_pid, bool) or parent_pid <= 0: + raise ParentProcessWaitError("parent pid must be a positive integer") + if parent_pid == os.getpid(): + raise ParentProcessWaitError("updater cannot wait on its own process") + return parent_pid + + +def _windows_wait_backend(parent_pid: int, timeout_ms: int) -> None: + try: + kernel32 = ctypes.WinDLL("kernel32", use_last_error=True) + except (AttributeError, OSError) as exc: + raise ParentProcessWaitError("Windows synchronization API is unavailable") from exc + + open_process = kernel32.OpenProcess + open_process.argtypes = (wintypes.DWORD, wintypes.BOOL, wintypes.DWORD) + open_process.restype = wintypes.HANDLE + + wait_for_single_object = kernel32.WaitForSingleObject + wait_for_single_object.argtypes = (wintypes.HANDLE, wintypes.DWORD) + wait_for_single_object.restype = wintypes.DWORD + + close_handle = kernel32.CloseHandle + close_handle.argtypes = (wintypes.HANDLE,) + close_handle.restype = wintypes.BOOL + + handle = open_process(_SYNCHRONIZE, False, parent_pid) + if not handle: + raise ParentProcessWaitError("cannot open parent process for synchronization") + + try: + result = wait_for_single_object(handle, timeout_ms) + finally: + close_handle(handle) + + if result == _WAIT_OBJECT_0: + return + if result == _WAIT_TIMEOUT: + raise ParentProcessWaitError("parent process did not exit before timeout") + if result == _WAIT_FAILED: + raise ParentProcessWaitError("waiting for parent process failed") + raise ParentProcessWaitError("unexpected parent wait result") + + +def wait_for_parent_exit( + parent_pid: int, + *, + timeout_ms: int = _DEFAULT_TIMEOUT_MS, + wait_backend: Callable[[int, int], None] | None = None, + os_name: str | None = None, +) -> None: + """Prove that the old packaged application has exited before replacement. + + Production Windows execution uses the kernel process handle as the waitable + authority. There is deliberately no polling loop, sleep, process-name + lookup, shell command, or browser-controlled timeout. Tests may inject a + backend to verify ordering without weakening production behavior. + """ + + pid = _validate_parent_pid(parent_pid) + if not isinstance(timeout_ms, int) or isinstance(timeout_ms, bool): + raise ParentProcessWaitError("timeout must be an integer") + if timeout_ms <= 0 or timeout_ms > _DEFAULT_TIMEOUT_MS: + raise ParentProcessWaitError("timeout is outside the permitted bound") + + backend = wait_backend + if backend is None: + effective_os_name = os.name if os_name is None else os_name + if effective_os_name != "nt": + raise ParentProcessWaitError("native parent wait is Windows-only") + backend = _windows_wait_backend + + try: + backend(pid, timeout_ms) + except ParentProcessWaitError: + raise + except Exception as exc: + raise ParentProcessWaitError("parent process wait failed") from exc diff --git a/runtime_engine/scripture_archive_runtime/application_update_pending.py b/runtime_engine/scripture_archive_runtime/application_update_pending.py new file mode 100644 index 000000000..136235e92 --- /dev/null +++ b/runtime_engine/scripture_archive_runtime/application_update_pending.py @@ -0,0 +1,291 @@ +"""Fail-closed readback and disarm semantics for a staged application update. + +This module deliberately does not install, execute, replace, restart, or roll back +application code. It gives the packaged host a durable way to re-open the fixed +pending-update journal after restart, bind it back to exact staged bytes, and remove +only the journal authority when the user cancels a pending update. +""" + +from __future__ import annotations + +from dataclasses import dataclass +import json +import os +from pathlib import Path +import stat +import threading +from typing import Any + +from .application_update import ( + ApplicationUpdateError, + ApplicationUpdateManifest, + verify_local_update, +) +from .application_update_staging import STAGING_JOURNAL_SCHEMA + + +_JOURNAL_NAME = "pending-update.json" +_PENDING_DIRECTORY = "pending" +_MAX_JOURNAL_BYTES = 16 * 1024 +_REQUIRED_KEYS = frozenset( + { + "schema", + "status", + "product_id", + "target_platform", + "current_version", + "target_version", + "source_head", + "artifact_name", + "artifact_size", + "artifact_sha256", + "authenticity", + } +) +_STATE_LOCKS_GUARD = threading.Lock() +_STATE_LOCKS: dict[str, threading.RLock] = {} + + +@dataclass(frozen=True) +class PendingApplicationUpdate: + product_id: str + target_platform: str + current_version: str + target_version: str + source_head: str + artifact_name: str + artifact_size: int + artifact_sha256: str + authenticity: str = "same_publisher_authenticode_verified" + status: str = "staged" + + +def inspect_pending_update( + staging_root: str | os.PathLike[str], + *, + current_version: str, +) -> PendingApplicationUpdate | None: + """Re-open a fixed pending journal and re-verify its exact staged bytes. + + ``None`` means there is no pending journal. Any present but malformed, stale, + redirected, or byte-mismatched state raises ``ApplicationUpdateError`` rather + than being presented as an installable update. + """ + + root = Path(staging_root) + lock = _state_lock_for_root(root) + with lock: + if not root.exists(): + return None + _require_real_directory(root, "update state root") + journal = root / _JOURNAL_NAME + payload = _read_fixed_journal(journal) + if payload is None: + return None + row = _parse_journal(payload) + if row["current_version"] != current_version: + raise ApplicationUpdateError( + "pending update was staged by a different current application version" + ) + + manifest = ApplicationUpdateManifest.from_mapping( + { + "schema": "scripture.application-update.v1", + "product_id": row["product_id"], + "target_platform": row["target_platform"], + "target_version": row["target_version"], + "source_head": row["source_head"], + "artifact_name": row["artifact_name"], + "artifact_size": row["artifact_size"], + "artifact_sha256": row["artifact_sha256"], + } + ) + pending_root = root / _PENDING_DIRECTORY + digest_root = pending_root / manifest.artifact_sha256 + _require_real_directory(pending_root, "pending update directory") + _require_real_directory(digest_root, "pending digest directory") + artifact = digest_root / manifest.artifact_name + verified = verify_local_update( + manifest, + artifact, + current_version=current_version, + ) + return PendingApplicationUpdate( + product_id=verified.product_id, + target_platform=verified.target_platform, + current_version=verified.current_version, + target_version=verified.target_version, + source_head=verified.source_head, + artifact_name=verified.artifact_name, + artifact_size=verified.artifact_size, + artifact_sha256=verified.artifact_sha256, + ) + + +def staged_artifact_path( + staging_root: str | os.PathLike[str], + pending: PendingApplicationUpdate, +) -> Path: + """Reconstruct the host-private staged path from already-validated identity. + + Callers must never serialize this path into browser-visible transport data. + ``inspect_pending_update`` should be called again after any signature operation + to bind that result back to exact bytes. + """ + + if not isinstance(pending, PendingApplicationUpdate): + raise ApplicationUpdateError("pending update identity is invalid") + root = Path(staging_root) + _require_real_directory(root, "update state root") + pending_root = root / _PENDING_DIRECTORY + digest_root = pending_root / pending.artifact_sha256 + _require_real_directory(pending_root, "pending update directory") + _require_real_directory(digest_root, "pending digest directory") + return digest_root / pending.artifact_name + + +def discard_pending_update(staging_root: str | os.PathLike[str]) -> bool: + """Disarm pending authority without deleting staged executable bytes. + + Cancellation intentionally removes only the fixed journal. Staged bytes become + inert and may be overwritten by a later staging operation. This avoids turning + recovery into a recursive deletion primitive when journal contents are corrupt. + The fixed journal path may itself be a symlink; unlinking that symlink is safe and + does not touch its target. + """ + + root = Path(staging_root) + lock = _state_lock_for_root(root) + with lock: + if not root.exists(): + return False + _require_real_directory(root, "update state root") + journal = root / _JOURNAL_NAME + try: + metadata = journal.lstat() + except FileNotFoundError: + return False + except OSError as exc: + raise ApplicationUpdateError("pending update journal is unavailable") from exc + if not (stat.S_ISREG(metadata.st_mode) or stat.S_ISLNK(metadata.st_mode)): + raise ApplicationUpdateError("pending update journal path is unsafe") + try: + journal.unlink() + _fsync_directory(root) + except OSError as exc: + raise ApplicationUpdateError("pending update could not be cancelled safely") from exc + return True + + +def _parse_journal(payload: bytes) -> dict[str, Any]: + try: + raw = json.loads(payload.decode("utf-8"), object_pairs_hook=_strict_json_object) + except ApplicationUpdateError: + raise + except (UnicodeDecodeError, TypeError, ValueError) as exc: + raise ApplicationUpdateError("pending update journal is not valid UTF-8 JSON") from exc + if not isinstance(raw, dict): + raise ApplicationUpdateError("pending update journal must be an object") + keys = frozenset(raw.keys()) + if keys != _REQUIRED_KEYS: + raise ApplicationUpdateError("pending update journal keys do not match the staging schema") + if raw["schema"] != STAGING_JOURNAL_SCHEMA: + raise ApplicationUpdateError("unsupported pending update journal schema") + if raw["status"] != "staged": + raise ApplicationUpdateError("pending update journal is not in staged state") + if raw["authenticity"] != "same_publisher_authenticode_verified": + raise ApplicationUpdateError("pending update journal lacks same-publisher authenticity") + current_version = raw["current_version"] + if not isinstance(current_version, str) or not current_version or len(current_version) > 128: + raise ApplicationUpdateError("pending update current_version is invalid") + return raw + + +def _read_fixed_journal(path: Path) -> bytes | None: + try: + before = path.lstat() + except FileNotFoundError: + return None + except OSError as exc: + raise ApplicationUpdateError("pending update journal is unavailable") from exc + if stat.S_ISLNK(before.st_mode) or not stat.S_ISREG(before.st_mode): + raise ApplicationUpdateError("pending update journal must be a regular non-symlink file") + if before.st_size <= 0 or before.st_size > _MAX_JOURNAL_BYTES: + raise ApplicationUpdateError("pending update journal is empty or exceeds the size limit") + before_identity = (before.st_dev, before.st_ino, before.st_size, before.st_mtime_ns) + try: + with path.open("rb") as handle: + opened = os.fstat(handle.fileno()) + opened_identity = ( + opened.st_dev, + opened.st_ino, + opened.st_size, + opened.st_mtime_ns, + ) + if opened_identity != before_identity or not stat.S_ISREG(opened.st_mode): + raise ApplicationUpdateError("pending update journal changed before readback") + payload = handle.read(_MAX_JOURNAL_BYTES + 1) + opened_after = os.fstat(handle.fileno()) + after_open_identity = ( + opened_after.st_dev, + opened_after.st_ino, + opened_after.st_size, + opened_after.st_mtime_ns, + ) + if after_open_identity != opened_identity: + raise ApplicationUpdateError("pending update journal changed during readback") + after = path.lstat() + except ApplicationUpdateError: + raise + except OSError as exc: + raise ApplicationUpdateError("pending update journal could not be read safely") from exc + after_identity = (after.st_dev, after.st_ino, after.st_size, after.st_mtime_ns) + if ( + after_identity != before_identity + or len(payload) != before.st_size + or len(payload) > _MAX_JOURNAL_BYTES + ): + raise ApplicationUpdateError("pending update journal changed during readback") + return payload + + +def _strict_json_object(pairs: list[tuple[str, Any]]) -> dict[str, Any]: + out: dict[str, Any] = {} + for key, value in pairs: + if key in out: + raise ApplicationUpdateError(f"pending update journal contains duplicate key: {key}") + out[key] = value + return out + + +def _require_real_directory(path: Path, label: str) -> None: + try: + metadata = path.lstat() + except OSError as exc: + raise ApplicationUpdateError(f"{label} is unavailable") from exc + if stat.S_ISLNK(metadata.st_mode) or not stat.S_ISDIR(metadata.st_mode): + raise ApplicationUpdateError(f"{label} must be a real directory") + + +def _state_lock_for_root(root: Path) -> threading.RLock: + key = os.path.normcase(str(root.absolute())) + with _STATE_LOCKS_GUARD: + lock = _STATE_LOCKS.get(key) + if lock is None: + lock = threading.RLock() + _STATE_LOCKS[key] = lock + return lock + + +def _fsync_directory(path: Path) -> None: + flags = os.O_RDONLY | getattr(os, "O_DIRECTORY", 0) + try: + descriptor = os.open(path, flags) + except OSError: + return + try: + os.fsync(descriptor) + except OSError: + pass + finally: + os.close(descriptor) diff --git a/runtime_engine/scripture_archive_runtime/application_update_process.py b/runtime_engine/scripture_archive_runtime/application_update_process.py new file mode 100644 index 000000000..6fd50fdc9 --- /dev/null +++ b/runtime_engine/scripture_archive_runtime/application_update_process.py @@ -0,0 +1,189 @@ +from __future__ import annotations + +from dataclasses import dataclass +import os +from pathlib import Path +import subprocess +from typing import Callable, Sequence + + +class UpdateProcessError(RuntimeError): + """Fail-closed updater process orchestration error.""" + + +@dataclass(frozen=True) +class UpdaterProcessPlan: + """Host-owned immutable launch plan for the separate updater process. + + The browser never supplies any value represented here. The updater must + still independently re-open and verify its durable apply authority before + mutating installed bytes; this plan only separates the updater from the + application process that is about to exit. + """ + + updater_executable: Path + installed_executable: Path + staging_root: Path + parent_pid: int + + def argv(self) -> tuple[str, ...]: + return ( + str(self.updater_executable), + "--scripture-archive-apply", + "--wait-pid", + str(self.parent_pid), + "--installed-executable", + str(self.installed_executable), + "--staging-root", + str(self.staging_root), + ) + + +def _require_plain_file(path: Path, *, label: str) -> Path: + try: + path.lstat() + except OSError as exc: + raise UpdateProcessError(f"{label} is unavailable") from exc + if path.is_symlink() or not path.is_file(): + raise UpdateProcessError(f"{label} must be a regular non-symlink file") + try: + resolved = path.resolve(strict=True) + except OSError as exc: + raise UpdateProcessError(f"{label} cannot be resolved") from exc + if not resolved.is_file(): + raise UpdateProcessError(f"{label} must resolve to a regular file") + return resolved + + +def _require_plain_directory(path: Path, *, label: str) -> Path: + try: + path.lstat() + except OSError as exc: + raise UpdateProcessError(f"{label} is unavailable") from exc + if path.is_symlink() or not path.is_dir(): + raise UpdateProcessError(f"{label} must be a real directory") + try: + resolved = path.resolve(strict=True) + except OSError as exc: + raise UpdateProcessError(f"{label} cannot be resolved") from exc + if not resolved.is_dir(): + raise UpdateProcessError(f"{label} must resolve to a directory") + return resolved + + +def build_updater_process_plan( + *, + updater_executable: Path, + installed_executable: Path, + staging_root: Path, + parent_pid: int | None = None, +) -> UpdaterProcessPlan: + """Build a fixed host-side process handoff. + + The updater executable is required to be a sibling of the installed + application. This prevents PATH/current-directory substitution and keeps + the launch target inside the packaged installation boundary. The staging + root remains separate and is only an authority location; the updater core + is responsible for reconstructing and re-verifying candidate bytes from + the durable apply handoff. + """ + + updater = _require_plain_file(Path(updater_executable), label="updater executable") + installed = _require_plain_file(Path(installed_executable), label="installed executable") + staging = _require_plain_directory(Path(staging_root), label="staging root") + + if updater.parent != installed.parent: + raise UpdateProcessError("updater executable must be packaged beside the installed application") + if updater == installed: + raise UpdateProcessError("updater executable must be distinct from the installed application") + + current_pid = os.getpid() + effective_parent_pid = current_pid if parent_pid is None else parent_pid + if not isinstance(effective_parent_pid, int) or isinstance(effective_parent_pid, bool): + raise UpdateProcessError("parent pid must be an integer") + if effective_parent_pid <= 0: + raise UpdateProcessError("parent pid must be positive") + if effective_parent_pid != current_pid: + raise UpdateProcessError("parent pid must identify the current host process") + + return UpdaterProcessPlan( + updater_executable=updater, + installed_executable=installed, + staging_root=staging, + parent_pid=effective_parent_pid, + ) + + +def launch_updater_process( + plan: UpdaterProcessPlan, + *, + popen: Callable[..., object] = subprocess.Popen, + os_name: str | None = None, +) -> int: + """Launch the separate updater without shell interpretation. + + On Windows the process is detached into its own process group so it can + survive normal application shutdown. No browser transport command is + added and no arbitrary command-line suffix is accepted. + """ + + if not isinstance(plan, UpdaterProcessPlan): + raise UpdateProcessError("invalid updater process plan") + + creationflags = 0 + effective_os_name = os.name if os_name is None else os_name + if effective_os_name == "nt": + creationflags = ( + getattr(subprocess, "CREATE_NEW_PROCESS_GROUP", 0) + | getattr(subprocess, "DETACHED_PROCESS", 0) + ) + + try: + child = popen( + list(plan.argv()), + cwd=str(plan.installed_executable.parent), + shell=False, + close_fds=True, + creationflags=creationflags, + ) + except Exception as exc: + raise UpdateProcessError("failed to launch updater process") from exc + + pid = getattr(child, "pid", None) + if not isinstance(pid, int) or isinstance(pid, bool) or pid <= 0: + raise UpdateProcessError("updater process did not return a valid pid") + return pid + + +def parse_trusted_updater_argv(argv: Sequence[str]) -> tuple[int, Path, Path]: + """Parse only the fixed updater command generated by ``UpdaterProcessPlan``. + + This is intentionally not a general CLI parser. Exact positional shape, + marker and flag order are part of the host/updater contract; extra flags or + duplicated options fail closed. The updater must subsequently apply the + same filesystem validation and durable-authority verification as its core. + """ + + values = tuple(argv) + if len(values) != 7: + raise UpdateProcessError("invalid updater command shape") + marker, wait_flag, wait_value, installed_flag, installed_value, staging_flag, staging_value = values + if marker != "--scripture-archive-apply": + raise UpdateProcessError("invalid updater command marker") + if wait_flag != "--wait-pid": + raise UpdateProcessError("invalid updater wait flag") + if installed_flag != "--installed-executable": + raise UpdateProcessError("invalid installed executable flag") + if staging_flag != "--staging-root": + raise UpdateProcessError("invalid staging root flag") + try: + parent_pid = int(wait_value, 10) + except (TypeError, ValueError) as exc: + raise UpdateProcessError("invalid parent pid") from exc + if parent_pid <= 0 or str(parent_pid) != wait_value: + raise UpdateProcessError("invalid parent pid") + if not installed_value or "\x00" in installed_value: + raise UpdateProcessError("invalid installed executable path") + if not staging_value or "\x00" in staging_value: + raise UpdateProcessError("invalid staging root path") + return parent_pid, Path(installed_value), Path(staging_value) diff --git a/runtime_engine/scripture_archive_runtime/application_update_relaunch.py b/runtime_engine/scripture_archive_runtime/application_update_relaunch.py new file mode 100644 index 000000000..c592e89db --- /dev/null +++ b/runtime_engine/scripture_archive_runtime/application_update_relaunch.py @@ -0,0 +1,53 @@ +"""Trusted post-update application relaunch boundary. + +The standalone updater owns this boundary after a successful atomic apply. It launches +only the exact installed target returned by the canonical apply consumer, never a browser- +supplied command line, and never through a shell. +""" + +from __future__ import annotations + +import os +from pathlib import Path +import stat +import subprocess +from typing import Callable + +from .application_update import ApplicationUpdateError + + +ProcessSpawner = Callable[..., object] + + +def launch_installed_application( + install_target: str | os.PathLike[str], + *, + spawn: ProcessSpawner = subprocess.Popen, +) -> None: + """Launch the exact installed executable without shell interpretation. + + This proves the target is still a regular non-symlink file immediately before + process creation and fixes the child working directory to the real install + directory. Successful process creation is the only claim here; later health + confirmation remains a separate post-restart responsibility. + """ + + if not callable(spawn): + raise ApplicationUpdateError("application process spawner is required") + + target = Path(install_target) + try: + target_meta = target.lstat() + parent_meta = target.parent.lstat() + except OSError as exc: + raise ApplicationUpdateError("installed application could not be inspected for relaunch") from exc + + if stat.S_ISLNK(target_meta.st_mode) or not stat.S_ISREG(target_meta.st_mode): + raise ApplicationUpdateError("installed application relaunch target must be a regular non-symlink file") + if stat.S_ISLNK(parent_meta.st_mode) or not stat.S_ISDIR(parent_meta.st_mode): + raise ApplicationUpdateError("installed application directory must be a real directory") + + try: + spawn((str(target),), cwd=str(target.parent), close_fds=True) + except (OSError, ValueError) as exc: + raise ApplicationUpdateError("updated application process could not be started") from exc diff --git a/runtime_engine/scripture_archive_runtime/application_update_runner.py b/runtime_engine/scripture_archive_runtime/application_update_runner.py new file mode 100644 index 000000000..b923237eb --- /dev/null +++ b/runtime_engine/scripture_archive_runtime/application_update_runner.py @@ -0,0 +1,170 @@ +"""Trusted standalone updater execution boundary. + +This module connects the fixed host-owned updater command from +``application_update_process`` to the bounded parent-exit barrier and the existing +atomic apply/rollback consumer. It is deliberately not exposed through browser +transport and does not introduce a second update implementation. +""" + +from __future__ import annotations + +from collections.abc import Callable, Sequence +from pathlib import Path +from typing import TypeAlias + +from .application_update import ApplicationUpdateError, SemVer +from .application_update_health import ( + discard_update_health_receipt, + publish_update_health_receipt, +) +from .application_update_parent_wait import wait_for_parent_exit +from .application_update_process import parse_trusted_updater_argv +from .application_update_relaunch import launch_installed_application +from .application_update_updater import ( + UpdateApplyResult, + consume_apply_handoff, + rollback_installed_update, +) + + +PublisherVerifier: TypeAlias = Callable[[Path, Path], bool] +ApplicationLauncher: TypeAlias = Callable[[Path], None] +RollbackConsumer: TypeAlias = Callable[..., str] +HealthPublisher: TypeAlias = Callable[..., object] +HealthDiscarder: TypeAlias = Callable[[Path], bool] + + +def _rollback_then_disarm_health( + installed_executable: Path, + staging_root: Path, + *, + previous_sha256: str, + rollback: RollbackConsumer, + discard_health: HealthDiscarder, + rollback_failure_message: str, + disarm_failure_message: str, +) -> None: + """Restore prior bytes before disarming health authority. + + If rollback itself fails, the receipt is intentionally preserved: that durable + exact-byte identity is most valuable in the worst recovery state. Only a proven + successful rollback permits receipt disarm. + """ + + try: + rollback(installed_executable, expected_previous_sha256=previous_sha256) + except Exception as rollback_error: + raise ApplicationUpdateError(rollback_failure_message) from rollback_error + try: + discard_health(staging_root) + except Exception as discard_error: + raise ApplicationUpdateError(disarm_failure_message) from discard_error + + +def execute_trusted_updater( + argv: Sequence[str], + *, + current_version: str, + verify_same_publisher: PublisherVerifier, + wait_for_exit: Callable[[int], None] = wait_for_parent_exit, + consume: Callable[..., UpdateApplyResult] = consume_apply_handoff, + launch: ApplicationLauncher = launch_installed_application, + rollback: RollbackConsumer = rollback_installed_update, + publish_health: HealthPublisher = publish_update_health_receipt, + discard_health: HealthDiscarder = discard_update_health_receipt, +) -> UpdateApplyResult: + """Execute one trusted updater invocation in fail-closed order. + + The old application is proven exited before replacement. After canonical atomic + apply, a durable exact-byte health receipt is published before relaunch while the + prior rollback bytes still exist. The new application later commits that receipt + only after its packaged native/frontend bridge is healthy. If receipt publication + or process creation fails, prior bytes are restored before receipt disarm. A failed + rollback deliberately preserves the receipt for recovery evidence. + """ + + if not isinstance(current_version, str): + raise ApplicationUpdateError("trusted updater current version must be a string") + SemVer.parse(current_version) + for dependency, label in ( + (verify_same_publisher, "same-publisher verifier"), + (wait_for_exit, "parent-exit waiter"), + (consume, "apply consumer"), + (launch, "application launcher"), + (rollback, "rollback consumer"), + (publish_health, "health receipt publisher"), + (discard_health, "health receipt discarder"), + ): + if not callable(dependency): + raise ApplicationUpdateError(f"{label} is required") + + parent_pid, installed_executable, staging_root = parse_trusted_updater_argv(argv) + wait_for_exit(parent_pid) + + result = consume( + staging_root, + current_version=current_version, + install_target=installed_executable, + verify_same_publisher=verify_same_publisher, + ) + if result.target_path != installed_executable: + try: + rollback(installed_executable, expected_previous_sha256=result.previous_sha256) + except Exception as rollback_error: + raise ApplicationUpdateError( + "apply consumer returned an unexpected install target and rollback failed" + ) from rollback_error + raise ApplicationUpdateError( + "apply consumer returned an unexpected install target; rollback restored prior bytes" + ) + + try: + publish_health( + staging_root, + previous_version=current_version, + target_version=result.target_version, + install_target=installed_executable, + previous_sha256=result.previous_sha256, + installed_sha256=result.installed_sha256, + ) + except Exception as health_error: + try: + _rollback_then_disarm_health( + installed_executable, + staging_root, + previous_sha256=result.previous_sha256, + rollback=rollback, + discard_health=discard_health, + rollback_failure_message="health receipt publication failed and rollback also failed", + disarm_failure_message=( + "health receipt publication failed; rollback restored prior bytes but receipt disarm failed" + ), + ) + except ApplicationUpdateError as recovery_error: + raise recovery_error from health_error + raise ApplicationUpdateError( + "health receipt publication failed; rollback restored prior bytes" + ) from health_error + + try: + launch(installed_executable) + except Exception as launch_error: + try: + _rollback_then_disarm_health( + installed_executable, + staging_root, + previous_sha256=result.previous_sha256, + rollback=rollback, + discard_health=discard_health, + rollback_failure_message="updated application relaunch failed and rollback also failed", + disarm_failure_message=( + "updated application relaunch failed; rollback restored prior bytes but receipt disarm failed" + ), + ) + except ApplicationUpdateError as recovery_error: + raise recovery_error from launch_error + raise ApplicationUpdateError( + "updated application relaunch failed; rollback restored prior bytes" + ) from launch_error + + return result diff --git a/runtime_engine/scripture_archive_runtime/application_update_updater.py b/runtime_engine/scripture_archive_runtime/application_update_updater.py new file mode 100644 index 000000000..666d2c246 --- /dev/null +++ b/runtime_engine/scripture_archive_runtime/application_update_updater.py @@ -0,0 +1,477 @@ +"""Standalone atomic consumer for a verified application-update apply handoff. + +This module is intentionally not exposed through browser transport. A trusted host/updater +process supplies the fixed staging root and exact installed executable path. The consumer +re-opens the durable apply handoff, re-verifies the staged bytes and publisher, preserves a +same-directory rollback copy, atomically replaces the target, and rolls back automatically +when installed-byte verification fails. +""" + +from __future__ import annotations + +from contextlib import contextmanager +from dataclasses import dataclass +import hashlib +import os +from pathlib import Path +import shutil +import stat +from typing import Callable + +from .application_update import ApplicationUpdateError +from .application_update_apply import discard_apply_handoff, inspect_apply_handoff +from .application_update_pending import PendingApplicationUpdate, staged_artifact_path + + +_ROLLBACK_SUFFIX = ".scripture-archive.rollback" +_COPY_CHUNK = 1024 * 1024 + + +@dataclass(frozen=True) +class UpdateApplyResult: + previous_sha256: str + installed_sha256: str + rollback_path: Path + target_path: Path + target_version: str + + +def consume_apply_handoff( + staging_root: str | os.PathLike[str], + *, + current_version: str, + install_target: str | os.PathLike[str], + verify_same_publisher: Callable[[Path, Path], bool], +) -> UpdateApplyResult: + """Serialize and consume one verified apply handoff across updater processes.""" + + root = Path(staging_root) + with _exclusive_update_lock(root): + return _consume_apply_handoff_locked( + root, + current_version=current_version, + install_target=install_target, + verify_same_publisher=verify_same_publisher, + ) + + +def _consume_apply_handoff_locked( + staging_root: str | os.PathLike[str], + *, + current_version: str, + install_target: str | os.PathLike[str], + verify_same_publisher: Callable[[Path, Path], bool], +) -> UpdateApplyResult: + """Atomically replace one installed executable from the fixed verified handoff. + + The caller must be a trusted standalone updater/host boundary. ``install_target`` is + never accepted from browser transport. The existing target and staged candidate must + both be regular non-symlink files. Publisher verification is repeated immediately + before replacement and exact SHA-256 is checked both before and after publication. + """ + + if not callable(verify_same_publisher): + raise ApplicationUpdateError("same-publisher verifier is required") + + root = Path(staging_root) + target = Path(install_target) + pending = inspect_apply_handoff(root, current_version=current_version) + if pending is None: + raise ApplicationUpdateError("no verified apply handoff is available") + + staged = staged_artifact_path(root, pending) + _require_regular_file(staged, "staged update artifact") + _require_regular_file(target, "installed application target") + _require_safe_parent(target.parent) + + if staged.name != pending.artifact_name: + raise ApplicationUpdateError("staged artifact name does not match apply handoff") + staged_identity = _file_identity(staged, "staged update artifact") + target_identity = _file_identity(target, "installed application target") + if _sha256_file(staged) != pending.artifact_sha256: + raise ApplicationUpdateError("staged artifact bytes changed before apply") + previous_sha = _sha256_file(target) + if not verify_same_publisher(target, staged): + raise ApplicationUpdateError("staged artifact failed same-publisher verification") + if _file_identity(staged, "staged update artifact") != staged_identity: + raise ApplicationUpdateError("staged artifact changed during publisher verification (identity)") + if _file_identity(target, "installed application target") != target_identity: + raise ApplicationUpdateError("installed application target changed during publisher verification (identity)") + if _sha256_file(staged) != pending.artifact_sha256: + raise ApplicationUpdateError("staged artifact bytes changed during publisher verification") + if _sha256_file(target) != previous_sha: + raise ApplicationUpdateError("installed application target changed during publisher verification") + rebound = inspect_apply_handoff(root, current_version=current_version) + if rebound != pending: + raise ApplicationUpdateError("apply handoff changed during publisher verification") + + rollback = target.with_name(target.name + _ROLLBACK_SUFFIX) + if _file_identity(target, "installed application target") != target_identity: + raise ApplicationUpdateError("installed application target identity changed before rollback capture") + _publish_rollback_copy(target, rollback, previous_sha) + + candidate = target.with_name(f".{target.name}.update-{os.getpid()}.tmp") + _prepare_temp_slot(candidate) + published = False + try: + if _file_identity(staged, "staged update artifact") != staged_identity: + raise ApplicationUpdateError("staged artifact identity changed before install copy") + _copy_exact(staged, candidate) + if _sha256_file(candidate) != pending.artifact_sha256: + raise ApplicationUpdateError("temporary install candidate failed exact-byte verification") + final_handoff = inspect_apply_handoff(root, current_version=current_version) + if final_handoff != pending: + raise ApplicationUpdateError("apply handoff changed before atomic publication") + if _file_identity(target, "installed application target") != target_identity: + raise ApplicationUpdateError("installed application target identity changed before atomic publication") + os.replace(candidate, target) + published = True + _fsync_directory(target.parent) + _require_regular_file(target, "installed application target") + installed_sha = _sha256_file(target) + if installed_sha != pending.artifact_sha256: + raise ApplicationUpdateError("installed artifact failed exact-byte verification") + 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() + except OSError: + pass + if published or (not target.exists() and rollback.exists()): + try: + _rollback_replace(target, rollback, previous_sha) + except Exception as rollback_error: + raise ApplicationUpdateError( + "update apply failed and automatic rollback also failed" + ) from rollback_error + if published: + raise ApplicationUpdateError( + "update apply failed after publication; rollback restored" + ) from apply_error + raise + + return UpdateApplyResult( + previous_sha256=previous_sha, + installed_sha256=pending.artifact_sha256, + rollback_path=rollback, + target_path=target, + target_version=pending.target_version, + ) + + +def rollback_installed_update( + install_target: str | os.PathLike[str], + *, + expected_previous_sha256: str, +) -> str: + """Restore the fixed same-directory rollback copy and verify exact prior bytes.""" + + target = Path(install_target) + _require_safe_sha256(expected_previous_sha256) + _require_safe_parent(target.parent) + rollback = target.with_name(target.name + _ROLLBACK_SUFFIX) + _require_regular_file(rollback, "rollback artifact") + _rollback_replace(target, rollback, expected_previous_sha256) + return expected_previous_sha256 + + +def _rollback_replace(target: Path, rollback: Path, expected_sha: str) -> None: + _require_regular_file(rollback, "rollback artifact") + if _sha256_file(rollback) != expected_sha: + raise ApplicationUpdateError("rollback artifact does not match expected prior bytes") + restore = target.with_name(f".{target.name}.rollback-{os.getpid()}.tmp") + _prepare_temp_slot(restore) + try: + _copy_exact(rollback, restore) + if _sha256_file(restore) != expected_sha: + raise ApplicationUpdateError("rollback temporary copy failed exact-byte verification") + os.replace(restore, target) + _fsync_directory(target.parent) + finally: + try: + restore.unlink() + except OSError: + pass + _require_regular_file(target, "restored application target") + if _sha256_file(target) != expected_sha: + raise ApplicationUpdateError("rollback restoration failed exact-byte verification") + + +@contextmanager +def _exclusive_update_lock(root: Path): + """Hold one non-blocking OS lock for the complete standalone apply transaction.""" + + _require_safe_parent(root) + lock_path = root / ".apply-update.lock" + flags = os.O_RDWR | os.O_CREAT | getattr(os, "O_NOFOLLOW", 0) + try: + descriptor = os.open(lock_path, flags, 0o600) + except OSError as exc: + raise ApplicationUpdateError("updater lock could not be opened safely") from exc + + locked = False + try: + opened = os.fstat(descriptor) + linked = lock_path.lstat() + if ( + stat.S_ISLNK(linked.st_mode) + or not stat.S_ISREG(linked.st_mode) + or not stat.S_ISREG(opened.st_mode) + or (opened.st_dev, opened.st_ino) != (linked.st_dev, linked.st_ino) + ): + raise ApplicationUpdateError("updater lock path is unsafe") + if opened.st_size == 0: + os.write(descriptor, b"\0") + os.fsync(descriptor) + elif opened.st_size != 1: + raise ApplicationUpdateError("updater lock file has invalid size") + + try: + if os.name == "nt": + import msvcrt + + os.lseek(descriptor, 0, os.SEEK_SET) + msvcrt.locking(descriptor, msvcrt.LK_NBLCK, 1) + else: + import fcntl + + fcntl.flock(descriptor, fcntl.LOCK_EX | fcntl.LOCK_NB) + except (OSError, BlockingIOError) as exc: + raise ApplicationUpdateError("another updater process already owns the apply lock") from exc + locked = True + yield + finally: + if locked: + try: + if os.name == "nt": + import msvcrt + + os.lseek(descriptor, 0, os.SEEK_SET) + msvcrt.locking(descriptor, msvcrt.LK_UNLCK, 1) + else: + import fcntl + + fcntl.flock(descriptor, fcntl.LOCK_UN) + except OSError: + pass + os.close(descriptor) + + +def _publish_rollback_copy(source: Path, rollback: Path, expected_sha: str) -> None: + try: + metadata = rollback.lstat() + except FileNotFoundError: + pass + except OSError as exc: + raise ApplicationUpdateError("rollback path is unavailable") from exc + else: + if stat.S_ISLNK(metadata.st_mode) or not stat.S_ISREG(metadata.st_mode): + raise ApplicationUpdateError("rollback path must not redirect update writes") + + temp = rollback.with_name(f".{rollback.name}.build-{os.getpid()}.tmp") + _prepare_temp_slot(temp) + try: + _copy_exact(source, temp) + if _sha256_file(temp) != expected_sha: + raise ApplicationUpdateError("rollback copy failed exact-byte verification") + os.replace(temp, rollback) + _fsync_directory(rollback.parent) + finally: + try: + temp.unlink() + except OSError: + pass + _require_regular_file(rollback, "rollback artifact") + if _sha256_file(rollback) != expected_sha: + raise ApplicationUpdateError("published rollback copy failed exact-byte verification") + + +def _prepare_temp_slot(path: Path) -> None: + try: + metadata = path.lstat() + except FileNotFoundError: + return + except OSError as exc: + raise ApplicationUpdateError("temporary update path is unavailable") from exc + if stat.S_ISLNK(metadata.st_mode) or not stat.S_ISREG(metadata.st_mode): + raise ApplicationUpdateError("temporary update path must not redirect update writes") + _discard_file(path) + + +def _discard_file(path: Path) -> None: + try: + path.unlink() + except FileNotFoundError: + return + except OSError as exc: + raise ApplicationUpdateError("update artifact could not be removed safely") from exc + + +def _copy_exact(source: Path, destination: Path) -> None: + try: + before = source.lstat() + except OSError as exc: + raise ApplicationUpdateError("update source is unavailable") from exc + if stat.S_ISLNK(before.st_mode) or not stat.S_ISREG(before.st_mode): + raise ApplicationUpdateError("update source must be a regular non-symlink file") + before_identity = (before.st_dev, before.st_ino, before.st_size, before.st_mtime_ns) + + try: + source_handle = source.open("rb") + except OSError as exc: + raise ApplicationUpdateError("update source could not be opened") from exc + + with source_handle as src: + opened = os.fstat(src.fileno()) + opened_identity = ( + opened.st_dev, + opened.st_ino, + opened.st_size, + opened.st_mtime_ns, + ) + if not stat.S_ISREG(opened.st_mode) or opened_identity != before_identity: + raise ApplicationUpdateError("update source changed before copy") + + try: + 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()) + opened_after = os.fstat(src.fileno()) + opened_after_identity = ( + opened_after.st_dev, + opened_after.st_ino, + opened_after.st_size, + opened_after.st_mtime_ns, + ) + if opened_after_identity != opened_identity: + raise ApplicationUpdateError("update source changed during copy") + after = source.lstat() + after_identity = ( + after.st_dev, + after.st_ino, + after.st_size, + after.st_mtime_ns, + ) + if after_identity != before_identity: + raise ApplicationUpdateError("update source changed during copy") + except Exception: + try: + destination.unlink() + except OSError: + pass + raise + + +def _sha256_file(path: Path) -> str: + try: + before = path.lstat() + except OSError as exc: + raise ApplicationUpdateError("update artifact is unavailable") from exc + if stat.S_ISLNK(before.st_mode) or not stat.S_ISREG(before.st_mode): + raise ApplicationUpdateError("update artifact must be a regular non-symlink file") + before_identity = (before.st_dev, before.st_ino, before.st_size, before.st_mtime_ns) + + digest = hashlib.sha256() + try: + with path.open("rb") as handle: + opened = os.fstat(handle.fileno()) + opened_identity = ( + opened.st_dev, + opened.st_ino, + opened.st_size, + opened.st_mtime_ns, + ) + if not stat.S_ISREG(opened.st_mode) or opened_identity != before_identity: + raise ApplicationUpdateError("update artifact changed before hashing") + while True: + chunk = handle.read(_COPY_CHUNK) + if not chunk: + break + digest.update(chunk) + opened_after = os.fstat(handle.fileno()) + opened_after_identity = ( + opened_after.st_dev, + opened_after.st_ino, + opened_after.st_size, + opened_after.st_mtime_ns, + ) + if opened_after_identity != opened_identity: + raise ApplicationUpdateError("update artifact changed during hashing") + after = path.lstat() + except ApplicationUpdateError: + raise + except OSError as exc: + raise ApplicationUpdateError("update artifact could not be hashed safely") from exc + + after_identity = (after.st_dev, after.st_ino, after.st_size, after.st_mtime_ns) + if after_identity != before_identity: + raise ApplicationUpdateError("update artifact changed during hashing") + return digest.hexdigest() + + +def _file_identity(path: Path, label: str) -> tuple[int, int, int, int]: + try: + metadata = path.lstat() + except OSError as exc: + raise ApplicationUpdateError(f"{label} is unavailable") from exc + if stat.S_ISLNK(metadata.st_mode) or not stat.S_ISREG(metadata.st_mode): + raise ApplicationUpdateError(f"{label} must be a regular non-symlink file") + return (metadata.st_dev, metadata.st_ino, metadata.st_size, metadata.st_mtime_ns) + + +def _require_regular_file(path: Path, label: str) -> None: + try: + metadata = path.lstat() + except OSError as exc: + raise ApplicationUpdateError(f"{label} is unavailable") from exc + if stat.S_ISLNK(metadata.st_mode) or not stat.S_ISREG(metadata.st_mode): + raise ApplicationUpdateError(f"{label} must be a regular non-symlink file") + + +def _require_safe_parent(path: Path) -> None: + try: + metadata = path.lstat() + except OSError as exc: + raise ApplicationUpdateError("install directory is unavailable") from exc + if stat.S_ISLNK(metadata.st_mode) or not stat.S_ISDIR(metadata.st_mode): + raise ApplicationUpdateError("install directory must be a real directory") + + +def _require_safe_sha256(value: str) -> None: + if len(value) != 64 or any(ch not in "0123456789abcdef" for ch in value): + raise ApplicationUpdateError("expected rollback SHA-256 is invalid") + + +def _fsync_directory(path: Path) -> None: + flags = os.O_RDONLY | getattr(os, "O_DIRECTORY", 0) + try: + descriptor = os.open(path, flags) + except OSError: + return + try: + os.fsync(descriptor) + except OSError: + pass + finally: + os.close(descriptor) diff --git a/runtime_engine/tests/test_application_update_health.py b/runtime_engine/tests/test_application_update_health.py new file mode 100644 index 000000000..3f656b8f7 --- /dev/null +++ b/runtime_engine/tests/test_application_update_health.py @@ -0,0 +1,286 @@ +from __future__ import annotations + +import hashlib +import json +import os +from pathlib import Path +import tempfile +import unittest +from unittest.mock import patch + +from scripture_archive_runtime.application_update import ApplicationUpdateError +from scripture_archive_runtime.application_update_health import ( + HEALTH_RECEIPT_SCHEMA, + _read_receipt, + commit_update_health_receipt, + discard_update_health_receipt, + inspect_update_health_receipt, + publish_update_health_receipt, +) + + +PREVIOUS_VERSION = "1.0.0" +TARGET_VERSION = "1.1.0" + + +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() + self.tmp_path = Path(self.temp.name) + + def tearDown(self) -> None: + self.temp.cleanup() + + def test_publish_and_inspect_bind_version_name_and_exact_installed_rollback_bytes(self) -> None: + root, target, rollback, previous, installed, receipt = _publish(self.tmp_path) + + self.assertEqual(receipt.previous_version, PREVIOUS_VERSION) + self.assertEqual(receipt.target_version, TARGET_VERSION) + self.assertEqual(receipt.installed_executable_name, target.name) + self.assertEqual(receipt.previous_sha256, _sha(previous)) + self.assertEqual(receipt.installed_sha256, _sha(installed)) + self.assertEqual( + inspect_update_health_receipt( + root, + current_version=TARGET_VERSION, + install_target=target, + ), + receipt, + ) + + payload = json.loads((root / "update-health.json").read_text(encoding="utf-8")) + self.assertEqual(payload["schema"], HEALTH_RECEIPT_SCHEMA) + self.assertEqual(payload["status"], "awaiting_health_commit") + serialized = json.dumps(payload) + self.assertNotIn(str(self.tmp_path), serialized) + self.assertNotIn("install_target", payload) + self.assertNotIn("rollback_path", payload) + + def test_publish_is_idempotent_only_for_same_exact_identity(self) -> None: + root, target, rollback, previous, installed, first = _publish(self.tmp_path) + before = (root / "update-health.json").read_bytes() + second = publish_update_health_receipt( + root, + previous_version=PREVIOUS_VERSION, + target_version=TARGET_VERSION, + install_target=target, + previous_sha256=_sha(previous), + installed_sha256=_sha(installed), + ) + self.assertEqual(second, first) + self.assertEqual((root / "update-health.json").read_bytes(), before) + + with self.assertRaisesRegex(ApplicationUpdateError, "different identity"): + publish_update_health_receipt( + root, + previous_version=PREVIOUS_VERSION, + target_version="1.2.0", + install_target=target, + previous_sha256=_sha(previous), + installed_sha256=_sha(installed), + ) + + def test_inspect_fails_closed_on_version_installed_or_rollback_tamper(self) -> None: + 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) + + target.write_bytes(b"x" * len(installed)) + with self.assertRaisesRegex(ApplicationUpdateError, "installed application bytes changed"): + inspect_update_health_receipt(root, current_version=TARGET_VERSION, install_target=target) + target.write_bytes(installed) + + rollback.write_bytes(b"y" * len(previous)) + with self.assertRaisesRegex(ApplicationUpdateError, "rollback bytes changed"): + inspect_update_health_receipt(root, current_version=TARGET_VERSION, install_target=target) + + def test_installed_path_swap_before_hash_fails_closed_even_for_identical_bytes(self) -> None: + root, target, rollback, previous, installed, receipt = _publish(self.tmp_path) + replacement = target.with_name("replacement-installed.exe") + parked = target.with_name("parked-installed.exe") + replacement.write_bytes(installed) + original_open = Path.open + swapped = False + + def swapping_open(path_obj: Path, *args, **kwargs): + nonlocal swapped + if path_obj == target and not swapped: + swapped = True + os.replace(target, parked) + os.replace(replacement, target) + return original_open(path_obj, *args, **kwargs) + + with patch.object(Path, "open", new=swapping_open): + with self.assertRaisesRegex( + ApplicationUpdateError, + "installed application target changed before hashing", + ): + inspect_update_health_receipt( + root, + current_version=TARGET_VERSION, + install_target=target, + ) + + self.assertTrue(swapped) + self.assertTrue(parked.exists()) + self.assertTrue(target.exists()) + + def test_rollback_path_swap_before_hash_fails_closed_even_for_identical_bytes(self) -> None: + root, target, rollback, previous, installed, receipt = _publish(self.tmp_path) + replacement = rollback.with_name("replacement-rollback.bin") + parked = rollback.with_name("parked-rollback.bin") + replacement.write_bytes(previous) + original_open = Path.open + swapped = False + + def swapping_open(path_obj: Path, *args, **kwargs): + nonlocal swapped + if path_obj == rollback and not swapped: + swapped = True + os.replace(rollback, parked) + os.replace(replacement, rollback) + return original_open(path_obj, *args, **kwargs) + + with patch.object(Path, "open", new=swapping_open): + with self.assertRaisesRegex( + ApplicationUpdateError, + "rollback artifact changed before hashing", + ): + inspect_update_health_receipt( + root, + current_version=TARGET_VERSION, + install_target=target, + ) + + self.assertTrue(swapped) + self.assertTrue(parked.exists()) + self.assertTrue(rollback.exists()) + + def test_receipt_shape_extra_field_and_symlink_fail_closed(self) -> None: + 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 + path.write_text(json.dumps(payload), encoding="utf-8") + with self.assertRaisesRegex(ApplicationUpdateError, "shape is invalid"): + inspect_update_health_receipt(root, current_version=TARGET_VERSION, install_target=target) + + path.unlink() + real = root / "real-health.json" + real.write_text("{}", encoding="utf-8") + try: + path.symlink_to(real) + except (OSError, NotImplementedError): + self.skipTest("symlinks unavailable") + with self.assertRaisesRegex(ApplicationUpdateError, "regular non-symlink"): + inspect_update_health_receipt(root, current_version=TARGET_VERSION, install_target=target) + + def test_receipt_path_swap_before_open_fails_closed(self) -> None: + root, target, rollback, previous, installed, receipt = _publish(self.tmp_path) + path = root / "update-health.json" + replacement = root / "replacement-health.json" + parked = root / "parked-health.json" + replacement.write_bytes(path.read_bytes()) + original_open = Path.open + swapped = False + + def swapping_open(path_obj: Path, *args, **kwargs): + nonlocal swapped + if path_obj == path and not swapped: + swapped = True + os.replace(path, parked) + os.replace(replacement, path) + return original_open(path_obj, *args, **kwargs) + + with patch.object(Path, "open", new=swapping_open): + with self.assertRaisesRegex(ApplicationUpdateError, "changed before readback"): + inspect_update_health_receipt( + root, + current_version=TARGET_VERSION, + install_target=target, + ) + + self.assertTrue(swapped) + self.assertTrue(parked.exists()) + self.assertTrue(path.exists()) + + def test_oversized_receipt_is_rejected_before_open(self) -> None: + root = self.tmp_path / "state" / "updates" + root.mkdir(parents=True) + path = root / "update-health.json" + path.write_bytes(b"x" * 4097) + + with patch.object(Path, "open", side_effect=AssertionError("receipt must not be opened")) as opened: + with self.assertRaisesRegex(ApplicationUpdateError, "unexpectedly large"): + _read_receipt(path) + opened.assert_not_called() + + def test_commit_disarms_old_pending_then_receipt_and_rollback_after_exact_proof(self) -> None: + 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") + + committed = commit_update_health_receipt( + root, + current_version=TARGET_VERSION, + install_target=target, + ) + self.assertEqual(committed, receipt) + self.assertFalse(pending.exists()) + self.assertFalse((root / "update-health.json").exists()) + self.assertFalse(rollback.exists()) + self.assertEqual(target.read_bytes(), installed) + + def test_failed_health_proof_preserves_receipt_pending_and_rollback(self) -> None: + 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") + + with self.assertRaises(ApplicationUpdateError): + commit_update_health_receipt(root, current_version=TARGET_VERSION, install_target=target) + self.assertTrue(pending.exists()) + self.assertTrue((root / "update-health.json").exists()) + self.assertTrue(rollback.exists()) + + def test_discard_only_disarms_receipt_and_preserves_recovery_bytes(self) -> None: + 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) + + +if __name__ == "__main__": + unittest.main() diff --git a/runtime_engine/tests/test_application_update_parent_wait.py b/runtime_engine/tests/test_application_update_parent_wait.py new file mode 100644 index 000000000..aafb2497e --- /dev/null +++ b/runtime_engine/tests/test_application_update_parent_wait.py @@ -0,0 +1,69 @@ +from __future__ import annotations + +import os +import unittest + +from scripture_archive_runtime.application_update_parent_wait import ( + ParentProcessWaitError, + wait_for_parent_exit, +) + + +class ParentProcessWaitTests(unittest.TestCase): + def test_wait_uses_exact_pid_and_bounded_timeout(self) -> None: + seen: list[tuple[int, int]] = [] + + def backend(pid: int, timeout_ms: int) -> None: + seen.append((pid, timeout_ms)) + + wait_for_parent_exit(4242, timeout_ms=30_000, wait_backend=backend) + self.assertEqual(seen, [(4242, 30_000)]) + + def test_wait_rejects_own_pid_before_backend(self) -> None: + called = False + + def backend(pid: int, timeout_ms: int) -> None: + nonlocal called + called = True + + with self.assertRaisesRegex(ParentProcessWaitError, "own process"): + wait_for_parent_exit(os.getpid(), wait_backend=backend) + self.assertFalse(called) + + def test_wait_rejects_invalid_pid(self) -> None: + for pid in [0, -1, True, 1.5, "1"]: + 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): + 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"): + wait_for_parent_exit(4242, os_name="posix") + + def test_wait_wraps_backend_failure(self) -> None: + def backend(pid: int, timeout_ms: int) -> None: + raise OSError("boom") + + with self.assertRaisesRegex(ParentProcessWaitError, "wait failed"): + wait_for_parent_exit(4242, wait_backend=backend) + + def test_wait_preserves_fail_closed_backend_verdict(self) -> None: + def backend(pid: int, timeout_ms: int) -> None: + raise ParentProcessWaitError("parent process did not exit before timeout") + + with self.assertRaisesRegex(ParentProcessWaitError, "did not exit"): + wait_for_parent_exit(4242, wait_backend=backend) + + +if __name__ == "__main__": + unittest.main() diff --git a/runtime_engine/tests/test_application_update_process.py b/runtime_engine/tests/test_application_update_process.py new file mode 100644 index 000000000..ddb75ba75 --- /dev/null +++ b/runtime_engine/tests/test_application_update_process.py @@ -0,0 +1,188 @@ +from __future__ import annotations + +from pathlib import Path +import os +import tempfile +import unittest + +from scripture_archive_runtime.application_update_process import ( + UpdateProcessError, + build_updater_process_plan, + launch_updater_process, + parse_trusted_updater_argv, +) + + +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() + self.tmp_path = Path(self.temp.name) + + def tearDown(self) -> None: + self.temp.cleanup() + + def test_build_plan_binds_sibling_packaged_updater_current_pid_and_fixed_argv(self) -> None: + updater, app, staging = _files(self.tmp_path) + plan = build_updater_process_plan( + updater_executable=updater, + installed_executable=app, + staging_root=staging, + ) + self.assertEqual(plan.parent_pid, os.getpid()) + self.assertEqual(plan.updater_executable, updater.resolve()) + self.assertEqual(plan.installed_executable, app.resolve()) + self.assertEqual(plan.staging_root, staging.resolve()) + self.assertEqual( + plan.argv(), + ( + str(updater.resolve()), + "--scripture-archive-apply", + "--wait-pid", + str(os.getpid()), + "--installed-executable", + str(app.resolve()), + "--staging-root", + str(staging.resolve()), + ), + ) + + def test_build_plan_rejects_external_updater(self) -> None: + 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"): + build_updater_process_plan( + updater_executable=external, + installed_executable=app, + staging_root=staging, + ) + + def test_build_plan_rejects_current_app_as_updater(self) -> None: + _, app, staging = _files(self.tmp_path) + with self.assertRaisesRegex(UpdateProcessError, "distinct"): + build_updater_process_plan( + updater_executable=app, + installed_executable=app, + staging_root=staging, + ) + + def test_build_plan_rejects_symlinked_updater_target_and_staging(self) -> None: + updater, app, staging = _files(self.tmp_path) + updater_link = updater.parent / "link-updater.exe" + staging_link = self.tmp_path / "state-link" + try: + updater_link.symlink_to(updater) + staging_link.symlink_to(staging, target_is_directory=True) + except (OSError, NotImplementedError): + self.skipTest("symlinks unavailable") + with self.assertRaisesRegex(UpdateProcessError, "non-symlink"): + build_updater_process_plan( + updater_executable=updater_link, + installed_executable=app, + staging_root=staging, + ) + with self.assertRaisesRegex(UpdateProcessError, "real directory"): + build_updater_process_plan( + updater_executable=updater, + installed_executable=app, + staging_root=staging_link, + ) + + def test_build_plan_rejects_foreign_parent_pid(self) -> None: + updater, app, staging = _files(self.tmp_path) + with self.assertRaisesRegex(UpdateProcessError, "current host process"): + build_updater_process_plan( + updater_executable=updater, + installed_executable=app, + staging_root=staging, + parent_pid=os.getpid() + 1, + ) + + def test_launch_is_shell_free_fixed_cwd_and_returns_child_pid(self) -> None: + updater, app, staging = _files(self.tmp_path) + plan = build_updater_process_plan( + updater_executable=updater, + installed_executable=app, + staging_root=staging, + ) + seen: dict[str, object] = {} + + class Child: + pid = 43210 + + def fake_popen(argv, **kwargs): + seen["argv"] = argv + seen.update(kwargs) + return Child() + + pid = launch_updater_process(plan, popen=fake_popen, os_name="posix") + self.assertEqual(pid, 43210) + self.assertEqual(seen["argv"], list(plan.argv())) + self.assertEqual(seen["cwd"], str(app.resolve().parent)) + self.assertIs(seen["shell"], False) + self.assertIs(seen["close_fds"], True) + self.assertEqual(seen["creationflags"], 0) + + def test_launch_wraps_process_failure(self) -> None: + updater, app, staging = _files(self.tmp_path) + plan = build_updater_process_plan( + updater_executable=updater, + installed_executable=app, + staging_root=staging, + ) + + def broken_popen(*args, **kwargs): + raise OSError("boom") + + with self.assertRaisesRegex(UpdateProcessError, "failed to launch"): + launch_updater_process(plan, popen=broken_popen) + + def test_parser_accepts_only_fixed_host_contract(self) -> None: + updater, app, staging = _files(self.tmp_path) + plan = build_updater_process_plan( + updater_executable=updater, + installed_executable=app, + staging_root=staging, + ) + pid, parsed_app, parsed_staging = parse_trusted_updater_argv(plan.argv()[1:]) + self.assertEqual(pid, os.getpid()) + self.assertEqual(parsed_app, app.resolve()) + self.assertEqual(parsed_staging, staging.resolve()) + + def test_parser_rejects_noncanonical_or_extended_commands(self) -> None: + 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", + ), + ] + for argv in invalid_commands: + with self.subTest(argv=argv): + with self.assertRaises(UpdateProcessError): + parse_trusted_updater_argv(argv) + + +if __name__ == "__main__": + unittest.main() diff --git a/runtime_engine/tests/test_application_update_relaunch.py b/runtime_engine/tests/test_application_update_relaunch.py new file mode 100644 index 000000000..6c05123d0 --- /dev/null +++ b/runtime_engine/tests/test_application_update_relaunch.py @@ -0,0 +1,76 @@ +from __future__ import annotations + +from pathlib import Path +import tempfile +import unittest + +from scripture_archive_runtime.application_update import ApplicationUpdateError +from scripture_archive_runtime.application_update_relaunch import launch_installed_application + + +class ApplicationUpdateRelaunchTests(unittest.TestCase): + def setUp(self) -> None: + self.temp = tempfile.TemporaryDirectory() + self.tmp_path = Path(self.temp.name) + + def tearDown(self) -> None: + self.temp.cleanup() + + def test_relaunch_uses_exact_target_without_shell_and_fixed_working_directory(self) -> None: + install = self.tmp_path / "Program Files" / "Архів Писання" + install.mkdir(parents=True) + target = install / "Scripture Archive.exe" + target.write_bytes(b"updated") + calls: list[tuple[tuple[str, ...], dict[str, object]]] = [] + + def spawn(argv, **kwargs): + calls.append((tuple(argv), dict(kwargs))) + return object() + + launch_installed_application(target, spawn=spawn) + + self.assertEqual( + calls, + [ + ((str(target),), {"cwd": str(install), "close_fds": True}), + ], + ) + + def test_relaunch_rejects_symlink_target_before_spawn(self) -> None: + real = self.tmp_path / "real.exe" + real.write_bytes(b"updated") + target = self.tmp_path / "Scripture Archive.exe" + try: + target.symlink_to(real) + except (OSError, NotImplementedError): + self.skipTest("symlinks unavailable") + spawned = False + + def spawn(*args, **kwargs): + nonlocal spawned + spawned = True + + with self.assertRaisesRegex(ApplicationUpdateError, "regular non-symlink"): + launch_installed_application(target, spawn=spawn) + self.assertFalse(spawned) + + def test_relaunch_translates_process_creation_failure(self) -> None: + target = self.tmp_path / "Scripture Archive.exe" + target.write_bytes(b"updated") + + def spawn(*args, **kwargs): + raise OSError("cannot execute") + + with self.assertRaisesRegex(ApplicationUpdateError, "could not be started"): + launch_installed_application(target, spawn=spawn) + + def test_relaunch_requires_callable_spawner(self) -> None: + target = self.tmp_path / "Scripture Archive.exe" + target.write_bytes(b"updated") + + with self.assertRaisesRegex(ApplicationUpdateError, "process spawner"): + launch_installed_application(target, spawn=None) # type: ignore[arg-type] + + +if __name__ == "__main__": + unittest.main() diff --git a/runtime_engine/tests/test_application_update_runner.py b/runtime_engine/tests/test_application_update_runner.py new file mode 100644 index 000000000..87a7551eb --- /dev/null +++ b/runtime_engine/tests/test_application_update_runner.py @@ -0,0 +1,358 @@ +from __future__ import annotations + +from pathlib import Path +import os +import tempfile +import unittest + +from scripture_archive_runtime.application_update import ApplicationUpdateError +from scripture_archive_runtime.application_update_parent_wait import ParentProcessWaitError +from scripture_archive_runtime.application_update_process import ( + UpdateProcessError, + build_updater_process_plan, +) +from scripture_archive_runtime.application_update_runner import execute_trusted_updater +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, + installed_sha256="2" * 64, + rollback_path=plan.installed_executable.with_name( + plan.installed_executable.name + ".scripture-archive.rollback" + ), + target_path=plan.installed_executable, + target_version="1.1.0", + ) + + +def _publish_noop(*args, **kwargs): + return object() + + +def _discard_noop(*args, **kwargs): + return False + + +class ApplicationUpdateRunnerTests(unittest.TestCase): + def setUp(self) -> None: + self.temp = tempfile.TemporaryDirectory() + self.tmp_path = Path(self.temp.name) + + def tearDown(self) -> None: + self.temp.cleanup() + + def test_runner_waits_applies_publishes_health_then_relaunches_exact_target(self) -> None: + plan = _plan(self.tmp_path) + events: list[object] = [] + sentinel = _result(plan) + + def wait_for_exit(parent_pid: int) -> None: + events.append(("wait", parent_pid)) + + def consume(staging_root, **kwargs): + events.append(("consume", Path(staging_root), kwargs)) + return sentinel + + def publish_health(staging_root, **kwargs): + events.append(("health", Path(staging_root), kwargs)) + return object() + + def launch(target: Path) -> None: + events.append(("launch", target)) + + verifier = lambda installed, staged: True + result = execute_trusted_updater( + plan.argv()[1:], + current_version="1.0.0", + verify_same_publisher=verifier, + wait_for_exit=wait_for_exit, + consume=consume, + publish_health=publish_health, + discard_health=_discard_noop, + launch=launch, + ) + + self.assertIs(result, sentinel) + self.assertEqual(events[0], ("wait", os.getpid())) + kind, staging, kwargs = events[1] + self.assertEqual(kind, "consume") + self.assertEqual(staging, plan.staging_root) + self.assertEqual( + kwargs, + { + "current_version": "1.0.0", + "install_target": plan.installed_executable, + "verify_same_publisher": verifier, + }, + ) + kind, staging, kwargs = events[2] + self.assertEqual(kind, "health") + self.assertEqual(staging, plan.staging_root) + self.assertEqual( + kwargs, + { + "previous_version": "1.0.0", + "target_version": "1.1.0", + "install_target": plan.installed_executable, + "previous_sha256": sentinel.previous_sha256, + "installed_sha256": sentinel.installed_sha256, + }, + ) + self.assertEqual(events[3], ("launch", plan.installed_executable)) + + def test_runner_health_publish_failure_rolls_back_and_disarms_before_no_launch(self) -> None: + plan = _plan(self.tmp_path) + sentinel = _result(plan) + events: list[object] = [] + + def rollback(target: Path, *, expected_previous_sha256: str) -> str: + events.append(("rollback", target, expected_previous_sha256)) + return expected_previous_sha256 + + def discard(staging_root: Path) -> bool: + events.append(("discard", Path(staging_root))) + return True + + def launch(target: Path) -> None: + events.append(("launch", target)) + + with self.assertRaisesRegex( + ApplicationUpdateError, + "health receipt publication failed; rollback restored", + ): + execute_trusted_updater( + plan.argv()[1:], + current_version="1.0.0", + verify_same_publisher=lambda installed, staged: True, + wait_for_exit=lambda parent_pid: None, + consume=lambda *args, **kwargs: sentinel, + publish_health=lambda *args, **kwargs: (_ for _ in ()).throw( + OSError("receipt failed") + ), + discard_health=discard, + rollback=rollback, + launch=launch, + ) + self.assertEqual( + events, + [ + ("rollback", plan.installed_executable, sentinel.previous_sha256), + ("discard", plan.staging_root), + ], + ) + + def test_runner_rolls_back_and_disarms_health_when_updated_process_cannot_start(self) -> None: + plan = _plan(self.tmp_path) + sentinel = _result(plan) + events: list[object] = [] + + def publish(staging_root, **kwargs): + events.append(("publish", Path(staging_root))) + return object() + + def launch(target: Path) -> None: + events.append(("launch", target)) + raise ApplicationUpdateError("spawn failed") + + def rollback(target: Path, *, expected_previous_sha256: str) -> str: + events.append(("rollback", target, expected_previous_sha256)) + return expected_previous_sha256 + + def discard(staging_root: Path) -> bool: + events.append(("discard", Path(staging_root))) + return True + + with self.assertRaisesRegex(ApplicationUpdateError, "rollback restored prior bytes"): + execute_trusted_updater( + plan.argv()[1:], + current_version="1.0.0", + verify_same_publisher=lambda installed, staged: True, + wait_for_exit=lambda parent_pid: None, + consume=lambda *args, **kwargs: sentinel, + publish_health=publish, + discard_health=discard, + launch=launch, + rollback=rollback, + ) + + self.assertEqual( + events, + [ + ("publish", plan.staging_root), + ("launch", plan.installed_executable), + ("rollback", plan.installed_executable, sentinel.previous_sha256), + ("discard", plan.staging_root), + ], + ) + + def test_runner_surfaces_combined_relaunch_and_rollback_failure(self) -> None: + plan = _plan(self.tmp_path) + sentinel = _result(plan) + + with self.assertRaisesRegex( + ApplicationUpdateError, + "relaunch failed and rollback also failed", + ): + execute_trusted_updater( + plan.argv()[1:], + current_version="1.0.0", + verify_same_publisher=lambda installed, staged: True, + wait_for_exit=lambda parent_pid: None, + consume=lambda *args, **kwargs: sentinel, + publish_health=_publish_noop, + discard_health=_discard_noop, + launch=lambda target: (_ for _ in ()).throw(OSError("spawn failed")), + rollback=lambda *args, **kwargs: (_ for _ in ()).throw( + OSError("rollback failed") + ), + ) + + def test_runner_rolls_back_consumer_target_substitution_before_health_or_launch(self) -> None: + plan = _plan(self.tmp_path) + sentinel = UpdateApplyResult( + previous_sha256="1" * 64, + installed_sha256="2" * 64, + rollback_path=plan.installed_executable.with_suffix(".rollback"), + target_path=self.tmp_path / "other.exe", + target_version="1.1.0", + ) + events: list[object] = [] + + def publish(*args, **kwargs): + events.append(("health",)) + + def launch(target: Path) -> None: + events.append(("launch", target)) + + def rollback(target: Path, *, expected_previous_sha256: str) -> str: + events.append(("rollback", target, expected_previous_sha256)) + return expected_previous_sha256 + + with self.assertRaisesRegex( + ApplicationUpdateError, + "unexpected install target; rollback restored", + ): + execute_trusted_updater( + plan.argv()[1:], + current_version="1.0.0", + verify_same_publisher=lambda installed, staged: True, + wait_for_exit=lambda parent_pid: None, + consume=lambda *args, **kwargs: sentinel, + publish_health=publish, + discard_health=_discard_noop, + launch=launch, + rollback=rollback, + ) + self.assertEqual( + events, + [("rollback", plan.installed_executable, sentinel.previous_sha256)], + ) + + def test_runner_never_consumes_when_parent_exit_cannot_be_proven(self) -> None: + plan = _plan(self.tmp_path) + consumed = False + + def blocked_wait(parent_pid: int) -> None: + raise ParentProcessWaitError("parent still alive") + + def consume(*args, **kwargs): + nonlocal consumed + consumed = True + raise AssertionError("must not consume") + + with self.assertRaisesRegex(ParentProcessWaitError, "parent still alive"): + execute_trusted_updater( + plan.argv()[1:], + current_version="1.0.0", + verify_same_publisher=lambda installed, staged: True, + wait_for_exit=blocked_wait, + consume=consume, + ) + self.assertFalse(consumed) + + def test_runner_rejects_malformed_command_before_wait_or_consume(self) -> None: + waited = False + consumed = False + + def wait_for_exit(parent_pid: int) -> None: + nonlocal waited + waited = True + + def consume(*args, **kwargs): + nonlocal consumed + consumed = True + raise AssertionError("must not consume") + + with self.assertRaisesRegex(UpdateProcessError, "invalid updater command shape"): + execute_trusted_updater( + ("--scripture-archive-apply", "--wait-pid", "1"), + current_version="1.0.0", + verify_same_publisher=lambda installed, staged: True, + wait_for_exit=wait_for_exit, + consume=consume, + ) + self.assertFalse(waited) + self.assertFalse(consumed) + + def test_runner_rejects_invalid_trusted_current_version_before_wait(self) -> None: + 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 = _plan(self.tmp_path / current_version.replace(".", "_").replace(" ", "_")) + waited = False + + def wait_for_exit(parent_pid: int) -> None: + nonlocal waited + waited = True + + with self.assertRaises(ApplicationUpdateError): + execute_trusted_updater( + plan.argv()[1:], + current_version=current_version, + verify_same_publisher=lambda installed, staged: True, + wait_for_exit=wait_for_exit, + ) + self.assertFalse(waited) + + def test_runner_requires_callable_security_dependencies_before_wait(self) -> None: + overrides = [ + ({"verify_same_publisher": None}, "same-publisher verifier"), + ({"wait_for_exit": None}, "parent-exit waiter"), + ({"consume": None}, "apply consumer"), + ({"launch": None}, "application launcher"), + ({"rollback": None}, "rollback consumer"), + ({"publish_health": None}, "health receipt publisher"), + ({"discard_health": None}, "health receipt discarder"), + ] + 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, + } + kwargs.update(override) + with self.assertRaisesRegex(ApplicationUpdateError, message): + execute_trusted_updater(plan.argv()[1:], **kwargs) # type: ignore[arg-type] + + +if __name__ == "__main__": + unittest.main() diff --git a/runtime_engine/tests/test_application_update_updater.py b/runtime_engine/tests/test_application_update_updater.py new file mode 100644 index 000000000..d48ba31ca --- /dev/null +++ b/runtime_engine/tests/test_application_update_updater.py @@ -0,0 +1,841 @@ +from __future__ import annotations + +import hashlib +import os +from pathlib import Path +import tempfile +import unittest +from unittest.mock import patch + +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, + _sha256_file, + consume_apply_handoff, + rollback_installed_update, +) + + +def _sha(data: bytes) -> str: + return hashlib.sha256(data).hexdigest() + + +class AtomicApplicationUpdaterTests(unittest.TestCase): + def _pending(self, staged: bytes) -> PendingApplicationUpdate: + return PendingApplicationUpdate( + product_id="scripture-archive", + target_platform="windows-x64", + current_version="1.0.0", + target_version="1.1.0", + source_head="a" * 40, + artifact_name="ScriptureArchive.exe", + artifact_size=len(staged), + artifact_sha256=_sha(staged), + ) + + def test_consume_handoff_replaces_exact_bytes_and_keeps_verified_rollback(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=True, + ): + result = consume_apply_handoff( + root, + current_version="1.0.0", + install_target=target, + verify_same_publisher=lambda current, candidate: current == target and candidate == staged, + ) + + self.assertEqual(target.read_bytes(), new) + self.assertEqual(result.installed_sha256, _sha(new)) + self.assertEqual(result.previous_sha256, _sha(old)) + self.assertEqual(result.target_version, "1.1.0") + self.assertEqual(result.rollback_path.read_bytes(), old) + + def test_consume_handoff_atomically_replaces_prior_rollback_generation(self): + old = b"current pre-update executable" + older = b"older rollback generation" + new = b"new signed executable bytes" + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + target = root / "ScriptureArchive.exe" + rollback = root / "ScriptureArchive.exe.scripture-archive.rollback" + staged = root / "staged" / "ScriptureArchive.exe" + staged.parent.mkdir() + target.write_bytes(old) + rollback.write_bytes(older) + 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=True, + ): + consume_apply_handoff( + root, + current_version="1.0.0", + install_target=target, + verify_same_publisher=lambda _current, _candidate: True, + ) + + self.assertEqual(target.read_bytes(), new) + self.assertEqual(rollback.read_bytes(), old) + + def test_failed_new_rollback_copy_preserves_prior_generation(self): + old = b"current pre-update executable" + older = b"older rollback generation" + new = b"new signed executable bytes" + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + target = root / "ScriptureArchive.exe" + rollback = root / "ScriptureArchive.exe.scripture-archive.rollback" + staged = root / "staged" / "ScriptureArchive.exe" + staged.parent.mkdir() + target.write_bytes(old) + rollback.write_bytes(older) + staged.write_bytes(new) + pending = self._pending(new) + + from scripture_archive_runtime import application_update_updater as updater_module + real_copy = updater_module._copy_exact + + def fail_backup_copy(source: Path, destination: Path) -> None: + if ".scripture-archive.rollback.build-" in destination.name: + raise ApplicationUpdateError("forced rollback copy failure") + real_copy(source, destination) + + 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._copy_exact", + side_effect=fail_backup_copy, + ): + with self.assertRaisesRegex(ApplicationUpdateError, "forced rollback copy failure"): + 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) + self.assertEqual(rollback.read_bytes(), older) + + def test_consume_handoff_fails_closed_when_publisher_check_rejects(self): + old = b"old" + new = b"new" + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + target = root / "ScriptureArchive.exe" + target.write_bytes(old) + pending = self._pending(new) + staged_named = root / "staged" / pending.artifact_name + staged_named.parent.mkdir() + staged_named.write_bytes(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_named, + ): + with self.assertRaisesRegex(ApplicationUpdateError, "same-publisher"): + consume_apply_handoff( + root, + current_version="1.0.0", + install_target=target, + verify_same_publisher=lambda _current, _candidate: False, + ) + + self.assertEqual(target.read_bytes(), old) + self.assertFalse((root / "ScriptureArchive.exe.scripture-archive.rollback").exists()) + + def test_consume_handoff_detects_staged_mutation_during_signature_check(self): + old = b"old" + new = b"new" + 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) + + def mutate(_current: Path, candidate: Path) -> bool: + candidate.write_bytes(b"tampered") + return True + + 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, + ): + with self.assertRaisesRegex(ApplicationUpdateError, "changed during publisher verification"): + consume_apply_handoff( + root, + current_version="1.0.0", + install_target=target, + verify_same_publisher=mutate, + ) + + self.assertEqual(target.read_bytes(), old) + + def test_consume_handoff_rejects_byte_identical_staged_replacement_during_signature_check(self): + old = b"old executable" + new = b"new signed executable" + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + target = root / "ScriptureArchive.exe" + staged = root / "staged" / "ScriptureArchive.exe" + alternate = root / "staged" / "alternate.exe" + parked = root / "staged" / "parked.exe" + staged.parent.mkdir() + target.write_bytes(old) + staged.write_bytes(new) + alternate.write_bytes(new) + pending = self._pending(new) + + def replace_staged(_current: Path, candidate: Path) -> bool: + os.replace(candidate, parked) + os.replace(alternate, candidate) + return True + + 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, + ): + with self.assertRaisesRegex( + ApplicationUpdateError, + "staged artifact changed during publisher verification", + ): + consume_apply_handoff( + root, + current_version="1.0.0", + install_target=target, + verify_same_publisher=replace_staged, + ) + + self.assertEqual(target.read_bytes(), old) + self.assertFalse( + (root / "ScriptureArchive.exe.scripture-archive.rollback").exists() + ) + + def test_consume_handoff_rejects_byte_identical_target_replacement_during_signature_check(self): + old = b"old trusted executable" + new = b"new signed executable" + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + target = root / "ScriptureArchive.exe" + alternate = root / "alternate-installed.exe" + parked = root / "parked-installed.exe" + staged = root / "staged" / "ScriptureArchive.exe" + staged.parent.mkdir() + target.write_bytes(old) + alternate.write_bytes(old) + staged.write_bytes(new) + pending = self._pending(new) + + def replace_target(current: Path, _candidate: Path) -> bool: + os.replace(current, parked) + os.replace(alternate, current) + return True + + 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, + ): + with self.assertRaisesRegex( + ApplicationUpdateError, + "installed application target changed during publisher verification", + ): + consume_apply_handoff( + root, + current_version="1.0.0", + install_target=target, + verify_same_publisher=replace_target, + ) + + self.assertEqual(target.read_bytes(), old) + self.assertFalse( + (root / "ScriptureArchive.exe.scripture-archive.rollback").exists() + ) + + def test_consume_handoff_rejects_target_mutation_during_signature_check(self): + old = b"old trusted executable" + new = b"new signed executable" + 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) + + def mutate_target(current: Path, _candidate: Path) -> bool: + current.write_bytes(b"attacker replacement") + return True + + 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, + ): + with self.assertRaisesRegex( + ApplicationUpdateError, + "target changed during publisher verification", + ): + consume_apply_handoff( + root, + current_version="1.0.0", + install_target=target, + verify_same_publisher=mutate_target, + ) + + self.assertEqual(target.read_bytes(), b"attacker replacement") + self.assertFalse( + (root / "ScriptureArchive.exe.scripture-archive.rollback").exists() + ) + + def test_consume_handoff_rejects_cancelled_authority_after_signature_check(self): + old = b"old trusted executable" + new = b"new signed executable" + 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, None] + + with patch( + "scripture_archive_runtime.application_update_updater.inspect_apply_handoff", + side_effect=inspections, + ), patch( + "scripture_archive_runtime.application_update_updater.staged_artifact_path", + return_value=staged, + ): + with self.assertRaisesRegex( + ApplicationUpdateError, + "apply handoff changed during publisher verification", + ): + 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) + self.assertFalse( + (root / "ScriptureArchive.exe.scripture-archive.rollback").exists() + ) + + def test_consume_handoff_rejects_staged_replacement_before_install_copy(self): + old = b"old executable bytes" + new = b"new signed executable bytes" + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + target = root / "ScriptureArchive.exe" + rollback = root / "ScriptureArchive.exe.scripture-archive.rollback" + staged = root / "staged" / "ScriptureArchive.exe" + alternate = root / "staged" / "alternate.exe" + parked = root / "staged" / "parked.exe" + staged.parent.mkdir() + target.write_bytes(old) + staged.write_bytes(new) + alternate.write_bytes(new) + pending = self._pending(new) + + from scripture_archive_runtime import application_update_updater as updater_module + real_publish = updater_module._publish_rollback_copy + + def publish_then_replace(source: Path, destination: Path, expected_sha: str) -> None: + real_publish(source, destination, expected_sha) + os.replace(staged, parked) + os.replace(alternate, staged) + + 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._publish_rollback_copy", + side_effect=publish_then_replace, + ): + with self.assertRaisesRegex( + ApplicationUpdateError, + "staged artifact identity changed before install copy", + ): + 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) + self.assertEqual(rollback.read_bytes(), old) + + def test_consume_handoff_rejects_target_replacement_before_atomic_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" + rollback = root / "ScriptureArchive.exe.scripture-archive.rollback" + alternate = root / "alternate-installed.exe" + parked = root / "parked-installed.exe" + staged = root / "staged" / "ScriptureArchive.exe" + staged.parent.mkdir() + target.write_bytes(old) + alternate.write_bytes(old) + staged.write_bytes(new) + pending = self._pending(new) + + from scripture_archive_runtime import application_update_updater as updater_module + real_copy = updater_module._copy_exact + + def copy_then_replace(source: Path, destination: Path) -> None: + real_copy(source, destination) + if ".update-" in destination.name: + os.replace(target, parked) + os.replace(alternate, target) + + 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._copy_exact", + side_effect=copy_then_replace, + ): + with self.assertRaisesRegex( + ApplicationUpdateError, + "installed application target identity changed before atomic publication", + ): + 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) + self.assertEqual(rollback.read_bytes(), old) + self.assertEqual(parked.read_bytes(), old) + + def test_consume_handoff_rolls_back_when_post_publish_verification_errors(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) + + real_hash = hashlib.sha256 + target_hash_reads = 0 + + def fail_post_publish_hash(path: Path) -> str: + nonlocal target_hash_reads + if path == target: + target_hash_reads += 1 + if target_hash_reads == 3: + raise ApplicationUpdateError("forced post-publish hash failure") + digest = real_hash() + digest.update(path.read_bytes()) + return digest.hexdigest() + + 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._sha256_file", + side_effect=fail_post_publish_hash, + ): + 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) + self.assertEqual( + (root / "ScriptureArchive.exe.scripture-archive.rollback").read_bytes(), + 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_hash_rejects_path_swap_before_open_even_for_identical_bytes(self): + data = b"same exact updater bytes" + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + target = root / "artifact.exe" + replacement = root / "replacement.exe" + parked = root / "parked.exe" + target.write_bytes(data) + replacement.write_bytes(data) + original_open = Path.open + swapped = False + + def swapping_open(path_obj: Path, *args, **kwargs): + nonlocal swapped + if path_obj == target and not swapped: + swapped = True + os.replace(target, parked) + os.replace(replacement, target) + return original_open(path_obj, *args, **kwargs) + + with patch.object(Path, "open", new=swapping_open): + with self.assertRaisesRegex( + ApplicationUpdateError, + "changed before hashing", + ): + _sha256_file(target) + + self.assertTrue(swapped) + self.assertEqual(data, target.read_bytes()) + self.assertEqual(data, parked.read_bytes()) + + def test_hash_rejects_symlink_without_following_target(self): + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + real = root / "real.exe" + link = root / "artifact.exe" + real.write_bytes(b"trusted bytes") + try: + link.symlink_to(real) + except (OSError, NotImplementedError): + self.skipTest("symlinks unavailable") + + with self.assertRaisesRegex( + ApplicationUpdateError, + "regular non-symlink", + ): + _sha256_file(link) + + self.assertEqual(b"trusted bytes", real.read_bytes()) + + def test_copy_exact_rejects_replaced_source_before_open(self): + data = b"same exact source bytes" + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + source = root / "source.exe" + alternate = root / "alternate.exe" + original = root / "original.exe" + destination = root / "destination.exe" + source.write_bytes(data) + alternate.write_bytes(data) + original_open = Path.open + replaced = False + + def replacing_open(path_obj: Path, *args, **kwargs): + nonlocal replaced + if path_obj == source and not replaced: + replaced = True + os.replace(source, original) + os.replace(alternate, source) + return original_open(path_obj, *args, **kwargs) + + with patch.object(Path, "open", new=replacing_open): + with self.assertRaisesRegex(ApplicationUpdateError, "changed before copy"): + _copy_exact(source, destination) + + self.assertTrue(replaced) + self.assertFalse(destination.exists()) + + 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" + source.write_bytes(b"source exists before forced open failure") + + original_open = Path.open + + def fail_source_open(path_obj, *args, **kwargs): + if path_obj == source: + raise OSError("forced source-open failure") + return original_open(path_obj, *args, **kwargs) + + with patch.object(Path, "open", new=fail_source_open): + with self.assertRaisesRegex( + ApplicationUpdateError, + "update source could not be opened", + ): + _copy_exact(source, destination) + + 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" + 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=True, + ) as discard: + consume_apply_handoff( + root, + current_version="1.0.0", + install_target=target, + verify_same_publisher=lambda _current, _candidate: True, + ) + + discard.assert_called_once_with(root) + self.assertEqual(target.read_bytes(), new) + + def test_consume_handoff_rolls_back_if_apply_authority_cannot_be_disarmed(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", + side_effect=ApplicationUpdateError("forced disarm failure"), + ): + 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_explicit_rollback_restores_exact_previous_bytes(self): + old = b"previous exact executable" + new = b"installed update" + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + target = root / "ScriptureArchive.exe" + rollback = root / "ScriptureArchive.exe.scripture-archive.rollback" + target.write_bytes(new) + rollback.write_bytes(old) + + restored = rollback_installed_update(target, expected_previous_sha256=_sha(old)) + + self.assertEqual(restored, _sha(old)) + self.assertEqual(target.read_bytes(), old) + self.assertEqual(rollback.read_bytes(), old) + + def test_symlink_install_target_is_rejected(self): + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + real = root / "real.exe" + real.write_bytes(b"old") + target = root / "ScriptureArchive.exe" + try: + target.symlink_to(real) + except (OSError, NotImplementedError): + self.skipTest("symlinks unavailable") + staged = root / "staged" / "ScriptureArchive.exe" + staged.parent.mkdir() + staged.write_bytes(b"new") + pending = self._pending(b"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, + ): + with self.assertRaisesRegex(ApplicationUpdateError, "regular non-symlink"): + consume_apply_handoff( + root, + current_version="1.0.0", + install_target=target, + verify_same_publisher=lambda _a, _b: True, + ) + + self.assertEqual(real.read_bytes(), b"old") + + +if __name__ == "__main__": + unittest.main()