From f755869a54af62b076b7bdee8344a14a57caed4f Mon Sep 17 00:00:00 2001 From: Sonja M Thomas Date: Thu, 26 Nov 2026 17:35:26 -0600 Subject: [PATCH] Add ARM signed updates and native release automation --- .gitignore | 2 + BUILD.md | 8 +- CHANGELOG.md | 5 + IMPLEMENTATION_REPORT.md | 3 - JENKINS.md | 20 ++ Jenkinsfile | 78 +++++++ Jenkinsfile.release | 68 ++++++ README.md | 6 +- RELEASE_PROCESS.md | 25 ++ SECURITY.md | 16 ++ UPDATE_MECHANISM.md | 51 ++++ VERSION.md | 1 + VERSIONING.md | 8 +- arm/about.py | 15 +- arm/application.py | 16 ++ arm/config.py | 6 + arm/dialogs.py | 4 + arm/tray_menu.py | 1 + arm/update_client.py | 181 +++++++++++++++ arm/update_release.py | 112 +++++++++ arm/update_ui.py | 288 +++++++++++++++++++++++ arm/update_worker.py | 360 +++++++++++++++++++++++++++++ arm/version.py | 28 ++- packaging/setup.iss | 11 +- requirements.txt | 2 + tests/test_updates.py | 152 ++++++++++++ tests/windows_gui.py | 60 ++++- tools/build_windows.py | 35 ++- tools/ci_release.py | 243 +++++++++++++++++++ tools/install_ci_compiler.py | 15 ++ tools/maintenance.py | 5 + tools/prepare_windows_compiler.ps1 | 19 ++ update-source.json | 6 + 33 files changed, 1814 insertions(+), 36 deletions(-) create mode 100644 JENKINS.md create mode 100644 Jenkinsfile create mode 100644 Jenkinsfile.release create mode 100644 RELEASE_PROCESS.md create mode 100644 UPDATE_MECHANISM.md create mode 100644 VERSION.md create mode 100644 arm/update_client.py create mode 100644 arm/update_release.py create mode 100644 arm/update_ui.py create mode 100644 arm/update_worker.py create mode 100644 tests/test_updates.py create mode 100644 tools/ci_release.py create mode 100644 tools/install_ci_compiler.py create mode 100644 tools/maintenance.py create mode 100644 tools/prepare_windows_compiler.ps1 create mode 100644 update-source.json diff --git a/.gitignore b/.gitignore index 48dd3a6..dc64a56 100644 --- a/.gitignore +++ b/.gitignore @@ -4,4 +4,6 @@ __pycache__/ build/ dist/ release/ +evidence/ +.ci/ *.spec diff --git a/BUILD.md b/BUILD.md index 2cc8150..c43c8e2 100644 --- a/BUILD.md +++ b/BUILD.md @@ -27,5 +27,9 @@ Settings and history stay under the user's local app data across upgrades and uninstall. Extract the portable ZIP before running AdaptiveResourceMonitor.exe. Both packages contain their Python and Qt runtime. -The alpha artifacts are unsigned. An Authenticode signing and distribution -workflow requires the publisher's certificate and publication authorization. +Jenkins adds signed release manifests and a pinned build receipt. A local +build produces packages and SHA-256 hashes. The maintenance executable and +runtime package both embed VERSION.md and the public verification key. +See [Jenkins](JENKINS.md) for the signed build workflow. Ed25519 authenticates +the package hashes in the update manifest. The Windows executables and +installer use a separate Authenticode trust mechanism. diff --git a/CHANGELOG.md b/CHANGELOG.md index e60f998..2df43a4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,10 @@ # Changelog +## v0.6.1.1_alpha — 2026-11-26 + +- Added signed update discovery, verified downloads and authorized installation for installed and portable Windows x64 editions. +- Added Jenkins build, signing and archive automation and an explicitly invoked publication workflow for Gitea releases. + ## v0.4.1.1_alpha — 2026-11-26 - Removed Aggregate - Peak and migrated saved selections to All Systems. diff --git a/IMPLEMENTATION_REPORT.md b/IMPLEMENTATION_REPORT.md index 1cbd5d4..2b783d9 100644 --- a/IMPLEMENTATION_REPORT.md +++ b/IMPLEMENTATION_REPORT.md @@ -92,9 +92,6 @@ behavior on a private native Windows desktop. | All Systems hover | 12 s | 0.358% | 5.729% | 159.46 MiB | | All Systems expanded | 12 s | 0.260% | 4.167% | 162.32 MiB | -### Native captures - - ### Release verification and cleanup All 17 automated tests passed. Native tray and About regression checks also diff --git a/JENKINS.md b/JENKINS.md new file mode 100644 index 0000000..42137e0 --- /dev/null +++ b/JENKINS.md @@ -0,0 +1,20 @@ +# Jenkins + +The Phantom Jenkins controller's Applications view contains the +Adaptive Resource Monitor folder at job/Adaptive-Resource-Monitor/. +Both jobs use the existing inkiron-windows native Windows x64 agent through +its inkiron-windows-x64 label. The agent needs Windows Git, Python 3.12 x64, +trusted HTTPS, workspace write access and permission to create a private +Windows desktop for acceptance. The build stages a hash-pinned and +Authenticode-verified Inno Setup 7.1.1 portable compiler in the workspace. + +- **Build and Archive** (Build-and-Archive) checks main with hashed five-minute SCM polling. It validates VERSION.md, checks dependencies, runs the test suite and isolated native test, builds native x64 packages, validates the binaries and archive, signs the update manifest and fingerprints the candidate. It retains 15 build records and six artifact sets. +- **Publish Release** (Publish-Release) is a manual job with 20 retained records. It validates an explicit build number, exact source commit and authoritative version. Verification-only mode is the default. It uses Copy Artifact to retrieve the chosen archive. + +The ARM folder owns the arm-gitea-read checkout identity, +arm-ed25519-release signing credential and arm-gitea-release write credential. +The two Gitea service identities are scoped through repository access to ARM. +Source checkout uses the Git credential binding. The Ed25519 and publication +secrets are bound only for their respective stages. Workspace cleanup follows +both jobs. About reports the packaged Git revision and build time. BUILD.json +and the signed release receipt record the exact Jenkins build number. diff --git a/Jenkinsfile b/Jenkinsfile new file mode 100644 index 0000000..2ade474 --- /dev/null +++ b/Jenkinsfile @@ -0,0 +1,78 @@ +pipeline { + agent { label 'inkiron-windows-x64' } + options { + skipDefaultCheckout() + disableConcurrentBuilds() + buildDiscarder(logRotator(numToKeepStr: '15', artifactNumToKeepStr: '6')) + copyArtifactPermission('Adaptive-Resource-Monitor/Publish-Release') + timeout(time: 35, unit: 'MINUTES') + timestamps() + } + triggers { pollSCM('H/5 * * * *') } + environment { + PYTHONDONTWRITEBYTECODE = '1' + PIP_NO_CACHE_DIR = '1' + PIP_DISABLE_PIP_VERSION_CHECK = '1' + } + stages { + stage('Source checkout and version') { + steps { + deleteDir() + checkout scm + script { + env.ARM_SOURCE_COMMIT = bat(returnStdout: true, script: '@git rev-parse HEAD').trim() + env.ARM_VERSION = readFile('VERSION.md').trim() + if (!(env.ARM_SOURCE_COMMIT ==~ /[0-9a-f]{40}/) || + !(env.ARM_VERSION ==~ /v(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)_(alpha|beta|rc|stable)/)) { + error('Invalid Git commit or authoritative VERSION.md.') + } + currentBuild.description = "${env.ARM_VERSION} · ${env.ARM_SOURCE_COMMIT.take(12)} · internal archive" + echo "Native Windows agent ${env.NODE_NAME}, build #${env.BUILD_NUMBER}, ${env.ARM_VERSION}, ${env.ARM_SOURCE_COMMIT}" + } + } + } + stage('Environment and dependencies') { + steps { + bat 'py -3.12 -m venv .ci\\python' + bat '.ci\\python\\Scripts\\python.exe -m pip install -r requirements-build.txt' + bat '.ci\\python\\Scripts\\python.exe -m pip check' + bat 'powershell.exe -NoLogo -NoProfile -NonInteractive -File tools\\prepare_windows_compiler.ps1' + } + } + stage('Regression and native Windows checks') { + steps { + bat '.ci\\python\\Scripts\\python.exe -m unittest discover -s tests -v' + bat '.ci\\python\\Scripts\\python.exe tests\\windows_gui.py --short' + } + } + stage('Native Windows build, installer and portable ZIP') { + steps { + bat '.ci\\python\\Scripts\\python.exe tools\\build_windows.py --iscc .ci\\inno\\ISCC.exe --output release\\candidate' + } + } + stage('Native package and executable metadata validation') { + steps { + bat '.ci\\python\\Scripts\\python.exe tests\\windows_gui.py --package release\\candidate --portable-only' + } + } + stage('Checksums, signed manifest and receipt') { + steps { + withCredentials([string(credentialsId: 'arm-ed25519-release', variable: 'ARM_ED25519_SIGNING_KEY')]) { + bat '@.ci\\python\\Scripts\\python.exe tools\\ci_release.py sign release\\candidate %ARM_SOURCE_COMMIT% %BUILD_NUMBER%' + } + } + } + stage('Artifact verification and archival') { + steps { + bat '.ci\\python\\Scripts\\python.exe tools\\ci_release.py verify release\\candidate %ARM_SOURCE_COMMIT% %BUILD_NUMBER%' + archiveArtifacts artifacts: 'release/candidate/*', fingerprint: true + } + } + } + post { + cleanup { + deleteDir() + echo 'Removed the ARM build workspace. Verified candidates are stored in Jenkins archival.' + } + } +} diff --git a/Jenkinsfile.release b/Jenkinsfile.release new file mode 100644 index 0000000..b9201d7 --- /dev/null +++ b/Jenkinsfile.release @@ -0,0 +1,68 @@ +pipeline { + agent { label 'inkiron-windows-x64' } + options { + skipDefaultCheckout() + disableConcurrentBuilds() + buildDiscarder(logRotator(numToKeepStr: '20')) + timeout(time: 30, unit: 'MINUTES') + timestamps() + } + parameters { + string(name: 'BUILD_TO_PUBLISH', defaultValue: '', description: 'Exact successful ARM Build-and-Archive build number.') + string(name: 'SOURCE_COMMIT', defaultValue: '', description: 'Exact full Git SHA-1 from the selected build receipt.') + string(name: 'RELEASE_VERSION', defaultValue: '', description: 'Exact version from VERSION.md for the selected commit.') + booleanParam(name: 'VERIFY_ONLY', defaultValue: true, description: 'Validate the exact archive without access to publication credentials.') + booleanParam(name: 'AUTHORIZE_PUBLICATION', defaultValue: false, description: 'Explicitly authorize publishing this pinned build.') + } + environment { + PYTHONDONTWRITEBYTECODE = '1' + PIP_NO_CACHE_DIR = '1' + PIP_DISABLE_PIP_VERSION_CHECK = '1' + } + stages { + stage('Validate authorization and pin') { + steps { + script { + if (!(params.BUILD_TO_PUBLISH ==~ /[1-9][0-9]*/) || + !(params.SOURCE_COMMIT ==~ /[0-9a-f]{40}/) || + !(params.RELEASE_VERSION ==~ /v(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)_(alpha|beta|rc|stable)/)) { + error('Select the exact archive build, commit and application version.') + } + if (!params.VERIFY_ONLY && !params.AUTHORIZE_PUBLICATION) { + error('Public release publication requires explicit authorization.') + } + env.ARM_PIN_BUILD = params.BUILD_TO_PUBLISH + env.ARM_PIN_COMMIT = params.SOURCE_COMMIT + env.ARM_PIN_VERSION = params.RELEASE_VERSION + currentBuild.description = "#${env.ARM_PIN_BUILD} · ${env.ARM_PIN_VERSION} · ${params.VERIFY_ONLY ? 'verification only' : 'authorized publication'}" + } + } + } + stage('Retrieve pinned successful archive') { + steps { + deleteDir() + checkout scm + copyArtifacts projectName: '/Adaptive-Resource-Monitor/Build-and-Archive', + selector: specific("${env.ARM_PIN_BUILD}"), filter: 'release/candidate/*', + target: 'release/pinned', flatten: true, fingerprintArtifacts: true + bat 'py -3.12 -m venv .ci\\python' + bat '.ci\\python\\Scripts\\python.exe -m pip install --no-cache-dir -r requirements.txt' + bat '.ci\\python\\Scripts\\python.exe tools\\ci_release.py verify release\\pinned %ARM_PIN_COMMIT% %ARM_PIN_BUILD% --version %ARM_PIN_VERSION%' + } + } + stage('Publish and verify anonymous downloads') { + when { expression { !params.VERIFY_ONLY && params.AUTHORIZE_PUBLICATION } } + steps { + withCredentials([string(credentialsId: 'arm-gitea-release', variable: 'ARM_GITEA_PUBLISH_TOKEN')]) { + bat '@.ci\\python\\Scripts\\python.exe tools\\ci_release.py publish release\\pinned %ARM_PIN_COMMIT% %ARM_PIN_BUILD% --version %ARM_PIN_VERSION%' + } + } + } + } + post { + cleanup { + deleteDir() + echo 'Removed the ARM publication workspace and copied archive.' + } + } +} diff --git a/README.md b/README.md index 87d14b3..57f5fe7 100644 --- a/README.md +++ b/README.md @@ -29,7 +29,11 @@ throughput scale per machine. Open the About tab from the monitor window or tray menu for build information, version history and support links. -The application version is defined in [arm/version.py](arm/version.py). +The application version is defined in [VERSION.md](VERSION.md). Open **About → +Check for Updates** to check the public ARM Releases page. Downloading and +installing are separate actions. Settings can enable startup or periodic checks. +Both Windows x64 distributions use signed update metadata. See +[Update mechanism](UPDATE_MECHANISM.md) and [Release process](RELEASE_PROCESS.md). See [BUILD.md](BUILD.md) for Windows build and verification commands, [TELEMETRY_PROVIDERS.md](TELEMETRY_PROVIDERS.md) for metric definitions, [REMOTE_MONITORING.md](REMOTE_MONITORING.md) for SSH setup, and diff --git a/RELEASE_PROCESS.md b/RELEASE_PROCESS.md new file mode 100644 index 0000000..a0376ff --- /dev/null +++ b/RELEASE_PROCESS.md @@ -0,0 +1,25 @@ +# Release process + +This application uses the existing [Adaptive_Resource_Monitor repository](https://phantom.zapto.org/gitea/sonja/Adaptive_Resource_Monitor) +for both source and public release attachments. Each release tag names the +exact archived source commit. The public attachments are the installer, +portable ZIP, SHA-256 manifest, signed release manifest, signed release notes +as a Markdown file, Ed25519 public key and build receipt. The product builds +never include private configuration, credentials or signing keys. + +1. Wait for a successful ARM Build and Archive run. Record the numbered build, + exact commit and VERSION.md value from its console and release-build.json. +2. Run Publish Release with those three values and **Verify only** enabled. + Check that the job retrieved and verified the exact archived files. +3. After explicit release authorization, run Publish Release with the same + values, turn **Verify only** off, and enable **Authorize publication**. + The publish job reuses the archive without rebuilding. +4. The job verifies the changelog and trusted signature, checks both packages, + uploads into a draft, checks downloaded bytes, and promotes the release. + It then anonymously reads back the Git tag, release, artifacts, hashes and + signature. A failed anonymous verification returns the release to draft + where possible. + +Existing version tags must point to the same commit. A public release for that +version is accepted only if its attachments match the pinned archive. Use a +new authorized application version for any change to its released bytes. diff --git a/SECURITY.md b/SECURITY.md index 5bc6762..889f05d 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -18,3 +18,19 @@ user under %LOCALAPPDATA%\Adaptive Resource Monitor. History and device names can reveal information about the monitored environment. The portable package also uses this user directory. Uninstall preserves the user data. No remote host is contacted until a target is enabled or tested. + +## Application updates + +Update checks and downloads use HTTPS with certificate validation and anonymous +access. The application pins its Ed25519 public key. It checks the signed +version, application identity, architecture, filenames, types and sizes, then +verifies SHA-256 before staging and again before installation. Explicit user +approval is required to install. The maintenance launcher handles application +files and installer registration. ARM's telemetry profile and credentials +remain in the existing per-user stores. + +The Jenkins ARM folder holds the private signing credential. The client bundles +only the public key. A signed manifest binds the downloaded bytes to ARM's +release identity. Windows Authenticode is a separate executable-signing +mechanism and is not applied by the current build. See +[Update mechanism](UPDATE_MECHANISM.md) and [Release process](RELEASE_PROCESS.md). diff --git a/UPDATE_MECHANISM.md b/UPDATE_MECHANISM.md new file mode 100644 index 0000000..f2c2ec9 --- /dev/null +++ b/UPDATE_MECHANISM.md @@ -0,0 +1,51 @@ +# Application updates + +In About, **Check for Updates** reads ARM's public Releases index. The panel +shows the highest published tag, the highest eligible verified version, +the time of the last successful check in the local timezone, package type and +size, verification status, progress and signed release notes. ARM defaults to +manual checks. Settings offers a startup check and periodic checks every +4 hours, 12 hours, day or week. A verified update uses the existing tray icon +for its notification. Checks and downloads run separately from collection. + +**Download Update** stores the signed envelope and verified package in the +application's per-user updates directory. Cancel leaves a partial file. A retry +requests a byte range and validates the server's response. If the server +returns a complete response, ARM starts the file over. **Install Later** +keeps the package. **Install Update** asks for approval. + +## Release contract + +The configured source is the [ARM Releases page](https://phantom.zapto.org/gitea/sonja/Adaptive_Resource_Monitor/releases). +Each release provides arm-update-windows-x64.json with a canonical UTF-8 +JSON manifest and a base64 Ed25519 signature. Protocol 1 includes the +application ID, Windows x64 architecture, exact VERSION.md value, Git commit, +Jenkins build number and release notes. Its installed and portable package +records carry the exact filename, byte count and SHA-256. The trusted public +key is embedded in both executables. A client accepts its own release channel +and eligible stable releases. A package for installation must be strictly newer. + +## Installed and portable applications + +The installed variant is identified from Windows' uninstall registration. +The maintenance launcher verifies the download, starts from a staged copy +outside the installed directory and waits for the monitor to close. The +monitor closes its collectors and drains pending history writes. The launcher +uses the native installer for an installed copy. For portable copies it +verifies and extracts the ZIP into staging on the same volume and replaces +only distribution-owned entries. Existing files outside those entries stay +in place. Before restarting ARM, the launcher verifies the new executable, +version and build metadata. The restarted process signals readiness. + +## Recovery + +The launcher creates a transaction journal before replacing files and retains +the prior application files until the new process confirms readiness. It +restores the previous executable and installer registration on failure. An +interrupted transaction can recover from the independently staged launcher +through the per-user Windows RunOnce entry. If a file is still locked, the +transaction and its backup remain available. The About panel reads the most +recent update result. Details are in maintenance.log and, for Setup, +installer.log under the transaction directory. Keep transaction files while an +installation is pending. Profiles, the Credential Manager, SSH trust and +telemetry history are outside the file-replacement transaction. diff --git a/VERSION.md b/VERSION.md new file mode 100644 index 0000000..cbb5c7f --- /dev/null +++ b/VERSION.md @@ -0,0 +1 @@ +v0.6.1.1_alpha diff --git a/VERSIONING.md b/VERSIONING.md index a980124..ad16c02 100644 --- a/VERSIONING.md +++ b/VERSIONING.md @@ -5,8 +5,10 @@ cumulative. Increment the appropriate counter and retain the other values. The initial milestone uses the alpha tag. Version updates happen once per milestone. -Edit arm/version.py to update the authoritative version. The application, -About tab, executable text resource, installer version, portable VERSION.txt, -and artifact filenames derive from it. The Windows binary version resource +Edit VERSION.md to update the authoritative version. The application, About +tab, executable text resource, installer version, portable version files, +Git release tag, manifest and Jenkins artifact receipt derive from it. +Jenkins numbers identify individual builds and are recorded separately. +The Windows binary version resource uses the four numeric fields because the PE numeric version cannot contain a prefix or tag. The Windows product and file version strings retain both. diff --git a/arm/about.py b/arm/about.py index 3ec76e5..671cab6 100644 --- a/arm/about.py +++ b/arm/about.py @@ -20,15 +20,15 @@ from .branding import ( SUPPORT_URL, WEBSITE, asset, document, ) from .version import NAME, VERSION +from .update_ui import UpdatePanel LOG = logging.getLogger(__name__) DOCS = { - "README.md": "Project Guide", + "README.md": "README", "CHANGELOG.md": "Change Log", "LICENSE.md": "Software License", "THIRD_PARTY.md": "Third-party Notices", } -UPDATE_STATUS = "No update channel configured." UNINSTALL_KEY = rf"Software\Microsoft\Windows\CurrentVersion\Uninstall\{INSTALL_ID}_is1" @@ -129,8 +129,7 @@ class AboutPage(QWidget): license_info = ("See Software License below." if "LICENSE.md" in self.documents else "Project license terms unavailable.") details.addRow("Software license", QLabel(license_info)) - details.addRow("Updates", QLabel(UPDATE_STATUS)) - view = QPushButton("View Details") + view = QPushButton("Application Details") view.clicked.connect(self.show_details) buttons = QHBoxLayout() buttons.addWidget(view) @@ -138,6 +137,9 @@ class AboutPage(QWidget): details.addRow(buttons) layout.addWidget(information) + self.updates = UpdatePanel(data_root, installation()[0]) + layout.addWidget(self.updates) + self.links = QLabel(alignment=center) self.links.setWordWrap(True) self.links.setTextInteractionFlags(Qt.TextInteractionFlag.TextBrowserInteraction) @@ -179,7 +181,8 @@ class AboutPage(QWidget): }} """) self.website.setText(link(WEBSITE, "www.designcreations.us", colors.accent)) - items = [link(name, label, colors.accent) for name, label in self.documents.items()] + items = [link(name, name if name in ("README.md", "CHANGELOG.md") else label, colors.accent) + for name, label in self.documents.items()] items.append(link(SUPPORT_URL, "Contact & Support", colors.accent)) self.links.setText(" | ".join(items)) @@ -213,7 +216,7 @@ class AboutPage(QWidget): ("Source revision", revision), ("Platform", f"{platform.system()} · {platform.machine()} · {struct.calcsize('P') * 8}-bit"), ("Installation type", kind), ("Installation location", str(directory)), - ("Application data", str(self.data_root)), ("Updates", UPDATE_STATUS), + ("Application data", str(self.data_root)), ) dialog = QDialog(self) dialog.setWindowTitle("Application Details") diff --git a/arm/application.py b/arm/application.py index d4bf684..ac095e2 100644 --- a/arm/application.py +++ b/arm/application.py @@ -82,6 +82,8 @@ class Application(QObject): self.icons = {} self.menus = {} self.about_page = AboutPage(self.root) + self.about_page.updates.notify.connect(self.update_notice) + self.about_page.updates.quit_requested.connect(self.qt.quit) self.expanded = Monitor(self.dashboard, True, self.request_archive, self.open_expanded, self.set_pin, self.about_page) self.expanded.setWindowIcon(self.brand_icon) @@ -129,6 +131,7 @@ class Application(QObject): self.expanded.sync() self.restore_monitor() self.render() + self.about_page.updates.configure(settings) def configure_history(self): cfg = self.settings @@ -190,6 +193,7 @@ class Application(QObject): icon = QSystemTrayIcon(self) icon.setIcon(self.brand_icon) icon.activated.connect(partial(self.activate_icon, machine)) + icon.messageClicked.connect(self.about) self.icons[machine] = icon self.menus[machine] = TrayMenu(self, machine) self.menus[machine].theme(self.brand_colors) @@ -489,6 +493,15 @@ class Application(QObject): def about(self): self.expanded.show_page(about=True) + def check_for_updates(self): + self.about() + self.about_page.updates.check_now() + + def update_notice(self, version): + icon = self.icons.get(self.settings.tray_machine) + if icon: + icon.showMessage(NAME, f"Verified update {version} is available. Open About for details.") + def open_website(self): QDesktopServices.openUrl(QUrl(WEBSITE)) @@ -496,6 +509,7 @@ class Application(QObject): if self._closed: return self._closed = True + self.about_page.updates.stop() for timer in (self.tray_timer, self.hover_timer, self.view_timer): timer.stop() for icon in self.icons.values(): @@ -531,6 +545,8 @@ def main(): controller = Application(app, root) if not controller.settings.minimized: controller.open_expanded() + from .update_worker import signal_ready + signal_ready() return app.exec() finally: if controller is not None: diff --git a/arm/config.py b/arm/config.py index e18909f..4a9b565 100644 --- a/arm/config.py +++ b/arm/config.py @@ -112,6 +112,8 @@ class Settings: max_history_mb: int = 128 history_file: str = "" log_level: str = "INFO" + update_startup: bool = False + update_interval: int = 0 targets: list[Target] = field(default_factory=list) @classmethod @@ -152,6 +154,10 @@ class Settings: cfg.network_colors = {key: valid_color(network_colors.get(key), value[1]) for key, value in NETWORK.items()} cfg.background = valid_color(cfg.background, "#171a22") + if not isinstance(cfg.update_startup, bool): + cfg.update_startup = False + if type(cfg.update_interval) is not int or cfg.update_interval not in (0, 4, 12, 24, 168): + cfg.update_interval = 0 cfg.targets = [Target.from_dict(item) for item in cfg.targets if isinstance(item, dict)] if isinstance(cfg.targets, list) else [] cfg.targets = list({target.identifier: target for target in cfg.targets}.values()) legacy_tray = source.get("tray_mode") diff --git a/arm/dialogs.py b/arm/dialogs.py index c669c63..064c80d 100644 --- a/arm/dialogs.py +++ b/arm/dialogs.py @@ -160,6 +160,10 @@ class SettingsDialog(QDialog): self.check(form, "Start minimized", "minimized") self.select(form, "Theme", "theme", [(value, value) for value in ("System", "Light", "Dark")]) self.select(form, "Default machine", "default_machine", machine_choices(self.app.dashboard)) + self.check(form, "Check for updates at startup", "update_startup") + self.select(form, "Check for updates periodically", "update_interval", + [("Off", 0), ("Every 4 hours", 4), ("Every 12 hours", 12), + ("Daily", 24), ("Weekly", 168)]) def tray(self): form = self.section("Tray Icon") diff --git a/arm/tray_menu.py b/arm/tray_menu.py index 67529f0..6973f6c 100644 --- a/arm/tray_menu.py +++ b/arm/tray_menu.py @@ -56,6 +56,7 @@ class TrayMenu(QMenu): self.addSeparator() self.action(self, f"About {NAME}", SP.SP_MessageBoxInformation, app.about) + self.action(self, "Check for Updates", SP.SP_BrowserReload, app.check_for_updates) self.action(self, "Design Creations Website", SP.SP_DriveNetIcon, app.open_website) self.addSeparator() self.action(self, f"Exit {NAME}", None, app.qt.quit) diff --git a/arm/update_client.py b/arm/update_client.py new file mode 100644 index 0000000..02797d7 --- /dev/null +++ b/arm/update_client.py @@ -0,0 +1,181 @@ +"""Anonymous update discovery and verified downloads from the ARM release repository.""" +from dataclasses import dataclass +import json +import os +from pathlib import Path +import re +from urllib.error import HTTPError, URLError +from urllib.parse import quote, urlsplit +from urllib.request import HTTPRedirectHandler, Request, build_opener + +from .update_release import MANIFEST, MAX_MANIFEST_SIZE, Release, UpdateError, eligible, source_config, verify_file, verify_manifest +from .version import VERSION, version_key + +MAX_INDEX_SIZE = 2 * 1024**2 +BLOCK = 256 * 1024 + + +class UpdateCancelled(UpdateError): + pass + + +class NoRedirect(HTTPRedirectHandler): + def redirect_request(self, *args, **kwargs): + return None + + +@dataclass(frozen=True) +class Check: + published: str | None + release: Release | None + issues: tuple[str, ...] + + +class ReleaseClient: + def __init__(self, source=None): + self.source = source if source is not None else source_config() + self.base = self.source["base"].rstrip("/") + origin = urlsplit(self.base) + if origin.scheme != "https" or not origin.hostname or origin.username or origin.password or origin.query or origin.fragment: + raise UpdateError("Update source requires a validated HTTPS origin") + for field in ("owner", "repository"): + if not re.fullmatch(r"[A-Za-z0-9_-]+", self.source[field]): + raise UpdateError("Update source repository is invalid") + self.repository = f"{self.source['owner']}/{self.source['repository']}" + self.api = f"{self.base}/api/v1/repos/{self.repository}" + self.opener = build_opener(NoRedirect()) + + def url(self, version, name): + return f"{self.base}/{self.repository}/releases/download/{quote(version, safe='')}/{quote(name, safe='')}" + + def open(self, url, headers=None): + return self.opener.open(Request(url, headers={ + "User-Agent": f"AdaptiveResourceMonitor/{VERSION}", "Accept-Encoding": "identity", **(headers or {}) + }), timeout=15) + + def read(self, url, limit): + with self.open(url) as response: + data = response.read(limit + 1) + if len(data) > limit: + raise UpdateError("Release server returned oversized metadata") + return data + + def attachment(self, row, version, name, size=None): + matches = [asset for asset in row["assets"] if asset.get("name") == name] + expected = self.url(version, name) + if len(matches) != 1 or matches[0].get("browser_download_url") != expected: + raise UpdateError(f"Missing or inconsistent release attachment: {name}") + if size is not None and matches[0].get("size") != size: + raise UpdateError(f"Release attachment size is inconsistent: {name}") + return expected + + def check(self, installed, kind): + rows = {} + for page in range(1, 11): + batch = json.loads(self.read(f"{self.api}/releases?limit=50&page={page}", MAX_INDEX_SIZE)) + if not isinstance(batch, list): + raise UpdateError("Release server returned an invalid index") + for row in batch: + if not isinstance(row, dict) or row.get("draft") is not False: + continue + version = row.get("tag_name") + try: + version_key(version) + except ValueError: + continue + rows.setdefault(version, []).append(row) + if len(batch) < 50: + break + ordered = sorted(rows, key=version_key, reverse=True) + issues = [] + for version in ordered: + if not eligible(version, installed): + continue + try: + if len(rows[version]) != 1: + raise UpdateError("Release tag appears more than once") + row = rows[version][0] + address = self.attachment(row, version, MANIFEST) + release = verify_manifest(self.read(address, MAX_MANIFEST_SIZE), self.source["public_key"], version) + if row.get("prerelease") is not (not version.endswith("_stable")): + raise UpdateError("Release classification disagrees with its signed version") + if row.get("body") != release.notes: + raise UpdateError("Public release notes disagree with the signed manifest") + for package in release.packages.values(): + self.attachment(row, version, package.name, package.size) + except (UpdateError, HTTPError, KeyError, TypeError, AttributeError) as exc: + issues.append(f"{version}: {exc.code if isinstance(exc, HTTPError) else exc}") + continue + return Check(ordered[0], release, tuple(issues)) + return Check(ordered[0] if ordered else None, None, tuple(issues)) + + def download(self, release, kind, storage, progress, cancelled): + signed = verify_manifest(release.envelope, self.source["public_key"], release.version) + if not eligible(signed.version, VERSION) or signed.version == VERSION: + raise UpdateError("Only an eligible version newer than the installed application may be downloaded") + package = signed.packages[kind] + folder = Path(storage) / f"{signed.version}-{package.sha256}" + folder.mkdir(parents=True, exist_ok=True) + output = folder / package.name + part = output.with_suffix(output.suffix + ".part") + if output.is_file(): + try: + verify_file(output, package) + except UpdateError: + output.unlink() + if not output.is_file(): + try: + self.fetch(self.url(signed.version, package.name), part, package.size, progress, cancelled) + if cancelled(): + raise UpdateCancelled("Download paused. Its partial file can be resumed.") + part.replace(output) + try: + verify_file(output, package) + except UpdateError: + output.unlink(missing_ok=True) + raise + except (URLError, OSError) as exc: + raise UpdateError(f"Download interrupted: {exc}. Retry to resume.") from None + write_atomic(folder / MANIFEST, signed.envelope) + return output + + def fetch(self, address, part, size, progress, cancelled): + offset = part.stat().st_size if part.is_file() else 0 + if offset > size: + part.unlink() + offset = 0 + if offset == size: + return + with self.open(address, {"Range": f"bytes={offset}-"} if offset else {}) as response: + if response.status == 200: + offset = 0 + elif not (offset and response.status == 206 + and response.headers.get("Content-Range") == f"bytes {offset}-{size-1}/{size}"): + raise UpdateError("Update server returned an invalid download range") + remaining = size - offset + length = response.headers.get("Content-Length") + if length is not None and length != str(remaining): + raise UpdateError("Download length does not match the signed manifest") + with part.open("ab" if offset else "wb") as output: + progress(offset, size) + while remaining: + if cancelled(): + raise UpdateCancelled("Download paused. Its partial file can be resumed.") + data = response.read(min(BLOCK, remaining)) + if not data: + raise UpdateError("Download interrupted. Retry to resume.") + output.write(data) + remaining -= len(data) + progress(size - remaining, size) + if response.read(1): + part.unlink(missing_ok=True) + raise UpdateError("Update server returned bytes beyond the signed size") + + +def write_atomic(path, data): + temporary = path.with_name(path.name + ".tmp") + with temporary.open("wb") as stream: + stream.write(data) + stream.flush() + os.fsync(stream.fileno()) + temporary.replace(path) diff --git a/arm/update_release.py b/arm/update_release.py new file mode 100644 index 0000000..e6c70bf --- /dev/null +++ b/arm/update_release.py @@ -0,0 +1,112 @@ +"""Signed release contract shared by the updater, maintenance worker and CI.""" +from base64 import b64decode +from dataclasses import dataclass +from hashlib import file_digest +import json +from pathlib import Path +import re + +from cryptography.exceptions import InvalidSignature +from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey + +from .branding import APP_MODEL_ID +from .version import ROOT, version_key + +MANIFEST = "arm-update-windows-x64.json" +ARCHITECTURE = "windows-x64" +KINDS = {"installed": "-setup.exe", "portable": "-portable.zip"} +MAX_PACKAGE_SIZE = 1024**3 +MAX_MANIFEST_SIZE = 256 * 1024 +MAX_NOTES_LENGTH = 32_000 +SHA256 = re.compile(r"[0-9a-f]{64}") +COMMIT = re.compile(r"[0-9a-f]{40}") + + +class UpdateError(Exception): + pass + + +def source_config(): + return json.loads((ROOT / "update-source.json").read_text(encoding="utf-8")) + + +def canonical(value): + return json.dumps(value, sort_keys=True, separators=(",", ":"), ensure_ascii=False, allow_nan=False).encode("utf-8") + + +def sha256(path): + with Path(path).open("rb") as stream: + return file_digest(stream, "sha256").hexdigest() + + +def artifact_name(version, kind): + version_key(version) + return f"AdaptiveResourceMonitor-{version}-{ARCHITECTURE}{KINDS[kind]}" + + +@dataclass(frozen=True) +class Package: + kind: str + name: str + size: int + sha256: str + + +@dataclass(frozen=True) +class Release: + version: str + commit: str + build: int + notes: str + packages: dict[str, Package] + envelope: bytes + + +def verify_manifest(raw, public_key, expected_version=None): + try: + if len(raw) > MAX_MANIFEST_SIZE: + raise ValueError() + envelope = json.loads(raw) + if set(envelope) != {"manifest", "signature"}: + raise ValueError() + manifest = envelope["manifest"] + key = Ed25519PublicKey.from_public_bytes(b64decode(public_key, validate=True)) + key.verify(b64decode(envelope["signature"], validate=True), canonical(manifest)) + if (set(manifest) != {"protocol", "application", "architecture", "version", "commit", "build", "notes", "packages"} + or type(manifest["protocol"]) is not int or manifest["protocol"] != 1 + or manifest["application"] != APP_MODEL_ID or manifest["architecture"] != ARCHITECTURE): + raise ValueError() + version = manifest["version"] + version_key(version) + if expected_version is not None and version != expected_version: + raise ValueError() + if (not COMMIT.fullmatch(manifest["commit"]) or type(manifest["build"]) is not int or manifest["build"] < 1 + or not isinstance(manifest["notes"], str) or not 1 <= len(manifest["notes"]) <= MAX_NOTES_LENGTH + or set(manifest["packages"]) != set(KINDS)): + raise ValueError() + packages = {} + for kind, data in manifest["packages"].items(): + if (set(data) != {"name", "size", "sha256"} or data["name"] != artifact_name(version, kind) + or type(data["size"]) is not int or not 0 < data["size"] <= MAX_PACKAGE_SIZE + or not SHA256.fullmatch(data["sha256"])): + raise ValueError() + packages[kind] = Package(kind, **data) + except InvalidSignature: + raise UpdateError("Ed25519 manifest signature is invalid") from None + except (KeyError, TypeError, ValueError, AttributeError, OverflowError): + raise UpdateError("Signed release metadata is invalid or inconsistent") from None + return Release(version, manifest["commit"], manifest["build"], manifest["notes"], packages, raw) + + +def verify_file(path, package): + path = Path(path) + if path.name != package.name or not path.is_file() or path.stat().st_size != package.size: + raise UpdateError("Package filename or size does not match the signed manifest") + if sha256(path) != package.sha256: + raise UpdateError("Package SHA-256 does not match the signed manifest") + + +def eligible(version, installed): + candidate = version_key(version) + current = version_key(installed) + return candidate >= current and candidate[-1] in (current[-1], 3) diff --git a/arm/update_ui.py b/arm/update_ui.py new file mode 100644 index 0000000..ba93d5b --- /dev/null +++ b/arm/update_ui.py @@ -0,0 +1,288 @@ +"""Asynchronous Workshop-style update controls for the About tab.""" +from datetime import datetime +import json +import logging +from threading import Event, Thread + +from PySide6.QtCore import Qt, QTimer, Signal +from PySide6.QtWidgets import ( + QFormLayout, QGridLayout, QGroupBox, QLabel, QMessageBox, QPlainTextEdit, QProgressBar, + QPushButton, QVBoxLayout, +) + +from .update_client import ReleaseClient, UpdateCancelled, write_atomic +from .update_release import MANIFEST, UpdateError, eligible, verify_file, verify_manifest +from .version import VERSION, version_key + +LOG = logging.getLogger(__name__) +PACKAGE_LABELS = {"installed": "Windows x64 installer", "portable": "Windows x64 portable ZIP"} + + +class UpdatePanel(QGroupBox): + notify = Signal(str) + result = Signal(str, object) + transferred = Signal(int, int) + quit_requested = Signal() + + def __init__(self, root, installation_kind): + super().__init__("Application Update") + self.root = root / "updates" + self.kind = "installed" if installation_kind == "Windows installed" else "portable" + self.installable = installation_kind != "Source checkout" + self.client = ReleaseClient() + self.job = None + self.release = self.downloaded = self.plan = None + self.announced = set() + self.cancel = Event() + self.closing = False + self.policy = None + self.last_file = self.root / "last-check.json" + self.root.mkdir(parents=True, exist_ok=True) + + layout = QVBoxLayout(self) + summary = QFormLayout() + self.fields = {} + for caption, value in ( + ("Installed version", VERSION), ("Latest published", "Not checked"), + ("Latest eligible verified", "Not checked"), ("Last successful check", self.last_check()), + ("Package", PACKAGE_LABELS[self.kind]), ("Download size", "—"), + ("Verification", "Awaiting a signed manifest"), + ): + field = QLabel(value, textFormat=Qt.TextFormat.PlainText, wordWrap=True) + self.fields[caption] = field + summary.addRow(caption, field) + layout.addLayout(summary) + self.status = QLabel("Ready to check for updates.", textFormat=Qt.TextFormat.PlainText, wordWrap=True) + layout.addWidget(self.status) + self.progress = QProgressBar() + self.progress.setAccessibleName("Update progress") + self.progress.hide() + layout.addWidget(self.progress) + buttons = QGridLayout() + actions = ( + ("Check for Updates", self.check_now), ("Download Update", self.download_now), + ("Cancel Download", self.cancel.set), ("View Details", self.toggle_details), + ("Install Update", self.install_now), ("Install Later", self.defer_install), + ) + self.buttons = {} + for index, (name, action) in enumerate(actions): + button = QPushButton(name) + button.clicked.connect(action) + buttons.addWidget(button, index // 3, index % 3) + self.buttons[name] = button + layout.addLayout(buttons) + self.notes = QPlainTextEdit(readOnly=True) + self.notes.setAccessibleName("Signed release notes") + self.notes.setMaximumHeight(110) + self.notes.hide() + layout.addWidget(self.notes) + self.periodic = QTimer(self) + self.periodic.timeout.connect(self.check_now) + self.handoff = QTimer(self, interval=250) + self.handoff.timeout.connect(self.poll_worker) + self.result.connect(self.finished) + self.transferred.connect(self.update_progress) + self.set_controls() + + def configure(self, settings): + policy = (settings.update_startup, settings.update_interval) + if self.policy == policy: + return + first = self.policy is None + self.policy = policy + self.periodic.stop() + if settings.update_interval: + self.periodic.start(settings.update_interval * 3_600_000) + if first: + QTimer.singleShot(900, self.initialize) + + def initialize(self): + if self.job: + return + self.start("restore", self.restore) + + def last_check(self): + try: + last = datetime.fromisoformat(json.loads(self.last_file.read_bytes())) + return last.astimezone().strftime("%Y-%m-%d %H:%M:%S %Z (UTC%z)") + except (ValueError, TypeError, OSError): + return "No successful check recorded" + + def restore(self): + status = None + plans = sorted((self.root / "transactions").glob("*/status.json"), + key=lambda path: path.stat().st_mtime, reverse=True) + if plans: + status = json.loads(plans[0].read_bytes()).get("message") + verified = [] + for manifest in (self.root / "downloads").glob(f"*/{MANIFEST}"): + try: + release = verify_manifest(manifest.read_bytes(), self.client.source["public_key"]) + if eligible(release.version, VERSION) and release.version != VERSION: + package = release.packages[self.kind] + artifact = manifest.parent / package.name + verify_file(artifact, package) + verified.append((release, artifact)) + except (OSError, UpdateError): + continue + return status, max(verified, key=lambda pair: version_key(pair[0].version), default=(None, None)) + + def start(self, operation, action): + if self.closing or self.job or self.plan: + return + self.job = operation + self.cancel.clear() + self.set_controls() + + def work(): + try: + value = action() + except UpdateCancelled as exc: + operation_result = ("paused", str(exc)) + except Exception as exc: + LOG.warning("ARM update %s: %s", operation, exc) + operation_result = ("error", str(exc)) + else: + operation_result = (operation, value) + if not self.closing: + self.result.emit(*operation_result) + + Thread(target=work, name=f"ARM update {operation}", daemon=True).start() + + def check_now(self): + if self.job or self.plan: + return + self.status.setText("Checking the public release repository…") + self.progress.hide() + self.start("check", lambda: self.client.check(VERSION, self.kind)) + + def set_release(self, release): + self.release = release + package = release.packages[self.kind] + self.fields["Latest eligible verified"].setText(release.version) + self.fields["Download size"].setText(f"{package.size / 1024**2:.1f} MiB ({package.size:,} bytes)") + self.fields["Verification"].setText("Ed25519 manifest and release metadata verified") + self.notes.setPlainText(release.notes) + + def finished(self, operation, value): + self.job = None + self.progress.hide() + if operation == "restore": + message, (release, artifact) = value + if release: + self.set_release(release) + self.downloaded = artifact + self.fields["Verification"].setText("Manifest signature and package SHA-256 verified") + if message or artifact: + self.status.setText(message or "Verified package saved. Install it when ready.") + if self.policy and self.policy[0]: + self.check_now() + elif operation == "check": + self.fields["Latest published"].setText(value.published or "No public releases") + if value.release: + if not self.release or value.release.envelope != self.release.envelope: + self.downloaded = None + self.set_release(value.release) + if self.release.version == VERSION: + self.status.setText("This is the latest verified version.") + else: + self.status.setText("A verified update is available." if self.downloaded is None else "Verified package saved.") + if self.downloaded: + self.fields["Verification"].setText("Manifest signature and package SHA-256 verified") + if self.release.version not in self.announced: + self.announced.add(self.release.version) + self.notify.emit(self.release.version) + else: + if not self.downloaded: + self.release = None + self.notes.clear() + self.fields["Latest eligible verified"].setText("None") + self.fields["Download size"].setText("—") + self.fields["Verification"].setText("Verification failed" if value.issues else "No eligible manifest") + self.status.setText("No eligible verified update is available.") + if value.issues: + self.status.setText(self.status.text() + " Rejected " + "; ".join(value.issues)[:380]) + if value.release or not value.issues: + try: + write_atomic(self.last_file, json.dumps(datetime.now().astimezone().isoformat()).encode()) + self.fields["Last successful check"].setText(self.last_check()) + except OSError: + LOG.exception("Could not save the last successful ARM update check") + elif operation == "download": + self.downloaded = value + self.fields["Verification"].setText("Manifest signature and package SHA-256 verified") + self.status.setText("Verified package saved. Install it when ready.") + elif operation == "prepare": + self.plan = value + self.elapsed = 0 + self.handoff.start() + else: + self.status.setText(("Update unavailable. " if operation == "error" else "") + value) + self.set_controls() + + def download_now(self): + release = self.release + if self.job or self.plan or release is None or release.version == VERSION: + return + self.status.setText("Downloading the signed release package…") + self.progress.setRange(0, 0) + self.progress.show() + self.start("download", lambda: self.client.download( + release, self.kind, self.root / "downloads", self.transferred.emit, self.cancel.is_set)) + + def update_progress(self, received, total): + if self.job == "download": + self.progress.setRange(0, 1000) + self.progress.setValue(received * 1000 // total) + + def toggle_details(self): + self.notes.setVisible(self.notes.isHidden()) + + def install_now(self): + if not self.downloaded or self.job or self.plan or not self.installable: + return + if QMessageBox.question(self, "Install Update", f"Install {self.release.version} and restart Adaptive Resource Monitor?", + QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.No, + QMessageBox.StandardButton.No) != QMessageBox.StandardButton.Yes: + return + from .about import installation + from .update_worker import prepare + release, artifact, target = self.release, self.downloaded, installation()[1] + self.status.setText("Revalidating the package and preparing the maintenance launcher…") + self.progress.setRange(0, 0) + self.progress.show() + self.start("prepare", lambda: prepare(release, artifact, target, self.kind, self.root)) + + def defer_install(self): + self.status.setText("Installation deferred. The verified package will be available from About.") + + def poll_worker(self): + self.elapsed += 250 + try: + status = json.loads((self.plan / "status.json").read_bytes()) + except (OSError, ValueError): + status = {} + if status.get("state") == "waiting": + self.handoff.stop() + self.quit_requested.emit() + elif status.get("state") == "failed" or self.elapsed > 70_000: + self.handoff.stop() + (self.plan / "abort").touch() + self.plan = None + self.status.setText(status.get("message") or "The maintenance launcher did not become ready. Installation was deferred.") + self.set_controls() + + def set_controls(self): + available = self.release is not None and self.release.version != VERSION + idle = self.job is None and self.plan is None + states = (idle, idle and available and self.downloaded is None, self.job == "download", + self.release is not None, idle and self.downloaded is not None and self.installable, + idle and self.downloaded is not None) + for button, enabled in zip(self.buttons.values(), states): + button.setEnabled(enabled) + + def stop(self): + self.closing = True + self.cancel.set() + self.handoff.stop() + self.periodic.stop() diff --git a/arm/update_worker.py b/arm/update_worker.py new file mode 100644 index 0000000..625c565 --- /dev/null +++ b/arm/update_worker.py @@ -0,0 +1,360 @@ +"""Independent Windows updater. Transaction data never includes the ARM user profile.""" +import argparse +import json +import logging +import os +from pathlib import Path, PurePosixPath +import re +import shutil +import stat +import subprocess +import sys +from time import monotonic, sleep +from uuid import uuid4 +import winreg +from zipfile import ZipFile + +import pefile +import psutil + +from .branding import INSTALL_ID, PUBLISHER +from .config import data_path +from .update_client import write_atomic +from .update_release import MANIFEST, UpdateError, eligible, source_config, verify_file, verify_manifest +from .version import VERSION, read_version, version_key + +EXE = "AdaptiveResourceMonitor.exe" +WORKER = "AdaptiveResourceMonitorMaintenance.exe" +MANAGED = {EXE, WORKER, "_internal", "Third-party notices", "VERSION.md", "VERSION.txt", "BUILD.json", + "README.md", "SECURITY.md", "REMOTE_MONITORING.md", "CHANGELOG.md", "LICENSE.md"} +UNINSTALL_KEY = rf"Software\Microsoft\Windows\CurrentVersion\Uninstall\{INSTALL_ID}_is1" +RUN_ONCE = r"Software\Microsoft\Windows\CurrentVersion\RunOnce" +UNINSTALLER = re.compile(r"unins[0-9]{3}\.(?:exe|dat|msg)", re.I) +ACK = "ARM_UPDATE_READY" +LOG = logging.getLogger(__name__) + + +def safe_entry(path): + if path.is_symlink() or getattr(path.lstat(), "st_file_attributes", 0) & stat.FILE_ATTRIBUTE_REPARSE_POINT: + raise UpdateError(f"Update cannot replace the link or junction {path.name}") + + +def registered_view(target): + for view in (winreg.KEY_WOW64_64KEY, winreg.KEY_WOW64_32KEY): + try: + with winreg.OpenKey(winreg.HKEY_CURRENT_USER, UNINSTALL_KEY, 0, winreg.KEY_READ | view) as key: + location = winreg.QueryValueEx(key, "InstallLocation")[0] + if location and Path(location).resolve() == target: + return view + except FileNotFoundError: + continue + return None + + +def verify_executable(path, version): + pe = pefile.PE(str(path), fast_load=True) + try: + pe.parse_data_directories([pefile.DIRECTORY_ENTRY["IMAGE_DIRECTORY_ENTRY_RESOURCE"]]) + table = next(node.StringTable[0].entries for group in pe.FileInfo for node in group if hasattr(node, "StringTable")) + numeric = version_key(version)[:4] + fixed = pe.VS_FIXEDFILEINFO[0] + product = (fixed.ProductVersionMS >> 16, fixed.ProductVersionMS & 65535, + fixed.ProductVersionLS >> 16, fixed.ProductVersionLS & 65535) + file = (fixed.FileVersionMS >> 16, fixed.FileVersionMS & 65535, + fixed.FileVersionLS >> 16, fixed.FileVersionLS & 65535) + if (pe.FILE_HEADER.Machine != 0x8664 or table[b"ProductVersion"].decode().strip() != version + or table[b"FileVersion"].decode().strip() != version + or table[b"CompanyName"].decode().strip() != PUBLISHER or product != numeric or file != numeric): + raise UpdateError(f"Executable identity or version is inconsistent: {path.name}") + finally: + pe.close() + + +def managed_entries(target, installed): + return sorted(entry.name for entry in target.iterdir() + if entry.name in MANAGED or (installed and UNINSTALLER.fullmatch(entry.name))) + + +def unpack_portable(artifact, output, version): + seen, total = set(), 0 + with ZipFile(artifact) as archive: + if len(archive.infolist()) > 10_000: + raise UpdateError("Portable package contains too many entries") + for member in archive.infolist(): + path = PurePosixPath(member.filename) + parts = path.parts + if (len(parts) < 2 or path.is_absolute() or parts[0] != "AdaptiveResourceMonitor" + or parts[1] not in MANAGED or any(not part or part in (".", "..") or part.endswith((".", " ")) + or re.search(r'[<>:"\\|?*\x00-\x1f]', part) or Path(part).is_reserved() for part in parts) + or stat.S_ISLNK(member.external_attr >> 16)): + raise UpdateError("Portable package contains an unexpected or unsafe path") + key = str(path).casefold() + total += member.file_size + if key in seen or total > 2 * 1024**3: + raise UpdateError("Portable package exceeds extraction limits or duplicates a path") + seen.add(key) + destination = output.joinpath(*parts[1:]) + if member.is_dir(): + destination.mkdir(parents=True, exist_ok=True) + else: + destination.parent.mkdir(parents=True, exist_ok=True) + with archive.open(member) as source, destination.open("xb") as target: + shutil.copyfileobj(source, target, 256 * 1024) + verify_payload(output, version) + + +def verify_payload(directory, version): + verify_executable(directory / EXE, version) + verify_executable(directory / WORKER, version) + if any(read_version(path) != version for path in ( + directory / "VERSION.md", directory / "VERSION.txt", directory / "_internal" / "VERSION.md" + )): + raise UpdateError("Packaged version documents are inconsistent") + if json.loads((directory / "BUILD.json").read_bytes()).get("version") != version: + raise UpdateError("Packaged build metadata is inconsistent") + + +def set_status(plan_dir, state, message): + write_atomic(plan_dir / "status.json", json.dumps({"state": state, "message": message}).encode()) + LOG.info("%s. %s", state, message) + + +def prepare(release, artifact, target, kind, root): + config = source_config() + signed = verify_manifest(release.envelope, config["public_key"], release.version) + if not eligible(signed.version, VERSION) or signed.version == VERSION: + raise UpdateError("Maintenance supports eligible upgrades only") + verify_file(artifact, signed.packages[kind]) + plan_dir = root / "transactions" / uuid4().hex + plan_dir.mkdir(parents=True) + plan = plan_dir / "plan.json" + parent = psutil.Process() + data = {"target": str(target), "artifact": str(Path(artifact).resolve()), "kind": kind, + "old": VERSION, "new": signed.version, "parent": parent.pid, "created": parent.create_time()} + write_atomic(plan, json.dumps(data).encode()) + write_atomic(plan_dir / MANIFEST, signed.envelope) + worker = plan_dir / WORKER + shutil.copy2(target / WORKER, worker) + verify_executable(worker, VERSION) + subprocess.Popen([str(worker), str(plan)], cwd=plan_dir, creationflags=subprocess.CREATE_NO_WINDOW) + return plan_dir + + +def snapshot_registry(view): + if view is None: + return [] + with winreg.OpenKey(winreg.HKEY_CURRENT_USER, UNINSTALL_KEY, 0, winreg.KEY_READ | view) as key: + return [winreg.EnumValue(key, index) for index in range(winreg.QueryInfoKey(key)[1])] + + +def restore_registry(view, previous): + if view is None: + return + with winreg.CreateKeyEx(winreg.HKEY_CURRENT_USER, UNINSTALL_KEY, 0, winreg.KEY_WRITE | winreg.KEY_READ | view) as key: + names = [winreg.EnumValue(key, index)[0] for index in range(winreg.QueryInfoKey(key)[1])] + keep = {name.casefold() for name, _, _ in previous} + for name in names: + if name.casefold() not in keep: + winreg.DeleteValue(key, name) + for name, value, kind in previous: + winreg.SetValueEx(key, name, 0, kind, value) + + +def recovery_entry(plan_dir, add): + name = "*ARMUpdate-" + plan_dir.name + with winreg.CreateKey(winreg.HKEY_CURRENT_USER, RUN_ONCE) as key: + if add: + command = subprocess.list2cmdline([str(plan_dir / WORKER), str(plan_dir / "plan.json"), "--recover"]) + winreg.SetValueEx(key, name, 0, winreg.REG_SZ, command) + else: + try: + winreg.DeleteValue(key, name) + except FileNotFoundError: + pass + + +def copy_managed(source, target): + safe_entry(source) + if source.is_dir(): + for item in source.rglob("*"): + safe_entry(item) + shutil.copytree(source, target) + else: + shutil.copy2(source, target) + + +def remove_managed(path): + if path.exists(): + safe_entry(path) + if path.is_dir(): + shutil.rmtree(path) + else: + path.unlink() + + +def wait_parent(data, target, plan_dir): + limit = monotonic() + 75 + while monotonic() < limit: + try: + parent = psutil.Process(data["parent"]) + if abs(parent.create_time() - data["created"]) > 0.01: + return + if Path(parent.exe()).resolve() != target / EXE: + raise UpdateError("The requesting process is not this ARM executable") + except psutil.NoSuchProcess: + return + if (plan_dir / "abort").exists(): + raise UpdateError("Installation canceled before touching the application") + sleep(.25) + raise UpdateError("The application did not exit. Installation was deferred.") + + +def restart(target, version, plan_dir): + ready = plan_dir / "ready.json" + child = subprocess.Popen([str(target / EXE)], cwd=target, env=dict(os.environ, **{ACK: str(ready)})) + try: + deadline = monotonic() + 35 + while monotonic() < deadline and child.poll() is None: + if ready.is_file(): + if json.loads(ready.read_bytes()) == {"version": version, "pid": child.pid}: + return + raise UpdateError("The restarted application reported a different version") + sleep(.2) + raise UpdateError("The restarted application did not confirm initialization") + except BaseException: + if child.poll() is None: + child.terminate() + child.wait(timeout=15) + raise + + +def rollback(target, work, journal): + originals = set(journal["originals"]) + backup = work / "previous" + for name in managed_entries(target, journal["view"] is not None): + if name not in originals or (backup / name).exists(): + remove_managed(target / name) + for original in backup.iterdir(): + original.replace(target / original.name) + restore_registry(journal["view"], journal["registration"]) + verify_executable(target / EXE, journal["old"]) + + +def transact(plan_dir, recover=False): + data = json.loads((plan_dir / "plan.json").read_bytes()) + target = Path(data["target"]).resolve(strict=True) + work = target / (".arm-update-" + plan_dir.name) + checkpoint = plan_dir / "journal.json" + if not eligible(data["new"], VERSION) or data["old"] != VERSION or data["new"] == VERSION: + raise UpdateError("Update plan does not describe an upgrade from this maintenance version") + safe_entry(target) + if recover: + journal = json.loads(checkpoint.read_bytes()) + if journal.get("committed"): + remove_managed(work) + recovery_entry(plan_dir, False) + return + rollback(target, work, journal) + remove_managed(work) + recovery_entry(plan_dir, False) + set_status(plan_dir, "rolled_back", "Restored the previous application after an interrupted installation.") + restart(target, data["old"], plan_dir) + return + release = verify_manifest((plan_dir / MANIFEST).read_bytes(), source_config()["public_key"], data["new"]) + view = registered_view(target) + kind = "installed" if view is not None else "portable" + if data["kind"] != kind: + raise UpdateError("The Windows installation type has changed") + artifact = Path(data["artifact"]) + package = release.packages[kind] + verify_file(artifact, package) + verify_executable(target / EXE, data["old"]) + work.mkdir() + previous = work / "previous" + previous.mkdir() + try: + payload = work / "next" + payload.mkdir() + if kind == "portable": + unpack_portable(artifact, payload, release.version) + else: + shutil.copy2(artifact, payload / package.name) + verify_file(payload / package.name, package) + verify_executable(payload / package.name, release.version) + set_status(plan_dir, "waiting", "Verified the update. Waiting for the monitor to close and save its history.") + wait_parent(data, target, plan_dir) + verify_file(artifact, package) + for name in managed_entries(target, view is not None): + safe_entry(target / name) + originals = managed_entries(target, view is not None) + journal = {"originals": originals, "view": view, "registration": snapshot_registry(view), "old": data["old"]} + if kind == "installed": + for name in originals: + copy_managed(target / name, previous / name) + write_atomic(checkpoint, json.dumps(journal).encode()) + recovery_entry(plan_dir, True) + set_status(plan_dir, "installing", "Installing the verified update.") + try: + if kind == "portable": + for name in originals: + (target / name).replace(previous / name) + for entry in payload.iterdir(): + entry.replace(target / entry.name) + else: + setup = payload / package.name + verify_file(setup, package) + subprocess.run([str(setup), "/ARMUPDATE=1", "/VERYSILENT", "/SUPPRESSMSGBOXES", "/NORESTART", + "/NOCLOSEAPPLICATIONS", "/NOICONS", "/TASKS=", f"/DIR={target}", + f"/LOG={plan_dir / 'installer.log'}"], cwd=payload, check=True, + creationflags=subprocess.CREATE_NO_WINDOW) + with winreg.OpenKey(winreg.HKEY_CURRENT_USER, UNINSTALL_KEY, 0, winreg.KEY_READ | view) as key: + if winreg.QueryValueEx(key, "DisplayVersion")[0] != release.version: + raise UpdateError("Windows installer registration did not report the expected version") + verify_payload(target, release.version) + build = json.loads((target / "BUILD.json").read_bytes()) + if (build.get("source_revision"), build.get("jenkins_build")) != (release.commit, release.build): + raise UpdateError("Installed build identity does not match the signed manifest") + restart(target, release.version, plan_dir) + except Exception as exc: + rollback(target, work, journal) + set_status(plan_dir, "rolled_back", f"Installed update failed. Restored the previous application. {exc}") + recovery_entry(plan_dir, False) + restart(target, data["old"], plan_dir) + return + journal["committed"] = True + write_atomic(checkpoint, json.dumps(journal).encode()) + recovery_entry(plan_dir, False) + set_status(plan_dir, "complete", f"Updated and restarted Adaptive Resource Monitor {release.version}.") + finally: + if not checkpoint.exists() or json.loads(checkpoint.read_bytes()).get("committed") or ( + (plan_dir / "status.json").exists() and json.loads((plan_dir / "status.json").read_bytes())["state"] == "rolled_back" + ): + remove_managed(work) + + +def signal_ready(): + if value := os.environ.pop(ACK, None): + path = Path(value) + transactions = data_path() / "updates" / "transactions" + if path.name == "ready.json" and path.parent.parent.resolve() == transactions.resolve(): + write_atomic(path, json.dumps({"version": VERSION, "pid": os.getpid()}).encode()) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("plan", type=Path) + parser.add_argument("--recover", action="store_true") + args = parser.parse_args() + plan_dir = args.plan.resolve().parent + expected = (data_path() / "updates" / "transactions").resolve() + if args.plan.name != "plan.json" or plan_dir.parent != expected or not re.fullmatch(r"[0-9a-f]{32}", plan_dir.name): + return 2 + logging.basicConfig(filename=plan_dir / "maintenance.log", level=logging.INFO, encoding="utf-8", + format="%(asctime)s %(levelname)s %(message)s") + try: + transact(plan_dir, args.recover) + except Exception as exc: + LOG.exception("Maintenance failed") + set_status(plan_dir, "failed", str(exc)) + return 1 + return 0 diff --git a/arm/version.py b/arm/version.py index 944196f..10428dc 100644 --- a/arm/version.py +++ b/arm/version.py @@ -1,2 +1,28 @@ -VERSION = "v0.4.1.1_alpha" +import re +import sys +from pathlib import Path + + +VERSION_PATTERN = re.compile(r"v(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)_(alpha|beta|rc|stable)") +CHANNELS = ("alpha", "beta", "rc", "stable") + + +def version_key(value): + match = VERSION_PATTERN.fullmatch(value) if isinstance(value, str) else None + if not match: + raise ValueError("Invalid application version") + numbers = tuple(map(int, match.groups()[:4])) + if max(numbers) > 65535: + raise ValueError("Application version exceeds Windows version resource limits") + return (*numbers, CHANNELS.index(match[5])) + + +def read_version(path): + value = Path(path).read_text(encoding="utf-8").rstrip("\n") + version_key(value) + return value + + +ROOT = Path(getattr(sys, "_MEIPASS", Path(__file__).resolve().parent.parent)) +VERSION = read_version(ROOT / "VERSION.md") NAME = "Adaptive Resource Monitor" diff --git a/packaging/setup.iss b/packaging/setup.iss index b5e6e82..f34612c 100644 --- a/packaging/setup.iss +++ b/packaging/setup.iss @@ -43,16 +43,21 @@ Name: "startup"; Description: "Start Adaptive Resource Monitor with Windows"; Fl Source: "{#Payload}\*"; DestDir: "{app}"; Flags: ignoreversion recursesubdirs createallsubdirs [Icons] -Name: "{group}\{#Product}"; Filename: "{app}\{#Executable}"; IconFilename: "{app}\{#Executable}"; AppUserModelID: "{#AppModelId}" -Name: "{userdesktop}\{#Product}"; Filename: "{app}\{#Executable}"; IconFilename: "{app}\{#Executable}"; AppUserModelID: "{#AppModelId}"; Tasks: desktopicon +Name: "{group}\{#Product}"; Filename: "{app}\{#Executable}"; IconFilename: "{app}\{#Executable}"; AppUserModelID: "{#AppModelId}"; Check: not ArmUpdate +Name: "{userdesktop}\{#Product}"; Filename: "{app}\{#Executable}"; IconFilename: "{app}\{#Executable}"; AppUserModelID: "{#AppModelId}"; Tasks: desktopicon; Check: not ArmUpdate [Registry] -Root: HKCU; Subkey: "{#RunKey}"; ValueType: string; ValueName: "AdaptiveResourceMonitor"; ValueData: """{app}\{#Executable}"""; Tasks: startup +Root: HKCU; Subkey: "{#RunKey}"; ValueType: string; ValueName: "AdaptiveResourceMonitor"; ValueData: """{app}\{#Executable}"""; Tasks: startup; Check: not ArmUpdate [Run] Filename: "{app}\{#Executable}"; Description: "Open Adaptive Resource Monitor"; Flags: nowait postinstall skipifsilent [Code] +function ArmUpdate: Boolean; +begin + Result := ExpandConstant('{param:ARMUPDATE|0}') = '1'; +end; + procedure CurUninstallStepChanged(Step: TUninstallStep); var Value, Target: String; diff --git a/requirements.txt b/requirements.txt index ad3416a..9006300 100644 --- a/requirements.txt +++ b/requirements.txt @@ -2,3 +2,5 @@ PySide6==6.11.2 psutil==7.2.2 paramiko==4.0.0 nvidia-ml-py==13.615.71 +cryptography==50.0.1 +pefile==2024.8.26 diff --git a/tests/test_updates.py b/tests/test_updates.py new file mode 100644 index 0000000..077e0f3 --- /dev/null +++ b/tests/test_updates.py @@ -0,0 +1,152 @@ +from base64 import b64encode +from hashlib import sha256 +from io import BytesIO +import json +from pathlib import Path +from tempfile import TemporaryDirectory +from threading import Event +import unittest +from unittest.mock import patch +from urllib.error import URLError +from zipfile import ZipFile + +from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey + +from arm.branding import APP_MODEL_ID +from arm.config import Settings +from arm.update_client import ReleaseClient, UpdateCancelled +from arm.update_release import MANIFEST, UpdateError, artifact_name, canonical, verify_manifest +from arm.update_worker import unpack_portable +from arm.version import VERSION, version_key + +COUNTERS = version_key(VERSION) +NEW = "v{}.{}.{}.{}_{}".format(*COUNTERS[:3], COUNTERS[3] + 1, VERSION.rsplit("_", 1)[1]) +OLD = "v0.0.0.0_alpha" +PACKAGE = b"abcdefgh" * 100_000 + + +class Response(BytesIO): + def __init__(self, data, status=200, headers=None): + super().__init__(data) + self.status = status + self.headers = headers or {"Content-Length": str(len(data))} + + +class UpdateTests(unittest.TestCase): + def setUp(self): + self.key = Ed25519PrivateKey.generate() + self.public = b64encode(self.key.public_key().public_bytes_raw()).decode("ascii") + self.client = ReleaseClient({"base": "https://updates.example.test/gitea", "owner": "qa", + "repository": "arm", "public_key": self.public}) + self.root = self.enterContext(TemporaryDirectory(prefix="arm-update-test-")) + self.work = Path(self.root) + + def metadata(self, version=NEW): + return {"protocol": 1, "application": APP_MODEL_ID, "architecture": "windows-x64", "version": version, + "commit": "d" * 40, "build": 13, "notes": "ARM test update", + "packages": {kind: {"name": artifact_name(version, kind), "size": len(PACKAGE), + "sha256": sha256(PACKAGE).hexdigest()} for kind in ("installed", "portable")}} + + def sign(self, metadata): + return canonical({"manifest": metadata, "signature": b64encode(self.key.sign(canonical(metadata))).decode()}) + + def row(self, metadata, raw=None): + version = metadata["version"] + manifest = raw or self.sign(metadata) + assets = [{"name": MANIFEST, "size": len(manifest), "browser_download_url": self.client.url(version, MANIFEST)}] + for package in metadata["packages"].values(): + assets.append({**package, "browser_download_url": self.client.url(version, package["name"])}) + return {"tag_name": version, "draft": False, "prerelease": not version.endswith("_stable"), + "body": metadata["notes"], "assets": assets}, manifest + + def test_signature_and_signed_identity(self): + meta = self.metadata() + signed = self.sign(meta) + self.assertEqual(verify_manifest(signed, self.public, NEW).build, 13) + for field, value in (("application", "OtherApp"), ("architecture", "windows-arm64"), + ("version", OLD), ("build", 0)): + with self.subTest(field=field), self.assertRaises(UpdateError): + verify_manifest(self.sign(meta | {field: value}), self.public, NEW) + modified = json.loads(signed) + modified["manifest"]["notes"] = "Modified" + with self.assertRaisesRegex(UpdateError, "signature"): + verify_manifest(canonical(modified), self.public, NEW) + with self.assertRaises(UpdateError): + verify_manifest(canonical({"manifest": meta}), self.public, NEW) + for field, value in (("name", "foreign.zip"), ("size", -1), ("sha256", "incorrect")): + with self.subTest(field=field), self.assertRaises(UpdateError): + self.verify_bad_package(field, value) + + def verify_bad_package(self, field, value): + bad = self.metadata() + bad["packages"]["portable"][field] = value + return verify_manifest(self.sign(bad), self.public, NEW) + + def test_discovery_verified_current_and_older(self): + for version in (NEW, VERSION, OLD): + row, raw = self.row(self.metadata(version)) + with patch.object(self.client, "read", side_effect=[canonical([row]), raw]): + checked = self.client.check(VERSION, "installed") + self.assertEqual(checked.published, version) + if version == OLD: + self.assertIsNone(checked.release) + else: + self.assertEqual(checked.release.version, version) + + def test_bad_latest_manifest_reports_rejection_and_falls_back(self): + newest, _ = self.row(self.metadata()) + current, raw = self.row(self.metadata(VERSION)) + with patch.object(self.client, "read", side_effect=[canonical([current, newest]), b"invalid", raw]): + checked = self.client.check(VERSION, "portable") + self.assertEqual((checked.published, checked.release.version), (NEW, VERSION)) + self.assertIn(NEW, checked.issues[0]) + with patch.object(self.client, "read", side_effect=URLError("unavailable")), self.assertRaises(URLError): + self.client.check(VERSION, "installed") + + def test_download_cancel_and_resume(self): + release = verify_manifest(self.sign(self.metadata()), self.public) + cancel = Event() + cancel_after_bytes = lambda received, total: cancel.set() if received else None + with patch.object(self.client, "open", return_value=Response(PACKAGE)): + with self.assertRaises(UpdateCancelled): + self.client.download(release, "portable", self.work, cancel_after_bytes, cancel.is_set) + part, = self.work.rglob("*.part") + start = part.stat().st_size + self.assertTrue(0 < start < len(PACKAGE)) + cancel.clear() + response = Response(PACKAGE[start:], 206, {"Content-Length": str(len(PACKAGE) - start), + "Content-Range": f"bytes {start}-{len(PACKAGE)-1}/{len(PACKAGE)}"}) + with patch.object(self.client, "open", return_value=response) as fetch: + path = self.client.download(release, "portable", self.work, lambda *_: None, cancel.is_set) + self.assertEqual(fetch.call_args.args[1]["Range"], f"bytes={start}-") + self.assertEqual(path.read_bytes(), PACKAGE) + self.assertEqual((path.parent / MANIFEST).read_bytes(), release.envelope) + self.assertFalse(part.exists()) + + def test_interrupted_then_corrupted_package(self): + release = verify_manifest(self.sign(self.metadata()), self.public) + with patch.object(self.client, "open", return_value=Response(PACKAGE[:30], headers={"Content-Length": str(len(PACKAGE))})): + with self.assertRaisesRegex(UpdateError, "interrupted"): + self.client.download(release, "installed", self.work, lambda *_: None, lambda: False) + part, = self.work.rglob("*.part") + self.assertEqual(part.read_bytes(), PACKAGE[:30]) + with patch.object(self.client, "open", return_value=Response(b"b" * len(PACKAGE))): + with self.assertRaisesRegex(UpdateError, "SHA-256"): + self.client.download(release, "installed", self.work, lambda *_: None, lambda: False) + self.assertFalse(any(self.work.rglob("*.exe"))) + + def test_portable_package_refuses_traversal_and_ntfs_streams(self): + archive = self.work / "bad.zip" + for member in ("../escape.exe", "AdaptiveResourceMonitor/_internal/trick:payload.dll", + "AdaptiveResourceMonitor/_internal/../escape.exe", "AdaptiveResourceMonitor/_internal/NUL.txt"): + with self.subTest(member=member), ZipFile(archive, "w") as target: + target.writestr(member, "test") + with self.assertRaisesRegex(UpdateError, "unsafe"): + unpack_portable(archive, self.work / "unzip", NEW) + + def test_version_and_startup_settings_validation(self): + self.assertGreater(version_key(NEW), version_key(VERSION)) + self.assertGreater(version_key(VERSION), version_key(OLD)) + self.assertEqual(Settings.from_dict({"update_startup": True, "update_interval": 168}).update_interval, 168) + default = Settings.from_dict({"update_startup": "yes", "update_interval": 169}) + self.assertEqual((default.update_startup, default.update_interval), (False, 0)) diff --git a/tests/windows_gui.py b/tests/windows_gui.py index 91ec5f4..b3420ca 100644 --- a/tests/windows_gui.py +++ b/tests/windows_gui.py @@ -365,7 +365,7 @@ def verify_branding(session, results, captures=None): assert menu.version.text() == VERSION and menu.local.isChecked() assert not menu.remote.menuAction().isVisible() actions = {action.text(): action for action in menu.actions()} - assert "Check for Updates" not in actions + assert "Check for Updates" in actions actions[f"About {NAME}"].trigger() assert session.expanded.tabs.currentWidget() is session.about_page assert session.about_page.version.text() == VERSION @@ -388,7 +388,7 @@ def verify_branding(session, results, captures=None): details.extend(label.text() for label in dialog.findChildren(QLabel)) dialog.reject() QTimer.singleShot(0, inspect_details) - view = next(button for button in session.about_page.findChildren(QPushButton) if button.text() == "View Details") + view = next(button for button in session.about_page.findChildren(QPushButton) if button.text() == "Application Details") view.click() assert "Installation type" in details and "Source checkout" in details and VERSION in details @@ -441,6 +441,7 @@ def evaluate_app(work, results, short=False, captures=None): from arm.providers.ssh import update_host_key from ssh_fixture import Fixture, SECRET from contextlib import ExitStack + from threading import Event from unittest.mock import patch assert set_windows_identity() == 0 @@ -511,6 +512,31 @@ def evaluate_app(work, results, short=False, captures=None): assert session.icons[LOCAL].icon().cacheKey() != session.brand_icon.cacheKey() verify_branding(session, results, captures) menu = session.menus[LOCAL] + from arm.update_client import Check + update = session.about_page.updates + lookup = next(action for action in menu.actions() if action.text() == "Check for Updates") + entered, release_check = Event(), Event() + + def slow_check(version, kind): + entered.set() + assert release_check.wait(10) + return Check(None, None, ()) + + with patch.object(update.client, "check", side_effect=slow_check): + try: + sample = session.collectors.last[LOCAL] + lookup.trigger() + assert session.expanded.tabs.currentWidget() is session.about_page + wait_for(entered.is_set) + assert not update.buttons["Check for Updates"].isEnabled() + wait_for(lambda: session.collectors.last[LOCAL] > sample) + finally: + release_check.set() + wait_for(lambda: update.job is None) + assert update.fields["Latest published"].text() == "No public releases" + assert "UTC" in update.fields["Last successful check"].text() + session.expanded.close() + results["asynchronous_update_check_with_live_telemetry"] = True modes = {} for mode in ("Stacked", STATIC_TRAY_MODE, "Overlay", "Composite"): menu.modes[mode].trigger() @@ -657,16 +683,30 @@ def evaluate_app(work, results, short=False, captures=None): source = json.loads(store.path.read_text(encoding="utf-8")) source.update(hover_machine="@peak", default_machine="@peak") store.path.write_text(json.dumps(source), encoding="utf-8") - reopened = Application(app, restart_root) - try: - assert reopened.scopes() == [primary] - assert reopened.popup.selected_machine == reopened.expanded.selected_machine == ALL - assert reopened.popup.span == 300 and not reopened.popup.pinned - assert reopened.settings.targets == stored_targets - finally: - reopened.close() + startup = replace(store.load(), update_startup=True, update_interval=4) + if legacy: + source["update_startup"] = True + source["update_interval"] = 4 + store.path.write_text(json.dumps(source), encoding="utf-8") + else: + store.save(startup) + from arm.update_client import ReleaseClient + with patch.object(ReleaseClient, "check", return_value=Check(None, None, ())) as check: + reopened = Application(app, restart_root) + try: + assert reopened.scopes() == [primary] + assert reopened.popup.selected_machine == reopened.expanded.selected_machine == ALL + assert reopened.popup.span == 300 and not reopened.popup.pinned + assert reopened.settings.targets == stored_targets + panel = reopened.about_page.updates + assert panel.periodic.isActive() and panel.periodic.interval() == 4 * 3_600_000 + wait_for(lambda: check.called and panel.job is None) + assert panel.fields["Latest published"].text() == "No public releases" + finally: + reopened.close() app.processEvents() results["restored_monitor_and_tray"] = "New and legacy settings restored All Systems at five minutes with a separate tray source" + results["startup_update_and_periodic_timer"] = True def child(args): diff --git a/tools/build_windows.py b/tools/build_windows.py index 3ee88b8..fb28ee9 100644 --- a/tools/build_windows.py +++ b/tools/build_windows.py @@ -4,6 +4,7 @@ from datetime import datetime, timezone from hashlib import file_digest from importlib import metadata import json +import os from pathlib import Path import platform import re @@ -16,7 +17,7 @@ from zipfile import ZIP_DEFLATED, ZipFile ROOT = Path(__file__).resolve().parents[1] sys.path.insert(0, str(ROOT)) -from arm.version import NAME, VERSION +from arm.version import NAME, VERSION, version_key from arm.branding import ( APPLICATION_ICON, APPLICATION_IMAGE, APPLICATION_LOGO, APP_MODEL_ID, BUNDLED_ASSETS, COPYRIGHT, DESCRIPTION, INSTALL_ID, PUBLISHER, SUPPORT_URL, WEBSITE, @@ -87,16 +88,25 @@ def build_info(): data[key] = bool(value) if key == "source_modified" else value except FileNotFoundError: pass + if "BUILD_NUMBER" in os.environ and "JENKINS_URL" in os.environ: + number = os.environ["BUILD_NUMBER"] + if not number.isdecimal() or int(number) < 1 or data.get("source_modified") is not False: + raise RuntimeError("Jenkins requires a clean, numbered source checkout") + revision = data.get("source_revision") + if not re.fullmatch(r"[0-9a-f]{40}", revision or "") or revision != os.environ.get("ARM_SOURCE_COMMIT"): + raise RuntimeError("Jenkins source commit does not match the build") + data["jenkins_build"] = int(number) return data def build(compiler, output): if platform.system() != "Windows" or struct.calcsize("P") != 8 or platform.machine().lower() not in ("amd64", "x86_64"): raise RuntimeError("Use native x64 Windows Python") - match = re.fullmatch(r"v(\d+)\.(\d+)\.(\d+)\.(\d+)_([a-z]+)", VERSION) - if not match: - raise ValueError("Unexpected ARM version format") - numbers = tuple(int(value) for value in match.groups()[:4]) + numbers = version_key(VERSION)[:4] + changelog = (ROOT / "CHANGELOG.md").read_text(encoding="utf-8") + if not re.search(rf"^## {re.escape(VERSION)}\s", changelog, re.M): + raise RuntimeError("CHANGELOG.md does not contain the authoritative version") + identity = build_info() output.mkdir(parents=True, exist_ok=True) with TemporaryDirectory(prefix="arm-release-") as temporary: temporary = Path(temporary) @@ -108,6 +118,15 @@ def build(compiler, output): encoding="utf-8", ) assets = [part for asset in BUNDLED_ASSETS for part in ("--add-data", f"{ROOT / asset};branding")] + update_data = [part for name in ("VERSION.md", "update-source.json") for part in ("--add-data", f"{ROOT / name};.")] + worker_name = "AdaptiveResourceMonitorMaintenance" + run([ + sys.executable, "-m", "PyInstaller", "--noconfirm", "--noupx", "--windowed", "--onefile", + "--name", worker_name, "--paths", str(ROOT), "--workpath", str(temporary / "work"), + "--distpath", str(temporary / "maintenance"), "--specpath", str(temporary), + "--version-file", str(version_file), "--manifest", str(ROOT / "packaging" / "windows.manifest"), + "--icon", str(ICON), "--exclude-module", "PySide6", *update_data, str(ROOT / "tools" / "maintenance.py"), + ]) run([ sys.executable, "-m", "PyInstaller", "--noconfirm", "--noupx", "--windowed", "--name", "AdaptiveResourceMonitor", "--paths", str(ROOT), @@ -116,14 +135,16 @@ def build(compiler, output): "--manifest", str(ROOT / "packaging" / "windows.manifest"), "--icon", str(ICON), *assets, + *update_data, "--add-data", f"{ROOT / 'arm' / 'providers' / 'linux_probe.sh'};arm/providers", "--hidden-import", "pynvml", "--exclude-module", "tkinter", str(ROOT / "monitor.pyw"), ]) payload = temporary / "dist" / "AdaptiveResourceMonitor" + shutil.copyfile(temporary / "maintenance" / f"{worker_name}.exe", payload / f"{worker_name}.exe") (payload / "VERSION.txt").write_text(VERSION + "\n", encoding="utf-8") - (payload / "BUILD.json").write_text(json.dumps(build_info(), indent=2) + "\n", encoding="utf-8") - for name in ("README.md", "SECURITY.md", "REMOTE_MONITORING.md", "CHANGELOG.md"): + (payload / "BUILD.json").write_text(json.dumps(identity, indent=2) + "\n", encoding="utf-8") + for name in ("README.md", "SECURITY.md", "REMOTE_MONITORING.md", "CHANGELOG.md", "VERSION.md"): shutil.copyfile(ROOT / name, payload / name) if (ROOT / "LICENSE.md").is_file(): shutil.copyfile(ROOT / "LICENSE.md", payload / "LICENSE.md") diff --git a/tools/ci_release.py b/tools/ci_release.py new file mode 100644 index 0000000..9648bf6 --- /dev/null +++ b/tools/ci_release.py @@ -0,0 +1,243 @@ +"""Sign an archived Jenkins candidate and publish an explicitly pinned build.""" +import argparse +from base64 import b64decode, b64encode +from hashlib import file_digest +import json +import os +from pathlib import Path +import re +import subprocess +import sys +from tempfile import TemporaryDirectory +from urllib.error import HTTPError +from urllib.parse import quote +from urllib.request import Request +from uuid import uuid4 + +from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT)) + +from arm.branding import APP_MODEL_ID +from arm.update_client import ReleaseClient +from arm.update_release import ( + ARCHITECTURE, KINDS, MANIFEST, UpdateError, artifact_name, canonical, sha256, source_config, + verify_file, verify_manifest, +) +from arm.update_worker import unpack_portable, verify_executable +from arm.version import VERSION, version_key + +CHECKSUMS = "SHA256SUMS.txt" +NOTES = "RELEASE_NOTES.md" +KEY = "arm-ed25519.pub" +RECEIPT = "release-build.json" + + +def git(*args): + return subprocess.check_output(("git", *args), cwd=ROOT, text=True, encoding="utf-8").strip() + + +def head_version(commit, version): + if not re.fullmatch(r"[0-9a-f]{40}", commit): + raise UpdateError("Expected a 40-character Git commit") + version_key(version) + if git("show", f"{commit}:VERSION.md") != version: + raise UpdateError("Pinned commit and authoritative version disagree") + + +def notes_at(commit, version): + text = git("show", f"{commit}:CHANGELOG.md") + section = re.search(rf"^## {re.escape(version)}\s[^\n]*\n(.*?)(?=^## |\Z)", text, re.M | re.S) + if not section or not section[1].strip(): + raise UpdateError("Pinned version has no changelog entry") + return section[1].strip() + + +def expected_receipt(release): + return { + "application": APP_MODEL_ID, "architecture": ARCHITECTURE, "version": release.version, + "source_commit": release.commit, "jenkins_build": release.build, + "packages": {kind: {"name": p.name, "size": p.size, "sha256": p.sha256} + for kind, p in release.packages.items()}, + } + + +def checksums(release): + return "".join(f"{package.sha256} {package.name}\n" for _, package in sorted(release.packages.items())) + + +def files_for(release): + return {*(p.name for p in release.packages.values()), MANIFEST, CHECKSUMS, NOTES, KEY, RECEIPT} + + +def verify(folder, version, commit, number): + head_version(commit, version) + source = source_config() + release = verify_manifest((folder / MANIFEST).read_bytes(), source["public_key"], version) + if (release.commit, release.build, release.notes) != (commit, number, notes_at(commit, version)): + raise UpdateError("Signed manifest does not match the pinned Jenkins build or changelog") + if {path.name for path in folder.iterdir()} != files_for(release): + raise UpdateError("Release folder contains missing or unexpected files") + if (json.loads((folder / RECEIPT).read_bytes()) != expected_receipt(release) + or (folder / KEY).read_text(encoding="ascii").strip() != source["public_key"] + or (folder / NOTES).read_text(encoding="utf-8").strip() != release.notes + or (folder / CHECKSUMS).read_text(encoding="ascii") != checksums(release)): + raise UpdateError("Artifact receipt, notes, key or checksums disagree with the signed manifest") + for package in release.packages.values(): + verify_file(folder / package.name, package) + print(f"{package.name} | {package.size:,} bytes | SHA-256 {package.sha256}") + verify_executable(folder / release.packages["installed"].name, version) + with TemporaryDirectory(prefix="arm-release-verify-") as temporary: + payload = Path(temporary) + unpack_portable(folder / release.packages["portable"].name, payload, version) + build = json.loads((payload / "BUILD.json").read_bytes()) + if (build.get("source_revision"), build.get("jenkins_build"), build.get("source_modified")) != (commit, number, False): + raise UpdateError("Portable package is inconsistent with the selected Jenkins build") + if json.loads((payload / "_internal" / "update-source.json").read_bytes()) != source: + raise UpdateError("Packaged update repository or trust key is inconsistent") + print(f"Verified Ed25519 signature, Windows x64 packages and build identity | {version} | {commit} | Jenkins #{number}") + return release + + +def sign(folder, commit, number): + head_version(commit, VERSION) + source = source_config() + key = Ed25519PrivateKey.from_private_bytes(b64decode(os.environ.pop("ARM_ED25519_SIGNING_KEY"), validate=True)) + if b64encode(key.public_key().public_bytes_raw()).decode() != source["public_key"]: + raise UpdateError("Jenkins signing identity does not match the application's public key") + archives = {} + for kind in KINDS: + name = artifact_name(VERSION, kind) + path = folder / name + archives[kind] = {"name": name, "size": path.stat().st_size, "sha256": sha256(path)} + notes = notes_at(commit, VERSION) + manifest = {"protocol": 1, "application": APP_MODEL_ID, "architecture": ARCHITECTURE, "version": VERSION, + "commit": commit, "build": number, "notes": notes, "packages": archives} + raw = canonical({"manifest": manifest, "signature": b64encode(key.sign(canonical(manifest))).decode()}) + release = verify_manifest(raw, source["public_key"], VERSION) + (folder / MANIFEST).write_bytes(raw) + (folder / RECEIPT).write_bytes(canonical(expected_receipt(release)) + b"\n") + (folder / CHECKSUMS).write_bytes(checksums(release).encode("ascii")) + (folder / NOTES).write_bytes((notes + "\n").encode("utf-8")) + (folder / KEY).write_bytes((source["public_key"] + "\n").encode("ascii")) + print(f"Signed {VERSION} with the ARM-specific Ed25519 Jenkins credential") + + +class Publication: + def __init__(self, client, token): + self.client = client + self.auth = {"Authorization": f"token {token}", "Accept": "application/json"} + + def request(self, path, data=None, method=None, optional=False, headers=None): + if isinstance(data, dict): + data = canonical(data) + request = Request(self.client.api + path, data, method=method, headers={ + **self.auth, "Content-Type": "application/json", **(headers or {}) + }) + try: + with self.client.opener.open(request, timeout=120) as response: + return json.load(response) + except HTTPError as exc: + if optional and exc.code == 404: + return None + raise UpdateError(f"Gitea {method or 'GET'} {path} failed HTTP {exc.code}") from None + + def upload(self, release_id, path): + boundary = uuid4().hex + start = (f"--{boundary}\r\nContent-Disposition: form-data; name=\"attachment\";" + f" filename=\"{path.name}\"\r\nContent-Type: application/octet-stream\r\n\r\n").encode("ascii") + body = start + path.read_bytes() + f"\r\n--{boundary}--\r\n".encode("ascii") + row = self.request(f"/releases/{release_id}/assets?name={quote(path.name)}", body, "POST", headers={ + "Content-Type": f"multipart/form-data; boundary={boundary}" + }) + if (row.get("name"), row.get("size")) != (path.name, path.stat().st_size): + raise UpdateError(f"Gitea returned unexpected attachment details for {path.name}") + print(f"Uploaded draft attachment {path.name}") + + def verify_downloads(self, folder, row, signed, anonymous): + matches = row["assets"] + if len(matches) != len(files_for(signed)) or {entry["name"] for entry in matches} != files_for(signed): + raise UpdateError("Release contains unexpected or missing attachments") + version = signed.version + if (row["tag_name"], row["body"], row["prerelease"]) != (version, signed.notes, not version.endswith("_stable")): + raise UpdateError("Release title, body or classification disagrees with the signed metadata") + for entry in matches: + file = folder / entry["name"] + url = self.client.attachment(row, version, file.name, file.stat().st_size) + headers = {} if anonymous else self.auth + with self.client.open(url, headers) as response: + if response.headers.get("Content-Length") not in (None, str(file.stat().st_size)): + raise UpdateError(f"Release download size mismatch for {file.name}") + if file.name == MANIFEST: + remote = response.read(file.stat().st_size + 1) + if remote != signed.envelope: + raise UpdateError("Downloaded signed release manifest differs from the archived candidate") + verify_manifest(remote, self.client.source["public_key"], version) + elif file_digest(response, "sha256").hexdigest() != sha256(file): + raise UpdateError(f"Downloaded SHA-256 mismatch for {file.name}") + print(f"{'Anonymous' if anonymous else 'Draft'} readback verified {file.name}") + + +def publish(folder, version, commit, number): + if subprocess.run(("git", "merge-base", "--is-ancestor", commit, "origin/main"), cwd=ROOT).returncode: + raise UpdateError("Selected commit is not reachable from main") + release = verify(folder, version, commit, number) + api = Publication(ReleaseClient(), os.environ.pop("ARM_GITEA_PUBLISH_TOKEN")) + tag = quote(version) + repository = api.request("") + if repository["private"] is not False: + raise UpdateError("The release repository must pass anonymous access validation before publication") + row = api.request(f"/releases/tags/{tag}", optional=True) + original_tag = api.request(f"/tags/{tag}", optional=True) + if original_tag and original_tag["commit"]["sha"] != commit: + raise UpdateError("An existing version tag points at a different commit") + if row and not row["draft"]: + api.verify_downloads(folder, row, release, True) + print(f"Version {version} is already public with the exact selected bytes") + return + if row is None: + row = api.request("/releases", {"tag_name": version, "target_commitish": commit, "name": f"Adaptive Resource Monitor {version}", + "body": release.notes, "draft": True, "prerelease": not version.endswith("_stable")}, "POST") + address = f"/releases/{row['id']}" + if (row["body"], row["target_commitish"]) != (release.notes, commit): + raise UpdateError("Existing draft does not match the selected build") + existing = {item["name"] for item in row["assets"]} + if existing - files_for(release): + raise UpdateError("Draft contains unrecognized attachments") + for name in sorted(files_for(release) - existing): + api.upload(row["id"], folder / name) + api.verify_downloads(folder, api.request(address), release, False) + api.request(address, {"draft": False}, "PATCH") + try: + opened = json.loads(api.client.read(api.client.api + f"/releases/tags/{tag}", 2 * 1024**2)) + tag_info = json.loads(api.client.read(api.client.api + f"/tags/{tag}", 64 * 1024)) + if opened["draft"] or tag_info["commit"]["sha"] != commit: + raise UpdateError("Published release or Git tag did not match the pinned build") + api.verify_downloads(folder, opened, release, True) + except Exception: + api.request(address, {"draft": True}, "PATCH") + raise + print(f"Published and anonymously verified {api.client.base}/{api.client.repository}/releases/tag/{tag}") + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("action", choices=("sign", "verify", "publish")) + parser.add_argument("folder", type=Path) + parser.add_argument("commit") + parser.add_argument("build", type=int) + parser.add_argument("--version", default=VERSION) + args = parser.parse_args() + if args.build < 1: + parser.error("Use a positive Jenkins build number") + if args.action == "sign": + sign(args.folder, args.commit, args.build) + elif args.action == "publish": + publish(args.folder, args.version, args.commit, args.build) + else: + verify(args.folder, args.version, args.commit, args.build) + + +if __name__ == "__main__": + main() diff --git a/tools/install_ci_compiler.py b/tools/install_ci_compiler.py new file mode 100644 index 0000000..3012987 --- /dev/null +++ b/tools/install_ci_compiler.py @@ -0,0 +1,15 @@ +"""Extract the signed Inno compiler through its native portable installer.""" +from pathlib import Path +import sys +from uuid import uuid4 + +sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "tests")) +from windows_gui import start_isolated + + +if __name__ == "__main__": + installer, destination = (Path(value).resolve() for value in sys.argv[1:]) + raise SystemExit(start_isolated( + [str(installer), "/PORTABLE=1", "/VERYSILENT", "/SUPPRESSMSGBOXES", "/NORESTART", f"/DIR={destination}"], + f"ARM_Compiler_{uuid4().hex[:10]}", timeout=90, + )) diff --git a/tools/maintenance.py b/tools/maintenance.py new file mode 100644 index 0000000..fa2d8a3 --- /dev/null +++ b/tools/maintenance.py @@ -0,0 +1,5 @@ +from arm.update_worker import main + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/tools/prepare_windows_compiler.ps1 b/tools/prepare_windows_compiler.ps1 new file mode 100644 index 0000000..db41f37 --- /dev/null +++ b/tools/prepare_windows_compiler.ps1 @@ -0,0 +1,19 @@ +$ErrorActionPreference = 'Stop' +$scratch = Join-Path $PWD '.ci' +$compiler = Join-Path $scratch 'inno' +$download = Join-Path $scratch 'innosetup-7.1.1-x64.exe' +$origin = 'https://github.com/jrsoftware/issrc/releases/download/is-7_1_1/innosetup-7.1.1-x64.exe' +$expected = '8a5a6711c3766a6e5fb74f280ba0e3551e719ce94538d901fdbd1f8f9920b3f0' +Invoke-WebRequest -UseBasicParsing -Uri $origin -OutFile $download +if ((Get-FileHash -LiteralPath $download -Algorithm SHA256).Hash -ine $expected) { + throw 'Inno Setup download SHA-256 mismatch' +} +$signature = Get-AuthenticodeSignature -LiteralPath $download +if ($signature.Status -ne 'Valid' -or $signature.SignerCertificate.Subject -notmatch 'CN=Pyrsys B\.V\.') { + throw 'Inno Setup publisher verification failed' +} +& '.ci\python\Scripts\python.exe' tools\install_ci_compiler.py $download $compiler +if ($LASTEXITCODE -ne 0 -or -not (Test-Path -LiteralPath (Join-Path $compiler 'ISCC.exe'))) { + throw 'Portable Inno Setup staging failed' +} +Write-Host 'Inno Setup 7.1.1 x64 hash, publisher and portable staging verified.' diff --git a/update-source.json b/update-source.json new file mode 100644 index 0000000..c09d3b6 --- /dev/null +++ b/update-source.json @@ -0,0 +1,6 @@ +{ + "base": "https://phantom.zapto.org/gitea", + "owner": "sonja", + "repository": "Adaptive_Resource_Monitor", + "public_key": "6WnGGXU9fYExkEtFbYE5N/iDPQmtIviByL/nOC5UImw=" +}