Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.
Python agent-orchestrationai-agentai-coding-assistantclaude-codecoding-agentcomputer-usedesktop-applocal-firstmcppersonal-jarvisvoice-assistantvoice-coding
feat(update): sign the update manifest the in-app updater trusts (Ed25519, version-bound) (#945)
Ruben Lütke68e12b1d40dd
diff --git a/.github/workflows/desktop-installers.yml b/.github/workflows/desktop-installers.ymlindex 2be89cf70e..2514d220be 100644--- a/.github/workflows/desktop-installers.yml+++ b/.github/workflows/desktop-installers.yml@@ -10,6 +10,8 @@# Dodaios-macOS-x64.dmg Intel Mac# Dodaios-Linux-x86_64.AppImage Linux x86_64# installers-SHA256SUMS.txt what the updater verifies against+# installers-update-manifest.json(.sig) the release key's signature over+# the version and that checksum manifest## Every installer is ALSO published under its earlier name# (PersonalJarvis-Setup-x64.exe, PersonalJarvis-macOS-<arch>.dmg,@@ -497,21 +499,14 @@ jobs:if-no-files-found: errorretention-days: 14- # ------------------------------------------------------- Checksums + Release- release:- name: Checksums and GitHub Release+ # ------------------------------------------------------- Checksum manifest+ checksums:+ name: Checksum manifestneeds: [windows, macos, linux]runs-on: ubuntu-latesttimeout-minutes: 20permissions:- # The ONLY job that may write to the repository, and only to attach the- # assets it just verified.- contents: write- # Build provenance for the native installers (tag runs only, see the- # attestation step): an OIDC identity for Sigstore plus the attestation- # store. Users check it with `gh attestation verify`.- id-token: write- attestations: write+ contents: readsteps:- name: Checkoutuses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0@@ -523,23 +518,6 @@ jobs:with:python-version: ${{ env.PYTHON_VERSION }}- # A tag that disagrees with the shipped version would publish installers- # nobody can trace back to a commit - and the in-app updater compares the- # release version against dodaios.__version__, so a mismatch would offer an- # update that installs the same build forever.- - name: Verify the tag matches dodaios.__version__- if: github.ref_type == 'tag'- shell: bash- run: |- set -euo pipefail- tag_version="${GITHUB_REF_NAME#v}"- package_version="$(python -c 'import re,pathlib; print(re.search(r"__version__ = \"([^\"]+)\"", pathlib.Path("dodaios/__init__.py").read_text()).group(1))')"- echo "tag=${tag_version} package=${package_version}"- if [ "${tag_version}" != "${package_version}" ]; then- echo "::error::Tag ${GITHUB_REF_NAME} does not match dodaios.__version__ (${package_version})."- exit 1- fi-- name: Download every installeruses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2with:@@ -593,6 +571,181 @@ jobs:if-no-files-found: errorretention-days: 14+ # ------------------------------------------------- Signed update manifest+ # The in-app updater of a frozen install trusts installers-SHA256SUMS.txt+ # only through installers-update-manifest.json: the release version, its tag+ # and the checksum manifest's SHA-256, signed with the offline-ceremony+ # Ed25519 key (dodaios/core/update_manifest.py, issue #810). The private key+ # is the WAVE2_OFFLINE_KEY_B64 secret of the `release-signing` environment,+ # which admits `v*` tag runs only; the public half is+ # install/keys/offline-ceremony.pub and is pinned in the app. This is the only+ # job of this workflow that can read the key, and it holds no write token.+ sign-update-manifest:+ name: Sign the update manifest+ needs: checksums+ if: github.ref_type == 'tag'+ environment: release-signing+ runs-on: ubuntu-latest+ timeout-minutes: 10+ permissions:+ contents: read+ steps:+ - name: Checkout+ uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0+ with:+ persist-credentials: false++ - name: Set up Python+ uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7.0.0+ with:+ python-version: ${{ env.PYTHON_VERSION }}++ - name: Download the checksum manifest+ uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2+ with:+ name: installers-checksums+ path: installers++ - name: Write installers-update-manifest.json+ run: >-+ python scripts/ci/update_manifest.py build --tag "$GITHUB_REF_NAME"+ --checksums installers/installers-SHA256SUMS.txt+ --out installers/installers-update-manifest.json++ # A release without the signature would be one no updated install can+ # take, so a missing key fails the release instead of shipping unsigned.+ - name: Sign the manifest with the release key+ env:+ WAVE2_OFFLINE_KEY_B64: ${{ secrets.WAVE2_OFFLINE_KEY_B64 }}+ shell: bash+ run: |+ set -euo pipefail+ if [ -z "${WAVE2_OFFLINE_KEY_B64:-}" ]; then+ echo "::error::WAVE2_OFFLINE_KEY_B64 is not available to the release-signing environment; refusing to publish an unsigned update manifest."+ exit 1+ fi+ key="${RUNNER_TEMP}/update-manifest.key"+ trap 'rm -f "$key" "${RUNNER_TEMP}/update-manifest.sig.raw"' EXIT+ umask 077+ printf '%s' "${WAVE2_OFFLINE_KEY_B64}" | base64 -d > "$key"+ if ! grep -q "BEGIN PRIVATE KEY" "$key"; then+ echo "::error::WAVE2_OFFLINE_KEY_B64 does not decode to a PEM private key"+ exit 1+ fi+ cd installers+ openssl pkeyutl -sign -inkey "$key" -rawin \+ -in installers-update-manifest.json \+ -out "${RUNNER_TEMP}/update-manifest.sig.raw"+ base64 -w0 "${RUNNER_TEMP}/update-manifest.sig.raw" > installers-update-manifest.json.sig+ echo "Signed installers-update-manifest.json (key contents not logged)."++ - name: Verify the signature against the pinned public key+ shell: bash+ run: |+ set -euo pipefail+ base64 -d installers/installers-update-manifest.json.sig > "${RUNNER_TEMP}/check.sig.raw"+ openssl pkeyutl -verify -pubin -inkey install/keys/offline-ceremony.pub -rawin \+ -in installers/installers-update-manifest.json \+ -sigfile "${RUNNER_TEMP}/check.sig.raw"+ python scripts/ci/update_manifest.py check --tag "$GITHUB_REF_NAME" \+ --checksums installers/installers-SHA256SUMS.txt \+ --manifest installers/installers-update-manifest.json++ - name: Upload the signed update manifest+ uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2+ with:+ name: installers-update-manifest+ path: |+ installers/installers-update-manifest.json+ installers/installers-update-manifest.json.sig+ if-no-files-found: error+ retention-days: 14++ # ------------------------------------------------------- GitHub Release+ release:+ name: Checksums and GitHub Release+ needs: [checksums, sign-update-manifest]+ # The signing job runs on tags only; a manual branch build still gets here+ # (and publishes nothing), a tag build only with a signed manifest.+ if: >-+ !cancelled() && needs.checksums.result == 'success' &&+ (needs.sign-update-manifest.result == 'success' ||+ (github.ref_type != 'tag' && needs.sign-update-manifest.result == 'skipped'))+ runs-on: ubuntu-latest+ timeout-minutes: 20+ permissions:+ # The ONLY job that may write to the repository, and only to attach the+ # assets it just verified.+ contents: write+ # Build provenance for the native installers (tag runs only, see the+ # attestation step): an OIDC identity for Sigstore plus the attestation+ # store. Users check it with `gh attestation verify`.+ id-token: write+ attestations: write+ steps:+ - name: Checkout+ uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0+ with:+ persist-credentials: false++ - name: Set up Python+ uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7.0.0+ with:+ python-version: ${{ env.PYTHON_VERSION }}++ # A tag that disagrees with the shipped version would publish installers+ # nobody can trace back to a commit - and the in-app updater compares the+ # release version against dodaios.__version__, so a mismatch would offer an+ # update that installs the same build forever.+ - name: Verify the tag matches dodaios.__version__+ if: github.ref_type == 'tag'+ shell: bash+ run: |+ set -euo pipefail+ tag_version="${GITHUB_REF_NAME#v}"+ package_version="$(python -c 'import re,pathlib; print(re.search(r"__version__ = \"([^\"]+)\"", pathlib.Path("dodaios/__init__.py").read_text()).group(1))')"+ echo "tag=${tag_version} package=${package_version}"+ if [ "${tag_version}" != "${package_version}" ]; then+ echo "::error::Tag ${GITHUB_REF_NAME} does not match dodaios.__version__ (${package_version})."+ exit 1+ fi++ - name: Download every installer+ uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2+ with:+ pattern: installer-*+ path: installers+ merge-multiple: true++ - name: Publish every installer under both of its names+ run: python scripts/ci/installer_aliases.py installers++ - name: Download the checksum manifest+ uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2+ with:+ name: installers-checksums+ path: installers++ - name: Download the signed update manifest+ if: github.ref_type == 'tag'+ uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2+ with:+ name: installers-update-manifest+ path: installers++ # The installers this job uploads must be exactly the bytes the checksum+ # manifest (and through it the signed update manifest) vouches for.+ - name: Check the installers against the manifests+ shell: bash+ run: |+ set -euo pipefail+ (cd installers && sha256sum -c installers-SHA256SUMS.txt)+ if [ "${GITHUB_REF_TYPE}" = "tag" ]; then+ python scripts/ci/update_manifest.py check --tag "$GITHUB_REF_NAME" \+ --checksums installers/installers-SHA256SUMS.txt \+ --manifest installers/installers-update-manifest.json+ fi+# SLSA build provenance for every native installer the manifest lists# (.exe, both .dmg, .AppImage, .deb, under both names), signed with this workflow's OIDC# identity and stored in GitHub's attestation store. It runs before thediff --git a/CHANGELOG.md b/CHANGELOG.mdindex 5130c905b3..5c2407299c 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -12,6 +12,14 @@ versioning per [SemVer](https://semver.org/).If your install is on version 3.1.1 or older, the in-app update no longer seesnew releases. Run the one-line installer again to update.+### Security++- The in-app updater of an installed app now installs an update only when the+ release's update manifest is signed by the Dodaios release key (Ed25519) and+ names exactly the version being installed, so neither swapped release files+ nor an older release served as a newer one get installed. Releases built from+ now on carry `installers-update-manifest.json` and its signature (#810).+---## [4.1.1] — 2026-10-26diff --git a/docs/ci-pipeline.md b/docs/ci-pipeline.mdindex 1a73b22320..6d3f2f75b7 100644--- a/docs/ci-pipeline.md+++ b/docs/ci-pipeline.md@@ -531,8 +531,10 @@ decides the order of steps:downgrades. A user already on the bad version leaves it only when a newerversion is published.* A native update downloads the installer from that same release and refuses- it unless it matches that release's `installers-SHA256SUMS.txt`- (`dodaios/core/installer_update.py`).+ it unless it matches that release's `installers-SHA256SUMS.txt`, which it+ trusts only when the release's `installers-update-manifest.json` is signed by+ the pinned release key and names that release's version+ (`dodaios/core/installer_update.py`, `dodaios/core/update_manifest.py`).Steps:@@ -562,7 +564,9 @@ Steps:steps: `pypi` (the PyPI upload in `release.yml`) and `release-signing` (the`sign` job of `sign-installer.yml`, the only job that reads the offlineEd25519 and ML-DSA-65 private keys, `WAVE2_OFFLINE_KEY_B64` and-`WAVE4_MLDSA65_KEY_B64`). Both admit deployments from `v*` tags only, never+`WAVE4_MLDSA65_KEY_B64`, and the `sign-update-manifest` job of+`desktop-installers.yml`, which signs the in-app updater's manifest with the+same Ed25519 key). Both admit deployments from `v*` tags only, neverfrom a branch, and administrators cannot bypass that policy. Neither hasrequired reviewers: a release runs from `release-cut.yml` to the publishedGitHub Release without an approval pause or a **Review deployments** click.diff --git a/docs/desktop-installers.md b/docs/desktop-installers.mdindex 9ae8f3c361..299736281c 100644--- a/docs/desktop-installers.md+++ b/docs/desktop-installers.md@@ -264,12 +264,21 @@ manually via `workflow_dispatch`):their OS build script and upload the artifact. The macOS jobs also read thefinished `.app` with `scripts/ci/check_frozen_macos_app.py` before theheadless smoke test.-2. `release` downloads all of them, refuses to continue if any promised asset is- missing, verifies the tag equals `dodaios.__version__`, writes- `installers-SHA256SUMS.txt` (plain `sha256sum` format, flat file names),- re-verifies it with `sha256sum -c`, and attaches everything to the Release.--`contents: write` is granted to that last job only.+2. `checksums` downloads all of them, refuses to continue if any promised+ asset is missing, and writes `installers-SHA256SUMS.txt` (plain `sha256sum`+ format, flat file names), re-verified with `sha256sum -c`.+3. `sign-update-manifest` (tag runs only, `release-signing` environment) writes+ `installers-update-manifest.json` - the release version, its tag and the+ SHA-256 of `installers-SHA256SUMS.txt` - and signs it with the+ offline-ceremony Ed25519 key (`WAVE2_OFFLINE_KEY_B64`) into+ `installers-update-manifest.json.sig`, then verifies the signature against+ `install/keys/offline-ceremony.pub`. A missing key fails the release.+4. `release` verifies the tag equals `dodaios.__version__`, re-checks every+ installer against the checksum manifest and the checksum manifest against+ the signed one, and attaches everything to the Release.++`contents: write` is granted to that last job only; the signing job holds a+read-only token and is the only job that can read the key.The version check matters twice over: a tag that disagrees with`dodaios.__version__` publishes installers nobody can trace back to a commit, and@@ -301,13 +310,21 @@ For a frozen install (`dodaios/core/installer_update.py`):mapping (Windows on ARM, Linux on aarch64) means the button never appears.2. **Refuse to offer what cannot be installed.** `status` reports`update_available: true` only when the release actually carries both this- platform's installer and `installers-SHA256SUMS.txt`. Status is fail-open:- any network error reports "no update", never an error.-3. **Verify before executing.** `apply` downloads to a temp directory under a+ platform's installer, `installers-SHA256SUMS.txt` and the signed update+ manifest (`installers-update-manifest.json` plus `.sig`). Status is+ fail-open: any network error reports "no update", never an error.+3. **Verify the signature.** Before any installer byte is fetched, `apply`+ checks the Ed25519 signature over `installers-update-manifest.json` against+ the release key pinned in `dodaios/core/update_manifest.py` (the same key as+ `install/keys/offline-ceremony.pub`), that the signed version equals the+ release being installed (a replayed older release is refused), and that the+ signed SHA-256 equals that of the release's `installers-SHA256SUMS.txt`. A+ release without the signed manifest is not offered and not installed.+4. **Verify before executing.** `apply` downloads to a temp directory under asize cap, computes SHA-256 and compares it against the manifest **of the samerelease**. A mismatch, a missing entry, an oversized body or an unreachablemanifest all delete the download and refuse. Apply is fail-closed.-4. **Hand over to the platform.**+5. **Hand over to the platform.**- Windows: runs the new `Setup.exe` detached with`/SILENT /CLOSEAPPLICATIONS /RESTARTAPPLICATIONS /NORESTART`. RestartManager closes the app, the files are replaced, the app comes back.diff --git a/dodaios/core/installer_update.py b/dodaios/core/installer_update.pyindex 12b94e2d47..f622a81ada 100644--- a/dodaios/core/installer_update.py+++ b/dodaios/core/installer_update.py@@ -61,6 +61,13 @@ from dodaios.core.branding import ()from dodaios.core.frozen import bundle_root, is_frozenfrom dodaios.core.process_utils import NO_WINDOW_CREATIONFLAGS+from dodaios.core.update_manifest import (+ MAX_MANIFEST_BYTES,+ MAX_SIGNATURE_BYTES,+ UPDATE_MANIFEST_ASSET_NAME,+ UpdateManifestError,+ verify_update_manifest,+)log = logging.getLogger(__name__)@@ -73,6 +80,7 @@ __all__ = ["HttpxAssetFetcher","InstallerAsset","InstallerUpdateError",+ "SignedManifestAssets","UpdateBlocker","SubprocessCommandRunner","apply_installer",@@ -148,6 +156,19 @@ class InstallerAsset:return {"name": self.name, "url": self.url, "size": self.size}+@dataclass(frozen=True)+class SignedManifestAssets:+ """The signed update manifest of one release, and the version it must name.++ See :mod:`dodaios.core.update_manifest`. ``version`` is the version of the+ release the caller is installing; the signed manifest must name exactly it.+ """++ manifest: InstallerAsset+ signature: InstallerAsset+ version: str++# --------------------------------------------------------------------------- ## Asset selection# --------------------------------------------------------------------------- #@@ -431,7 +452,7 @@ class HttpxAssetFetcher:body.extend(chunk)if len(body) > max_bytes:raise InstallerUpdateError(- f"checksum manifest is larger than {max_bytes} bytes — refusing it"+ f"release manifest is larger than {max_bytes} bytes — refusing it")return bytes(body).decode("utf-8", errors="replace")@@ -490,9 +511,18 @@ async def download_and_verify(on_progress: DownloadProgress | None = None,download_timeout_s: float = DOWNLOAD_TIMEOUT_S,alternatives: Sequence[InstallerAsset] = (),+ signed: SignedManifestAssets | None = None,) -> Path:"""Download ``asset`` and prove it against ``checksums``. Fail closed.+ ``signed`` is the release's signed update manifest. When given, the+ checksum manifest is trusted only after the Ed25519 signature over the+ update manifest verifies against the pinned release key, the signed+ version equals ``signed.version`` and the signed digest equals the+ checksum manifest's own SHA-256 — all before a byte of the installer is+ fetched. The in-app updater always passes it; ``None`` keeps the bare+ checksum check for callers that have no release to bind to.+``alternatives`` are further assets of the SAME release holding the sameinstaller under another accepted name, in order of preference after``asset``. The first of them all that has a line in the checksum manifest@@ -540,6 +570,9 @@ async def download_and_verify(except Exception as exc: # noqa: BLE001 — every transport error is the same refusalraise InstallerUpdateError(f"could not download {CHECKSUMS_ASSET_NAME}: {exc}") from exc+ if signed is not None:+ await _verify_signed_manifest(active, signed, manifest_text)+digests = parse_sha256sums(manifest_text)candidates = (asset, *alternatives)vouched = [candidate for candidate in candidates if digests.get(candidate.name)]@@ -591,6 +624,42 @@ async def download_and_verify(return target+async def _fetch_small_text(active: AssetFetcher, asset: InstallerAsset, max_bytes: int) -> str:+ """Fetch one small release document; every failure is the same refusal."""+ try:+ return await asyncio.wait_for(+ active.get_text(asset.url, max_bytes=max_bytes), timeout=READ_TIMEOUT_S+ )+ except InstallerUpdateError:+ raise+ except TimeoutError as exc:+ raise InstallerUpdateError(+ f"{asset.name} did not arrive within {READ_TIMEOUT_S:.0f}s"+ ) from exc+ except Exception as exc: # noqa: BLE001 — every transport error is the same refusal+ raise InstallerUpdateError(f"could not download {asset.name}: {exc}") from exc+++async def _verify_signed_manifest(+ active: AssetFetcher, signed: SignedManifestAssets, checksums_text: str+) -> None:+ """Prove the checksum manifest is the one the release key signed for this version."""+ manifest_text = await _fetch_small_text(active, signed.manifest, MAX_MANIFEST_BYTES)+ signature_text = await _fetch_small_text(active, signed.signature, MAX_SIGNATURE_BYTES)+ try:+ # Both documents are ASCII as published, so the text round trip+ # returns their exact bytes; anything else fails the signature check.+ verified = verify_update_manifest(+ manifest_text.encode("utf-8"),+ signature_text,+ checksums=checksums_text.encode("utf-8"),+ expected_version=signed.version,+ )+ except UpdateManifestError as exc:+ raise InstallerUpdateError(f"{UPDATE_MANIFEST_ASSET_NAME}: {exc}") from exc+ log.info("[update] signed update manifest verified for %s", verified.tag)++def _prepare_target(dest_dir: Path, name: str) -> Path:"""Create the download directory and return the file path inside it.diff --git a/dodaios/core/update_manifest.py b/dodaios/core/update_manifest.pynew file mode 100644index 0000000000..8f4b106352--- /dev/null+++ b/dodaios/core/update_manifest.py@@ -0,0 +1,232 @@+"""The signed, version-bound update manifest the in-app updater trusts.++A release's ``installers-SHA256SUMS.txt`` proves which bytes each installer+must have, but on its own it proves nothing about WHO wrote it: anyone able to+replace release assets could replace the installer and its checksum line+together. So every release built by ``desktop-installers.yml`` also carries++* ``installers-update-manifest.json`` — a small JSON document that names the+ release version and tag and the SHA-256 of that release's checksum manifest,+* ``installers-update-manifest.json.sig`` — the base64 of a raw Ed25519+ signature over the exact manifest bytes.++The signature is made in the release workflow with the offline-ceremony+Ed25519 key, whose private half lives only in the ``WAVE2_OFFLINE_KEY_B64``+secret of the ``release-signing`` environment (AP-29; only ``v*`` tag runs can+read it). Its public half is pinned below and is the same key published as+``install/keys/offline-ceremony.pub`` (a test keeps the two identical). The+``schema`` field separates these signatures from the ones that key makes over+the install scripts: a signature over a manifest can never be passed off as one+over a script, and the reverse fails to parse as a manifest.++The version binding is what stops a replay: a validly signed manifest of an+OLDER release (with its older, perhaps vulnerable installers) cannot be served+as a newer one, because the updater compares the signed version with the+release it is installing.++Pure functions, no network. ``cryptography`` is imported lazily: it is a base+dependency, but this module sits on the updater's import path and must not cost+the boot anything (AP-26).+"""++from __future__ import annotations++import base64+import binascii+import hashlib+import json+from collections.abc import Sequence+from dataclasses import dataclass+from typing import Any++__all__ = [+ "MANIFEST_SCHEMA",+ "MAX_MANIFEST_BYTES",+ "MAX_SIGNATURE_BYTES",+ "PINNED_PUBLIC_KEYS",+ "UPDATE_MANIFEST_ASSET_NAME",+ "UPDATE_MANIFEST_SIGNATURE_ASSET_NAME",+ "UpdateManifest",+ "UpdateManifestError",+ "build_manifest",+ "normalize_version",+ "parse_manifest",+ "verify_signature",+ "verify_update_manifest",+]++UPDATE_MANIFEST_ASSET_NAME = "installers-update-manifest.json"+UPDATE_MANIFEST_SIGNATURE_ASSET_NAME = "installers-update-manifest.json.sig"++#: Identifies what the signature is about. Changing the document's shape means+#: a new schema string, never a silent reinterpretation of the old one.+MANIFEST_SCHEMA = "dodaios-update-manifest/1"++# The manifest is a few hundred bytes and the signature 88 characters; anything+# much larger is not what the release workflow wrote.+MAX_MANIFEST_BYTES = 16_000+MAX_SIGNATURE_BYTES = 1_000++#: Ed25519 public keys allowed to sign an update manifest, as base64 of the DER+#: SubjectPublicKeyInfo (the body of the ``PUBLIC KEY`` PEM). Rotating the key+#: means shipping the NEW key here in one release while the old one still signs,+#: and switching the release workflow only after that release is out — an+#: install that does not know the signing key refuses every update.+PINNED_PUBLIC_KEYS: tuple[str, ...] = (+ # install/keys/offline-ceremony.pub+ "MCowBQYDK2VwAyEArlfig3ALFBrED+VrNZ8hlrVnRJxDnI8PCkxGB26N4U4=",+)++_SHA256_HEX_LENGTH = 64+_ED25519_SIGNATURE_LENGTH = 64+++class UpdateManifestError(ValueError):+ """The update manifest is missing, malformed, unsigned or for another release.++ The message is user-facing: the updater shows it when it refuses an update.+ """+++@dataclass(frozen=True)+class UpdateManifest:+ """The fields of a parsed, structurally valid update manifest."""++ version: str+ tag: str+ checksums_sha256: str+++def normalize_version(value: str) -> str:+ """A version or tag reduced to the bare version (``v4.2.0`` -> ``4.2.0``)."""+ text = str(value).strip()+ return text[1:] if text[:1] in {"v", "V"} else text+++def build_manifest(*, version: str, tag: str, checksums: bytes) -> bytes:+ """The exact manifest bytes the release workflow signs.++ Canonical JSON (sorted keys, no whitespace, ASCII only) so the same inputs+ always give the same bytes, and a text transport cannot alter them.+ """+ bare = normalize_version(version)+ if not bare or normalize_version(tag) != bare:+ raise UpdateManifestError(f"tag {tag!r} does not match version {version!r}")+ document = {+ "schema": MANIFEST_SCHEMA,+ "version": bare,+ "tag": tag,+ "checksums_sha256": hashlib.sha256(checksums).hexdigest(),+ }+ return json.dumps(document, sort_keys=True, separators=(",", ":"), ensure_ascii=True).encode(+ "ascii"+ )+++def parse_manifest(data: bytes) -> UpdateManifest:+ """Parse manifest bytes; raise :class:`UpdateManifestError` on any defect."""+ if len(data) > MAX_MANIFEST_BYTES:+ raise UpdateManifestError("the update manifest is too large to be genuine")+ try:+ document: Any = json.loads(data.decode("utf-8"))+ except (UnicodeDecodeError, json.JSONDecodeError) as exc:+ raise UpdateManifestError(f"the update manifest is not valid JSON: {exc}") from exc+ if not isinstance(document, dict):+ raise UpdateManifestError("the update manifest is not a JSON object")+ if document.get("schema") != MANIFEST_SCHEMA:+ raise UpdateManifestError(+ f"the update manifest has an unknown schema {document.get('schema')!r}"+ )+ version = document.get("version")+ tag = document.get("tag")+ digest = document.get("checksums_sha256")+ if not isinstance(version, str) or not version:+ raise UpdateManifestError("the update manifest names no version")+ if not isinstance(tag, str) or normalize_version(tag) != version:+ raise UpdateManifestError("the update manifest's tag does not match its version")+ if (+ not isinstance(digest, str)+ or len(digest) != _SHA256_HEX_LENGTH+ or any(char not in "0123456789abcdef" for char in digest)+ ):+ raise UpdateManifestError("the update manifest carries no valid checksum digest")+ return UpdateManifest(version=version, tag=tag, checksums_sha256=digest)+++def _decode_signature(signature_text: str) -> bytes:+ text = signature_text.strip()+ if len(text) > MAX_SIGNATURE_BYTES:+ raise UpdateManifestError("the update manifest signature is too large to be genuine")+ try:+ raw = base64.b64decode(text, validate=True)+ except (binascii.Error, ValueError) as exc:+ raise UpdateManifestError("the update manifest signature is not base64") from exc+ if len(raw) != _ED25519_SIGNATURE_LENGTH:+ raise UpdateManifestError("the update manifest signature is not an Ed25519 signature")+ return raw+++def verify_signature(+ data: bytes, signature_text: str, *, public_keys: Sequence[str] | None = None+) -> None:+ """Prove ``data`` was signed by one of ``public_keys``. Fail closed.++ ``None`` means :data:`PINNED_PUBLIC_KEYS`, read at call time.+ """+ if public_keys is None:+ public_keys = PINNED_PUBLIC_KEYS+ raw_signature = _decode_signature(signature_text)+ try:+ from cryptography.exceptions import InvalidSignature+ from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey+ from cryptography.hazmat.primitives.serialization import load_der_public_key+ except ImportError as exc: # pragma: no cover - cryptography is a base dependency+ raise UpdateManifestError(+ "this install cannot check update signatures (cryptography is missing) — "+ "reinstall Dodaios from the download page"+ ) from exc++ for encoded in public_keys:+ key = load_der_public_key(base64.b64decode(encoded))+ if not isinstance(key, Ed25519PublicKey):+ raise UpdateManifestError("a pinned update key is not an Ed25519 key")+ try:+ key.verify(raw_signature, data)+ except InvalidSignature:+ # Not this key; during a rotation another pinned key may have+ # signed. No key matching is reported below.+ continue+ return+ raise UpdateManifestError(+ "the update manifest is not signed by the Dodaios release key — "+ "refusing to install this update"+ )+++def verify_update_manifest(+ data: bytes,+ signature_text: str,+ *,+ checksums: bytes,+ expected_version: str,+ public_keys: Sequence[str] | None = None,+) -> UpdateManifest:+ """Verify signature, version binding and checksum binding, in that order.++ ``checksums`` are the exact bytes of the release's checksum manifest that+ the installer will be verified against; ``expected_version`` is the version+ of the release being installed. Returns the manifest when all three hold.+ """+ verify_signature(data, signature_text, public_keys=public_keys)+ manifest = parse_manifest(data)+ expected = normalize_version(expected_version)+ if manifest.version != expected:+ raise UpdateManifestError(+ f"the signed update manifest is for version {manifest.version}, "+ f"not {expected} — refusing a replayed release"+ )+ if hashlib.sha256(checksums).hexdigest() != manifest.checksums_sha256:+ raise UpdateManifestError(+ "the checksum manifest of this release is not the one the release key signed"+ )+ return manifestdiff --git a/dodaios/ui/web/update_routes.py b/dodaios/ui/web/update_routes.pyindex 9f6e84d337..05fb05dd4a 100644--- a/dodaios/ui/web/update_routes.py+++ b/dodaios/ui/web/update_routes.py@@ -6,8 +6,10 @@ updates itself differently:* **frozen** — the visitor downloaded a native installer from the website(``Setup.exe`` / ``.dmg`` / ``.AppImage``). There is no git checkout here. Theupdate is the NEXT installer asset on the GitHub Release: downloaded, proven- against that same release's ``installers-SHA256SUMS.txt``, then handed to the- platform's own upgrade mechanism (``dodaios/core/installer_update.py``).+ against that same release's ``installers-SHA256SUMS.txt`` — which is trusted+ only once the release's Ed25519-signed, version-bound update manifest vouches+ for it (``dodaios/core/update_manifest.py``) — then handed to the platform's+ own upgrade mechanism (``dodaios/core/installer_update.py``).``dodaios.core.frozen.is_frozen()`` is the ONLY probe that selects this path,so a dev tree and a managed checkout are structurally unaffected by it.* **managed** — the one-line installer's git checkout under@@ -88,6 +90,7 @@ from dodaios.core.frozen import is_frozenfrom dodaios.core.installer_update import (CHECKSUMS_ASSET_NAME,InstallerUpdateError,+ SignedManifestAssets,apply_installer,download_and_verify,download_workdir,@@ -107,6 +110,10 @@ from dodaios.core.update_contract import (parse_update_contract,read_update_contract,)+from dodaios.core.update_manifest import (+ UPDATE_MANIFEST_ASSET_NAME,+ UPDATE_MANIFEST_SIGNATURE_ASSET_NAME,+)log = logging.getLogger(__name__)@@ -971,6 +978,21 @@ def _frozen_release_assets()+def _signed_manifest_assets(release: dict[str, Any]) -> tuple[Any | None, Any | None]:+ """``(update manifest, its signature)`` from a release payload; ``None`` when absent.++ Without both, a frozen install refuses the release: an update whose+ checksums the release key did not sign is not installed (issue #810).+ """+ assets = release.get("assets") or []+ if not isinstance(assets, list):+ return None, None+ return (+ select_asset(assets, UPDATE_MANIFEST_ASSET_NAME),+ select_asset(assets, UPDATE_MANIFEST_SIGNATURE_ASSET_NAME),+ )++async def _frozen_status(current: str) -> dict[str, object]:"""Status for a natively installed app. Fail-OPEN, exactly like the managed one.@@ -1040,6 +1062,15 @@ async def _frozen_status(current: str) -> dict[str, object]:CHECKSUMS_ASSET_NAME,)return result+ signed_manifest, signature = _signed_manifest_assets(latest)+ if signed_manifest is None or signature is None:+ # apply would refuse it: the checksums are not signed by the release key.+ log.info(+ "[update] release %s carries no signed %s — not offering a frozen update",+ version or "?",+ UPDATE_MANIFEST_ASSET_NAME,+ )+ return resultresult["asset"] = asset.as_dict()if _is_newer(version, current):@@ -1132,8 +1163,7 @@ async def _apply_frozen(raise HTTPException(status_code=501,detail=(- f"no Dodaios installer is published for "- f"{sys.platform}/{platform_module.machine()}"+ f"no Dodaios installer is published for {sys.platform}/{platform_module.machine()}"),)@@ -1176,6 +1206,19 @@ async def _apply_frozen(),)+ signed_manifest, signature = _signed_manifest_assets(latest)+ if signed_manifest is None or signature is None:+ raise HTTPException(+ status_code=502,+ detail=(+ f"release {release_tag} has no signed {UPDATE_MANIFEST_ASSET_NAME} — "+ "refusing to install an update the release key did not sign"+ ),+ )+ signed = SignedManifestAssets(+ manifest=signed_manifest, signature=signature, version=release_version+ )+blocker = update_blocker()if blocker is not None:# Asked before the download: otherwise the user waits for several@@ -1207,11 +1250,12 @@ async def _apply_frozen(dest_dir=workdir,on_progress=on_bytes,alternatives=installers[1:],+ signed=signed,)asset = next((a for a in installers if a.name == installer.name), asset)else:installer = await download_and_verify(- asset, checksums, dest_dir=workdir, on_progress=on_bytes+ asset, checksums, dest_dir=workdir, on_progress=on_bytes, signed=signed)# download_and_verify hashes the file after the last byte lands, so by# the time it returns the verify phase is already over — the window isdiff --git a/scripts/ci/release_assets.py b/scripts/ci/release_assets.pyindex 259a1a73ec..8c507f4ebc 100644--- a/scripts/ci/release_assets.py+++ b/scripts/ci/release_assets.py@@ -65,8 +65,18 @@ REQUIRED_ASSETS = ("pq-mldsa65.pub.pem",})-DESKTOP_ASSETS = INSTALLERS | {"installers-SHA256SUMS.txt"}+#: The signed, version-bound update manifest the in-app updater requires before+#: it trusts ``installers-SHA256SUMS.txt`` (``dodaios/core/update_manifest.py``).+#: Required for every new desktop release; releases published before it existed+#: lack it, so the published-release check only verifies it where present.+UPDATE_MANIFEST_ASSETS = (+ "installers-update-manifest.json",+ "installers-update-manifest.json.sig",+)+DESKTOP_ASSETS = INSTALLERS | {"installers-SHA256SUMS.txt", *UPDATE_MANIFEST_ASSETS}SIGNING_ASSETS = REQUIRED_ASSETS - DESKTOP_ASSETS+#: What a draft must carry before finalization publishes it.+FINALIZE_ASSETS = REQUIRED_ASSETS | set(UPDATE_MANIFEST_ASSETS)PLATFORM_INSTALLERS = {"linux": {"Dodaios-Linux-x86_64.AppImage", "PersonalJarvis-Linux-x86_64.AppImage"},"windows": {"Dodaios-Setup-x64.exe", "PersonalJarvis-Setup-x64.exe"},@@ -311,6 +321,35 @@ def asset_errors(assets: list[dict], manifests: dict[str, str]) -> list[str]:return errors+def update_manifest_errors(tag: str, checksums: str, manifest: bytes, signature: str) -> list[str]:+ """The signed update manifest must bind ``tag`` to exactly ``checksums``.++ The signature is checked with the updater's own verifier when+ ``cryptography`` is importable; the signing job has already checked it+ with ``openssl`` against the same pinned key.+ """+ from dodaios.core.update_manifest import (+ UpdateManifestError,+ build_manifest,+ parse_manifest,+ verify_update_manifest,+ )++ checksum_bytes = checksums.encode("utf-8")+ try:+ parsed = parse_manifest(manifest)+ if manifest != build_manifest(version=parsed.version, tag=tag, checksums=checksum_bytes):+ return [f"installers-update-manifest.json does not bind {tag} to its checksums"]+ try:+ import cryptography # noqa: F401+ except ImportError:+ return []+ verify_update_manifest(manifest, signature, checksums=checksum_bytes, expected_version=tag)+ except UpdateManifestError as exc:+ return [f"installers-update-manifest.json: {exc}"]+ return []++def alias_errors(digests: dict[str, str]) -> list[str]:"""Both names of one installer must carry the same bytes."""return [@@ -363,6 +402,19 @@ def finalize(repo: str, tag: str, sha: str, wait_minutes: int) -> int:)manifests[name] = (folder / name).read_text(encoding="utf-8")errors = asset_errors(assets, manifests)+ present = {asset["name"] for asset in assets}+ if missing := [name for name in UPDATE_MANIFEST_ASSETS if name not in present]:+ errors.extend(f"missing or incomplete asset: {name}" for name in missing)+ else:+ manifest, signature = (_download(repo, tag, n, folder) for n in UPDATE_MANIFEST_ASSETS)+ errors.extend(+ update_manifest_errors(+ tag,+ manifests["installers-SHA256SUMS.txt"],+ manifest.read_bytes(),+ signature.read_text(encoding="ascii"),+ )+ )if manifests["payload-commit.txt"].strip() != sha:errors.append("signed payload commit does not match the release commit")if errors:@@ -455,7 +507,18 @@ def published_errors(repo: str, tag: str) -> list[str]:name: _download(repo, tag, name, folder).read_text(encoding="utf-8")for name in ("checksums.txt", "installers-SHA256SUMS.txt", "source-SHA256SUMS.txt")}- errors = asset_errors(assets, manifests)+ errors = asset_errors(assets, manifests)+ present = {asset["name"] for asset in assets}+ if all(name in present for name in UPDATE_MANIFEST_ASSETS):+ manifest, signature = (_download(repo, tag, n, folder) for n in UPDATE_MANIFEST_ASSETS)+ errors.extend(+ update_manifest_errors(+ tag,+ manifests["installers-SHA256SUMS.txt"],+ manifest.read_bytes(),+ signature.read_text(encoding="ascii"),+ )+ )by_name = {asset["name"]: asset for asset in assets}source, problems = parse_manifest(manifests["source-SHA256SUMS.txt"])errors.extend(f"{problem} in source-SHA256SUMS.txt" for problem in problems)diff --git a/scripts/ci/update_manifest.py b/scripts/ci/update_manifest.pynew file mode 100644index 0000000000..3d650fc495--- /dev/null+++ b/scripts/ci/update_manifest.py@@ -0,0 +1,111 @@+#!/usr/bin/env python3+"""Write and check the signed update manifest of a desktop release (issue #810).++The in-app updater of a frozen install trusts a release's+``installers-SHA256SUMS.txt`` only when ``installers-update-manifest.json``+names that release's version and the checksum manifest's SHA-256, and an+Ed25519 signature by the release key over the manifest verifies+(``dodaios/core/update_manifest.py``). ``desktop-installers.yml`` writes the+manifest with this script, signs it with ``openssl pkeyutl`` inside the+``release-signing`` environment, and checks the result before it is uploaded:++ python scripts/ci/update_manifest.py build --tag v4.2.0 \\+ --checksums installers/installers-SHA256SUMS.txt \\+ --out installers/installers-update-manifest.json+ python scripts/ci/update_manifest.py check --tag v4.2.0 \\+ --checksums installers/installers-SHA256SUMS.txt \\+ --manifest installers/installers-update-manifest.json++``check`` covers the version and checksum binding; the signature itself is+verified by the workflow with ``openssl`` against+``install/keys/offline-ceremony.pub`` (and, when ``--signature`` is given and+``cryptography`` is importable, with the updater's own verifier too).+"""++from __future__ import annotations++import argparse+import sys+from pathlib import Path++ROOT = Path(__file__).resolve().parents[2]+if str(ROOT) not in sys.path:+ sys.path.insert(0, str(ROOT))++from dodaios.core.update_manifest import ( # noqa: E402+ UpdateManifestError,+ build_manifest,+ normalize_version,+ parse_manifest,+ verify_update_manifest,+)+++def _package_version() -> str:+ import re++ text = (ROOT / "dodaios" / "__init__.py").read_text(encoding="utf-8")+ match = re.search(r'__version__ = "([^"]+)"', text)+ if match is None:+ raise UpdateManifestError("dodaios/__init__.py has no __version__")+ return match.group(1)+++def build(tag: str, checksums: Path, out: Path) -> None:+ version = _package_version()+ if normalize_version(tag) != version:+ raise UpdateManifestError(f"tag {tag} does not match dodaios.__version__ {version}")+ out.write_bytes(build_manifest(version=version, tag=tag, checksums=checksums.read_bytes()))+ print(f"[update-manifest] wrote {out.name} for {tag}")+++def check(tag: str, checksums: Path, manifest: Path, signature: Path | None) -> None:+ data = manifest.read_bytes()+ if signature is not None:+ try:+ import cryptography # noqa: F401+ except ImportError:+ print("[update-manifest] cryptography not installed; signature left to openssl")+ else:+ verify_update_manifest(+ data,+ signature.read_text(encoding="ascii"),+ checksums=checksums.read_bytes(),+ expected_version=tag,+ )+ print("[update-manifest] signature verified with the updater's own verifier")+ parsed = parse_manifest(data)+ expected = build_manifest(version=parsed.version, tag=tag, checksums=checksums.read_bytes())+ if data != expected:+ raise UpdateManifestError(+ f"{manifest.name} does not bind {tag} to {checksums.name} byte for byte"+ )+ print(f"[update-manifest] {manifest.name} binds {tag} to {checksums.name}")+++def main(argv: list[str] | None = None) -> int:+ parser = argparse.ArgumentParser(description=__doc__)+ sub = parser.add_subparsers(dest="command", required=True)+ for name in ("build", "check"):+ command = sub.add_parser(name)+ command.add_argument("--tag", required=True)+ command.add_argument("--checksums", type=Path, required=True)+ if name == "build":+ command.add_argument("--out", type=Path, required=True)+ else:+ command.add_argument("--manifest", type=Path, required=True)+ command.add_argument("--signature", type=Path)+ args = parser.parse_args(argv)+ try:+ if args.command == "build":+ build(args.tag, args.checksums, args.out)+ else:+ check(args.tag, args.checksums, args.manifest, args.signature)+ except (OSError, UpdateManifestError) as exc:+ print(f"::error::{exc}", file=sys.stderr)+ return 1+ return 0+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/tests/fakes/fake_installer_update.py b/tests/fakes/fake_installer_update.pyindex 18d5ff5efa..d869f3dc94 100644--- a/tests/fakes/fake_installer_update.py+++ b/tests/fakes/fake_installer_update.py@@ -36,14 +36,19 @@ class FakeAssetFetcher:text_urls: list[str] = field(default_factory=list)download_urls: list[str] = field(default_factory=list)progress_ticks: list[tuple[int, int | None]] = field(default_factory=list)+ #: Further small documents by the file name their URL ends with (the+ #: signed update manifest and its signature); anything else gets+ #: ``manifest``.+ texts: dict[str, str] = field(default_factory=dict)async def get_text(self, url: str, *, max_bytes: int) -> str:self.text_urls.append(url)if self.fail_text is not None:raise self.fail_text- if len(self.manifest.encode("utf-8")) > max_bytes:- raise AssertionError("the fake manifest exceeds the caller's cap")- return self.manifest+ body = self.texts.get(url.rsplit("/", 1)[-1], self.manifest)+ if len(body.encode("utf-8")) > max_bytes:+ raise AssertionError("the fake document exceeds the caller's cap")+ return bodyasync def download(self,diff --git a/tests/unit/ci/test_installer_aliases.py b/tests/unit/ci/test_installer_aliases.pyindex 415cbbf4fa..56d917a76c 100644--- a/tests/unit/ci/test_installer_aliases.py+++ b/tests/unit/ci/test_installer_aliases.py@@ -55,11 +55,11 @@ def test_the_pairs_cover_exactly_the_published_installers() -> None:assert all(earlier.startswith("PersonalJarvis-") for _current, earlier in PAIRS)-def test_the_release_job_aliases_after_download_and_before_the_manifest() -> None:+def test_the_checksum_job_aliases_after_download_and_before_the_manifest() -> None:workflow = yaml.safe_load((ROOT / ".github/workflows/desktop-installers.yml").read_text(encoding="utf-8"))- steps = workflow["jobs"]["release"]["steps"]+ steps = workflow["jobs"]["checksums"]["steps"]runs = [step.get("run", "") for step in steps]download = next(i for i, s in enumerate(steps) if "download-artifact@" in s.get("uses", ""))alias = next(i for i, run in enumerate(runs) if "installer_aliases.py installers" in run)@@ -69,6 +69,19 @@ def test_the_release_job_aliases_after_download_and_before_the_manifest() -> Nonassert name in runs[manifest], name+def test_the_release_job_uploads_only_what_the_manifest_vouches_for() -> None:+ """The release job re-creates the aliases, then checks every file it uploads."""+ workflow = yaml.safe_load(+ (ROOT / ".github/workflows/desktop-installers.yml").read_text(encoding="utf-8")+ )+ steps = workflow["jobs"]["release"]["steps"]+ runs = [step.get("run", "") for step in steps]+ alias = next(i for i, run in enumerate(runs) if "installer_aliases.py installers" in run)+ check = next(i for i, run in enumerate(runs) if "sha256sum -c" in run)+ upload = next(i for i, run in enumerate(runs) if "release_assets.py upload" in run)+ assert alias < check < upload++def test_the_windows_setup_is_signed_under_the_pinned_name() -> None:"""SignPath pins the setup's file name; the current name is copied later."""workflow = yaml.safe_load(diff --git a/tests/unit/ci/test_pipeline_audit.py b/tests/unit/ci/test_pipeline_audit.pyindex f45e0ee7e1..36f71ec00e 100644--- a/tests/unit/ci/test_pipeline_audit.py+++ b/tests/unit/ci/test_pipeline_audit.py@@ -494,7 +494,7 @@ def test_a_red_nightly_reaches_someone_and_only_a_nightly_on_main_can_write_issuassert '[ "$gate_conclusion" != "failure" ]' in scriptassert '[ "$label" = "macos-main" ] && [ "$conclusion" = "cancelled" ]' in scriptassert '.jobs[] | select(.conclusion == "failure") | .name' in script- assert 'macOS sweep ended cancelled without a failed job' in script+ assert "macOS sweep ended cancelled without a failed job" in scriptassert '--label "$label"' in script# A check by hand runs from main only, vets the run it is given like the# event, and writes nothing unless the dry run is switched off.@@ -1023,6 +1023,32 @@ class FakeRelease:self.manifests["payload-commit.txt"] = ("c" * 40 if wrong_payload else SHA) + "\n"self.corrupt_source = corrupt_sourceself.commands = []+ # The signed update manifest every new desktop release carries (#810),+ # signed with a throwaway key that install() pins in its place.+ import base64++ from cryptography.hazmat.primitives import serialization+ from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey++ from dodaios.core.update_manifest import build_manifest++ key = Ed25519PrivateKey.generate()+ self.public_key = base64.b64encode(+ key.public_key().public_bytes(+ serialization.Encoding.DER, serialization.PublicFormat.SubjectPublicKeyInfo+ )+ ).decode("ascii")+ manifest = build_manifest(+ version=TAG,+ tag=TAG,+ checksums=self.manifests["installers-SHA256SUMS.txt"].encode("utf-8"),+ )+ self.manifests["installers-update-manifest.json"] = manifest.decode("ascii")+ self.manifests["installers-update-manifest.json.sig"] = base64.b64encode(+ key.sign(manifest)+ ).decode("ascii")+ for name in release_assets.UPDATE_MANIFEST_ASSETS:+ self.assets.append({"name": name, "size": 1, "state": "uploaded"})def pages(self, endpoint, key):if "/assets?" in endpoint:@@ -1061,6 +1087,7 @@ class FakeRelease:return subprocess.CompletedProcess(args, 0, output, "")def install(self, monkeypatch):+ monkeypatch.setattr("dodaios.core.update_manifest.PINNED_PUBLIC_KEYS", (self.public_key,))monkeypatch.setattr(release_assets, "api_pages", self.pages)monkeypatch.setattr(release_assets, "run_command", self.command)monkeypatch.setattr(release_assets, "gate_state", lambda *a, **k: "success")@@ -1101,6 +1128,23 @@ def test_corrupt_release_never_becomes_public(monkeypatch, defect):assert not any(command[:3] == ["gh", "release", "edit"] for command in fake.commands)[email protected]("defect", ["unsigned", "forged"])+def test_a_release_without_a_valid_signed_update_manifest_stays_a_draft(monkeypatch, defect):+ fake = FakeRelease()+ fake.install(monkeypatch)+ if defect == "unsigned":+ fake.assets = [+ asset+ for asset in fake.assets+ if asset["name"] not in release_assets.UPDATE_MANIFEST_ASSETS+ ]+ else:+ fake.manifests["installers-update-manifest.json.sig"] = "A" * 86 + "=="+ with pytest.raises(ValueError, match="installers-update-manifest.json"):+ release_assets.finalize(REPO, TAG, SHA, 0)+ assert not any(command[:3] == ["gh", "release", "edit"] for command in fake.commands)++def test_skipped_pypi_publication_cannot_finalize_a_release(monkeypatch):fake = FakeRelease()fake.install(monkeypatch)diff --git a/tests/unit/core/test_update_manifest.py b/tests/unit/core/test_update_manifest.pynew file mode 100644index 0000000000..938e42f7f8--- /dev/null+++ b/tests/unit/core/test_update_manifest.py@@ -0,0 +1,331 @@+"""The signed, version-bound update manifest (issue #810).++Every case signs with a throwaway Ed25519 key made inside the test; the real+release key never leaves the ``release-signing`` environment. What is pinned:++* the verifier accepts exactly what the release workflow produces (including a+ signature made by ``openssl pkeyutl``, the workflow's own tool),+* a wrong key, a tampered manifest, a replayed older version and a swapped+ checksum manifest are each refused before any installer byte is fetched,+* the key pinned in the app is the published offline-ceremony key.+"""++from __future__ import annotations++import base64+import hashlib+import shutil+import subprocess+from pathlib import Path++import pytest+from cryptography.hazmat.primitives import serialization+from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey++from dodaios.core.installer_update import (+ CHECKSUMS_ASSET_NAME,+ InstallerAsset,+ InstallerUpdateError,+ SignedManifestAssets,+ download_and_verify,+)+from dodaios.core.update_manifest import (+ MANIFEST_SCHEMA,+ PINNED_PUBLIC_KEYS,+ UPDATE_MANIFEST_ASSET_NAME,+ UPDATE_MANIFEST_SIGNATURE_ASSET_NAME,+ UpdateManifestError,+ build_manifest,+ parse_manifest,+ verify_update_manifest,+)+from scripts.ci import release_assets+from scripts.ci import update_manifest as manifest_cli+from tests.fakes.fake_installer_update import FakeAssetFetcher++ROOT = Path(__file__).resolve().parents[3]+PAYLOAD = b"an installer stand-in"+SETUP = "Dodaios-Setup-x64.exe"+CHECKSUMS = f"{hashlib.sha256(PAYLOAD).hexdigest()} {SETUP}\n".encode()+++def _key_pair() -> tuple[Ed25519PrivateKey, str]:+ private = Ed25519PrivateKey.generate()+ public = private.public_key().public_bytes(+ serialization.Encoding.DER, serialization.PublicFormat.SubjectPublicKeyInfo+ )+ return private, base64.b64encode(public).decode("ascii")+++def _sign(private: Ed25519PrivateKey, data: bytes) -> str:+ return base64.b64encode(private.sign(data)).decode("ascii")+++# --------------------------------------------------------------------------- #+# The document and its signature+# --------------------------------------------------------------------------- #+def test_build_is_canonical_and_parses_back() -> None:+ data = build_manifest(version="4.2.0", tag="v4.2.0", checksums=CHECKSUMS)+ assert data == build_manifest(version="v4.2.0", tag="v4.2.0", checksums=CHECKSUMS)+ assert b" " not in data and data.isascii()+ parsed = parse_manifest(data)+ assert parsed.version == "4.2.0"+ assert parsed.tag == "v4.2.0"+ assert parsed.checksums_sha256 == hashlib.sha256(CHECKSUMS).hexdigest()+++def test_build_refuses_a_tag_for_another_version() -> None:+ with pytest.raises(UpdateManifestError):+ build_manifest(version="4.2.0", tag="v4.1.0", checksums=CHECKSUMS)+++def test_a_valid_manifest_verifies() -> None:+ private, public = _key_pair()+ data = build_manifest(version="4.2.0", tag="v4.2.0", checksums=CHECKSUMS)+ verified = verify_update_manifest(+ data,+ _sign(private, data),+ checksums=CHECKSUMS,+ expected_version="4.2.0",+ public_keys=(public,),+ )+ assert verified.tag == "v4.2.0"+++def test_any_pinned_key_may_sign_so_a_rotation_can_overlap() -> None:+ old_private, old_public = _key_pair()+ _new_private, new_public = _key_pair()+ data = build_manifest(version="4.2.0", tag="v4.2.0", checksums=CHECKSUMS)+ verify_update_manifest(+ data,+ _sign(old_private, data),+ checksums=CHECKSUMS,+ expected_version="v4.2.0",+ public_keys=(new_public, old_public),+ )+++ "defect", ["wrong_key", "tampered", "replayed", "other_checksums", "garbage_sig", "short_sig"]+)+def test_every_defect_is_refused(defect: str) -> None:+ private, public = _key_pair()+ version = "4.2.0"+ data = build_manifest(version=version, tag="v4.2.0", checksums=CHECKSUMS)+ signature = _sign(private, data)+ checksums = CHECKSUMS+ if defect == "wrong_key":+ signature = _sign(Ed25519PrivateKey.generate(), data)+ elif defect == "tampered":+ data = data.replace(b"4.2.0", b"4.3.0")+ elif defect == "replayed":+ # A genuine, signed manifest of an older release served as the newer one.+ data = build_manifest(version="4.1.0", tag="v4.1.0", checksums=CHECKSUMS)+ signature = _sign(private, data)+ elif defect == "other_checksums":+ checksums = CHECKSUMS.replace(SETUP.encode(), b"Evil-Setup.exe")+ elif defect == "garbage_sig":+ signature = "not base64 at all!"+ else:+ signature = base64.b64encode(b"x" * 10).decode()+ with pytest.raises(UpdateManifestError):+ verify_update_manifest(+ data,+ signature,+ checksums=checksums,+ expected_version=version,+ public_keys=(public,),+ )+++def test_a_signature_over_something_else_is_not_a_manifest() -> None:+ """The release key also signs install scripts; those never parse as a manifest."""+ private, public = _key_pair()+ script = b"#!/bin/sh\necho install\n"+ with pytest.raises(UpdateManifestError):+ verify_update_manifest(+ script,+ _sign(private, script),+ checksums=CHECKSUMS,+ expected_version="4.2.0",+ public_keys=(public,),+ )+ with pytest.raises(UpdateManifestError, match="schema"):+ parse_manifest(b'{"schema":"other","version":"4.2.0"}')+ assert MANIFEST_SCHEMA.startswith("dodaios-update-manifest/")+++def test_the_pinned_key_is_the_published_offline_ceremony_key() -> None:+ pem = (ROOT / "install" / "keys" / "offline-ceremony.pub").read_text(encoding="ascii")+ body = "".join(line for line in pem.splitlines() if not line.startswith("-----"))+ assert PINNED_PUBLIC_KEYS == (body,)++[email protected](shutil.which("openssl") is None, reason="openssl is not installed")+def test_a_signature_made_like_the_workflow_makes_it_verifies(tmp_path: Path) -> None:+ """``openssl pkeyutl -sign -rawin`` + ``base64 -w0`` is what the release job runs."""+ private, public = _key_pair()+ key = tmp_path / "release.key"+ key.write_bytes(+ private.private_bytes(+ serialization.Encoding.PEM,+ serialization.PrivateFormat.PKCS8,+ serialization.NoEncryption(),+ )+ )+ manifest = tmp_path / UPDATE_MANIFEST_ASSET_NAME+ manifest.write_bytes(build_manifest(version="4.2.0", tag="v4.2.0", checksums=CHECKSUMS))+ raw = tmp_path / "sig.raw"+ subprocess.run(+ [+ "openssl",+ "pkeyutl",+ "-sign",+ "-inkey",+ str(key),+ "-rawin",+ "-in",+ str(manifest),+ "-out",+ str(raw),+ ],+ check=True,+ capture_output=True,+ )+ verify_update_manifest(+ manifest.read_bytes(),+ base64.b64encode(raw.read_bytes()).decode("ascii"),+ checksums=CHECKSUMS,+ expected_version="4.2.0",+ public_keys=(public,),+ )+++# --------------------------------------------------------------------------- #+# The updater refuses before downloading the installer+# --------------------------------------------------------------------------- #+def _asset(name: str) -> InstallerAsset:+ return InstallerAsset(name=name, url=f"https://example.invalid/{name}", size=len(PAYLOAD))+++def _signed(version: str = "4.2.0") -> SignedManifestAssets:+ return SignedManifestAssets(+ manifest=_asset(UPDATE_MANIFEST_ASSET_NAME),+ signature=_asset(UPDATE_MANIFEST_SIGNATURE_ASSET_NAME),+ version=version,+ )+++def _fetcher(manifest: bytes, signature: str) -> FakeAssetFetcher:+ return FakeAssetFetcher(+ manifest=CHECKSUMS.decode("ascii"),+ payload=PAYLOAD,+ texts={+ UPDATE_MANIFEST_ASSET_NAME: manifest.decode("ascii"),+ UPDATE_MANIFEST_SIGNATURE_ASSET_NAME: signature,+ },+ )+++async def test_a_signed_release_downloads_and_verifies(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ private, public = _key_pair()+ monkeypatch.setattr("dodaios.core.update_manifest.PINNED_PUBLIC_KEYS", (public,))+ data = build_manifest(version="4.2.0", tag="v4.2.0", checksums=CHECKSUMS)+ fetcher = _fetcher(data, _sign(private, data))++ result = await download_and_verify(+ _asset(SETUP),+ _asset(CHECKSUMS_ASSET_NAME),+ dest_dir=tmp_path,+ fetcher=fetcher,+ signed=_signed(),+ )++ assert result.read_bytes() == PAYLOAD++[email protected]("defect", ["unsigned_by_release_key", "replayed_version"])+async def test_a_bad_signed_manifest_stops_before_the_installer_download(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch, defect: str+) -> None:+ private, public = _key_pair()+ monkeypatch.setattr("dodaios.core.update_manifest.PINNED_PUBLIC_KEYS", (public,))+ data = build_manifest(version="4.1.0", tag="v4.1.0", checksums=CHECKSUMS)+ signer = Ed25519PrivateKey.generate() if defect == "unsigned_by_release_key" else private+ fetcher = _fetcher(data, _sign(signer, data))++ with pytest.raises(InstallerUpdateError, match=UPDATE_MANIFEST_ASSET_NAME):+ await download_and_verify(+ _asset(SETUP),+ _asset(CHECKSUMS_ASSET_NAME),+ dest_dir=tmp_path,+ fetcher=fetcher,+ signed=_signed("4.2.0" if defect == "replayed_version" else "4.1.0"),+ )++ assert fetcher.download_urls == []+ assert not (tmp_path / SETUP).exists()+++# --------------------------------------------------------------------------- #+# The release pipeline's side+# --------------------------------------------------------------------------- #+def test_the_ci_script_builds_and_checks_the_binding(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ monkeypatch.setattr(manifest_cli, "_package_version", lambda: "4.2.0")+ checksums = tmp_path / CHECKSUMS_ASSET_NAME+ checksums.write_bytes(CHECKSUMS)+ out = tmp_path / UPDATE_MANIFEST_ASSET_NAME+ args = ["--tag", "v4.2.0", "--checksums", str(checksums)]++ assert manifest_cli.main(["build", *args, "--out", str(out)]) == 0+ assert manifest_cli.main(["check", *args, "--manifest", str(out)]) == 0+ # A tag for another version is refused at build time.+ assert (+ manifest_cli.main(+ ["build", "--tag", "v9.9.9", "--checksums", str(checksums), "--out", str(out)]+ )+ == 1+ )+ # A checksum manifest changed after signing no longer matches.+ checksums.write_bytes(CHECKSUMS + CHECKSUMS)+ assert manifest_cli.main(["check", *args, "--manifest", str(out)]) == 1+++def test_release_finalization_checks_the_signed_manifest(monkeypatch: pytest.MonkeyPatch) -> None:+ private, public = _key_pair()+ monkeypatch.setattr("dodaios.core.update_manifest.PINNED_PUBLIC_KEYS", (public,))+ text = CHECKSUMS.decode("ascii")+ data = build_manifest(version="4.2.0", tag="v4.2.0", checksums=CHECKSUMS)++ assert release_assets.update_manifest_errors("v4.2.0", text, data, _sign(private, data)) == []+ assert release_assets.update_manifest_errors("v4.3.0", text, data, _sign(private, data))+ assert release_assets.update_manifest_errors("v4.2.0", text + text, data, _sign(private, data))+ forged = _sign(Ed25519PrivateKey.generate(), data)+ assert release_assets.update_manifest_errors("v4.2.0", text, data, forged)+++def test_the_desktop_upload_requires_the_signed_manifest() -> None:+ for name in (UPDATE_MANIFEST_ASSET_NAME, UPDATE_MANIFEST_SIGNATURE_ASSET_NAME):+ assert name in release_assets.DESKTOP_ASSETS+ assert name not in release_assets.SIGNING_ASSETS+++def test_only_the_tag_signing_job_reads_the_release_key() -> None:+ import yaml++ workflow = yaml.safe_load(+ (ROOT / ".github" / "workflows" / "desktop-installers.yml").read_text(encoding="utf-8")+ )+ jobs = workflow["jobs"]+ sign = jobs["sign-update-manifest"]+ assert sign["environment"] == "release-signing"+ assert sign["if"] == "github.ref_type == 'tag'"+ assert sign["permissions"] == {"contents": "read"}+ readers = [name for name, job in jobs.items() if "WAVE2_OFFLINE_KEY_B64" in yaml.safe_dump(job)]+ assert readers == ["sign-update-manifest"]+ assert "sign-update-manifest" in jobs["release"]["needs"]+ assert jobs["release"]["name"] == release_assets.PUBLISHER_JOBS["desktop-installers.yml"]diff --git a/tests/unit/ui/web/test_update_routes_frozen.py b/tests/unit/ui/web/test_update_routes_frozen.pyindex e119486b3a..d5c1e1d74f 100644--- a/tests/unit/ui/web/test_update_routes_frozen.py+++ b/tests/unit/ui/web/test_update_routes_frozen.py@@ -26,6 +26,10 @@ from dodaios.core.installer_update import (InstallerUpdateError,UpdateBlocker,)+from dodaios.core.update_manifest import (+ UPDATE_MANIFEST_ASSET_NAME,+ UPDATE_MANIFEST_SIGNATURE_ASSET_NAME,+)from dodaios.ui.web.update_routes import router as update_routerSETUP_NAME = "PersonalJarvis-Setup-x64.exe"@@ -62,6 +66,7 @@ def _release("browser_download_url": (f"https://example.invalid/{CHECKSUMS_ASSET_NAME}"),"size": 90,},+ *_signed_entries(),]return {"version": version,@@ -73,6 +78,18 @@ def _release(}+def _signed_entries() -> list[dict[str, Any]]:+ """The signed update manifest every current release carries (issue #810)."""+ return [+ {+ "name": name,+ "browser_download_url": f"https://example.invalid/{name}",+ "size": 64,+ }+ for name in (UPDATE_MANIFEST_ASSET_NAME, UPDATE_MANIFEST_SIGNATURE_ASSET_NAME)+ ]++def _patch_frozen(monkeypatch: pytest.MonkeyPatch,*,@@ -228,10 +245,16 @@ def _capture_install(monkeypatch: pytest.MonkeyPatch) -> dict[str, Any]:return pathasync def _download(- asset: Any, checksums: Any, *, dest_dir: Path, on_progress: Any = None+ asset: Any,+ checksums: Any,+ *,+ dest_dir: Path,+ on_progress: Any = None,+ signed: Any = None,) -> Path:seen["asset"] = assetseen["checksums"] = checksums+ seen["signed"] = signedreturn _write_verified(dest_dir, asset.name)def _apply(installer: Path, **kwargs: Any) -> str:@@ -264,6 +287,11 @@ def test_apply_downloads_verifies_and_hands_over(assert body["restart_required"] is Falseassert seen["asset"].name == SETUP_NAMEassert seen["checksums"].name == CHECKSUMS_ASSET_NAME+ # The signed manifest travels with the download and is bound to the+ # version being installed.+ assert seen["signed"].manifest.name == UPDATE_MANIFEST_ASSET_NAME+ assert seen["signed"].signature.name == UPDATE_MANIFEST_SIGNATURE_ASSET_NAME+ assert seen["signed"].version == "1.6.0"assert seen["installer"].name == SETUP_NAME@@ -320,7 +348,12 @@ def test_apply_surfaces_a_verification_failure(_patch_latest(monkeypatch, _release("1.6.0"))async def _download(- asset: Any, checksums: Any, *, dest_dir: Path, on_progress: Any = None+ asset: Any,+ checksums: Any,+ *,+ dest_dir: Path,+ on_progress: Any = None,+ signed: Any = None,) -> Path:raise InstallerUpdateError("PersonalJarvis-Setup-x64.exe failed its SHA-256 check")@@ -670,6 +703,10 @@ def _asset_entry(name: str) -> dict[str, Any]:}+def _manifest_entries() -> list[dict[str, Any]]:+ return [_asset_entry(CHECKSUMS_ASSET_NAME), *_signed_entries()]++def _patch_frozen_names(monkeypatch: pytest.MonkeyPatch, *names: str) -> None:_patch_frozen(monkeypatch)monkeypatch.setattr(u, "installer_asset_names", lambda _p, _m: names)@@ -689,7 +726,7 @@ def test_status_offers_the_preferred_name_when_a_release_carries_both(assets = [_asset_entry(SETUP_NAME),_asset_entry(NEW_SETUP_NAME),- _asset_entry(CHECKSUMS_ASSET_NAME),+ *_manifest_entries(),]_patch_latest(monkeypatch, _release("1.6.0", assets=assets))@@ -704,7 +741,7 @@ def test_status_offers_whichever_single_name_a_release_carries(client: TestClient, monkeypatch: pytest.MonkeyPatch, published: str) -> None:_patch_frozen_names(monkeypatch, NEW_SETUP_NAME, SETUP_NAME)- assets = [_asset_entry(published), _asset_entry(CHECKSUMS_ASSET_NAME)]+ assets = [_asset_entry(published), *_manifest_entries()]_patch_latest(monkeypatch, _release("1.6.0", assets=assets))body = client.get("/api/update/status").json()@@ -719,7 +756,7 @@ def test_apply_with_one_published_name_downloads_exactly_as_before() -> None:"""One candidate: the download is called without any alternative."""_patch_frozen_names(monkeypatch, NEW_SETUP_NAME, SETUP_NAME)- assets = [_asset_entry(published), _asset_entry(CHECKSUMS_ASSET_NAME)]+ assets = [_asset_entry(published), *_manifest_entries()]_patch_latest(monkeypatch, _release("1.6.0", assets=assets))# This recorder accepts no ``alternatives`` keyword - passing one fails.seen = _capture_install(monkeypatch)@@ -738,7 +775,7 @@ def test_apply_lets_the_checksum_manifest_choose_between_two_names(assets = [_asset_entry(SETUP_NAME),_asset_entry(NEW_SETUP_NAME),- _asset_entry(CHECKSUMS_ASSET_NAME),+ *_manifest_entries(),]_patch_latest(monkeypatch, _release("1.6.0", assets=assets))seen: dict[str, Any] = {}@@ -755,6 +792,7 @@ def test_apply_lets_the_checksum_manifest_choose_between_two_names(dest_dir: Path,on_progress: Any = None,alternatives: Any = (),+ signed: Any = None,) -> Path:seen["asset"] = asset.nameseen["alternatives"] = [candidate.name for candidate in alternatives]@@ -783,12 +821,58 @@ def test_apply_names_every_accepted_file_when_a_release_has_none(client: TestClient, monkeypatch: pytest.MonkeyPatch) -> None:_patch_frozen_names(monkeypatch, NEW_SETUP_NAME, SETUP_NAME)- _patch_latest(- monkeypatch, _release("1.6.0", assets=[_asset_entry(CHECKSUMS_ASSET_NAME)])- )+ _patch_latest(monkeypatch, _release("1.6.0", assets=[*_manifest_entries()]))response = client.post("/api/update/apply")assert response.status_code == 502assert NEW_SETUP_NAME in response.json()["detail"]assert SETUP_NAME in response.json()["detail"]+++# --------------------------------------------------------------------------- #+# The signed update manifest (issue #810)+# --------------------------------------------------------------------------- #+def _unsigned_release() -> dict[str, Any]:+ return _release(+ "1.6.0",+ assets=[+ {+ "name": SETUP_NAME,+ "browser_download_url": f"https://example.invalid/{SETUP_NAME}",+ "size": 123,+ },+ {+ "name": CHECKSUMS_ASSET_NAME,+ "browser_download_url": f"https://example.invalid/{CHECKSUMS_ASSET_NAME}",+ "size": 90,+ },+ ],+ )+++def test_status_without_a_signed_manifest_offers_nothing(+ client: TestClient, monkeypatch: pytest.MonkeyPatch+) -> None:+ _patch_frozen(monkeypatch)+ _patch_latest(monkeypatch, _unsigned_release())+ body = client.get("/api/update/status").json()+ # apply would refuse it, so status must not offer it.+ assert body["update_available"] is False+++def test_apply_refuses_a_release_without_a_signed_manifest(+ client: TestClient, monkeypatch: pytest.MonkeyPatch+) -> None:+ _patch_frozen(monkeypatch)+ _patch_latest(monkeypatch, _unsigned_release())++ async def _never_download(*_args: Any, **_kwargs: Any) -> Path:+ raise AssertionError("nothing may be downloaded without a signed manifest")++ monkeypatch.setattr(u, "download_and_verify", _never_download)++ response = client.post("/api/update/apply")++ assert response.status_code == 502+ assert UPDATE_MANIFEST_ASSET_NAME in response.json()["detail"]